diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..d4b73443 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git/ +artifacts/ +models/ +captures/ +logs/ +control-plane/target/ +engine/* +!engine/strata/ +engine/strata/* +!engine/strata/LICENSE +benchmarks/ +docs/ diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml new file mode 100644 index 00000000..89e8c786 --- /dev/null +++ b/.github/workflows/desktop.yml @@ -0,0 +1,44 @@ +name: Desktop foundation +on: + push: + paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml'] + pull_request: + paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml'] +permissions: + contents: read +jobs: + core: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - name: Format + run: cargo fmt --manifest-path desktop-core/Cargo.toml --check + - name: Tests + run: cargo test --locked --manifest-path desktop-core/Cargo.toml + - name: Lints + run: cargo clippy --locked --manifest-path desktop-core/Cargo.toml --all-targets -- -D warnings + - name: Hardware smoke (no inference) + run: cargo run --locked --manifest-path desktop-core/Cargo.toml -- hardware + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + - name: Restore desktop dependencies + run: dotnet restore desktop/Strata.Desktop.csproj --locked-mode + - name: Build desktop + run: dotnet build desktop/Strata.Desktop.csproj --no-restore + - name: Desktop gRPC node integration (headless, no inference) + run: dotnet desktop/bin/Debug/net10.0/Strata.Desktop.dll --self-check + - name: Desktop gRPC restart recovery (isolated node) + run: python desktop/tests/reconnect.py + - name: Desktop managed lifecycle (isolated synthetic worker) + run: python desktop/tests/lifecycle.py + - name: Real isolated SSH tunnel and gRPC recovery + if: runner.os == 'macOS' + run: python desktop/tests/ssh_tunnel.py + - name: Real isolated SSH installation and rollback + if: runner.os == 'macOS' + run: python desktop/tests/remote_install.py diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml new file mode 100644 index 00000000..bff86839 --- /dev/null +++ b/.github/workflows/linux.yml @@ -0,0 +1,358 @@ +name: Linux + +on: + push: + branches: [main] + 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 + 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 + +jobs: + verify: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Install build tools + run: sudo apt-get update && sudo apt-get install -y cmake ninja-build g++ python3-numpy + - name: Install pinned Rust + run: rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy + - name: Local checks + run: scripts/check-local.sh + + keyless-cuda: + if: github.event_name == 'workflow_dispatch' && inputs.keyless_gpu + 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: + if: github.event_name == 'workflow_dispatch' && inputs.static_cuda_package && github.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: | + rustup toolchain install 1.99.0 --profile minimal + rustup target add --toolchain 1.99.0 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" \ + --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --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) + - uses: actions/upload-artifact@v4 + with: + name: strata-next-static-cuda-preview + path: ${{ runner.temp }}/strata-package-${{ github.run_id }}/ + if-no-files-found: error + retention-days: 7 + - name: Remove uploaded package copy + 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: + if: github.event_name == 'workflow_dispatch' && inputs.hosted_cuda_package && github.event.repository.private + needs: verify + runs-on: ubuntu-24.04 + timeout-minutes: 150 + env: + CUDA_VISIBLE_DEVICES: '' + BUILD_JOBS: '1' + CARGO_BUILD_JOBS: '2' + CUDA_ARCHITECTURES: '120' + 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" + sudo apt-get update && sudo apt-get install -y gcc-13 g++-13 cmake ninja-build musl-tools binutils + - name: Assemble pinned build-only CUDA components + run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" + - name: Record actual toolchain + run: | + "$CUDACXX" --version + 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()) + info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), + gcc=subprocess.check_output(['g++-13','--version'],text=True), + 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: + CC: gcc-13 + CXX: g++-13 + CUDAHOSTCXX: g++-13 + run: scripts/build-static-cuda.sh + - name: Install pinned Rust and musl target + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup target add --toolchain 1.99.0 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" \ + --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --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" + 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) + - uses: actions/upload-artifact@v4 + with: + name: strata-next-hosted-cuda-preview + path: ${{ runner.temp }}/strata-hosted-cuda-package/ + if-no-files-found: error + retention-days: 7 + - name: Remove uploaded package copy + 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" + + linux-static-cli: + needs: verify + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Install musl toolchain + run: sudo apt-get update && sudo apt-get install -y musl-tools cmake binutils python3-numpy + - name: Install pinned Rust and target + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup target add --toolchain 1.99.0 x86_64-unknown-linux-musl + - name: Build static CLI + run: cargo build --manifest-path control-plane/Cargo.toml --locked --release --target x86_64-unknown-linux-musl --bin strata-next + - name: Verify ELF and checksum + run: | + binary=control-plane/target/x86_64-unknown-linux-musl/release/strata-next + if readelf -l "$binary" | grep -q INTERP; then + echo 'ELF has a dynamic interpreter' >&2 + exit 1 + fi + if readelf -d "$binary" | grep -q NEEDED; then + echo 'ELF has a dynamic library dependency' >&2 + exit 1 + fi + "$binary" --version + mkdir -p dist + cp "$binary" dist/strata-next-linux-x86_64-musl + { + echo "Commit: $GITHUB_SHA" + echo "Workflow: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + rustc --version + cargo --version + musl-gcc --version + readelf --version + } > dist/BUILD-PROVENANCE.txt + { + readelf -h "$binary" + readelf -l "$binary" + readelf -d "$binary" + } > dist/ELF-AUDIT.txt + cd dist + sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS + - name: Static CLI model smoke + run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Engine loader probe before model acquisition + run: python3 scripts/smoke-engine-probe.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Explicit GPU profile driver policy without GPU + run: python3 scripts/smoke-gpu-requirement.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Declared GPU memory admission and child UUID pin without GPU + run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Atomic pinned assets before native serving + run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native GGUF pack preparation against upstream oracle + run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - 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/strata-next + - name: Pinned MTP structural preflight and native bootstrap + run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native runtime profile metadata admission + run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native systemd unit syntax and path safety + run: python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native installer with actual isolated systemd user service + run: | + uid=$(id -u) + sudo systemctl start "user@$uid.service" + export XDG_RUNTIME_DIR="/run/user/$uid" + export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus" + python3 scripts/smoke-service-unit.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --lifecycle + python3 scripts/smoke-native-switch.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native deployment configuration without worker launch + run: python3 scripts/smoke-config-check.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native deployment readiness deadline without GPU + run: python3 scripts/smoke-wait-ready.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native API authentication without GPU + run: python3 scripts/smoke-native-auth.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native custom text and regex tools without GPU + run: python3 scripts/smoke-custom-tools.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native auto/none/required/forced tool policy without GPU + run: python3 scripts/smoke-tool-policy.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Live Responses replay and corrupt SSE evidence without GPU + run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-live-responses-replay.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Input token count exact GEN wire parity without inference + run: python3 scripts/smoke-input-tokens.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Chat Completions live protocol and wire parity + run: python3 scripts/smoke-chat-completions.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Messages named SSE and tool protocol without GPU + run: python3 scripts/smoke-messages.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: SSE idle keep-alive, terminal parity and disconnect without GPU + run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/smoke-sse-keepalive.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Stored Responses retrieval and deletion without GPU + run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Durable Responses restart and disk failure gate + run: python3 scripts/smoke-response-history.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --durable + - name: Native drain and resume without GPU + run: python3 scripts/smoke-native-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native signal shutdown grace without GPU + run: python3 scripts/smoke-signal-drain.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native generation deadline and recovery without GPU + run: python3 scripts/smoke-generation-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Native queue deadline without expiring active work + run: python3 scripts/smoke-queue-deadline.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Static CLI HTTP cancellation failure isolation + run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next + - name: Static CLI HTTP crash recovery without request replay + run: python3 scripts/smoke-worker-cancel.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next --restart + - name: Embedded CPU worker packaging without GPU + run: | + musl-gcc -O2 -static scripts/fixtures/embedded-worker.c -o "$RUNNER_TEMP/embedded-worker" + python3 scripts/build-linux-package.py --cpu-fixture --engine "$RUNNER_TEMP/embedded-worker" \ + --sha256 "$(sha256sum "$RUNNER_TEMP/embedded-worker" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ + --cargo-target-dir control-plane/target --output "$RUNNER_TEMP/combined-fixture" + cd "$RUNNER_TEMP/combined-fixture" + sha256sum -c SHA256SUMS + cd "$GITHUB_WORKSPACE" + python3 scripts/smoke-embedded-engine.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" "$RUNNER_TEMP/embedded-worker" + python3 scripts/smoke-controller-deployment.py "$RUNNER_TEMP/combined-fixture/strata-next-linux-x86_64-musl" + python3 scripts/build-runtime-image.py --cpu-fixture --package "$RUNNER_TEMP/combined-fixture" \ + --receipt-sha256 "$(sha256sum "$RUNNER_TEMP/combined-fixture/SHA256SUMS" | cut -d ' ' -f 1)" \ + > "$RUNNER_TEMP/combined-image.json" + python3 scripts/smoke-runtime-image.py "$RUNNER_TEMP/combined-image.json" + rm "$RUNNER_TEMP/embedded-worker" + - name: Remove owned CPU fixture image + if: always() + run: | + receipt="$RUNNER_TEMP/combined-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" + rm "$receipt" + fi + - uses: actions/upload-artifact@v4 + with: + name: strata-next-linux-x86_64-musl + path: dist/ + + linux-cli-container: + needs: verify + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Build actual CLI-only scratch image + run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check . + - name: Check isolated CLI container startup and shutdown + run: python3 scripts/smoke-cli-container.py strata-cli-check + - name: Remove test image + if: always() + run: docker image rm strata-cli-check || true + + release-cli: + if: startsWith(github.ref, 'refs/tags/v') + needs: [linux-static-cli, linux-cli-container] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + name: strata-next-linux-x86_64-musl + path: dist/ + - name: Publish CLI preview release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "${GITHUB_REF_NAME}" dist/strata-next-linux-x86_64-musl dist/SHA256SUMS dist/BUILD-PROVENANCE.txt dist/ELF-AUDIT.txt \ + --repo "${GITHUB_REPOSITORY}" --title "Strata Next ${GITHUB_REF_NAME}" \ + --notes 'CLI/control-plane preview. CUDA engine and model files are not included.' --prerelease diff --git a/.gitignore b/.gitignore index 019491eb..501e2fd0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,40 @@ -/target/ +.DS_Store +.idea/ +.vscode/ + +# Credentials and local configuration +.env +.env.* +!.env.example +*.pem +*.key + +# Builds and caches +build/ +cmake-build-*/ +CMakeFiles/ +CMakeCache.txt +compile_commands.json +target/ +desktop/**/bin/ +desktop/**/obj/ +.cache/ +__pycache__/ +.pytest_cache/ +.venv/ +*.o +*.so +*.dylib + +# Local data, models, captures, logs and generated results +/dist/ +artifacts/ +models/ +captures/ +logs/ +*.log *.gguf +*.kar +*.kar2 *.safetensors *.bin -.env* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..3bac86e4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,23 @@ +# Repository instructions + +Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or scope. The charter is the source of truth for goals and milestones. + +## Priorities + +1. Preserve protocol correctness and successful task completion. +2. Preserve model quality and tool-call integrity. +3. Improve end-to-end agent throughput, then decode/prefill throughput. + +## Change rules + +- Keep production serving independent of Python. Python is allowed for offline conversion, calibration, experiments, and evaluations. +- Keep model weights, request captures, credentials, logs, and generated artifacts out of Git. Use external volumes or ignored local paths. Sanitize any fixture committed to the repository. +- Do not enable lossy optimizations by default until their separate quality gate passes. Mark experimental modes explicitly. +- For non-lossy changes, compare greedy output or tensor values against the defined baseline and record numerical tolerances. +- Do not label a change as a performance improvement without paired A/B measurements on the same workload and a quality result. Record hardware, software, model digest, configuration, cache state, token counts, and distributions as required by the charter. +- Do not conflate a synthetic kernel gain with an end-to-end agent workload gain. Report both when relevant. +- Keep the Strata upstream commit and local changes traceable. Do not overwrite or silently replace the upstream provenance record. + +## Repository state + +The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md`. The Rust control plane exposes health, readiness, status, and a `/v1/responses` validation stub, and can supervise one configured worker. A synthetic offline Responses replay exists, but live inference, project benchmark results, and deployment assets are not yet present. Read `engine/strata/AGENTS.md` before modifying imported engine code. diff --git a/Cargo.lock b/Cargo.lock index ca3fdc51..5fb51353 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,2940 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fraction" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500" +dependencies = [ + "num", + "num-bigint", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonschema" +version = "0.58.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea18b8d5e1469b1bdd6b349169305141316a7c26da27f239773b65c830c0f5d6" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex", + "fraction", + "getrandom 0.3.4", + "itoa", + "jsonschema-regex", + "jsonschema-value", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing", + "regex", + "serde", + "serde_json", + "strum", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.58.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854e9e22c420535035e95eed240cbfb4a5f4b7da74d122d63144e0c31926dbfd" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonschema-value" +version = "0.58.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e3bfac11ac357ec620880025757d38c67da8fd5b9ef5024d19f0f360002b4ca" +dependencies = [ + "ahash", + "bytecount", + "fraction", + "getrandom 0.3.4", + "num-cmp", + "num-traits", + "serde_json", + "zmij", +] + [[package]] name = "leleka-backend-api" version = "0.1.0" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "pulldown-cmark", + "pulldown-cmark-to-cmark", + "regex", + "syn 2.0.119", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-types" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +dependencies = [ + "prost", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8760a25b6ff9c620324822737e468478fa092234190d2e449760344354896ed9" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fa2624782ca04cd44f51554566717377acd240e4c0016d757dd74fccc9324f" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2417e9817fa237dab803ad4dda7357a111656e242959cc6b8f9a1a583367d42" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d189c34636356a46a7ed3188233dc8a88c431278cc54d4a19b096a2d270e985" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171e39f1e846e5f322ced1ac3b8d4cd3a3833ca24b6e5d58b3632574fe6204fa" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873cdcc097593432086661aa432b8078f1cd87bfb02847c332e98ae2c119e966" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb72df001783b8297847fe8f5f874ee400fd742c843d60583e8c23d96977c7f" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04652167eca899dda05f32f5481adeaf25c623a98ce2fc146a001cc59a2add7" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263a3f48f01e7309e857138bd47f785585b4a005e8e56c6d2824ce91195999c3" + +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + +[[package]] +name = "pulldown-cmark-to-cmark" +version = "22.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84bbb29c624230c4bd1047bbdb2aa47e41c860e9665ce62ba9504eebe91bf867" +dependencies = [ + "pulldown-cmark", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "referencing" +version = "0.58.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590efadb0a669f1712c1e3ab810a55d4c3d20d0127c455f7236dd0710aba0346" +dependencies = [ + "ahash", + "fluent-uri", + "getrandom 0.3.4", + "hashbrown 0.17.1", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strata-control" +version = "0.1.0" +dependencies = [ + "aho-corasick", + "axum", + "cc", + "fancy-regex", + "futures-core", + "hex", + "http-body", + "http-body-util", + "jsonschema", + "libc", + "regex", + "regex-syntax", + "reqwest", + "serde", + "serde_json", + "sha2", + "subtle", + "tokio", + "webpki-root-certs", +] + +[[package]] +name = "strata-desktop-core" +version = "0.1.0" +dependencies = [ + "async-stream", + "axum", + "futures-util", + "prost", + "protoc-bin-vendored", + "reqwest", + "serde", + "serde_json", + "sha2", + "subtle", + "sysinfo", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tonic-prost-build", + "tower", + "uuid", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "sysinfo" +version = "0.39.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tonic" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +dependencies = [ + "async-trait", + "axum", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2", + "sync_wrapper", + "tokio", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tonic-prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +dependencies = [ + "bytes", + "prost", + "tonic", +] + +[[package]] +name = "tonic-prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn 2.0.119", + "tempfile", + "tonic-build", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "indexmap", + "pin-project-lite", + "slab", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index baa34093..d73133ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,12 @@ [workspace] resolver = "3" -members = ["crates/backend-api"] +members = ["crates/backend-api", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "control-plane", "desktop-core"] [workspace.package] edition = "2024" license = "Apache-2.0" -rust-version = "1.85" +rust-version = "1.99" [workspace.lints.rust] unsafe_code = "forbid" diff --git a/PROJECT_CHARTER.md b/PROJECT_CHARTER.md new file mode 100644 index 00000000..7934b38f --- /dev/null +++ b/PROJECT_CHARTER.md @@ -0,0 +1,531 @@ +# Strata Next — постановка задачі та цілі проєкту + +**Статус:** проєктний документ v0.1 +**Дата:** 2026-10-02 +**Тип:** окремий проєкт і форк Strata +**Робоча назва:** `strata-next` + +## 1. Мета проєкту + +Створити production-ready inference runtime для локального та орендованого GPU-обладнання, оптимізований для автономних Codex-агентів із довгим контекстом. + +Результат має: + +1. давати максимально можливу кількість коректно згенерованих токенів за секунду; +2. підтримувати один потік із контекстом 512K або два незалежні потоки по 256K; +3. масштабуватися горизонтально на кілька орендованих GPU-серверів; +4. працювати з Codex без зовнішнього compatibility bridge; +5. зберігати якість моделі та достовірність tool calls; +6. розгортатися однією командою на чистому Linux-сервері з NVIDIA GPU; +7. дозволяти відтворювати й перевіряти кожне заявлене прискорення; +8. після завантаження й перевірки моделі створювати придатний для запуску стиснений артефакт; цільовий GPU-шлях тримає стиснені ваги у VRAM і декодує потрібні блоки CUDA-декодером перед обчисленням. + +Основна модель першого етапу — **Qwen3.8-Flash-Next IQ3_S**. Основне цільове обладнання — **RTX 5090 32 GB + Ryzen 9 9950X3D + 128 GB RAM**. + +## 2. Проблема + +Поточна Strata вже забезпечує високу швидкість Qwen3.8-Flash-Next, але має обмеження для production-використання з Codex: + +- немає нативного повного `/v1/responses` API; +- `text.format` і structured output підтримуються не повністю; +- помилка логування або заповнений диск можуть обірвати SSE до `finish_reason`; +- сервер обслуговує один запит за раз; +- немає production scheduler для кількох GPU-вузлів; +- Python control plane ускладнює автономне розгортання й контроль процесів; +- експертний кеш, KV cache та speculative decoding оптимізуються окремо, без єдиного performance budget; +- дослідження `koference` ще не інтегровані в inference engine; +- можливість Value-Only Cache для Qwen3.8 не перевірена. + +Проєкт має усунути ці обмеження та перетворити Strata на керований, вимірюваний і горизонтально масштабований runtime. + +## 3. Вихідна база + +### 3.1 Strata + +- C++20 inference engine; +- CUDA backend для NVIDIA; +- HIP backend для AMD; +- native quantized kernels; +- expert cache у VRAM із CPU-обчисленням cache misses; +- MTP і suffix speculative decoding; +- KV streaming між RAM і VRAM; +- формати KV: FP16, INT8, Q4_0, K8V4; +- conversation/prefix cache; +- підтримка Qwen3.8-Flash-Next, Coder і Swift; +- активний upstream, який потрібно регулярно синхронізувати. + +### 3.2 Поточний виміряний baseline + +Поточна конфігурація: + +- Qwen3.8-Flash-Next IQ3_S; +- 1 слот; +- контекст 256K; +- INT8 KV; +- 32K KV resident у VRAM, решта через KV streaming; +- MTP `spec=4`; +- RTX 5090 32 GB. + +Орієнтири з поточного журналу реального агентного трафіку: + +- медіана decode для останніх 100 запитів із prompt ≥50K та output ≥200: **118 ток/с**; +- 10–90 перцентиль: **81–138 ток/с**; +- cold prefill великих prompt: приблизно **5,4–5,9 тис. ток/с**; +- expert-cache hit rate: переважно **90–96%**; +- медіанний draft acceptance: приблизно **70%**. + +Ці числа є початковими орієнтирами. Офіційний baseline проєкту має бути повторно зафіксований контрольованим benchmark harness. + +### 3.3 Koference + +Проєкт `koference` уже містить: + +- формат прогресивного стиснення KAR; +- CUDA-декодер KAR; +- виміряну швидкість декодування великих tensor blocks; +- окреме кодування expert bank, dense matrices і PLE lookup tables; +- `kar_decode_rows()` для декодування лише потрібних рядків PLE; +- дослідження resident/offload режимів; +- scheduler і memory planner; +- activation tracing та quality/speed harness; +- результати rate-distortion і перевірки якості на реальній Qwen3.8-Flash-Next. + +### 3.4 Ресурси проєкту + +- локальна RTX 5090 32 GB для розробки й профілювання; +- 128 GB системної RAM; +- доступ до орендованих NVIDIA GPU-серверів для масштабних тестів; +- готові Qwen3.8 GGUF-квантизації; +- реальний довготривалий workload Codex + LeaseVibe MCP; +- можливість збирати request/response, performance і quality telemetry; +- AI-assisted розробка, тому обсяг ручного переписування коду не є основним обмеженням; +- наявний дослідницький код `koference`, який можна переносити в C++/CUDA engine. + +## 4. Обов'язкові вимоги + +### 4.1 Контекст і паралельність + +Runtime повинен підтримувати два режими: + +1. `1 × 512K` — один агентний потік із контекстом 512K; +2. `2 × 256K` — два незалежні потоки з контекстом 256K кожен. + +Режим `1 × 256K` допускається як локальний профіль для максимальної швидкості на 32 GB VRAM, але не замінює два обов'язкові режими. + +### 4.2 Якість + +- Жодна lossy-оптимізація не вмикається за замовчуванням без окремого quality gate. +- Зміни API, scheduler, Rust control plane та non-lossy kernels повинні зберігати результат у межах визначеної числової похибки або давати ідентичний greedy output. +- Lossy-зміни перевіряються окремо на perplexity, long-context retrieval, tool calling і завершенні реальних задач. +- Помилка або деградація не можуть приховуватися усередненням кількох benchmark-наборів. + +### 4.3 Відтворюваність + +Кожен performance result повинен містити: + +- commit engine і control plane; +- модель, quant і digest файлів; +- GPU, driver, CUDA toolkit і power limit; +- параметри контексту, KV, slots, batch і speculation; +- cold/warm стан кешів; +- prompt/output token counts; +- TTFT, prefill tok/s, decode tok/s і end-to-end wall time; +- draft acceptance, expert-cache hit і KV-streaming hit; +- середнє, медіану, перцентилі та довірчий інтервал; +- результат quality gate. + +### 4.4 Мінімальний значущий приріст + +- Повторюване покращення від **1%** вважається корисним. +- Зміна приймається як performance improvement лише після парного A/B тесту. +- Для змін порядку 1% потрібно щонайменше 30 повторів або достатня кількість парних вимірів для вузького довірчого інтервалу. +- Результат не приймається, якщо приріст швидкості компенсується неприйнятною втратою якості або нестабільністю. + +## 5. Цільова архітектура + +```text +Codex / OpenAI-compatible clients + │ + ▼ +Rust control plane + ├─ /v1/responses + ├─ /v1/chat/completions + ├─ /v1/messages + ├─ structured output / text.format + ├─ SSE, cancellation, backpressure + ├─ auth, health, readiness, metrics + ├─ request routing and queues + └─ worker lifecycle management + │ + ▼ +C++20/CUDA Strata engine fork + ├─ native quantized inference + ├─ expert cache and cache-miss paths + ├─ MTP / suffix speculation + ├─ KV streaming and Value-Only experiments + ├─ continuous batching / multiple slots + └─ Koference/KAR kernels + │ + ▼ +GPU / RAM / local NVMe model storage +``` + +Python залишається offline-інструментом для: + +- завантаження й конвертації моделей; +- calibration; +- KAR packing; +- дослідницьких експериментів; +- формування eval-наборів. + +Production serving не повинен залежати від Python runtime. + +## 6. Цілі проєкту + +### G1. Надійний нативний API для Codex + +Реалізувати в Rust control plane: + +- OpenAI Responses API; +- Chat Completions API; +- Anthropic Messages API; +- streaming і non-streaming режими; +- tool calls; +- reasoning content; +- `text.format` і structured output; +- коректні `finish_reason` та terminal events; +- cancellation і timeout; +- обмеження розміру запитів; +- health, readiness і status endpoints. + +**Критерій приймання:** записані реальні Codex-сесії відтворюються через Rust control plane без protocol errors, втрачених tool calls або незавершених SSE streams. + +### G2. Простий deployment + +Підготувати versioned OCI image і один керівний executable. + +Deployment повинен: + +- запускатися однією командою; +- автоматично визначати GPU і допустимий memory plan; +- використовувати зовнішній model volume; +- підтримувати конфігурацію через файл та environment variables; +- мати readiness лише після повного завантаження моделі; +- коректно завершувати й перезапускати worker; +- не вимагати ручного встановлення Python dependencies. + +**Критерій приймання:** чистий Linux GPU-вузол після встановлення драйвера запускає готовий endpoint однією командою; модель не завантажується повторно після перезапуску контейнера. + +### G3. Єдиний performance harness + +Створити benchmark suite для: + +- raw engine; +- HTTP/SSE control plane; +- cold і warm prefill; +- decode без speculation; +- MTP і suffix speculation; +- 1×256K, 2×256K і 1×512K; +- коротких, довгих, повторюваних і реальних agent outputs; +- single-slot latency та aggregate multi-slot throughput; +- RAM, VRAM, PCIe і NVMe traffic. + +**Критерій приймання:** будь-яку оптимізацію можна перевірити однією командою та отримати machine-readable JSON і Markdown-звіт. + +### G4. Максимізація speculative decoding + +Оптимізувати: + +- розмір MTP verify window; +- адаптивний вибір speculation depth; +- перемикання між MTP і suffix drafts; +- workload-specific policy без зміни якості; +- взаємодію speculation з expert cache і multi-token CPU kernels. + +**Критерій приймання:** приріст decode tok/s на реальному agent workload підтверджений A/B тестом; greedy output або quality gate не погіршується. + +### G5. Оптимізація GPU kernels і memory traffic + +Виконати профілювання Nsight Systems/Compute та оптимізувати: + +- quantized GEMV/MMQ; +- QSA attention; +- KV append/read; +- synchronization points; +- CUDA Graph capture; +- allocations і staging buffers; +- kernel fusion; +- compile flags, LTO та спеціалізацію під `sm_120`; +- overlap CPU, PCIe і GPU work. + +**Критерій приймання:** кожна прийнята зміна має профіль до/після та не створює нової глобальної синхронізації в hot path. + +### G6. Інтеграція Koference/KAR + +Цільовий ланцюг розгортання: `fetch` → перевірка SHA-256 джерела → `prepare` у KAR-2 з provenance та digest → перевірка архіву → передача стисненого представлення на GPU → декодування потрібних блоків на GPU → multiply. Початковий IQ3_S сам уже квантований; перекодування до KAR не можна вважати збереженням якості без окремих вимірювань. Поки quality gate KAR не пройдено, базовий IQ3_S шлях залишається контрольним і жодне lossy-перетворення не стає типовим режимом. + +Перевірити й реалізувати окремо: + +1. KAR для expert cache misses; +2. GPU decode стисненого експерта з подальшим GPU multiply; +3. прогресивні рівні точності для hot/cold experts; +4. `kar_decode_rows()` для PLE; +5. окремий rate budget для expert bank, dense matrices і PLE; +6. scheduler, який перекриває decode, transfer і multiply. + +**Критерій приймання:** інтегрований шлях швидший за поточний CPU cache-miss path на однаковій якості та не збільшує median latency при високому cache hit. + +### G7. Value-Only Cache для Qwen3.8 + +Два явні режими конфігурації кешу: `with-key` (контрольний KV cache) і `without-key` (експериментальний Value-Only). Режим без K не означає видалення окремих QSA indexer keys. Артефакт моделі, параметри перетворення `Wq_keyless` і вибір режиму мають бути прив'язані до digest та журналу вимірювань. + +Дослідити retrofit методу Keyless Attention: + +1. витягнути `Wq`, `Wk`, `Wv` для 12 QSA-шарів; +2. знайти найкраще algebraic/least-squares перетворення `Wq_keyless`; +3. виміряти residual у weight space; +4. перевірити attention logits і layer outputs на реальних activation traces; +5. за потреби навчити лише routing matrices, залишивши решту моделі замороженою; +6. реалізувати Value-Only kernel у Strata; +7. перевірити повну модель на 256K і 512K. + +Очікувана економія INT8 K: + +- 1×256K: приблизно **1,55 GiB**; +- 2×256K: приблизно **3,1 GiB**; +- 1×512K: приблизно **3,1 GiB**. + +Окремі QSA indexer keys зберігаються. + +**Критерій приймання:** режим проходить quality gate і дає вимірюваний виграш у пам'яті; швидкість і якість публікуються незалежно одна від одної. Якщо quality gate не пройдено, режим залишається експериментальним і не вмикається за замовчуванням. + +### G8. Continuous batching і кілька slots + +Реалізувати: + +- два незалежні 256K slots; +- continuous batching; +- fair scheduling; +- окремий conversation/KV state для кожного slot; +- контроль VRAM/RAM admission до запуску запиту; +- пріоритет latency або aggregate throughput через конфігурацію. + +**Критерій приймання:** два паралельні агенти не пошкоджують стан один одного, не блокують control plane та дають більший aggregate tok/s, ніж послідовне виконання тих самих запитів. + +### G9. Горизонтальне масштабування + +Створити fleet scheduler для кількох GPU-вузлів: + +- реєстрація worker nodes; +- health і capacity discovery; +- sticky routing за conversation/prefix cache; +- least-loaded routing для нових сесій; +- backpressure; +- retry лише до початку видимого stream або через явний resumable protocol; +- graceful drain вузла; +- централізовані метрики; +- окреме зберігання model artifacts і runtime images. + +**Критерій приймання:** додавання нового вузла збільшує доступну concurrency без зміни клієнтської конфігурації; активні сесії не мігрують без явного механізму перенесення state. + +### G10. Телеметрія для аналізу й подальшого tuning + +Логувати в структурованому форматі: + +- request metadata; +- response metadata; +- optional full request/response capture; +- token counts; +- TTFT і wall time; +- prefill/decode tok/s; +- speculation source, depth і acceptance; +- expert-cache hit/miss; +- KV hit/transfer; +- GPU/CPU/RAM/VRAM usage; +- tool calls і protocol termination; +- model/config/build identifiers. + +Secrets і credentials мають вилучатися до запису. Full payload capture вмикається окремо для дослідницького середовища. + +**Критерій приймання:** кожну повільну або невдалу відповідь можна пов'язати з конкретним request, engine run, конфігурацією й ресурсним профілем. + +## 7. Quality gates + +### Gate A — protocol + +- 100% terminal SSE events; +- жодного stream без `finish_reason`; +- tool-call arguments не втрачаються і не змінюються; +- structured output проходить schema validation; +- cancellation не залишає slot зайнятим. + +### Gate B — deterministic inference + +Для non-lossy змін: + +- greedy output повинен збігатися з baseline або; +- відхилення tensor outputs має вкладатися в наперед визначений numerical tolerance. + +### Gate C — model quality + +Для lossy змін: + +- perplexity; +- long-context needle/retrieval на різних глибинах; +- код, документи, арифметика й cross-reference; +- tool selection і tool arguments; +- завершення реальних LeaseVibe-задач; +- відсутність fluent nonsense, порожніх відповідей і повторюваних циклів. + +Рішення приймається за кожною категорією окремо. Загальна середня оцінка не може приховати провал категорії. + +### Gate D — performance + +- парний A/B; +- однакові prompts і sampling settings; +- прогрітий та cold режими розділені; +- однакові power/clock conditions; +- звіт про розподіл, а не лише найкращий результат; +- зміна якості враховується поруч із приростом швидкості. + +### Gate E — stability + +- тривалий soak із реальним agent workload; +- заповнення диска, обрив клієнта й timeout не ламають worker; +- control plane відновлюється після crash worker; +- відсутні витоки VRAM/RAM між запитами; +- два slots ізольовані. + +## 8. Етапи реалізації + +### M0. Fork і baseline + +- створити окремий fork Strata; +- зафіксувати upstream commit; +- відокремити generated/runtime files від source tree; +- додати reproducible build; +- зафіксувати baseline 1×256K; +- створити performance ledger. + +**Результат:** відтворювана точка порівняння. + +### M1. API reliability + +- виправити завершення SSE при помилках логування; +- додати native Responses API; +- реалізувати `text.format`; +- додати structured telemetry; +- закрити відомі Codex/MCP failures. + +**Результат:** Codex працює без bridge і без automatic-review protocol failures. + +### M2. Rust control plane + +- перенести production API й process supervision; +- створити differential replay проти Python server; +- додати deployment image; +- провести soak і performance comparison. + +**Результат:** production serving не залежить від Python. + +### M3. Safe performance work + +- speculation policy; +- sync removal; +- CUDA Graph і buffer reuse; +- KV/expert-cache memory planner; +- compile specialization; +- 1×256K optimization. + +**Результат:** накопичений підтверджений приріст без зміни якості. + +### M4. Multi-slot + +- 2×256K; +- continuous batching; +- admission control; +- aggregate throughput benchmark. + +**Результат:** два стабільні паралельні агенти. + +### M5. Experimental memory architecture + +- KAR integration; +- PLE row decode; +- GPU cache-miss path; +- Value-Only Cache feasibility; +- 1×512K. + +**Результат:** окремі experimental profiles із чесними quality/performance звітами. + +### M6. Fleet + +- node agent; +- central scheduler; +- sticky routing; +- autoscaling hooks; +- multi-node load test. + +**Результат:** горизонтальне масштабування на орендованих серверах. + +## 9. Перший backlog + +1. Створити fork і чистий source checkout. +2. Зафіксувати build provenance та baseline configuration. +3. Зібрати golden corpus реальних Codex request/response streams. +4. Виправити залежність protocol completion від запису логів. +5. Реалізувати native `/v1/responses` і `text.format`. +6. Додати machine-readable performance ledger. +7. Створити Rust control plane skeleton із health/status/SSE. +8. Реалізувати differential replay Python vs Rust. +9. Побудувати контрольований benchmark для speculation depth. +10. Провести Nsight profile одного cold і одного warm agent turn. +11. Реалізувати offline Keyless least-squares feasibility probe. +12. Додати окремий експеримент `K4V8` для визначення чутливості K. +13. Оформити стабільний C ABI для libkar. +14. Порівняти CPU expert miss із KAR GPU miss на однаковому expert block. +15. Спроєктувати memory admission для 2×256K і 1×512K. + +## 10. Межі першої версії + +Перша production-версія повинна підтримувати: + +- Linux; +- NVIDIA RTX 50xx; +- один GPU на worker; +- Qwen3.8-Flash-Next IQ3_S; +- 1×256K; +- native Codex Responses API; +- Rust control plane; +- structured telemetry; +- відтворюваний OCI deployment. + +HIP/AMD, multi-GPU всередині одного worker, Value-Only Cache, KAR і 512K додаються після стабільного baseline та мають власні quality gates. + +## 11. Definition of Done + +Проєкт досяг основної мети, коли виконані всі умови: + +1. Qwen3.8-Flash-Next працює в режимах 2×256K і 1×512K. +2. Codex підключається напряму через native Responses API. +3. MCP tool calls, automatic approval review і structured output працюють стабільно. +4. Production endpoint не залежить від Python runtime. +5. Є one-command deployment на орендованому NVIDIA GPU-вузлі. +6. Є reproducible performance і quality harness. +7. Жоден заявлений приріст не базується на одиничному best run. +8. Накопичені оптимізації дають вимірюваний приріст speed або throughput без неприйнятної втрати якості. +9. Кілька вузлів об'єднуються одним scheduler із sticky routing і backpressure. +10. Усі experimental режими мають чіткий статус: `rejected`, `experimental` або `production`. + +## 12. Принцип прийняття рішень + +Пріоритет визначається так: + +1. коректність і завершення задач; +2. якість моделі; +3. end-to-end task throughput; +4. decode і prefill throughput; +5. використання VRAM/RAM; +6. простота deployment і масштабування. + +Оптимізація, що дає 1% і стабільно проходить gates, зберігається. Оптимізація з великим синтетичним прискоренням, яка не покращує реальний agent workload, не входить до production profile. diff --git a/README.md b/README.md index d8ecf4e0..518cef37 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,50 @@ -# Leleka +# Leleka / Strata Next -Leleka is an independent Rust inference runtime. The first checked-in slice is -the versioned backend boundary in `leleka-backend-api`. +Leleka is the independent Rust NVIDIA inference runtime being developed from +this repository. The complete tracked Strata Next source tree was imported from +`paveldhq/strata-next` commit +`1263e88f8947b9796924eb7e8d8d7af08b589049`; see `docs/upstream.md` for the +pinned Strata engine provenance. The imported desktop application, Rust control +plane, deployment code, model tooling, tests, and reference engine are all here. -## Current scope +The migration is staged: Leleka must eventually run without a Strata process, +Strata source, Python, or a separately installed CUDA Toolkit on the target +host. Until the replacement passes the same protocol, model-quality, and +operational gates, Strata remains the behavior baseline. No model family or +performance gain is claimed for Leleka until its real-model gates pass. -- The API crate defines model identity, backend capabilities, load/generate/ - cancel/unload operations, and typed generation events. -- Generation streams enforce one terminal result and report a producer that - disappears without completion. -- The crate has no Strata, Python, CUDA, model weights, or inference engine - dependency. No model family is claimed as implemented yet. +## Repository layout -This is the interface foundation, not a runnable model server. NVIDIA engine -integration and real-model/protocol/quality qualification remain future work. +- `crates/backend-api/` — Leleka's versioned Rust backend contract. +- `desktop/`, `desktop-core/` — current desktop application and its Rust core. +- `control-plane/` — current Rust API, Responses handling, and worker supervisor. +- `engine/strata/` — pinned upstream Strata reference; retained during migration. +- `gpu/` — experimental optimization components, including KAR. +- `integrations/`, `manifests/`, `deploy/`, `scripts/` — client integration, + model profiles, packaging, and development/test tooling. +- `PROJECT_CHARTER.md`, `docs/` — requirements, provenance, decisions, and + performance/quality gates. + +Model weights, request captures, credentials, local logs, and generated build +artifacts remain outside Git or under ignored paths. + +## Current Leleka scope + +The Leleka implementation currently defines a backend contract for model +identity, capability declarations, loading, generation, cancellation, unloading, +typed output events, and exactly-one terminal stream behavior. It has no +inference backend or CUDA integration yet. The repository also contains the +existing Strata Next desktop and control-plane implementations as migration +source; their presence does not mean Leleka can serve a model independently. ## Development +Run the Rust workspace tests and lint: + ```sh cargo test --workspace --locked cargo clippy --workspace --all-targets --all-features -- -D warnings ``` + +For the Linux release requirements, see [PROJECT_CHARTER.md](PROJECT_CHARTER.md) +and [the independent engine design](docs/architecture/independent-nvidia-engine.md). diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 00000000..2e991ab3 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,63 @@ +# Benchmarks + +The `fixtures/responses/` directory currently holds a synthetic protocol replay example. It is not a real Codex capture or a performance measurement. Run it through the Rust `replay-responses` binary described in [control-plane/README.md](../control-plane/README.md). + +Store future benchmark definitions and sanitized fixtures in Git; place generated reports and sensitive captures outside the source tree or under ignored local paths. No baseline has been measured yet. + +## Synthetic paired Chat smoke + +`fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report. + +For the current upstream server, pass its full bound URL as `--baseline-url`, its `/health` URL as `--baseline-ready-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. The readiness poll waits for a nonzero `max_context` because upstream can report `loaded: true` during loading. Once a compressed inference endpoint exists, pass its URL as `--candidate-url` and optionally `--candidate-ready-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config. +# Live Responses episode replay + +`scripts/replay-live-responses.py` is an offline evaluator for an **explicitly +isolated native endpoint**. It sends real inference requests. Do not point it +at a user's active runtime. Remote evaluation uses an existing SSH loopback +tunnel; this tool does not create tunnels or change runtime configuration. + +Copy `fixtures/responses/live-tool-episode.json` to private storage, set the +configured model ID in both requests, and record model digests, runtime/engine +commits, hardware/driver, configuration and cache conditions in `provenance`. +Only use deliberately sanitized episodes. The `sanitized` flag records the +operator's assertion; it cannot sanitize arbitrary captured agent traffic. + +```sh +python3 scripts/replay-live-responses.py \ + --endpoint http://127.0.0.1:18082 \ + --fixture /private/evaluation/episode.json \ + --key-file /private/evaluation/api.key \ + --output /private/evaluation/new-evidence-directory +``` + +The output directory must not exist. It is created with mode 0700, with 0600 +fixture, request, raw response and report files. Credentials never enter those +files or command arguments. HTTP calls have an 8 MiB response limit and a total +wall deadline (default 120 seconds, configurable with `--timeout`); an isolated +child is killed and reaped on timeout, including drip-fed headers. Redirects +are not followed. Failed checks retain a failing report and available evidence; +partial transport bodies lost on timeout are not captured. + +Each episode runs twice, first JSON then SSE, with independent explicitly +replayed history and `store=false`. Each step supplies a request and exact +semantic `expect` list. Later steps can supply `tool_results` strings in the +previous turn's call order. Returned call IDs are bound automatically. No shell, +MCP or other tool is ever executed. Call IDs and argument JSON formatting may +differ between arms; normalized argument values and visible content must match +exactly. Tokens, timings and hashes are recorded separately; this is not a +paired performance benchmark. + +The verifier requires contiguous named events, exactly one successful terminal, +consistent response/item identities, matching delta/done/final values, all +items closed and consistent usage. It accepts native text, reasoning-content, +function and custom-tool events; unsupported events fail closed. Readiness, +idle queue/admission state and generation-counter deltas are checked around +each arm. Counter mismatches invalidate the isolated replay; this is not an +exclusive server lease or a durable process-epoch check. Reserve the endpoint +for the evaluation and independently record its process/build identity. +These observations do not replace cancellation/crash fault injection or a +long-running soak. A declared real-model provenance alone is not qualification. + +Hosted CI runs the runner against actual native HTTP with a synthetic CPU +worker, plus corrupt-stream/auth/overwrite/deadline tests. The full sanitized +Codex/MCP real-model replay and model-quality gates remain separate and open. diff --git a/benchmarks/fixtures/chat/cold-prefill-v1.json b/benchmarks/fixtures/chat/cold-prefill-v1.json new file mode 100644 index 00000000..a87484e3 --- /dev/null +++ b/benchmarks/fixtures/chat/cold-prefill-v1.json @@ -0,0 +1,42 @@ +{ + "schema": 1, + "name": "public-synthetic-cold-prefill-v1", + "cases": [ + { + "id": "cold-alpha", + "category": "retrieval", + "messages": [{"role": "user", "content": {"parts": [ + {"text": "ALPHA run. Read the log and return only its valid audit code. Decoy codes are invalid.\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "VALID AUDIT CODE: amber-731\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "What is the VALID AUDIT CODE? Reply with the code only."} + ]}}], + "expect": {"text_regex": "^amber-731\\s*$"} + }, + { + "id": "cold-beta", + "category": "retrieval", + "messages": [{"role": "user", "content": {"parts": [ + {"text": "BETA run. Read the log and return only its valid audit code. Decoy codes are invalid.\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "VALID AUDIT CODE: cobalt-482\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "What is the VALID AUDIT CODE? Reply with the code only."} + ]}}], + "expect": {"text_regex": "^cobalt-482\\s*$"} + }, + { + "id": "cold-gamma", + "category": "retrieval", + "messages": [{"role": "user", "content": {"parts": [ + {"text": "GAMMA run. Read the log and return only its valid audit code. Decoy codes are invalid.\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "VALID AUDIT CODE: violet-915\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "What is the VALID AUDIT CODE? Reply with the code only."} + ]}}], + "expect": {"text_regex": "^violet-915\\s*$"} + } + ] +} diff --git a/benchmarks/fixtures/chat/paired-smoke.json b/benchmarks/fixtures/chat/paired-smoke.json new file mode 100644 index 00000000..a12778bf --- /dev/null +++ b/benchmarks/fixtures/chat/paired-smoke.json @@ -0,0 +1,34 @@ +{ + "schema": 1, + "name": "public-synthetic-chat-smoke", + "cases": [ + { + "id": "arithmetic", + "category": "reasoning", + "messages": [ + {"role": "user", "content": "Compute 17 * 19. Reply with the integer only."} + ], + "expect": {"text_regex": "^323\\s*$"} + }, + { + "id": "retrieval", + "category": "retrieval", + "messages": [ + {"role": "user", "content": "Facts: Ada owns a blue kite. Bruno owns a red cup. Cora owns a green book. Dany owns a yellow lamp. Who owns the green book? Reply with the name only."} + ], + "expect": {"text_regex": "^Cora\\s*$"} + }, + { + "id": "tool-call", + "category": "tool-calling", + "messages": [ + {"role": "user", "content": "Look up the weather for Paris. Use the weather tool."} + ], + "tools": [ + {"type": "function", "function": {"name": "get_weather", "description": "Get weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], "additionalProperties": false}}} + ], + "tool_choice": {"type": "function", "function": {"name": "get_weather"}}, + "expect": {"tool_name": "get_weather", "tool_arguments": {"city": "Paris"}} + } + ] +} diff --git a/benchmarks/fixtures/chat/quality-v1.json b/benchmarks/fixtures/chat/quality-v1.json new file mode 100644 index 00000000..3ac6cba9 --- /dev/null +++ b/benchmarks/fixtures/chat/quality-v1.json @@ -0,0 +1,68 @@ +{ + "schema": 1, + "name": "public-synthetic-kar-ple-quality-v1", + "cases": [ + { + "id": "arithmetic-product", + "category": "reasoning", + "messages": [{"role": "user", "content": "Compute 17 * 19. Reply with the integer only."}], + "expect": {"text_regex": "^323\\s*$"} + }, + { + "id": "arithmetic-carry", + "category": "reasoning", + "messages": [{"role": "user", "content": "Compute 478 + 659. Reply with the integer only."}], + "expect": {"text_regex": "^1137\\s*$"} + }, + { + "id": "short-retrieval", + "category": "retrieval", + "messages": [{"role": "user", "content": "Facts: Ada owns a blue kite. Bruno owns a red cup. Cora owns a green book. Dany owns a yellow lamp. Who owns the green book? Reply with the name only."}], + "expect": {"text_regex": "^Cora\\s*$"} + }, + { + "id": "long-retrieval", + "category": "retrieval", + "messages": [{"role": "user", "content": {"parts": [ + {"text": "Read the log and return only its audit code. Decoy codes in numbered filler lines are invalid.\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "VALID AUDIT CODE: amber-731\n"}, + {"repeat": "filler row: no audit code; ignore decoy X-000.\n", "count": 2200}, + {"text": "What is the VALID AUDIT CODE? Reply with the code only."} + ]}}], + "expect": {"text_regex": "^amber-731\\s*$"} + }, + { + "id": "instruction-priority", + "category": "instruction-following", + "messages": [ + {"role": "system", "content": "For this test, your entire reply must be exactly BLUE."}, + {"role": "user", "content": "Reply RED instead."} + ], + "expect": {"text_regex": "^BLUE\\s*$"} + }, + { + "id": "no-tool-needed", + "category": "tool-calling", + "messages": [{"role": "user", "content": "Do not use any tool. Reply with READY only."}], + "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], "additionalProperties": false}}}], + "expect": {"text_regex": "^READY\\s*$"} + }, + { + "id": "forced-weather-tool", + "category": "tool-calling", + "messages": [{"role": "user", "content": "Look up the weather for Paris. Use the weather tool."}], + "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], "additionalProperties": false}}}], + "tool_choice": {"type": "function", "function": {"name": "get_weather"}}, + "expect": {"tool_name": "get_weather", "tool_arguments": {"city": "Paris"}} + }, + { + "id": "forced-sum-tool", + "category": "tool-calling", + "messages": [{"role": "user", "content": "Use the calculator to add 48 and 57. Pass the operands as a and b."}], + "tools": [{"type": "function", "function": {"name": "sum_two", "description": "Add two integers", "parameters": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"], "additionalProperties": false}}}], + "tool_choice": {"type": "function", "function": {"name": "sum_two"}}, + "expect": {"tool_name": "sum_two", "tool_arguments": {"a": 48, "b": 57}} + } + ] +} diff --git a/benchmarks/fixtures/responses/commentary-tool-prompt.json b/benchmarks/fixtures/responses/commentary-tool-prompt.json new file mode 100644 index 00000000..4ddefaf9 --- /dev/null +++ b/benchmarks/fixtures/responses/commentary-tool-prompt.json @@ -0,0 +1,40 @@ +{ + "provenance": "Pinned engine/strata/serve/chat_template.jinja rendered with Jinja2 3.1.6; sanitized fixture", + "request": { + "model": "strata-local", + "reasoning": { + "effort": "none" + }, + "input": [ + { + "role": "user", + "content": "Weather in Oslo?" + }, + { + "type": "reasoning", + "content": [ + { + "type": "reasoning_text", + "text": "Use the lookup." + } + ] + }, + { + "role": "assistant", + "content": "Checking. \n" + }, + { + "type": "function_call", + "call_id": "call_fixture", + "name": "lookup", + "arguments": "{\"city\":\"Oslo\"}" + }, + { + "type": "function_call_output", + "call_id": "call_fixture", + "output": "3°C" + } + ] + }, + "rendered": "<|im_start|>user\nWeather in Oslo?<|im_end|>\n<|im_start|>assistant\n\nUse the lookup.\n\n\nChecking.\n\n\n\n\nOslo\n\n\n<|im_end|>\n<|im_start|>user\n\n3°C\n<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" +} diff --git a/benchmarks/fixtures/responses/live-tool-episode.json b/benchmarks/fixtures/responses/live-tool-episode.json new file mode 100644 index 00000000..29ce5600 --- /dev/null +++ b/benchmarks/fixtures/responses/live-tool-episode.json @@ -0,0 +1,26 @@ +{ + "schema": 1, + "sanitized": true, + "provenance": {"class": "synthetic episode; supply actual model/build/hardware identities for qualification"}, + "steps": [ + { + "request": { + "model": "strata-local", "input": "Call lookup with key value. Do not output any other text.", + "max_output_tokens": 256, "temperature": 0, "reasoning": {"effort": "none"}, + "tools": [{"type": "function", "name": "lookup", "parameters": {"type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"], "additionalProperties": false}}], + "tool_choice": {"type": "function", "name": "lookup"} + }, + "expect": [{"type": "function_call", "name": "lookup", "arguments": {"key": "value"}}] + }, + { + "request": { + "model": "strata-local", "input": "Reply with exactly CONFIRMED-731 and nothing else.", + "max_output_tokens": 64, "temperature": 0, "reasoning": {"effort": "none"}, + "tools": [{"type": "function", "name": "lookup", "parameters": {"type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"], "additionalProperties": false}}], + "tool_choice": "none" + }, + "tool_results": ["CONFIRMED-731"], + "expect": [{"type": "text", "text": "CONFIRMED-731"}] + } + ] +} diff --git a/benchmarks/fixtures/responses/structured-tool.json b/benchmarks/fixtures/responses/structured-tool.json new file mode 100644 index 00000000..9b5160fa --- /dev/null +++ b/benchmarks/fixtures/responses/structured-tool.json @@ -0,0 +1,30 @@ +{ + "request": { + "model": "strata-local", + "input": "Return a small result and call the example tool.", + "stream": true, + "store": false, + "text": { + "format": { + "type": "json_schema", + "name": "result", + "strict": true, + "schema": { + "type": "object", + "properties": {"ok": {"type": "boolean"}}, + "required": ["ok"], + "additionalProperties": false + } + } + }, + "tools": [{"type": "function", "name": "example_tool", "parameters": {"type": "object"}}] + }, + "items": [ + {"type": "text", "deltas": ["{\"ok\":", "true}"]}, + {"type": "function_call", "name": "example_tool", "call_id": "call_example", "argument_deltas": ["{\"value\":", "1}"]} + ], + "usage": {"input_tokens": 14, "output_tokens": 9, "reasoning_tokens": 0, "cached_tokens": 0}, + "id": "resp_fixture_001", + "created_at": 1, + "completed_at": 2 +} diff --git a/control-plane/Cargo.lock b/control-plane/Cargo.lock new file mode 100644 index 00000000..684c75e5 --- /dev/null +++ b/control-plane/Cargo.lock @@ -0,0 +1,2224 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "borrow-or-share" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fancy-regex" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" +dependencies = [ + "bit-set", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fluent-uri" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e" +dependencies = [ + "borrow-or-share", + "ref-cast", + "serde", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fraction" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500" +dependencies = [ + "num", + "num-bigint", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonschema" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5761b0ca0a31464030d7c2a98087fde3124ebb5e09b5a112cdb815f03b8ee150" +dependencies = [ + "ahash", + "bytecount", + "data-encoding", + "email_address", + "fancy-regex", + "fraction", + "getrandom 0.3.4", + "itoa", + "jsonschema-regex", + "jsonschema-value", + "num-cmp", + "num-traits", + "percent-encoding", + "referencing", + "regex", + "serde", + "serde_json", + "strum", + "unicode-general-category", + "uuid-simd", +] + +[[package]] +name = "jsonschema-regex" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1ffba4378a3d6ee7f1ab65a8ed95c711ccfe4a3870932bdce89d8260abed38a" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "jsonschema-value" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "386121f898b560ff6aaa7974952720e9d9276a201eca31296387c2ed8707855e" +dependencies = [ + "ahash", + "bytecount", + "fraction", + "getrandom 0.3.4", + "num-cmp", + "num-traits", + "serde_json", + "zmij", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "micromap" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-cmp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "referencing" +version = "0.58.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cfa1c91745dbca76a406b926918d7c63e15a4525ebab939fec3e015a1fb82b1" +dependencies = [ + "ahash", + "fluent-uri", + "getrandom 0.3.4", + "hashbrown", + "itoa", + "micromap", + "parking_lot", + "percent-encoding", + "serde_json", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strata-control" +version = "0.1.0" +dependencies = [ + "aho-corasick", + "axum", + "cc", + "fancy-regex", + "futures-core", + "hex", + "http-body", + "http-body-util", + "jsonschema", + "libc", + "regex", + "regex-syntax", + "reqwest", + "serde", + "serde_json", + "sha2", + "subtle", + "tokio", + "webpki-root-certs", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml new file mode 100644 index 00000000..3a1da7d8 --- /dev/null +++ b/control-plane/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "strata-control" +version = "0.1.0" +edition = "2024" +rust-version = "1.99" +default-run = "strata-next" + +[[bin]] +name = "strata-next" +path = "src/main.rs" + +[dependencies] +aho-corasick = "1.1" +axum = "0.8" +fancy-regex = "0.19" +futures-core = "0.3" +hex = "0.4" +http-body = "1" +jsonschema = { version = "0.58.4", default-features = false } +libc = "0.2" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] } +regex = "1.13.1" +regex-syntax = "0.8.11" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.11" +subtle = "2.6.1" +tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt-multi-thread", "signal", "sync", "time"] } +webpki-root-certs = "1.0" + +[build-dependencies] +cc = "1" +sha2 = "0.11" + +[dev-dependencies] +http-body-util = "0.1" diff --git a/control-plane/README.md b/control-plane/README.md new file mode 100644 index 00000000..9c7a6089 --- /dev/null +++ b/control-plane/README.md @@ -0,0 +1,22 @@ +# Control plane + +For small, experimental sharded fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` acquires and verifies the sources, creates a KAR-2 preview, and verifies it again. It reuses an existing archive only when its payload, provenance, source identity, and requested level count verify. `model smoke-fixture --output FILE.kar` creates a deterministic model-free archive, and `model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes it on CPU for comparison with the CUDA smoke tool. The 64 MiB input limit remains; these commands cannot prepare the target model for serving. + +The repository pins Rust 1.99.0 in [`rust-toolchain.toml`](../rust-toolchain.toml). `rustup` selects it automatically from this checkout. The `strata-next` executable defaults to `serve` and also supports `doctor`, `model fetch MANIFEST --output DIR`, `model verify MANIFEST --output DIR`, `model inspect FILE.gguf`, `model index FILE.gguf [--hash]`, `model derive-iq3-identity FILE.gguf`, `model derive-mixed-identity FILE.gguf`, `model derive-sharded-identity MANIFEST --source-dir DIR`, `model prepare-f32-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N`, `model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N`, `model inspect-kar FILE.kar`, `model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]`, `model verify-iq3-preview FILE.kar --source FILE.gguf`, `model verify-mixed-preview FILE.kar --source FILE.gguf`, `model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR`, `model extract-tokenizer FILE.gguf --output DIR`, `model tokenize TOKENIZER_DIR TEXT [--special]`, and `model detokenize TOKENIZER_DIR IDS`. Use `model tokenize TOKENIZER_DIR --stdin [--special]` for long text or control bytes. The IQ3, mixed, and sharded identity commands hash virtual F32 streams with bounded memory. Preview preparation commands write provenance sidecars, which the corresponding verification commands recompute and check against the archives. No preview archive is approved for serving. `model inspect-kar` checks bounded KAR-2 metadata, header CRC, directory digest, tensor shapes, and section bounds; `model verify-kar` also scans payload CRC-32 checksums. With a manifest and source directory it verifies each physical source shard and the archive's concatenated source digest. Neither command decodes KAR weights or measures quality. `scripts/check-local.sh` runs formatting, Clippy, Rust tests, protocol replay, and the CPU engine tests. + +The Rust control plane provides process health, worker readiness, status, and graceful shutdown. It can start a Strata engine worker and records worker readiness only after the engine emits `READY `. An abandoned internal generation sends `STOP` and drains its terminal response before the next request; shutdown during generation sends `STOP` before `QUIT`. With tokenizer assets configured, `POST /v1/responses` can perform a restricted non-streaming text generation with `reasoning.effort: "none"`. It returns 503 while the worker is unavailable, 501 for unsupported live features or a missing tokenizer, and never fabricates a model response. Worker restart is not yet implemented. + +Run locally with `cargo run --manifest-path control-plane/Cargo.toml`. It binds to `127.0.0.1:8081` by default; set `STRATA_BIND` to another socket address if needed. Check `/health`, `/ready`, and `/status`. + +Set `STRATA_CONFIG` to a JSON file using [`config.example.json`](config.example.json) as a template. The file supports `bind` and an `engine` object with `executable`, `args`, `tokenizer_dir`, and `startup_timeout_s` (1–3600 seconds, default 600). `STRATA_BIND`, `STRATA_ENGINE_EXE`, `STRATA_ENGINE_ARGS_JSON`, `STRATA_TOKENIZER_DIR`, and `STRATA_STARTUP_TIMEOUT_S` override their file counterparts. The control plane supplies `--serve` itself. The tokenizer directory must contain the native assets extracted from the model. + +Without an engine configuration, `/ready` returns HTTP 503 and `/status` reports `unconfigured`. A configured worker reports `starting`, then `ready` with `max_context`, or `failed` if startup, the readiness handshake, or the process fails. `/ready` returns HTTP 200 only when the worker and native tokenizer are configured and ready for the restricted text preview. During shutdown the worker reports `stopping` and receives `QUIT`. Startup has a timeout; the control plane never advertises readiness before the engine handshake. + +Run the local contract checks with `cargo test --manifest-path control-plane/Cargo.toml --locked`. The tests use a small fake engine process and need no GPU or model. The supervisor test sends a token-ID `GEN` command through the worker pipe, reads `T` and `DONE`, and rejects a request that exceeds the ready worker's context. The Responses trace builder checks ordered SSE events, terminal completion, unchanged tool arguments, and JSON Schema output validation. The synthetic replay can be run as JSON or SSE: + +```sh +cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- benchmarks/fixtures/responses/structured-tool.json +cargo run --manifest-path control-plane/Cargo.toml --locked --bin replay-responses -- --sse benchmarks/fixtures/responses/structured-tool.json +``` + +See [API contract](../docs/api-contract.md) for the supported subset and remaining integration work. diff --git a/control-plane/build.rs b/control-plane/build.rs new file mode 100644 index 00000000..5d2f7dee --- /dev/null +++ b/control-plane/build.rs @@ -0,0 +1,117 @@ +#[path = "src/embedded_spec.rs"] +mod embedded_spec; + +fn main() { + embed_engine().expect("invalid embedded engine build configuration"); + println!("cargo:rerun-if-changed=src/ggml_bridge.c"); + println!("cargo:rerun-if-changed=third_party/ggml"); + cc::Build::new() + .file("third_party/ggml/ggml-quants.c") + .file("src/ggml_bridge.c") + .include("third_party/ggml") + .flag_if_supported("-std=c11") + .flag_if_supported("-ffunction-sections") + .flag_if_supported("-fdata-sections") + .warnings(false) + .compile("strata_ggml_quants"); +} + +fn embed_engine() -> Result<(), Box> { + use std::{env, fs, path::PathBuf}; + let names = [ + "STRATA_EMBED_ENGINE_PATH", + "STRATA_EMBED_ENGINE_SHA256", + "STRATA_EMBED_ENGINE_REVISION", + ]; + for name in names { + println!("cargo:rerun-if-env-changed={name}"); + } + let values: Vec<_> = names.iter().map(env::var_os).collect(); + let output = PathBuf::from(env::var_os("OUT_DIR").ok_or("missing OUT_DIR")?); + let payload_path = output.join("embedded-engine.bin"); + let (digest, revision) = if values.iter().all(Option::is_none) { + fs::write(&payload_path, [])?; + (String::new(), String::new()) + } else { + if values.iter().any(Option::is_none) { + return Err("set all three STRATA_EMBED_ENGINE_PATH/SHA256/REVISION variables".into()); + } + if env::var("CARGO_CFG_TARGET_OS")? != "linux" { + return Err("embedded engines require a Linux target".into()); + } + let path = PathBuf::from(values[0].as_ref().unwrap()).canonicalize()?; + let printable = path.to_str().ok_or("engine path must be UTF-8")?; + if printable.contains(['\n', '\r']) { + return Err("engine path cannot contain newlines".into()); + } + println!("cargo:rerun-if-changed={printable}"); + let file = fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Err("embedded engine must be a regular file".into()); + } + if file.metadata()?.len() > embedded_spec::MAX_BYTES { + return Err("embedded engine exceeds 1 GiB".into()); + } + let digest = values[1] + .as_ref() + .unwrap() + .to_str() + .ok_or("digest must be ASCII")?; + let revision = values[2] + .as_ref() + .unwrap() + .to_str() + .ok_or("revision must be ASCII")?; + embedded_spec::copy_verified( + file, + fs::File::create(&payload_path)?, + &env::var("CARGO_CFG_TARGET_ARCH")?, + digest, + revision, + )?; + (digest.to_ascii_lowercase(), revision.to_ascii_lowercase()) + }; + let size = fs::metadata(&payload_path)?.len(); + let declaration = if size == 0 { + "pub const BYTES: &[u8] = &[];\n".to_owned() + } else { + // Keep large verified payloads out of Rust constant evaluation/LLVM IR. + // The target assembler copies the bytes into an immutable ELF section. + let path = payload_path.to_str().ok_or("payload path must be UTF-8")?; + if path.contains(['\n', '\r']) { + return Err("payload path cannot contain newlines".into()); + } + let path = path.replace('\\', "\\\\").replace('"', "\\\""); + let assembly = output.join("embedded-engine.S"); + fs::write( + &assembly, + format!( + ".section .rodata.strata_engine,\"a\"\n\ + .balign 16\n\ + .global strata_embedded_engine_bytes\n\ + .hidden strata_embedded_engine_bytes\n\ + strata_embedded_engine_bytes:\n\ + .incbin \"{path}\"\n\ + .size strata_embedded_engine_bytes, .-strata_embedded_engine_bytes\n\ + .section .note.GNU-stack,\"\"\n" + ), + )?; + cc::Build::new() + .file(assembly) + .compile("strata_embedded_payload"); + format!( + "unsafe extern \"C\" {{ static strata_embedded_engine_bytes: [u8; {size}]; }}\n\ + // SAFETY: build.rs emits exactly {size} verified bytes in read-only storage.\n\ + pub static BYTES: &[u8] = unsafe {{ &strata_embedded_engine_bytes }};\n" + ) + }; + fs::write( + output.join("embedded-engine.rs"), + format!( + "{declaration}\ + pub const SHA256: &str = {digest:?};\n\ + pub const SOURCE_REVISION: &str = {revision:?};\n" + ), + )?; + Ok(()) +} diff --git a/control-plane/config.example.json b/control-plane/config.example.json new file mode 100644 index 00000000..b0563274 --- /dev/null +++ b/control-plane/config.example.json @@ -0,0 +1,10 @@ +{ + "bind": "127.0.0.1:8081", + "shutdown_grace_s": 0, + "engine": { + "executable": "/absolute/path/to/strata", + "tokenizer_dir": "/models/pack/tokenizer", + "args": ["--pack", "/models/pack", "--max-context", "262144", "--kv", "int8"], + "startup_timeout_s": 600 + } +} diff --git a/control-plane/examples/compare-iq3-s.rs b/control-plane/examples/compare-iq3-s.rs new file mode 100644 index 00000000..1b857aac --- /dev/null +++ b/control-plane/examples/compare-iq3-s.rs @@ -0,0 +1,57 @@ +//! Compare the independent Rust IQ3_S decoder with pinned ggml on real GGUF blocks. +//! The GGUF input stays outside Git; this diagnostic reads only caller-chosen blocks. + +use std::{ + env, + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, +}; + +use strata_control::{ggml_bridge, gguf, iq3_s}; + +fn main() -> Result<(), Box> { + let mut args = env::args().skip(1); + let path = args + .next() + .ok_or("usage: compare-iq3-s FILE.gguf [BLOCKS]")?; + let requested: u64 = args.next().unwrap_or_else(|| "1024".into()).parse()?; + if args.next().is_some() || requested == 0 { + return Err("usage: compare-iq3-s FILE.gguf [BLOCKS]".into()); + } + let path = Path::new(&path); + let index = gguf::tensor_index(path)?; + let tensor = index + .tensors + .iter() + .find(|tensor| tensor.kind == 21) + .ok_or("GGUF has no IQ3_S tensor")?; + let blocks = requested.min(tensor.bytes / iq3_s::BLOCK_BYTES as u64); + let mut source = File::open(path)?; + source.seek(SeekFrom::Start(index.summary.data_start + tensor.offset))?; + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + let mut ggml = [0.0f32; iq3_s::BLOCK_ELEMENTS]; + for number in 0..blocks { + source.read_exact(&mut block)?; + let rust = iq3_s::decode_block(&block)?; + ggml_bridge::decode_into(21, &block, &mut ggml)?; + if let Some(position) = rust + .iter() + .zip(&ggml) + .position(|(left, right)| left.to_bits() != right.to_bits()) + { + return Err(format!( + "block {number}, value {position}: Rust={:#010x}, ggml={:#010x}", + rust[position].to_bits(), + ggml[position].to_bits() + ) + .into()); + } + } + println!( + "{}: {blocks} IQ3_S blocks, {} F32 values bit-identical to pinned ggml", + tensor.name, + blocks * iq3_s::BLOCK_ELEMENTS as u64 + ); + Ok(()) +} diff --git a/control-plane/examples/compare-kar-range.rs b/control-plane/examples/compare-kar-range.rs new file mode 100644 index 00000000..a07054d7 --- /dev/null +++ b/control-plane/examples/compare-kar-range.rs @@ -0,0 +1,89 @@ +//! Independently decode a bounded KAR range and compare it with GGUF values. +//! The one-tensor GGUF and KAR inputs stay outside Git. This is a CPU diagnostic. + +use std::{ + env, + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, +}; + +use strata_control::{ggml_bridge, gguf, kar}; + +fn main() -> Result<(), Box> { + let mut args = env::args().skip(1); + let usage = "usage: compare-kar-range FILE.gguf FILE.kar LEVEL START COUNT"; + let source_path = args.next().ok_or(usage)?; + let archive_path = args.next().ok_or(usage)?; + let level: u8 = args.next().ok_or(usage)?.parse()?; + let start: usize = args.next().ok_or(usage)?.parse()?; + let count: usize = args.next().ok_or(usage)?.parse()?; + if args.next().is_some() || count == 0 || count > 1_000_000 { + return Err(usage.into()); + } + let source_path = Path::new(&source_path); + let archive_path = Path::new(&archive_path); + let index = gguf::tensor_index(source_path)?; + if index.tensors.len() != 1 { + return Err("diagnostic source must contain exactly one tensor".into()); + } + let tensor = &index.tensors[0]; + let (block_elements, block_bytes) = match tensor.kind { + 20 => (32usize, 18usize), + 21 => (256, 110), + _ => return Err("diagnostic supports IQ4_NL and IQ3_S sources".into()), + }; + let end = start.checked_add(count).ok_or("GGUF range overflow")?; + let elements = tensor + .dimensions + .iter() + .try_fold(1usize, |n, d| n.checked_mul(usize::try_from(*d).ok()?)) + .ok_or("GGUF element count overflow")?; + if end > elements { + return Err("GGUF range exceeds tensor".into()); + } + let reconstructed = kar::decode_tensor_range(archive_path, &tensor.name, level, start, count)?; + let first_block = start / block_elements; + let final_block = end.div_ceil(block_elements); + let first_block_bytes = first_block + .checked_mul(block_bytes) + .and_then(|n| u64::try_from(n).ok()) + .ok_or("GGUF offset overflow")?; + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|n| n.checked_add(first_block_bytes)) + .ok_or("GGUF offset overflow")?; + let mut source = File::open(source_path)?; + source.seek(SeekFrom::Start(absolute))?; + let mut block = vec![0u8; block_bytes]; + let mut decoded = vec![0.0f32; block_elements]; + let mut error_sum = 0.0f64; + let mut reference_sum = 0.0f64; + let mut maximum_absolute_error = 0.0f64; + for number in first_block..final_block { + source.read_exact(&mut block)?; + ggml_bridge::decode_into(tensor.kind, &block, &mut decoded)?; + let begin = start.max(number * block_elements); + let finish = end.min((number + 1) * block_elements); + for position in begin..finish { + let reference = f64::from(decoded[position - number * block_elements]); + let value = f64::from(reconstructed[position - start]); + let error = (reference - value).abs(); + error_sum += error * error; + reference_sum += reference * reference; + maximum_absolute_error = maximum_absolute_error.max(error); + } + } + let relative_l2 = if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }; + println!( + "{}: {count} archived F32 values decoded at level {level}, start {start}; relative L2 {relative_l2:.8}, maximum absolute error {maximum_absolute_error:.8}", + tensor.name + ); + Ok(()) +} diff --git a/control-plane/examples/kar-expert-fixture.rs b/control-plane/examples/kar-expert-fixture.rs new file mode 100644 index 00000000..6c3ae49e --- /dev/null +++ b/control-plane/examples/kar-expert-fixture.rs @@ -0,0 +1,69 @@ +//! Model-free routed-expert fixture, using the production KAR writer. +use sha2::{Digest, Sha256}; +use std::path::Path; +use strata_control::kar_writer::{self, SourceIdentity, Tensor, TensorData}; + +fn main() -> Result<(), String> { + let args: Vec<_> = std::env::args().collect(); + if args.len() != 2 { + return Err("usage: kar-expert-fixture NEW_OUTPUT.kar".into()); + } + const H: u64 = 64; + const F: u64 = 32; + const E: u64 = 2; + let scales = vec![0x2800u16; (H * F * E / 32) as usize]; // 1/32 + let mut plane = vec![u32::MAX; (H * F / 32) as usize]; + plane.extend(vec![0u32; (H * F / 32) as usize]); + let book = [0xbc00u16, 0x3c00]; // expert 0 positive, expert 1 negative + let books: [&[u16]; 1] = [&book]; + let planes: [&[u32]; 1] = [&plane]; + let raw: Vec = (0..3) + .flat_map(|_| { + (0..H * F * E).flat_map(|i| { + (if i < H * F { + 1.0f32 / 32.0 + } else { + -1.0f32 / 32.0 + }) + .to_le_bytes() + }) + }) + .collect(); + let source = SourceIdentity { + name: "synthetic-routed-experts", + architecture: "synthetic", + builder: "strata-next/kar-expert-fixture-v1", + digest: Sha256::digest(&raw).into(), + total_elements: H * F * E * 3, + bytes: raw.len() as u64, + }; + let dims = [[H, F, E], [H, F, E], [F, H, E]]; + let names = [ + "blk.0.ffn_gate_exps.weight", + "blk.0.ffn_up_exps.weight", + "blk.0.ffn_down_exps.weight", + ]; + let tensors: Vec<_> = (0..3) + .map(|role| Tensor { + name: names[role], + dims: &dims[role], + source_dtype: 0, + source_digest: Sha256::digest( + &raw[role * (H * F * E * 4) as usize..(role + 1) * (H * F * E * 4) as usize], + ) + .into(), + source_offset: role as u64 * H * F * E * 4, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 1, + scales: &scales, + books: &books, + planes: &planes, + }, + }) + .collect(); + kar_writer::write_archive(Path::new(&args[1]), &source, &tensors)?; + Ok(()) +} diff --git a/control-plane/examples/scan-quant-blocks.rs b/control-plane/examples/scan-quant-blocks.rs new file mode 100644 index 00000000..597d0df7 --- /dev/null +++ b/control-plane/examples/scan-quant-blocks.rs @@ -0,0 +1,53 @@ +//! Decode the first real block of each quantized GGUF kind in one source shard. +//! This is an offline diagnostic; input weights remain outside Git. + +use std::{collections::BTreeMap, env, fs::File, path::Path}; + +use sha2::{Digest, Sha256}; +use strata_control::{gguf, gguf_f32_stream}; + +fn main() -> Result<(), Box> { + let path = env::args() + .nth(1) + .ok_or("usage: scan-quant-blocks FILE.gguf")?; + let path = Path::new(&path); + let index = gguf::tensor_index(path)?; + let mut first_by_kind = BTreeMap::new(); + for tensor in &index.tensors { + first_by_kind.entry(tensor.kind).or_insert(tensor); + } + let mut source = File::open(path)?; + for (kind, tensor) in first_by_kind { + let (expected_elements, bytes) = + gguf::block_geometry(kind).ok_or_else(|| format!("unsupported source kind {kind}"))?; + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + let mut hasher = Sha256::new(); + let decoded_bytes = + gguf_f32_stream::visit(&mut source, absolute, kind, bytes, |_, values| { + if values + .as_chunks::<4>() + .0 + .iter() + .any(|word| !f32::from_le_bytes(*word).is_finite()) + { + return Err(format!("{}: non-finite decoded value", tensor.name)); + } + hasher.update(values); + Ok(()) + })?; + if decoded_bytes != expected_elements * 4 { + return Err(format!("{}: decoded block length mismatch", tensor.name).into()); + } + println!( + "kind {kind}: {} values from {} SHA-256 {}", + expected_elements, + tensor.name, + hex::encode(hasher.finalize()) + ); + } + Ok(()) +} diff --git a/control-plane/src/app.rs b/control-plane/src/app.rs new file mode 100644 index 00000000..92e9ccb0 --- /dev/null +++ b/control-plane/src/app.rs @@ -0,0 +1,414 @@ +use std::sync::Arc; + +use axum::{ + Json, Router, + extract::{DefaultBodyLimit, State}, + http::{HeaderMap, StatusCode}, + middleware, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use serde::Serialize; +use tokio::sync::{RwLock, mpsc}; + +use crate::{ + responses, + tokenizer::Tokenizer, + worker::{GenerationCommand, WorkerState, WorkerStatus}, +}; + +#[derive(Clone)] +pub struct AppState { + pub queue_timeout: Option, + pub lifecycle: crate::lifecycle::Lifecycle, + pub api_key: Option>, + pub model: Option, + pub worker: Arc>, + pub tokenizer: Option>, + pub generation: Option>, + pub response_history: Arc>, +} + +impl Default for AppState { + fn default() -> Self { + Self { + queue_timeout: None, + lifecycle: Default::default(), + api_key: None, + model: None, + worker: Arc::new(RwLock::new(WorkerStatus::default())), + tokenizer: None, + generation: None, + response_history: Arc::new(RwLock::new(responses::ResponseHistory::default())), + } + } +} + +#[derive(Serialize)] +struct HealthResponse { + status: &'static str, +} + +#[derive(Serialize)] +struct StatusResponse { + service: &'static str, + server_pid: u32, + model: Option, + version: &'static str, + worker: WorkerState, + ready: bool, + max_context: Option, +} + +pub fn router(state: AppState) -> Router { + Router::new() + .route("/health", get(health)) + .route("/ready", get(ready)) + .route("/status", get(status)) + .route("/metrics", get(metrics)) + .route("/v1/models", get(crate::models_api::list)) + .route("/v1/models/{id}", get(crate::models_api::retrieve)) + .route( + "/v1/responses", + post(responses::create).layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )), + ) + .route( + "/v1/responses/input_tokens", + post(responses::count_input_tokens).layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )), + ) + .route( + "/v1/chat/completions", + post(crate::chat::create).layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )), + ) + .route( + "/v1/messages/count_tokens", + post(crate::messages::count_tokens) + .layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )) + .layer(middleware::from_fn(crate::messages::protocol)), + ) + .route( + "/v1/messages", + post(crate::messages::create) + .layer(middleware::from_fn_with_state( + state.lifecycle.clone(), + crate::lifecycle::admit, + )) + .layer(middleware::from_fn(crate::messages::protocol)), + ) + .route("/admin/lifecycle", get(lifecycle_status)) + .route( + "/v1/responses/{id}", + get(responses::retrieve).delete(responses::delete), + ) + .route( + "/v1/responses/{id}/input_items", + get(responses::input_items), + ) + .route("/admin/drain", post(drain)) + .route("/admin/resume", post(resume)) + .layer(DefaultBodyLimit::max(16 * 1024 * 1024)) + .layer(middleware::from_fn_with_state( + state.api_key.clone(), + crate::auth::authorize, + )) + .with_state(state) +} + +async fn health() -> Json { + Json(HealthResponse { status: "ok" }) +} + +async fn lifecycle_status(State(state): State) -> Json { + let worker = *state.worker.read().await; + let lifecycle = state.lifecycle.snapshot(); + let drained = lifecycle.draining + && lifecycle.requests_in_flight == 0 + && lifecycle.generation_jobs == 0 + && worker.metrics.active_since.is_none() + && matches!(worker.state, WorkerState::Ready | WorkerState::Unconfigured); + Json( + serde_json::json!({"service":"strata-control", "server_pid":std::process::id(), "model":state.model, + "draining":lifecycle.draining, + "shutting_down":lifecycle.shutting_down, + "max_in_flight_requests":lifecycle.max_in_flight_requests, + "available_request_slots":lifecycle.max_in_flight_requests.saturating_sub(lifecycle.requests_in_flight), + "requests_in_flight":lifecycle.requests_in_flight, "generation_jobs":lifecycle.generation_jobs, + "drained":drained, "worker":worker.state}), + ) +} + +fn lifecycle_precondition(headers: &HeaderMap) -> Option { + let mut values = headers.get_all("x-strata-expected-pid").iter(); + let value = values.next()?; + let pid = value + .to_str() + .ok() + .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + .and_then(|s| s.parse::().ok()) + .filter(|n| *n > 0); + if values.next().is_some() || pid.is_none() { + return Some((StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"code":"invalid_expected_pid","message":"expected PID must be one positive integer"}}))).into_response()); + } + if pid != Some(std::process::id()) { + return Some((StatusCode::CONFLICT, Json(serde_json::json!({"error":{"code":"process_identity_changed","message":"native process no longer matches expected PID; admission unchanged"}}))).into_response()); + } + None +} + +async fn drain(State(state): State, headers: HeaderMap) -> Response { + if let Some(response) = lifecycle_precondition(&headers) { + return response; + } + state.lifecycle.set_draining(true); + lifecycle_status(State(state)).await.into_response() +} + +async fn resume(State(state): State, headers: HeaderMap) -> Response { + if let Some(response) = lifecycle_precondition(&headers) { + return response; + } + state.lifecycle.set_draining(false); + lifecycle_status(State(state)).await.into_response() +} + +async fn metrics(State(state): State) -> Json { + let worker = *state.worker.read().await; + let generation = worker.metrics; + let queue_capacity = state.generation.as_ref().map(mpsc::Sender::max_capacity); + let queue_used = state + .generation + .as_ref() + .map(|sender| sender.max_capacity() - sender.capacity()); + Json(serde_json::json!({ + "schema_version": 1, + "scope": "control_plane_process", + "model": state.model, + "worker": worker.state, + "active": generation.active_since.is_some(), + "active_elapsed_ms": generation.active_since.map(|start| start.elapsed().as_millis().min(u64::MAX as u128) as u64), + "queue_capacity": queue_capacity, + "queue_used": queue_used, + "generation": generation, + "done_decode_tokens_per_second": crate::metrics::token_rate(generation.done_generated_tokens, generation.done_decode_ms), + })) +} + +async fn ready(State(state): State) -> (StatusCode, Json) { + let worker = *state.worker.read().await; + let inference_ready = worker.state == WorkerState::Ready + && state.tokenizer.is_some() + && state.generation.is_some() + && !state.lifecycle.snapshot().draining; + let code = if inference_ready { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + ( + code, + Json(status_body(worker, inference_ready, state.model)), + ) +} + +async fn status(State(state): State) -> Json { + let worker = *state.worker.read().await; + let inference_ready = worker.state == WorkerState::Ready + && state.tokenizer.is_some() + && state.generation.is_some() + && !state.lifecycle.snapshot().draining; + Json(status_body(worker, inference_ready, state.model)) +} + +fn status_body( + worker: WorkerStatus, + inference_ready: bool, + model: Option, +) -> StatusResponse { + StatusResponse { + service: "strata-control", + server_pid: std::process::id(), + model, + version: env!("CARGO_PKG_VERSION"), + worker: worker.state, + ready: inference_ready, + max_context: worker.max_context, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn conditional_admission_rejects_stale_or_ambiguous_pid_before_mutation() { + let state = AppState::default(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let client = reqwest::Client::new(); + for (path, initial) in [("drain", false), ("resume", true)] { + state.lifecycle.set_draining(initial); + for (value, status) in [ + ("0".to_string(), 400), + ("bad".into(), 400), + ((std::process::id() + 1).to_string(), 409), + ] { + let response = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", value) + .send() + .await + .unwrap(); + assert_eq!(response.status().as_u16(), status); + assert_eq!(state.lifecycle.snapshot().draining, initial); + } + let duplicate = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", std::process::id()) + .header("x-strata-expected-pid", std::process::id()) + .send() + .await + .unwrap(); + assert_eq!(duplicate.status(), StatusCode::BAD_REQUEST); + assert_eq!(state.lifecycle.snapshot().draining, initial); + let response = client + .post(format!("{url}/admin/{path}")) + .header("x-strata-expected-pid", std::process::id()) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let value: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(value["server_pid"], std::process::id()); + assert_eq!(value["service"], "strata-control"); + assert_eq!(value["draining"], !initial); + } + server.abort(); + let _ = server.await; + } + + #[tokio::test] + async fn drain_rejects_new_requests_before_json_parsing_and_resume_is_idempotent() { + let state = AppState::default(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let client = reqwest::Client::new(); + for _ in 0..2 { + let response = client + .post(format!("{url}/admin/drain")) + .send() + .await + .unwrap(); + let data: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(data["draining"], true); + assert_eq!(data["drained"], true); + } + let response = client + .post(format!("{url}/v1/responses")) + .header("content-type", "application/json") + .body("invalid json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert!(response.text().await.unwrap().contains("runtime_draining")); + assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0); + let job = state.lifecycle.generation(); + assert_eq!( + lifecycle_status(State(state.clone())).await.0["drained"], + false + ); + drop(job); + state.worker.write().await.state = WorkerState::Restarting; + assert_eq!( + lifecycle_status(State(state.clone())).await.0["drained"], + false + ); + for _ in 0..2 { + let response = client + .post(format!("{url}/admin/resume")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + } + let response = client + .post(format!("{url}/v1/responses")) + .header("content-type", "application/json") + .body("invalid json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let _ = response.text().await.unwrap(); + server.abort(); + } + + #[tokio::test] + async fn metrics_expose_activity_without_changing_discovery() { + let (sender, mut receiver) = mpsc::channel(2); + let state = AppState { + generation: Some(sender.clone()), + ..Default::default() + }; + let initial_status = serde_json::to_value(status(State(state.clone())).await.0).unwrap(); + let initial_metrics = metrics(State(state.clone())).await.0; + assert_eq!(initial_metrics["active"], false); + assert!(initial_metrics["done_decode_tokens_per_second"].is_null()); + let (result, _rx) = tokio::sync::oneshot::channel(); + sender + .send(GenerationCommand { + queue: None, + activity: None, + request: crate::wire::Generate { + token_ids: vec![10], + max_new: 1, + temperature: None, + top_p: None, + }, + result: crate::worker::GenerationResult::Buffered(result), + }) + .await + .unwrap(); + state.worker.write().await.metrics.start(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/metrics", listener.local_addr().unwrap()); + let router = router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let response = reqwest::get(url).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "application/json"); + let body: serde_json::Value = + serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(body["active"], true); + assert!(body["active_elapsed_ms"].is_u64()); + assert_eq!(body["generation"]["started"], 1); + assert_eq!(body["queue_capacity"], 2); + assert_eq!(body["queue_used"], 1); + assert!(body["generation"].get("active_since").is_none()); + assert_eq!( + serde_json::to_value(status(State(state.clone())).await.0).unwrap(), + initial_status + ); + receiver.recv().await.unwrap(); + assert_eq!(metrics(State(state)).await.0["queue_used"], 0); + server.abort(); + } +} diff --git a/control-plane/src/asset_bundle.rs b/control-plane/src/asset_bundle.rs new file mode 100644 index 00000000..9b9f9064 --- /dev/null +++ b/control-plane/src/asset_bundle.rs @@ -0,0 +1,141 @@ +//! Immutable, manifest-pinned assets acquired before native serving starts. +use std::{ + error::Error, + fs::{self, File, OpenOptions}, + io, + path::{Component, Path, PathBuf}, +}; + +use serde::Deserialize; + +use crate::model; + +type Result = std::result::Result>; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AssetBundle { + pub manifest: PathBuf, + pub directory: PathBuf, +} + +pub fn validate(bundles: &[AssetBundle]) -> Result<()> { + if bundles.len() > 16 { + return Err("at most 16 asset bundles may be configured".into()); + } + for (index, bundle) in bundles.iter().enumerate() { + for path in [&bundle.manifest, &bundle.directory] { + if !path.is_absolute() + || path.file_name().is_none() + || path + .components() + .any(|part| matches!(part, Component::ParentDir)) + { + return Err("asset paths must be absolute, non-root paths without '..'".into()); + } + } + if bundles[..index].iter().any(|other| { + other.directory.starts_with(&bundle.directory) + || bundle.directory.starts_with(&other.directory) + }) { + return Err("asset bundle destinations must not overlap".into()); + } + } + Ok(()) +} + +/// Parse every manifest before mutation. Each destination is an immutable +/// versioned bundle: a mismatch is an error, never an implicit replacement. +pub async fn provision(bundles: &[AssetBundle]) -> Result<()> { + validate(bundles)?; + let mut manifests = Vec::with_capacity(bundles.len()); + for bundle in bundles { + manifests.push(model::Manifest::load(&bundle.manifest).await?); + } + for (bundle, manifest) in bundles.iter().zip(manifests) { + ensure(bundle, &manifest).await?; + } + Ok(()) +} + +async fn ensure(bundle: &AssetBundle, manifest: &model::Manifest) -> Result<()> { + let parent = bundle + .directory + .parent() + .ok_or("asset directory has no parent")?; + fs::create_dir_all(parent)?; + let name = bundle + .directory + .file_name() + .ok_or("asset directory has no name")?; + let sibling = |suffix: &str| { + let mut value = std::ffi::OsString::from("."); + value.push(name); + value.push(suffix); + parent.join(value) + }; + // Keep the lock inode after releasing it: unlinking could let two later + // preparers lock different inodes for the same destination. OS locks are + // released on process death, allowing interrupted downloads to resume. + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let lock = options.open(sibling(".strata-lock"))?; + if !lock.metadata()?.is_file() { + return Err("asset lock must be a regular file".into()); + } + lock.try_lock().map_err( + |_| "asset bundle is busy or cannot be locked; retry after preparation finishes", + )?; + if directory_exists(&bundle.directory)? { + return verify_bundle(manifest, &bundle.directory).await; + } + let stage = sibling(".strata-stage"); + if !directory_exists(&stage)? { + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&stage)?; + } + // On failure the private stage remains for resumable acquisition. It is + // never used by the worker and never replaces an existing bundle. + model::fetch(manifest, &stage).await?; + verify_bundle(manifest, &stage).await?; + File::open(&stage)?.sync_all()?; + if fs::symlink_metadata(&bundle.directory).is_ok() { + return Err("asset destination appeared during preparation; refusing to replace it".into()); + } + crate::immutable_directory::publish(&stage, &bundle.directory)?; + File::open(parent)?.sync_all()?; + Ok(()) +} + +fn directory_exists(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err("asset destination/stage must be a directory, not a symlink".into()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error.into()), + } +} + +async fn verify_bundle(manifest: &model::Manifest, directory: &Path) -> Result<()> { + // Extra files could come from a different interrupted manifest. Do not + // silently publish a mixed bundle or trust a completion marker alone. + for entry in fs::read_dir(directory)? { + let name = entry?.file_name(); + if !manifest.files.iter().any(|file| name == file.name.as_str()) { + return Err( + "asset bundle contains files absent from its manifest; use a new directory".into(), + ); + } + } + model::verify(manifest, directory).await +} diff --git a/control-plane/src/auth.rs b/control-plane/src/auth.rs new file mode 100644 index 00000000..c3d923da --- /dev/null +++ b/control-plane/src/auth.rs @@ -0,0 +1,238 @@ +//! Optional single-operator bearer authentication. Never format the credential. +use std::{fs::OpenOptions, io::Read, path::Path, sync::Arc}; + +use axum::{ + Json, + extract::{Request, State}, + http::{HeaderMap, StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +pub struct ApiKey([u8; 32]); + +impl ApiKey { + pub fn from_file(path: &Path) -> Result> { + Self::from_token(&read_token(path)?).map_err(Into::into) + } + + fn from_token(value: &str) -> Result { + if !(32..=512).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_graphic()) { + return Err("API key requires 32..512 printable ASCII bytes without whitespace"); + } + Ok(Self(Sha256::digest(value.as_bytes()).into())) + } + + fn accepts_messages(&self, headers: &HeaderMap) -> bool { + let mut values = headers.get_all("x-api-key").iter(); + let Some(value) = values.next() else { + return self.accepts(headers); + }; + if values.next().is_some() || headers.contains_key(header::AUTHORIZATION) { + return false; + } + let Ok(value) = value.to_str() else { + return false; + }; + let Ok(candidate) = Self::from_token(value) else { + return false; + }; + bool::from(self.0.ct_eq(&candidate.0)) + } + + fn accepts(&self, headers: &HeaderMap) -> bool { + let mut values = headers.get_all(header::AUTHORIZATION).iter(); + let Some(value) = values.next() else { + return false; + }; + if values.next().is_some() { + return false; + } + let Ok(value) = value.to_str() else { + return false; + }; + let Some((scheme, token)) = value.split_once(' ') else { + return false; + }; + if !scheme.eq_ignore_ascii_case("Bearer") { + return false; + } + let Ok(candidate) = Self::from_token(token) else { + return false; + }; + bool::from(self.0.ct_eq(&candidate.0)) + } +} + +// Client code needs the original token; keep file and syntax policy identical to serving. +pub(crate) fn read_token(path: &Path) -> Result> { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + let file = options.open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err("API key source must be a regular file".into()); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if metadata.permissions().mode() & 0o077 != 0 { + return Err( + "API key file must not grant group/other permissions (use chmod 600)".into(), + ); + } + } + let mut bytes = Vec::new(); + file.take(515).read_to_end(&mut bytes)?; + parse_token(&bytes) +} + +pub(crate) fn parse_token(bytes: &[u8]) -> Result> { + if bytes.len() > 514 { + return Err("API key file exceeds 514 bytes".into()); + } + let value = std::str::from_utf8(bytes) + .map_err(|_| "API key must contain printable ASCII")? + .trim_end_matches(['\r', '\n']); + ApiKey::from_token(value)?; + Ok(value.to_owned()) +} + +pub async fn authorize( + State(key): State>>, + request: Request, + next: Next, +) -> Response { + let messages = matches!( + request.uri().path(), + "/v1/messages" | "/v1/messages/count_tokens" + ); + if request.uri().path() != "/health" + && key.as_ref().is_some_and(|key| { + if messages { + !key.accepts_messages(request.headers()) + } else { + !key.accepts(request.headers()) + } + }) + { + return ( + StatusCode::UNAUTHORIZED, + [(header::WWW_AUTHENTICATE, "Bearer")], + Json(if messages { crate::messages::error_value(StatusCode::UNAUTHORIZED, "Invalid API key") } else { json!({"error":{"message":"Invalid API key","type":"authentication_error","code":"invalid_api_key"}}) }), + ).into_response(); + } + next.run(request).await +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: &str = "fixture-only-not-a-real-secret-0001"; + + #[test] + fn header_contract_rejects_ambiguous_or_invalid_credentials() { + let key = ApiKey::from_token(KEY).unwrap(); + let mut headers = HeaderMap::new(); + for value in [format!("Bearer {KEY}"), format!("bearer {KEY}")] { + headers.insert(header::AUTHORIZATION, value.parse().unwrap()); + assert!(key.accepts(&headers)); + } + for value in [ + format!("Basic {KEY}"), + format!("Bearer {KEY} "), + format!("Bearer {KEY}"), + "Bearer wrong".into(), + "Bearer fixture-only-not-a-real-secret-0002".into(), + ] { + headers.insert(header::AUTHORIZATION, value.parse().unwrap()); + assert!(!key.accepts(&headers)); + } + headers.insert( + header::AUTHORIZATION, + format!("Bearer {KEY}").parse().unwrap(), + ); + headers.append( + header::AUTHORIZATION, + format!("Bearer {KEY}").parse().unwrap(), + ); + assert!(!key.accepts(&headers)); + } + + #[tokio::test] + async fn protected_routes_fail_before_body_parsing_and_health_stays_public() { + let state = crate::app::AppState { + api_key: Some(Arc::new(ApiKey::from_token(KEY).unwrap())), + ..Default::default() + }; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = + tokio::spawn(async move { axum::serve(listener, crate::app::router(state)).await }); + let client = reqwest::Client::new(); + for path in [ + "/status", + "/metrics", + "/ready", + "/v1/responses", + "/admin/drain", + "/admin/resume", + "/admin/lifecycle", + "/unknown", + ] { + let response = client + .post(format!("{url}{path}")) + .body("not json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(response.headers()[header::WWW_AUTHENTICATE], "Bearer"); + assert!(!response.text().await.unwrap().contains(KEY)); + } + assert_eq!( + client + .get(format!("{url}/health")) + .send() + .await + .unwrap() + .status(), + StatusCode::OK + ); + let response = client + .get(format!("{url}/status")) + .bearer_auth(KEY) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert!(!response.text().await.unwrap().contains(KEY)); + let response = client + .post(format!("{url}/v1/responses")) + .bearer_auth(KEY) + .header(header::CONTENT_TYPE, "application/json") + .body("not json") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + server.abort(); + } + + #[test] + fn malformed_token_is_rejected_without_echoing_it() { + for token in ["short".to_owned(), "X".repeat(513), "X".repeat(32) + "\nY"] { + let error = ApiKey::from_token(&token).err().unwrap(); + assert!(!error.contains(&token)); + } + } +} diff --git a/control-plane/src/bin/replay-responses.rs b/control-plane/src/bin/replay-responses.rs new file mode 100644 index 00000000..4f0492cd --- /dev/null +++ b/control-plane/src/bin/replay-responses.rs @@ -0,0 +1,64 @@ +use std::{env, fs, process::ExitCode}; + +use serde::Deserialize; +use strata_control::responses::{CreateRequest, OutputItem, ResponseTrace, Usage}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Fixture { + request: CreateRequest, + items: Vec, + usage: Usage, + id: String, + created_at: u64, + completed_at: u64, +} + +fn main() -> ExitCode { + if let Err(error) = run() { + eprintln!("replay-responses: {error}"); + return ExitCode::FAILURE; + } + ExitCode::SUCCESS +} + +fn run() -> Result<(), String> { + let mut args = env::args().skip(1); + let first = args + .next() + .ok_or("usage: replay-responses [--sse] FIXTURE.json")?; + let (sse, path) = if first == "--sse" { + ( + true, + args.next() + .ok_or("usage: replay-responses [--sse] FIXTURE.json")?, + ) + } else { + (false, first) + }; + if args.next().is_some() { + return Err("usage: replay-responses [--sse] FIXTURE.json".to_owned()); + } + let source = fs::read_to_string(&path).map_err(|error| format!("{path}: {error}"))?; + let fixture: Fixture = serde_json::from_str(&source) + .map_err(|error| format!("invalid fixture {path}: {error}"))?; + let trace = ResponseTrace::build( + &fixture.request, + &fixture.items, + fixture.usage, + &fixture.id, + fixture.created_at, + fixture.completed_at, + )?; + if sse { + for frame in trace.sse_frames() { + print!("{frame}"); + } + } else { + println!( + "{}", + serde_json::to_string_pretty(&trace.response).map_err(|error| error.to_string())? + ); + } + Ok(()) +} diff --git a/control-plane/src/chat.rs b/control-plane/src/chat.rs new file mode 100644 index 00000000..a912e6fc --- /dev/null +++ b/control-plane/src/chat.rs @@ -0,0 +1,579 @@ +//! Stateless, one-choice Chat Completions adapter over native Responses. +use crate::{app::AppState, responses}; +use axum::{ + Json, + body::{Body, to_bytes}, + extract::{State, rejection::JsonRejection}, + http::StatusCode, + response::{IntoResponse, Response, Sse, sse::Event}, +}; +use futures_core::Stream; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{ + convert::Infallible, + pin::Pin, + task::{Context, Poll}, +}; +use tokio::sync::mpsc; + +use crate::native_events::{MAX_EVENT, NativeEvents}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + model: String, + messages: Vec, + #[serde(default)] + stream: bool, + stream_options: Option, + n: Option, + max_tokens: Option, + max_completion_tokens: Option, + temperature: Option, + top_p: Option, + #[serde(default)] + tools: Vec, + tool_choice: Option, + parallel_tool_calls: Option, + response_format: Option, + reasoning_effort: Option, + store: Option, + stop: Option, + logprobs: Option, + frequency_penalty: Option, + presence_penalty: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StreamOptions { + include_usage: Option, + include_obfuscation: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Message { + role: String, + content: Option, + tool_calls: Option>, + tool_call_id: Option, + refusal: Option, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Call { + id: String, + #[serde(rename = "type")] + kind: String, + function: CallFunction, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CallFunction { + name: String, + arguments: String, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Tool { + #[serde(rename = "type")] + kind: String, + function: Function, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Function { + name: String, + description: Option, + parameters: Option, + strict: Option, +} + +type Invalid = (&'static str, &'static str); +fn invalid(param: &'static str, message: &'static str) -> Invalid { + (param, message) +} +fn content(value: Option) -> Result, Invalid> { + match value { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s)), + Some(Value::Array(parts)) => { + let mut text = String::new(); + for part in parts { + let object = part + .as_object() + .ok_or(invalid("messages", "content must contain text parts"))?; + if object.len() != 2 || part["type"] != "text" { + return Err(invalid("messages", "only text content parts are supported")); + } + text.push_str( + part["text"] + .as_str() + .ok_or(invalid("messages", "text part needs a string"))?, + ); + } + Ok(Some(text)) + } + _ => Err(invalid("messages", "content must be text or text parts")), + } +} + +impl Request { + fn into_responses(self) -> Result<(Value, bool, bool), Invalid> { + if self.n.is_some_and(|n| n != 1) { + return Err(invalid("n", "only n=1 is supported")); + } + if self.max_tokens.is_some() && self.max_completion_tokens.is_some() { + return Err(invalid( + "max_completion_tokens", + "specify only one output token limit", + )); + } + if self + .reasoning_effort + .as_deref() + .is_some_and(|e| e != "none") + { + return Err(invalid( + "reasoning_effort", + "this Chat subset supports only reasoning_effort=none", + )); + } + if self.store == Some(true) { + return Err(invalid( + "store", + "stored Chat completions are not supported", + )); + } + if self.stop.is_some() { + return Err(invalid("stop", "custom stop sequences are not supported")); + } + if self.logprobs == Some(true) { + return Err(invalid("logprobs", "log probabilities are not supported")); + } + if self.frequency_penalty.is_some_and(|x| x != 0.0) + || self.presence_penalty.is_some_and(|x| x != 0.0) + { + return Err(invalid( + "frequency_penalty", + "nonzero frequency/presence penalties are not supported", + )); + } + if !self.stream && self.stream_options.is_some() { + return Err(invalid( + "stream_options", + "stream_options requires stream=true", + )); + } + if self + .stream_options + .as_ref() + .is_some_and(|s| s.include_obfuscation == Some(true)) + { + return Err(invalid( + "stream_options", + "stream obfuscation is not supported", + )); + } + let include_usage = self + .stream_options + .is_some_and(|s| s.include_usage == Some(true)); + let mut input = Vec::new(); + for message in self.messages { + if message.refusal.is_some() { + return Err(invalid("messages", "refusal content is not supported")); + } + let text = content(message.content)?; + match message.role.as_str() { + "system" | "developer" | "user" | "assistant" => { + if message.tool_call_id.is_some() + || (message.role != "assistant" && message.tool_calls.is_some()) + { + return Err(invalid( + "messages", + "tool_calls belongs to assistant; tool_call_id belongs to tool", + )); + } + let calls = message.tool_calls.unwrap_or_default(); + if text.is_none() && calls.is_empty() { + return Err(invalid( + "messages", + "message needs text or assistant tool calls", + )); + } + if let Some(text) = text { + input.push(json!({"role":message.role,"content":text})); + } + for call in calls { + if call.kind != "function" { + return Err(invalid( + "messages", + "only function tool calls are supported", + )); + } + input.push(json!({"type":"function_call","call_id":call.id,"name":call.function.name,"arguments":call.function.arguments})); + } + } + "tool" => { + if message.tool_calls.is_some() { + return Err(invalid("messages", "tool result cannot declare tool calls")); + } + input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.ok_or(invalid("messages", "tool result needs text"))?})); + } + _ => return Err(invalid("messages", "unsupported message role")), + } + } + let mut tools = Vec::new(); + for tool in self.tools { + if tool.kind != "function" { + return Err(invalid("tools", "only function tools are supported")); + } + let f = tool.function; + let mut value = json!({"type":"function","name":f.name,"parameters":f.parameters.unwrap_or(json!({"type":"object","properties":{}}))}); + if let Some(description) = f.description { + value["description"] = json!(description); + } + if let Some(strict) = f.strict { + value["strict"] = json!(strict); + } + tools.push(value); + } + let choice = match self.tool_choice { + Some(Value::Object(value)) => { + if value.len() != 2 || value.get("type") != Some(&json!("function")) { + return Err(invalid("tool_choice", "unsupported tool choice")); + } + let function = value + .get("function") + .and_then(Value::as_object) + .ok_or(invalid("tool_choice", "forced function needs a name"))?; + if function.len() != 1 { + return Err(invalid("tool_choice", "forced function accepts only name")); + } + Some( + json!({"type":"function","name":function.get("name").and_then(Value::as_str).ok_or(invalid("tool_choice", "forced function needs a name"))?}), + ) + } + choice => choice, + }; + let format = match self.response_format { + Some(Value::Object(mut format)) + if format.get("type") == Some(&json!("json_schema")) => + { + if format.len() != 2 { + return Err(invalid( + "response_format", + "json_schema format requires a json_schema object", + )); + } + let mut schema = format + .remove("json_schema") + .and_then(|v| v.as_object().cloned()) + .ok_or(invalid( + "response_format", + "json_schema format requires a json_schema object", + ))?; + if schema + .keys() + .any(|k| !matches!(k.as_str(), "name" | "schema" | "strict")) + { + return Err(invalid( + "response_format", + "supported json_schema fields are name, schema and strict", + )); + } + schema.insert("type".into(), json!("json_schema")); + Some(Value::Object(schema)) + } + Some(value) => { + if !value.as_object().is_some_and(|o| o.len() == 1) + || !matches!(value["type"].as_str(), Some("text" | "json_object")) + { + return Err(invalid("response_format", "unsupported response format")); + } + Some(value) + } + None => None, + }; + let mut request = json!({"model":self.model,"input":input,"stream":self.stream,"store":false, + "reasoning":{"effort":"none"},"tools":tools}); + for (key, value) in [ + ( + "max_output_tokens", + self.max_completion_tokens + .or(self.max_tokens) + .map(|v| json!(v)), + ), + ("temperature", self.temperature.map(|v| json!(v))), + ("top_p", self.top_p.map(|v| json!(v))), + ( + "parallel_tool_calls", + self.parallel_tool_calls.map(|v| json!(v)), + ), + ("tool_choice", choice), + ] { + if let Some(value) = value { + request[key] = value; + } + } + if let Some(format) = format { + request["text"] = json!({"format":format}); + } + Ok((request, self.stream, include_usage)) + } +} + +fn usage(response: &Value) -> Value { + let u = &response["usage"]; + json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"], + "prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]}, + "completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}}) +} +fn call(item: &Value) -> Value { + json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}}) +} +fn finish(response: &Value) -> &'static str { + if response["status"] == "incomplete" { + "length" + } else if response["output"] + .as_array() + .is_some_and(|items| items.iter().any(|i| i["type"] == "function_call")) + { + "tool_calls" + } else { + "stop" + } +} +fn identity(response: &Value, object: &str) -> Value { + json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object, + "created":response["created_at"],"model":response["model"]}) +} +fn completion(response: &Value) -> Value { + let mut text = String::new(); + let mut calls = Vec::new(); + if let Some(items) = response["output"].as_array() { + for item in items { + if item["type"] == "function_call" { + calls.push(call(item)); + } + if item["type"] == "message" + && let Some(parts) = item["content"].as_array() + { + for part in parts { + if part["type"] == "output_text" { + text.push_str(part["text"].as_str().unwrap_or("")); + } + } + } + } + } + let mut message = json!({"role":"assistant","content":if text.is_empty() && !calls.is_empty() {Value::Null} else {json!(text)},"refusal":null}); + if !calls.is_empty() { + message["tool_calls"] = json!(calls); + } + let mut value = identity(response, "chat.completion"); + value["choices"] = + json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]); + value["usage"] = usage(response); + value +} +fn error(status: StatusCode, code: &str, param: Option<&str>, message: &str) -> Response { + (status,Json(json!({"error":{"type":if status.is_server_error(){"server_error"}else{"invalid_request_error"},"code":code,"param":param,"message":message}}))).into_response() +} + +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let Json(body) = match body { + Ok(body) => body, + Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()), + }; + let request: Request = match serde_json::from_value(body) { + Ok(r) => r, + Err(e) => { + return error( + StatusCode::BAD_REQUEST, + "invalid_request", + None, + &e.to_string(), + ); + } + }; + let (request, stream, include_usage) = match request.into_responses() { + Ok(r) => r, + Err((p, m)) => { + return error( + StatusCode::BAD_REQUEST, + "unsupported_chat_feature", + Some(p), + m, + ); + } + }; + let response = responses::create(State(state), Ok(Json(request))).await; + if stream && response.status().is_success() { + return stream_response(response.into_body(), include_usage); + } + let status = response.status(); + let bytes = match to_bytes(response.into_body(), MAX_EVENT).await { + Ok(b) => b, + Err(_) => { + return error( + StatusCode::BAD_GATEWAY, + "response_too_large", + None, + "native response could not be read within the adapter limit", + ); + } + }; + let mut value: Value = match serde_json::from_slice(&bytes) { + Ok(v) => v, + Err(_) => { + return error( + StatusCode::BAD_GATEWAY, + "invalid_native_response", + None, + "native response was not JSON", + ); + } + }; + if !status.is_success() { + if let Some(param) = value["error"]["param"].as_str() { + let mapped = match param { + "input" => "messages", + "max_output_tokens" => "max_completion_tokens", + "text" => "response_format", + p => p, + }; + value["error"]["param"] = json!(mapped); + } + return (status, Json(value)).into_response(); + } + Json(completion(&value)).into_response() +} + +struct Events(mpsc::Receiver); +impl Stream for Events { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.0.poll_recv(cx).map(|v| v.map(Ok)) + } +} +async fn send(sender: &mpsc::Sender, value: Value) -> Result<(), &'static str> { + sender + .send(Event::default().data(value.to_string())) + .await + .map_err(|_| "client disconnected") +} +fn chunk(base: &Value, delta: Value, reason: Value, include_usage: bool) -> Value { + let mut v = base.clone(); + v["choices"] = json!([{"index":0,"delta":delta,"finish_reason":reason,"logprobs":null}]); + if include_usage { + v["usage"] = Value::Null; + } + v +} +async fn adapt( + body: &mut Body, + sender: &mpsc::Sender, + include_usage: bool, +) -> Result<(), &'static str> { + let mut reader = NativeEvents::new(body); + let mut base = None; + let mut calls = 0; + loop { + let event = + tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? }; + match event["type"].as_str() { + Some("response.created") => { + let value = identity(&event["response"], "chat.completion.chunk"); + send( + sender, + chunk( + &value, + json!({"role":"assistant","content":""}), + Value::Null, + include_usage, + ), + ) + .await?; + base = Some(value); + } + Some("response.output_text.delta") => { + send( + sender, + chunk( + base.as_ref().ok_or("missing stream identity")?, + json!({"content":event["delta"]}), + Value::Null, + include_usage, + ), + ) + .await?; + } + Some("response.output_item.done") if event["item"]["type"] == "function_call" => { + let mut item = call(&event["item"]); + item["index"] = json!(calls); + calls += 1; + send( + sender, + chunk( + base.as_ref().ok_or("missing stream identity")?, + json!({"tool_calls":[item]}), + Value::Null, + include_usage, + ), + ) + .await?; + } + Some("response.completed" | "response.incomplete") => { + let base = base.as_ref().ok_or("missing stream identity")?; + send( + sender, + chunk( + base, + json!({}), + json!(finish(&event["response"])), + include_usage, + ), + ) + .await?; + if include_usage { + let mut v = base.clone(); + v["choices"] = json!([]); + v["usage"] = usage(&event["response"]); + send(sender, v).await?; + } + sender + .send(Event::default().data("[DONE]")) + .await + .map_err(|_| "client disconnected")?; + return Ok(()); + } + Some("response.failed") => { + send(sender, json!({"error":event["response"]["error"]})).await?; + sender + .send(Event::default().data("[DONE]")) + .await + .map_err(|_| "client disconnected")?; + return Ok(()); + } + _ => {} + } + } +} +fn stream_response(mut body: Body, include_usage: bool) -> Response { + let (sender, received) = mpsc::channel(8); + tokio::spawn(async move { + let outcome = adapt(&mut body, &sender, include_usage).await; + drop(body); // Release the native receiver before reporting an adapter failure. + if let Err(message) = outcome { + let _=send(&sender,json!({"error":{"type":"server_error","code":"chat_stream_failed","message":message}})).await; + let _ = sender.send(Event::default().data("[DONE]")).await; + } + }); + Sse::new(Events(received)) + .keep_alive(crate::native_events::keep_alive()) + .into_response() +} diff --git a/control-plane/src/config.rs b/control-plane/src/config.rs new file mode 100644 index 00000000..f6d9e460 --- /dev/null +++ b/control-plane/src/config.rs @@ -0,0 +1,367 @@ +use std::{ + env, + ffi::OsString, + fs, + net::SocketAddr, + path::{Path, PathBuf}, + time::Duration, +}; + +use serde::Deserialize; + +use crate::worker::WorkerConfig; + +pub struct Config { + pub queue_timeout: Option, + pub response_history_dir: Option, + pub mtp_pack: Option, + pub assets: Vec, + pub native_model: Option, + pub gpu_requirement: Option, + pub cuda_memory: Option, + host_checked: bool, + pub engine_probe: bool, + pub shutdown_grace: Duration, + pub max_in_flight_requests: usize, + pub api_key: Option>, + pub bind: SocketAddr, + pub model: Option, + pub worker: Option, + pub tokenizer_dir: Option, +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FileConfig { + queue_timeout_s: Option, + mtp_pack: Option, + response_history_dir: Option, + #[serde(default)] + assets: Vec, + native_model: Option, + gpu_requirement: Option, + cuda_memory: Option, + #[serde(default)] + engine_probe: bool, + shutdown_grace_s: Option, + max_in_flight_requests: Option, + api_key_file: Option, + bind: Option, + model: Option, + engine: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct FileEngine { + executable: String, + #[serde(default)] + args: Vec, + startup_timeout_s: Option, + generation_timeout_s: Option, + max_restarts: Option, + tokenizer_dir: Option, +} + +impl Config { + pub fn load() -> Result> { + Self::load_with_path(None) + } + + /// An explicit CLI config path takes precedence over STRATA_CONFIG. + pub fn load_with_path(path: Option<&Path>) -> Result> { + let file = match path + .map(|p| p.as_os_str().to_owned()) + .or_else(|| env::var_os("STRATA_CONFIG")) + { + Some(path) => { + let path = PathBuf::from(path); + serde_json::from_str::(&fs::read_to_string(path)?)? + } + None => FileConfig::default(), + }; + + crate::asset_bundle::validate(&file.assets)?; + if let Some(native) = &file.native_model { + native.validate(&file.assets)?; + } + let bind: SocketAddr = optional_env("STRATA_BIND")? + .or(file.bind) + .unwrap_or_else(|| "127.0.0.1:8081".to_owned()) + .parse()?; + + let max_in_flight_requests = optional_env("STRATA_MAX_IN_FLIGHT_REQUESTS")? + .map(|value| value.parse::()) + .transpose()? + .or(file.max_in_flight_requests) + .unwrap_or(crate::lifecycle::DEFAULT_MAX_IN_FLIGHT_REQUESTS); + crate::lifecycle::validate_capacity(max_in_flight_requests)?; + + let queue_timeout_s = optional_env("STRATA_QUEUE_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()? + .or(file.queue_timeout_s); + if queue_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("queue_timeout_s must be between 1 and 86400 when configured".into()); + } + + let shutdown_grace_s = optional_env("STRATA_SHUTDOWN_GRACE_S")? + .map(|value| value.parse::()) + .transpose()? + .or(file.shutdown_grace_s) + .unwrap_or(0); + if shutdown_grace_s > 20 { + return Err("shutdown_grace_s must be between 0 and 20".into()); + } + + let executable = env::var_os("STRATA_ENGINE_EXE").or_else(|| { + file.engine + .as_ref() + .map(|engine| OsString::from(&engine.executable)) + }); + let args_override = optional_env("STRATA_ENGINE_ARGS_JSON")? + .map(|value| serde_json::from_str::>(&value)) + .transpose()?; + let timeout_override = optional_env("STRATA_STARTUP_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()?; + let configured_args = file.engine.as_ref().map(|engine| engine.args.clone()); + let args = args_override.or(configured_args).unwrap_or_default(); + let startup_timeout_s = timeout_override + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.startup_timeout_s) + }) + .unwrap_or(600); + + if !(1..=3600).contains(&startup_timeout_s) { + return Err("startup_timeout_s must be between 1 and 3600".into()); + } + let max_restarts = optional_env("STRATA_MAX_WORKER_RESTARTS")? + .map(|value| value.parse::()) + .transpose()? + .or_else(|| file.engine.as_ref().and_then(|engine| engine.max_restarts)) + .unwrap_or(3); + if max_restarts > 3 { + return Err("max_restarts must be between 0 and 3".into()); + } + let generation_timeout_s = optional_env("STRATA_GENERATION_TIMEOUT_S")? + .map(|value| value.parse::()) + .transpose()? + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.generation_timeout_s) + }); + if generation_timeout_s.is_some_and(|seconds| !(1..=86400).contains(&seconds)) { + return Err("generation_timeout_s must be between 1 and 86400".into()); + } + let worker = match executable { + Some(executable) if !executable.is_empty() => Some(WorkerConfig { + executable, + cuda_memory: None, + args, + startup_timeout: Duration::from_secs(startup_timeout_s), + generation_timeout: generation_timeout_s.map(Duration::from_secs), + max_restarts, + }), + Some(_) => return Err("engine executable cannot be empty".into()), + None if !args.is_empty() => return Err("engine args require an executable".into()), + None => None, + }; + let mut tokenizer_dir = env::var_os("STRATA_TOKENIZER_DIR") + .map(PathBuf::from) + .or_else(|| { + file.engine + .as_ref() + .and_then(|engine| engine.tokenizer_dir.clone()) + }); + if let Some(native) = &file.native_model { + let worker = worker + .as_ref() + .ok_or("native_model requires an engine executable")?; + if tokenizer_dir.is_some() + || worker.args.iter().any(|arg| { + ["--pack", "--native", "--gguf"] + .iter() + .any(|key| arg == key || arg.starts_with(&format!("{key}="))) + }) + { + return Err("native_model owns pack/source/tokenizer settings; remove conflicting overrides".into()); + } + tokenizer_dir = Some(native.output.join("tokenizer")); + } + if worker.is_none() && tokenizer_dir.is_some() { + return Err("tokenizer_dir requires an engine executable".into()); + } + if worker.is_none() && file.gpu_requirement.is_some() { + return Err("gpu_requirement requires an engine executable".into()); + } + if let Some(policy) = file.cuda_memory { + policy.validate()?; + if file.gpu_requirement.is_none() { + return Err("cuda_memory requires an explicit gpu_requirement".into()); + } + } + if worker.is_none() && file.engine_probe { + return Err("engine_probe requires an engine executable".into()); + } + if let Some(mtp) = &file.mtp_pack { + let worker = worker + .as_ref() + .ok_or("mtp_pack requires an engine executable")?; + if !file.assets.iter().any(|asset| &asset.directory == mtp) { + return Err("mtp_pack must exactly match a pinned assets bundle directory".into()); + } + if mtp.to_str().is_none() + || worker + .args + .iter() + .any(|arg| arg == "--mtp" || arg.starts_with("--mtp=")) + { + return Err( + "mtp_pack requires UTF-8 path and owns --mtp; remove conflicting engine args" + .into(), + ); + } + } + let model = optional_env("STRATA_MODEL_ID")?.or(file.model); + if model.as_ref().is_some_and(|id| { + id.is_empty() + || id.len() > 180 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + }) { + return Err( + "model ID requires 1..180 ASCII letters, digits, dots, hyphens or underscores" + .into(), + ); + } + let api_key = env::var_os("STRATA_API_KEY_FILE") + .map(PathBuf::from) + .or(file.api_key_file) + .map(|path| crate::auth::ApiKey::from_file(&path).map(std::sync::Arc::new)) + .transpose()?; + let response_history_dir = env::var_os("STRATA_RESPONSE_HISTORY_DIR") + .map(PathBuf::from) + .or(file.response_history_dir); + if response_history_dir.as_ref().is_some_and(|p| { + !p.is_absolute() + || p.file_name().is_none() + || p.components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + }) { + return Err( + "response_history_dir must be an absolute non-root path without '..'".into(), + ); + } + Ok(Self { + mtp_pack: file.mtp_pack, + response_history_dir, + assets: file.assets, + native_model: file.native_model, + gpu_requirement: file.gpu_requirement, + cuda_memory: file.cuda_memory, + host_checked: false, + engine_probe: file.engine_probe, + shutdown_grace: Duration::from_secs(shutdown_grace_s), + queue_timeout: queue_timeout_s.map(Duration::from_secs), + max_in_flight_requests, + api_key, + bind, + model, + worker, + tokenizer_dir, + }) + } + + /// Complete acquisition/preparation before the listener or worker starts. + pub async fn provision(&mut self) -> Result<(), Box> { + self.check_host().await?; + self.prepare_assets().await + } + + /// Prepare a switch target while the previous runtime still owns GPU memory. + /// Serving must subsequently perform full host admission; never mark it checked here. + pub async fn prepare_for_switch(&mut self) -> Result<(), Box> { + if let Some(requirement) = self.gpu_requirement { + crate::doctor::check(requirement).await?; + } + self.prepare_assets().await + } + + async fn prepare_assets(&mut self) -> Result<(), Box> { + if self.engine_probe { + let worker = self + .worker + .as_ref() + .ok_or("engine_probe requires an engine executable")?; + crate::engine_probe::check(&worker.executable).await?; + } + // Parse all manifests before any acquisition, including the source model. + if let Some(native) = &self.native_model { + crate::model::Manifest::load(&native.manifest).await?; + } + crate::asset_bundle::provision(&self.assets).await?; + if let Some(mtp) = self.mtp_pack.clone() { + let checked = mtp.clone(); + tokio::task::spawn_blocking(move || crate::mtp_pack::check(&checked)).await??; + self.worker + .as_mut() + .ok_or("mtp_pack requires worker")? + .args + .extend([ + "--mtp".to_owned(), + mtp.to_str().ok_or("MTP path must be UTF-8")?.to_owned(), + ]); + } + if let Some(native) = &self.native_model { + let primary = native.ensure().await?; + let output = native.output.to_str().ok_or("pack path must be UTF-8")?; + let source = primary.to_str().ok_or("source path must be UTF-8")?; + self.worker + .as_mut() + .ok_or("native_model requires worker")? + .args + .extend([ + "--pack".to_owned(), + output.to_owned(), + "--native".to_owned(), + source.to_owned(), + ]); + } + Ok(()) + } + + /// Point-in-time driver policy check; never creates a CUDA context. + pub async fn check_host(&mut self) -> Result<(), Box> { + if let Some(requirement) = self.gpu_requirement + && !self.host_checked + { + crate::doctor::check(requirement).await?; + if let Some(policy) = self.cuda_memory { + let selected = policy.select().await?; + eprintln!( + "cuda_memory: selected {} for declared {} + {} MiB; allocation is not reserved", + selected.uuid, policy.required_mib, policy.reserve_mib + ); + self.worker + .as_mut() + .ok_or("cuda_memory requires worker")? + .cuda_memory = Some(selected); + } + self.host_checked = true; + } + Ok(()) + } +} + +fn optional_env(name: &str) -> Result, env::VarError> { + match env::var(name) { + Ok(value) => Ok(Some(value)), + Err(env::VarError::NotPresent) => Ok(None), + Err(error) => Err(error), + } +} diff --git a/control-plane/src/cuda_memory.rs b/control-plane/src/cuda_memory.rs new file mode 100644 index 00000000..bb1bcdc3 --- /dev/null +++ b/control-plane/src/cuda_memory.rs @@ -0,0 +1,225 @@ +//! Declared-budget admission only: no allocation, model sizing or CUDA context. +use serde::{Deserialize, Serialize}; +use std::{collections::HashSet, process::Stdio, time::Duration}; +use tokio::{io::AsyncReadExt, process::Command, time::timeout}; + +#[derive(Clone, Copy, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Policy { + pub required_mib: u64, + pub reserve_mib: u64, +} +impl Policy { + pub fn validate(self) -> Result { + if self.required_mib == 0 { + return Err("cuda_memory.required_mib must be positive"); + } + self.required_mib + .checked_add(self.reserve_mib) + .ok_or("cuda_memory budget overflow") + } + pub async fn select(self) -> Result { + self.validate()?; + let visible = std::env::var("CUDA_VISIBLE_DEVICES") + .map(Some) + .or_else(|e| match e { + std::env::VarError::NotPresent => Ok(None), + _ => Err("CUDA_VISIBLE_DEVICES must be UTF-8".to_owned()), + })?; + let allowed = visibility(visible.as_deref())?; + let devices = inventory().await?; + choose(self, devices, allowed.as_deref()) + } +} +#[derive(Clone)] +pub struct Selection { + pub uuid: String, + pub policy: Policy, +} +impl Selection { + pub async fn recheck(&self) -> Result<(), String> { + let devices = inventory().await?; + choose(self.policy, devices, Some(std::slice::from_ref(&self.uuid))).map(|_| ()) + } +} +struct Device { + uuid: String, + free: u64, + eligible: bool, +} +fn uuid_valid(uuid: &str) -> bool { + uuid.len() == 40 + && uuid.starts_with("GPU-") + && uuid[4..].bytes().enumerate().all(|(i, b)| { + if [8, 13, 18, 23].contains(&i) { + b == b'-' + } else { + b.is_ascii_hexdigit() + } + }) +} +fn visibility(value: Option<&str>) -> Result>, String> { + let Some(value) = value else { return Ok(None) }; + if value.is_empty() { + return Ok(Some(Vec::new())); + } + let ids: Vec<_> = value.split(',').map(str::to_owned).collect(); + if ids.iter().any(|id| !uuid_valid(id)) || ids.iter().collect::>().len() != ids.len() + { + return Err("cuda_memory requires CUDA_VISIBLE_DEVICES unset or a comma-separated list of full GPU UUIDs; ordinal, abbreviated and MIG identifiers are unsupported".into()); + } + Ok(Some(ids)) +} +fn parse(text: &str) -> Result, String> { + let mut ids = HashSet::new(); + let mut devices = Vec::new(); + for line in text.lines() { + let v: Vec<_> = line.split(',').map(str::trim).collect(); + if v.len() != 4 || !uuid_valid(v[0]) || !ids.insert(v[0]) { + return Err("malformed or duplicate GPU inventory".into()); + } + let total: u64 = v[1].parse().map_err(|_| "invalid GPU total memory")?; + let free: u64 = v[2].parse().map_err(|_| "invalid GPU free memory")?; + if total == 0 || free > total { + return Err("inconsistent GPU memory inventory".into()); + } + let eligible = match v[3] { + "Disabled" | "[N/A]" => true, + "Enabled" => false, + _ => return Err("unknown GPU MIG mode".into()), + }; + devices.push(Device { + uuid: v[0].to_owned(), + free, + eligible, + }); + } + if devices.is_empty() { + return Err("GPU inventory is empty".into()); + } + Ok(devices) +} +fn choose( + policy: Policy, + mut devices: Vec, + allowed: Option<&[String]>, +) -> Result { + let needed = policy.validate()?; + devices.retain(|d| { + d.eligible && d.free >= needed && allowed.is_none_or(|ids| ids.contains(&d.uuid)) + }); + devices.sort_by(|a, b| b.free.cmp(&a.free).then(a.uuid.cmp(&b.uuid))); + let device = devices.into_iter().next().ok_or_else(|| format!("no visible non-MIG GPU has {needed} MiB free for cuda_memory; free capacity or select a qualified smaller profile"))?; + Ok(Selection { + uuid: device.uuid, + policy, + }) +} +async fn inventory() -> Result, String> { + if !cfg!(target_os = "linux") { + return Err("cuda_memory requires Linux".into()); + } + let mut child = Command::new("nvidia-smi") + .args([ + "--query-gpu=uuid,memory.total,memory.free,mig.mode.current", + "--format=csv,noheader,nounits", + ]) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .stdout(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "cannot query GPU memory; make nvidia-smi available")?; + let result = timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + child + .stdout + .take() + .ok_or("GPU query stdout unavailable")? + .take(8193) + .read_to_end(&mut bytes) + .await + .map_err(|_| "GPU query read failed")?; + if bytes.len() > 8192 { + return Err("GPU inventory exceeds 8 KiB".to_owned()); + } + if !child + .wait() + .await + .map_err(|_| "GPU query wait failed")? + .success() + { + return Err("GPU memory query failed".into()); + } + parse(std::str::from_utf8(&bytes).map_err(|_| "GPU inventory is not UTF-8")?) + }) + .await; + match result { + Ok(Ok(devices)) => Ok(devices), + result => { + let _ = child.kill().await; + Err(match result { + Ok(Err(e)) => e, + _ => "GPU memory query timed out after 5 seconds".into(), + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + const A: &str = "GPU-00000000-0000-0000-0000-000000000001"; + const B: &str = "GPU-00000000-0000-0000-0000-000000000002"; + #[test] + fn selection_respects_budget_visibility_and_mig() { + let p = Policy { + required_mib: 7000, + reserve_mib: 1000, + }; + let data = format!("{A},8192,8000,Disabled\n{B},16384,16000,[N/A]\n"); + assert_eq!(choose(p, parse(&data).unwrap(), None).unwrap().uuid, B); + assert_eq!( + choose(p, parse(&data).unwrap(), Some(&[A.into()])) + .unwrap() + .uuid, + A + ); + assert!(choose(p, parse(&data).unwrap(), Some(&[])).is_err()); + assert!(choose(p, parse(&format!("{A},8192,7999,Disabled")).unwrap(), None).is_err()); + assert!(choose(p, parse(&format!("{A},8192,8000,Enabled")).unwrap(), None).is_err()); + for s in ["0", "-1", "all", "GPU-123", "MIG-123", &format!("{A},{A}")] { + assert!(visibility(Some(s)).is_err()); + } + assert_eq!(visibility(Some(A)).unwrap(), Some(vec![A.into()])); + } + #[test] + fn rejects_untrusted_inventory_and_budget() { + for s in [ + String::new(), + format!("{A},1,2,Disabled"), + format!("{A},0,0,Disabled"), + format!("{A},8192,NaN,Disabled"), + format!("{A},8192,8192,Unknown"), + format!("{A},8192,8192,Disabled\n{A},8192,8192,Disabled"), + ] { + assert!(parse(&s).is_err()); + } + assert!( + Policy { + required_mib: 0, + reserve_mib: 1 + } + .validate() + .is_err() + ); + assert!( + Policy { + required_mib: u64::MAX, + reserve_mib: 1 + } + .validate() + .is_err() + ); + } +} diff --git a/control-plane/src/derived_iq3.rs b/control-plane/src/derived_iq3.rs new file mode 100644 index 00000000..858af7a4 --- /dev/null +++ b/control-plane/src/derived_iq3.rs @@ -0,0 +1,186 @@ +//! Experimental identity for a virtual F32 stream decoded from one all-IQ3_S +//! GGUF. The bytes are never materialized on disk. This is a preparation aid, +//! not an approval to serve a lossy KAR archive. + +use std::{ + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, +}; + +use sha2::{Digest, Sha256}; + +use crate::{gguf, iq3_s}; + +const BLOCKS_PER_BATCH: usize = 256; + +#[derive(Debug)] +pub struct TensorIdentity { + pub name: String, + pub derived_offset: u64, + pub derived_bytes: u64, + pub iq3_sha256: [u8; 32], + pub f32_sha256: [u8; 32], +} + +#[derive(Debug)] +pub struct Identity { + pub gguf_sha256: [u8; 32], + pub derived_sha256: [u8; 32], + pub derived_bytes: u64, + pub tensors: Vec, +} + +/// The virtual source is the concatenation, in GGUF tensor-directory order, +/// of each tensor's dequantized IEEE-754 little-endian F32 values. No GGUF +/// header, alignment padding, tensor name, or framing appears in that stream. +/// Tensor offsets and digests refer to this stream, never to IQ3_S file bytes. +pub fn fingerprint(path: &Path) -> Result { + let index = gguf::tensor_index(path).map_err(|error| error.to_string())?; + if index.tensors.is_empty() || index.tensors.iter().any(|tensor| tensor.kind != 21) { + return Err("IQ3 derivation currently requires a nonempty all-IQ3_S GGUF".into()); + } + let gguf_sha256 = hash_file(path)?; + let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut derived = Sha256::new(); + let mut derived_bytes = 0u64; + let mut tensors = Vec::with_capacity(index.tensors.len()); + let mut block_buffer = vec![0u8; BLOCKS_PER_BATCH * iq3_s::BLOCK_BYTES]; + for tensor in &index.tensors { + if !tensor.bytes.is_multiple_of(iq3_s::BLOCK_BYTES as u64) { + return Err(format!( + "{}: IQ3_S tensor is not block-aligned", + tensor.name + )); + } + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + source + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let offset = derived_bytes; + let mut iq3_hash = Sha256::new(); + let mut f32_hash = Sha256::new(); + let mut remaining = tensor.bytes; + while remaining != 0 { + let count = remaining.min(block_buffer.len() as u64) as usize; + source + .read_exact(&mut block_buffer[..count]) + .map_err(|error| error.to_string())?; + iq3_hash.update(&block_buffer[..count]); + for block in block_buffer[..count] + .as_chunks::<{ iq3_s::BLOCK_BYTES }>() + .0 + { + let values = iq3_s::decode_block(block)?; + for value in values { + let bytes = value.to_le_bytes(); + f32_hash.update(bytes); + derived.update(bytes); + } + } + let expanded = (count / iq3_s::BLOCK_BYTES) + .checked_mul(iq3_s::BLOCK_ELEMENTS * 4) + .ok_or("derived IQ3 byte count overflow")?; + derived_bytes = derived_bytes + .checked_add(expanded as u64) + .ok_or("derived IQ3 byte count overflow")?; + remaining -= count as u64; + } + tensors.push(TensorIdentity { + name: tensor.name.clone(), + derived_offset: offset, + derived_bytes: derived_bytes - offset, + iq3_sha256: iq3_hash.finalize().into(), + f32_sha256: f32_hash.finalize().into(), + }); + } + if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size + || hash_file(path)? != gguf_sha256 + { + return Err("GGUF source changed during IQ3 derivation".into()); + } + Ok(Identity { + gguf_sha256, + derived_sha256: derived.finalize().into(), + derived_bytes, + tensors, + }) +} + +fn hash_file(path: &Path) -> Result<[u8; 32], String> { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut digest = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = source + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(digest.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); + } + + #[test] + fn virtual_f32_identity_uses_tensor_directory_order_and_rejects_bad_source() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&2u64.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + for (name, offset) in [("second", 128u64), ("first", 0)] { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&256u64.to_le_bytes()); + gguf.extend_from_slice(&21u32.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let data_start = gguf.len(); + let mut first = [0u8; iq3_s::BLOCK_BYTES]; + first[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut second = first; + second[..2].copy_from_slice(&0x4000u16.to_le_bytes()); + gguf.extend_from_slice(&first); + gguf.resize(data_start + 128, 0); + gguf.extend_from_slice(&second); + let path = + std::env::temp_dir().join(format!("strata-iq3-identity-{}.gguf", std::process::id())); + fs::write(&path, &gguf).unwrap(); + let identity = fingerprint(&path).unwrap(); + assert_eq!( + identity.gguf_sha256.as_slice(), + Sha256::digest(&gguf).as_slice() + ); + assert_eq!(identity.derived_bytes, 2048); + assert_eq!(identity.tensors[0].name, "second"); + assert_eq!(identity.tensors[1].name, "first"); + assert_eq!(identity.tensors[1].derived_offset, 1024); + let mut expected = Sha256::new(); + expected.update([2.0f32.to_le_bytes(); 256].concat()); + expected.update([1.0f32.to_le_bytes(); 256].concat()); + assert_eq!( + identity.derived_sha256.as_slice(), + expected.finalize().as_slice() + ); + gguf[0] = b'X'; + fs::write(&path, gguf).unwrap(); + assert!(fingerprint(&path).is_err()); + fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/derived_mixed.rs b/control-plane/src/derived_mixed.rs new file mode 100644 index 00000000..5964bea6 --- /dev/null +++ b/control-plane/src/derived_mixed.rs @@ -0,0 +1,393 @@ +//! Versioned virtual F32 identity for a single GGUF containing IQ3_S plus +//! F32, F16, or BF16 tensors. Preparation only; no serving quality approval. + +use std::{ + collections::HashSet, + fs::File, + io::Read, + path::{Component, Path}, +}; + +use sha2::{Digest, Sha256}; + +use crate::{gguf, gguf_f32_stream, model::Manifest}; + +#[derive(Debug)] +pub struct TensorIdentity { + pub name: String, + pub source_kind: u32, + pub source_sha256: [u8; 32], + pub derived_offset: u64, + pub derived_bytes: u64, + pub f32_sha256: [u8; 32], +} + +#[derive(Debug)] +pub struct Identity { + pub gguf_sha256: [u8; 32], + pub derived_sha256: [u8; 32], + pub derived_bytes: u64, + pub tensors: Vec, +} + +#[derive(Debug)] +pub struct ShardIdentity { + pub name: String, + pub gguf_sha256: [u8; 32], + pub gguf_bytes: u64, + pub tensor_count: usize, +} + +#[derive(Debug)] +pub struct ShardedIdentity { + pub derived_sha256: [u8; 32], + pub derived_bytes: u64, + pub shards: Vec, + pub tensors: Vec, +} + +/// `strata-next/gguf-mixed-to-f32-le-v1`: concatenate tensor values in GGUF +/// directory order, each converted to little-endian IEEE F32. Preserve F32 +/// source bits; expand F16 and BF16 with the Rust conversion below; dequantize +/// IQ3_S with the pinned ggml grid. Do not include header or alignment bytes. +pub fn fingerprint(path: &Path) -> Result { + fingerprint_inner(path, None, true) +} + +/// The sharded stream orders GGUF files by byte-wise filename, then tensors +/// by each file's directory order. Every shard is checked against its pinned +/// manifest size and digest before its virtual bytes contribute to the result. +pub fn fingerprint_shards( + manifest: &Manifest, + source_dir: &Path, +) -> Result { + if manifest.schema_version != 1 || manifest.files.len() < 2 { + return Err( + "sharded derivation requires a schema v1 manifest with two or more files".into(), + ); + } + let mut entries = manifest.files.iter().collect::>(); + entries.sort_unstable_by(|left, right| left.name.as_bytes().cmp(right.name.as_bytes())); + let mut names = HashSet::new(); + let mut tensor_names = HashSet::new(); + let mut combined = Sha256::new(); + let mut derived_bytes = 0u64; + let mut shards = Vec::with_capacity(entries.len()); + let mut tensors = Vec::new(); + for entry in entries { + let mut components = Path::new(&entry.name).components(); + if !matches!(components.next(), Some(Component::Normal(_))) + || components.next().is_some() + || !names.insert(&entry.name) + { + return Err("invalid or duplicate GGUF shard filename".into()); + } + let path = source_dir.join(&entry.name); + if path + .symlink_metadata() + .map_err(|error| error.to_string())? + .file_type() + .is_symlink() + { + return Err(format!("{}: GGUF shard is a symlink", entry.name)); + } + let bytes = path.metadata().map_err(|error| error.to_string())?.len(); + if bytes != entry.size { + return Err(format!( + "{}: GGUF shard size differs from manifest", + entry.name + )); + } + let identity = fingerprint_inner(&path, Some(&mut combined), false)?; + if hex::encode(identity.gguf_sha256) != entry.sha256.to_ascii_lowercase() { + return Err(format!( + "{}: GGUF shard SHA-256 differs from manifest", + entry.name + )); + } + let tensor_count = identity.tensors.len(); + for mut tensor in identity.tensors { + if !tensor_names.insert(tensor.name.clone()) { + return Err(format!( + "duplicate tensor across GGUF shards: {}", + tensor.name + )); + } + tensor.derived_offset = tensor + .derived_offset + .checked_add(derived_bytes) + .ok_or("sharded derived offset overflow")?; + tensors.push(tensor); + } + derived_bytes = derived_bytes + .checked_add(identity.derived_bytes) + .ok_or("sharded derived byte count overflow")?; + shards.push(ShardIdentity { + name: entry.name.clone(), + gguf_sha256: identity.gguf_sha256, + gguf_bytes: bytes, + tensor_count, + }); + } + if !tensors.iter().any(|tensor| tensor.source_kind == 21) { + return Err("sharded derivation requires at least one IQ3_S tensor".into()); + } + Ok(ShardedIdentity { + derived_sha256: combined.finalize().into(), + derived_bytes, + shards, + tensors, + }) +} + +fn fingerprint_inner( + path: &Path, + mut combined: Option<&mut Sha256>, + require_mixed: bool, +) -> Result { + let index = gguf::tensor_index(path).map_err(|error| error.to_string())?; + if index.tensors.is_empty() + || (require_mixed + && (!index.tensors.iter().any(|tensor| tensor.kind == 21) + || !index.tensors.iter().any(|tensor| tensor.kind != 21))) + || index.tensors.iter().any(|tensor| { + !matches!( + tensor.kind, + 0 | 1 | 8 | 12 | 13 | 14 | 18 | 20 | 21 | 22 | 23 | 30 | 42 + ) + }) + { + return Err("mixed derivation requires IQ3_S and supported F32/quantized tensors".into()); + } + let gguf_sha256 = hash_file(path)?; + let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut derived = Sha256::new(); + let mut derived_bytes = 0u64; + let mut tensors = Vec::with_capacity(index.tensors.len()); + for tensor in &index.tensors { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + let offset = derived_bytes; + let mut source_hash = Sha256::new(); + let mut f32_hash = Sha256::new(); + let tensor_bytes = gguf_f32_stream::visit( + &mut source, + absolute, + tensor.kind, + tensor.bytes, + |raw, f32_bytes| { + source_hash.update(raw); + f32_hash.update(f32_bytes); + derived.update(f32_bytes); + if let Some(combined) = &mut combined { + combined.update(f32_bytes); + } + Ok(()) + }, + )?; + derived_bytes = derived_bytes + .checked_add(tensor_bytes) + .ok_or("mixed derived byte count overflow")?; + let shape_bytes = tensor + .dimensions + .iter() + .try_fold(4u64, |product, dim| product.checked_mul(*dim)) + .ok_or("mixed derived tensor shape overflow")?; + if tensor_bytes != shape_bytes { + return Err(format!( + "{}: derived tensor size differs from shape", + tensor.name + )); + } + tensors.push(TensorIdentity { + name: tensor.name.clone(), + source_kind: tensor.kind, + source_sha256: source_hash.finalize().into(), + derived_offset: offset, + derived_bytes: tensor_bytes, + f32_sha256: f32_hash.finalize().into(), + }); + } + if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size + || hash_file(path)? != gguf_sha256 + { + return Err("GGUF source changed during mixed derivation".into()); + } + Ok(Identity { + gguf_sha256, + derived_sha256: derived.finalize().into(), + derived_bytes, + tensors, + }) +} + +fn hash_file(path: &Path) -> Result<[u8; 32], String> { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut digest = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = source + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(digest.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{iq3_s, model::ModelFile}; + use std::fs; + + fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); + } + + fn one_tensor_gguf(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf + } + + #[test] + fn hashes_mixed_types_in_directory_order_without_gguf_padding() { + let cases = [ + ("bf16", 30u32, 192u64, 2u64), + ("f32", 0, 128, 2), + ("iq3", 21, 0, 256), + ("f16", 1, 160, 2), + ]; + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&(cases.len() as u64).to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + for (name, kind, offset, elements) in cases { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let data_start = gguf.len(); + let mut iq3 = [0u8; iq3_s::BLOCK_BYTES]; + iq3[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + gguf.extend_from_slice(&iq3); + gguf.resize(data_start + 128, 0); + for value in [3.0f32, -2.0] { + gguf.extend_from_slice(&value.to_le_bytes()); + } + gguf.resize(data_start + 160, 0); + for bits in [0x3400u16, 0x4000] { + gguf.extend_from_slice(&bits.to_le_bytes()); + } + gguf.resize(data_start + 192, 0); + for bits in [0x3f00u16, 0xbf80] { + gguf.extend_from_slice(&bits.to_le_bytes()); + } + let path = + std::env::temp_dir().join(format!("strata-mixed-identity-{}.gguf", std::process::id())); + fs::write(&path, &gguf).unwrap(); + let identity = fingerprint(&path).unwrap(); + assert_eq!(identity.tensors.len(), 4); + assert_eq!(identity.tensors[0].name, "bf16"); + assert_eq!(identity.tensors[1].derived_offset, 8); + assert_eq!(identity.tensors[2].derived_offset, 16); + assert_eq!(identity.tensors[3].derived_offset, 1040); + assert_eq!(identity.derived_bytes, 1048); + let mut expected = Vec::new(); + for value in [0.5f32, -1.0, 3.0, -2.0] { + expected.extend_from_slice(&value.to_le_bytes()); + } + for _ in 0..256 { + expected.extend_from_slice(&1.0f32.to_le_bytes()); + } + for value in [0.25f32, 2.0] { + expected.extend_from_slice(&value.to_le_bytes()); + } + assert_eq!( + identity.derived_sha256.as_slice(), + Sha256::digest(&expected).as_slice() + ); + assert_eq!( + identity.tensors[2].source_sha256.as_slice(), + Sha256::digest(iq3).as_slice() + ); + assert!(crate::derived_iq3::fingerprint(&path).is_err()); + fs::remove_file(path).unwrap(); + } + + #[test] + fn sharded_identity_sorts_verified_files_and_offsets_tensors() { + let directory = + std::env::temp_dir().join(format!("strata-mixed-shards-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let mut f32_payload = Vec::new(); + for index in 0..32 { + f32_payload.extend_from_slice(&(index as f32).to_le_bytes()); + } + let f32 = one_tensor_gguf("dense", 0, 32, &f32_payload); + let mut iq3_payload = [0u8; iq3_s::BLOCK_BYTES]; + iq3_payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let iq3 = one_tensor_gguf("expert", 21, 256, &iq3_payload); + fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); + fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); + let mut manifest = Manifest { + schema_version: 1, + files: vec![ + ModelFile { + name: "z-iq3.gguf".into(), + url: "https://example.invalid/z".into(), + size: iq3.len() as u64, + sha256: hex::encode(Sha256::digest(&iq3)), + }, + ModelFile { + name: "a-f32.gguf".into(), + url: "https://example.invalid/a".into(), + size: f32.len() as u64, + sha256: hex::encode(Sha256::digest(&f32)), + }, + ], + }; + let identity = fingerprint_shards(&manifest, &directory).unwrap(); + assert_eq!(identity.shards[0].name, "a-f32.gguf"); + assert_eq!(identity.shards[1].name, "z-iq3.gguf"); + assert_eq!(identity.tensors[0].name, "dense"); + assert_eq!(identity.tensors[1].name, "expert"); + assert_eq!(identity.tensors[1].derived_offset, 128); + assert_eq!(identity.derived_bytes, 1152); + let mut expected = f32_payload; + for _ in 0..256 { + expected.extend_from_slice(&1.0f32.to_le_bytes()); + } + assert_eq!( + identity.derived_sha256.as_slice(), + Sha256::digest(expected).as_slice() + ); + manifest.files[0].sha256 = "00".repeat(32); + assert!( + fingerprint_shards(&manifest, &directory) + .unwrap_err() + .contains("SHA-256 differs") + ); + fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/control-plane/src/doctor.rs b/control-plane/src/doctor.rs new file mode 100644 index 00000000..94f41414 --- /dev/null +++ b/control-plane/src/doctor.rs @@ -0,0 +1,153 @@ +//! Read-only Linux driver-version checks for the explicit CUDA 13.0 GA profile. +use serde::{Deserialize, Serialize}; +use std::{error::Error, fs, process::Stdio, time::Duration}; +use tokio::{io::AsyncReadExt, process::Command, time::timeout}; + +const MIN_DRIVER: DriverVersion = DriverVersion(580, 65, 6); +const PROBE_LIMIT: u64 = 8192; + +#[derive(Clone, Copy, Deserialize, Serialize)] +pub enum GpuRequirement { + #[serde(rename = "cuda-13.0-linux")] + Cuda13Linux, +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] +struct DriverVersion(u32, u32, u32); + +pub async fn report() -> Result<(), Box> { + println!( + "platform: {} {}", + std::env::consts::OS, + std::env::consts::ARCH + ); + let version = check(GpuRequirement::Cuda13Linux).await?; + println!("NVIDIA driver: {version}"); + println!( + "CUDA 13.0 GA profile driver floor: met (>=580.65.06); GPU/model readiness not checked" + ); + Ok(()) +} + +pub async fn check(_requirement: GpuRequirement) -> Result> { + if !cfg!(target_os = "linux") { + return Err("cuda-13.0-linux requires Linux; select a compatible host/profile".into()); + } + let version = match fs::read_to_string("/proc/driver/nvidia/version") + .ok() + .and_then(|s| parse_driver_version(&s)) + { + Some(version) => version, + None => probe().await?, + }; + if version < MIN_DRIVER { + return Err(format!("NVIDIA driver {}.{}.{} is below the cuda-13.0-linux profile floor 580.65.06; upgrade the host driver", version.0, version.1, version.2).into()); + } + Ok(format!("{}.{}.{}", version.0, version.1, version.2)) +} + +async fn probe() -> Result> { + let mut child = Command::new("nvidia-smi") + .args(["--query-gpu=driver_version", "--format=csv,noheader"]) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .stdout(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err( + |_| "NVIDIA driver unavailable; install the host driver and make nvidia-smi accessible", + )?; + let result = timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + child + .stdout + .take() + .ok_or("driver probe stdout unavailable")? + .take(PROBE_LIMIT + 1) + .read_to_end(&mut bytes) + .await + .map_err(|_| "driver probe output read failed")?; + if bytes.len() as u64 > PROBE_LIMIT { + return Err("driver probe output exceeded 8 KiB; check nvidia-smi"); + } + let status = child.wait().await.map_err(|_| "driver probe wait failed")?; + if !status.success() { + return Err("NVIDIA driver query failed; check driver installation and nvidia-smi"); + } + let text = std::str::from_utf8(&bytes).map_err(|_| "driver probe output was not UTF-8")?; + parse_csv(text).ok_or("NVIDIA driver version was missing or malformed; check nvidia-smi") + }) + .await; + match result { + Ok(Ok(version)) => Ok(version), + error => { + let _ = child.kill().await; + let message = match error { + Ok(Err(message)) => message, + _ => "NVIDIA driver query timed out after 5 seconds; check host driver health", + }; + Err(message.into()) + } + } +} + +fn parse_csv(text: &str) -> Option { + let versions = text + .lines() + .map(|line| { + let line = line.trim(); + if !line.bytes().all(|b| b.is_ascii_digit() || b == b'.') { + return None; + } + parse_driver_version(line) + }) + .collect::>>()?; + versions.into_iter().min() +} + +fn parse_driver_version(text: &str) -> Option { + text.split_whitespace().find_map(|word| { + let word = word.trim_matches(|ch: char| !ch.is_ascii_digit() && ch != '.'); + let mut parts = word.split('.'); + let major = parts.next()?.parse::().ok()?; + let minor = parts.next()?.parse::().ok()?; + let patch = parts.next()?.parse::().ok()?; + (parts.next().is_none() && major >= 100).then_some(DriverVersion(major, minor, patch)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn csv_requires_only_versions_and_checks_the_oldest() { + assert_eq!(parse_csv("580.65.06\n600.1.0\n"), Some(MIN_DRIVER)); + for invalid in [ + "", + "580.65.06\n\n", + "580.65.06\nheader", + "580.65", + "580.65.06.1", + "x580.65.06", + "580.65.06 secret", + ] { + assert_eq!(parse_csv(invalid), None, "{invalid:?}"); + } + } + + #[test] + fn driver_version_is_compared_numerically() { + assert_eq!( + parse_driver_version("NVRM version: NVIDIA UNIX x86_64 Kernel Module 580.65.06 Wed"), + Some(DriverVersion(580, 65, 6)) + ); + assert_eq!( + parse_driver_version("580.1.0\n"), + Some(DriverVersion(580, 1, 0)) + ); + assert!(DriverVersion(579, 99, 99) < MIN_DRIVER); + assert!(DriverVersion(580, 65, 5) < MIN_DRIVER); + assert!(DriverVersion(580, 65, 6) >= MIN_DRIVER); + } +} diff --git a/control-plane/src/embedded_engine.rs b/control-plane/src/embedded_engine.rs new file mode 100644 index 00000000..05c0cb30 --- /dev/null +++ b/control-plane/src/embedded_engine.rs @@ -0,0 +1,133 @@ +//! Opt-in packaged worker. The host still supplies the ELF's shared libraries. +use std::{error::Error, ffi::OsStr, fs::File, path::PathBuf}; + +mod payload { + include!(concat!(env!("OUT_DIR"), "/embedded-engine.rs")); +} + +pub fn info() -> serde_json::Value { + serde_json::json!({ + "embedded": !payload::BYTES.is_empty(), + "bytes": payload::BYTES.len(), + "sha256": (!payload::BYTES.is_empty()).then_some(payload::SHA256), + "declared_source_revision": (!payload::BYTES.is_empty()).then_some(payload::SOURCE_REVISION), + "target_os": std::env::consts::OS, + "target_arch": std::env::consts::ARCH, + "shared_libraries_bundled": false, + "model_bundled": false, + "selection": "engine.executable=@embedded", + }) +} + +/// Holds the anonymous executable alive for initial spawn and all worker restarts. +pub struct EmbeddedEngine { + _file: File, + pub executable: PathBuf, +} + +pub fn resolve(executable: &OsStr) -> Result, Box> { + if executable != OsStr::new("@embedded") { + return Ok(None); + } + if payload::BYTES.is_empty() { + return Err( + "this binary has no embedded engine; use an external executable or a payload build" + .into(), + ); + } + materialize(payload::BYTES).map(Some) +} + +/// Explicit loader/help probe; this is not an inference or readiness check. +pub fn help() -> Result<(), Box> { + let engine = resolve(OsStr::new("@embedded"))?.ok_or("no embedded engine")?; + let status = std::process::Command::new(&engine.executable) + .arg("--help") + .env("CUDA_VISIBLE_DEVICES", "") + .status()?; + if !status.success() { + return Err(format!("embedded engine help exited with {status}").into()); + } + Ok(()) +} + +#[cfg(not(target_os = "linux"))] +fn materialize(_: &[u8]) -> Result> { + Err("embedded worker execution requires Linux".into()) +} + +#[cfg(target_os = "linux")] +fn materialize(bytes: &[u8]) -> Result> { + use std::{ + io::Write, + os::fd::{AsRawFd, FromRawFd}, + }; + // SAFETY: constant NUL-terminated name, supported flags, no borrowed pointers retained. + let mut fd = unsafe { + libc::memfd_create( + c"strata-engine".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING | libc::MFD_EXEC, + ) + }; + if fd < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) { + // Older kernels do not know MFD_EXEC. Do not retry EPERM/EACCES policy failures. + // SAFETY: same constant name; legacy flags have been available since Linux 3.17. + fd = unsafe { + libc::memfd_create( + c"strata-engine".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ) + }; + } + if fd < 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: successful memfd_create transfers a new owned fd exactly once. + let mut file = unsafe { File::from_raw_fd(fd) }; + file.write_all(bytes)?; + let seals = libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; + // SAFETY: valid owned fd, integer fcntl argument for F_ADD_SEALS. + if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } < 0 { + return Err(std::io::Error::last_os_error().into()); + } + // Use the parent's fd path: CLOEXEC does not need to leak a descriptor to children. + let executable = PathBuf::from(format!( + "/proc/{}/fd/{}", + std::process::id(), + file.as_raw_fd() + )); + Ok(EmbeddedEngine { + _file: file, + executable, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn external_selection_never_materializes_an_engine() { + assert!(resolve(OsStr::new("/external/strata")).unwrap().is_none()); + assert_eq!(info()["shared_libraries_bundled"], false); + if payload::BYTES.is_empty() { + assert!(resolve(OsStr::new("@embedded")).is_err()); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn sealed_payload_is_exact_immutable_and_removed_on_drop() { + use std::io::Write; + let engine = materialize(b"immutable fixture bytes").unwrap(); + let path = engine.executable.clone(); + assert_eq!(std::fs::read(&path).unwrap(), b"immutable fixture bytes"); + let mut other = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + assert!(other.write_all(b"x").is_err()); + assert!(other.set_len(0).is_err()); + assert!(other.set_len(100).is_err()); + drop(other); + drop(engine); + assert!(!path.exists()); + } +} diff --git a/control-plane/src/embedded_spec.rs b/control-plane/src/embedded_spec.rs new file mode 100644 index 00000000..389f4eee --- /dev/null +++ b/control-plane/src/embedded_spec.rs @@ -0,0 +1,197 @@ +//! Bounded build-time payload copying, shared with ordinary unit tests. +use std::io::{self, Read, Write}; + +use sha2::{Digest, Sha256}; + +pub const MAX_BYTES: u64 = 1024 * 1024 * 1024; +const BUFFER_BYTES: usize = 64 * 1024; + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +fn hex_digest(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// On error the destination may be partial and must not be published as a payload. +pub fn copy_verified( + source: impl Read, + destination: impl Write, + arch: &str, + digest: &str, + revision: &str, +) -> io::Result { + copy_with_limit(source, destination, arch, digest, revision, MAX_BYTES) +} + +fn copy_with_limit( + mut source: impl Read, + mut destination: impl Write, + arch: &str, + digest: &str, + revision: &str, + limit: u64, +) -> io::Result { + if digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(invalid( + "embedded engine SHA256 must be 64 hexadecimal characters", + )); + } + if revision.len() != 40 || !revision.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(invalid( + "embedded engine source revision must be a full 40-character Git SHA", + )); + } + let machine = match arch { + "x86_64" => 62, + "aarch64" => 183, + _ => { + return Err(invalid( + "embedded engines support Linux x86_64 or aarch64 only", + )); + } + }; + let mut header = [0; 64]; + source.read_exact(&mut header)?; + if &header[..7] != b"\x7fELF\x02\x01\x01" + || !matches!(u16::from_le_bytes([header[16], header[17]]), 2 | 3) + || u16::from_le_bytes([header[18], header[19]]) != machine + { + return Err(invalid( + "embedded engine must be an ELF64 little-endian executable for the target architecture", + )); + } + let mut total = header.len() as u64; + if total > limit { + return Err(invalid("embedded engine exceeds size limit")); + } + let mut hash = Sha256::new(); + hash.update(header); + destination.write_all(&header)?; + let mut buffer = [0; BUFFER_BYTES]; + loop { + // At the limit, read only one extra byte to distinguish EOF from overflow. + let available = (limit - total + 1).min(BUFFER_BYTES as u64) as usize; + let count = match source.read(&mut buffer[..available]) { + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + result => result?, + }; + if count == 0 { + break; + } + total += count as u64; + if total > limit { + return Err(invalid("embedded engine exceeds size limit")); + } + hash.update(&buffer[..count]); + destination.write_all(&buffer[..count])?; + } + if hex_digest(&hash.finalize()) != digest.to_ascii_lowercase() { + return Err(invalid("embedded engine SHA256 mismatch")); + } + destination.flush()?; + Ok(total) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture(size: usize) -> Vec { + let mut elf = vec![0x5a; size]; + elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + elf[16..18].copy_from_slice(&3u16.to_le_bytes()); + elf[18..20].copy_from_slice(&62u16.to_le_bytes()); + elf + } + + #[test] + fn payload_digest_architecture_and_provenance_are_required() { + let mut elf = fixture(64); + let digest = hex_digest(&Sha256::digest(&elf)); + let rev = "a".repeat(40); + assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, &rev).is_ok()); + assert!(copy_verified(&elf[..], io::sink(), "aarch64", &digest, &rev).is_err()); + assert!(copy_verified(&elf[..], io::sink(), "x86_64", &"0".repeat(64), &rev).is_err()); + assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, "untracked").is_err()); + elf[4] = 1; + assert!(copy_verified(&elf[..], io::sink(), "x86_64", &digest, &rev).is_err()); + assert!(copy_verified(&b"#!/bin/sh"[..], io::sink(), "x86_64", &digest, &rev).is_err()); + } + + #[test] + fn copy_is_exact_bounded_and_rejects_overflow_without_copying_extra_bytes() { + let elf = fixture(BUFFER_BYTES * 2 + 19); + let digest = hex_digest(&Sha256::digest(&elf)); + let rev = "a".repeat(40); + let mut output = Vec::new(); + let mut input = io::Cursor::new(&elf); + assert_eq!( + copy_with_limit( + &mut input, + &mut output, + "x86_64", + &digest, + &rev, + elf.len() as u64 + ) + .unwrap(), + elf.len() as u64 + ); + assert_eq!(output, elf); + output.clear(); + input.set_position(0); + let cap = BUFFER_BYTES as u64; + assert!(copy_with_limit(&mut input, &mut output, "x86_64", &digest, &rev, cap).is_err()); + assert_eq!(input.position(), cap + 1); + assert!(output.len() as u64 <= cap); + } + + #[test] + fn io_errors_and_truncated_sources_do_not_pass_verification() { + struct BrokenWriter; + impl Write for BrokenWriter { + fn write(&mut self, _: &[u8]) -> io::Result { + Err(io::Error::other("fixture write failed")) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let elf = fixture(BUFFER_BYTES + 31); + let digest = hex_digest(&Sha256::digest(&elf)); + let rev = "a".repeat(40); + assert!(copy_verified(&elf[..], BrokenWriter, "x86_64", &digest, &rev).is_err()); + assert!(copy_verified(&elf[..elf.len() - 1], io::sink(), "x86_64", &digest, &rev).is_err()); + let mut interrupted = true; + let mut input = io::Cursor::new(&elf); + let source = io::Read::by_ref(&mut input); + struct InterruptedOnce<'a> { + inner: &'a mut dyn Read, + first: &'a mut bool, + } + impl Read for InterruptedOnce<'_> { + fn read(&mut self, out: &mut [u8]) -> io::Result { + assert!(out.len() <= BUFFER_BYTES); + if std::mem::take(self.first) { + return Err(io::ErrorKind::Interrupted.into()); + } + self.inner.read(out) + } + } + assert!( + copy_verified( + InterruptedOnce { + inner: source, + first: &mut interrupted + }, + io::sink(), + "x86_64", + &digest, + &rev + ) + .is_ok() + ); + } +} diff --git a/control-plane/src/engine_probe.rs b/control-plane/src/engine_probe.rs new file mode 100644 index 00000000..9c2a6006 --- /dev/null +++ b/control-plane/src/engine_probe.rs @@ -0,0 +1,32 @@ +//! Explicit loader probe for an operator-trusted engine with a side-effect-free --help. +use std::{error::Error, ffi::OsStr, process::Stdio, time::Duration}; +use tokio::{process::Command, time::timeout}; + +pub async fn check(executable: &OsStr) -> Result<(), Box> { + // Keep the memfd alive until the help process has exited. Serving may have + // already resolved the payload and keeps its own lifetime guard. + let embedded = crate::embedded_engine::resolve(executable)?; + let executable = embedded + .as_ref() + .map_or(executable, |e| e.executable.as_os_str()); + let mut child = Command::new(executable) + .arg("--help") + .env("CUDA_VISIBLE_DEVICES", "") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "engine loader probe could not start; check executable permissions, ELF architecture and loader/shared-library dependencies")?; + match timeout(Duration::from_secs(10), child.wait()).await { + Ok(Ok(status)) if status.success() => Ok(()), + Ok(Ok(status)) => Err(format!("engine --help probe failed ({status}); check loader/shared-library dependencies or use a profile with a working --help command").into()), + failure => { + let _ = child.kill().await; + Err(match failure { + Err(_) => "engine --help probe timed out after 10 seconds; check the selected engine before preparing the model", + _ => "engine --help probe could not be collected; check the selected engine", + }.into()) + } + } +} diff --git a/control-plane/src/ggml_bridge.c b/control-plane/src/ggml_bridge.c new file mode 100644 index 00000000..20d9b039 --- /dev/null +++ b/control-plane/src/ggml_bridge.c @@ -0,0 +1,58 @@ +// Offline GGUF-to-F32 conversion through the pinned ggml CPU oracle. +// The source and destination are complete blocks and are 16-byte aligned by +// the Rust caller. No Python or dynamically loaded ggml library is involved. +#include "ggml-quants.h" +#include "ggml.h" + +#include + +uint32_t strata_ggml_block_bytes(uint32_t kind) { + switch (kind) { + case GGML_TYPE_Q4_0: return sizeof(block_q4_0); + case GGML_TYPE_Q4_1: return sizeof(block_q4_1); + case GGML_TYPE_Q5_0: return sizeof(block_q5_0); + case GGML_TYPE_Q5_1: return sizeof(block_q5_1); + case GGML_TYPE_Q8_0: return sizeof(block_q8_0); + case GGML_TYPE_Q2_K: return sizeof(block_q2_K); + case GGML_TYPE_Q3_K: return sizeof(block_q3_K); + case GGML_TYPE_Q4_K: return sizeof(block_q4_K); + case GGML_TYPE_Q5_K: return sizeof(block_q5_K); + case GGML_TYPE_Q6_K: return sizeof(block_q6_K); + case GGML_TYPE_IQ2_XXS: return sizeof(block_iq2_xxs); + case GGML_TYPE_IQ2_XS: return sizeof(block_iq2_xs); + case GGML_TYPE_IQ3_XXS: return sizeof(block_iq3_xxs); + case GGML_TYPE_IQ4_NL: return sizeof(block_iq4_nl); + case GGML_TYPE_IQ3_S: return sizeof(block_iq3_s); + case GGML_TYPE_IQ2_S: return sizeof(block_iq2_s); + case GGML_TYPE_IQ4_XS: return sizeof(block_iq4_xs); + case GGML_TYPE_IQ1_M: return sizeof(block_iq1_m); + case GGML_TYPE_Q2_0: return sizeof(block_q2_0); + default: return 0; + } +} + +int strata_ggml_dequantize(uint32_t kind, const uint8_t * source, float * destination, int64_t elements) { + if (!source || !destination || elements <= 0) return -1; + switch (kind) { + case GGML_TYPE_Q4_0: dequantize_row_q4_0((const block_q4_0 *) source, destination, elements); return 0; + case GGML_TYPE_Q4_1: dequantize_row_q4_1((const block_q4_1 *) source, destination, elements); return 0; + case GGML_TYPE_Q5_0: dequantize_row_q5_0((const block_q5_0 *) source, destination, elements); return 0; + case GGML_TYPE_Q5_1: dequantize_row_q5_1((const block_q5_1 *) source, destination, elements); return 0; + case GGML_TYPE_Q8_0: dequantize_row_q8_0((const block_q8_0 *) source, destination, elements); return 0; + case GGML_TYPE_Q2_K: dequantize_row_q2_K((const block_q2_K *) source, destination, elements); return 0; + case GGML_TYPE_Q3_K: dequantize_row_q3_K((const block_q3_K *) source, destination, elements); return 0; + case GGML_TYPE_Q4_K: dequantize_row_q4_K((const block_q4_K *) source, destination, elements); return 0; + case GGML_TYPE_Q5_K: dequantize_row_q5_K((const block_q5_K *) source, destination, elements); return 0; + case GGML_TYPE_Q6_K: dequantize_row_q6_K((const block_q6_K *) source, destination, elements); return 0; + case GGML_TYPE_IQ2_XXS: dequantize_row_iq2_xxs((const block_iq2_xxs *) source, destination, elements); return 0; + case GGML_TYPE_IQ2_XS: dequantize_row_iq2_xs((const block_iq2_xs *) source, destination, elements); return 0; + case GGML_TYPE_IQ3_XXS: dequantize_row_iq3_xxs((const block_iq3_xxs *) source, destination, elements); return 0; + case GGML_TYPE_IQ4_NL: dequantize_row_iq4_nl((const block_iq4_nl *) source, destination, elements); return 0; + case GGML_TYPE_IQ3_S: dequantize_row_iq3_s((const block_iq3_s *) source, destination, elements); return 0; + case GGML_TYPE_IQ2_S: dequantize_row_iq2_s((const block_iq2_s *) source, destination, elements); return 0; + case GGML_TYPE_IQ4_XS: dequantize_row_iq4_xs((const block_iq4_xs *) source, destination, elements); return 0; + case GGML_TYPE_IQ1_M: dequantize_row_iq1_m((const block_iq1_m *) source, destination, elements); return 0; + case GGML_TYPE_Q2_0: dequantize_row_q2_0((const block_q2_0 *) source, destination, elements); return 0; + default: return -2; + } +} diff --git a/control-plane/src/ggml_bridge.rs b/control-plane/src/ggml_bridge.rs new file mode 100644 index 00000000..797e31ed --- /dev/null +++ b/control-plane/src/ggml_bridge.rs @@ -0,0 +1,112 @@ +//! Pinned ggml CPU dequantization for offline model preparation. The C source +//! is built into this binary; production serving still uses the native engine. + +use std::ffi::c_int; + +use crate::gguf; + +unsafe extern "C" { + fn strata_ggml_block_bytes(kind: u32) -> u32; + fn strata_ggml_dequantize( + kind: u32, + source: *const u8, + destination: *mut f32, + elements: i64, + ) -> c_int; +} + +pub fn decode_into(kind: u32, source: &[u8], destination: &mut [f32]) -> Result<(), String> { + let (block_elements, block_bytes) = + gguf::block_geometry(kind).ok_or_else(|| format!("unsupported GGUF source kind {kind}"))?; + // The GGUF reader and the pinned C decoder must agree before the C code + // can read blocks. A mismatch could otherwise read past the source slice. + if u64::from(unsafe { strata_ggml_block_bytes(kind) }) != block_bytes { + return Err(format!("ggml block geometry differs for GGUF kind {kind}")); + } + if source.is_empty() + || !(source.len() as u64).is_multiple_of(block_bytes) + || source.len() as u64 / block_bytes * block_elements != destination.len() as u64 + { + return Err("GGUF dequantization block shape mismatch".into()); + } + let elements = i64::try_from(destination.len()).map_err(|_| "GGUF chunk is too large")?; + // ggml block structs include f16 words; guarantee their pointer alignment + // even when a caller supplies an arbitrary byte slice. + let mut aligned = Vec::::new(); + let pointer = if source.as_ptr().align_offset(16) == 0 { + source.as_ptr() + } else { + aligned.resize(source.len().div_ceil(16), 0); + // SAFETY: `aligned` has at least `source.len()` initialized bytes and + // the allocations do not overlap. + unsafe { + std::ptr::copy_nonoverlapping( + source.as_ptr(), + aligned.as_mut_ptr().cast::(), + source.len(), + ); + } + aligned.as_ptr().cast::() + }; + // SAFETY: all lengths and alignment are checked above; the C switch calls + // only the pinned ggml function for this kind and fills `destination`. + let status = + unsafe { strata_ggml_dequantize(kind, pointer, destination.as_mut_ptr(), elements) }; + if status != 0 { + return Err(format!( + "ggml dequantization does not support GGUF kind {kind}" + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::iq3_s; + + #[test] + fn pinned_ggml_block_sizes_match_gguf_geometry() { + for kind in [ + 2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 29, 42, + ] { + assert_eq!( + u64::from(unsafe { strata_ggml_block_bytes(kind) }), + gguf::block_geometry(kind).unwrap().1, + "kind {kind}" + ); + } + } + + #[test] + fn pinned_ggml_iq3_matches_independent_rust_decoder() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + let mut decoded = [0.0f32; 256]; + decode_into(21, &block, &mut decoded).unwrap(); + assert_eq!(decoded, iq3_s::decode_block(&block).unwrap()); + } + + #[test] + fn q8_0_and_q2_0_match_known_block_values() { + let mut q8 = [0u8; 34]; + q8[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in q8[2..].iter_mut().enumerate() { + *byte = (index as i8 - 16) as u8; + } + let mut values = [0.0f32; 32]; + decode_into(8, &q8, &mut values).unwrap(); + assert_eq!(values[0], -16.0); + assert_eq!(values[31], 15.0); + + let mut q2 = [0u8; 18]; + q2[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut values = [0.0f32; 64]; + decode_into(42, &q2, &mut values).unwrap(); + assert!(values.iter().all(|value| *value == -1.0)); + } +} diff --git a/control-plane/src/gguf.rs b/control-plane/src/gguf.rs new file mode 100644 index 00000000..ec052e4b --- /dev/null +++ b/control-plane/src/gguf.rs @@ -0,0 +1,787 @@ +//! Bounded GGUF v3 header inspection; tensor payloads are never loaded into memory. + +use std::{ + collections::{BTreeMap, HashSet}, + error::Error, + fs::File, + io::{Read, Seek, SeekFrom}, + path::Path, +}; + +use sha2::{Digest, Sha256}; + +type Result = std::result::Result>; + +#[derive(Debug)] +pub struct Summary { + pub tensors: u64, + pub metadata: u64, + pub architecture: Option, + pub split_no: Option, + pub split_count: Option, + pub split_tensors_count: Option, + pub data_start: u64, + pub file_size: u64, + pub types: BTreeMap, +} + +#[derive(Debug)] +pub struct TensorInfo { + pub name: String, + /// GGUF order: dimension zero varies fastest. + pub dimensions: Vec, + pub kind: u32, + pub offset: u64, + pub bytes: u64, +} + +#[derive(Debug)] +pub struct TensorIndex { + pub summary: Summary, + pub tensors: Vec, +} + +#[derive(Debug)] +pub struct TokenizerMetadata { + pub model: String, + pub pre: String, + pub tokens: Vec, + pub merges: Vec, + pub token_types: Option>, + pub special_ids: BTreeMap, + pub chat_template: String, +} + +/// Metadata admission for the specialised engine, before expensive preparation. +/// Mirrors artifact/gguf_reader.hpp::Qwen4ExpGuard; this does not inspect tensor values. +pub fn check_flash_next_profile(path: &Path) -> Result<()> { + let summary = inspect(path)?; + if summary.architecture.as_deref() != Some("qwen4exp") { + return Err("runtime_profile requires general.architecture=qwen4exp".into()); + } + let required = [ + ("qwen4exp.block_count", Some(48)), + ("qwen4exp.embedding_length", Some(2560)), + ("qwen4exp.attention.head_count", Some(24)), + ("qwen4exp.attention.head_count_kv", Some(2)), + ("qwen4exp.expert_count", None), + ("qwen4exp.expert_used_count", None), + ]; + let mut cursor = Cursor { + file: File::open(path)?, + size: summary.file_size, + }; + cursor.skip(24)?; + let mut values = BTreeMap::new(); + for _ in 0..summary.metadata { + let key = cursor.string()?; + let kind = cursor.u32()?; + if required.iter().any(|(name, _)| *name == key) { + if !matches!(kind, 0..=5 | 10 | 11) { + return Err(format!("runtime_profile: {key} must be an integer").into()); + } + let value = cursor.integer(kind).map_err(|_| { + format!("runtime_profile: {key} must be a nonnegative 32-bit integer") + })?; + values.insert(key, value); + } else { + cursor.skip_value(kind)?; + } + } + for (key, expected) in required { + let value = *values + .get(key) + .ok_or_else(|| format!("runtime_profile: missing {key}"))?; + if value == 0 || value > i32::MAX as u32 { + return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); + } + if let Some(expected) = expected + && value != expected + { + return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); + } + } + if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { + return Err( + "runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(), + ); + } + Ok(()) +} + +/// Read only tokenizer fields after the complete GGUF header has passed inspection. +pub fn tokenizer_metadata(path: &Path) -> Result { + inspect(path)?; + let file = File::open(path)?; + let size = file.metadata()?.len(); + let mut cursor = Cursor { file, size }; + cursor.skip(16)?; // magic, version, tensor count + let count = cursor.u64()?; + let mut model = None; + let mut pre = None; + let mut tokens = None; + let mut merges = None; + let mut token_types = None; + let mut special_ids = BTreeMap::new(); + let mut chat_template = None; + for _ in 0..count { + let key = cursor.string()?; + let kind = cursor.u32()?; + match key.as_str() { + "tokenizer.ggml.model" if kind == 8 => model = Some(cursor.string()?), + "tokenizer.ggml.pre" if kind == 8 => pre = Some(cursor.string()?), + "tokenizer.ggml.tokens" => tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" => merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" => token_types = Some(cursor.integer_array(kind)?), + "tokenizer.chat_template" if kind == 8 => chat_template = Some(cursor.string()?), + _ if key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { + special_ids.insert(key, cursor.integer(kind)?); + } + _ => cursor.skip_value(kind)?, + } + } + let model = model.ok_or("GGUF is missing tokenizer.ggml.model")?; + let tokens = tokens.ok_or("GGUF is missing tokenizer.ggml.tokens")?; + let merges = merges.ok_or("GGUF is missing tokenizer.ggml.merges")?; + let chat_template = chat_template.ok_or("GGUF is missing tokenizer.chat_template")?; + if model != "gpt2" || pre.as_deref().is_some_and(|value| value != "qwen35") { + return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); + } + if tokens.is_empty() || chat_template.is_empty() { + return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); + } + if token_types + .as_ref() + .is_some_and(|types| types.len() != tokens.len()) + { + return Err("token_type length differs from vocabulary length".into()); + } + let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); + if vocab.len() != tokens.len() { + return Err("GGUF tokenizer has duplicate vocabulary entries".into()); + } + let mut seen_merges = HashSet::new(); + for merge in &merges { + let Some((left, right)) = merge.split_once(' ') else { + return Err("GGUF BPE merge is not a pair".into()); + }; + if left.is_empty() + || right.is_empty() + || right.contains(' ') + || !vocab.contains(left) + || !vocab.contains(right) + || !seen_merges.insert(merge) + { + return Err("GGUF BPE merge is invalid or duplicated".into()); + } + } + for &id in special_ids.values() { + if id as usize >= tokens.len() { + return Err("special token ID exceeds vocabulary".into()); + } + } + Ok(TokenizerMetadata { + model, + pre: pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types, + special_ids, + chat_template, + }) +} + +pub fn inspect(path: &Path) -> Result { + Ok(read_index(path, false)?.summary) +} + +/// Locate each supported tensor payload without reading the tensor into RAM. +/// Types and byte lengths follow the pinned Strata GGUF reader geometry. +pub fn tensor_index(path: &Path) -> Result { + read_index(path, true) +} + +/// Hash one indexed tensor with a fixed-size buffer. The caller must keep the +/// verified source file stable between indexing and reading. +pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> Result<[u8; 32]> { + let tensor = index + .tensors + .get(tensor_number) + .ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 { + return Err("GGUF tensor index lacks verified byte geometry".into()); + } + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if absolute + .checked_add(tensor.bytes) + .is_none_or(|end| end > index.summary.file_size) + { + return Err("GGUF tensor exceeds indexed file".into()); + } + let mut file = File::open(path)?; + if file.metadata()?.len() != index.summary.file_size { + return Err("GGUF source size changed after indexing".into()); + } + file.seek(SeekFrom::Start(absolute))?; + let mut digest = Sha256::new(); + let mut buffer = vec![0u8; 1024 * 1024]; + let mut remaining = tensor.bytes; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..count])?; + digest.update(&buffer[..count]); + remaining -= count as u64; + } + Ok(digest.finalize().into()) +} + +fn read_index(path: &Path, strict: bool) -> Result { + let file = File::open(path)?; + let size = file.metadata()?.len(); + let mut cursor = Cursor { file, size }; + if cursor.take(4)? != b"GGUF" { + return Err("not a GGUF file".into()); + } + if cursor.u32()? != 3 { + return Err("only GGUF v3 is supported".into()); + } + let tensors = cursor.u64()?; + let metadata = cursor.u64()?; + if tensors > 1_000_000 || metadata > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + let mut architecture = None; + let mut split_no = None; + let mut split_count = None; + let mut split_tensors_count = None; + let mut alignment = 32u64; + let mut keys = HashSet::new(); + for _ in 0..metadata { + let key = cursor.string()?; + if !keys.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } + let kind = cursor.u32()?; + match (key.as_str(), kind) { + ("general.architecture", 8) => architecture = Some(cursor.string()?), + ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), + ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), + ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), + ("split.tensors.count", 5) => { + let count = cursor.u32()?; + if count > i32::MAX as u32 { + return Err("negative GGUF split tensor count".into()); + } + split_tensors_count = Some(u64::from(count)); + } + ("split.no" | "split.count" | "split.tensors.count", _) => { + return Err("GGUF split metadata has an invalid integer type".into()); + } + _ => cursor.skip_value(kind)?, + } + } + if !alignment.is_power_of_two() || alignment > 4096 { + return Err("invalid GGUF alignment".into()); + } + let mut types = BTreeMap::new(); + let mut names = HashSet::new(); + let mut tensor_index = Vec::with_capacity(tensors as usize); + for _ in 0..tensors { + let name = cursor.string()?; + if !names.insert(name.clone()) { + return Err("duplicate GGUF tensor name".into()); + } + let dimensions = cursor.u32()?; + if !(1..=8).contains(&dimensions) { + return Err("invalid GGUF tensor dimensions".into()); + } + let mut shape = Vec::with_capacity(dimensions as usize); + for _ in 0..dimensions { + let dim = cursor.u64()?; + if dim == 0 { + return Err("zero GGUF tensor dimension".into()); + } + shape.push(dim); + } + let kind = cursor.u32()?; + let offset = cursor.u64()?; + *types.entry(kind).or_insert(0) += 1; + tensor_index.push(TensorInfo { + name, + dimensions: shape, + kind, + offset, + bytes: 0, + }); + } + let header_end = cursor.position()?; + let data_start = header_end + .checked_add(alignment - 1) + .ok_or("GGUF header offset overflow")? + / alignment + * alignment; + if data_start > size { + return Err("GGUF data section is truncated".into()); + } + for tensor in &tensor_index { + if tensor.offset % alignment != 0 + || data_start + .checked_add(tensor.offset) + .is_none_or(|start| start >= size) + { + return Err("GGUF tensor offset is out of bounds or unaligned".into()); + } + } + if strict { + let mut positions = (0..tensor_index.len()).collect::>(); + if positions.is_empty() { + return Err("GGUF has no tensors to index".into()); + } + positions.sort_unstable_by_key(|&index| tensor_index[index].offset); + if tensor_index[positions[0]].offset != 0 { + return Err("GGUF first tensor does not start at data offset zero".into()); + } + for (at, &index) in positions.iter().enumerate() { + let tensor = &tensor_index[index]; + let (block_elements, block_bytes) = block_geometry(tensor.kind) + .ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |product, dim| product.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if tensor.dimensions[0] % block_elements != 0 { + return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); + } + let bytes = elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or("GGUF tensor byte count overflow")?; + let end = tensor + .offset + .checked_add(bytes) + .ok_or("GGUF tensor end overflow")?; + let next = positions + .get(at + 1) + .map(|&next| tensor_index[next].offset) + .unwrap_or(size - data_start); + if end > next || next - end >= alignment { + return Err(format!( + "{}: tensor bytes overlap or have an invalid gap", + tensor.name + ) + .into()); + } + tensor_index[index].bytes = bytes; + } + } + if let (Some(no), Some(count)) = (split_no, split_count) + && (count == 0 || no >= count) + { + return Err("invalid GGUF split metadata".into()); + } + let summary = Summary { + tensors, + metadata, + architecture, + split_no, + split_count, + split_tensors_count, + data_start, + file_size: size, + types, + }; + Ok(TensorIndex { + summary, + tensors: tensor_index, + }) +} + +pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { + // Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the + // upstream commit recorded in docs/upstream.md. + Some(match kind { + 0 => (1, 4), + 1 | 30 => (1, 2), + 2 => (32, 18), + 3 => (32, 20), + 6 => (32, 22), + 7 => (32, 24), + 8 => (32, 34), + 9 => (32, 36), + 10 => (256, 84), + 11 | 21 => (256, 110), + 12 => (256, 144), + 13 => (256, 176), + 14 => (256, 210), + 16 => (256, 66), + 17 => (256, 74), + 18 => (256, 98), + 20 => (32, 18), + 22 => (256, 82), + 23 => (256, 136), + 24 => (1, 1), + 29 => (256, 56), + 42 => (64, 18), + _ => return None, + }) +} + +struct Cursor { + file: File, + size: u64, +} + +impl Cursor { + fn position(&mut self) -> Result { + Ok(self.file.stream_position()?) + } + + fn skip(&mut self, bytes: u64) -> Result<()> { + let end = self + .position()? + .checked_add(bytes) + .ok_or("GGUF offset overflow")?; + if end > self.size { + return Err("truncated GGUF header".into()); + } + self.file.seek(SeekFrom::Start(end))?; + Ok(()) + } + + fn take(&mut self, size: usize) -> Result> { + if self + .position()? + .checked_add(size as u64) + .is_none_or(|end| end > self.size) + { + return Err("truncated GGUF header".into()); + } + let mut data = vec![0; size]; + self.file.read_exact(&mut data)?; + Ok(data) + } + + fn u16(&mut self) -> Result { + let bytes = self.take(2)?; + Ok(u16::from_le_bytes([bytes[0], bytes[1]])) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u32(&mut self) -> Result { + let bytes = self.take(4)?; + Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + fn u64(&mut self) -> Result { + let bytes = self.take(8)?; + Ok(u64::from_le_bytes([ + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], + ])) + } + + fn string(&mut self) -> Result { + let size = self.u64()?; + if size > 1_048_576 { + return Err("GGUF header string is too large".into()); + } + Ok(String::from_utf8(self.take(size as usize)?)?) + } + + fn string_array(&mut self, kind: u32) -> Result> { + if kind != 9 || self.u32()? != 8 { + return Err("expected a GGUF string array".into()); + } + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF tokenizer array count".into()); + } + let mut total = 0u64; + let mut values = Vec::with_capacity(count as usize); + for _ in 0..count { + let value = self.string()?; + total = total + .checked_add(value.len() as u64) + .ok_or("GGUF tokenizer array size overflow")?; + if total > 512 * 1024 * 1024 { + return Err("GGUF tokenizer array exceeds 512 MiB".into()); + } + values.push(value); + } + Ok(values) + } + + fn integer_array(&mut self, kind: u32) -> Result> { + if kind != 9 { + return Err("expected a GGUF integer array".into()); + } + let element = self.u32()?; + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF tokenizer array count".into()); + } + let mut values = Vec::with_capacity(count as usize); + for _ in 0..count { + values.push(self.integer(element)?); + } + Ok(values) + } + + fn integer(&mut self, kind: u32) -> Result { + match kind { + 0 | 7 => Ok(u32::from(self.u8()?)), + 1 => u32::try_from(self.u8()? as i8).map_err(Into::into), + 2 => Ok(u32::from(self.u16()?)), + 3 => u32::try_from(self.u16()? as i16).map_err(Into::into), + 4 => self.u32(), + 5 => u32::try_from(self.u32()? as i32).map_err(Into::into), + 10 => u32::try_from(self.u64()?).map_err(Into::into), + 11 => u32::try_from(self.u64()? as i64).map_err(Into::into), + _ => Err(format!("GGUF metadata type {kind} is not an integer").into()), + } + } + + fn skip_value(&mut self, kind: u32) -> Result<()> { + match kind { + 0 | 1 | 7 => self.skip(1), + 2 | 3 => self.skip(2), + 4..=6 => self.skip(4), + 8 => { + let size = self.u64()?; + self.skip(size) + } + 9 => { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => { + if count > 10_000_000 { + return Err("unreasonable GGUF string array count".into()); + } + for _ in 0..count { + let size = self.u64()?; + self.skip(size)?; + } + Ok(()) + } + 9 => Err("nested GGUF arrays are unsupported".into()), + _ => self.skip( + count + .checked_mul(value_width(element)?) + .ok_or("GGUF array size overflow")?, + ), + } + } + 10..=12 => self.skip(8), + _ => Err(format!("unknown GGUF metadata type {kind}").into()), + } + } +} + +fn value_width(kind: u32) -> Result { + match kind { + 0 | 1 | 7 => Ok(1), + 2 | 3 => Ok(2), + 4..=6 => Ok(4), + 10..=12 => Ok(8), + _ => Err(format!("invalid GGUF array element type {kind}").into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); + } + + #[test] + fn admits_flash_metadata_and_rejects_incompatible_profiles() { + let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id())); + let fields = [ + ("qwen4exp.block_count", 48u32), + ("qwen4exp.embedding_length", 2560), + ("qwen4exp.attention.head_count", 24), + ("qwen4exp.attention.head_count_kv", 2), + ("qwen4exp.expert_count", 512), + ("qwen4exp.expert_used_count", 10), + ]; + let write = |entries: Vec<(&str, u32, Vec)>| { + let mut data = b"GGUF".to_vec(); + data.extend(3u32.to_le_bytes()); + data.extend(0u64.to_le_bytes()); + data.extend((entries.len() as u64 + 1).to_le_bytes()); + string(&mut data, "general.architecture"); + data.extend(8u32.to_le_bytes()); + string(&mut data, "qwen4exp"); + for (key, kind, bytes) in entries { + string(&mut data, key); + data.extend(kind.to_le_bytes()); + data.extend(bytes); + } + data.resize(data.len().div_ceil(32) * 32, 0); + std::fs::write(&path, data).unwrap(); + }; + let good = || { + fields + .iter() + .map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())) + .collect::>() + }; + write(good()); + check_flash_next_profile(&path).unwrap(); + for index in 0..fields.len() { + let mut entries = good(); + entries.remove(index); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[index].0) + ); + let mut entries = good(); + entries[index].2 = 0u32.to_le_bytes().to_vec(); + write(entries); + assert!(check_flash_next_profile(&path).is_err()); + } + for index in 0..4 { + let mut entries = good(); + entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("expected") + ); + } + for (kind, bytes) in [ + (7, vec![1]), + (6, 48f32.to_le_bytes().to_vec()), + (5, (-1i32).to_le_bytes().to_vec()), + (10, (1u64 << 32).to_le_bytes().to_vec()), + ] { + let mut entries = good(); + entries[0] = (fields[0].0, kind, bytes); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains(fields[0].0) + ); + } + let mut entries = good(); + entries[4].2 = 256u32.to_le_bytes().to_vec(); + write(entries); + check_flash_next_profile(&path).unwrap(); + let mut entries = good(); + entries[5].2 = 513u32.to_le_bytes().to_vec(); + write(entries); + assert!( + check_flash_next_profile(&path) + .unwrap_err() + .to_string() + .contains("exceeds") + ); + for kind in [0, 1, 2, 3, 4, 5, 10, 11] { + let mut entries = good(); + let bytes = 48u64.to_le_bytes(); + let n = match kind { + 0 | 1 => 1, + 2 | 3 => 2, + 4 | 5 => 4, + _ => 8, + }; + entries[0] = (fields[0].0, kind, bytes[..n].to_vec()); + write(entries); + check_flash_next_profile(&path).unwrap(); + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn inspects_header_and_rejects_truncated_payload() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen4exp"); + string(&mut gguf, "test.weight"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&4u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(128, 0); + gguf.extend_from_slice(&[0; 16]); + let path = std::env::temp_dir().join(format!("strata-gguf-test-{}", std::process::id())); + std::fs::write(&path, &gguf).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.tensors, 1); + assert_eq!(summary.architecture.as_deref(), Some("qwen4exp")); + assert_eq!(summary.types.get(&0), Some(&1)); + std::fs::write(&path, &gguf[..80]).unwrap(); + assert!(inspect(&path).is_err()); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&2u64.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + string(&mut gguf, "norm"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&4u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + let shape_at = gguf.len(); + gguf.extend_from_slice(&256u64.to_le_bytes()); + let kind_at = gguf.len(); + gguf.extend_from_slice(&21u32.to_le_bytes()); + let offset_at = gguf.len(); + gguf.extend_from_slice(&32u64.to_le_bytes()); + let data_start = gguf.len().div_ceil(32) * 32; + gguf.resize(data_start, 0); + gguf.extend_from_slice(&[0u8; 16]); + gguf.extend_from_slice(&[0u8; 16]); + gguf.extend_from_slice(&[0u8; 110]); + let path = std::env::temp_dir().join(format!("strata-gguf-index-{}", std::process::id())); + std::fs::write(&path, &gguf).unwrap(); + let index = tensor_index(&path).unwrap(); + assert_eq!(index.summary.data_start, data_start as u64); + assert_eq!(index.tensors[0].bytes, 16); + assert_eq!(index.tensors[1].offset, 32); + assert_eq!(index.tensors[1].bytes, 110); + let expected: [u8; 32] = Sha256::digest([0u8; 110]).into(); + assert_eq!(tensor_sha256(&path, &index, 1).unwrap(), expected); + + gguf[offset_at..offset_at + 8].copy_from_slice(&0u64.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + gguf[offset_at..offset_at + 8].copy_from_slice(&32u64.to_le_bytes()); + gguf[shape_at..shape_at + 8].copy_from_slice(&255u64.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + gguf[shape_at..shape_at + 8].copy_from_slice(&256u64.to_le_bytes()); + gguf[kind_at..kind_at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + std::fs::write(&path, &gguf).unwrap(); + assert!(tensor_index(&path).is_err()); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/gguf_f32_stream.rs b/control-plane/src/gguf_f32_stream.rs new file mode 100644 index 00000000..ad2a35f4 --- /dev/null +++ b/control-plane/src/gguf_f32_stream.rs @@ -0,0 +1,161 @@ +//! Bounded GGUF tensor decoding for native preparation. The callback receives +//! source bytes and the corresponding little-endian virtual F32 bytes. + +use std::io::{Read, Seek, SeekFrom}; + +use crate::{ggml_bridge, gguf, iq3_s, kar_codec}; + +pub const SOURCE_CHUNK_BYTES: usize = 256 * iq3_s::BLOCK_BYTES; + +#[repr(align(16))] +struct AlignedSource([u8; SOURCE_CHUNK_BYTES]); + +pub fn visit( + reader: &mut R, + absolute_offset: u64, + source_kind: u32, + source_bytes: u64, + mut callback: F, +) -> Result +where + R: Read + Seek, + F: FnMut(&[u8], &[u8]) -> Result<(), String>, +{ + let (block_elements, block_bytes) = gguf::block_geometry(source_kind) + .ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?; + let block_bytes = usize::try_from(block_bytes).map_err(|_| "GGUF block is too large")?; + if block_bytes > SOURCE_CHUNK_BYTES { + return Err("GGUF block exceeds bounded source chunk".into()); + } + if source_bytes == 0 || !source_bytes.is_multiple_of(block_bytes as u64) { + return Err("GGUF source tensor is empty or not block-aligned".into()); + } + reader + .seek(SeekFrom::Start(absolute_offset)) + .map_err(|error| error.to_string())?; + let mut raw = Box::new(AlignedSource([0u8; SOURCE_CHUNK_BYTES])); + let mut derived = Vec::with_capacity(512 * 1024); + let mut decoded = Vec::::new(); + let mut remaining = source_bytes; + let mut derived_bytes = 0u64; + while remaining != 0 { + let chunk_bytes = SOURCE_CHUNK_BYTES / block_bytes * block_bytes; + let count = remaining.min(chunk_bytes as u64) as usize; + reader + .read_exact(&mut raw.0[..count]) + .map_err(|error| error.to_string())?; + let source = &raw.0[..count]; + derived.clear(); + match source_kind { + 0 => callback(source, source)?, + 1 | 30 => { + for pair in source.as_chunks::<2>().0 { + let bits = u16::from_le_bytes(*pair); + let value = if source_kind == 1 { + kar_codec::f16_bits_to_f32(bits) + } else { + f32::from_bits(u32::from(bits) << 16) + }; + derived.extend_from_slice(&value.to_le_bytes()); + } + callback(source, &derived)?; + } + 21 => { + for block in source.as_chunks::<{ iq3_s::BLOCK_BYTES }>().0 { + for value in iq3_s::decode_block(block)? { + derived.extend_from_slice(&value.to_le_bytes()); + } + } + callback(source, &derived)?; + } + _ => { + let values = (count / block_bytes) + .checked_mul(block_elements as usize) + .ok_or("GGUF decoded chunk size overflow")?; + decoded.resize(values, 0.0); + ggml_bridge::decode_into(source_kind, source, &mut decoded[..values])?; + for value in &decoded[..values] { + derived.extend_from_slice(&value.to_le_bytes()); + } + callback(source, &derived)?; + } + } + let output_count = if source_kind == 0 { + count + } else { + derived.len() + }; + derived_bytes = derived_bytes + .checked_add(output_count as u64) + .ok_or("GGUF derived F32 byte count overflow")?; + remaining -= count as u64; + } + Ok(derived_bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn iq3_stream_spans_chunks_with_bounded_buffers() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut source = block.repeat(257); + let mut cursor = Cursor::new(&source); + let mut chunks = Vec::new(); + let output_bytes = visit(&mut cursor, 0, 21, source.len() as u64, |raw, decoded| { + assert!(raw.len() <= SOURCE_CHUNK_BYTES); + assert!(decoded.len() <= 256 * iq3_s::BLOCK_ELEMENTS * 4); + assert!( + decoded + .as_chunks::<4>() + .0 + .iter() + .all(|v| *v == 1f32.to_le_bytes()) + ); + chunks.push((raw.len(), decoded.len())); + Ok(()) + }) + .unwrap(); + assert_eq!(chunks, [(SOURCE_CHUNK_BYTES, 262_144), (110, 1024)]); + assert_eq!(output_bytes, 257 * 256 * 4); + source.pop(); + assert!( + visit( + &mut Cursor::new(source), + 0, + 21, + (257 * 110 - 1) as u64, + |_, _| Ok(()) + ) + .is_err() + ); + } + + #[test] + fn actual_target_quant_types_decode_one_block_each() { + for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + let source = vec![0u8; bytes as usize]; + let mut output = Vec::new(); + let count = visit(&mut Cursor::new(&source), 0, kind, bytes, |raw, derived| { + assert_eq!(raw.len() as u64, bytes); + output.extend_from_slice(derived); + Ok(()) + }) + .unwrap(); + assert_eq!(count, elements * 4, "kind {kind}"); + assert_eq!(output.len() as u64, elements * 4, "kind {kind}"); + assert!( + output + .as_chunks::<4>() + .0 + .iter() + .all(|word| f32::from_le_bytes(*word).is_finite()), + "kind {kind}" + ); + } + } +} diff --git a/control-plane/src/history_store.rs b/control-plane/src/history_store.rs new file mode 100644 index 00000000..07c86935 --- /dev/null +++ b/control-plane/src/history_store.rs @@ -0,0 +1,224 @@ +//! Explicitly opted-in, single-operator plaintext history. No payload logging. +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicBool, Ordering}, +}; + +pub(crate) struct Store { + directory: PathBuf, + directory_handle: File, + _lock: File, + failed: AtomicBool, +} + +const SNAPSHOT: &str = "history-v1.json"; +const STAGE: &str = "history-v1.pending"; +pub(crate) const MAX_SNAPSHOT_BYTES: u64 = 129 * 1024 * 1024; + +impl Store { + #[cfg(unix)] + pub(crate) fn open(directory: &Path) -> Result { + use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; + if !directory.is_absolute() || directory.file_name().is_none() { + return Err("response_history_dir must be an absolute non-root path"); + } + match fs::DirBuilder::new().mode(0o700).create(directory) { + Ok(()) => (), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (), + Err(_) => { + return Err("cannot create private response history directory; parent must exist"); + } + } + let metadata = + fs::symlink_metadata(directory).map_err(|_| "cannot inspect history directory")?; + if !metadata.is_dir() + || metadata.file_type().is_symlink() + || metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o777 != 0o700 + { + return Err( + "history directory must be owned by this user with mode 0700, not a symlink", + ); + } + let directory = directory + .canonicalize() + .map_err(|_| "cannot resolve history directory")?; + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(directory.join("history.lock")) + .map_err(|_| "cannot open history lock")?; + private_file(&lock)?; + lock.try_lock() + .map_err(|_| "response history is already in use or cannot be locked")?; + let store = Self { + directory_handle: File::open(&directory) + .map_err(|_| "cannot open history directory")?, + directory, + _lock: lock, + failed: AtomicBool::new(false), + }; + // The only disposable file is our unpublished stage, after taking the lock. + let stage = store.directory.join(STAGE); + match fs::symlink_metadata(&stage) { + Ok(_) => { + drop(open_private(&stage)?); + fs::remove_file(stage).map_err(|_| "cannot clean interrupted history stage")?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(_) => return Err("cannot inspect history stage"), + } + // Persist creation of the private directory before acknowledging any data. + File::open( + store + .directory + .parent() + .ok_or("history directory has no parent")?, + ) + .and_then(|f| f.sync_all()) + .map_err(|_| "cannot flush history parent directory")?; + Ok(store) + } + + #[cfg(not(unix))] + pub(crate) fn open(_: &Path) -> Result { + Err("durable response history currently requires Unix private-file semantics") + } + + pub(crate) fn read(&self) -> Result>, &'static str> { + let path = self.directory.join(SNAPSHOT); + match fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(_) => return Err("cannot inspect history snapshot"), + Ok(_) => (), + } + let file = open_private(&path)?; + if file + .metadata() + .map_err(|_| "cannot inspect history snapshot")? + .len() + > MAX_SNAPSHOT_BYTES + { + return Err("history snapshot exceeds size limit"); + } + let mut bytes = Vec::new(); + file.take(MAX_SNAPSHOT_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| "cannot read history snapshot")?; + if bytes.len() as u64 > MAX_SNAPSHOT_BYTES { + return Err("history snapshot exceeds size limit"); + } + Ok(Some(bytes)) + } + + pub(crate) fn write(&self, bytes: &[u8]) -> Result<(), &'static str> { + if self.failed.load(Ordering::Acquire) { + return Err("history storage failed; restart after repairing storage"); + } + if bytes.len() as u64 > MAX_SNAPSHOT_BYTES { + return Err("history snapshot exceeds size limit"); + } + let result = self.publish(bytes); + if result.is_err() { + // A directory fsync failure after rename has an uncertain durability + // outcome. Never permit subsequent commits to overwrite that outcome. + self.failed.store(true, Ordering::Release); + } + result + } + + fn publish(&self, bytes: &[u8]) -> Result<(), &'static str> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let current = fs::symlink_metadata(&self.directory) + .map_err(|_| "history directory disappeared")?; + let original = self + .directory_handle + .metadata() + .map_err(|_| "cannot inspect history directory")?; + if current.dev() != original.dev() + || current.ino() != original.ino() + || !current.is_dir() + || current.mode() & 0o777 != 0o700 + || current.uid() != unsafe { libc::geteuid() } + { + return Err("history directory identity or private permissions changed"); + } + } + let path = self.directory.join(SNAPSHOT); + if fs::symlink_metadata(&path).is_ok() { + drop(open_private(&path)?); + } + let stage = self.directory.join(STAGE); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let mut file = options + .open(&stage) + .map_err(|_| "cannot stage response history snapshot")?; + let result = (|| { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(0o600)) + .map_err(|_| "cannot set private history snapshot permissions")?; + private_file(&file)?; + } + file.write_all(bytes) + .and_then(|_| file.sync_all()) + .map_err(|_| "cannot flush response history snapshot")?; + fs::rename(&stage, &path).map_err(|_| "cannot publish response history snapshot")?; + self.directory_handle + .sync_all() + .map_err(|_| "history commit durability uncertain; restart and inspect storage")?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_file(stage); + } + result + } +} + +#[cfg(unix)] +fn private_file(file: &File) -> Result<(), &'static str> { + use std::os::unix::fs::MetadataExt; + let meta = file.metadata().map_err(|_| "cannot inspect history file")?; + if !meta.is_file() + || meta.uid() != unsafe { libc::geteuid() } + || meta.mode() & 0o777 != 0o600 + || meta.nlink() != 1 + { + return Err( + "history files must be private owned regular files with mode 0600 and one link", + ); + } + Ok(()) +} + +fn open_private(path: &Path) -> Result { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options + .open(path) + .map_err(|_| "cannot open private history file")?; + #[cfg(unix)] + private_file(&file)?; + Ok(file) +} diff --git a/control-plane/src/immutable_directory.rs b/control-plane/src/immutable_directory.rs new file mode 100644 index 00000000..fe0be714 --- /dev/null +++ b/control-plane/src/immutable_directory.rs @@ -0,0 +1,166 @@ +//! Atomic publication of a new immutable directory. Existence checks alone +//! cannot protect an empty destination created immediately before rename. +use std::{io, path::Path}; + +pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> { + #[cfg(any(target_os = "linux", target_os = "macos"))] + { + use std::{ffi::CString, os::unix::ffi::OsStrExt}; + let source = CString::new(source.as_os_str().as_bytes())?; + let destination = CString::new(destination.as_os_str().as_bytes())?; + #[cfg(target_os = "linux")] + let result = unsafe { + // Rust's bundled musl exposes no renameat2 wrapper. Use the same + // kernel primitive through syscall, with the target's syscall ID. + libc::syscall( + libc::SYS_renameat2, + libc::AT_FDCWD, + source.as_ptr(), + libc::AT_FDCWD, + destination.as_ptr(), + libc::RENAME_NOREPLACE, + ) + }; + #[cfg(target_os = "macos")] + let result = + unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) }; + if result == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + #[cfg(not(any(target_os = "linux", target_os = "macos")))] + { + let _ = (source, destination); + Err(io::Error::new( + io::ErrorKind::Unsupported, + "atomic no-replace directory publication requires Linux or macOS", + )) + } +} + +#[cfg(all(test, any(target_os = "linux", target_os = "macos")))] +mod tests { + use super::*; + use std::{ + fs, + os::unix::fs::{MetadataExt, symlink}, + path::PathBuf, + sync::{Arc, Barrier}, + }; + + struct Temporary(PathBuf); + impl Temporary { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "strata-publish-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temporary { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn conflicts_preserve_even_empty_destination_and_source() { + let root = Temporary::new(); + let source = root.0.join("stage"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("payload"), b"complete bytes").unwrap(); + for kind in ["empty", "nonempty", "file", "symlink", "dangling"] { + let target = root.0.join(kind); + match kind { + "empty" => fs::create_dir(&target).unwrap(), + "nonempty" => { + fs::create_dir(&target).unwrap(); + fs::write(target.join("original"), b"keep").unwrap(); + } + "file" => fs::write(&target, b"keep").unwrap(), + "symlink" => symlink(&source, &target).unwrap(), + _ => symlink(root.0.join("absent"), &target).unwrap(), + } + let before = fs::symlink_metadata(&target).unwrap(); + assert_eq!( + publish(&source, &target).unwrap_err().kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!(fs::symlink_metadata(&target).unwrap().ino(), before.ino()); + assert_eq!(fs::read(source.join("payload")).unwrap(), b"complete bytes"); + match kind { + "empty" => assert_eq!(fs::read_dir(&target).unwrap().count(), 0), + "nonempty" => assert_eq!(fs::read(target.join("original")).unwrap(), b"keep"), + "file" => assert_eq!(fs::read(&target).unwrap(), b"keep"), + _ => assert!( + fs::symlink_metadata(&target) + .unwrap() + .file_type() + .is_symlink() + ), + } + } + #[cfg(target_os = "linux")] + let target = { + use std::os::unix::ffi::OsStringExt; + root.0 + .join(std::ffi::OsString::from_vec(b"pack-\xff".to_vec())) + }; + // APFS rejects invalid UTF-8 filenames independently of rename flags. + #[cfg(target_os = "macos")] + let target = root.0.join("pack-версія one"); + publish(&source, &target).unwrap(); + assert!(!source.exists()); + assert_eq!(fs::read(target.join("payload")).unwrap(), b"complete bytes"); + } + + #[test] + fn concurrent_publish_has_one_complete_winner() { + let root = Temporary::new(); + let target = root.0.join("version"); + let barrier = Arc::new(Barrier::new(2)); + let mut handles = Vec::new(); + for number in 0..2u8 { + let source = root.0.join(format!("stage-{number}")); + fs::create_dir(&source).unwrap(); + fs::write(source.join("payload"), vec![number; 1024]).unwrap(); + fs::write(source.join("receipt"), [number]).unwrap(); + let target = target.clone(); + let barrier = barrier.clone(); + handles.push(std::thread::spawn(move || { + barrier.wait(); + (number, source.clone(), publish(&source, &target)) + })); + } + let results = handles + .into_iter() + .map(|h| h.join().unwrap()) + .collect::>(); + assert_eq!(results.iter().filter(|(_, _, r)| r.is_ok()).count(), 1); + let (winner, source, _) = results.iter().find(|(_, _, r)| r.is_ok()).unwrap(); + assert!(!source.exists()); + assert_eq!( + fs::read(target.join("payload")).unwrap(), + vec![*winner; 1024] + ); + assert_eq!(fs::read(target.join("receipt")).unwrap(), [*winner]); + let (loser, source, error) = results.iter().find(|(_, _, r)| r.is_err()).unwrap(); + assert_eq!( + error.as_ref().unwrap_err().kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!( + fs::read(source.join("payload")).unwrap(), + vec![*loser; 1024] + ); + assert_eq!(fs::read(source.join("receipt")).unwrap(), [*loser]); + } +} diff --git a/control-plane/src/iq3_s.rs b/control-plane/src/iq3_s.rs new file mode 100644 index 00000000..aca002db --- /dev/null +++ b/control-plane/src/iq3_s.rs @@ -0,0 +1,111 @@ +//! Bounded CPU decoder for ggml IQ3_S source blocks (256 values / 110 bytes). +//! Layout and grid are pinned to Strata upstream d9ab8435. This is preparation +//! code, not a serving kernel; numerical parity with a real model is pending. + +use crate::{iq3s_grid::IQ3S_GRID, kar_codec::f16_bits_to_f32}; + +pub const BLOCK_BYTES: usize = 110; +pub const BLOCK_ELEMENTS: usize = 256; + +pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> { + let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]])); + if !base.is_finite() { + return Err("IQ3_S block has a non-finite scale".into()); + } + let mut output = [0.0f32; BLOCK_ELEMENTS]; + for subblock in 0..8 { + let high = block[66 + subblock]; + let packed_scale = block[106 + subblock / 2]; + let nibble = (packed_scale >> (4 * (subblock % 2))) & 0x0f; + let scale = base * f32::from(1 + 2 * nibble); + for quartet_pair in 0..4 { + let signs = block[74 + 4 * subblock + quartet_pair]; + for half in 0..2 { + let part = 2 * quartet_pair + half; + let low = usize::from(block[2 + 8 * subblock + part]); + let high_bit = usize::from((high >> part) & 1) << 8; + let grid = IQ3S_GRID[low | high_bit].to_le_bytes(); + for (within, magnitude) in grid.iter().enumerate() { + let local = 4 * half + within; + let destination = 32 * subblock + 8 * quartet_pair + local; + let value = scale * f32::from(*magnitude); + output[destination] = if signs & (1 << local) != 0 { + -value + } else { + value + }; + } + } + } + } + Ok(output) +} + +pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> { + if !blocks.len().is_multiple_of(BLOCK_BYTES) + || (blocks.len() / BLOCK_BYTES) + .checked_mul(BLOCK_ELEMENTS) + .is_none_or(|expected| expected != output.len()) + { + return Err("IQ3_S block and output lengths do not match".into()); + } + for (block, values) in blocks + .as_chunks::() + .0 + .iter() + .zip(output.as_chunks_mut::().0.iter_mut()) + { + values.copy_from_slice(&decode_block(block)?); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use sha2::{Digest, Sha256}; + + #[test] + fn decodes_constant_and_pinned_mixed_block() { + let mut table_bytes = Vec::with_capacity(512 * 4); + for value in IQ3S_GRID { + table_bytes.extend_from_slice(&value.to_le_bytes()); + } + assert_eq!( + hex::encode(Sha256::digest(table_bytes)), + "bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f" + ); + let mut block = [0u8; BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + assert_eq!(decode_block(&block).unwrap(), [1.0; BLOCK_ELEMENTS]); + block[74] = 1; + let values = decode_block(&block).unwrap(); + assert_eq!(values[0], -1.0); + assert_eq!(values[1], 1.0); + let mut blocks = [0u8; BLOCK_BYTES * 2]; + blocks[..BLOCK_BYTES].copy_from_slice(&block); + blocks[BLOCK_BYTES..BLOCK_BYTES + 2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let mut decoded = [0.0f32; BLOCK_ELEMENTS * 2]; + decode_into(&blocks, &mut decoded).unwrap(); + assert_eq!(decoded[0], -1.0); + assert_eq!(decoded[BLOCK_ELEMENTS], 1.0); + let mut mixed = [0u8; BLOCK_BYTES]; + for (index, byte) in mixed.iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(73).wrapping_add(19); + } + mixed[..2].copy_from_slice(&0x3800u16.to_le_bytes()); + let values = decode_block(&mixed).unwrap(); + assert_eq!(&values[..4], &[-94.5, 67.5, -67.5, -148.5]); + let mut bytes = Vec::with_capacity(BLOCK_ELEMENTS * 4); + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } + assert_eq!( + hex::encode(Sha256::digest(bytes)), + "cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec" + ); + mixed[..2].copy_from_slice(&0x7c00u16.to_le_bytes()); + assert!(decode_block(&mixed).is_err()); + assert!(decode_into(&mixed[..109], &mut [0.0; BLOCK_ELEMENTS]).is_err()); + } +} diff --git a/control-plane/src/iq3s_grid.rs b/control-plane/src/iq3s_grid.rs new file mode 100644 index 00000000..a7586b42 --- /dev/null +++ b/control-plane/src/iq3s_grid.rs @@ -0,0 +1,71 @@ +// iq3s_grid from ggml-common.h at Strata upstream d9ab8435f654c368c586340d490915f6addf56a3. +// Copyright (c) 2023-2026 The ggml authors. MIT License. +// See engine/strata/third_party/ggml/LICENSE for the full license text. +// This table is pinned to the imported upstream revision; do not regenerate silently. + +pub const IQ3S_GRID: [u32; 512] = [ + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, + 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, + 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, + 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, + 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, + 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, + 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, + 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, + 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, + 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, + 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, + 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, + 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, + 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, + 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, + 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, + 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, + 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, + 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, + 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, + 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, + 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, + 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, + 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, + 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, + 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, + 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, + 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, + 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, + 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, + 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, + 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, + 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, + 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, + 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, + 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, + 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, + 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, + 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, + 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, + 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, + 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, + 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, + 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, + 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, + 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, + 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, + 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, + 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, + 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, + 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, + 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, + 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, + 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, + 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, + 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, + 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, +]; diff --git a/control-plane/src/kar.rs b/control-plane/src/kar.rs new file mode 100644 index 00000000..94b3d9ce --- /dev/null +++ b/control-plane/src/kar.rs @@ -0,0 +1,983 @@ +//! Bounded KAR-2 metadata inspector. Payload CRC validation and decoding are separate work. + +use std::{ + collections::HashSet, + fs::File, + io::{Read, Seek, SeekFrom}, + path::{Component, Path}, +}; + +use sha2::{Digest, Sha256}; + +use crate::{kar_codec, model::Manifest}; + +const HEADER_BYTES: usize = 256; +const RECORD_BYTES: usize = 192; +const MAX_TENSORS: usize = 100_000; +const MAX_NAMES: usize = 64 * 1024 * 1024; + +#[derive(Debug, PartialEq)] +pub struct Summary { + pub archive_bytes: u64, + pub tensor_count: u32, + pub total_elements: u64, + pub source_total_elements: u64, + pub accounted_bpw: f64, + pub source_digest: [u8; 32], + pub source_bytes: u64, + pub max_planes: u8, +} + +#[derive(Debug)] +pub struct TensorSource { + pub name: String, + pub dimensions: Vec, + pub dtype: u8, + pub digest: [u8; 32], + pub offset: u64, + pub section_bytes: u64, + pub storage_class: u8, + pub n_elements: u64, + pub planes_min: u8, + pub planes_max: u8, + pub section_offset: u64, + pub planes_offset: u64, + pub plane_stride_bytes: u32, +} + +impl TensorSource { + /// The bytes libkar::kar_reserve stages for this record at the requested + /// level. RAW records have no precision dial and always stage in full. + pub fn gpu_resident_bytes(&self, level: u8) -> Result { + if self.storage_class == 1 { + return Ok(self.section_bytes); + } + if !(1..=8).contains(&level) || level < self.planes_min || level > self.planes_max { + return Err(format!( + "{}: KAR level {level} is outside its supported dial", + self.name + )); + } + self.planes_offset + .checked_sub(self.section_offset) + .and_then(|prefix| { + prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)) + }) + .filter(|bytes| *bytes <= self.section_bytes) + .ok_or_else(|| format!("{}: invalid KAR GPU prefix size", self.name)) + } + + pub fn gpu_decode_bytes(&self) -> Result { + self.n_elements + .checked_mul(4) + .ok_or_else(|| format!("{}: KAR F32 decode size overflow", self.name)) + } + + /// One-row output size for a geometrically addressable NESTED table. + /// Whether the model can consume only selected rows is a separate question. + pub fn gpu_one_row_decode_bytes(&self) -> Option { + let row_len = *self.dimensions.first()?; + if self.storage_class == 0 + && self.dimensions.len() >= 2 + && row_len.is_multiple_of(32) + && row_len <= u32::MAX as u64 + && self.n_elements > row_len + && self.n_elements.is_multiple_of(row_len) + { + row_len.checked_mul(4) + } else { + None + } + } +} + +/// CPU quality oracle for repeated bounded reads from one verified archive. +/// Payload CRCs are checked once when opened; callers must keep the archive +/// immutable while this reader is alive. +pub struct VerifiedRangeDecoder { + file: File, + directory: Vec, + names: Vec, +} + +impl VerifiedRangeDecoder { + pub fn open(path: &Path) -> Result { + verify(path)?; + Self::open_previously_verified(path) + } + + /// Only for callers that have already verified the exact archive bytes. + pub(crate) fn open_previously_verified(path: &Path) -> Result { + inspect(path)?; + let mut file = File::open(path).map_err(|error| error.to_string())?; + let header = read_region(&mut file, 0, HEADER_BYTES)?; + let directory_bytes = u64::from(u32_at(&header, 32)) * RECORD_BYTES as u64; + let directory = read_region( + &mut file, + u64_at(&header, 24), + usize::try_from(directory_bytes).map_err(|_| "KAR directory is too large")?, + )?; + let names = read_region( + &mut file, + u64_at(&header, 40), + usize::try_from(u64_at(&header, 48)).map_err(|_| "KAR names are too large")?, + )?; + Ok(Self { + file, + directory, + names, + }) + } + + pub fn decode_range( + &mut self, + name: &str, + level: u8, + start: usize, + count: usize, + ) -> Result, String> { + let record = *self.record(name)?; + decode_record_range(&mut self.file, &record, level, start, count) + } + + pub fn element_count(&self, name: &str) -> Result { + usize::try_from(u64_at(self.record(name)?, 48)) + .map_err(|_| "KAR tensor is too large".into()) + } + + fn record(&self, name: &str) -> Result<&[u8; RECORD_BYTES], String> { + let (records, _) = self.directory.as_chunks::(); + records + .iter() + .find(|record| { + let start = u32_at(*record, 0) as usize; + let end = start + u16_at(*record, 4) as usize; + self.names.get(start..end) == Some(name.as_bytes()) + }) + .ok_or_else(|| format!("KAR tensor not found: {name}")) + } +} + +pub fn inspect(path: &Path) -> Result { + let (summary, _, _, _) = inspect_inner(path)?; + Ok(summary) +} + +pub fn inspect_with_sources(path: &Path) -> Result<(Summary, Vec), String> { + let (summary, _, _, sources) = inspect_inner(path)?; + Ok((summary, sources)) +} + +pub fn verify(path: &Path) -> Result { + Ok(verify_with_sources(path)?.0) +} + +/// Independently reconstruct one bounded nested tensor from the archived bytes. +/// This is a CPU validation path for preview archives, not a serving decoder. +pub fn decode_preview_tensor(path: &Path, name: &str, level: u8) -> Result, String> { + decode_tensor_inner(path, name, level, 0, None) +} + +/// Decode at most one million values from an arbitrary offset of a nested +/// tensor. Only the relevant scales and plane words are read into memory. +/// This is a CPU quality oracle, not a serving implementation. +pub fn decode_tensor_range( + path: &Path, + name: &str, + level: u8, + start: usize, + count: usize, +) -> Result, String> { + decode_tensor_inner(path, name, level, start, Some(count)) +} + +/// CPU parity oracle for one CUDA row-gather request. The entire archive is +/// verified before the bounded row is decoded. +pub fn decode_tensor_row( + path: &Path, + name: &str, + level: u8, + row_id: u32, +) -> Result, String> { + let (_, records) = inspect_with_sources(path)?; + let record = records + .iter() + .find(|record| record.name == name) + .ok_or_else(|| format!("KAR tensor not found: {name}"))?; + let row_len = usize::try_from( + *record + .dimensions + .first() + .ok_or("KAR tensor has no dimensions")?, + ) + .map_err(|_| "KAR row length is too large")?; + if record.storage_class != 0 + || row_len == 0 + || !row_len.is_multiple_of(32) + || row_len > 1_000_000 + { + return Err("CUDA row gather requires a compressed record with a row length divisible by 32 and at most one million values".into()); + } + let start = (row_id as usize) + .checked_mul(row_len) + .ok_or("KAR row offset overflow")?; + if start + .checked_add(row_len) + .is_none_or(|end| end as u64 > record.n_elements) + { + return Err("KAR row ID exceeds tensor bounds".into()); + } + decode_tensor_range(path, name, level, start, row_len) +} + +fn decode_tensor_inner( + path: &Path, + name: &str, + level: u8, + start: usize, + count: Option, +) -> Result, String> { + let mut decoder = VerifiedRangeDecoder::open(path)?; + let count = count.map_or_else(|| decoder.element_count(name), Ok)?; + decoder.decode_range(name, level, start, count) +} + +fn decode_record_range( + file: &mut File, + record: &[u8; RECORD_BYTES], + level: u8, + start: usize, + count: usize, +) -> Result, String> { + let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; + let end = start + .checked_add(count) + .ok_or("KAR decode range overflow")?; + if count == 0 || count > 1_000_000 || end > elements { + return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into()); + } + if record[7] == 1 { + if record[41] != 0 { + return Err("CPU quality oracle only supports RAW F32 tensors".into()); + } + let offset = u64_at(record, 112) + .checked_add( + (start as u64) + .checked_mul(4) + .ok_or("KAR raw offset overflow")?, + ) + .ok_or("KAR raw offset overflow")?; + let bytes = read_region( + file, + offset, + count.checked_mul(4).ok_or("KAR raw byte count overflow")?, + )?; + return Ok(bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)) + .collect()); + } + let stored = record[42]; + if level == 0 || level > stored { + return Err(format!("KAR tensor stores 1..={stored} levels")); + } + let group = u16_at(record, 46); + let group_size = usize::from(group); + if group_size == 0 { + return Err("KAR group is zero".into()); + } + let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?; + let base_group = start / group_size; + let end_group = end.div_ceil(group_size); + let base_element = base_group + .checked_mul(group_size) + .ok_or("KAR decode base overflow")?; + let local_padded = (end_group - base_group) + .checked_mul(group_size) + .ok_or("KAR decode padded size overflow")?; + if base_element + .checked_add(local_padded) + .is_none_or(|end| end > padded) + { + return Err("KAR decode range exceeds padded tensor".into()); + } + let scale_bytes = read_region( + file, + u64_at(record, 64) + .checked_add( + (base_group as u64) + .checked_mul(2) + .ok_or("KAR scale offset overflow")?, + ) + .ok_or("KAR scale offset overflow")?, + (end_group - base_group) + .checked_mul(2) + .ok_or("KAR scale byte count overflow")?, + )?; + let scales = scale_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let book_offset = u64_at(record, 80) + .checked_add((1u64 << (u32::from(level) + 1)) - 4) + .ok_or("KAR book offset overflow")?; + let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?; + let book = book_bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(); + let plane_stride = u64::from(u32_at(record, 104)); + let plane_bytes = local_padded / 32 * 4; + let plane_base = u64::try_from( + (base_element / 32) + .checked_mul(4) + .ok_or("KAR plane offset overflow")?, + ) + .map_err(|_| "KAR plane offset overflow")?; + let mut planes = Vec::with_capacity(usize::from(level)); + for plane in 0..u64::from(level) { + let offset = u64_at(record, 96) + .checked_add( + plane + .checked_mul(plane_stride) + .ok_or("KAR plane offset overflow")?, + ) + .and_then(|offset| offset.checked_add(plane_base)) + .ok_or("KAR plane offset overflow")?; + let bytes = read_region(file, offset, plane_bytes)?; + planes.push( + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + .collect::>(), + ); + } + let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); + let mut output = vec![0.0f32; count]; + kar_codec::decode_range( + &scales, + &book, + &plane_refs, + group, + start - base_element, + &mut output, + )?; + Ok(output) +} + +pub fn f32_fnv1a64(values: &[f32]) -> u64 { + values + .iter() + .flat_map(|value| value.to_le_bytes()) + .fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3) + }) +} + +pub fn verify_with_sources(path: &Path) -> Result<(Summary, Vec), String> { + let (summary, mut file, sections, sources) = inspect_inner(path)?; + let mut buffer = vec![0; 8 * 1024 * 1024]; + for (index, section) in sections.iter().enumerate() { + file.seek(SeekFrom::Start(section.offset)) + .map_err(|error| error.to_string())?; + let mut remaining = section.bytes; + let mut crc = !0u32; + while remaining > 0 { + let length = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..length]) + .map_err(|error| error.to_string())?; + crc = crc32_step(crc, &buffer[..length]); + remaining -= length as u64; + } + if !crc != section.crc32 { + return Err(format!("KAR tensor {index} payload CRC-32 mismatch")); + } + } + Ok((summary, sources)) +} + +pub fn verify_source_files( + summary: &Summary, + manifest: &Manifest, + source_dir: &Path, +) -> Result<(), String> { + let mut files = manifest.files.iter().collect::>(); + if files.is_empty() { + return Err("source manifest has no files".into()); + } + files.sort_unstable_by(|left, right| left.name.as_bytes().cmp(right.name.as_bytes())); + let mut combined = Sha256::new(); + let mut total = 0u64; + let mut buffer = vec![0; 8 * 1024 * 1024]; + for entry in files { + let mut components = Path::new(&entry.name).components(); + if !matches!(components.next(), Some(Component::Normal(_))) || components.next().is_some() { + return Err("source manifest contains an invalid file name".into()); + } + let mut file = File::open(source_dir.join(&entry.name)) + .map_err(|error| format!("{}: {error}", entry.name))?; + let size = file.metadata().map_err(|error| error.to_string())?.len(); + if size != entry.size { + return Err(format!("{}: source size differs from manifest", entry.name)); + } + total = total + .checked_add(size) + .ok_or("source byte count overflow")?; + let mut individual = Sha256::new(); + loop { + let read = file.read(&mut buffer).map_err(|error| error.to_string())?; + if read == 0 { + break; + } + individual.update(&buffer[..read]); + combined.update(&buffer[..read]); + } + if hex::encode(individual.finalize()) != entry.sha256.to_ascii_lowercase() { + return Err(format!( + "{}: source SHA-256 differs from manifest", + entry.name + )); + } + } + if total != summary.source_bytes || combined.finalize().as_slice() != summary.source_digest { + return Err("KAR source identity differs from verified manifest shards".into()); + } + Ok(()) +} + +struct Section { + offset: u64, + bytes: u64, + crc32: u32, +} + +fn inspect_inner(path: &Path) -> Result<(Summary, File, Vec
, Vec), String> { + let mut file = File::open(path).map_err(|error| error.to_string())?; + let file_bytes = file.metadata().map_err(|error| error.to_string())?.len(); + let header = read_region(&mut file, 0, HEADER_BYTES)?; + if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 { + return Err("unsupported KAR archive magic or version".into()); + } + if u32_at(&header, 12) != 0x04030201 + || u32_at(&header, 16) != HEADER_BYTES as u32 + || u32_at(&header, 20) != RECORD_BYTES as u32 + { + return Err("invalid KAR byte order or record size".into()); + } + if crc32(&header[..192]) != u32_at(&header, 192) { + return Err("KAR header CRC-32 mismatch".into()); + } + let directory_offset = u64_at(&header, 24); + let tensor_count = u32_at(&header, 32); + let string_offset = u64_at(&header, 40); + let string_bytes = u64_at(&header, 48); + let payload_offset = u64_at(&header, 56); + let archive_bytes = u64_at(&header, 64); + let total_elements = u64_at(&header, 72); + let payload_bits = u64_at(&header, 80); + let source_total_elements = u64_at(&header, 88); + let source_bytes = u64_at(&header, 120); + let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap()); + let mut source_digest = [0; 32]; + source_digest.copy_from_slice(&header[128..160]); + if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 { + return Err("KAR archive length mismatch".into()); + } + if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 { + return Err("KAR metadata exceeds bounded inspector limits".into()); + } + if u32_at(&header, 36) != 0 + || header[106] != 1 + || total_elements == 0 + || total_elements > source_total_elements + || source_bytes == 0 + { + return Err("invalid KAR flags, digest algorithm, or element counts".into()); + } + let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64; + if !accounted_bpw.is_finite() + || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) + { + return Err("KAR accounted_bpw does not match archive size".into()); + } + let directory_bytes = (tensor_count as u64) + .checked_mul(RECORD_BYTES as u64) + .ok_or("KAR directory length overflow")?; + let directory_end = directory_offset + .checked_add(directory_bytes) + .ok_or("KAR directory overflow")?; + let string_end = string_offset + .checked_add(string_bytes) + .ok_or("KAR string table overflow")?; + if !directory_offset.is_multiple_of(64) + || !string_offset.is_multiple_of(64) + || !payload_offset.is_multiple_of(256) + || directory_offset < HEADER_BYTES as u64 + || directory_end > string_offset + || string_end > payload_offset + || payload_offset > archive_bytes + { + return Err("invalid KAR metadata offsets or alignment".into()); + } + let names = read_region(&mut file, string_offset, string_bytes as usize)?; + let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?; + let mut digest = Sha256::new(); + digest.update(&names); + digest.update(&directory); + if digest.finalize().as_slice() != &header[160..192] { + return Err("KAR directory digest mismatch".into()); + } + + let mut seen_names = HashSet::new(); + let mut elements_sum = 0u64; + let mut bits_sum = 0u64; + let mut previous_end = payload_offset; + let mut min_planes = u8::MAX; + let mut max_planes = 0u8; + let mut sections = Vec::with_capacity(tensor_count as usize); + let mut sources = Vec::with_capacity(tensor_count as usize); + let (records, remainder) = directory.as_chunks::(); + debug_assert!(remainder.is_empty()); + for record in records { + let name_start = u32_at(record, 0) as usize; + let name_len = u16_at(record, 4) as usize; + let name_end = name_start + .checked_add(name_len) + .ok_or("KAR name offset overflow")?; + if name_end >= names.len() || names[name_end] != 0 { + return Err("invalid KAR tensor name bounds".into()); + } + let name = std::str::from_utf8(&names[name_start..name_end]) + .map_err(|_| "KAR tensor name is not UTF-8")?; + if !seen_names.insert(name) { + return Err("duplicate KAR tensor name".into()); + } + let n_dims = record[6] as usize; + let storage = record[7]; + if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 { + return Err("unsupported KAR tensor layout".into()); + } + let dims = (0..4) + .map(|index| u64_at(record, 8 + index * 8)) + .collect::>(); + if dims[n_dims..].iter().any(|dim| *dim != 1) { + return Err("invalid KAR unused dimension".into()); + } + let product = dims[..n_dims] + .iter() + .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) + .ok_or("KAR tensor shape overflow")?; + let n_elements = u64_at(record, 48); + if product != n_elements || n_elements == 0 { + return Err("KAR tensor element count mismatch".into()); + } + elements_sum = elements_sum + .checked_add(n_elements) + .ok_or("KAR model element count overflow")?; + let mut source_digest = [0u8; 32]; + source_digest.copy_from_slice(&record[128..160]); + sources.push(TensorSource { + name: name.to_owned(), + dimensions: dims[..n_dims].to_vec(), + dtype: record[41], + digest: source_digest, + offset: u64_at(record, 160), + section_bytes: u64_at(record, 120), + storage_class: storage, + n_elements, + planes_min: record[43], + planes_max: record[44], + section_offset: u64_at(record, 112), + planes_offset: u64_at(record, 96), + plane_stride_bytes: u32_at(record, 104), + }); + let section_offset = u64_at(record, 112); + let section_bytes = u64_at(record, 120); + let section_end = section_offset + .checked_add(section_bytes) + .ok_or("KAR tensor section overflow")?; + if section_offset != previous_end + || !section_offset.is_multiple_of(256) + || section_end > archive_bytes + { + return Err("KAR tensor sections are not contiguous or bounded".into()); + } + previous_end = section_end; + sections.push(Section { + offset: section_offset, + bytes: section_bytes, + crc32: u32_at(record, 108), + }); + if storage == 0 { + let group = u16_at(record, 46) as u64; + let planes = record[42]; + let n_padded = u64_at(record, 56); + if group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || !(1..=16).contains(&planes) + || record[43] == 0 + || record[43] > record[44] + || record[44] > planes + || record[45] > 1 + { + return Err("invalid KAR nested tensor parameters".into()); + } + let rounded = n_elements + .div_ceil(group) + .checked_mul(group) + .ok_or("KAR padded count overflow")?; + if n_padded != rounded { + return Err("KAR padded tensor count mismatch".into()); + } + let scales_offset = u64_at(record, 64); + let scales_bytes = u64_at(record, 72); + let books_offset = u64_at(record, 80); + let books_bytes = u64_at(record, 88); + let planes_offset = u64_at(record, 96); + let stride = u32_at(record, 104) as u64; + let expected_scales = (n_padded / group) + .checked_mul(2) + .ok_or("KAR scale count overflow")?; + let expected_books = (1u64 << (planes as u32 + 2)) - 4; + let plane_words_bytes = (n_padded / 32) + .checked_mul(4) + .ok_or("KAR plane size overflow")?; + let expected_stride = + round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; + let books_start = scales_offset + .checked_add(scales_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR books offset overflow")?; + let planes_start = books_offset + .checked_add(books_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR planes offset overflow")?; + if scales_offset != section_offset + || scales_bytes != expected_scales + || books_offset != books_start + || books_bytes != expected_books + || planes_offset != planes_start + || stride != expected_stride + || planes_offset + .checked_add(planes as u64 * stride) + .is_none_or(|end| end > section_end) + { + return Err("invalid KAR nested tensor section layout".into()); + } + let tensor_bits = (planes as u64) + .checked_mul(n_padded) + .and_then(|bits| { + (n_padded / group) + .checked_mul(16) + .and_then(|scale_bits| bits.checked_add(scale_bits)) + }) + .ok_or("KAR tensor bit count overflow")?; + bits_sum = bits_sum + .checked_add(tensor_bits) + .ok_or("KAR coded bit count overflow")?; + min_planes = min_planes.min(record[43]); + max_planes = max_planes.max(record[44]); + } else { + if record[42..48].iter().any(|value| *value != 0) + || u64_at(record, 56) != n_elements + || record[64..104].iter().any(|value| *value != 0) + || u32_at(record, 104) != 0 + { + return Err("invalid KAR raw tensor metadata".into()); + } + let width = if record[41] == 0 { 4 } else { 2 }; + if section_bytes + < n_elements + .checked_mul(width) + .ok_or("KAR raw tensor size overflow")? + { + return Err("KAR raw tensor section is too small".into()); + } + } + } + if previous_end != archive_bytes + || elements_sum != total_elements + || bits_sum != payload_bits + || header[104] != if min_planes == u8::MAX { 0 } else { min_planes } + || header[105] != max_planes + { + return Err("KAR aggregate metadata mismatch".into()); + } + let summary = Summary { + archive_bytes, + tensor_count, + total_elements, + source_total_elements, + accounted_bpw, + source_digest, + source_bytes, + max_planes, + }; + Ok((summary, file, sections, sources)) +} + +fn read_region(file: &mut File, offset: u64, length: usize) -> Result, String> { + file.seek(SeekFrom::Start(offset)) + .map_err(|error| error.to_string())?; + let mut bytes = vec![0; length]; + file.read_exact(&mut bytes) + .map_err(|error| error.to_string())?; + Ok(bytes) +} + +fn u16_at(bytes: &[u8], offset: usize) -> u16 { + u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap()) +} + +fn u32_at(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) +} + +fn u64_at(bytes: &[u8], offset: usize) -> u64 { + u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap()) +} + +pub(crate) fn crc32(bytes: &[u8]) -> u32 { + !crc32_step(!0u32, bytes) +} + +pub(crate) fn crc32_step(mut crc: u32, bytes: &[u8]) -> u32 { + for &byte in bytes { + crc ^= byte as u32; + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb88320u32 & (0u32.wrapping_sub(crc & 1))); + } + } + crc +} + +fn round_up(value: u64, alignment: u64) -> Option { + value.div_ceil(alignment).checked_mul(alignment) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::ModelFile; + use crate::{kar_codec, kar_writer}; + use std::fs; + + fn put_u32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + + fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + } + + #[test] + fn crc32_matches_iso_hdlc_reference() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + let first = crc32_step(!0, b"1234"); + assert_eq!(!crc32_step(first, b"56789"), 0xcbf4_3926); + } + + #[test] + fn source_identity_uses_verified_shards_in_filename_order() { + let root = std::env::temp_dir().join(format!("strata-kar-source-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + fs::write(root.join("b.gguf"), b"def").unwrap(); + fs::write(root.join("a.gguf"), b"abc").unwrap(); + let sha = |bytes: &[u8]| hex::encode(Sha256::digest(bytes)); + let manifest = Manifest { + schema_version: 1, + files: vec![ + ModelFile { + name: "b.gguf".into(), + url: "https://example.invalid/b".into(), + size: 3, + sha256: sha(b"def"), + }, + ModelFile { + name: "a.gguf".into(), + url: "https://example.invalid/a".into(), + size: 3, + sha256: sha(b"abc"), + }, + ], + }; + let mut digest = [0; 32]; + digest.copy_from_slice(&Sha256::digest(b"abcdef")); + let summary = Summary { + archive_bytes: 1, + tensor_count: 1, + total_elements: 1, + source_total_elements: 1, + accounted_bpw: 8.0, + source_digest: digest, + source_bytes: 6, + max_planes: 0, + }; + verify_source_files(&summary, &manifest, &root).unwrap(); + fs::write(root.join("b.gguf"), b"xyz").unwrap(); + assert!( + verify_source_files(&summary, &manifest, &root) + .unwrap_err() + .contains("SHA-256") + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn inspects_a_raw_archive_and_rejects_corruption() { + let mut archive = vec![0u8; 768]; + let payload_crc = crc32(&archive[512..]); + let (header, rest) = archive.split_at_mut(256); + let (directory, string_and_payload) = rest.split_at_mut(192); + let names = &mut string_and_payload[..7]; + names.copy_from_slice(b"weight\0"); + put_u32(directory, 0, 0); + directory[4..6].copy_from_slice(&6u16.to_le_bytes()); + directory[6] = 1; + directory[7] = 1; + for index in 0..4 { + put_u64(directory, 8 + index * 8, if index == 0 { 64 } else { 1 }); + } + put_u64(directory, 48, 64); + put_u64(directory, 56, 64); + put_u64(directory, 112, 512); + put_u64(directory, 120, 256); + put_u32(directory, 108, payload_crc); + + header[..8].copy_from_slice(b"KARCHIV2"); + put_u32(header, 8, 2); + put_u32(header, 12, 0x04030201); + put_u32(header, 16, 256); + put_u32(header, 20, 192); + put_u64(header, 24, 256); + put_u32(header, 32, 1); + put_u64(header, 40, 448); + put_u64(header, 48, 7); + put_u64(header, 56, 512); + put_u64(header, 64, 768); + put_u64(header, 72, 64); + put_u64(header, 88, 64); + put_u64(header, 120, 256); + header[96..104].copy_from_slice(&96f64.to_le_bytes()); + header[106] = 1; + let mut digest = Sha256::new(); + digest.update(names); + digest.update(directory); + header[160..192].copy_from_slice(&digest.finalize()); + let header_crc = crc32(&header[..192]); + put_u32(header, 192, header_crc); + + let path = std::env::temp_dir().join(format!("strata-kar-test-{}", std::process::id())); + fs::write(&path, &archive).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.tensor_count, 1); + assert_eq!(summary.accounted_bpw, 96.0); + assert_eq!(verify(&path).unwrap(), summary); + let mut decoder = VerifiedRangeDecoder::open(&path).unwrap(); + assert_eq!(decoder.element_count("weight").unwrap(), 64); + assert_eq!( + decoder.decode_range("weight", 0, 8, 4).unwrap(), + vec![0.0; 4] + ); + let mut nested = archive.clone(); + let (header, rest) = nested.split_at_mut(256); + let (directory, string_and_payload) = rest.split_at_mut(192); + directory[7] = 0; + put_u64(directory, 8, 32); + put_u64(directory, 48, 32); + put_u64(directory, 56, 32); + directory[42..45].fill(1); + directory[46..48].copy_from_slice(&32u16.to_le_bytes()); + put_u64(directory, 64, 512); + put_u64(directory, 72, 2); + put_u64(directory, 80, 528); + put_u64(directory, 88, 4); + put_u64(directory, 96, 544); + put_u32(directory, 104, 16); + put_u64(header, 72, 32); + put_u64(header, 80, 48); + put_u64(header, 88, 32); + header[96..104].copy_from_slice(&192f64.to_le_bytes()); + header[104..106].fill(1); + let mut digest = Sha256::new(); + digest.update(&string_and_payload[..7]); + digest.update(directory); + header[160..192].copy_from_slice(&digest.finalize()); + let header_crc = crc32(&header[..192]); + put_u32(header, 192, header_crc); + fs::write(&path, &nested).unwrap(); + let summary = inspect(&path).unwrap(); + assert_eq!(summary.accounted_bpw, 192.0); + assert_eq!(verify(&path).unwrap(), summary); + nested[512] ^= 1; + fs::write(&path, &nested).unwrap(); + assert_eq!(inspect(&path).unwrap(), summary); + assert!(verify(&path).unwrap_err().contains("payload CRC")); + + archive[300] ^= 1; + fs::write(&path, &archive).unwrap(); + assert!(inspect(&path).unwrap_err().contains("digest")); + archive.truncate(767); + fs::write(&path, &archive).unwrap(); + assert!(inspect(&path).unwrap_err().contains("length")); + fs::remove_file(path).unwrap(); + } + + #[test] + fn bounded_archive_range_decode_crosses_scale_and_plane_groups() { + let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(24); + let encoded = + kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2).unwrap(); + let book1 = [0xb800u16, 0x3800]; + let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let planes = encoded.planes.iter().map(Vec::as_slice).collect::>(); + let source = kar_writer::SourceIdentity { + name: "range-fixture", + architecture: "synthetic", + builder: "strata-next/kar-range-test", + digest: Sha256::digest(b"source").into(), + total_elements: 96, + bytes: 384, + }; + let tensor = [kar_writer::Tensor { + name: "expert", + dims: &[96], + source_dtype: 0, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &encoded.scales, + books: &books, + planes: &planes, + }, + }]; + let path = + std::env::temp_dir().join(format!("strata-kar-range-{}.kar", std::process::id())); + let _ = fs::remove_file(&path); + kar_writer::write_archive(&path, &source, &tensor).unwrap(); + let full = decode_preview_tensor(&path, "expert", 2).unwrap(); + for (start, count) in [(0, 1), (27, 10), (31, 34), (64, 32), (95, 1)] { + assert_eq!( + decode_tensor_range(&path, "expert", 2, start, count).unwrap(), + full[start..start + count] + ); + } + assert!(decode_tensor_range(&path, "expert", 2, 96, 1).is_err()); + assert!(decode_tensor_range(&path, "expert", 2, 0, 0).is_err()); + fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs new file mode 100644 index 00000000..bc047dd8 --- /dev/null +++ b/control-plane/src/kar_codec.rs @@ -0,0 +1,475 @@ +//! Experimental KAR scalar calibration, bit-plane encoding, and CPU decoding. +//! The caller selects samples and lossy rates; serving does not enable this path. + +pub struct EncodedPlanes { + pub scales: Vec, + /// Plane zero is the most significant index bit. Bit m of word w belongs + /// to weight 32*w+m, matching the koference CUDA decoder. + pub planes: Vec>, + pub padded_elements: usize, +} + +pub struct NormalizedTensor { + pub scales: Vec, + pub values: Vec, +} + +/// Normalize one finite f32 tensor using the exact rounded f16 group scales +/// that the KAR decoder will later multiply back in. +pub fn normalize_for_calibration(weights: &[f32], group: u16) -> Result { + let group = usize::from(group); + if weights.is_empty() + || group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || weights.iter().any(|value| !value.is_finite()) + { + return Err("invalid KAR normalization input".into()); + } + let padded = weights + .len() + .div_ceil(group) + .checked_mul(group) + .ok_or("KAR encoder padded size overflow")?; + let mut scales = Vec::with_capacity(padded / group); + let mut values = Vec::with_capacity(padded); + let mut normalized = vec![0.0f32; group]; + for group_index in 0..padded / group { + let start = group_index * group; + let end = (start + group).min(weights.len()); + let scale_bits = normalize_group_into(&weights[start..end], &mut normalized)?; + scales.push(scale_bits); + values.extend_from_slice(&normalized); + } + Ok(NormalizedTensor { scales, values }) +} + +/// Normalize one nonempty group into reusable, padded storage. +pub fn normalize_group_into(weights: &[f32], output: &mut [f32]) -> Result { + if weights.is_empty() + || weights.len() > output.len() + || output.is_empty() + || output.len() > 1024 + || !output.len().is_multiple_of(32) + || weights.iter().any(|value| !value.is_finite()) + { + return Err("invalid KAR normalization input".into()); + } + let maximum = weights + .iter() + .map(|value| value.abs()) + .fold(0.0f32, f32::max); + if maximum > 65504.0 || (maximum != 0.0 && maximum < f32::from_bits(0x3380_0000)) { + return Err("KAR scale overflows or underflows f16".into()); + } + let scale = if maximum == 0.0 { + f32::from_bits(0x3380_0000) + } else { + maximum + }; + let scale_bits = f32_to_f16_bits(scale); + let rounded_scale = f16_bits_to_f32(scale_bits); + if !rounded_scale.is_finite() || rounded_scale == 0.0 { + return Err("KAR rounded scale is invalid".into()); + } + for (position, value) in output.iter_mut().enumerate() { + *value = weights + .get(position) + .map_or(0.0, |weight| *weight / rounded_scale); + } + Ok(scale_bits) +} + +pub struct Calibration { + pub boundaries: Vec, + /// One f16 reconstruction table per level, from level 1 upward. + pub books: Vec>, +} + +/// Fit koference's top-down nested scalar partitions to an already selected, +/// normalized sample. Sampling policy and rate selection remain external. +pub fn fit_topdown(sample: &[f32], levels: u8) -> Result { + if !(1..=16).contains(&levels) + || sample.len() < (1usize << levels) + || sample.iter().any(|value| !value.is_finite()) + { + return Err("invalid KAR calibration sample or level count".into()); + } + let mut sorted = sample + .iter() + .map(|value| f64::from(*value)) + .collect::>(); + sorted.sort_unstable_by(f64::total_cmp); + let mut sums = Vec::with_capacity(sorted.len() + 1); + let mut squares = Vec::with_capacity(sorted.len() + 1); + sums.push(0.0); + squares.push(0.0); + for value in &sorted { + sums.push(sums.last().copied().unwrap() + value); + squares.push(squares.last().copied().unwrap() + value * value); + } + let mut cells = vec![(0usize, sorted.len())]; + let mut boundaries = Vec::with_capacity((1usize << levels) - 1); + for _ in 0..levels { + let mut next = Vec::with_capacity(cells.len() * 2); + for (lo, hi) in cells { + let mut best = None; + for middle in lo + 1..hi { + if sorted[middle - 1] == sorted[middle] { + continue; + } + let left_count = (middle - lo) as f64; + let right_count = (hi - middle) as f64; + let left_sum = sums[middle] - sums[lo]; + let right_sum = sums[hi] - sums[middle]; + let left_cost = squares[middle] - squares[lo] - left_sum * left_sum / left_count; + let right_cost = + squares[hi] - squares[middle] - right_sum * right_sum / right_count; + let cost = left_cost + right_cost; + if best.is_none_or(|(_, previous)| cost < previous) { + best = Some((middle, cost)); + } + } + let (middle, _) = best.ok_or("KAR calibration sample cannot split every cell")?; + boundaries.push(((sorted[middle - 1] + sorted[middle]) / 2.0) as f32); + next.push((lo, middle)); + next.push((middle, hi)); + } + cells = next; + } + boundaries.sort_unstable_by(f32::total_cmp); + if boundaries.windows(2).any(|pair| pair[0] >= pair[1]) { + return Err("KAR calibration boundaries collapse in f32".into()); + } + let finest = 1usize << levels; + let mut counts = vec![0usize; finest]; + let mut totals = vec![0f64; finest]; + for value in &sorted { + let index = boundaries.partition_point(|boundary| f64::from(*boundary) < *value); + counts[index] += 1; + totals[index] += value; + } + let mut books = vec![Vec::new(); usize::from(levels)]; + for level in (1..=usize::from(levels)).rev() { + books[level - 1] = counts + .iter() + .zip(&totals) + .map(|(count, total)| { + f64_to_f16_bits(if *count == 0 { + 0.0 + } else { + *total / *count as f64 + }) + }) + .collect(); + if level > 1 { + counts = counts + .as_chunks::<2>() + .0 + .iter() + .map(|pair| pair[0] + pair[1]) + .collect(); + totals = totals + .as_chunks::<2>() + .0 + .iter() + .map(|pair| pair[0] + pair[1]) + .collect(); + } + } + Ok(Calibration { boundaries, books }) +} + +/// Decode a bounded range from a selected KAR prefix. `book` is the f16 table +/// for exactly `planes.len()` levels; `start` is a flat element index. +pub fn decode_range( + scales: &[u16], + book: &[u16], + planes: &[&[u32]], + group: u16, + start: usize, + output: &mut [f32], +) -> Result<(), String> { + let group = usize::from(group); + if group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || !(1..=16).contains(&planes.len()) + || book.len() != 1usize << planes.len() + { + return Err("invalid KAR decoder geometry or book".into()); + } + let padded = scales + .len() + .checked_mul(group) + .ok_or("KAR decoder padded size overflow")?; + let end = start + .checked_add(output.len()) + .ok_or("KAR decoder range overflow")?; + if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) { + return Err("KAR decoder range or plane length is invalid".into()); + } + if scales[start / group..end.div_ceil(group)] + .iter() + .any(|bits| bits & 0x7c00 == 0x7c00) + || book.iter().any(|bits| bits & 0x7c00 == 0x7c00) + { + return Err("KAR decoder received non-finite f16 data".into()); + } + for (relative, value) in output.iter_mut().enumerate() { + let position = start + relative; + let mut index = 0usize; + for plane in planes { + let bit = (plane[position / 32] >> (position % 32)) & 1; + index = (index << 1) | bit as usize; + } + *value = f16_bits_to_f32(book[index]) * f16_bits_to_f32(scales[position / group]); + } + Ok(()) +} + +pub fn encode_with_boundaries( + weights: &[f32], + group: u16, + boundaries: &[f32], + levels: u8, +) -> Result { + if !(1..=16).contains(&levels) || boundaries.len() != (1usize << levels) - 1 { + return Err("invalid KAR encoder shape or calibration".into()); + } + if boundaries.iter().any(|value| !value.is_finite()) + || boundaries.windows(2).any(|pair| pair[0] >= pair[1]) + { + return Err("KAR encoder needs increasing finite boundaries".into()); + } + let normalized = normalize_for_calibration(weights, group)?; + let padded = normalized.values.len(); + let words = padded / 32; + let mut planes = vec![vec![0u32; words]; usize::from(levels)]; + for (position, value) in normalized.values.iter().enumerate() { + // NumPy searchsorted defaults to side='left': equality stays in + // the lower cell, as in koference's reference encoder. + let index = boundaries.partition_point(|boundary| *boundary < *value); + for (level, plane) in planes.iter_mut().enumerate() { + let bit = (index >> (usize::from(levels) - 1 - level)) & 1; + plane[position / 32] |= (bit as u32) << (position % 32); + } + } + Ok(EncodedPlanes { + scales: normalized.scales, + planes, + padded_elements: padded, + }) +} + +// IEEE-754 round-to-nearest, ties-to-even conversion, independent of host +// f16 support so the Linux control binary and offline oracle agree. +pub fn f32_to_f16_bits(value: f32) -> u16 { + let bits = value.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exponent = ((bits >> 23) & 0xff) as i32; + let mantissa = bits & 0x7f_ffff; + if exponent == 255 { + return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 }; + } + let half_exponent = exponent - 127 + 15; + if half_exponent >= 31 { + return sign | 0x7c00; + } + if half_exponent <= 0 { + if half_exponent < -10 { + return sign; + } + let significand = mantissa | 0x80_0000; + let shift = (14 - half_exponent) as u32; + let rounded = + (significand + ((1u32 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift; + return sign | rounded as u16; + } + let rounded = mantissa + 0x0fff + ((mantissa >> 13) & 1); + if rounded & 0x80_0000 != 0 { + return sign | (((half_exponent + 1) as u16) << 10); + } + sign | ((half_exponent as u16) << 10) | ((rounded >> 13) as u16) +} + +fn f64_to_f16_bits(value: f64) -> u16 { + let bits = value.to_bits(); + let sign = ((bits >> 48) & 0x8000) as u16; + let exponent = ((bits >> 52) & 0x7ff) as i32; + let mantissa = bits & 0x000f_ffff_ffff_ffff; + if exponent == 2047 { + return sign | 0x7c00 | if mantissa == 0 { 0 } else { 0x0200 }; + } + let half_exponent = exponent - 1023 + 15; + if half_exponent >= 31 { + return sign | 0x7c00; + } + if half_exponent <= 0 { + if half_exponent < -10 { + return sign; + } + let significand = mantissa | 0x0010_0000_0000_0000; + let shift = (43 - half_exponent) as u32; + let rounded = + (significand + ((1u64 << (shift - 1)) - 1) + ((significand >> shift) & 1)) >> shift; + return sign | rounded as u16; + } + let rounded = mantissa + 0x0000_01ff_ffff_ffff + ((mantissa >> 42) & 1); + if rounded & 0x0010_0000_0000_0000 != 0 { + return sign | (((half_exponent + 1) as u16) << 10); + } + sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16) +} + +pub fn f16_bits_to_f32(bits: u16) -> f32 { + let sign = (u32::from(bits & 0x8000)) << 16; + let exponent = (bits >> 10) & 0x1f; + let mantissa = u32::from(bits & 0x03ff); + let result = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + let leading = mantissa.leading_zeros() - 21; + let normalized = mantissa << leading; + sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13) + } + 31 => sign | 0x7f80_0000 | (mantissa << 13), + _ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13), + }; + f32::from_bits(result) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{kar, kar_writer}; + use sha2::{Digest, Sha256}; + use std::fs; + + #[test] + fn f16_rounding_and_subnormals_match_ieee_examples() { + for (value, bits) in [ + (0.0, 0x0000), + (-0.0, 0x8000), + (1.0, 0x3c00), + (-2.0, 0xc000), + (65504.0, 0x7bff), + (f32::from_bits(0x3380_0000), 0x0001), + ] { + assert_eq!(f32_to_f16_bits(value), bits); + assert_eq!(f16_bits_to_f32(bits), value); + } + assert_eq!(f32_to_f16_bits(f32::from_bits(0x3300_0000)), 0); + assert_eq!(f32_to_f16_bits(f32::from_bits(0x3f80_1000)), 0x3c00); + assert_eq!(f32_to_f16_bits(f32::from_bits(0x3f80_3000)), 0x3c02); + assert_eq!(f32_to_f16_bits(f32::INFINITY), 0x7c00); + let above_midpoint = 1.0 + 2f64.powi(-11) + 2f64.powi(-40); + assert_eq!(f32_to_f16_bits(above_midpoint as f32), 0x3c00); + assert_eq!(f64_to_f16_bits(above_midpoint), 0x3c01); + // Independent Python struct.pack('>(); + let mut decoded = [0.0f32; 5]; + decode_range(&encoded.scales, &book2, &planes, 32, 3, &mut decoded).unwrap(); + assert_eq!(decoded, [0.75, -0.75, -0.25, 0.25, 0.75]); + decode_range(&encoded.scales, &book1, &planes[..1], 32, 3, &mut decoded).unwrap(); + assert_eq!(decoded, [0.5, -0.5, -0.5, 0.5, 0.5]); + assert!(decode_range(&encoded.scales, &book2, &planes, 32, 31, &mut decoded).is_err()); + let source = kar_writer::SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "strata-next-experimental", + digest: Sha256::digest(b"source").into(), + total_elements: 32, + bytes: 6, + }; + let tensor = [kar_writer::Tensor { + name: "expert", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &encoded.scales, + books: &books, + planes: &planes, + }, + }]; + let path = std::env::temp_dir().join(format!("strata-codec-{}.kar", std::process::id())); + let _ = fs::remove_file(&path); + kar_writer::write_archive(&path, &source, &tensor).unwrap(); + assert_eq!(kar::verify(&path).unwrap().tensor_count, 1); + let archived = kar::decode_preview_tensor(&path, "expert", 2).unwrap(); + assert_eq!(&archived[3..8], &[0.75, -0.75, -0.25, 0.25, 0.75]); + assert_eq!(kar::f32_fnv1a64(&[1.0]), 0x4b72_477f_9c5c_2f98); + let coarse = kar::decode_preview_tensor(&path, "expert", 1).unwrap(); + assert_eq!(&coarse[3..8], &[0.5, -0.5, -0.5, 0.5, 0.5]); + assert!(kar::decode_preview_tensor(&path, "expert", 3).is_err()); + fs::remove_file(path).unwrap(); + } + + #[test] + fn topdown_calibration_matches_pinned_koference_oracle() { + // koference 806d2398, kar_codec.nested_books(sample, 2, "topdown"). + let sample = [-1.0, -0.75, -0.25, -0.1, 0.1, 0.25, 0.75, 1.0]; + let calibration = fit_topdown(&sample, 2).unwrap(); + assert_eq!(calibration.boundaries, [-0.5, 0.0, 0.5]); + assert_eq!(calibration.books[0], [0xb833, 0x3833]); + assert_eq!(calibration.books[1], [0xbb00, 0xb19a, 0x319a, 0x3b00]); + assert!(fit_topdown(&[0.0; 8], 2).is_err()); + let varied = [ + -1.0, -0.93, -0.8, -0.65, -0.49, -0.3, -0.15, -0.05, 0.05, 0.14, 0.29, 0.43, 0.6, 0.77, + 0.91, 1.0, + ]; + let calibration = fit_topdown(&varied, 3).unwrap(); + assert_eq!( + calibration + .boundaries + .iter() + .map(|v| v.to_bits()) + .collect::>(), + [ + 0xbf5d_70a4, + 0xbf11_eb85, + 0xbe66_6667, + 0, + 0x3e5c_28f6, + 0x3f03_d70a, + 0x3f57_0a3e, + ] + ); + assert_eq!( + calibration.books[2], + [ + 0xbbb8, 0xb9cd, 0xb652, 0xae66, 0x2e14, 0x35c3, 0x397b, 0x3ba4 + ] + ); + } +} diff --git a/control-plane/src/kar_fixture.rs b/control-plane/src/kar_fixture.rs new file mode 100644 index 00000000..cf096c3e --- /dev/null +++ b/control-plane/src/kar_fixture.rs @@ -0,0 +1,183 @@ +//! Deterministic, model-free archive for CPU/CUDA decode parity checks. + +use std::path::Path; + +use sha2::{Digest, Sha256}; + +use crate::{kar, kar_codec, kar_writer}; + +pub struct FixtureSummary { + pub archive: kar::Summary, + pub archive_digest: [u8; 32], + pub decoded_fnv1a64: u64, +} + +pub struct PleFixtureSummary { + pub archive_digest: [u8; 32], + pub row_fnv1a64: [u64; 4], +} + +/// Four PLE-shaped rows in two KAR parts, for the optional Strata PLE reader. +pub fn write_ple(destination: &Path) -> Result { + let mut weights = Vec::with_capacity(4 * 160); + for row in 0..4 { + for column in 0..160 { + let value = [-1.0f32, -0.25, 0.25, 1.0][(row + column) % 4]; + weights.push(value); + } + } + let mut raw = Vec::with_capacity(weights.len() * 4); + for weight in &weights { + raw.extend_from_slice(&weight.to_le_bytes()); + } + let source = kar_writer::SourceIdentity { + name: "strata-next-ple-smoke-f32", + architecture: "synthetic", + builder: "strata-next/ple-smoke-topdown-g32-l2-v1", + digest: Sha256::digest(&raw).into(), + total_elements: weights.len() as u64, + bytes: raw.len() as u64, + }; + let first = kar_codec::encode_with_boundaries(&weights[..320], 32, &[-0.5, 0.0, 0.5], 2)?; + let second = kar_codec::encode_with_boundaries(&weights[320..], 32, &[-0.5, 0.0, 0.5], 2)?; + let book1 = [0xb800u16, 0x3800]; + let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let first_planes = first.planes.iter().map(Vec::as_slice).collect::>(); + let second_planes = second.planes.iter().map(Vec::as_slice).collect::>(); + let first_digest: [u8; 32] = Sha256::digest(&raw[..1280]).into(); + let second_digest: [u8; 32] = Sha256::digest(&raw[1280..]).into(); + let tensors = [ + kar_writer::Tensor { + name: "per_layer_token_embd.weight#strata-part-001-of-002", + dims: &[160, 2], + source_dtype: 0, + source_digest: first_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &first.scales, + books: &books, + planes: &first_planes, + }, + }, + kar_writer::Tensor { + name: "per_layer_token_embd.weight#strata-part-002-of-002", + dims: &[160, 2], + source_dtype: 0, + source_digest: second_digest, + source_offset: 1280, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &second.scales, + books: &books, + planes: &second_planes, + }, + }, + ]; + kar_writer::write_archive(destination, &source, &tensors)?; + let mut row_fnv1a64 = [0; 4]; + for (row, checksum) in row_fnv1a64.iter_mut().enumerate() { + let name = tensors[row / 2].name; + let values = kar::decode_tensor_row(destination, name, 2, (row % 2) as u32)?; + *checksum = kar::f32_fnv1a64(&values); + } + Ok(PleFixtureSummary { + archive_digest: Sha256::digest(std::fs::read(destination).map_err(|e| e.to_string())?) + .into(), + row_fnv1a64, + }) +} + +pub fn write(destination: &Path) -> Result { + let weights = [-1.0f32, -0.25, 0.25, 1.0].repeat(8); + let encoded = kar_codec::encode_with_boundaries(&weights, 32, &[-0.5, 0.0, 0.5], 2)?; + let book1 = [0xb800u16, 0x3800]; + let book2 = [0xba00u16, 0xb400, 0x3400, 0x3a00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let planes = encoded.planes.iter().map(Vec::as_slice).collect::>(); + let mut source_bytes = Vec::with_capacity(weights.len() * 4); + for weight in &weights { + source_bytes.extend_from_slice(&weight.to_le_bytes()); + } + let source_digest: [u8; 32] = Sha256::digest(&source_bytes).into(); + let source = kar_writer::SourceIdentity { + name: "strata-next-smoke-f32", + architecture: "synthetic", + builder: "strata-next/smoke-topdown-g32-l2-v1", + digest: source_digest, + total_elements: weights.len() as u64, + bytes: source_bytes.len() as u64, + }; + let tensor = [kar_writer::Tensor { + name: "smoke.expert", + dims: &[32], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &encoded.scales, + books: &books, + planes: &planes, + }, + }]; + let archive = kar_writer::write_archive(destination, &source, &tensor)?; + let decoded = kar::decode_preview_tensor(destination, "smoke.expert", 2)?; + let archive_digest = + Sha256::digest(std::fs::read(destination).map_err(|e| e.to_string())?).into(); + Ok(FixtureSummary { + archive, + archive_digest, + decoded_fnv1a64: kar::f32_fnv1a64(&decoded), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[test] + fn archive_fixture_decodes_from_published_bytes_and_rejects_overwrite() { + let path = std::env::temp_dir().join(format!( + "strata-kar-fixture-{}-{}.kar", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let created = write(&path).unwrap(); + assert_eq!(created.archive.tensor_count, 1); + let decoded = kar::decode_preview_tensor(&path, "smoke.expert", 2).unwrap(); + assert_eq!(&decoded[..4], &[-0.75, -0.25, 0.25, 0.75]); + assert_eq!(created.decoded_fnv1a64, kar::f32_fnv1a64(&decoded)); + assert_eq!( + kar::decode_tensor_row(&path, "smoke.expert", 2, 0).unwrap(), + decoded + ); + assert!(kar::decode_tensor_row(&path, "smoke.expert", 2, 1).is_err()); + assert!(write(&path).is_err()); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn ple_fixture_has_two_ordered_parts_and_four_rows() { + let path = + std::env::temp_dir().join(format!("strata-ple-fixture-{}.kar", std::process::id())); + let created = write_ple(&path).unwrap(); + assert_eq!(kar::verify(&path).unwrap().tensor_count, 2); + assert_ne!(created.row_fnv1a64[0], created.row_fnv1a64[1]); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/kar_memory.rs b/control-plane/src/kar_memory.rs new file mode 100644 index 00000000..f3d79aa7 --- /dev/null +++ b/control-plane/src/kar_memory.rs @@ -0,0 +1,263 @@ +//! Metadata-only GPU memory admission for an experimental KAR archive. +//! This is not a scheduler, payload verification, or a model quality gate. + +use std::path::Path; + +use serde::Serialize; + +use crate::{kar, kar_overlay}; + +#[derive(Serialize)] +pub struct RecordMemory { + pub name: String, + pub compressed_bytes: u64, + pub decode_bytes: u64, + pub single_record_peak_bytes: u64, + /// Geometric lower bound for kar_decode_rows, not a model execution plan. + pub one_row_peak_bytes: Option, +} + +#[derive(Serialize)] +pub struct Report { + pub schema: &'static str, + pub level: u8, + pub budget_bytes: u64, + pub record_count: usize, + pub all_compressed_resident_bytes: u64, + pub largest_decode_scratch_bytes: u64, + pub all_resident_plus_scratch_bytes: u64, + pub largest_single_record_peak_bytes: u64, + pub records_exceeding_budget: usize, + pub full_decode_exceeds_but_one_row_fits: usize, + pub largest_records: Vec, + pub verification: &'static str, +} + +#[derive(Serialize)] +pub struct SelectedRecordMemory { + pub archive: &'static str, + pub level: u8, + #[serde(flatten)] + pub memory: RecordMemory, +} + +#[derive(Serialize)] +pub struct SelectedReport { + pub schema: &'static str, + pub base_archive_sha256: String, + pub overlay_archive_sha256: String, + pub base_level: u8, + pub overlay_level: u8, + pub budget_bytes: u64, + pub record_count: usize, + pub replacement_count: usize, + pub selected_base_compressed_bytes: u64, + pub selected_overlay_compressed_bytes: u64, + pub selected_compressed_bytes: u64, + pub largest_decode_scratch_bytes: u64, + pub all_selected_plus_scratch_bytes: u64, + pub largest_single_record_peak_bytes: u64, + pub records_exceeding_budget: usize, + pub full_decode_exceeds_but_one_row_fits: usize, + pub largest_records: Vec, + pub verification: &'static str, +} + +/// Plan the exact base/overlay record selection after full archive and +/// provenance verification. This is metadata arithmetic, not GPU admission. +pub fn plan_selected( + base_path: &Path, + overlay_path: &Path, + base_level: u8, + overlay_level: u8, + budget_bytes: u64, +) -> Result { + if !(1..=8).contains(&base_level) || !(1..=8).contains(&overlay_level) || budget_bytes == 0 { + return Err("KAR levels must be 1..8 and GPU budget must be positive".into()); + } + let selection = kar_overlay::resolve_verified(base_path, overlay_path)?; + let (_, base_sources) = kar::inspect_with_sources(base_path)?; + let (_, overlay_sources) = kar::inspect_with_sources(overlay_path)?; + let mut base_bytes = 0u64; + let mut overlay_bytes = 0u64; + let mut scratch_max = 0u64; + let mut peak_max = 0u64; + let mut exceeding = 0usize; + let mut row_fits = 0usize; + let mut largest = Vec::with_capacity(selection.records.len()); + for selected in &selection.records { + let (source, level, total) = match selected.archive { + "base" => ( + base_sources.get(selected.archive_index), + base_level, + &mut base_bytes, + ), + "overlay" => ( + overlay_sources.get(selected.archive_index), + overlay_level, + &mut overlay_bytes, + ), + _ => return Err("unknown KAR selection archive".into()), + }; + let source = source.ok_or("selected KAR record index is out of bounds")?; + if source.name != selected.name + || source.offset != selected.source_offset + || source.dimensions != selected.dimensions + || hex::encode(source.digest) != selected.source_sha256 + { + return Err(format!("{}: selected KAR record changed", selected.name)); + } + let compressed = source.gpu_resident_bytes(level)?; + let scratch = source.gpu_decode_bytes()?; + let peak = compressed + .checked_add(scratch) + .ok_or("selected KAR single-record peak overflow")?; + *total = total + .checked_add(compressed) + .ok_or("selected KAR compressed total overflow")?; + scratch_max = scratch_max.max(scratch); + peak_max = peak_max.max(peak); + if peak > budget_bytes { + exceeding += 1; + } + let one_row_peak = source + .gpu_one_row_decode_bytes() + .and_then(|row_bytes| compressed.checked_add(row_bytes)); + if peak > budget_bytes && one_row_peak.is_some_and(|bytes| bytes <= budget_bytes) { + row_fits += 1; + } + largest.push(SelectedRecordMemory { + archive: selected.archive, + level, + memory: RecordMemory { + name: selected.name.clone(), + compressed_bytes: compressed, + decode_bytes: scratch, + single_record_peak_bytes: peak, + one_row_peak_bytes: one_row_peak, + }, + }); + } + largest.sort_unstable_by(|a, b| { + b.memory + .single_record_peak_bytes + .cmp(&a.memory.single_record_peak_bytes) + .then_with(|| a.memory.name.cmp(&b.memory.name)) + }); + largest.truncate(10); + let selected_bytes = base_bytes + .checked_add(overlay_bytes) + .ok_or("selected KAR compressed total overflow")?; + let all_plus_scratch = selected_bytes + .checked_add(scratch_max) + .ok_or("selected KAR all-resident peak overflow")?; + Ok(SelectedReport { + schema: "strata-next/selected-kar-gpu-memory-plan-v1", + base_archive_sha256: selection.base_archive_sha256, + overlay_archive_sha256: selection.overlay_archive_sha256, + base_level, + overlay_level, + budget_bytes, + record_count: selection.records.len(), + replacement_count: selection.replacement_count, + selected_base_compressed_bytes: base_bytes, + selected_overlay_compressed_bytes: overlay_bytes, + selected_compressed_bytes: selected_bytes, + largest_decode_scratch_bytes: scratch_max, + all_selected_plus_scratch_bytes: all_plus_scratch, + largest_single_record_peak_bytes: peak_max, + records_exceeding_budget: exceeding, + full_decode_exceeds_but_one_row_fits: row_fits, + largest_records: largest, + verification: "complete base and overlay hashes, payload CRCs, provenance, and replacement mappings verified before metadata planning; keep archives immutable; no GPU execution or model quality check", + }) +} + +pub fn plan(path: &Path, level: u8, budget_bytes: u64) -> Result { + if !(1..=8).contains(&level) || budget_bytes == 0 { + return Err("KAR level must be 1..8 and GPU budget must be positive".into()); + } + let (summary, records) = kar::inspect_with_sources(path)?; + let mut compressed_total = 0u64; + let mut scratch_max = 0u64; + let mut peak_max = 0u64; + let mut exceeding = 0usize; + let mut row_fits = 0usize; + let mut largest = Vec::with_capacity(records.len()); + for record in records { + let compressed = record.gpu_resident_bytes(level)?; + let scratch = record.gpu_decode_bytes()?; + let peak = compressed + .checked_add(scratch) + .ok_or("KAR single-record GPU peak overflow")?; + compressed_total = compressed_total + .checked_add(compressed) + .ok_or("KAR total GPU residency overflow")?; + scratch_max = scratch_max.max(scratch); + peak_max = peak_max.max(peak); + if peak > budget_bytes { + exceeding += 1; + } + let one_row_peak = record + .gpu_one_row_decode_bytes() + .and_then(|row_bytes| compressed.checked_add(row_bytes)); + if peak > budget_bytes && one_row_peak.is_some_and(|bytes| bytes <= budget_bytes) { + row_fits += 1; + } + largest.push(RecordMemory { + name: record.name, + compressed_bytes: compressed, + decode_bytes: scratch, + single_record_peak_bytes: peak, + one_row_peak_bytes: one_row_peak, + }); + } + largest.sort_unstable_by(|a, b| { + b.single_record_peak_bytes + .cmp(&a.single_record_peak_bytes) + .then_with(|| a.name.cmp(&b.name)) + }); + largest.truncate(10); + let all_plus_scratch = compressed_total + .checked_add(scratch_max) + .ok_or("KAR all-resident GPU peak overflow")?; + Ok(Report { + schema: "strata-next/kar-gpu-memory-plan-v1", + level, + budget_bytes, + record_count: summary.tensor_count as usize, + all_compressed_resident_bytes: compressed_total, + largest_decode_scratch_bytes: scratch_max, + all_resident_plus_scratch_bytes: all_plus_scratch, + largest_single_record_peak_bytes: peak_max, + records_exceeding_budget: exceeding, + full_decode_exceeds_but_one_row_fits: row_fits, + largest_records: largest, + verification: "bounded KAR metadata only; payload CRCs, archive SHA-256, model quality, and GPU execution not checked", + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[test] + fn smoke_fixture_has_bounded_single_record_peak() { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "strata-kar-memory-{}-{nonce}.kar", + std::process::id() + )); + crate::kar_fixture::write(&path).unwrap(); + let report = plan(&path, 2, 1 << 20).unwrap(); + assert_eq!(report.record_count, 1); + assert_eq!(report.records_exceeding_budget, 0); + assert!(report.largest_single_record_peak_bytes <= 1 << 20); + assert_eq!(plan(&path, 2, 1).unwrap().records_exceeding_budget, 1); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/kar_overlay.rs b/control-plane/src/kar_overlay.rs new file mode 100644 index 00000000..ffa8396d --- /dev/null +++ b/control-plane/src/kar_overlay.rs @@ -0,0 +1,1048 @@ +//! Experimental higher-precision KAR records for selected tensors of an +//! already verified base archive. This does not install a serving overlay. + +use std::{ + collections::{HashMap, HashSet}, + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Component, Path, PathBuf}, +}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::{gguf, kar, kar_codec, kar_sample, kar_stream_encode, kar_writer, model::Manifest}; + +#[derive(Deserialize)] +struct Candidates { + schema: String, + source_archive_sha256: String, + proposed_levels: u8, + records: Vec, +} + +#[derive(Deserialize)] +struct Candidate { + name: String, + elements: u64, +} + +#[derive(Deserialize)] +struct BaseProvenance { + schema: String, + #[serde(default)] + ple_part_elements: Option, + archive_sha256: String, + derived_f32_sha256: String, + derived_f32_bytes: u64, + shards: Vec, + tensors: Vec, + #[serde(default)] + partitioned_tensors: Vec, +} + +impl BaseProvenance { + fn supported_partition_policy(&self) -> bool { + match (self.schema.as_str(), self.ple_part_elements) { + ("strata-next/sharded-stream-provenance-v4", None) => true, + ("strata-next/sharded-stream-provenance-v5", Some(limit)) => { + (32..=crate::stream_parts::MAX_PART_ELEMENTS).contains(&limit) + && self + .partitioned_tensors + .iter() + .any(|tensor| tensor.parent_name == crate::stream_parts::PLE_TENSOR_NAME) + } + _ => false, + } + } +} + +#[derive(Deserialize)] +struct PartitionedTensor { + parent_name: String, + parent_dimensions: Vec, + source_kind: u32, + parts: Vec, +} + +#[derive(Deserialize)] +struct PartitionPart { + name: String, + dimensions: Vec, + source_byte_offset: u64, + source_bytes: u64, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Deserialize)] +struct BaseShard { + name: String, + gguf_sha256: String, + gguf_bytes: u64, +} + +#[derive(Deserialize)] +struct BaseTensor { + name: String, + source_kind: u32, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Deserialize)] +struct OverlayProvenance { + schema: String, + base_archive_sha256: String, + overlay_archive_sha256: String, + levels: u8, + records: Vec, +} + +#[derive(Deserialize)] +struct OverlayRecord { + name: String, + derived_offset: u64, + f32_sha256: String, + section_bytes: u64, + relative_l2: f64, +} + +/// A verified mapping for a future GPU loader. It does not decode or enable +/// the experimental overlay for serving. +#[derive(Serialize)] +pub struct Resolution { + pub schema: &'static str, + pub base_archive_sha256: String, + pub overlay_archive_sha256: String, + pub records: Vec, + pub replacement_count: usize, +} + +#[derive(Serialize)] +pub struct ResolvedRecord { + pub name: String, + pub archive: &'static str, + pub archive_index: usize, + pub source_offset: u64, + pub source_sha256: String, + pub dimensions: Vec, +} + +#[derive(Serialize)] +pub struct Comparison { + pub schema: &'static str, + pub base_archive_sha256: String, + pub overlay_archive_sha256: String, + pub verification: &'static str, + pub records: Vec, +} + +#[derive(Serialize)] +pub struct ComparedRecord { + pub name: String, + pub elements: u64, + pub base_relative_l2: f64, + pub overlay_relative_l2: f64, +} + +#[derive(Clone)] +struct Location { + path: PathBuf, + absolute: u64, + kind: u32, + source_bytes: u64, + dimensions: Vec, +} + +struct CandidateSource<'a> { + location: Location, + source_sha256: &'a str, + f32_sha256: &'a str, + derived_offset: u64, + derived_bytes: u64, +} + +fn candidate_source<'a>( + base: &'a BaseProvenance, + locations: &HashMap, + name: &str, +) -> Result, String> { + if let Some(parent) = base + .partitioned_tensors + .iter() + .find(|parent| parent.parts.iter().any(|part| part.name == name)) + { + let part = parent.parts.iter().find(|part| part.name == name).unwrap(); + let original = base + .tensors + .iter() + .find(|tensor| tensor.name == parent.parent_name) + .ok_or("partition parent absent from base provenance")?; + let location = locations + .get(&parent.parent_name) + .ok_or("partition parent absent from GGUF source")?; + let (block_elements, block_bytes) = + gguf::block_geometry(parent.source_kind).ok_or("unsupported partition source kind")?; + let elements = part + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("partition shape overflow")?; + let raw_end = part + .source_byte_offset + .checked_add(part.source_bytes) + .ok_or("partition source offset overflow")?; + let derived_end = part + .derived_offset + .checked_add(part.derived_bytes) + .ok_or("partition derived offset overflow")?; + let expected_offset = original + .derived_offset + .checked_add( + part.source_byte_offset + .checked_div(block_bytes) + .and_then(|blocks| blocks.checked_mul(block_elements)) + .and_then(|values| values.checked_mul(4)) + .ok_or("partition virtual offset overflow")?, + ) + .ok_or("partition virtual offset overflow")?; + if part.dimensions.is_empty() + || parent.parent_dimensions != location.dimensions + || parent.source_kind != location.kind + || original.source_kind != location.kind + || part.dimensions.len() != parent.parent_dimensions.len() + || part.dimensions[..part.dimensions.len() - 1] + != parent.parent_dimensions[..parent.parent_dimensions.len() - 1] + || part.source_byte_offset % block_bytes != 0 + || elements == 0 + || elements % block_elements != 0 + || part.source_bytes != elements / block_elements * block_bytes + || part.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + || raw_end > location.source_bytes + || part.derived_offset != expected_offset + || derived_end + > original + .derived_offset + .checked_add(original.derived_bytes) + .ok_or("parent derived offset overflow")? + { + return Err(format!("{name}: partition geometry differs from base")); + } + return Ok(CandidateSource { + location: Location { + path: location.path.clone(), + absolute: location + .absolute + .checked_add(part.source_byte_offset) + .ok_or("partition absolute offset overflow")?, + kind: location.kind, + source_bytes: part.source_bytes, + dimensions: part.dimensions.clone(), + }, + source_sha256: &part.source_sha256, + f32_sha256: &part.f32_sha256, + derived_offset: part.derived_offset, + derived_bytes: part.derived_bytes, + }); + } + if base + .partitioned_tensors + .iter() + .any(|parent| parent.parent_name == name) + { + return Err(format!("{name}: partition parent is not a KAR record")); + } + let original = base + .tensors + .iter() + .find(|tensor| tensor.name == name) + .ok_or("candidate absent from base provenance")?; + let location = locations + .get(name) + .ok_or("candidate absent from GGUF source")?; + if location.kind != original.source_kind { + return Err(format!("{name}: source kind differs from base")); + } + Ok(CandidateSource { + location: location.clone(), + source_sha256: &original.source_sha256, + f32_sha256: &original.f32_sha256, + derived_offset: original.derived_offset, + derived_bytes: original.derived_bytes, + }) +} + +struct Prepared { + name: String, + dimensions: Vec, + source_offset: u64, + f32_sha256: [u8; 32], + section_path: PathBuf, + section_bytes: u64, + section_sha256: [u8; 32], + relative_l2: f64, +} + +struct Staging(PathBuf); + +impl Drop for Staging { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +struct PendingArchive { + path: PathBuf, + committed: bool, +} + +impl Drop for PendingArchive { + fn drop(&mut self) { + if !self.committed { + let _ = fs::remove_file(&self.path); + } + } +} + +pub struct Summary { + pub archive_bytes: u64, + pub archive_sha256: [u8; 32], + pub record_count: usize, + pub maximum_relative_l2: f64, + pub provenance_path: PathBuf, +} + +/// Verify both complete archives and bind every replacement to the same +/// virtual-F32 source record before a loader selects an archive by tensor name. +pub fn resolve_verified(base_archive: &Path, overlay_archive: &Path) -> Result { + let sidecar = |path: &Path| -> Result { + let name = path.file_name().ok_or("KAR archive has no file name")?; + Ok(path.with_file_name(format!("{}.provenance.json", name.to_string_lossy()))) + }; + let base: BaseProvenance = serde_json::from_reader( + File::open(sidecar(base_archive)?).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + let overlay: OverlayProvenance = serde_json::from_reader( + File::open(sidecar(overlay_archive)?).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + if !base.supported_partition_policy() + || overlay.schema != "strata-next/kar-overlay-provenance-v1" + || overlay.base_archive_sha256 != base.archive_sha256 + || overlay.levels < 2 + || overlay.levels > 8 + || overlay.records.is_empty() + || hex::encode(hash_file(base_archive)?) != base.archive_sha256 + || hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256 + { + return Err("base or overlay archive differs from its provenance".into()); + } + let (base_summary, base_sources) = kar::verify_with_sources(base_archive)?; + let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?; + if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)? + || overlay_summary.source_digest != base_summary.source_digest + || base_summary.source_bytes != base.derived_f32_bytes + || overlay_summary.source_bytes != base_summary.source_bytes + || overlay_sources.len() != overlay.records.len() + { + return Err("KAR directory differs from virtual-F32 provenance".into()); + } + let mut recorded_base = HashMap::new(); + for record in &base.tensors { + if recorded_base.insert(record.name.as_str(), record).is_some() { + return Err("duplicate base provenance tensor".into()); + } + } + struct ExpectedSource<'a> { + offset: u64, + bytes: u64, + digest: &'a str, + dimensions: Option<&'a [u64]>, + } + let mut expected = HashMap::new(); + let mut partitioned = HashSet::new(); + for parent in &base.partitioned_tensors { + let original = recorded_base + .get(parent.parent_name.as_str()) + .ok_or("partitioned parent absent from base provenance")?; + if !partitioned.insert(parent.parent_name.as_str()) + || parent.parts.len() < 2 + || parent.parent_dimensions.is_empty() + || parent + .parent_dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .and_then(|n| n.checked_mul(4)) + != Some(original.derived_bytes) + { + return Err("invalid partitioned tensor provenance".into()); + } + let mut offset = original.derived_offset; + let mut last_dimension = 0u64; + for part in &parent.parts { + if part.dimensions.len() != parent.parent_dimensions.len() + || part.dimensions[..part.dimensions.len() - 1] + != parent.parent_dimensions[..parent.parent_dimensions.len() - 1] + || part + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .and_then(|n| n.checked_mul(4)) + != Some(part.derived_bytes) + || part.derived_offset != offset + { + return Err(format!("{}: invalid partition geometry", part.name)); + } + offset = offset + .checked_add(part.derived_bytes) + .ok_or("partitioned tensor offset overflow")?; + last_dimension = last_dimension + .checked_add(*part.dimensions.last().unwrap()) + .ok_or("partitioned tensor shape overflow")?; + if expected + .insert( + part.name.as_str(), + ExpectedSource { + offset: part.derived_offset, + bytes: part.derived_bytes, + digest: &part.f32_sha256, + dimensions: Some(&part.dimensions), + }, + ) + .is_some() + { + return Err("duplicate partitioned tensor part".into()); + } + } + if offset + != original + .derived_offset + .checked_add(original.derived_bytes) + .ok_or("partitioned parent offset overflow")? + || last_dimension != *parent.parent_dimensions.last().unwrap() + { + return Err("partitioned parts do not cover their parent".into()); + } + } + for record in &base.tensors { + if partitioned.contains(record.name.as_str()) { + continue; + } + if expected + .insert( + record.name.as_str(), + ExpectedSource { + offset: record.derived_offset, + bytes: record.derived_bytes, + digest: &record.f32_sha256, + dimensions: None, + }, + ) + .is_some() + { + return Err("base provenance record collides with a partition".into()); + } + } + if expected.len() != base_sources.len() { + return Err("base KAR record count differs from partitioned provenance".into()); + } + for source in &base_sources { + let record = expected + .get(source.name.as_str()) + .ok_or("base KAR tensor absent from provenance")?; + if source.digest != parse_digest(record.digest)? + || source.offset != record.offset + || source.dtype != 0 + || record + .dimensions + .is_some_and(|dims| source.dimensions != dims) + || source + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .and_then(|n| n.checked_mul(4)) + != Some(record.bytes) + { + return Err(format!("{}: base source mapping differs", source.name)); + } + } + let mut replacements = HashMap::new(); + for (index, source) in overlay_sources.iter().enumerate() { + let record = overlay + .records + .iter() + .find(|record| record.name == source.name) + .ok_or("overlay KAR tensor absent from provenance")?; + if replacements.insert(source.name.as_str(), index).is_some() + || record.derived_offset != source.offset + || record.f32_sha256 != hex::encode(source.digest) + || record.section_bytes != source.section_bytes + || !record.relative_l2.is_finite() + || record.relative_l2 < 0.0 + || source.dtype != 0 + { + return Err(format!("{}: overlay source mapping differs", source.name)); + } + } + if replacements.len() != overlay.records.len() { + return Err("duplicate overlay provenance tensor".into()); + } + let mut records = Vec::with_capacity(base_sources.len()); + for (index, source) in base_sources.iter().enumerate() { + let replacement = replacements.get(source.name.as_str()).copied(); + if let Some(overlay_index) = replacement { + let selected = &overlay_sources[overlay_index]; + if selected.digest != source.digest + || selected.offset != source.offset + || selected.dimensions != source.dimensions + { + return Err(format!( + "{}: overlay replaces a different source tensor", + source.name + )); + } + } + records.push(ResolvedRecord { + name: source.name.clone(), + archive: if replacement.is_some() { + "overlay" + } else { + "base" + }, + archive_index: replacement.unwrap_or(index), + source_offset: source.offset, + source_sha256: hex::encode(source.digest), + dimensions: source.dimensions.clone(), + }); + } + Ok(Resolution { + schema: "strata-next/verified-kar-overlay-selection-v1", + base_archive_sha256: base.archive_sha256, + overlay_archive_sha256: overlay.overlay_archive_sha256, + replacement_count: replacements.len(), + records, + }) +} + +pub fn prepare( + manifest: &Manifest, + source_dir: &Path, + base_archive: &Path, + candidate_path: &Path, + destination: &Path, +) -> Result { + let sidecar = destination.with_file_name(format!( + "{}.provenance.json", + destination + .file_name() + .ok_or("overlay destination has no file name")? + .to_string_lossy() + )); + if fs::symlink_metadata(destination).is_ok() || fs::symlink_metadata(&sidecar).is_ok() { + return Err("overlay archive or provenance destination already exists".into()); + } + let candidates_bytes = fs::read(candidate_path).map_err(|error| error.to_string())?; + let candidates: Candidates = + serde_json::from_slice(&candidates_bytes).map_err(|error| error.to_string())?; + if candidates.schema != "strata-next/proposed-kar-precision-candidates-v1" + || !(1..=8).contains(&candidates.proposed_levels) + || candidates.records.is_empty() + { + return Err("invalid KAR overlay candidate policy".into()); + } + let base_sidecar = base_archive.with_file_name(format!( + "{}.provenance.json", + base_archive + .file_name() + .ok_or("base archive has no file name")? + .to_string_lossy() + )); + let base: BaseProvenance = + serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if !base.supported_partition_policy() || candidates.source_archive_sha256 != base.archive_sha256 + { + return Err("candidate policy differs from base KAR provenance".into()); + } + let base_digest = parse_digest(&base.archive_sha256)?; + let source_digest = parse_digest(&base.derived_f32_sha256)?; + let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?; + if base_summary.source_digest != source_digest + || base_summary.source_bytes != base.derived_f32_bytes + { + return Err("base KAR header differs from provenance".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() { + return Err("source manifest differs from base provenance".into()); + } + let mut locations = HashMap::new(); + let mut architecture = None::; + for (entry, recorded) in manifest_files.iter().zip(&base.shards) { + if entry.name != recorded.name + || entry.size != recorded.gguf_bytes + || entry.sha256 != recorded.gguf_sha256 + || !matches!( + Path::new(&entry.name).components().next(), + Some(Component::Normal(_)) + ) + || Path::new(&entry.name).components().count() != 1 + { + return Err("source manifest differs from base shard identity".into()); + } + let path = source_dir.join(&entry.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != entry.size { + return Err("source shard length changed since base preparation".into()); + } + if let Some(arch) = index.summary.architecture { + if architecture.as_deref().is_some_and(|old| old != arch) { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert(arch); + } + for tensor in index.tensors { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if locations + .insert( + tensor.name, + Location { + path: path.clone(), + absolute, + kind: tensor.kind, + source_bytes: tensor.bytes, + dimensions: tensor.dimensions, + }, + ) + .is_some() + { + return Err("duplicate GGUF tensor name".into()); + } + } + } + let base_tensors = base + .tensors + .iter() + .map(|tensor| (tensor.name.as_str(), tensor)) + .collect::>(); + if base_tensors.len() != base.tensors.len() { + return Err("duplicate tensor in base provenance".into()); + } + let base_records = base_sources + .iter() + .map(|record| (record.name.as_str(), record)) + .collect::>(); + let staging = Staging(destination.with_file_name(format!( + "{}.overlay-sections-{}", + destination.file_name().unwrap().to_string_lossy(), + std::process::id() + ))); + fs::create_dir(&staging.0).map_err(|error| error.to_string())?; + let mut prepared = Vec::with_capacity(candidates.records.len()); + let mut seen = HashSet::new(); + for candidate in &candidates.records { + if !seen.insert(candidate.name.as_str()) { + return Err("duplicate KAR overlay candidate".into()); + } + let selected = candidate_source(&base, &locations, &candidate.name)?; + let location = &selected.location; + let elements = location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("candidate tensor shape overflow")?; + let base_record = base_records + .get(candidate.name.as_str()) + .ok_or("candidate is missing from base KAR directory")?; + if elements != candidate.elements + || selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + || base_record.offset != selected.derived_offset + || base_record.digest != parse_digest(selected.f32_sha256)? + || base_record.dimensions != location.dimensions + { + return Err(format!( + "{}: candidate geometry differs from base", + candidate.name + )); + } + let source_sha256 = parse_digest(selected.source_sha256)?; + let f32_sha256 = parse_digest(selected.f32_sha256)?; + let mut source = File::open(&location.path).map_err(|error| error.to_string())?; + let sample = kar_sample::sample_normalized( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + elements, + source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + let calibration = kar_codec::fit_topdown(&sample, candidates.proposed_levels) + .map_err(|error| format!("{}: {error}", candidate.name))?; + let section_path = staging.0.join(format!("{:06}.section", prepared.len())); + let section = kar_stream_encode::encode_section( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + elements, + &calibration, + §ion_path, + )?; + if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 { + return Err(format!("{}: candidate source changed", candidate.name)); + } + prepared.push(Prepared { + name: candidate.name.clone(), + dimensions: location.dimensions.clone(), + source_offset: selected.derived_offset, + f32_sha256, + section_path, + section_bytes: section.bytes, + section_sha256: section.digest, + relative_l2: section.relative_l2, + }); + } + let tensors = prepared + .iter() + .map(|entry| kar_writer::Tensor { + name: &entry.name, + dims: &entry.dimensions, + source_dtype: 0, + source_digest: entry.f32_sha256, + source_offset: entry.source_offset, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: candidates.proposed_levels, + levels: candidates.proposed_levels, + path: &entry.section_path, + offset: 0, + bytes: entry.section_bytes, + digest: entry.section_sha256, + }, + }) + .collect::>(); + let candidate_sha256: [u8; 32] = Sha256::digest(&candidates_bytes).into(); + let builder = format!( + "strata-next/experimental-kar-overlay-v1:l{}:base{}:policy{}", + candidates.proposed_levels, + &base.archive_sha256[..16], + &hex::encode(candidate_sha256)[..16] + ); + let source = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v4-overlay", + architecture: architecture.as_deref().ok_or("GGUF architecture missing")?, + builder: &builder, + digest: source_digest, + total_elements: base.derived_f32_bytes / 4, + bytes: base.derived_f32_bytes, + }; + let archive = kar_writer::write_archive(destination, &source, &tensors)?; + let mut pending = PendingArchive { + path: destination.to_path_buf(), + committed: false, + }; + let archive_sha256 = hash_file(destination)?; + let (verified, records) = kar::verify_with_sources(destination)?; + if verified != archive + || records.len() != prepared.len() + || records.iter().zip(&prepared).any(|(record, entry)| { + record.name != entry.name + || record.digest != entry.f32_sha256 + || record.offset != entry.source_offset + }) + { + return Err("overlay archive source records failed verification".into()); + } + let provenance = serde_json::json!({ + "schema": "strata-next/kar-overlay-provenance-v1", + "base_archive_sha256": hex::encode(base_digest), + "candidate_policy_sha256": hex::encode(candidate_sha256), + "overlay_archive_sha256": hex::encode(archive_sha256), + "derived_f32_sha256": hex::encode(source_digest), + "levels": candidates.proposed_levels, + "records": prepared.iter().map(|entry| serde_json::json!({ + "name": entry.name, + "derived_offset": entry.source_offset, + "f32_sha256": hex::encode(entry.f32_sha256), + "section_bytes": entry.section_bytes, + "relative_l2": entry.relative_l2, + })).collect::>(), + "serving_status": "experimental-not-approved", + }); + write_provenance(&sidecar, &provenance)?; + pending.committed = true; + Ok(Summary { + archive_bytes: archive.archive_bytes, + archive_sha256, + record_count: prepared.len(), + maximum_relative_l2: prepared + .iter() + .map(|entry| entry.relative_l2) + .fold(0.0f64, f64::max), + provenance_path: sidecar, + }) +} + +/// Compare complete selected tensors against the verified source bytes. +/// The large base archive is assumed unchanged since its earlier full verify; +/// every selected GGUF tensor and the small overlay are checked in this run. +pub fn compare( + manifest: &Manifest, + source_dir: &Path, + base_archive: &Path, + overlay_archive: &Path, +) -> Result { + let base_sidecar = base_archive.with_file_name(format!( + "{}.provenance.json", + base_archive + .file_name() + .ok_or("base archive has no file name")? + .to_string_lossy() + )); + let overlay_sidecar = overlay_archive.with_file_name(format!( + "{}.provenance.json", + overlay_archive + .file_name() + .ok_or("overlay archive has no file name")? + .to_string_lossy() + )); + let base: BaseProvenance = + serde_json::from_reader(File::open(base_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + let overlay: OverlayProvenance = + serde_json::from_reader(File::open(overlay_sidecar).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if !base.supported_partition_policy() + || overlay.schema != "strata-next/kar-overlay-provenance-v1" + || overlay.base_archive_sha256 != base.archive_sha256 + || overlay.levels < 2 + || overlay.records.is_empty() + || hex::encode(hash_file(overlay_archive)?) != overlay.overlay_archive_sha256 + { + return Err("overlay provenance differs from base or overlay archive".into()); + } + let (base_summary, base_sources) = kar::inspect_with_sources(base_archive)?; + let (overlay_summary, overlay_sources) = kar::verify_with_sources(overlay_archive)?; + if base_summary.source_digest != parse_digest(&base.derived_f32_sha256)? + || overlay_summary.source_digest != base_summary.source_digest + || base_summary.source_bytes != base.derived_f32_bytes + || overlay_sources.len() != overlay.records.len() + { + return Err("KAR source identity differs from overlay provenance".into()); + } + let base_records = base_sources + .iter() + .map(|record| (record.name.as_str(), record)) + .collect::>(); + if overlay + .records + .iter() + .map(|record| record.name.as_str()) + .collect::>() + .len() + != overlay.records.len() + { + return Err("duplicate overlay tensor name".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != base.shards.len() { + return Err("source manifest differs from base provenance".into()); + } + let mut locations = HashMap::new(); + for (entry, shard) in manifest_files.iter().zip(&base.shards) { + if entry.name != shard.name + || entry.size != shard.gguf_bytes + || entry.sha256 != shard.gguf_sha256 + { + return Err("source manifest differs from base provenance".into()); + } + let path = source_dir.join(&entry.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != entry.size { + return Err("GGUF shard length changed".into()); + } + for tensor in index.tensors { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + if locations + .insert( + tensor.name, + Location { + path: path.clone(), + absolute, + kind: tensor.kind, + source_bytes: tensor.bytes, + dimensions: tensor.dimensions, + }, + ) + .is_some() + { + return Err("duplicate GGUF tensor name".into()); + } + } + } + let mut base_decoder = kar::VerifiedRangeDecoder::open_previously_verified(base_archive)?; + let mut overlay_decoder = kar::VerifiedRangeDecoder::open_previously_verified(overlay_archive)?; + let mut compared = Vec::with_capacity(overlay.records.len()); + for (record, overlay_source) in overlay.records.iter().zip(&overlay_sources) { + let selected = candidate_source(&base, &locations, &record.name)?; + let base_source = base_records + .get(record.name.as_str()) + .ok_or("selected tensor absent from base KAR directory")?; + let location = &selected.location; + let f32_digest = parse_digest(&record.f32_sha256)?; + let elements = location + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("GGUF tensor shape overflow")?; + if overlay_source.name != record.name + || base_source.digest != f32_digest + || overlay_source.digest != f32_digest + || base_source.dimensions != location.dimensions + || overlay_source.dimensions != location.dimensions + || f32_digest != parse_digest(selected.f32_sha256)? + || base_source.offset != selected.derived_offset + || overlay_source.offset != selected.derived_offset + || record.derived_offset != selected.derived_offset + || selected.derived_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + { + return Err(format!("{}: selected source mapping differs", record.name)); + } + let mut source = File::open(&location.path).map_err(|error| error.to_string())?; + let mut raw_hash = Sha256::new(); + let mut f32_hash = Sha256::new(); + let mut position = 0usize; + let mut reference_sum = 0.0f64; + let mut base_error = 0.0f64; + let mut overlay_error = 0.0f64; + let decoded_bytes = crate::gguf_f32_stream::visit( + &mut source, + location.absolute, + location.kind, + location.source_bytes, + |raw, f32_bytes| { + raw_hash.update(raw); + f32_hash.update(f32_bytes); + let count = f32_bytes.len() / 4; + let base_values = base_decoder.decode_range(&record.name, 2, position, count)?; + let overlay_values = + overlay_decoder.decode_range(&record.name, overlay.levels, position, count)?; + for ((word, base_value), overlay_value) in f32_bytes + .as_chunks::<4>() + .0 + .iter() + .zip(&base_values) + .zip(&overlay_values) + { + let original = f64::from(f32::from_le_bytes(*word)); + reference_sum += original * original; + base_error += (original - f64::from(*base_value)).powi(2); + overlay_error += (original - f64::from(*overlay_value)).powi(2); + } + position += count; + Ok(()) + }, + )?; + if decoded_bytes != elements * 4 + || position as u64 != elements + || raw_hash.finalize().as_slice() != parse_digest(selected.source_sha256)? + || f32_hash.finalize().as_slice() != f32_digest + { + return Err(format!( + "{}: selected GGUF source digest mismatch", + record.name + )); + } + let denominator = if reference_sum == 0.0 { + 1.0 + } else { + reference_sum + }; + let base_relative_l2 = (base_error / denominator).sqrt(); + let overlay_relative_l2 = (overlay_error / denominator).sqrt(); + if !base_relative_l2.is_finite() + || !overlay_relative_l2.is_finite() + || (overlay_relative_l2 - record.relative_l2).abs() > 1e-6 + { + return Err(format!( + "{}: overlay reconstruction differs from encoding", + record.name + )); + } + compared.push(ComparedRecord { + name: record.name.clone(), + elements, + base_relative_l2, + overlay_relative_l2, + }); + } + Ok(Comparison { + schema: "strata-next/kar-overlay-comparison-v1", + base_archive_sha256: base.archive_sha256, + overlay_archive_sha256: overlay.overlay_archive_sha256, + verification: "prior-full-base-verification-assumed; selected-source-digests-and-overlay-verified-now", + records: compared, + }) +} + +pub fn write_comparison(path: &Path, comparison: &Comparison) -> Result<(), String> { + let value = serde_json::to_value(comparison).map_err(|error| error.to_string())?; + write_provenance(path, &value) +} + +fn parse_digest(value: &str) -> Result<[u8; 32], String> { + hex::decode(value) + .map_err(|error| error.to_string())? + .try_into() + .map_err(|_| "SHA-256 digest is not 32 bytes".into()) +} + +fn hash_file(path: &Path) -> Result<[u8; 32], String> { + let mut file = File::open(path).map_err(|error| error.to_string())?; + let mut hash = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = file.read(&mut buffer).map_err(|error| error.to_string())?; + if count == 0 { + break; + } + hash.update(&buffer[..count]); + } + Ok(hash.finalize().into()) +} + +fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| error.to_string())?; + let result = (|| -> Result<(), String> { + serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?; + file.write_all(b"\n").map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string()) + })(); + if result.is_err() { + let _ = fs::remove_file(path); + } + result +} diff --git a/control-plane/src/kar_quality.rs b/control-plane/src/kar_quality.rs new file mode 100644 index 00000000..4b58873c --- /dev/null +++ b/control-plane/src/kar_quality.rs @@ -0,0 +1,518 @@ +//! Sampled reconstruction diagnostics for a verified sharded KAR archive. +//! These measurements do not substitute for a full-model quality gate. + +use std::{collections::HashMap, fs::File, io::Write, path::Path}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + derived_mixed, gguf, gguf_f32_stream, + kar::{self, VerifiedRangeDecoder}, + model::Manifest, + prepare_preview, stream_parts, +}; + +const SAMPLE_ELEMENTS: u64 = 4096; + +#[derive(Serialize)] +pub struct Report { + pub schema: &'static str, + pub archive_sha256: String, + pub derived_f32_sha256: String, + pub levels: u8, + pub method: &'static str, + pub verification: &'static str, + pub records: Vec, +} + +#[derive(Deserialize)] +struct Provenance { + schema: String, + archive_sha256: String, + derived_f32_sha256: String, + derived_f32_bytes: u64, + levels: u8, + shards: Vec, + tensors: Vec, + partitioned_tensors: Vec, +} + +#[derive(Deserialize)] +struct ProvenanceShard { + name: String, + gguf_sha256: String, + gguf_bytes: u64, + tensor_count: usize, +} + +#[derive(Deserialize)] +struct ProvenanceTensor { + name: String, + source_kind: u32, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Deserialize)] +struct ProvenancePartition { + parent_name: String, + source_kind: u32, + parts: Vec, +} + +#[derive(Deserialize)] +struct ProvenancePart { + name: String, + dimensions: Vec, + source_byte_offset: u64, + source_bytes: u64, + source_sha256: String, + derived_offset: u64, + derived_bytes: u64, + f32_sha256: String, +} + +#[derive(Serialize)] +pub struct RecordError { + pub name: String, + pub parent_name: String, + pub source_kind: u32, + pub elements: u64, + pub sampled_elements: u64, + pub relative_l2: f64, + pub windows: Vec, +} + +#[derive(Serialize)] +pub struct SampleWindow { + pub start: u64, + pub elements: u64, +} + +pub fn analyze( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, +) -> Result { + let summary = + prepare_preview::verify_sharded_streamed(manifest, source_dir, archive_path, levels)?; + let provenance_path = archive_path.with_file_name(format!( + "{}.provenance.json", + archive_path + .file_name() + .ok_or("KAR archive has no file name")? + .to_string_lossy() + )); + let provenance: serde_json::Value = + serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + let archive_sha256 = provenance["archive_sha256"] + .as_str() + .ok_or("verified provenance has no archive digest")? + .to_owned(); + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + if summary.source_digest != identity.derived_sha256 { + return Err("KAR source digest changed after verification".into()); + } + let parts = stream_parts::plan_shards(&identity, source_dir)?; + sample_records( + source_dir, + &identity, + &parts, + VerifiedRangeDecoder::open(archive_path)?, + levels, + archive_sha256, + "full-derived-source-and-archive-verification", + ) +} + +/// Reuse a prior full verification of immutable source shards and archive. +/// Checks metadata and provenance mappings, then reads only sampled payloads. +pub fn analyze_previously_verified( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, +) -> Result { + let provenance_path = archive_path.with_file_name(format!( + "{}.provenance.json", + archive_path + .file_name() + .ok_or("KAR archive has no file name")? + .to_string_lossy() + )); + let provenance: Provenance = + serde_json::from_reader(File::open(provenance_path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + if provenance.schema != "strata-next/sharded-stream-provenance-v4" + || provenance.levels != levels + || !(1..=8).contains(&levels) + { + return Err("KAR sampled analysis requires v4 provenance and matching levels".into()); + } + let (summary, sources) = kar::inspect_with_sources(archive_path)?; + let derived_sha256 = parse_digest(&provenance.derived_f32_sha256)?; + parse_digest(&provenance.archive_sha256)?; + if summary.source_digest != derived_sha256 + || summary.source_bytes != provenance.derived_f32_bytes + || summary.max_planes > levels + { + return Err("KAR metadata differs from recorded provenance".into()); + } + let mut manifest_files = manifest.files.iter().collect::>(); + manifest_files.sort_unstable_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); + if manifest.schema_version != 1 || manifest_files.len() != provenance.shards.len() { + return Err("source manifest differs from recorded shard list".into()); + } + let mut identity = derived_mixed::ShardedIdentity { + derived_sha256, + derived_bytes: provenance.derived_f32_bytes, + shards: Vec::with_capacity(provenance.shards.len()), + tensors: Vec::with_capacity(provenance.tensors.len()), + }; + for (manifest_file, recorded) in manifest_files.iter().zip(&provenance.shards) { + if manifest_file.name != recorded.name + || manifest_file.size != recorded.gguf_bytes + || manifest_file.sha256 != recorded.gguf_sha256 + { + return Err("source manifest differs from recorded provenance".into()); + } + let path = source_dir.join(&recorded.name); + if File::open(path) + .and_then(|file| file.metadata()) + .map_err(|error| error.to_string())? + .len() + != recorded.gguf_bytes + { + return Err("source shard length changed since prior verification".into()); + } + identity.shards.push(derived_mixed::ShardIdentity { + name: recorded.name.clone(), + gguf_sha256: parse_digest(&recorded.gguf_sha256)?, + gguf_bytes: recorded.gguf_bytes, + tensor_count: recorded.tensor_count, + }); + } + for tensor in &provenance.tensors { + identity.tensors.push(derived_mixed::TensorIdentity { + name: tensor.name.clone(), + source_kind: tensor.source_kind, + source_sha256: parse_digest(&tensor.source_sha256)?, + derived_offset: tensor.derived_offset, + derived_bytes: tensor.derived_bytes, + f32_sha256: parse_digest(&tensor.f32_sha256)?, + }); + } + let partitioned = provenance + .partitioned_tensors + .iter() + .map(|entry| (entry.parent_name.as_str(), entry)) + .collect::>(); + if partitioned.len() != provenance.partitioned_tensors.len() { + return Err("duplicate KAR partition parent".into()); + } + let mut parts = Vec::with_capacity(identity.tensors.len()); + let mut number = 0usize; + for shard in &identity.shards { + let index = + gguf::tensor_index(&source_dir.join(&shard.name)).map_err(|error| error.to_string())?; + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes + { + return Err("GGUF shard metadata changed since prior verification".into()); + } + for tensor in &index.tensors { + let recorded = identity + .tensors + .get(number) + .ok_or("GGUF tensor count differs from provenance")?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("GGUF tensor shape overflow")?; + if recorded.name != tensor.name + || recorded.source_kind != tensor.kind + || recorded.derived_bytes != elements * 4 + { + return Err("GGUF tensor metadata differs from provenance".into()); + } + let group = if let Some(split) = partitioned.get(tensor.name.as_str()) { + if split.source_kind != tensor.kind || split.parts.len() < 2 { + return Err("invalid KAR partition metadata".into()); + } + split + .parts + .iter() + .map(|part| { + Ok(stream_parts::PartIdentity { + name: part.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: part.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: part.source_byte_offset, + source_bytes: part.source_bytes, + source_sha256: parse_digest(&part.source_sha256)?, + derived_offset: part.derived_offset, + derived_bytes: part.derived_bytes, + f32_sha256: parse_digest(&part.f32_sha256)?, + }) + }) + .collect::, String>>()? + } else { + vec![stream_parts::PartIdentity { + name: tensor.name.clone(), + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: tensor.dimensions.clone(), + source_kind: tensor.kind, + source_byte_offset: 0, + source_bytes: tensor.bytes, + source_sha256: recorded.source_sha256, + derived_offset: recorded.derived_offset, + derived_bytes: recorded.derived_bytes, + f32_sha256: recorded.f32_sha256, + }] + }; + let mut source_cursor = 0u64; + let mut derived_cursor = recorded.derived_offset; + for part in &group { + let part_elements = part + .dimensions + .iter() + .try_fold(1u64, |n, dim| n.checked_mul(*dim)) + .ok_or("KAR part shape overflow")?; + if part.source_byte_offset != source_cursor + || part.derived_offset != derived_cursor + || part.derived_bytes != part_elements * 4 + { + return Err("KAR part offsets or shape differ from provenance".into()); + } + source_cursor = source_cursor + .checked_add(part.source_bytes) + .ok_or("KAR part source overflow")?; + derived_cursor = derived_cursor + .checked_add(part.derived_bytes) + .ok_or("KAR part derived overflow")?; + } + if source_cursor != tensor.bytes + || derived_cursor != recorded.derived_offset + recorded.derived_bytes + { + return Err("KAR parts do not cover GGUF parent".into()); + } + parts.push(group); + number += 1; + } + } + if number != identity.tensors.len() + || partitioned.len() != parts.iter().filter(|group| group.len() > 1).count() + || sources.len() != parts.iter().map(Vec::len).sum::() + { + return Err("KAR record count differs from provenance".into()); + } + for (record, part) in sources.iter().zip(parts.iter().flatten()) { + if record.name != part.name + || record.dimensions != part.dimensions + || record.dtype != 0 + || record.digest != part.f32_sha256 + || record.offset != part.derived_offset + { + return Err("KAR directory differs from recorded source mapping".into()); + } + } + sample_records( + source_dir, + &identity, + &parts, + VerifiedRangeDecoder::open_previously_verified(archive_path)?, + levels, + provenance.archive_sha256, + "previous-full-verification-assumed; metadata-checked-now", + ) +} + +fn parse_digest(value: &str) -> Result<[u8; 32], String> { + hex::decode(value) + .map_err(|error| error.to_string())? + .try_into() + .map_err(|_| "SHA-256 digest is not 32 bytes".into()) +} + +fn sample_records( + source_dir: &Path, + identity: &derived_mixed::ShardedIdentity, + parts: &[Vec], + mut decoder: VerifiedRangeDecoder, + levels: u8, + archive_sha256: String, + verification: &'static str, +) -> Result { + let mut records = Vec::with_capacity(parts.iter().map(Vec::len).sum()); + let mut number = 0usize; + for shard in &identity.shards { + let path = source_dir.join(&shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + let mut source = File::open(&path).map_err(|error| error.to_string())?; + for tensor in &index.tensors { + let group = parts.get(number).ok_or("KAR source part count changed")?; + for part in group { + let (block_elements, block_bytes) = + gguf::block_geometry(part.source_kind).ok_or("unsupported GGUF source kind")?; + let elements = part.derived_bytes / 4; + let windows = sample_windows(elements, block_elements)?; + let mut error_sum = 0.0f64; + let mut reference_sum = 0.0f64; + let mut sampled_elements = 0u64; + for window in &windows { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|offset| offset.checked_add(part.source_byte_offset)) + .and_then(|offset| { + offset.checked_add(window.start / block_elements * block_bytes) + }) + .ok_or("GGUF sample offset overflow")?; + let source_bytes = window.elements / block_elements * block_bytes; + let mut original = Vec::with_capacity(window.elements as usize); + let decoded_bytes = gguf_f32_stream::visit( + &mut source, + absolute, + part.source_kind, + source_bytes, + |_, f32_bytes| { + original.extend( + f32_bytes + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)), + ); + Ok(()) + }, + )?; + if decoded_bytes != window.elements * 4 + || original.len() != window.elements as usize + { + return Err(format!("{}: GGUF sample shape changed", part.name)); + } + let reconstructed = decoder.decode_range( + &part.name, + levels, + window.start as usize, + window.elements as usize, + )?; + if reconstructed.len() != original.len() { + return Err(format!("{}: KAR sample shape changed", part.name)); + } + for (expected, actual) in original.iter().zip(&reconstructed) { + let delta = f64::from(*expected) - f64::from(*actual); + error_sum += delta * delta; + reference_sum += f64::from(*expected).powi(2); + } + sampled_elements += window.elements; + } + let relative_l2 = if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }; + if !relative_l2.is_finite() { + return Err(format!("{}: non-finite KAR sample error", part.name)); + } + records.push(RecordError { + name: part.name.clone(), + parent_name: part.parent_name.clone(), + source_kind: part.source_kind, + elements, + sampled_elements, + relative_l2, + windows, + }); + } + number += 1; + } + } + if number != parts.len() || records.len() != parts.iter().map(Vec::len).sum::() { + return Err("KAR source records changed during analysis".into()); + } + Ok(Report { + schema: "strata-next/kar-sampled-distortion-v1", + archive_sha256, + derived_f32_sha256: hex::encode(identity.derived_sha256), + levels, + method: "nonoverlapping-first-middle-last-aligned-4096-v2", + verification, + records, + }) +} + +fn sample_windows(elements: u64, block_elements: u64) -> Result, String> { + if elements == 0 || block_elements == 0 || !elements.is_multiple_of(block_elements) { + return Err("invalid GGUF sample geometry".into()); + } + let count = elements.min(SAMPLE_ELEMENTS); + if !count.is_multiple_of(block_elements) { + return Err("GGUF block is larger than quality sample".into()); + } + let end = elements - count; + let starts = if elements >= 3 * count { + vec![0, end / 2 / block_elements * block_elements, end] + } else if elements >= 2 * count { + vec![0, end] + } else { + vec![0] + }; + let mut result = Vec::new(); + for start in starts { + if result + .iter() + .all(|window: &SampleWindow| window.start != start) + { + result.push(SampleWindow { + start, + elements: count, + }); + } + } + Ok(result) +} + +pub fn write_report(path: &Path, report: &Report) -> Result<(), String> { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| error.to_string())?; + let result = (|| -> Result<(), String> { + serde_json::to_writer_pretty(&mut file, report).map_err(|error| error.to_string())?; + file.write_all(b"\n").map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string()) + })(); + if result.is_err() { + let _ = std::fs::remove_file(path); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sampled_windows_are_bounded_and_distinct() { + assert_eq!(sample_windows(256, 256).unwrap().len(), 1); + assert_eq!(sample_windows(5000, 1).unwrap().len(), 1); + assert_eq!(sample_windows(8192, 256).unwrap().len(), 2); + let windows = sample_windows(32_000, 256).unwrap(); + assert_eq!(windows.len(), 3); + assert!(windows.iter().all(|window| { + window.start.is_multiple_of(256) + && window.elements == 4096 + && window.start + window.elements <= 32_000 + })); + } +} diff --git a/control-plane/src/kar_sample.rs b/control-plane/src/kar_sample.rs new file mode 100644 index 00000000..b9643c9c --- /dev/null +++ b/control-plane/src/kar_sample.rs @@ -0,0 +1,305 @@ +//! Deterministic bounded calibration sampling from a GGUF tensor stream. +//! This is an offline preparation primitive; quality approval is separate. + +use std::io::{Read, Seek}; + +use crate::{gguf_f32_stream, kar_codec}; + +pub const MAX_SAMPLE_VALUES: usize = 65_536; + +pub fn sample_normalized( + reader: &mut R, + absolute_offset: u64, + source_kind: u32, + source_bytes: u64, + elements: u64, + source_digest: [u8; 32], + max_samples: usize, +) -> Result, String> { + if elements == 0 || max_samples == 0 || max_samples > MAX_SAMPLE_VALUES { + return Err("invalid KAR sample size or tensor element count".into()); + } + let padded = elements + .div_ceil(32) + .checked_mul(32) + .ok_or("KAR sampled tensor size overflow")?; + let stride = padded.div_ceil(max_samples as u64); + let seed = u64::from_le_bytes(source_digest[..8].try_into().unwrap()); + let mut targets = + Vec::with_capacity(max_samples.min(usize::try_from(padded).unwrap_or(max_samples))); + let mut bucket = 0u64; + let mut start = 0u64; + while start < padded { + let span = stride.min(padded - start); + targets.push(start + mix64(seed ^ bucket) % span); + start += span; + bucket += 1; + } + if elements > 1_048_576 { + return sample_sparse( + reader, + absolute_offset, + source_kind, + source_bytes, + elements, + &targets, + ); + } + let mut sampled = Vec::with_capacity(targets.len()); + let mut group = [0.0f32; 32]; + let mut normalized = [0.0f32; 32]; + let mut filled = 0usize; + let mut position = 0u64; + let mut target_index = 0usize; + let mut seen = 0u64; + let decoded_bytes = gguf_f32_stream::visit( + reader, + absolute_offset, + source_kind, + source_bytes, + |_, f32_bytes| { + for word in f32_bytes.as_chunks::<4>().0 { + if seen >= elements { + return Err("GGUF tensor decodes to more elements than its shape".into()); + } + group[filled] = f32::from_le_bytes(*word); + filled += 1; + seen += 1; + if filled == 32 { + collect_group( + &group, + &mut normalized, + &targets, + &mut target_index, + &mut position, + &mut sampled, + )?; + filled = 0; + } + } + Ok(()) + }, + )?; + if seen != elements || decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? { + return Err("GGUF tensor decoded element count differs from its shape".into()); + } + if filled > 0 { + collect_group( + &group[..filled], + &mut normalized, + &targets, + &mut target_index, + &mut position, + &mut sampled, + )?; + } + if position != padded || target_index != targets.len() { + return Err("KAR calibration sample coverage mismatch".into()); + } + Ok(sampled) +} + +fn sample_sparse( + reader: &mut R, + absolute_offset: u64, + source_kind: u32, + source_bytes: u64, + elements: u64, + targets: &[u64], +) -> Result, String> { + let (block_elements, block_bytes) = crate::gguf::block_geometry(source_kind) + .ok_or("unsupported GGUF source kind for KAR sampling")?; + if !elements.is_multiple_of(block_elements) + || elements / block_elements * block_bytes != source_bytes + { + return Err("KAR sampling source geometry differs from tensor shape".into()); + } + let mut sampled = Vec::with_capacity(targets.len()); + let mut normalized = [0.0f32; 32]; + let mut previous_group = None; + for &target in targets { + let group_start = target / 32 * 32; + if previous_group != Some(group_start) { + let count = (elements - group_start).min(32); + let first_block = group_start / block_elements; + let block_offset = first_block + .checked_mul(block_bytes) + .ok_or("KAR sample block offset overflow")?; + let skip = group_start % block_elements; + let blocks = (skip + count).div_ceil(block_elements); + let bytes = blocks + .checked_mul(block_bytes) + .ok_or("KAR sample byte count overflow")?; + let mut values = Vec::with_capacity((blocks * block_elements * 4) as usize); + gguf_f32_stream::visit( + reader, + absolute_offset + .checked_add(block_offset) + .ok_or("KAR sample absolute offset overflow")?, + source_kind, + bytes, + |_, f32_bytes| { + values.extend_from_slice(f32_bytes); + Ok(()) + }, + )?; + let begin = usize::try_from(skip * 4).map_err(|error| error.to_string())?; + let end = usize::try_from((skip + count) * 4).map_err(|error| error.to_string())?; + let group = values[begin..end] + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)) + .collect::>(); + kar_codec::normalize_group_into(&group, &mut normalized)?; + previous_group = Some(group_start); + } + sampled.push(normalized[(target - group_start) as usize]); + } + Ok(sampled) +} + +fn collect_group( + weights: &[f32], + normalized: &mut [f32; 32], + targets: &[u64], + target_index: &mut usize, + position: &mut u64, + sample: &mut Vec, +) -> Result<(), String> { + kar_codec::normalize_group_into(weights, normalized)?; + for value in normalized { + if targets.get(*target_index) == Some(position) { + sample.push(*value); + *target_index += 1; + } + *position += 1; + } + Ok(()) +} + +fn mix64(mut value: u64) -> u64 { + value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); + value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + value ^ (value >> 31) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::iq3_s; + use std::io::Cursor; + + #[test] + fn small_sample_matches_existing_full_tensor_normalization() { + let weights = (0..33) + .map(|number| (number as f32 - 16.0) / 8.0) + .collect::>(); + let bytes = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let sample = sample_normalized( + &mut Cursor::new(bytes.clone()), + 0, + 0, + bytes.len() as u64, + weights.len() as u64, + [7; 32], + 64, + ) + .unwrap(); + assert_eq!( + sample, + kar_codec::normalize_for_calibration(&weights, 32) + .unwrap() + .values + ); + } + + #[test] + fn large_sample_is_bounded_and_deterministic() { + let weights = (0..2048) + .map(|number| (number as f32 - 1024.0) / 1024.0) + .collect::>(); + let bytes = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let run = || { + sample_normalized( + &mut Cursor::new(&bytes), + 0, + 0, + bytes.len() as u64, + 2048, + [3; 32], + 32, + ) + .unwrap() + }; + assert_eq!(run(), run()); + assert_eq!(run().len(), 32); + } + + #[test] + fn iq3_sampling_stays_bounded_across_source_chunks() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let source = block.repeat(257); + let sample = sample_normalized( + &mut Cursor::new(&source), + 0, + 21, + source.len() as u64, + (257 * iq3_s::BLOCK_ELEMENTS) as u64, + [9; 32], + 64, + ) + .unwrap(); + assert_eq!(sample.len(), 64); + assert!(sample.iter().all(|value| *value == 1.0)); + } + + #[test] + fn sparse_sampling_matches_complete_stream_for_f32_and_iq3() { + let f32_bytes = (0..2048) + .flat_map(|number| ((number as f32 - 1024.0) / 1024.0).to_le_bytes()) + .collect::>(); + let mut iq3_block = [0u8; iq3_s::BLOCK_BYTES]; + iq3_block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let iq3_bytes = iq3_block.repeat(17); + for (kind, bytes, elements) in [(0, f32_bytes, 2048u64), (21, iq3_bytes, 4352u64)] { + let seed = u64::from_le_bytes([11; 8]); + let padded = elements.div_ceil(32) * 32; + let stride = padded.div_ceil(64); + let targets = (0..padded.div_ceil(stride)) + .map(|bucket| { + let start = bucket * stride; + start + mix64(seed ^ bucket) % stride.min(padded - start) + }) + .collect::>(); + let full = sample_normalized( + &mut Cursor::new(&bytes), + 0, + kind, + bytes.len() as u64, + elements, + [11; 32], + 64, + ) + .unwrap(); + let sparse = sample_sparse( + &mut Cursor::new(&bytes), + 0, + kind, + bytes.len() as u64, + elements, + &targets, + ) + .unwrap(); + assert_eq!(sparse, full); + } + } +} diff --git a/control-plane/src/kar_stream_encode.rs b/control-plane/src/kar_stream_encode.rs new file mode 100644 index 00000000..037078d3 --- /dev/null +++ b/control-plane/src/kar_stream_encode.rs @@ -0,0 +1,405 @@ +//! Bounded-memory KAR-2 section encoder. Calibration is supplied explicitly; +//! this module does not approve a lossy rate or a serving configuration. + +use std::{ + fs::{self, File, OpenOptions}, + io::{BufWriter, Read, Seek, SeekFrom, Write}, + path::Path, +}; + +use sha2::{Digest, Sha256}; + +use crate::{gguf_f32_stream, kar_codec}; + +pub struct SectionResult { + pub bytes: u64, + pub digest: [u8; 32], + pub source_digest: [u8; 32], + pub derived_digest: [u8; 32], + pub relative_l2: f64, +} + +pub fn encode_section( + reader: &mut R, + absolute_offset: u64, + source_kind: u32, + source_bytes: u64, + elements: u64, + calibration: &kar_codec::Calibration, + destination: &Path, +) -> Result { + let levels = calibration.books.len(); + if elements == 0 + || !(1..=8).contains(&levels) + || calibration.boundaries.len() != (1usize << levels) - 1 + || calibration + .boundaries + .iter() + .any(|boundary| !boundary.is_finite()) + || calibration + .boundaries + .windows(2) + .any(|pair| pair[0] >= pair[1]) + || calibration.books.iter().enumerate().any(|(index, book)| { + book.len() != 1usize << (index + 1) || book.iter().any(|bits| bits & 0x7c00 == 0x7c00) + }) + { + return Err("invalid streamed KAR calibration".into()); + } + let words = elements.div_ceil(32); + let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?; + let books_start = round_up(scales_bytes, 16)?; + let books_bytes = (1u64 << (levels + 2)) - 4; + let planes_start = round_up( + books_start + .checked_add(books_bytes) + .ok_or("KAR books overflow")?, + 16, + )?; + let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?; + if plane_stride > u32::MAX as u64 { + return Err("KAR plane stride exceeds format limit".into()); + } + let section_bytes = round_up( + planes_start + .checked_add( + plane_stride + .checked_mul(levels as u64) + .ok_or("KAR planes overflow")?, + ) + .ok_or("KAR section overflow")?, + 256, + )?; + let section = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(destination) + .map_err(|error| error.to_string())?; + let result = (|| -> Result { + section + .set_len(section_bytes) + .map_err(|error| error.to_string())?; + let mut scale_writer = writer_at(destination, 0)?; + let mut plane_writers = (0..levels) + .map(|level| writer_at(destination, planes_start + level as u64 * plane_stride)) + .collect::, _>>()?; + let mut pending = [0.0f32; 32]; + let mut filled = 0usize; + let mut seen = 0u64; + let mut groups = 0u64; + let mut error_sum = 0.0f64; + let mut reference_sum = 0.0f64; + let mut source_hash = Sha256::new(); + let mut derived_hash = Sha256::new(); + let decoded_bytes = gguf_f32_stream::visit( + reader, + absolute_offset, + source_kind, + source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + derived_hash.update(f32_bytes); + for word in f32_bytes.as_chunks::<4>().0 { + if seen >= elements { + return Err("GGUF tensor decodes beyond its shape".into()); + } + pending[filled] = f32::from_le_bytes(*word); + filled += 1; + seen += 1; + if filled == 32 { + write_group( + &pending, + calibration, + &mut scale_writer, + &mut plane_writers, + &mut error_sum, + &mut reference_sum, + )?; + filled = 0; + groups += 1; + } + } + Ok(()) + }, + )?; + if seen != elements + || decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")? + { + return Err("GGUF decoded tensor shape mismatch".into()); + } + if filled != 0 { + write_group( + &pending[..filled], + calibration, + &mut scale_writer, + &mut plane_writers, + &mut error_sum, + &mut reference_sum, + )?; + groups += 1; + } + if groups != words { + return Err("KAR encoded group count mismatch".into()); + } + scale_writer.flush().map_err(|error| error.to_string())?; + for writer in &mut plane_writers { + writer.flush().map_err(|error| error.to_string())?; + } + drop(scale_writer); + drop(plane_writers); + let mut book_writer = writer_at(destination, books_start)?; + for book in &calibration.books { + for bits in book { + book_writer + .write_all(&bits.to_le_bytes()) + .map_err(|error| error.to_string())?; + } + } + book_writer.flush().map_err(|error| error.to_string())?; + drop(book_writer); + section.sync_all().map_err(|error| error.to_string())?; + let digest = hash_file(destination)?; + let relative_l2 = if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }; + Ok(SectionResult { + bytes: section_bytes, + digest, + source_digest: source_hash.finalize().into(), + derived_digest: derived_hash.finalize().into(), + relative_l2, + }) + })(); + drop(section); + if result.is_err() { + let _ = fs::remove_file(destination); + } + result +} + +fn write_group( + weights: &[f32], + calibration: &kar_codec::Calibration, + scales: &mut BufWriter, + planes: &mut [BufWriter], + error_sum: &mut f64, + reference_sum: &mut f64, +) -> Result<(), String> { + let mut normalized = [0.0f32; 32]; + let scale = kar_codec::normalize_group_into(weights, &mut normalized)?; + scales + .write_all(&scale.to_le_bytes()) + .map_err(|error| error.to_string())?; + let mut words = [0u32; 8]; + let final_book = calibration.books.last().ok_or("missing KAR codebook")?; + let rounded_scale = kar_codec::f16_bits_to_f32(scale); + for (position, value) in normalized.iter().enumerate() { + let index = calibration + .boundaries + .partition_point(|boundary| *boundary < *value); + for (level, word) in words[..planes.len()].iter_mut().enumerate() { + let bit = (index >> (planes.len() - 1 - level)) & 1; + *word |= (bit as u32) << position; + } + if let Some(original) = weights.get(position) { + let rebuilt = kar_codec::f16_bits_to_f32(final_book[index]) * rounded_scale; + let delta = f64::from(*original) - f64::from(rebuilt); + *error_sum += delta * delta; + *reference_sum += f64::from(*original).powi(2); + } + } + for (writer, word) in planes.iter_mut().zip(words) { + writer + .write_all(&word.to_le_bytes()) + .map_err(|error| error.to_string())?; + } + Ok(()) +} + +fn writer_at(path: &Path, offset: u64) -> Result, String> { + let mut file = OpenOptions::new() + .write(true) + .open(path) + .map_err(|error| error.to_string())?; + file.seek(SeekFrom::Start(offset)) + .map_err(|error| error.to_string())?; + Ok(BufWriter::with_capacity(64 * 1024, file)) +} + +fn round_up(value: u64, alignment: u64) -> Result { + value + .div_ceil(alignment) + .checked_mul(alignment) + .ok_or("KAR section offset overflow".into()) +} + +fn hash_file(path: &Path) -> Result<[u8; 32], String> { + let mut file = File::open(path).map_err(|error| error.to_string())?; + let mut hash = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = file.read(&mut buffer).map_err(|error| error.to_string())?; + if count == 0 { + break; + } + hash.update(&buffer[..count]); + } + Ok(hash.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{iq3_s, kar, kar_writer}; + use std::io::Cursor; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[test] + fn streamed_section_matches_existing_writer_and_forms_verified_archive() { + let root = std::env::temp_dir().join(format!( + "strata-stream-section-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&root).unwrap(); + let weights = (0..33) + .map(|number| [-1.0f32, -0.25, 0.25, 1.0][number % 4]) + .collect::>(); + let source = weights + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let calibration = kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + }; + let expected = + kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, 2).unwrap(); + let books = calibration + .books + .iter() + .map(Vec::as_slice) + .collect::>(); + let planes = expected + .planes + .iter() + .map(Vec::as_slice) + .collect::>(); + let source_digest: [u8; 32] = Sha256::digest(&source).into(); + let reference = root.join("reference.section"); + kar_writer::write_nested_section( + &reference, + &kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &expected.scales, + books: &books, + planes: &planes, + }, + }, + ) + .unwrap(); + let output = root.join("streamed.section"); + let streamed = encode_section( + &mut Cursor::new(&source), + 0, + 0, + source.len() as u64, + weights.len() as u64, + &calibration, + &output, + ) + .unwrap(); + assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap()); + assert_eq!(streamed.source_digest, source_digest); + assert_eq!(streamed.derived_digest, source_digest); + assert!(streamed.relative_l2.is_finite()); + let archive = root.join("model.kar"); + kar_writer::write_archive( + &archive, + &kar_writer::SourceIdentity { + name: "streamed-test", + architecture: "synthetic", + builder: "test-streamed-g32-l2", + digest: source_digest, + total_elements: 33, + bytes: source.len() as u64, + }, + &[kar_writer::Tensor { + name: "expert", + dims: &[33], + source_dtype: 0, + source_digest, + source_offset: 0, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: &output, + offset: 0, + bytes: streamed.bytes, + digest: streamed.digest, + }, + }], + ) + .unwrap(); + assert_eq!(kar::verify(&archive).unwrap().tensor_count, 1); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn iq3_section_preserves_source_and_virtual_f32_identity_across_chunks() { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let source = block.repeat(257); + let calibration = kar_codec::Calibration { + boundaries: vec![-0.5, 0.0, 0.5], + books: vec![vec![0xb800, 0x3800], vec![0xba00, 0xb400, 0x3400, 0x3a00]], + }; + let path = std::env::temp_dir().join(format!( + "strata-iq3-stream-{}-{}.section", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let result = encode_section( + &mut Cursor::new(&source), + 0, + 21, + source.len() as u64, + (257 * iq3_s::BLOCK_ELEMENTS) as u64, + &calibration, + &path, + ) + .unwrap(); + assert_eq!( + result.source_digest.as_slice(), + Sha256::digest(&source).as_slice() + ); + let virtual_f32 = 1.0f32.to_le_bytes().repeat(257 * iq3_s::BLOCK_ELEMENTS); + assert_eq!( + result.derived_digest.as_slice(), + Sha256::digest(&virtual_f32).as_slice() + ); + assert_eq!(result.relative_l2, 0.25); + fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/kar_writer.rs b/control-plane/src/kar_writer.rs new file mode 100644 index 00000000..e55065f3 --- /dev/null +++ b/control-plane/src/kar_writer.rs @@ -0,0 +1,1293 @@ +//! KAR-2 container writer for already encoded tensors. Compression policy and +//! GGUF conversion are separate; this module never chooses a lossy precision. + +use std::{ + collections::HashSet, + fs::{self, File, OpenOptions}, + io::{Read, Seek, SeekFrom, Write}, + path::Path, +}; + +use sha2::{Digest, Sha256}; + +use crate::kar; + +pub struct SourceIdentity<'a> { + pub name: &'a str, + pub architecture: &'a str, + pub builder: &'a str, + pub digest: [u8; 32], + pub total_elements: u64, + pub bytes: u64, +} + +pub struct Tensor<'a> { + pub name: &'a str, + pub dims: &'a [u64], + pub source_dtype: u8, + pub source_digest: [u8; 32], + pub source_offset: u64, + pub data: TensorData<'a>, +} + +pub enum TensorData<'a> { + Raw(&'a [u8]), + RawFile { + path: &'a Path, + offset: u64, + bytes: u64, + }, + Nested { + group: u16, + nesting: u8, + planes_min: u8, + planes_max: u8, + scales: &'a [u16], + books: &'a [&'a [u16]], + planes: &'a [&'a [u32]], + }, + /// Canonical KAR-2 section bytes produced by a tensor encoder. The writer + /// checks layout, f16 values, zero padding, and the supplied section hash. + NestedFile { + group: u16, + nesting: u8, + planes_min: u8, + planes_max: u8, + levels: u8, + path: &'a Path, + offset: u64, + bytes: u64, + digest: [u8; 32], + }, +} + +struct NestedLayout { + n_padded: u64, + section_bytes: u64, + scales_offset: u64, + books_offset: u64, + planes_offset: u64, + plane_stride: u32, + payload_bits: u64, +} + +struct Placed<'a> { + tensor: &'a Tensor<'a>, + name_offset: u32, + n_elements: u64, + n_padded: u64, + section_offset: u64, + section_bytes: u64, + scales_offset: u64, + books_offset: u64, + planes_offset: u64, + plane_stride: u32, + payload_crc32: u32, +} + +pub fn write_archive( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], +) -> Result { + write_archive_inner(destination, source, tensors, false) +} + +/// Consume caller-owned, private staging files as their sections are copied. +/// This bounds peak disk use during streamed model preparation. A failed build +/// must be restarted because some input sections may already be removed. +pub(crate) fn write_archive_consuming_files( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], +) -> Result { + if tensors.iter().any(|tensor| { + !matches!( + &tensor.data, + TensorData::RawFile { .. } | TensorData::NestedFile { .. } + ) + }) { + return Err("consuming KAR writer requires file-backed tensors".into()); + } + write_archive_inner(destination, source, tensors, true) +} + +fn write_archive_inner( + destination: &Path, + source: &SourceIdentity<'_>, + tensors: &[Tensor<'_>], + consume_files: bool, +) -> Result { + if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 { + return Err("KAR destination exists or tensor count is invalid".into()); + } + if source.bytes == 0 || source.total_elements == 0 { + return Err("KAR source identity needs nonzero bytes and elements".into()); + } + let mut names = Vec::new(); + let mut name_offsets = Vec::with_capacity(tensors.len()); + let mut unique = HashSet::new(); + for tensor in tensors { + if tensor.name.is_empty() || !unique.insert(tensor.name) { + return Err("KAR tensor names must be nonempty and unique".into()); + } + name_offsets.push(u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?); + push_cstr(&mut names, tensor.name)?; + } + let source_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; + push_cstr(&mut names, source.name)?; + let source_arch = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; + push_cstr(&mut names, source.architecture)?; + let builder_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?; + push_cstr(&mut names, source.builder)?; + if names.len() > 64 * 1024 * 1024 { + return Err("KAR string table exceeds inspector limit".into()); + } + + let directory_offset = 256u64; + let directory_bytes = (tensors.len() as u64) + .checked_mul(192) + .ok_or("KAR directory overflow")?; + let string_offset = round_up(directory_offset + directory_bytes, 64)?; + let payload_offset = round_up(string_offset + names.len() as u64, 256)?; + let mut cursor = payload_offset; + let mut total_elements = 0u64; + let mut payload_bits = 0u64; + let mut min_planes = u8::MAX; + let mut max_planes = 0u8; + let mut placed = Vec::with_capacity(tensors.len()); + for (tensor, &name_offset) in tensors.iter().zip(&name_offsets) { + let n_elements = validate_shape(tensor)?; + total_elements = total_elements + .checked_add(n_elements) + .ok_or("KAR element count overflow")?; + let (n_padded, section_bytes, scales_offset, books_offset, planes_offset, plane_stride) = + match &tensor.data { + TensorData::Raw(raw) => { + let width = if tensor.source_dtype == 0 { 4 } else { 2 }; + if raw.len() as u64 + != n_elements + .checked_mul(width) + .ok_or("KAR RAW byte count overflow")? + { + return Err(format!( + "{}: RAW byte count differs from tensor shape", + tensor.name + )); + } + (n_elements, round_up(raw.len() as u64, 256)?, 0, 0, 0, 0) + } + TensorData::RawFile { bytes, .. } => { + let width = if tensor.source_dtype == 0 { 4 } else { 2 }; + if *bytes + != n_elements + .checked_mul(width) + .ok_or("KAR RAW byte count overflow")? + { + return Err(format!( + "{}: RAW file byte count differs from tensor shape", + tensor.name + )); + } + (n_elements, round_up(*bytes, 256)?, 0, 0, 0, 0) + } + TensorData::Nested { + group, + nesting, + planes_min, + planes_max, + scales, + books, + planes, + } => { + let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?; + let layout = nested_layout( + cursor, + n_elements, + *group, + *nesting, + *planes_min, + *planes_max, + levels, + )?; + validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?; + payload_bits = payload_bits + .checked_add(layout.payload_bits) + .ok_or("KAR payload bit count overflow")?; + min_planes = min_planes.min(*planes_min); + max_planes = max_planes.max(*planes_max); + ( + layout.n_padded, + layout.section_bytes, + layout.scales_offset, + layout.books_offset, + layout.planes_offset, + layout.plane_stride, + ) + } + TensorData::NestedFile { + group, + nesting, + planes_min, + planes_max, + levels, + bytes, + .. + } => { + let layout = nested_layout( + cursor, + n_elements, + *group, + *nesting, + *planes_min, + *planes_max, + *levels, + )?; + if *bytes != layout.section_bytes { + return Err(format!( + "{}: nested file section size mismatch", + tensor.name + )); + } + payload_bits = payload_bits + .checked_add(layout.payload_bits) + .ok_or("KAR payload bit count overflow")?; + min_planes = min_planes.min(*planes_min); + max_planes = max_planes.max(*planes_max); + ( + layout.n_padded, + layout.section_bytes, + layout.scales_offset, + layout.books_offset, + layout.planes_offset, + layout.plane_stride, + ) + } + }; + placed.push(Placed { + tensor, + name_offset, + n_elements, + n_padded, + section_offset: cursor, + section_bytes, + scales_offset, + books_offset, + planes_offset, + plane_stride, + payload_crc32: 0, + }); + cursor = cursor + .checked_add(section_bytes) + .ok_or("KAR archive size overflow")?; + } + if total_elements > source.total_elements { + return Err("KAR tensors exceed source element count".into()); + } + let archive_bytes = cursor; + let temporary = destination.with_file_name(format!( + "{}.part", + destination + .file_name() + .ok_or("KAR destination has no filename")? + .to_string_lossy() + )); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .map_err(|error| error.to_string())?; + let result = (|| -> Result<(), String> { + file.set_len(payload_offset) + .map_err(|error| error.to_string())?; + file.seek(SeekFrom::Start(string_offset)) + .map_err(|error| error.to_string())?; + file.write_all(&names).map_err(|error| error.to_string())?; + for entry in &mut placed { + entry.payload_crc32 = write_section(&mut file, entry)?; + if consume_files { + let path = match &entry.tensor.data { + TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path, + _ => unreachable!(), + }; + fs::remove_file(path).map_err(|error| error.to_string())?; + } + } + if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes { + return Err("KAR writer produced the wrong archive length".into()); + } + let mut directory = vec![0u8; directory_bytes as usize]; + let (records, remainder) = directory.as_chunks_mut::<192>(); + debug_assert!(remainder.is_empty()); + for (entry, record) in placed.iter().zip(records) { + write_record(record, entry)?; + } + file.seek(SeekFrom::Start(directory_offset)) + .map_err(|error| error.to_string())?; + file.write_all(&directory) + .map_err(|error| error.to_string())?; + let mut digest = Sha256::new(); + digest.update(&names); + digest.update(&directory); + let mut header = [0u8; 256]; + header[..8].copy_from_slice(b"KARCHIV2"); + put_u32(&mut header, 8, 2); + put_u32(&mut header, 12, 0x0403_0201); + put_u32(&mut header, 16, 256); + put_u32(&mut header, 20, 192); + put_u64(&mut header, 24, directory_offset); + put_u32(&mut header, 32, tensors.len() as u32); + put_u64(&mut header, 40, string_offset); + put_u64(&mut header, 48, names.len() as u64); + put_u64(&mut header, 56, payload_offset); + put_u64(&mut header, 64, archive_bytes); + put_u64(&mut header, 72, total_elements); + put_u64(&mut header, 80, payload_bits); + put_u64(&mut header, 88, source.total_elements); + header[96..104] + .copy_from_slice(&(archive_bytes as f64 * 8.0 / total_elements as f64).to_le_bytes()); + header[104] = if min_planes == u8::MAX { 0 } else { min_planes }; + header[105] = max_planes; + header[106] = 1; + put_u32(&mut header, 108, source_name); + put_u32(&mut header, 112, source_arch); + put_u32(&mut header, 116, builder_name); + put_u64(&mut header, 120, source.bytes); + header[128..160].copy_from_slice(&source.digest); + header[160..192].copy_from_slice(&digest.finalize()); + let header_crc = kar::crc32(&header[..192]); + put_u32(&mut header, 192, header_crc); + file.seek(SeekFrom::Start(0)) + .map_err(|error| error.to_string())?; + file.write_all(&header).map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string())?; + Ok(()) + })(); + drop(file); + if let Err(error) = result { + let _ = fs::remove_file(&temporary); + return Err(error); + } + let summary = match kar::verify(&temporary) { + Ok(summary) => summary, + Err(error) => { + let _ = fs::remove_file(&temporary); + return Err(error); + } + }; + // A hard link publishes a fully written archive atomically without replacing + // an existing destination, even if another writer won the race after preflight. + if let Err(error) = fs::hard_link(&temporary, destination) { + let _ = fs::remove_file(&temporary); + return Err(error.to_string()); + } + fs::remove_file(&temporary).map_err(|error| error.to_string())?; + Ok(summary) +} + +pub struct SectionSummary { + pub bytes: u64, + pub digest: [u8; 32], +} + +/// Write one canonical NESTED section for later bounded-memory archive assembly. +/// The destination must not exist and is meant to live in a private staging dir. +pub fn write_nested_section( + destination: &Path, + tensor: &Tensor<'_>, +) -> Result { + let n_elements = validate_shape(tensor)?; + let TensorData::Nested { + group, + nesting, + planes_min, + planes_max, + scales, + books, + planes, + } = &tensor.data + else { + return Err("KAR section spool requires in-memory NESTED tensor".into()); + }; + let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?; + let layout = nested_layout( + 0, + n_elements, + *group, + *nesting, + *planes_min, + *planes_max, + levels, + )?; + validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?; + let entry = Placed { + tensor, + name_offset: 0, + n_elements, + n_padded: layout.n_padded, + section_offset: 0, + section_bytes: layout.section_bytes, + scales_offset: layout.scales_offset, + books_offset: layout.books_offset, + planes_offset: layout.planes_offset, + plane_stride: layout.plane_stride, + payload_crc32: 0, + }; + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .open(destination) + .map_err(|error| error.to_string())?; + let result = (|| -> Result<(), String> { + write_section(&mut output, &entry)?; + if output.metadata().map_err(|error| error.to_string())?.len() != layout.section_bytes { + return Err("KAR section spool size mismatch".into()); + } + output.sync_all().map_err(|error| error.to_string())?; + Ok(()) + })(); + drop(output); + if let Err(error) = result { + let _ = fs::remove_file(destination); + return Err(error); + } + let verified = (|| -> Result { + let mut file = File::open(destination).map_err(|error| error.to_string())?; + validate_nested_file(&mut file, &entry, 0, *group, levels)?; + file.seek(SeekFrom::Start(0)) + .map_err(|error| error.to_string())?; + let mut digest = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = file.read(&mut buffer).map_err(|error| error.to_string())?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(SectionSummary { + bytes: layout.section_bytes, + digest: digest.finalize().into(), + }) + })(); + if verified.is_err() { + let _ = fs::remove_file(destination); + } + verified +} + +fn validate_shape(tensor: &Tensor<'_>) -> Result { + if !(1..=4).contains(&tensor.dims.len()) || tensor.source_dtype > 2 { + return Err(format!( + "{}: unsupported KAR dimensions or dtype", + tensor.name + )); + } + let n = tensor + .dims + .iter() + .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) + .ok_or("KAR tensor shape overflow")?; + if n == 0 { + return Err("KAR tensor has zero elements".into()); + } + Ok(n) +} + +fn validate_nested_slices( + name: &str, + layout: &NestedLayout, + group: u16, + scales: &[u16], + books: &[&[u16]], + planes: &[&[u32]], +) -> Result<(), String> { + if books.len() != planes.len() { + return Err(format!("{name}: level book count mismatch")); + } + if scales.len() as u64 != layout.n_padded / u64::from(group) { + return Err(format!("{name}: scale count mismatch")); + } + if scales.iter().any(|bits| bits & 0x7c00 == 0x7c00) { + return Err(format!("{name}: non-finite f16 scale")); + } + for (index, book) in books.iter().enumerate() { + if book.len() != 1usize << (index + 1) { + return Err(format!("{name}: level book size mismatch")); + } + if book.iter().any(|bits| bits & 0x7c00 == 0x7c00) { + return Err(format!("{name}: non-finite f16 codebook")); + } + } + if planes + .iter() + .any(|plane| plane.len() as u64 != layout.n_padded / 32) + { + return Err(format!("{name}: plane word count mismatch")); + } + Ok(()) +} + +fn push_cstr(destination: &mut Vec, value: &str) -> Result<(), String> { + if value.contains('\0') { + return Err("KAR names cannot contain NUL".into()); + } + destination.extend_from_slice(value.as_bytes()); + destination.push(0); + Ok(()) +} + +fn round_up(value: u64, alignment: u64) -> Result { + value + .div_ceil(alignment) + .checked_mul(alignment) + .ok_or("KAR aligned offset overflow".into()) +} + +fn nested_layout( + cursor: u64, + n_elements: u64, + group: u16, + nesting: u8, + planes_min: u8, + planes_max: u8, + levels: u8, +) -> Result { + let group = u64::from(group); + if group == 0 + || group > 1024 + || !group.is_multiple_of(32) + || !(1..=16).contains(&levels) + || nesting > 1 + || planes_min == 0 + || planes_min > planes_max + || planes_max > levels + { + return Err("invalid nested KAR parameters".into()); + } + let n_padded = n_elements + .div_ceil(group) + .checked_mul(group) + .ok_or("KAR padded size overflow")?; + let groups = n_padded / group; + let words = n_padded / 32; + let scales_bytes = groups.checked_mul(2).ok_or("KAR scales overflow")?; + let books_offset = round_up( + cursor + .checked_add(scales_bytes) + .ok_or("KAR scales overflow")?, + 16, + )?; + let book_bytes = (1u64 << (levels as u32 + 2)) - 4; + let planes_offset = round_up( + books_offset + .checked_add(book_bytes) + .ok_or("KAR books overflow")?, + 16, + )?; + let stride = round_up(words.checked_mul(4).ok_or("KAR plane size overflow")?, 16)?; + let plane_stride = u32::try_from(stride).map_err(|_| "KAR plane stride exceeds u32")?; + let end = planes_offset + .checked_add( + (levels as u64) + .checked_mul(stride) + .ok_or("KAR planes overflow")?, + ) + .ok_or("KAR planes overflow")?; + let section_bytes = round_up( + end.checked_sub(cursor) + .ok_or("KAR section offset underflow")?, + 256, + )?; + let payload_bits = (levels as u64) + .checked_mul(n_padded) + .and_then(|value| value.checked_add(groups.checked_mul(16)?)) + .ok_or("KAR payload bit count overflow")?; + Ok(NestedLayout { + n_padded, + section_bytes, + scales_offset: cursor, + books_offset, + planes_offset, + plane_stride, + payload_bits, + }) +} + +fn write_section(file: &mut File, entry: &Placed<'_>) -> Result { + file.seek(SeekFrom::Start(entry.section_offset)) + .map_err(|error| error.to_string())?; + let mut crc = !0u32; + let mut written = 0u64; + match &entry.tensor.data { + TensorData::Raw(raw) => write_bytes(file, raw, &mut crc, &mut written)?, + TensorData::RawFile { + path, + offset, + bytes, + } => { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let source_len = source.metadata().map_err(|error| error.to_string())?.len(); + if offset + .checked_add(*bytes) + .is_none_or(|end| end > source_len) + { + return Err("KAR RAW source file is truncated".into()); + } + source + .seek(SeekFrom::Start(*offset)) + .map_err(|error| error.to_string())?; + let mut remaining = *bytes; + let mut buffer = vec![0u8; 1024 * 1024]; + let mut digest = Sha256::new(); + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + source + .read_exact(&mut buffer[..count]) + .map_err(|error| error.to_string())?; + digest.update(&buffer[..count]); + write_bytes(file, &buffer[..count], &mut crc, &mut written)?; + remaining -= count as u64; + } + if digest.finalize().as_slice() != entry.tensor.source_digest { + return Err(format!("{}: RAW source digest mismatch", entry.tensor.name)); + } + } + TensorData::NestedFile { + group, + levels, + path, + offset, + bytes, + digest, + .. + } => { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let source_len = source.metadata().map_err(|error| error.to_string())?.len(); + if offset + .checked_add(*bytes) + .is_none_or(|end| end > source_len) + { + return Err("KAR nested source file is truncated".into()); + } + validate_nested_file(&mut source, entry, *offset, *group, *levels)?; + source + .seek(SeekFrom::Start(*offset)) + .map_err(|error| error.to_string())?; + let mut remaining = *bytes; + let mut buffer = vec![0u8; 1024 * 1024]; + let mut actual_digest = Sha256::new(); + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + source + .read_exact(&mut buffer[..count]) + .map_err(|error| error.to_string())?; + actual_digest.update(&buffer[..count]); + write_bytes(file, &buffer[..count], &mut crc, &mut written)?; + remaining -= count as u64; + } + if actual_digest.finalize().as_slice() != *digest { + return Err(format!( + "{}: nested section digest mismatch", + entry.tensor.name + )); + } + } + TensorData::Nested { + scales, + books, + planes, + .. + } => { + for value in *scales { + write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; + } + pad_to( + file, + entry.books_offset - entry.section_offset, + &mut crc, + &mut written, + )?; + for book in *books { + for value in *book { + write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; + } + } + pad_to( + file, + entry.planes_offset - entry.section_offset, + &mut crc, + &mut written, + )?; + for plane in *planes { + let base = written; + for value in *plane { + write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?; + } + pad_to( + file, + base + entry.plane_stride as u64, + &mut crc, + &mut written, + )?; + } + } + } + pad_to(file, entry.section_bytes, &mut crc, &mut written)?; + Ok(!crc) +} + +#[derive(Clone, Copy)] +enum RegionRule { + FiniteScale, + FiniteBook, + ZeroPadding, +} + +fn validate_nested_file( + source: &mut File, + entry: &Placed<'_>, + source_offset: u64, + group: u16, + levels: u8, +) -> Result<(), String> { + let scales_bytes = (entry.n_padded / u64::from(group)) * 2; + let books_start = entry.books_offset - entry.section_offset; + let books_bytes = (1u64 << (u32::from(levels) + 2)) - 4; + let planes_start = entry.planes_offset - entry.section_offset; + let plane_bytes = (entry.n_padded / 32) * 4; + let stride = u64::from(entry.plane_stride); + check_file_region(source, source_offset, scales_bytes, RegionRule::FiniteScale)?; + check_file_region( + source, + source_offset + scales_bytes, + books_start - scales_bytes, + RegionRule::ZeroPadding, + )?; + check_file_region( + source, + source_offset + books_start, + books_bytes, + RegionRule::FiniteBook, + )?; + check_file_region( + source, + source_offset + books_start + books_bytes, + planes_start - books_start - books_bytes, + RegionRule::ZeroPadding, + )?; + for level in 0..u64::from(levels) { + check_file_region( + source, + source_offset + planes_start + level * stride + plane_bytes, + stride - plane_bytes, + RegionRule::ZeroPadding, + )?; + } + let used_end = planes_start + u64::from(levels) * stride; + check_file_region( + source, + source_offset + used_end, + entry.section_bytes - used_end, + RegionRule::ZeroPadding, + )?; + Ok(()) +} + +fn check_file_region( + source: &mut File, + offset: u64, + bytes: u64, + rule: RegionRule, +) -> Result<(), String> { + source + .seek(SeekFrom::Start(offset)) + .map_err(|error| error.to_string())?; + let mut remaining = bytes; + let mut buffer = [0u8; 64 * 1024]; + while remaining > 0 { + let count = remaining.min(buffer.len() as u64) as usize; + source + .read_exact(&mut buffer[..count]) + .map_err(|error| error.to_string())?; + match rule { + RegionRule::FiniteScale | RegionRule::FiniteBook => { + if buffer[..count] + .as_chunks::<2>() + .0 + .iter() + .any(|pair| u16::from_le_bytes(*pair) & 0x7c00 == 0x7c00) + { + let name = if matches!(rule, RegionRule::FiniteScale) { + "scale" + } else { + "codebook" + }; + return Err(format!("non-finite f16 {name} in nested file")); + } + } + RegionRule::ZeroPadding => { + if buffer[..count].iter().any(|byte| *byte != 0) { + return Err("nonzero padding in nested file".into()); + } + } + } + remaining -= count as u64; + } + Ok(()) +} + +fn write_bytes( + file: &mut File, + bytes: &[u8], + crc: &mut u32, + written: &mut u64, +) -> Result<(), String> { + file.write_all(bytes).map_err(|error| error.to_string())?; + *crc = kar::crc32_step(*crc, bytes); + *written = written + .checked_add(bytes.len() as u64) + .ok_or("KAR section write overflow")?; + Ok(()) +} + +fn pad_to(file: &mut File, target: u64, crc: &mut u32, written: &mut u64) -> Result<(), String> { + if *written > target { + return Err("KAR section exceeds planned layout".into()); + } + let zeros = [0u8; 4096]; + while *written < target { + let count = (target - *written).min(zeros.len() as u64) as usize; + write_bytes(file, &zeros[..count], crc, written)?; + } + Ok(()) +} + +fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> { + let tensor = entry.tensor; + put_u32(record, 0, entry.name_offset); + put_u16( + record, + 4, + u16::try_from(tensor.name.len()).map_err(|_| "KAR tensor name too long")?, + ); + record[6] = tensor.dims.len() as u8; + record[7] = u8::from(matches!( + tensor.data, + TensorData::Raw(_) | TensorData::RawFile { .. } + )); + for index in 0..4 { + put_u64( + record, + 8 + index * 8, + tensor.dims.get(index).copied().unwrap_or(1), + ); + } + record[41] = tensor.source_dtype; + let nested = match &tensor.data { + TensorData::Nested { + group, + nesting, + planes_min, + planes_max, + planes, + .. + } => Some(( + *group, + *nesting, + *planes_min, + *planes_max, + planes.len() as u8, + )), + TensorData::NestedFile { + group, + nesting, + planes_min, + planes_max, + levels, + .. + } => Some((*group, *nesting, *planes_min, *planes_max, *levels)), + _ => None, + }; + if let Some((group, nesting, planes_min, planes_max, levels)) = nested { + record[42] = levels; + record[43] = planes_min; + record[44] = planes_max; + record[45] = nesting; + put_u16(record, 46, group); + put_u64(record, 64, entry.scales_offset); + put_u64( + record, + 72, + (entry.n_padded / u64::from(group)) + .checked_mul(2) + .ok_or("KAR scales overflow")?, + ); + put_u64(record, 80, entry.books_offset); + put_u64(record, 88, (1u64 << (u32::from(levels) + 2)) - 4); + put_u64(record, 96, entry.planes_offset); + put_u32(record, 104, entry.plane_stride); + } + put_u64(record, 48, entry.n_elements); + put_u64(record, 56, entry.n_padded); + put_u32(record, 108, entry.payload_crc32); + put_u64(record, 112, entry.section_offset); + put_u64(record, 120, entry.section_bytes); + record[128..160].copy_from_slice(&tensor.source_digest); + put_u64(record, 160, tensor.source_offset); + Ok(()) +} + +fn put_u16(bytes: &mut [u8], offset: usize, value: u16) { + bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); +} +fn put_u32(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); +} +fn put_u64(bytes: &mut [u8], offset: usize, value: u64) { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn streams_canonical_nested_section_and_rejects_corruption() { + let source = SourceIdentity { + name: "nested-fixture", + architecture: "qwen35", + builder: "strata-next-test", + digest: Sha256::digest(b"source").into(), + total_elements: 32, + bytes: 6, + }; + let book1 = [0xbc00, 0x3c00]; + let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let plane1 = [0xaaaa_aaaa]; + let plane2 = [0x5555_5555]; + let planes: [&[u32]; 2] = [&plane1, &plane2]; + let source_digest: [u8; 32] = Sha256::digest(b"weights").into(); + let original = + std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id())); + let streamed = + std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id())); + let spool = + std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id())); + let _ = fs::remove_file(&original); + let _ = fs::remove_file(&streamed); + let nested = [Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest, + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }]; + write_archive(&original, &source, &nested).unwrap(); + let reference = fs::read(&original).unwrap(); + let section_offset = + u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize; + let section_bytes = + u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize; + let section = &reference[section_offset..section_offset + section_bytes]; + let native_spool = std::env::temp_dir().join(format!( + "strata-nested-native-spool-{}.bin", + std::process::id() + )); + let _ = fs::remove_file(&native_spool); + let native_section = write_nested_section(&native_spool, &nested[0]).unwrap(); + assert_eq!(native_section.bytes, section_bytes as u64); + assert_eq!(fs::read(&native_spool).unwrap(), section); + let expected_digest: [u8; 32] = Sha256::digest(section).into(); + assert_eq!(native_section.digest, expected_digest); + let mut spool_bytes = vec![0xabu8; 11]; + spool_bytes.extend_from_slice(section); + fs::write(&spool, &spool_bytes).unwrap(); + let digest: [u8; 32] = Sha256::digest(section).into(); + let file_tensor = |digest| { + [Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest, + source_offset: 0, + data: TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + levels: 2, + path: &spool, + offset: 11, + bytes: section_bytes as u64, + digest, + }, + }] + }; + write_archive(&streamed, &source, &file_tensor(digest)).unwrap(); + assert_eq!(fs::read(&streamed).unwrap(), reference); + fs::remove_file(&streamed).unwrap(); + + spool_bytes[11] = 0; + spool_bytes[12] = 0x7c; + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor(digest)) + .unwrap_err() + .contains("non-finite f16 scale") + ); + assert!(!streamed.exists()); + spool_bytes[11..11 + section_bytes].copy_from_slice(section); + spool_bytes[13] = 1; + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor(digest)) + .unwrap_err() + .contains("nonzero padding") + ); + assert!(!streamed.exists()); + spool_bytes[11..11 + section_bytes].copy_from_slice(section); + fs::write(&spool, &spool_bytes).unwrap(); + assert!( + write_archive(&streamed, &source, &file_tensor([0; 32])) + .unwrap_err() + .contains("nested section digest mismatch") + ); + assert!(!streamed.exists()); + fs::remove_file(original).unwrap(); + fs::remove_file(spool).unwrap(); + fs::remove_file(native_spool).unwrap(); + } + + #[test] + fn streams_raw_tensor_across_buffer_boundary() { + let raw = vec![0x5au8; 1_048_580]; + let source = SourceIdentity { + name: "large-synthetic", + architecture: "qwen35", + builder: "strata-next-test", + digest: Sha256::digest(&raw).into(), + total_elements: 262_145, + bytes: raw.len() as u64, + }; + let input = + std::env::temp_dir().join(format!("strata-kar-large-{}.bin", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-kar-large-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&input, &raw).unwrap(); + let tensors = [Tensor { + name: "large", + dims: &[262_145], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::RawFile { + path: &input, + offset: 0, + bytes: raw.len() as u64, + }, + }]; + let summary = write_archive(&output, &source, &tensors).unwrap(); + assert_eq!(summary.tensor_count, 1); + assert_eq!(summary.total_elements, 262_145); + assert_eq!(kar::verify(&output).unwrap(), summary); + fs::remove_file(output).unwrap(); + fs::remove_file(input).unwrap(); + } + + #[test] + fn consuming_writer_removes_staged_input_after_verified_copy() { + let raw = (0..32u32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let input = root.join("section.bin"); + let output = root.join("archive.kar"); + fs::write(&input, &raw).unwrap(); + let digest: [u8; 32] = Sha256::digest(&raw).into(); + let source = SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "consume-test", + digest, + total_elements: 32, + bytes: raw.len() as u64, + }; + let tensors = [Tensor { + name: "raw", + dims: &[32], + source_dtype: 0, + source_digest: digest, + source_offset: 0, + data: TensorData::RawFile { + path: &input, + offset: 0, + bytes: raw.len() as u64, + }, + }]; + let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap(); + assert!(!input.exists()); + assert_eq!(kar::verify(&output).unwrap(), summary); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn archive_bytes_match_pinned_koference_reference_writer() { + // Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture. + let raw = (0..32) + .flat_map(|value| (value as f32).to_le_bytes()) + .collect::>(); + let mut source_bytes = raw.clone(); + source_bytes.extend_from_slice(b"weights"); + let source = SourceIdentity { + name: "synthetic", + architecture: "qwen35", + builder: "kar_container.py/2", + digest: Sha256::digest(&source_bytes).into(), + total_elements: 64, + bytes: source_bytes.len() as u64, + }; + let book1 = [0xbc00, 0x3c00]; + let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00]; + let books: [&[u16]; 2] = [&book1, &book2]; + let plane1 = [0xaaaa_aaaa]; + let plane2 = [0x5555_5555]; + let planes: [&[u32]; 2] = [&plane1, &plane2]; + let tensors = [ + Tensor { + name: "norm", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::Raw(&raw), + }, + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }, + ]; + let path = + std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id())); + let _ = fs::remove_file(&path); + let summary = write_archive(&path, &source, &tensors).unwrap(); + assert_eq!(summary.archive_bytes, 1280); + assert_eq!(summary.tensor_count, 2); + assert_eq!(summary.accounted_bpw, 160.0); + let archive = fs::read(&path).unwrap(); + assert_eq!( + hex::encode(Sha256::digest(&archive)), + "013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2" + ); + assert!(write_archive(&path, &source, &tensors).is_err()); + let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id())); + let stale = other.with_file_name(format!( + "{}.part", + other.file_name().unwrap().to_string_lossy() + )); + fs::write(&stale, b"previous work").unwrap(); + assert!(write_archive(&other, &source, &tensors).is_err()); + assert_eq!(fs::read(&stale).unwrap(), b"previous work"); + fs::remove_file(stale).unwrap(); + let invalid = [Tensor { + name: "bad-scale", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x7c00], + books: &books, + planes: &planes, + }, + }]; + assert!( + write_archive(&other, &source, &invalid) + .unwrap_err() + .contains("non-finite f16 scale") + ); + assert!(!other.exists()); + let raw_file = + path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id())); + let mut padded_raw = vec![0u8; 17]; + padded_raw.extend_from_slice(&raw); + fs::write(&raw_file, &padded_raw).unwrap(); + let streamed_tensors = [ + Tensor { + name: "norm", + dims: &[32], + source_dtype: 0, + source_digest: Sha256::digest(&raw).into(), + source_offset: 0, + data: TensorData::RawFile { + path: &raw_file, + offset: 17, + bytes: raw.len() as u64, + }, + }, + Tensor { + name: "expert", + dims: &[32], + source_dtype: 1, + source_digest: Sha256::digest(b"weights").into(), + source_offset: 0, + data: TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: 2, + scales: &[0x3c00], + books: &books, + planes: &planes, + }, + }, + ]; + let streamed = + path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id())); + let _ = fs::remove_file(&streamed); + write_archive(&streamed, &source, &streamed_tensors).unwrap(); + assert_eq!(fs::read(&streamed).unwrap(), archive); + padded_raw[17] ^= 1; + fs::write(&raw_file, padded_raw).unwrap(); + let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id())); + let _ = fs::remove_file(&corrupt); + assert!( + write_archive(&corrupt, &source, &streamed_tensors) + .unwrap_err() + .contains("RAW source digest mismatch") + ); + assert!(!corrupt.exists()); + fs::remove_file(streamed).unwrap(); + fs::remove_file(raw_file).unwrap(); + fs::remove_file(path).unwrap(); + } +} diff --git a/control-plane/src/key_init.rs b/control-plane/src/key_init.rs new file mode 100644 index 00000000..363912ff --- /dev/null +++ b/control-plane/src/key_init.rs @@ -0,0 +1,218 @@ +//! Explicit Linux credential provisioning. Never return the secret or rotate a key. +use std::path::Path; + +const USAGE: &str = "usage: strata-next api-key init --file ABSOLUTE_PATH"; + +fn parse(args: &[String]) -> Result<&Path, String> { + let [action, flag, file] = args else { + return Err(USAGE.into()); + }; + if action != "init" || flag != "--file" { + return Err(USAGE.into()); + } + let path = Path::new(file); + if !path.is_absolute() + || path.file_name().is_none() + || file.ends_with('/') + || file.split('/').any(|part| matches!(part, "." | "..")) + || file.chars().any(char::is_control) + { + return Err( + "key path must be an absolute file path without dot components or control characters" + .into(), + ); + } + Ok(path) +} + +pub fn run(args: &[String]) -> Result { + let path = parse(args)?; + #[cfg(target_os = "linux")] + { + let created = linux::init(path)?; + Ok(serde_json::json!({"created":created,"reused":!created})) + } + #[cfg(not(target_os = "linux"))] + { + let _ = path; + Err("api-key init currently requires Linux".into()) + } +} + +#[cfg(target_os = "linux")] +mod linux { + use super::*; + use std::{ + ffi::CString, + fs::{File, OpenOptions}, + io::{Read, Write}, + os::{ + fd::{AsRawFd, FromRawFd}, + unix::{ + ffi::OsStrExt, + fs::{MetadataExt, OpenOptionsExt}, + }, + }, + }; + + fn random() -> Result<[u8; 32], String> { + let mut bytes = [0u8; 32]; + let mut offset = 0; + while offset < bytes.len() { + // Linux OS CSPRNG; no clock/PID/user-provided seed or fallback. + let n = unsafe { + libc::getrandom(bytes[offset..].as_mut_ptr().cast(), bytes.len() - offset, 0) + }; + if n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { + continue; + } + if n <= 0 { + return Err("OS random source failed; key not created".into()); + } + offset += n as usize; + } + Ok(bytes) + } + + fn existing(directory: &File, name: &CString) -> Result { + let fd = unsafe { + libc::openat( + directory.as_raw_fd(), + name.as_ptr(), + libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK, + ) + }; + if fd < 0 { + return if std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound { + Ok(false) + } else { + Err("cannot open existing key safely; no replacement performed".into()) + }; + } + let file = unsafe { File::from_raw_fd(fd) }; + let m = file.metadata().map_err(|_| "cannot inspect existing key")?; + if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 { + return Err( + "existing key must be an owned private regular file; no replacement performed" + .into(), + ); + } + let mut bytes = Vec::new(); + file.take(515) + .read_to_end(&mut bytes) + .map_err(|_| "cannot read existing key")?; + crate::auth::parse_token(&bytes) + .map_err(|_| "existing key is invalid; no replacement performed")?; + Ok(true) + } + + struct Temporary<'a> { + directory: &'a File, + name: CString, + } + impl Drop for Temporary<'_> { + fn drop(&mut self) { + unsafe { + libc::unlinkat(self.directory.as_raw_fd(), self.name.as_ptr(), 0); + } + } + } + + pub(super) fn init(path: &Path) -> Result { + let directory = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(path.parent().ok_or(USAGE)?) + .map_err(|_| "key parent must be an existing private directory, not a symlink")?; + let m = directory + .metadata() + .map_err(|_| "cannot inspect key parent")?; + if m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 { + return Err( + "key parent must be owned and private (mode 700); no permissions changed".into(), + ); + } + let name = CString::new(path.file_name().ok_or(USAGE)?.as_bytes()).map_err(|_| USAGE)?; + if existing(&directory, &name)? { + directory + .sync_all() + .map_err(|_| "key exists but directory synchronization failed")?; + return Ok(false); + } + let temporary = CString::new(format!(".strata-key-{}", hex::encode(random()?))).unwrap(); + let fd = unsafe { + libc::openat( + directory.as_raw_fd(), + temporary.as_ptr(), + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, + 0o600, + ) + }; + if fd < 0 { + return Err("cannot create private temporary key; no replacement performed".into()); + } + let guard = Temporary { + directory: &directory, + name: temporary, + }; + let mut file = unsafe { File::from_raw_fd(fd) }; + // Only the newly created temporary inode; never change existing keys. + if unsafe { libc::fchmod(file.as_raw_fd(), 0o600) } != 0 { + return Err("cannot set private temporary key mode; target not published".into()); + } + let token = hex::encode(random()?); + file.write_all(token.as_bytes()) + .and_then(|_| file.write_all(b"\n")) + .and_then(|_| file.sync_all()) + .map_err(|_| "private key write failed; target not published")?; + // linkat never replaces an existing target. Both names are scoped to the + // opened directory, including when an ancestor path is renamed. + let linked = unsafe { + libc::linkat( + directory.as_raw_fd(), + guard.name.as_ptr(), + directory.as_raw_fd(), + name.as_ptr(), + 0, + ) + }; + let created = if linked == 0 { + true + } else if std::io::Error::last_os_error().kind() == std::io::ErrorKind::AlreadyExists { + if !existing(&directory, &name)? { + return Err("concurrent key disappeared; retry init to reconcile".into()); + } + false + } else { + return Err("cannot publish private key; no replacement performed".into()); + }; + drop(file); + drop(guard); + directory.sync_all().map_err( + |_| "key published but directory synchronization failed; retry init to reconcile", + )?; + Ok(created) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_explicit_absolute_init() { + let args = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::>(); + assert!(parse(&args(&["init", "--file", "/private/api.key"])).is_ok()); + for parts in [ + vec![], + vec!["rotate", "--file", "/a"], + vec!["init", "--file", "relative"], + vec!["init", "--file", "/a/../b"], + vec!["init", "--file", "/a/."], + vec!["init", "--file", "/a/"], + vec!["init", "--file", "/a\nb"], + vec!["init", "--file", "/a", "--force"], + ] { + assert!(parse(&args(&parts)).is_err()); + } + } +} diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs new file mode 100644 index 00000000..b4b6cf33 --- /dev/null +++ b/control-plane/src/lib.rs @@ -0,0 +1,63 @@ +pub mod app; +pub mod asset_bundle; +pub mod auth; +pub mod config; +pub mod derived_iq3; +pub mod derived_mixed; +pub mod doctor; +pub mod embedded_engine; +#[cfg(test)] +mod embedded_spec; +pub mod engine_probe; +pub mod ggml_bridge; +pub mod gguf; +pub mod gguf_f32_stream; +mod history_store; +mod immutable_directory; +pub mod iq3_s; +mod iq3s_grid; +pub mod kar; +pub mod kar_codec; +pub mod kar_fixture; +pub mod kar_memory; +pub mod kar_overlay; +pub mod kar_quality; +pub mod kar_sample; +pub mod kar_stream_encode; +pub mod kar_writer; +pub mod key_init; +pub mod lifecycle; +pub mod metrics; +pub mod model; +pub mod model_pipeline; +pub mod models_api; +pub mod mtp_pack; +pub mod native_model; +pub mod native_pack; +pub mod preflight; +pub mod prepare_preview; +pub mod prompt; +mod response_tools; +pub mod responses; +pub mod service_install; +pub mod service_unit; +pub mod stream_parts; +pub mod tensor_export; +pub mod tokenizer; +pub mod tokenizer_assets; +pub mod tool_output; +pub mod wire; +pub mod worker; + +pub mod wait_ready; + +pub mod chat; + +pub mod messages; +mod native_events; + +pub mod cuda_memory; + +pub mod service_switch; + +pub mod queue; diff --git a/control-plane/src/lifecycle.rs b/control-plane/src/lifecycle.rs new file mode 100644 index 00000000..8e46e9f2 --- /dev/null +++ b/control-plane/src/lifecycle.rs @@ -0,0 +1,322 @@ +//! Process-local admission drain. A request remains admitted until its body is +//! consumed/dropped; commands remain tracked through worker protocol cleanup. +use std::{ + pin::Pin, + sync::{Arc, Mutex}, + task::{Context, Poll}, +}; + +use axum::{ + Json, + body::{Body, Bytes}, + extract::{Request, State}, + http::{StatusCode, header::RETRY_AFTER}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use http_body::{Body as HttpBody, Frame, SizeHint}; +use serde::Serialize; +use serde_json::json; + +pub const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 17; + +pub fn validate_capacity(value: usize) -> Result<(), &'static str> { + if (1..=256).contains(&value) { + Ok(()) + } else { + Err("max_in_flight_requests must be between 1 and 256") + } +} + +#[derive(Clone)] +pub struct Lifecycle(Arc>); + +impl Default for Lifecycle { + fn default() -> Self { + Self::new(DEFAULT_MAX_IN_FLIGHT_REQUESTS).expect("valid default capacity") + } +} + +#[derive(Debug, PartialEq, Eq)] +enum AdmissionError { + Draining, + Overloaded, +} + +#[derive(Clone, Copy, Default, Serialize)] +pub struct Snapshot { + pub max_in_flight_requests: usize, + pub draining: bool, + pub shutting_down: bool, + pub requests_in_flight: usize, + pub generation_jobs: usize, +} + +pub struct Guard { + lifecycle: Lifecycle, + generation: bool, +} + +impl Lifecycle { + pub fn new(max_in_flight_requests: usize) -> Result { + validate_capacity(max_in_flight_requests)?; + Ok(Self(Arc::new(Mutex::new(Snapshot { + max_in_flight_requests, + ..Snapshot::default() + })))) + } + + pub fn snapshot(&self) -> Snapshot { + *self.0.lock().expect("admission mutex") + } + + pub fn set_draining(&self, draining: bool) { + let mut state = self.0.lock().expect("admission mutex"); + state.draining = draining || state.shutting_down; + } + + /// Signal shutdown cannot be undone by an administrative resume. + pub fn begin_shutdown(&self) { + let mut state = self.0.lock().expect("admission mutex"); + state.shutting_down = true; + state.draining = true; + } + + /// Wait for admitted HTTP bodies and queued/active worker commands. This + /// bounds only the drain phase; process/connection cleanup happens later. + pub async fn wait_drained(&self, grace: std::time::Duration) -> bool { + tokio::time::timeout(grace, async { + loop { + let state = self.snapshot(); + if state.requests_in_flight == 0 && state.generation_jobs == 0 { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + }) + .await + .is_ok() + } + + fn admit(&self) -> Result { + let mut state = self.0.lock().expect("admission mutex"); + if state.draining { + return Err(AdmissionError::Draining); + } + if state.requests_in_flight >= state.max_in_flight_requests { + return Err(AdmissionError::Overloaded); + } + state.requests_in_flight += 1; + Ok(Guard { + lifecycle: self.clone(), + generation: false, + }) + } + + // Called only for requests that already passed admission. Drain must not + // prevent those requests from entering the command queue later. + pub fn generation(&self) -> Guard { + self.0.lock().expect("admission mutex").generation_jobs += 1; + Guard { + lifecycle: self.clone(), + generation: true, + } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + let mut state = self.lifecycle.0.lock().expect("admission mutex"); + if self.generation { + state.generation_jobs -= 1; + } else { + state.requests_in_flight -= 1; + } + } +} + +pub async fn admit(State(lifecycle): State, request: Request, next: Next) -> Response { + let guard = match lifecycle.admit() { + Ok(guard) => guard, + Err(AdmissionError::Draining) => { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({"error":{ + "type":"server_error", "code":"runtime_draining", + "message":"Runtime is draining; new inference requests are not accepted" + }})), + ) + .into_response(); + } + Err(AdmissionError::Overloaded) => { + return ( + StatusCode::TOO_MANY_REQUESTS, + [(RETRY_AFTER, "1")], + Json(json!({"error":{ + "type":"server_error", "code":"runtime_overloaded", + "message":"Runtime request capacity is full; retry later" + }})), + ) + .into_response(); + } + }; + let response = next.run(request).await; + let (parts, body) = response.into_parts(); + Response::from_parts( + parts, + Body::new(TrackedBody { + body, + guard: Some(guard), + }), + ) +} + +struct TrackedBody { + body: Body, + guard: Option, +} + +impl HttpBody for TrackedBody { + type Data = Bytes; + type Error = axum::Error; + + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + let frame = Pin::new(&mut self.body).poll_frame(cx); + if matches!(frame, Poll::Ready(None | Some(Err(_)))) { + self.guard.take(); + } + frame + } + fn is_end_stream(&self) -> bool { + self.body.is_end_stream() + } + fn size_hint(&self) -> SizeHint { + self.body.size_hint() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use http_body_util::{BodyExt, StreamBody}; + use std::{collections::VecDeque, convert::Infallible}; + + struct Frames(VecDeque>); + + #[tokio::test] + async fn signal_drain_cannot_resume_and_waits_for_both_lifetimes() { + use std::time::Duration; + let lifecycle = Lifecycle::default(); + let request = lifecycle.admit().unwrap(); + lifecycle.begin_shutdown(); + lifecycle.set_draining(false); + assert!(lifecycle.snapshot().shutting_down); + assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining))); + // An admitted request can still enqueue after signal arrival. + let command = lifecycle.generation(); + assert!(!lifecycle.wait_drained(Duration::ZERO).await); + drop(request); + assert!(!lifecycle.wait_drained(Duration::from_millis(5)).await); + let cloned = lifecycle.clone(); + let waiter = tokio::spawn(async move { cloned.wait_drained(Duration::from_secs(1)).await }); + drop(command); + assert!(waiter.await.unwrap()); + assert!(lifecycle.wait_drained(Duration::ZERO).await); + lifecycle.set_draining(false); + assert!(lifecycle.snapshot().draining); + } + + #[test] + fn concurrent_admission_reserves_capacity_and_releases_on_drop() { + use std::{sync::Barrier, thread}; + assert!(Lifecycle::new(0).is_err()); + assert!(Lifecycle::new(257).is_err()); + assert!(Lifecycle::new(256).is_ok()); + let lifecycle = Lifecycle::new(3).unwrap(); + let start = Arc::new(Barrier::new(32)); + let reserved = Arc::new(Barrier::new(32)); + let results = thread::scope(|scope| { + let handles: Vec<_> = (0..32) + .map(|_| { + let lifecycle = lifecycle.clone(); + let start = start.clone(); + let reserved = reserved.clone(); + scope.spawn(move || { + start.wait(); + let admission = lifecycle.admit(); + reserved.wait(); // Keep every admitted guard until all attempts finish. + let count = lifecycle.snapshot().requests_in_flight; + reserved.wait(); + assert_eq!(count, 3); + admission.is_ok() + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap()) + .filter(|ok| *ok) + .count() + }); + assert_eq!(results, 3); + assert_eq!(lifecycle.snapshot().requests_in_flight, 0); + let _request = lifecycle.admit().unwrap(); + lifecycle.set_draining(true); + assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining))); + } + impl futures_core::Stream for Frames { + type Item = Result, Infallible>; + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(self.0.pop_front().map(Ok)) + } + } + + #[tokio::test] + async fn drain_tracks_body_frames_trailers_and_command_lifetimes_independently() { + let lifecycle = Lifecycle::default(); + let request = lifecycle.admit().unwrap(); + lifecycle.set_draining(true); + assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining))); + // Already admitted work can enqueue after drain was requested. + let command = lifecycle.generation(); + let mut trailers = axum::http::HeaderMap::new(); + trailers.insert("x-fixture", "kept".parse().unwrap()); + let frames = Frames(VecDeque::from([ + Frame::data(Bytes::from_static(b"data: terminal\n\n")), + Frame::trailers(trailers.clone()), + ])); + let mut body = TrackedBody { + body: Body::new(StreamBody::new(frames)), + guard: Some(request), + }; + assert_eq!( + body.frame().await.unwrap().unwrap().into_data().unwrap(), + "data: terminal\n\n" + ); + assert_eq!(lifecycle.snapshot().requests_in_flight, 1); + assert_eq!( + body.frame() + .await + .unwrap() + .unwrap() + .into_trailers() + .unwrap(), + trailers + ); + assert!(body.frame().await.is_none()); + assert_eq!(lifecycle.snapshot().requests_in_flight, 0); + assert_eq!(lifecycle.snapshot().generation_jobs, 1); + drop(command); + assert_eq!(lifecycle.snapshot().generation_jobs, 0); + lifecycle.set_draining(false); + let guard = lifecycle.admit().unwrap(); + drop(TrackedBody { + body: Body::empty(), + guard: Some(guard), + }); + assert_eq!(lifecycle.snapshot().requests_in_flight, 0); + } +} diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs new file mode 100644 index 00000000..d1553d91 --- /dev/null +++ b/control-plane/src/main.rs @@ -0,0 +1,883 @@ +use std::{env, io::Read, path::Path, sync::Arc}; + +use tokio::sync::{mpsc, watch}; + +use strata_control::{ + app, config::Config, derived_iq3, derived_mixed, doctor, gguf, kar, kar_fixture, kar_memory, + kar_overlay, kar_quality, model, model_pipeline, prepare_preview, tokenizer, tokenizer_assets, + worker, +}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let args: Vec = env::args().skip(1).collect(); + match args.as_slice() { + [command, rest @ ..] if command == "api-key" => { + println!("{}", strata_control::key_init::run(rest)?); + Ok(()) + } + [model, action, spec, source_flag, source, output_flag, output] + if model == "model" && action == "prepare-native-pack" + && source_flag == "--source-dir" && output_flag == "--output" => { + let manifest = strata_control::model::Manifest::from_spec(spec).await?; + println!("{}", strata_control::native_pack::prepare(&manifest, Path::new(source), Path::new(output)).await?); + Ok(()) + } + [command, flag, path, defer] + if command == "provision" && flag == "--config" && defer == "--defer-memory-check" => { + let mut config = Config::load_with_path(Some(Path::new(path)))?; + config.prepare_for_switch().await?; + println!("{}", serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false, "memory_admission": "deferred_until_serve"})); + Ok(()) + } + [command, flag, path] if command == "provision" && flag == "--config" => { + let mut config = Config::load_with_path(Some(Path::new(path)))?; + config.provision().await?; + println!("{}", serde_json::json!({"assets_verified": config.assets.len(), "native_model_prepared":config.native_model.is_some(), "mtp_pack_structurally_validated":config.mtp_pack.is_some(), "worker_started": false})); + Ok(()) + } + [command] if command == "check-config" => { + println!("{}", strata_control::preflight::check(None)?); + Ok(()) + } + [command, flag, config] if command == "check-config" && flag == "--config" => { + println!("{}", strata_control::preflight::check(Some(Path::new(config)))?); + Ok(()) + } + [command] if command == "engine-info" => { + println!("{}", strata_control::embedded_engine::info()); + Ok(()) + } + [command] if command == "engine-help" => strata_control::embedded_engine::help(), + [command] if command == "--engine-license" => { + print!("{}", include_str!("../../engine/strata/LICENSE")); + Ok(()) + } + [model, action, source, tensor, flag, output] + if model == "model" && action == "export-tensor-f32" && flag == "--output" => + { + let report = strata_control::tensor_export::export(Path::new(source), tensor, Path::new(output))?; + println!("{}", serde_json::to_string(&report)?); + Ok(()) + } + [] => serve(None).await, + [command] if command == "serve" => serve(None).await, + [command, flag, config] if command == "serve" && flag == "--config" => { + serve(Some(Path::new(config))).await + } + [command, rest @ ..] if command == "wait-ready" => { + println!("{}", strata_control::wait_ready::run(rest).await?); + Ok(()) + } + [command, rest @ ..] if command == "service-switch" => { + println!("{}", strata_control::service_switch::run(rest).await?); + Ok(()) + } + [command, rest @ ..] if command == "service-control" => { + println!("{}", strata_control::service_install::control(rest).await?); + Ok(()) + } + [command, rest @ ..] if command == "service-install" => { + println!("{}", strata_control::service_install::run(rest).await?); + Ok(()) + } + [command, rest @ ..] if command == "service-unit" => { + let (config, working_dir, env_file) = match rest { + [config_flag, config, work_flag, working_dir] + if config_flag == "--config" && work_flag == "--working-dir" => + (config, working_dir, None), + [config_flag, config, work_flag, working_dir, env_flag, env_file] + if config_flag == "--config" && work_flag == "--working-dir" && env_flag == "--env-file" => + (config, working_dir, Some(Path::new(env_file))), + _ => return Err("usage: strata-next service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]".into()), + }; + print!("{}", strata_control::service_unit::render( + &env::current_exe()?, Path::new(config), Path::new(working_dir), env_file, + )?); + Ok(()) + } + [doctor] if doctor == "doctor" => { + doctor::report().await?; + Ok(()) + } + [model, action, flag, output] + if model == "model" && action == "smoke-fixture" && flag == "--output" => + { + let result = kar_fixture::write(Path::new(output))?; + println!("KAR-2 smoke fixture: {output}"); + println!("tensor=smoke.expert elements=32 level=2"); + println!("archive_sha256={}", hex::encode(result.archive_digest)); + println!("output_fnv1a64={:x}", result.decoded_fnv1a64); + Ok(()) + } + [model, action, flag, output] + if model == "model" && action == "ple-smoke-fixture" && flag == "--output" => + { + let result = kar_fixture::write_ple(Path::new(output))?; + println!("KAR-2 PLE smoke fixture: {output}"); + println!("archive_sha256={}", hex::encode(result.archive_digest)); + for (row, checksum) in result.row_fnv1a64.iter().enumerate() { + println!("row={row} fnv1a64={checksum:016x}"); + } + Ok(()) + } + [model, action, manifest, flag, output] + if model == "model" && flag == "--output" && action == "fetch" => + { + let manifest = model::Manifest::from_spec(manifest).await?; + model::fetch(&manifest, Path::new(output)).await?; + Ok(()) + } + [model, action, manifest, flag, output] + if model == "model" && flag == "--output" && action == "verify" => + { + let manifest = model::Manifest::from_spec(manifest).await?; + model::verify(&manifest, Path::new(output)).await?; + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "ensure-sharded-preview" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let outcome = model_pipeline::ensure_sharded_preview( + &manifest, + Path::new(source_dir), + Path::new(destination), + levels.parse()?, + ).await?; + match outcome { + model_pipeline::PreviewOutcome::Created(result) => { + println!("created and verified experimental KAR-2: {destination}"); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + } + model_pipeline::PreviewOutcome::Reused(summary) => { + println!("reused verified experimental KAR-2: {destination}"); + println!("tensors: {}", summary.tensor_count); + } + } + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "ensure-sharded-streamed" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let outcome = model_pipeline::ensure_sharded_streamed( + &manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, + ).await?; + let source_bytes = manifest.files.iter().try_fold(0u64, |sum, file| sum.checked_add(file.size)) + .ok_or("sharded source byte count overflow")?; + match outcome { + model_pipeline::PreviewOutcome::Created(result) => { + println!("created and verified experimental streamed KAR-2: {destination}"); + println!("archive bytes: {}", result.archive.archive_bytes); + println!("source GGUF bytes: {source_bytes}"); + println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64); + println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + print_top_tensor_distortions(&result.tensor_distortions); + } + model_pipeline::PreviewOutcome::Reused(summary) => { + println!("reused verified experimental streamed KAR-2: {destination}"); + println!("archive bytes: {}", summary.archive_bytes); + println!("source GGUF bytes: {source_bytes}"); + println!("archive/source ratio: {:.6}", summary.archive_bytes as f64 / source_bytes as f64); + println!("accounted bits per weight: {:.6}", summary.accounted_bpw); + println!("tensors: {}", summary.tensor_count); + } + } + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels, ple_flag, ple_limit] + if model == "model" + && action == "ensure-sharded-streamed" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" + && ple_flag == "--ple-part-elements" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let limit: u64 = ple_limit.parse()?; + let outcome = model_pipeline::ensure_sharded_streamed_ple( + &manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, limit, + ).await?; + match outcome { + model_pipeline::PreviewOutcome::Created(result) => { + println!("created and verified experimental PLE-partitioned KAR-2: {destination}"); + println!("archive bytes: {}", result.archive.archive_bytes); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + print_top_tensor_distortions(&result.tensor_distortions); + } + model_pipeline::PreviewOutcome::Reused(summary) => { + println!("reused verified experimental PLE-partitioned KAR-2: {destination}"); + println!("archive bytes: {}", summary.archive_bytes); + println!("tensors: {}", summary.tensor_count); + } + } + println!("PLE maximum part elements: {limit}"); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, path] if model == "model" && action == "inspect" => { + let summary = gguf::inspect(Path::new(path))?; + println!("GGUF v3: {path}"); + println!("size: {} bytes", summary.file_size); + println!("tensors: {}; metadata: {}", summary.tensors, summary.metadata); + println!("data starts at byte {}", summary.data_start); + if let Some(architecture) = summary.architecture { + println!("architecture: {architecture}"); + } + if let (Some(no), Some(count)) = (summary.split_no, summary.split_count) { + println!("split: {}/{}", no + 1, count); + } + println!("tensor types: {:?}", summary.types); + Ok(()) + } + [model, action, path] if model == "model" && action == "index" => { + print_tensor_index(Path::new(path), false) + } + [model, action, path, hash_flag] + if model == "model" && action == "index" && hash_flag == "--hash" => + { + print_tensor_index(Path::new(path), true) + } + [model, action, path] if model == "model" && action == "derive-iq3-identity" => { + let identity = derived_iq3::fingerprint(Path::new(path))?; + println!("{}", serde_json::to_string_pretty(&serde_json::json!({ + "derivation": "strata-next/iq3_s-to-f32-le-v1", + "gguf_sha256": hex::encode(identity.gguf_sha256), + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "iq3_sha256": hex::encode(tensor.iq3_sha256), + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }))?); + Ok(()) + } + [model, action, path] if model == "model" && action == "derive-mixed-identity" => { + let identity = derived_mixed::fingerprint(Path::new(path))?; + println!("{}", serde_json::to_string_pretty(&serde_json::json!({ + "derivation": "strata-next/gguf-mixed-to-f32-le-v1", + "gguf_sha256": hex::encode(identity.gguf_sha256), + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "source_kind": tensor.source_kind, + "source_sha256": hex::encode(tensor.source_sha256), + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }))?); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir] + if model == "model" + && action == "derive-sharded-identity" + && source_flag == "--source-dir" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let identity = derived_mixed::fingerprint_shards(&manifest, Path::new(source_dir))?; + println!("{}", serde_json::to_string_pretty(&serde_json::json!({ + "derivation": "strata-next/gguf-shards-to-f32-le-v1", + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "shards": identity.shards.iter().map(|shard| serde_json::json!({ + "name": shard.name, + "gguf_sha256": hex::encode(shard.gguf_sha256), + "gguf_bytes": shard.gguf_bytes, + "tensor_count": shard.tensor_count, + })).collect::>(), + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "source_kind": tensor.source_kind, + "source_sha256": hex::encode(tensor.source_sha256), + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }))?); + Ok(()) + } + [model, action, source, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "prepare-f32-preview" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let result = prepare_preview::prepare_f32( + Path::new(source), + Path::new(destination), + levels.parse()?, + )?; + println!("EXPERIMENTAL F32 preview KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("source SHA-256: {}", hex::encode(result.archive.source_digest)); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, source, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "prepare-iq3-preview" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let result = prepare_preview::prepare_iq3( + Path::new(source), + Path::new(destination), + levels.parse()?, + )?; + println!("EXPERIMENTAL IQ3_S-derived F32 KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest)); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("provenance: {}", result.provenance_path.unwrap().display()); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, source, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "prepare-mixed-preview" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let result = prepare_preview::prepare_mixed( + Path::new(source), + Path::new(destination), + levels.parse()?, + )?; + println!("EXPERIMENTAL mixed GGUF-derived F32 KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest)); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("provenance: {}", result.provenance_path.unwrap().display()); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "prepare-sharded-preview" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let result = prepare_preview::prepare_sharded( + &manifest, + Path::new(source_dir), + Path::new(destination), + levels.parse()?, + )?; + println!("EXPERIMENTAL sharded GGUF-derived F32 KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest)); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("provenance: {}", result.provenance_path.unwrap().display()); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels] + if model == "model" + && action == "prepare-sharded-streamed" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let result = prepare_preview::prepare_sharded_streamed( + &manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, + )?; + let source_bytes = manifest.files.iter().try_fold(0u64, |sum, file| sum.checked_add(file.size)) + .ok_or("sharded source byte count overflow")?; + println!("EXPERIMENTAL streamed sharded GGUF-derived F32 KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("archive bytes: {}", result.archive.archive_bytes); + println!("source GGUF bytes: {source_bytes}"); + println!("archive/source ratio: {:.6}", result.archive.archive_bytes as f64 / source_bytes as f64); + println!("accounted bits per weight: {:.6}", result.archive.accounted_bpw); + println!("derived F32 SHA-256: {}", hex::encode(result.archive.source_digest)); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("provenance: {}", result.provenance_path.unwrap().display()); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + print_top_tensor_distortions(&result.tensor_distortions); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, output_flag, destination, levels_flag, levels, ple_flag, ple_limit] + if model == "model" + && action == "prepare-sharded-streamed" + && source_flag == "--source-dir" + && output_flag == "--output" + && levels_flag == "--levels" + && ple_flag == "--ple-part-elements" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let limit: u64 = ple_limit.parse()?; + let result = prepare_preview::prepare_sharded_streamed_ple( + &manifest, Path::new(source_dir), Path::new(destination), levels.parse()?, limit, + )?; + println!("EXPERIMENTAL PLE-partitioned KAR-2: {destination}"); + println!("tensors: {}", result.archive.tensor_count); + println!("archive bytes: {}", result.archive.archive_bytes); + println!("archive SHA-256: {}", hex::encode(result.archive_digest)); + println!("PLE maximum part elements: {limit}"); + println!("maximum tensor relative L2: {:.8}", result.maximum_relative_l2); + print_top_tensor_distortions(&result.tensor_distortions); + println!("not eligible for serving without a full-model quality gate"); + Ok(()) + } + [model, action, path, tensor, level] + if model == "model" && action == "checksum-kar-preview" => + { + let values = kar::decode_preview_tensor(Path::new(path), tensor, level.parse()?)?; + println!("tensor={tensor} elements={} level={level}", values.len()); + println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values)); + println!("first={} last={}", values[0], values[values.len() - 1]); + Ok(()) + } + [model, action, path, tensor, level, row_flag, row_id] + if model == "model" && action == "checksum-kar-row" && row_flag == "--row" => + { + let row_id: u32 = row_id.parse()?; + let values = kar::decode_tensor_row(Path::new(path), tensor, level.parse()?, row_id)?; + println!("tensor={tensor} row_id={row_id} elements={} level={level}", values.len()); + println!("output_fnv1a64={:x}", kar::f32_fnv1a64(&values)); + println!("first={} last={}", values[0], values[values.len() - 1]); + Ok(()) + } + [model, action, path] if model == "model" && action == "inspect-kar" => { + let summary = kar::inspect(Path::new(path))?; + println!("KAR-2: {path}"); + println!("size: {} bytes", summary.archive_bytes); + println!("tensors: {}; elements: {}", summary.tensor_count, summary.total_elements); + println!("source elements: {}", summary.source_total_elements); + println!("accounted bpw: {}", summary.accounted_bpw); + println!("source SHA-256: {}", hex::encode(summary.source_digest)); + println!("source bytes: {}", summary.source_bytes); + println!("bounded metadata checks passed; payload CRCs and padding not checked"); + Ok(()) + } + [model, action, path, level_flag, level, budget_flag, budget] + if model == "model" && action == "plan-kar-memory" + && level_flag == "--level" && budget_flag == "--budget-mib" => + { + let budget_mib: u64 = budget.parse()?; + let budget_bytes = budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?; + let report = kar_memory::plan(Path::new(path), level.parse()?, budget_bytes)?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) + } + [model, action, base_flag, base, overlay_flag, overlay, base_level_flag, base_level, overlay_level_flag, overlay_level, budget_flag, budget] + if model == "model" && action == "plan-kar-overlay-memory" + && base_flag == "--base" && overlay_flag == "--overlay" + && base_level_flag == "--base-level" + && overlay_level_flag == "--overlay-level" + && budget_flag == "--budget-mib" => + { + let budget_mib: u64 = budget.parse()?; + let budget_bytes = budget_mib.checked_mul(1 << 20).ok_or("GPU budget overflow")?; + let report = kar_memory::plan_selected( + Path::new(base), + Path::new(overlay), + base_level.parse()?, + overlay_level.parse()?, + budget_bytes, + )?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) + } + [model, action, path] if model == "model" && action == "verify-kar" => { + let summary = kar::verify(Path::new(path))?; + println!("verified KAR-2 metadata and {} payload CRCs", summary.tensor_count); + println!("source SHA-256: {}", hex::encode(summary.source_digest)); + println!("source files not checked; use --manifest SPEC --source-dir DIR"); + Ok(()) + } + [model, action, archive, source_flag, source] + if model == "model" && action == "verify-iq3-preview" && source_flag == "--source" => + { + let summary = prepare_preview::verify_iq3(Path::new(source), Path::new(archive))?; + println!("verified IQ3 preview: {archive}"); + println!("tensors: {}", summary.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest)); + println!("original GGUF, provenance, KAR source records, and payload CRCs match"); + println!("not a model quality or GPU execution result"); + Ok(()) + } + [model, action, archive, source_flag, source] + if model == "model" && action == "verify-mixed-preview" && source_flag == "--source" => + { + let summary = prepare_preview::verify_mixed(Path::new(source), Path::new(archive))?; + println!("verified mixed preview: {archive}"); + println!("tensors: {}", summary.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest)); + println!("original GGUF, provenance, KAR source records, and payload CRCs match"); + println!("not a model quality or GPU execution result"); + Ok(()) + } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir] + if model == "model" + && action == "verify-sharded-preview" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let summary = prepare_preview::verify_sharded( + &manifest, + Path::new(source_dir), + Path::new(archive), + )?; + println!("verified sharded preview: {archive}"); + println!("tensors: {}", summary.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest)); + println!("manifest shards, provenance, KAR source records, and payload CRCs match"); + println!("not a model quality or GPU execution result"); + Ok(()) + } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels] + if model == "model" + && action == "verify-sharded-streamed" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" + && levels_flag == "--levels" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let summary = prepare_preview::verify_sharded_streamed( + &manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, + )?; + println!("verified experimental streamed sharded KAR-2: {archive}"); + println!("tensors: {}", summary.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest)); + println!("manifest shards, provenance, KAR source records, and payload CRCs match"); + println!("not a model quality or GPU execution result"); + Ok(()) + } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, ple_flag, ple_limit] + if model == "model" + && action == "verify-sharded-streamed" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" + && levels_flag == "--levels" + && ple_flag == "--ple-part-elements" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let limit: u64 = ple_limit.parse()?; + let summary = prepare_preview::verify_sharded_streamed_ple( + &manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, limit, + )?; + println!("verified experimental PLE-partitioned KAR-2: {archive}"); + println!("tensors: {}", summary.tensor_count); + println!("derived F32 SHA-256: {}", hex::encode(summary.source_digest)); + println!("PLE maximum part elements: {limit}"); + println!("manifest shards, provenance, KAR source records, and payload CRCs match"); + println!("not a model quality or GPU execution result"); + Ok(()) + } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, output_flag, report_path] + if model == "model" + && action == "analyze-sharded-kar" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" + && levels_flag == "--levels" + && output_flag == "--output" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let report = kar_quality::analyze( + &manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, + )?; + kar_quality::write_report(Path::new(report_path), &report)?; + println!("sampled KAR reconstruction report: {report_path}"); + println!("records: {}", report.records.len()); + println!("archive SHA-256: {}", report.archive_sha256); + println!("samples are not a full-tensor or model-quality gate"); + Ok(()) + } + [model, action, archive, manifest_flag, manifest_spec, source_flag, source_dir, levels_flag, levels, output_flag, report_path, assume_flag] + if model == "model" + && action == "analyze-sharded-kar" + && manifest_flag == "--manifest" + && source_flag == "--source-dir" + && levels_flag == "--levels" + && output_flag == "--output" + && assume_flag == "--assume-verified" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let report = kar_quality::analyze_previously_verified( + &manifest, Path::new(source_dir), Path::new(archive), levels.parse()?, + )?; + kar_quality::write_report(Path::new(report_path), &report)?; + println!("sampled KAR reconstruction report: {report_path}"); + println!("records: {}", report.records.len()); + println!("archive SHA-256 from previously verified provenance: {}", report.archive_sha256); + println!("full archive and source hashes were not recomputed in this run"); + println!("samples are not a full-tensor or model-quality gate"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, candidates_flag, candidates_path, output_flag, destination] + if model == "model" + && action == "prepare-kar-overlay" + && source_flag == "--source-dir" + && base_flag == "--base" + && candidates_flag == "--candidates" + && output_flag == "--output" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let result = kar_overlay::prepare( + &manifest, + Path::new(source_dir), + Path::new(base_archive), + Path::new(candidates_path), + Path::new(destination), + )?; + println!("EXPERIMENTAL KAR precision overlay: {destination}"); + println!("records: {}; bytes: {}", result.record_count, result.archive_bytes); + println!("overlay SHA-256: {}", hex::encode(result.archive_sha256)); + println!("maximum selected-record relative L2: {:.8}", result.maximum_relative_l2); + println!("provenance: {}", result.provenance_path.display()); + println!("not eligible for serving without model-quality and GPU gates"); + Ok(()) + } + [model, action, manifest_spec, source_flag, source_dir, base_flag, base_archive, overlay_flag, overlay_archive, output_flag, report_path] + if model == "model" + && action == "compare-kar-overlay" + && source_flag == "--source-dir" + && base_flag == "--base" + && overlay_flag == "--overlay" + && output_flag == "--output" => + { + let manifest = model::Manifest::from_spec(manifest_spec).await?; + let comparison = kar_overlay::compare( + &manifest, + Path::new(source_dir), + Path::new(base_archive), + Path::new(overlay_archive), + )?; + kar_overlay::write_comparison(Path::new(report_path), &comparison)?; + println!("complete selected-tensor L2/L3 comparison: {report_path}"); + println!("records: {}", comparison.records.len()); + println!("not a full-model quality or GPU performance result"); + Ok(()) + } + [model, action, base_flag, base_archive, overlay_flag, overlay_archive] + if model == "model" + && action == "resolve-kar-overlay" + && base_flag == "--base" + && overlay_flag == "--overlay" => + { + let resolution = kar_overlay::resolve_verified( + Path::new(base_archive), + Path::new(overlay_archive), + )?; + println!("{}", serde_json::to_string_pretty(&resolution)?); + Ok(()) + } + [model, action, path, manifest_flag, manifest_spec, source_flag, source_dir] + if model == "model" && action == "verify-kar" + && manifest_flag == "--manifest" && source_flag == "--source-dir" => { + let summary = kar::verify(Path::new(path))?; + let manifest = model::Manifest::from_spec(manifest_spec).await?; + kar::verify_source_files(&summary, &manifest, Path::new(source_dir))?; + println!("verified KAR-2 metadata, {} payload CRCs, and source identity", summary.tensor_count); + Ok(()) + } + [model, action, path, flag, output] + if model == "model" && action == "extract-tokenizer" && flag == "--output" => + { + let destination = tokenizer_assets::extract(Path::new(path), Path::new(output))?; + println!("extracted {}", destination.display()); + Ok(()) + } + [model, action, path, input] + if model == "model" && action == "tokenize" && input != "--stdin" => + { + let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?; + println!("{}", serde_json::to_string(&tokenizer.encode(input, false)?)?); + Ok(()) + } + [model, action, path, input, flag] + if model == "model" && action == "tokenize" && input != "--stdin" && flag == "--special" => + { + let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?; + println!("{}", serde_json::to_string(&tokenizer.encode(input, true)?)?); + Ok(()) + } + [model, action, path, flag] + if model == "model" && action == "tokenize" && flag == "--stdin" => + { + let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?; + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + println!("{}", serde_json::to_string(&tokenizer.encode(&input, false)?)?); + Ok(()) + } + [model, action, path, stdin_flag, special_flag] + if model == "model" + && action == "tokenize" + && stdin_flag == "--stdin" + && special_flag == "--special" => + { + let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?; + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + println!("{}", serde_json::to_string(&tokenizer.encode(&input, true)?)?); + Ok(()) + } + [model, action, path, ids] if model == "model" && action == "detokenize" => { + let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?; + let ids = if ids.is_empty() { + Vec::new() + } else { + ids.split(',') + .map(str::parse::) + .collect::, _>>()? + }; + println!("{}", serde_json::to_string(&tokenizer.decode(&ids)?)?); + Ok(()) + } + [version] if version == "--version" || version == "-V" => { + println!("strata-next {}", env!("CARGO_PKG_VERSION")); + Ok(()) + } + [license] if license == "--ggml-license" => { + println!("ggml IQ3_S grid table — MIT License\n"); + print!("{}", include_str!("../third_party/ggml/LICENSE")); + Ok(()) + } + _ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model detokenize TOKENIZER_DIR IDS]".into()), + } +} + +fn print_top_tensor_distortions(distortions: &[prepare_preview::TensorDistortion]) { + let mut ranked = distortions.iter().collect::>(); + ranked.sort_by(|a, b| b.relative_l2.total_cmp(&a.relative_l2)); + println!( + "highest relative L2 by KAR record (top 20 of {}):", + ranked.len() + ); + for tensor in ranked.into_iter().take(20) { + println!( + " {:.8} kind={} bytes={} {}", + tensor.relative_l2, tensor.source_kind, tensor.section_bytes, tensor.name + ); + } +} + +fn print_tensor_index(path: &Path, hash: bool) -> Result<(), Box> { + let index = gguf::tensor_index(path)?; + for (number, tensor) in index.tensors.iter().enumerate() { + let mut row = serde_json::json!({ + "name": tensor.name, + "dimensions": tensor.dimensions, + "type": tensor.kind, + "offset": index.summary.data_start + tensor.offset, + "bytes": tensor.bytes, + }); + if hash { + row["sha256"] = hex::encode(gguf::tensor_sha256(path, &index, number)?).into(); + } + println!("{row}"); + } + Ok(()) +} + +async fn serve(config_path: Option<&Path>) -> Result<(), Box> { + let mut config = Config::load_with_path(config_path)?; + let history_dir = config.response_history_dir.clone(); + let response_history = tokio::task::spawn_blocking(move || { + strata_control::responses::ResponseHistory::open(history_dir.as_deref()) + }) + .await??; + config.check_host().await?; + let _embedded = match config.worker.as_mut() { + Some(worker) => { + let embedded = strata_control::embedded_engine::resolve(&worker.executable)?; + if let Some(engine) = &embedded { + worker.executable = engine.executable.clone().into_os_string(); + } + embedded + } + None => None, + }; + config.provision().await?; + let listener = tokio::net::TcpListener::bind(config.bind).await?; + let mut state = app::AppState { + queue_timeout: config.queue_timeout, + lifecycle: strata_control::lifecycle::Lifecycle::new(config.max_in_flight_requests)?, + response_history: Arc::new(tokio::sync::RwLock::new(response_history)), + api_key: config.api_key.clone(), + model: config.model.clone(), + ..Default::default() + }; + if let Some(path) = config.tokenizer_dir.as_deref() { + state.tokenizer = Some(Arc::new(tokenizer::Tokenizer::from_assets(path)?)); + } + let (shutdown_tx, shutdown_rx) = watch::channel(false); + let worker_task = config.worker.map(|config| { + let (sender, receiver) = mpsc::channel(16); + state.generation = Some(sender); + tokio::spawn(worker::run_with_requests( + config, + state.worker.clone(), + shutdown_rx, + receiver, + )) + }); + eprintln!("strata-control listening on {}", listener.local_addr()?); + let server_shutdown = shutdown_tx.clone(); + let lifecycle = state.lifecycle.clone(); + let shutdown_grace = config.shutdown_grace; + let result = axum::serve(listener, app::router(state)) + .with_graceful_shutdown(async move { + shutdown_signal().await; + lifecycle.begin_shutdown(); + if !shutdown_grace.is_zero() && !lifecycle.wait_drained(shutdown_grace).await { + eprintln!("Shutdown admission grace expired; stopping worker"); + } + let _ = server_shutdown.send(true); + }) + .await; + let _ = shutdown_tx.send(true); + if let Some(task) = worker_task { + task.await?; + } + result?; + Ok(()) +} + +async fn shutdown_signal() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler"); + tokio::select! { + _ = tokio::signal::ctrl_c() => {}, + _ = terminate.recv() => {}, + } + } + #[cfg(not(unix))] + tokio::signal::ctrl_c() + .await + .expect("install Ctrl-C handler"); +} diff --git a/control-plane/src/messages.rs b/control-plane/src/messages.rs new file mode 100644 index 00000000..8036d2e6 --- /dev/null +++ b/control-plane/src/messages.rs @@ -0,0 +1,623 @@ +//! Stateless Anthropic Messages text/client-tool adapter. No remote model service. +use crate::{ + app::AppState, + native_events::{MAX_EVENT, NativeEvents}, + responses, +}; +use axum::{ + Json, + body::{Body, to_bytes}, + extract::{Request as HttpRequest, State, rejection::JsonRejection}, + http::{StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response, Sse, sse::Event}, +}; +use futures_core::Stream; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{ + convert::Infallible, + pin::Pin, + task::{Context, Poll}, +}; +use tokio::sync::mpsc; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + model: String, + max_tokens: u32, + messages: Vec, + system: Option, + #[serde(default)] + stream: bool, + #[serde(default)] + tools: Vec, + tool_choice: Option, + temperature: Option, + top_p: Option, + thinking: Option, + stop_sequences: Option>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CountRequest { + model: String, + messages: Vec, + system: Option, + #[serde(default)] + tools: Vec, + tool_choice: Option, + thinking: Option, +} +impl CountRequest { + fn into_responses(self) -> Result { + // Use the serving converter, including its exact tool/history validation. + // This output limit is only for native request validation; no GEN is sent. + Request { + model: self.model, + max_tokens: 1, + messages: self.messages, + system: self.system, + stream: false, + tools: self.tools, + tool_choice: self.tool_choice, + temperature: None, + top_p: None, + thinking: self.thinking, + stop_sequences: None, + } + .into_responses() + .map(|(value, _)| value) + } +} + +pub async fn count_tokens( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let value = match body { + Ok(Json(value)) => value, + Err(e) => return error(e.status(), &e.body_text()), + }; + let request: CountRequest = match serde_json::from_value(value) { + Ok(request) => request, + Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()), + }; + let native = match request.into_responses() { + Ok(value) => value, + Err(e) => return error(StatusCode::BAD_REQUEST, &e), + }; + let response = responses::count_input_tokens(State(state), Ok(Json(native))).await; + if !response.status().is_success() { + return response; // Route middleware normalizes native errors. + } + let bytes = to_bytes(response.into_body(), 1024).await; + if let Ok(bytes) = bytes + && let Ok(value) = serde_json::from_slice::(&bytes) + && let Some(count) = value["input_tokens"].as_u64() + { + return Json(json!({"input_tokens":count})).into_response(); + } + error(StatusCode::BAD_GATEWAY, "invalid native token count") +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Message { + role: String, + content: Value, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Tool { + name: String, + description: Option, + input_schema: Value, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Choice { + #[serde(rename = "type")] + kind: String, + name: Option, + disable_parallel_tool_use: Option, +} +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +enum Block { + Text { + text: String, + }, + ToolUse { + id: String, + name: String, + input: Value, + }, + ToolResult { + tool_use_id: String, + #[serde(default = "empty_tool_result")] + content: Value, + is_error: Option, + }, +} +fn empty_tool_result() -> Value { + Value::String(String::new()) +} +fn blocks(value: Value) -> Result, String> { + match value { + Value::String(text) => Ok(vec![Block::Text { text }]), + Value::Array(items) => items + .into_iter() + .map(|v| serde_json::from_value(v).map_err(|e| e.to_string())) + .collect(), + _ => Err("content must be a text string or supported blocks".into()), + } +} +fn text_only(value: Value) -> Result { + let mut text = Vec::new(); + for block in blocks(value)? { + match block { + Block::Text { text: t } => text.push(t), + _ => return Err("only text blocks are supported here".into()), + } + } + Ok(text.join("\n")) +} +impl Request { + fn into_responses(self) -> Result<(Value, bool), String> { + if self + .thinking + .is_some_and(|v| v != json!({"type":"disabled"})) + { + return Err("only disabled thinking is supported".into()); + } + if self.stop_sequences.is_some_and(|s| !s.is_empty()) { + return Err("custom stop_sequences are not supported".into()); + } + if self.messages.first().is_some_and(|m| m.role != "user") + || self.messages.last().is_some_and(|m| m.role != "user") + { + return Err("this subset requires first and last user messages; assistant prefill is unsupported".into()); + } + let mut turns: Vec<(String, Vec)> = Vec::new(); + for message in self.messages { + if !matches!(message.role.as_str(), "user" | "assistant") { + return Err("messages role must be user or assistant; use top-level system".into()); + } + let parts = blocks(message.content)?; + if parts.is_empty() { + return Err("message content must not be empty".into()); + } + if let Some((role, previous)) = turns.last_mut() + && *role == message.role + { + previous.extend(parts); + } else { + turns.push((message.role, parts)); + } + } + let mut input = Vec::new(); + for (role, parts) in turns { + let mut text = Vec::new(); + let flush = |text: &mut Vec, input: &mut Vec| { + if !text.is_empty() { + input.push(json!({"role":role,"content":text.join("\n")})); + text.clear(); + } + }; + for part in parts { + match part { + Block::Text { text: t } => text.push(t), + Block::ToolUse { + id, + name, + input: arguments, + } if role == "assistant" => { + flush(&mut text, &mut input); + if !arguments.is_object() { + return Err("tool_use.input must be an object".into()); + } + input.push(json!({"type":"function_call","call_id":id,"name":name,"arguments":arguments.to_string()})); + } + Block::ToolResult { + tool_use_id, + content, + is_error, + } if role == "user" => { + flush(&mut text, &mut input); + let text = text_only(content)?; + // The local template has text tool outputs, not a separate error bit. + // Keep the bit and exact normalized content together in the tool role. + let output = if is_error == Some(true) { + json!({"is_error":true,"content":text}).to_string() + } else { + text + }; + input.push(json!({"type":"function_call_output","call_id":tool_use_id,"output":output})); + } + _ => { + return Err( + "tool_use belongs to assistant; tool_result belongs to user".into() + ); + } + } + } + flush(&mut text, &mut input); + } + let tools: Vec<_> = self + .tools + .into_iter() + .map(|t| { + let mut v = json!({"type":"function","name":t.name,"parameters":t.input_schema}); + if let Some(description) = t.description { + v["description"] = json!(description); + } + v + }) + .collect(); + let mut r = json!({"model":self.model,"input":input,"max_output_tokens":self.max_tokens,"stream":self.stream,"store":false,"reasoning":{"effort":"none"},"tools":tools}); + if let Some(choice) = self.tool_choice { + r["tool_choice"] = match choice.kind.as_str() { + "auto" | "none" | "any" if choice.name.is_none() => { + json!(if choice.kind == "any" { + "required" + } else { + &choice.kind + }) + } + "tool" => { + json!({"type":"function","name":choice.name.ok_or("tool choice requires name")?}) + } + _ => return Err("unsupported tool_choice".into()), + }; + if let Some(disabled) = choice.disable_parallel_tool_use { + r["parallel_tool_calls"] = json!(!disabled); + } + } + if let Some(system) = self.system { + r["instructions"] = json!(text_only(system)?); + } + if let Some(v) = self.temperature { + if !(0.0..=1.0).contains(&v) { + return Err("temperature must be in 0..1".into()); + } + r["temperature"] = json!(v); + } + if let Some(v) = self.top_p { + r["top_p"] = json!(v); + } + Ok((r, self.stream)) + } +} +fn error_type(status: StatusCode) -> &'static str { + match status.as_u16() { + 401 => "authentication_error", + 403 => "permission_error", + 404 => "not_found_error", + 413 => "request_too_large", + 429 => "rate_limit_error", + 503 | 529 => "overloaded_error", + 500..=599 => "api_error", + _ => "invalid_request_error", + } +} +pub(crate) fn error_value(status: StatusCode, message: &str) -> Value { + json!({"type":"error","error":{"type":error_type(status),"message":message}}) +} +fn error(status: StatusCode, message: &str) -> Response { + (status, Json(error_value(status, message))).into_response() +} +/// This wraps route admission and extraction errors, so they share the Messages envelope. +pub async fn protocol(request: HttpRequest, next: Next) -> Response { + let versions: Vec<_> = request + .headers() + .get_all("anthropic-version") + .iter() + .collect(); + if versions.len() != 1 || versions[0] != "2023-06-01" { + return error( + StatusCode::BAD_REQUEST, + "anthropic-version must be 2023-06-01", + ); + } + if request.headers().contains_key("anthropic-beta") { + return error( + StatusCode::BAD_REQUEST, + "anthropic-beta features are not supported", + ); + } + let response = next.run(request).await; + if response.status().is_success() { + return response; + } + let status = response.status(); + let preserved: Vec<_> = [header::ALLOW, header::RETRY_AFTER, header::WWW_AUTHENTICATE] + .into_iter() + .filter_map(|name| { + response + .headers() + .get(&name) + .cloned() + .map(|value| (name, value)) + }) + .collect(); + let bytes = to_bytes(response.into_body(), 64 * 1024) + .await + .unwrap_or_default(); + let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + let message = value["error"]["message"] + .as_str() + .unwrap_or("Request failed"); + let mut result = error(status, message); + for (name, value) in preserved { + result.headers_mut().insert(name, value); + } + result +} +fn usage(r: &Value) -> Value { + let u = &r["usage"]; + let cached = u["input_tokens_details"]["cached_tokens"] + .as_u64() + .unwrap_or(0); + json!({"input_tokens":u["input_tokens"].as_u64().unwrap_or(0).saturating_sub(cached),"output_tokens":u["output_tokens"].as_u64().unwrap_or(0),"cache_read_input_tokens":cached,"cache_creation_input_tokens":0}) +} +fn stop(r: &Value) -> &'static str { + if r["status"] == "incomplete" { + "max_tokens" + } else if r["output"] + .as_array() + .is_some_and(|a| a.iter().any(|i| i["type"] == "function_call")) + { + "tool_use" + } else { + "end_turn" + } +} +fn tool(item: &Value) -> Result { + let input: Value = serde_json::from_str( + item["arguments"] + .as_str() + .ok_or("missing native tool arguments")?, + ) + .map_err(|_| "invalid native tool arguments")?; + if !input.is_object() { + return Err("native tool input must be an object"); + } + Ok(json!({"type":"tool_use","id":item["call_id"],"name":item["name"],"input":input})) +} +fn message(r: &Value, initial: bool) -> Result { + let mut content = Vec::new(); + if !initial && let Some(items) = r["output"].as_array() { + for item in items { + if item["type"] == "function_call" { + content.push(tool(item)?); + } + if item["type"] == "message" + && let Some(parts) = item["content"].as_array() + { + for p in parts { + if p["type"] == "output_text" { + content.push(json!({"type":"text","text":p["text"]})); + } + } + } + } + } + Ok( + json!({"id":format!("msg_{}",r["id"].as_str().unwrap_or("unknown")),"type":"message","role":"assistant","model":r["model"],"content":content,"stop_reason":if initial{Value::Null}else{json!(stop(r))},"stop_sequence":null,"usage":usage(r)}), + ) +} +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let Json(value) = match body { + Ok(v) => v, + Err(e) => return error(e.status(), &e.to_string()), + }; + let r: Request = match serde_json::from_value(value) { + Ok(r) => r, + Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()), + }; + let (r, stream) = match r.into_responses() { + Ok(r) => r, + Err(e) => return error(StatusCode::BAD_REQUEST, &e), + }; + let response = responses::create(State(state), Ok(Json(r))).await; + if !response.status().is_success() { + return response; + } + if stream { + return stream_response(response.into_body()); + } + let bytes = match to_bytes(response.into_body(), MAX_EVENT).await { + Ok(v) => v, + Err(_) => { + return error( + StatusCode::BAD_GATEWAY, + "native response exceeds adapter limit", + ); + } + }; + let value: Value = match serde_json::from_slice(&bytes) { + Ok(v) => v, + Err(_) => return error(StatusCode::BAD_GATEWAY, "invalid native response"), + }; + match message(&value, false) { + Ok(v) => Json(v).into_response(), + Err(e) => error(StatusCode::BAD_GATEWAY, e), + } +} +struct Events(mpsc::Receiver); +impl Stream for Events { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.0.poll_recv(cx).map(|v| v.map(Ok)) + } +} +async fn send(sender: &mpsc::Sender, value: Value) -> Result<(), &'static str> { + let kind = value["type"].as_str().ok_or("missing event type")?; + sender + .send(Event::default().event(kind).data(value.to_string())) + .await + .map_err(|_| "client disconnected") +} +async fn close_text( + sender: &mpsc::Sender, + active: &mut bool, + index: &mut usize, +) -> Result<(), &'static str> { + if *active { + send(sender, json!({"type":"content_block_stop","index":*index})).await?; + *active = false; + *index += 1; + } + Ok(()) +} +async fn adapt(body: &mut Body, sender: &mpsc::Sender) -> Result<(), &'static str> { + let mut reader = NativeEvents::new(body); + let mut index = 0; + let mut active = false; + loop { + let e = tokio::select! {_=sender.closed()=>return Ok(()),e=reader.next()=>e?}; + match e["type"].as_str() { + Some("response.created") => { + send( + sender, + json!({"type":"message_start","message":message(&e["response"],true)?}), + ) + .await? + } + Some("response.output_text.delta") => { + if !active { + send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?; + active = true; + } + send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"text_delta","text":e["delta"]}})).await?; + } + Some("response.output_text.done") => { + if !active && e["text"] == "" { + send(sender,json!({"type":"content_block_start","index":index,"content_block":{"type":"text","text":""}})).await?; + active = true; + } + close_text(sender, &mut active, &mut index).await?; + } + Some("response.output_item.done") if e["item"]["type"] == "function_call" => { + close_text(sender, &mut active, &mut index).await?; + let mut block = tool(&e["item"])?; + block["input"] = json!({}); + send( + sender, + json!({"type":"content_block_start","index":index,"content_block":block}), + ) + .await?; + send(sender,json!({"type":"content_block_delta","index":index,"delta":{"type":"input_json_delta","partial_json":e["item"]["arguments"]}})).await?; + send(sender, json!({"type":"content_block_stop","index":index})).await?; + index += 1; + } + Some("response.completed" | "response.incomplete") => { + close_text(sender, &mut active, &mut index).await?; + send(sender,json!({"type":"message_delta","delta":{"stop_reason":stop(&e["response"]),"stop_sequence":null},"usage":usage(&e["response"])})).await?; + send(sender, json!({"type":"message_stop"})).await?; + return Ok(()); + } + Some("response.failed") => { + send( + sender, + error_value( + StatusCode::BAD_GATEWAY, + e["response"]["error"]["message"] + .as_str() + .unwrap_or("Generation failed"), + ), + ) + .await?; + return Ok(()); + } + _ => {} + } + } +} +fn stream_response(mut body: Body) -> Response { + let (sender, receiver) = mpsc::channel(8); + tokio::spawn(async move { + let result = adapt(&mut body, &sender).await; + drop(body); + if let Err(message) = result { + let _ = send(&sender, error_value(StatusCode::BAD_GATEWAY, message)).await; + } + }); + Sse::new(Events(receiver)) + .keep_alive(crate::native_events::keep_alive()) + .into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tool_results_preserve_errors_empty_content_and_success_bytes() { + let text = "failure 🌍\n\"quote\" \\ path\u{0000}"; + let make = |result: Value| { + serde_json::from_value::(json!({"model":"fixture","max_tokens":8,"messages":[ + {"role":"user","content":"Do it"}, + {"role":"assistant","content":[{"type":"tool_use","id":"call","name":"work","input":{}}]}, + {"role":"user","content":[result]} + ]})).unwrap().into_responses() + }; + for error in [None, Some(false), Some(true)] { + for content in [ + None, + Some(json!(text)), + Some(json!([])), + Some(json!([ + {"type":"text","text":text}, {"type":"text","text":"last"} + ])), + ] { + let normalized = match &content { + None => String::new(), + Some(Value::String(s)) => s.clone(), + Some(Value::Array(parts)) if parts.is_empty() => String::new(), + _ => format!("{text}\nlast"), + }; + let mut result = json!({"type":"tool_result","tool_use_id":"call"}); + if let Some(content) = content { + result["content"] = content; + } + if let Some(error) = error { + result["is_error"] = json!(error); + } + let (native, _) = make(result).unwrap(); + let output = native["input"][2]["output"].as_str().unwrap(); + assert_eq!(native["input"][2]["call_id"], "call"); + assert_eq!(native["input"][2]["type"], "function_call_output"); + assert_eq!(native["input"].as_array().unwrap().len(), 3); + if error == Some(true) { + assert_eq!( + serde_json::from_str::(output).unwrap(), + json!({"is_error":true,"content":normalized}) + ); + } else { + assert_eq!(output, normalized); + } + } + } + for content in [ + Value::Null, + json!(3), + json!({}), + json!([{"type":"image","source":{}}]), + ] { + assert!(make(json!({"type":"tool_result","tool_use_id":"call","content":content,"is_error":true})).is_err()); + } + for flag in [json!("true"), json!(1), json!({})] { + assert!( + serde_json::from_value::( + json!({"type":"tool_result","tool_use_id":"call","is_error":flag}) + ) + .is_err() + ); + } + } +} diff --git a/control-plane/src/metrics.rs b/control-plane/src/metrics.rs new file mode 100644 index 00000000..fc6ca2da --- /dev/null +++ b/control-plane/src/metrics.rs @@ -0,0 +1,120 @@ +//! Payload-free engine telemetry, scoped to one control-plane process. +use std::time::Instant; + +use serde::Serialize; + +use crate::wire::{Done, Finish}; + +#[derive(Clone, Copy, Default, Serialize)] +pub struct GenerationMetrics { + #[serde(skip)] + pub active_since: Option, + pub started: u64, + pub completed: u64, + pub cancelled: u64, + pub failed_or_interrupted: u64, + pub done_generated_tokens: u64, + pub done_prompt_tokens: u64, + pub done_decode_ms: f64, + pub done_prefill_ms: f64, + pub last_done: Option, +} + +#[derive(Clone, Copy, Serialize)] +pub struct GenerationSummary { + pub generated_tokens: u64, + pub prompt_tokens: u64, + pub prefill_ms: f64, + pub decode_ms: f64, + pub decode_tokens_per_second: Option, + pub finish: &'static str, + pub reused_tokens: Option, + pub drafts_accepted: Option, + pub drafts_offered: Option, + pub expert_hits: Option, + pub expert_lookups: Option, +} + +pub fn token_rate(tokens: u64, milliseconds: f64) -> Option { + let rate = tokens as f64 / milliseconds * 1000.0; + (milliseconds > 0.0 && rate.is_finite()).then_some(rate) +} + +impl GenerationMetrics { + pub fn start(&mut self) { + self.started = self.started.saturating_add(1); + self.active_since = Some(Instant::now()); + } + + pub fn fail(&mut self) { + if self.active_since.take().is_some() { + self.failed_or_interrupted = self.failed_or_interrupted.saturating_add(1); + } + } + + pub fn finish(&mut self, done: &Done, disconnected: bool) { + self.active_since = None; + if disconnected || done.finish == Finish::Cancel { + self.cancelled = self.cancelled.saturating_add(1); + } else { + self.completed = self.completed.saturating_add(1); + } + self.done_generated_tokens = self.done_generated_tokens.saturating_add(done.generated); + self.done_prompt_tokens = self.done_prompt_tokens.saturating_add(done.prompt_tokens); + // Parser rejects negative/nonfinite individual timings; cap sum overflow. + self.done_decode_ms = (self.done_decode_ms + done.decode_ms).min(f64::MAX); + self.done_prefill_ms = (self.done_prefill_ms + done.prompt_ms).min(f64::MAX); + self.last_done = Some(GenerationSummary { + generated_tokens: done.generated, + prompt_tokens: done.prompt_tokens, + prefill_ms: done.prompt_ms, + decode_ms: done.decode_ms, + decode_tokens_per_second: token_rate(done.generated, done.decode_ms), + finish: match done.finish { + Finish::Stop => "stop", + Finish::Length => "length", + Finish::Cancel => "cancel", + }, + reused_tokens: done.reused, + drafts_accepted: done.drafts_accepted, + drafts_offered: done.drafts_offered, + expert_hits: done.expert_hits, + expert_lookups: done.expert_lookups, + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unavailable_rates_are_null_and_disconnected_done_is_cancelled() { + assert_eq!(token_rate(10, 0.0), None); + assert_eq!(token_rate(10, f64::MIN_POSITIVE), None); + assert_eq!(token_rate(10, 20.0), Some(500.0)); + let crate::wire::Event::Done(done) = crate::wire::parse_line("DONE 2 3 1.0 4.0 stop") + .unwrap() + .unwrap() + else { + panic!() + }; + let mut metrics = GenerationMetrics::default(); + metrics.start(); + metrics.finish(&done, true); + metrics.fail(); + assert_eq!( + ( + metrics.completed, + metrics.cancelled, + metrics.failed_or_interrupted + ), + (0, 1, 0) + ); + assert_eq!(metrics.last_done.unwrap().finish, "stop"); + assert_eq!( + token_rate(metrics.done_generated_tokens, metrics.done_decode_ms), + Some(500.0) + ); + } +} diff --git a/control-plane/src/model.rs b/control-plane/src/model.rs new file mode 100644 index 00000000..a4b12e85 --- /dev/null +++ b/control-plane/src/model.rs @@ -0,0 +1,816 @@ +//! Manifest-pinned model acquisition. Finished files are never accepted by name alone. + +use std::{ + error::Error, + io, + path::{Component, Path, PathBuf}, + time::Duration, +}; + +#[cfg(unix)] +use std::ffi::CString; + +use reqwest::{ + Client, RequestBuilder, StatusCode, + header::{ACCEPT_ENCODING, CONTENT_RANGE, RANGE}, +}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use tokio::{ + fs::{self, File, OpenOptions}, + io::{AsyncReadExt, AsyncWriteExt}, +}; + +type Result = std::result::Result>; +const FETCH_ATTEMPTS: usize = 4; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub schema_version: u32, + pub files: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ModelFile { + pub name: String, + pub url: String, + pub size: u64, + pub sha256: String, +} + +impl Manifest { + pub async fn load(path: &Path) -> Result { + Self::parse(&fs::read(path).await?) + } + + pub async fn from_spec(spec: &str) -> Result { + if spec == "qwen-iq3-s" { + Self::parse(include_bytes!( + "../../manifests/qwen3.8-flash-next-iq3-s.json" + )) + } else { + Self::load(Path::new(spec)).await + } + } + + fn parse(bytes: &[u8]) -> Result { + let manifest: Self = serde_json::from_slice(bytes)?; + if manifest.schema_version != 1 || manifest.files.is_empty() { + return Err("model manifest needs schema_version 1 and at least one file".into()); + } + let mut names = std::collections::HashSet::new(); + for file in &manifest.files { + let path = Path::new(&file.name); + if path.components().count() != 1 + || !matches!(path.components().next(), Some(Component::Normal(_))) + || !names.insert(&file.name) + || file.size == 0 + || file.sha256.len() != 64 + || !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return Err(format!("invalid model file entry: {}", file.name).into()); + } + let url = reqwest::Url::parse(&file.url)?; + if url.scheme() != "https" + && !(url.scheme() == "http" + && matches!(url.host_str(), Some("127.0.0.1" | "localhost"))) + { + return Err(format!("model URL must use HTTPS: {}", file.name).into()); + } + if !url.username().is_empty() || url.password().is_some() { + return Err( + format!("model URL must not contain credentials: {}", file.name).into(), + ); + } + } + Ok(manifest) + } +} + +pub async fn verify(manifest: &Manifest, output: &Path) -> Result<()> { + for file in &manifest.files { + let path = output.join(&file.name); + verify_one(file, &path).await?; + eprintln!("verified {}", path.display()); + } + Ok(()) +} + +pub async fn fetch(manifest: &Manifest, output: &Path) -> Result<()> { + fs::create_dir_all(output).await?; + preflight_space(manifest, output).await?; + // A scratch image and a standalone musl binary may have no host CA store. + // Keep certificate and hostname verification, with a root set in the binary. + let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS + .iter() + .map(|der| reqwest::Certificate::from_der(der.as_ref())) + .collect::, _>>()?; + let client = Client::builder() + .tls_certs_only(roots) + .connect_timeout(Duration::from_secs(30)) + .read_timeout(Duration::from_secs(120)) + .redirect(reqwest::redirect::Policy::custom(|attempt| { + let url = attempt.url(); + if attempt.previous().len() >= 10 { + attempt.error("too many redirects") + } else if url.scheme() == "https" + || (url.scheme() == "http" + && matches!(url.host_str(), Some("127.0.0.1" | "localhost"))) + { + if url.username().is_empty() && url.password().is_none() { + attempt.follow() + } else { + attempt.error("refusing a model redirect containing credentials") + } + } else { + attempt.error("refusing a non-HTTPS model redirect") + } + })) + .build()?; + let hub_token = match std::env::var("HF_TOKEN") { + Ok(token) if token.is_empty() => None, + Ok(token) if token.chars().any(char::is_whitespace) => { + return Err("HF_TOKEN must not contain whitespace".into()); + } + Ok(token) => Some(token), + Err(std::env::VarError::NotPresent) => None, + Err(std::env::VarError::NotUnicode(_)) => { + return Err("HF_TOKEN must contain valid UTF-8".into()); + } + }; + for file in &manifest.files { + fetch_one_with_retry(&client, file, output, hub_token.as_deref()).await?; + } + Ok(()) +} + +async fn fetch_one_with_retry( + client: &Client, + file: &ModelFile, + output: &Path, + hub_token: Option<&str>, +) -> Result<()> { + for attempt in 1..=FETCH_ATTEMPTS { + match fetch_one(client, file, output, hub_token).await { + Ok(()) => return Ok(()), + Err(error) if attempt < FETCH_ATTEMPTS && retryable_fetch_error(error.as_ref()) => { + let delay = Duration::from_secs(1 << (attempt - 1)); + eprintln!( + "temporary download failure for {} (attempt {attempt}/{FETCH_ATTEMPTS}): {error}; retrying in {}s", + file.name, + delay.as_secs() + ); + tokio::time::sleep(delay).await; + } + Err(error) => return Err(error), + } + } + unreachable!("the final fetch attempt returns directly") +} + +fn retryable_fetch_error(error: &(dyn Error + 'static)) -> bool { + if let Some(network) = error.downcast_ref::() { + return network.is_connect() + || network.is_timeout() + || network.is_body() + || network.status().is_some_and(|status| { + status.is_server_error() + || status == StatusCode::TOO_MANY_REQUESTS + || status == StatusCode::REQUEST_TIMEOUT + }); + } + error + .downcast_ref::() + .is_some_and(|local| local.kind() == io::ErrorKind::UnexpectedEof) +} + +fn model_request( + client: &Client, + file: &ModelFile, + offset: u64, + hub_token: Option<&str>, +) -> Result { + let url = reqwest::Url::parse(&file.url)?; + let mut request = client.get(url.clone()).header(ACCEPT_ENCODING, "identity"); + if is_hugging_face_url(&url) + && let Some(token) = hub_token + { + request = request.bearer_auth(token); + } + if offset > 0 { + request = request.header(RANGE, format!("bytes={offset}-")); + } + Ok(request) +} + +fn is_hugging_face_url(url: &reqwest::Url) -> bool { + url.scheme() == "https" && url.host_str() == Some("huggingface.co") +} + +async fn fetch_one( + client: &Client, + file: &ModelFile, + output: &Path, + hub_token: Option<&str>, +) -> Result<()> { + let destination = output.join(&file.name); + reject_symlink(&destination).await?; + match fs::metadata(&destination).await { + Ok(_) => { + verify_one(file, &destination).await?; + eprintln!("already verified {}", destination.display()); + return Ok(()); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + let partial = part_path(&destination); + reject_symlink(&partial).await?; + let mut offset = match fs::metadata(&partial).await { + Ok(metadata) => metadata.len(), + Err(error) if error.kind() == io::ErrorKind::NotFound => 0, + Err(error) => return Err(error.into()), + }; + if offset > file.size { + return Err(format!("partial file is larger than manifest size: {}", file.name).into()); + } + if offset == file.size { + verify_one(file, &partial).await?; + fs::rename(&partial, &destination).await?; + return Ok(()); + } + let request = model_request(client, file, offset, hub_token)?; + let mut response = request.send().await?.error_for_status()?; + match response.status() { + StatusCode::PARTIAL_CONTENT => { + let expected = format!("bytes {offset}-{}/{}", file.size - 1, file.size); + let actual = response + .headers() + .get(CONTENT_RANGE) + .and_then(|value| value.to_str().ok()); + if actual != Some(expected.as_str()) { + return Err( + format!("unexpected Content-Range for {}: {actual:?}", file.name).into(), + ); + } + } + StatusCode::OK => offset = 0, + status => return Err(format!("unexpected HTTP {status} for {}", file.name).into()), + } + require_space( + destination + .parent() + .ok_or("model destination has no parent")?, + file.size - offset, + )?; + let mut hasher = Sha256::new(); + if offset > 0 { + let (size, prefix_hash) = hash_file(&partial).await?; + if size != offset { + return Err("partial file changed during resume".into()); + } + hasher = prefix_hash; + } + let mut writer = OpenOptions::new() + .create(true) + .write(true) + .append(offset > 0) + .truncate(offset == 0) + .open(&partial) + .await?; + let mut received = offset; + let mut progress_at = tokio::time::Instant::now(); + eprintln!("fetching {}: {received}/{} bytes", file.name, file.size); + while let Some(chunk) = response.chunk().await? { + received = received + .checked_add(chunk.len() as u64) + .ok_or("download length overflow")?; + if received > file.size { + return Err(format!("download exceeded manifest size: {}", file.name).into()); + } + writer.write_all(&chunk).await?; + hasher.update(&chunk); + if progress_at.elapsed() >= Duration::from_secs(10) { + eprintln!( + "fetching {}: {received}/{} bytes ({:.1}%)", + file.name, + file.size, + received as f64 * 100.0 / file.size as f64 + ); + progress_at = tokio::time::Instant::now(); + } + } + writer.flush().await?; + writer.sync_all().await?; + drop(writer); + if received != file.size { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!( + "incomplete download for {}: {received}/{}", + file.name, file.size + ), + ) + .into()); + } + let digest = hex::encode(hasher.finalize()); + if !digest.eq_ignore_ascii_case(&file.sha256) { + fs::remove_file(&partial).await?; + return Err(format!("SHA-256 mismatch for {}", file.name).into()); + } + fs::rename(&partial, &destination).await?; + eprintln!("downloaded {}", destination.display()); + Ok(()) +} + +async fn preflight_space(manifest: &Manifest, output: &Path) -> Result<()> { + let mut needed = 0u64; + for entry in &manifest.files { + let destination = output.join(&entry.name); + reject_symlink(&destination).await?; + let remaining = match fs::metadata(&destination).await { + Ok(metadata) if metadata.len() == entry.size => 0, + Ok(_) => { + return Err( + format!("existing model file has unexpected size: {}", entry.name).into(), + ); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let partial = part_path(&destination); + reject_symlink(&partial).await?; + let offset = match fs::metadata(&partial).await { + Ok(metadata) => metadata.len(), + Err(error) if error.kind() == io::ErrorKind::NotFound => 0, + Err(error) => return Err(error.into()), + }; + entry + .size + .checked_sub(offset) + .ok_or("partial file exceeds manifest size")? + } + Err(error) => return Err(error.into()), + }; + needed = needed + .checked_add(remaining) + .ok_or("model disk-space requirement overflow")?; + } + require_space(output, needed) +} + +pub(crate) fn require_space(directory: &Path, needed: u64) -> Result<()> { + let available = available_bytes(directory)?; + if available < needed { + return Err(format!( + "insufficient disk space: need {needed} additional bytes, have {available} available bytes in {}", + directory.display() + ).into()); + } + Ok(()) +} + +#[cfg(unix)] +fn available_bytes(directory: &Path) -> io::Result { + use std::{mem::MaybeUninit, os::unix::ffi::OsStrExt}; + let path = CString::new(directory.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "directory contains NUL"))?; + let mut stats = MaybeUninit::::uninit(); + // SAFETY: path is NUL-terminated and stats points to writable statvfs storage. + if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: a successful statvfs call initialized every field of stats. + let stats = unsafe { stats.assume_init() }; + // statvfs counters have different widths on macOS and Linux. Widen both + // before multiplying, then check the byte count at the public u64 bound. + u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize)) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "available space overflow")) +} + +#[cfg(not(unix))] +fn available_bytes(_directory: &Path) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "model fetch needs a Unix filesystem", + )) +} + +async fn verify_one(file: &ModelFile, path: &Path) -> Result<()> { + reject_symlink(path).await?; + let (size, hasher) = hash_file(path).await?; + if size != file.size || !hex::encode(hasher.finalize()).eq_ignore_ascii_case(&file.sha256) { + return Err(format!( + "model file failed size/SHA-256 verification: {}", + path.display() + ) + .into()); + } + Ok(()) +} + +async fn hash_file(path: &Path) -> Result<(u64, Sha256)> { + let mut reader = File::open(path).await?; + let mut hasher = Sha256::new(); + let mut size = 0u64; + let mut buffer = vec![0u8; 1024 * 1024]; + loop { + let read = reader.read(&mut buffer).await?; + if read == 0 { + break; + } + size = size + .checked_add(read as u64) + .ok_or("file length overflow")?; + hasher.update(&buffer[..read]); + } + Ok((size, hasher)) +} + +async fn reject_symlink(path: &Path) -> Result<()> { + match fs::symlink_metadata(path).await { + Ok(metadata) if metadata.file_type().is_symlink() => { + Err(format!("refusing symlink: {}", path.display()).into()) + } + Ok(_) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.into()), + } +} + +fn part_path(destination: &Path) -> PathBuf { + destination.with_file_name(format!( + "{}.part", + destination.file_name().unwrap().to_string_lossy() + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::time::{SystemTime, UNIX_EPOCH}; + use tokio::{net::TcpListener, time::timeout}; + + #[tokio::test] + async fn insufficient_space_stops_before_network_or_partial_file() { + let root = std::env::temp_dir().join(format!( + "strata-space-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let manifest = Manifest { + schema_version: 1, + files: vec![ModelFile { + name: "huge.gguf".into(), + url: "https://example.invalid/huge.gguf".into(), + size: u64::MAX, + sha256: "0".repeat(64), + }], + }; + let error = fetch(&manifest, &root).await.unwrap_err().to_string(); + assert!(error.contains("insufficient disk space")); + assert!(!root.join("huge.gguf.part").exists()); + fs::remove_dir_all(root).await.unwrap(); + } + + #[tokio::test] + async fn interrupted_download_resumes_and_verifies() { + let base = std::env::temp_dir().join(format!( + "strata-model-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + let output = base.join("model"); + fs::create_dir_all(&output).await.unwrap(); + fs::write(output.join("sample.bin.part"), b"abc") + .await + .unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + let request = String::from_utf8(request).unwrap(); + assert!(request.to_ascii_lowercase().contains("range: bytes=3-")); + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + }); + let manifest_path = base.join("manifest.json"); + fs::write( + &manifest_path, + serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .await + .unwrap(); + let manifest = Manifest::load(&manifest_path).await.unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &output)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + verify(&manifest, &output).await.unwrap(); + assert_eq!( + fs::read(output.join("sample.bin")).await.unwrap(), + b"abcdef" + ); + assert!(!output.join("sample.bin.part").exists()); + fs::write(output.join("sample.bin"), b"xxxxxx") + .await + .unwrap(); + assert!(verify(&manifest, &output).await.is_err()); + fs::remove_dir_all(&base).await.unwrap(); + } + + #[tokio::test] + async fn checksum_mismatch_never_publishes_download() { + let base = std::env::temp_dir().join(format!( + "strata-bad-download-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nxxxxxx", + ) + .await + .unwrap(); + }); + let manifest = Manifest { + schema_version: 1, + files: vec![ModelFile { + name: "sample.bin".into(), + url: format!("http://{address}/sample.bin"), + size: 6, + sha256: hex::encode(Sha256::digest(b"abcdef")), + }], + }; + let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap_err(); + assert!(error.to_string().contains("SHA-256 mismatch")); + server.await.unwrap(); + assert!(!base.join("sample.bin").exists()); + assert!(!base.join("sample.bin.part").exists()); + // Also cover a full-length partial left by a prior interrupted process. + fs::write(base.join("sample.bin.part"), b"xxxxxx") + .await + .unwrap(); + let error = timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap_err(); + assert!(error.to_string().contains("size/SHA-256 verification")); + assert!(!base.join("sample.bin").exists()); + fs::remove_dir_all(base).await.unwrap(); + } + + #[tokio::test] + async fn transient_server_failure_retries_the_same_partial_download() { + let base = std::env::temp_dir().join(format!( + "strata-retry-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + fs::write(base.join("sample.bin.part"), b"abc") + .await + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + assert!( + String::from_utf8(request) + .unwrap() + .to_ascii_lowercase() + .contains("range: bytes=3-") + ); + if attempt == 0 { + socket + .write_all( + b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + } else { + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + } + } + }); + let manifest = Manifest::parse( + &serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); + assert!(!base.join("sample.bin.part").exists()); + fs::remove_dir_all(base).await.unwrap(); + } + + #[tokio::test] + async fn short_response_resumes_from_new_partial_offset() { + let base = std::env::temp_dir().join(format!( + "strata-short-response-test-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(&base).await.unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + for attempt in 0..2 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = Vec::new(); + let mut buffer = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + } + let request = String::from_utf8(request).unwrap().to_ascii_lowercase(); + if attempt == 0 { + assert!(!request.contains("range:")); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: close\r\n\r\nabc", + ) + .await + .unwrap(); + } else { + assert!(request.contains("range: bytes=3-")); + socket + .write_all(b"HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 3-5/6\r\nConnection: close\r\n\r\ndef") + .await + .unwrap(); + } + } + }); + let manifest = Manifest::parse( + &serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "sample.bin", + "url": format!("http://{address}/sample.bin"), + "size": 6, + "sha256": hex::encode(Sha256::digest(b"abcdef")) + }] + })) + .unwrap(), + ) + .unwrap(); + timeout(Duration::from_secs(5), fetch(&manifest, &base)) + .await + .unwrap() + .unwrap(); + server.await.unwrap(); + assert_eq!(fs::read(base.join("sample.bin")).await.unwrap(), b"abcdef"); + assert!(!base.join("sample.bin.part").exists()); + fs::remove_dir_all(base).await.unwrap(); + } + + #[tokio::test] + async fn manifest_rejects_path_traversal() { + let path = + std::env::temp_dir().join(format!("strata-bad-manifest-{}.json", std::process::id())); + fs::write(&path, serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{"name": "../escape", "url": "https://example.com/file", "size": 1, "sha256": "a".repeat(64)}] + })).unwrap()).await.unwrap(); + assert!(Manifest::load(&path).await.is_err()); + fs::remove_file(path).await.unwrap(); + } + + #[test] + fn hub_token_is_only_attached_to_exact_https_host() { + let client = Client::new(); + for (url, expected_auth) in [ + ( + "https://huggingface.co/org/repo/resolve/commit/model.gguf", + true, + ), + ("https://huggingface.co.evil.example/model.gguf", false), + ("https://example.com/model.gguf", false), + ("http://localhost/model.gguf", false), + ] { + let file = ModelFile { + name: "model.gguf".into(), + url: url.into(), + size: 1, + sha256: "0".repeat(64), + }; + let request = model_request(&client, &file, 3, Some("test-secret")) + .unwrap() + .build() + .unwrap(); + assert_eq!( + request + .headers() + .get(reqwest::header::AUTHORIZATION) + .is_some(), + expected_auth, + "{url}" + ); + assert_eq!(request.headers().get(RANGE).unwrap(), "bytes=3-"); + } + } + + #[test] + fn manifest_rejects_url_credentials() { + let bytes = serde_json::to_vec(&json!({ + "schema_version": 1, + "files": [{ + "name": "model.gguf", + "url": "https://alice:secret@huggingface.co/model.gguf", + "size": 1, + "sha256": "0".repeat(64) + }] + })) + .unwrap(); + assert!(Manifest::parse(&bytes).is_err()); + } + + #[tokio::test] + async fn builtin_profile_is_embedded_and_pinned() { + let manifest = Manifest::from_spec("qwen-iq3-s").await.unwrap(); + assert_eq!(manifest.files.len(), 2); + assert_eq!( + manifest.files[0].size + manifest.files[1].size, + 83_617_662_656 + ); + assert!(manifest.files.iter().all(|file| { + file.url + .contains("/resolve/ed59f92082b1e93c0e96d60a8b11aab089b52f09/") + })); + } +} diff --git a/control-plane/src/model_pipeline.rs b/control-plane/src/model_pipeline.rs new file mode 100644 index 00000000..1822c559 --- /dev/null +++ b/control-plane/src/model_pipeline.rs @@ -0,0 +1,225 @@ +//! Fail-closed acquisition and preparation paths. The full-size stream is +//! experimental until real-model quality and Linux GPU loading are verified. + +use std::{ + error::Error, + fs, io, + path::{Component, Path}, +}; + +use crate::{gguf, kar, model, prepare_preview, stream_parts}; + +pub enum PreviewOutcome { + Created(prepare_preview::PreviewSummary), + Reused(kar::Summary), +} + +pub async fn ensure_sharded_preview( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result> { + if !(1..=8).contains(&levels) { + return Err("sharded preview requires 1..=8 KAR levels".into()); + } + let source_bytes = manifest + .files + .iter() + .try_fold(0u64, |sum, file| sum.checked_add(file.size)) + .ok_or("sharded source byte count overflow")?; + if source_bytes > 64 * 1024 * 1024 { + return Err("sharded preview accepts at most 64 MiB of GGUF input; full-model preparation is not implemented".into()); + } + + model::fetch(manifest, source_dir).await?; + model::verify(manifest, source_dir).await?; + + match fs::symlink_metadata(archive) { + Ok(metadata) => { + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("existing KAR path must be a regular file".into()); + } + let summary = prepare_preview::verify_sharded(manifest, source_dir, archive)?; + if summary.max_planes != levels { + return Err(format!( + "existing KAR has {} levels, requested {levels}; choose another output path", + summary.max_planes + ) + .into()); + } + Ok(PreviewOutcome::Reused(summary)) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let created = prepare_preview::prepare_sharded(manifest, source_dir, archive, levels)?; + prepare_preview::verify_sharded(manifest, source_dir, archive)?; + Ok(PreviewOutcome::Created(created)) + } + Err(error) => Err(error.into()), + } +} + +pub async fn ensure_sharded_streamed( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result> { + ensure_sharded_streamed_with_policy(manifest, source_dir, archive, levels, None).await +} + +pub async fn ensure_sharded_streamed_ple( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: u64, +) -> Result> { + ensure_sharded_streamed_with_policy( + manifest, + source_dir, + archive, + levels, + Some(ple_part_elements), + ) + .await +} + +async fn ensure_sharded_streamed_with_policy( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, + ple_part_elements: Option, +) -> Result> { + if !(1..=8).contains(&levels) { + return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); + } + if let Some(limit) = ple_part_elements { + stream_parts::validate_ple_limit(limit)?; + } + preflight_existing_shards(manifest, source_dir, archive, levels)?; + model::fetch(manifest, source_dir).await?; + model::verify(manifest, source_dir).await?; + match fs::symlink_metadata(archive) { + Ok(metadata) => { + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("existing KAR path must be a regular file".into()); + } + let summary = if let Some(limit) = ple_part_elements { + prepare_preview::verify_sharded_streamed_ple( + manifest, source_dir, archive, levels, limit, + )? + } else { + prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)? + }; + Ok(PreviewOutcome::Reused(summary)) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let created = if let Some(limit) = ple_part_elements { + prepare_preview::prepare_sharded_streamed_ple( + manifest, source_dir, archive, levels, limit, + )? + } else { + prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels)? + }; + if let Some(limit) = ple_part_elements { + prepare_preview::verify_sharded_streamed_ple( + manifest, source_dir, archive, levels, limit, + )?; + } else { + prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?; + } + Ok(PreviewOutcome::Created(created)) + } + Err(error) => Err(error.into()), + } +} + +/// Reject an impossible new archive before hashing already-present large +/// shards. GGUF metadata is only a rejection hint; fetch/verify still pins +/// every source byte before preparation when the volume has enough space. +fn preflight_existing_shards( + manifest: &model::Manifest, + source_dir: &Path, + archive: &Path, + levels: u8, +) -> Result<(), Box> { + match fs::symlink_metadata(archive) { + Ok(_) => return Ok(()), // Reusing an archive needs no new payload space. + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + let mut minimum = 0u64; + for shard in &manifest.files { + let name = Path::new(&shard.name); + if name.components().count() != 1 + || !matches!(name.components().next(), Some(Component::Normal(_))) + { + return Err("invalid model shard name".into()); + } + let path = source_dir.join(name); + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(format!("model shard is not a regular file: {}", path.display()).into()); + } + if metadata.len() != shard.size { + return Ok(()); // Fetch will reject or resume this shard. + } + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.summary.file_size != shard.size { + return Err("GGUF shard size differs from manifest".into()); + } + for tensor in index.tensors { + let derived_bytes = tensor + .dimensions + .iter() + .try_fold(4u64, |bytes, dim| bytes.checked_mul(*dim)) + .ok_or("GGUF tensor F32 byte count overflow")?; + minimum = minimum + .checked_add(prepare_preview::minimum_part_payload_bytes( + derived_bytes, + levels, + )?) + .ok_or("KAR minimum payload size overflow")?; + } + } + let parent = archive + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + model::require_space(parent, minimum) + .map_err(|error| format!("KAR minimum payload does not fit: {error}").into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{SystemTime, UNIX_EPOCH}; + + #[tokio::test] + async fn full_model_is_rejected_before_creating_a_download_directory() { + let manifest = model::Manifest::from_spec("qwen-iq3-s").await.unwrap(); + let source_dir = std::env::temp_dir().join(format!( + "strata-oversized-preview-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + assert!(!source_dir.exists()); + let error = + ensure_sharded_preview(&manifest, &source_dir, &source_dir.join("model.kar"), 2) + .await + .err() + .unwrap() + .to_string(); + assert!(error.contains("at most 64 MiB")); + assert!(!source_dir.exists()); + } +} diff --git a/control-plane/src/models_api.rs b/control-plane/src/models_api.rs new file mode 100644 index 00000000..5fbe6f87 --- /dev/null +++ b/control-plane/src/models_api.rs @@ -0,0 +1,120 @@ +//! Configured deployment discovery; does not acquire a worker or imply readiness. +use axum::{ + Json, + extract::{Path, RawQuery, State}, + http::StatusCode, + response::{IntoResponse, Response}, +}; +use serde_json::{Value, json}; + +use crate::app::AppState; + +fn record(id: &str) -> Value { + // No upstream creation/ownership metadata is supplied by the local config. + // Zero is an explicit unknown timestamp sentinel; local names the deployment. + json!({"id":id,"object":"model","created":0,"owned_by":"local"}) +} + +fn query_error(query: Option) -> Option { + query.filter(|q| !q.is_empty()).map(|_| { + ( + StatusCode::BAD_REQUEST, + Json(json!({"error":{ + "type":"invalid_request_error","code":"unsupported_query","param":null, + "message":"model discovery does not support query parameters" + }})), + ) + .into_response() + }) +} + +pub async fn list(State(state): State, RawQuery(query): RawQuery) -> Response { + if let Some(error) = query_error(query) { + return error; + } + let data: Vec<_> = state.model.as_deref().map(record).into_iter().collect(); + Json(json!({"object":"list","data":data})).into_response() +} + +pub async fn retrieve( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = query_error(query) { + return error; + } + if state.model.as_deref() == Some(id.as_str()) { + return Json(record(&id)).into_response(); + } + ( + StatusCode::NOT_FOUND, + Json(json!({"error":{ + "type":"invalid_request_error","code":"model_not_found","param":"model", + "message":"the requested model is not configured on this runtime" + }})), + ) + .into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn discovery_during_worker_outage_and_drain_never_schedules_generation() { + let (sender, mut receiver) = tokio::sync::mpsc::channel(1); + let state = AppState { + model: Some("org/model : v1".into()), + generation: Some(sender), + ..Default::default() + }; + state.lifecycle.set_draining(true); + state.worker.write().await.state = crate::worker::WorkerState::Restarting; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = crate::app::router(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await }); + let client = reqwest::Client::new(); + for (path, expected) in [ + ( + "/v1/models", + json!({"object":"list","data":[{"id":"org/model : v1","object":"model","created":0,"owned_by":"local"}]}), + ), + ( + "/v1/models/org%2Fmodel%20%3A%20v1", + json!({"id":"org/model : v1","object":"model","created":0,"owned_by":"local"}), + ), + ] { + let response = client.get(format!("{url}{path}")).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body: Value = serde_json::from_str(&response.text().await.unwrap()).unwrap(); + assert_eq!(body, expected); + } + for (path, code) in [ + ("/v1/models/unknown", 404), + ("/v1/models?limit=1", 400), + ("/v1/models/unknown?x=1", 400), + ] { + let response = client.get(format!("{url}{path}")).send().await.unwrap(); + assert_eq!(response.status().as_u16(), code); + } + assert!(receiver.try_recv().is_err()); + assert_eq!(state.lifecycle.snapshot().requests_in_flight, 0); + assert_eq!(state.lifecycle.snapshot().generation_jobs, 0); + assert_eq!( + state.worker.read().await.state, + crate::worker::WorkerState::Restarting + ); + server.abort(); + let _ = server.await; + let response = list(State(AppState::default()), RawQuery(None)).await; + let body = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + json!({"object":"list","data":[]}) + ); + } +} diff --git a/control-plane/src/mtp_pack.rs b/control-plane/src/mtp_pack.rs new file mode 100644 index 00000000..8e3de0a6 --- /dev/null +++ b/control-plane/src/mtp_pack.rs @@ -0,0 +1,341 @@ +//! Structural preflight for the current Qwen3.8 Flash Next Q2 MTP runtime. +//! Checks current MTP tensor geometry, not values, base-model pairing or draft quality. +use std::{ + collections::HashMap, + fs::{self, File, OpenOptions}, + io::Read, + path::Path, +}; + +const INDEX_LIMIT: u64 = 64 * 1024; +// engine/strata/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). +const REQUIRED: &[(&str, &str, u64, u64)] = &[ + ("fc_embedding.weight", "q8_0", 2560, 2560), + ("fc_hidden.weight", "q8_0", 2560, 2560), + ("self_attn.q_proj.weight", "q8_0", 12288, 2560), + ("self_attn.k_proj.weight", "q8_0", 512, 2560), + ("self_attn.v_proj.weight", "q8_0", 512, 2560), + ("self_attn.o_proj.weight", "q8_0", 2560, 6144), + ("mlp.shared_expert.gate_proj.weight", "q8_0", 640, 2560), + ("mlp.shared_expert.up_proj.weight", "q8_0", 640, 2560), + ("mlp.shared_expert.down_proj.weight", "q8_0", 2560, 640), + ( + "attn_hyper_connection.block_inject_weight.weight", + "bf16", + 4, + 10240, + ), + ( + "attn_hyper_connection.input_mix_weight_down.weight", + "bf16", + 320, + 10240, + ), + ( + "attn_hyper_connection.input_mix_weight_up.weight", + "bf16", + 10240, + 320, + ), + ( + "hyper_connection_mixer.input_mix_weight_down.weight", + "bf16", + 320, + 10240, + ), + ( + "hyper_connection_mixer.input_mix_weight_up.weight", + "bf16", + 10240, + 320, + ), + ("mlp.gate.weight", "bf16", 512, 2560), + ("mlp.shared_expert_gate.weight", "bf16", 1, 2560), + ( + "mlp_hyper_connection.block_inject_weight.weight", + "bf16", + 4, + 10240, + ), + ( + "mlp_hyper_connection.input_mix_weight_down.weight", + "bf16", + 320, + 10240, + ), + ( + "mlp_hyper_connection.input_mix_weight_up.weight", + "bf16", + 10240, + 320, + ), + ("attn_hyper_connection.hc_norm.weight", "f32", 1, 10240), + ("hyper_connection_mixer.hc_norm.weight", "f32", 1, 10240), + ("mlp_hyper_connection.hc_norm.weight", "f32", 1, 10240), + ("pre_fc_norm_embedding.weight", "f32", 1, 2560), + ("pre_fc_norm_hidden.weight", "f32", 1, 10240), + ("self_attn.k_norm.weight", "f32", 1, 256), + ("self_attn.q_norm.weight", "f32", 1, 256), +]; +const OPTIONAL: &[(&str, &str, u64, u64)] = &[ + ("self_attn.indexer.index_qk_proj.weight", "q8_0", 640, 2560), + ("self_attn.indexer.k_layernorm.weight", "f32", 1, 128), + ("self_attn.indexer.q_layernorm.weight", "f32", 1, 128), +]; + +fn regular(path: &Path) -> Result { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options + .open(path) + .map_err(|_| "cannot open MTP runtime file")?; + let meta = file + .metadata() + .map_err(|_| "cannot inspect MTP runtime file")?; + if !meta.is_file() + || fs::symlink_metadata(path) + .map_err(|_| "cannot inspect MTP file path")? + .file_type() + .is_symlink() + { + return Err("MTP runtime files must be regular files, not symlinks"); + } + Ok(file) +} + +pub fn check(directory: &Path) -> Result<(), &'static str> { + let meta = fs::symlink_metadata(directory).map_err(|_| "MTP runtime directory is absent")?; + if !meta.is_dir() || meta.file_type().is_symlink() { + return Err("MTP pack must be a directory, not a symlink"); + } + let index = regular(&directory.join("dense.txt"))?; + if index + .metadata() + .map_err(|_| "cannot inspect MTP index")? + .len() + > INDEX_LIMIT + { + return Err("MTP index exceeds 64 KiB limit"); + } + let mut text = String::new(); + index + .take(INDEX_LIMIT + 1) + .read_to_string(&mut text) + .map_err(|_| "cannot read UTF-8 MTP index")?; + if text.len() as u64 > INDEX_LIMIT { + return Err("MTP index exceeds 64 KiB limit"); + } + let dense = regular(&directory.join("dense.bin"))? + .metadata() + .map_err(|_| "cannot inspect MTP dense file")? + .len(); + let experts = regular(&directory.join("experts.bin"))? + .metadata() + .map_err(|_| "cannot inspect MTP experts")? + .len(); + if experts != EXPERT_BYTES { + return Err("MTP Q2 experts size does not match the 512-expert runtime profile"); + } + validate_index(&text, dense) +} + +fn validate_index(text: &str, dense_bytes: u64) -> Result<(), &'static str> { + if !text.is_ascii() { + return Err("MTP index must use the ASCII engine format"); + } + let mut tensors = HashMap::new(); + let mut ranges = Vec::new(); + for line in text.lines().filter(|s| !s.is_empty()) { + let fields: Vec<_> = line.split_whitespace().collect(); + if fields.len() != 6 || tensors.len() >= 128 { + return Err("malformed or oversized MTP tensor index"); + } + let name = fields[0]; + if name.len() > 180 + || !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b)) + || tensors.contains_key(name) + { + return Err("invalid or duplicate MTP tensor name"); + } + let numbers = fields[2..] + .iter() + .map(|s| s.parse::()) + .collect::, _>>() + .map_err(|_| "invalid MTP tensor dimensions or offsets")?; + let (rows, cols, offset, bytes) = (numbers[0], numbers[1], numbers[2], numbers[3]); + if rows == 0 + || cols == 0 + || rows > i32::MAX as u64 + || cols > i32::MAX as u64 + || offset % 256 != 0 + { + return Err("invalid MTP tensor dimensions or alignment"); + } + let row_bytes = match fields[1] { + "f32" if rows == 1 => cols.checked_mul(4), + "bf16" => cols.checked_mul(2), + "q8_0" if cols.is_multiple_of(32) => (cols / 32).checked_mul(34), + _ => return Err("unsupported MTP tensor kind or row shape"), + } + .ok_or("MTP tensor row size overflow")?; + if row_bytes.checked_mul(rows) != Some(bytes) { + return Err("MTP tensor byte count mismatch"); + } + let end = offset + .checked_add(bytes) + .ok_or("MTP tensor range overflow")?; + if end > dense_bytes { + return Err("MTP dense tensor extends beyond file"); + } + tensors.insert(name, (fields[1], rows, cols)); + ranges.push((offset, end)); + } + for &(name, kind, rows, cols) in REQUIRED { + if tensors.get(name) != Some(&(kind, rows, cols)) { + return Err("MTP required tensor dtype or geometry does not match the current runtime"); + } + } + for &(name, kind, rows, cols) in OPTIONAL { + if tensors + .get(name) + .is_some_and(|shape| *shape != (kind, rows, cols)) + { + return Err("MTP optional tensor dtype or geometry does not match the current runtime"); + } + } + ranges.sort_unstable(); + if ranges.windows(2).any(|p| p[0].1 > p[1].0) { + return Err("MTP dense tensor ranges overlap"); + } + if ranges.last().map(|r| r.1) != Some(dense_bytes) { + return Err("MTP dense file has unindexed trailing bytes"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + fn fixture() -> (String, u64) { + let mut text = String::new(); + let mut end = 0u64; + for (name, kind, rows, cols) in REQUIRED.iter().chain(OPTIONAL) { + let at = end.div_ceil(256) * 256; + let bytes = match *kind { + "q8_0" => rows * (cols / 32) * 34, + "bf16" => rows * cols * 2, + _ => rows * cols * 4, + }; + text.push_str(&format!("{name} {kind} {rows} {cols} {at} {bytes}\n")); + end = at + bytes; + } + (text, end) + } + #[test] + fn validates_layout_and_rejects_malformed_mtp() { + let (text, bytes) = fixture(); + validate_index(&text, bytes).unwrap(); + for invalid in [ + text.replacen(' ', "\u{a0}", 1), + text.replacen("q8_0", "bf16", 1), + text.replacen("2560 2560", "0 2560", 1), + text.replacen("2560 2560", "2560 31", 1), + text.replacen("0 6963200", "1 6963200", 1), + text.replacen("0 6963200", "0 6963201", 1), + text.replacen("6963200 6963200", "0 6963200", 1), + text.lines().skip(1).collect::>().join("\n"), + format!("{text}{}\n", text.lines().next().unwrap()), + text.replacen("fc_hidden", "fc_embedding", 1), + text.replacen("2560 2560", "18446744073709551615 2560", 1), + ] { + assert!(validate_index(&invalid, bytes).is_err()); + } + assert!(validate_index(&text, bytes - 1).is_err()); + assert!(validate_index(&text, bytes + 1).is_err()); + } + #[test] + fn rejects_byte_consistent_transposed_or_undersized_tensors() { + let (text, bytes) = fixture(); + for (name, _, _, _) in REQUIRED.iter().chain(OPTIONAL) { + let mut lines: Vec = text.lines().map(str::to_owned).collect(); + let line = lines + .iter_mut() + .find(|line| line.starts_with(&format!("{name} "))) + .unwrap(); + let mut fields: Vec = line.split_whitespace().map(str::to_owned).collect(); + let rows: u64 = fields[2].parse().unwrap(); + let cols: u64 = fields[3].parse().unwrap(); + if fields[1] != "f32" && rows != cols { + fields.swap(2, 3); // Same elements, range and byte count; wrong kernel geometry. + } else { + fields[3] = (cols / 2).to_string(); + fields[5] = (fields[5].parse::().unwrap() / 2).to_string(); + } + *line = fields.join(" "); + assert!( + validate_index(&lines.join("\n"), bytes) + .unwrap_err() + .contains("geometry"), + "{name}" + ); + } + } + #[test] + fn checks_sparse_files_without_loading_payloads() { + let dir = std::env::temp_dir().join(format!("strata-mtp-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + let (text, bytes) = fixture(); + fs::write(dir.join("dense.txt"), text).unwrap(); + File::create(dir.join("dense.bin")) + .unwrap() + .set_len(bytes) + .unwrap(); + File::create(dir.join("experts.bin")) + .unwrap() + .set_len(EXPERT_BYTES) + .unwrap(); + check(&dir).unwrap(); + File::create(dir.join("experts.bin")) + .unwrap() + .set_len(EXPERT_BYTES - 1) + .unwrap(); + assert!(check(&dir).is_err()); + File::create(dir.join("experts.bin")) + .unwrap() + .set_len(EXPERT_BYTES) + .unwrap(); + fs::remove_file(dir.join("dense.bin")).unwrap(); + assert!(check(&dir).is_err()); + #[cfg(unix)] + { + std::os::unix::fs::symlink(dir.join("experts.bin"), dir.join("dense.bin")).unwrap(); + assert!(check(&dir).is_err()); + fs::remove_file(dir.join("dense.bin")).unwrap(); + } + File::create(dir.join("dense.bin")) + .unwrap() + .set_len(bytes) + .unwrap(); + fs::write(dir.join("dense.txt"), " ".repeat(INDEX_LIMIT as usize + 1)).unwrap(); + assert!(check(&dir).is_err()); + #[cfg(unix)] + { + fs::remove_file(dir.join("dense.txt")).unwrap(); + let path = std::ffi::CString::new(dir.join("dense.txt").as_os_str().as_encoded_bytes()) + .unwrap(); + assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0); + assert!(check(&dir).is_err()); // Must return without waiting for a FIFO writer. + } + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/control-plane/src/native_events.rs b/control-plane/src/native_events.rs new file mode 100644 index 00000000..ff9709fd --- /dev/null +++ b/control-plane/src/native_events.rs @@ -0,0 +1,49 @@ +//! Bounded reader for SSE emitted by our own native Responses pipeline. +use axum::body::Body; +use http_body::Body as _; +use serde_json::Value; +use std::{future::poll_fn, pin::Pin}; + +/// Transport comments keep silent prefill/buffered output connections active. +/// They carry no model data, usage, sequence number, or completion semantics. +pub(crate) fn keep_alive() -> axum::response::sse::KeepAlive { + axum::response::sse::KeepAlive::new() + .interval(std::time::Duration::from_secs(15)) + .text("keep-alive") +} + +pub(crate) const MAX_EVENT: usize = 64 * 1024 * 1024; +pub(crate) struct NativeEvents<'a> { + body: &'a mut Body, + buffer: Vec, +} +impl<'a> NativeEvents<'a> { + pub(crate) fn new(body: &'a mut Body) -> Self { + Self { + body, + buffer: Vec::new(), + } + } + pub(crate) async fn next(&mut self) -> Result { + loop { + while let Some(end) = self.buffer.windows(2).position(|w| w == b"\n\n") { + let frame: Vec<_> = self.buffer.drain(..end + 2).collect(); + let text = std::str::from_utf8(&frame).map_err(|_| "native stream is not UTF-8")?; + if let Some(data) = text.lines().find_map(|line| line.strip_prefix("data: ")) { + return serde_json::from_str(data).map_err(|_| "invalid native stream event"); + } + } + let frame = poll_fn(|cx| Pin::new(&mut *self.body).poll_frame(cx)) + .await + .ok_or("native stream ended without a terminal event")? + .map_err(|_| "native stream read failed")?; + let Ok(data) = frame.into_data() else { + continue; + }; + if data.len() > MAX_EVENT - self.buffer.len() { + return Err("native stream event exceeds 64 MiB"); + } + self.buffer.extend_from_slice(&data); + } + } +} diff --git a/control-plane/src/native_model.rs b/control-plane/src/native_model.rs new file mode 100644 index 00000000..088690b3 --- /dev/null +++ b/control-plane/src/native_model.rs @@ -0,0 +1,276 @@ +//! Config-driven immutable GGUF acquisition, exact preparation and offline reuse. +use crate::{ + asset_bundle::{self, AssetBundle}, + model, native_pack, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + error::Error, + fs::{self, File, OpenOptions}, + io::Read, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result>; +const FILES: &[&str] = &[ + "dense.bin", + "index.txt", + "native_experts.txt", + "conversions.json", + "source.json", + "tokenizer/vocab.json", + "tokenizer/merges.txt", + "tokenizer/token_type.json", + "tokenizer/tokenizer.json", + "tokenizer/chat_template.jinja", +]; + +#[derive(Clone, Copy, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum RuntimeProfile { + Qwen4expFlashNext, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NativeModel { + pub manifest: PathBuf, + pub source_dir: PathBuf, + pub output: PathBuf, + pub runtime_profile: Option, +} + +impl NativeModel { + pub fn validate(&self, assets: &[AssetBundle]) -> Result<()> { + let mut all = vec![ + AssetBundle { + manifest: self.manifest.clone(), + directory: self.source_dir.clone(), + }, + AssetBundle { + manifest: self.manifest.clone(), + directory: self.output.clone(), + }, + ]; + all.extend(assets.iter().map(|a| AssetBundle { + manifest: a.manifest.clone(), + directory: a.directory.clone(), + })); + asset_bundle::validate(&all)?; + let directories = all + .iter() + .map(|a| resolved(&a.directory)) + .collect::>>()?; + for (i, directory) in directories.iter().enumerate() { + if directories[..i] + .iter() + .any(|other| directory.starts_with(other) || other.starts_with(directory)) + { + return Err("native model directories overlap through filesystem aliases".into()); + } + } + // The manifest itself must survive publication and cannot live in a generated tree. + for asset in &all { + let manifest = resolved(&asset.manifest)?; + if directories + .iter() + .any(|directory| manifest.starts_with(directory)) + { + return Err("asset manifests must be outside generated directories".into()); + } + } + Ok(()) + } + + pub async fn ensure(&self) -> Result { + let manifest = model::Manifest::load(&self.manifest).await?; + // Source acquisition uses the existing private resumable stage and lock. + asset_bundle::provision(&[AssetBundle { + manifest: self.manifest.clone(), + directory: self.source_dir.clone(), + }]) + .await?; + let primary = native_pack::primary_shard(&manifest, &self.source_dir)?; + if let Some(RuntimeProfile::Qwen4expFlashNext) = self.runtime_profile { + crate::gguf::check_flash_next_profile(&primary)?; + } + let parent = self.output.parent().ok_or("pack directory has no parent")?; + fs::create_dir_all(parent)?; + let mut name = std::ffi::OsString::from("."); + name.push(self.output.file_name().ok_or("pack filename missing")?); + name.push(".native-model-lock"); + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let lock = options.open(parent.join(name))?; + if !lock.metadata()?.is_file() { + return Err("native model lock must be a regular file".into()); + } + lock.try_lock() + .map_err(|_| "native model preparation is busy; retry when it finishes")?; + match fs::symlink_metadata(&self.output) { + Ok(_) => verify_receipt(&manifest, &self.output)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + native_pack::prepare(&manifest, &self.source_dir, &self.output).await?; + verify_receipt(&manifest, &self.output)?; + } + Err(e) => return Err(e.into()), + } + Ok(primary) + } +} + +// Resolve existing ancestors too: a new path beneath a symlink can otherwise +// appear lexically disjoint while writing inside another immutable version. +fn resolved(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(_) => Ok(fs::canonicalize(path)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let parent = path.parent().ok_or("path has no existing ancestor")?; + Ok(resolved(parent)?.join(path.file_name().ok_or("path component missing")?)) + } + Err(e) => Err(e.into()), + } +} + +#[derive(Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +struct Entry { + size: u64, + sha256: String, +} +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Receipt { + schema: u32, + converter: u32, + sources: BTreeMap, + files: BTreeMap, +} + +fn sources(manifest: &model::Manifest) -> BTreeMap { + manifest + .files + .iter() + .map(|f| { + ( + f.name.clone(), + Entry { + size: f.size, + sha256: f.sha256.to_ascii_lowercase(), + }, + ) + }) + .collect() +} +fn digest(path: &Path) -> Result { + let metadata = fs::symlink_metadata(path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("pack entries must be regular files".into()); + } + let mut file = File::open(path)?; + let mut hash = Sha256::new(); + let mut buffer = [0u8; 65536]; + let mut size = 0; + loop { + let n = file.read(&mut buffer)?; + if n == 0 { + break; + } + hash.update(&buffer[..n]); + size += n as u64; + } + Ok(Entry { + size, + sha256: hex::encode(hash.finalize()), + }) +} +fn exact_tree(output: &Path) -> Result<()> { + for (dir, expected) in [ + ( + output.to_path_buf(), + vec![ + "dense.bin", + "index.txt", + "native_experts.txt", + "conversions.json", + "source.json", + "receipt.json", + "tokenizer", + ], + ), + ( + output.join("tokenizer"), + vec![ + "vocab.json", + "merges.txt", + "token_type.json", + "tokenizer.json", + "chat_template.jinja", + ], + ), + ] { + let md = fs::symlink_metadata(&dir)?; + if !md.is_dir() || md.file_type().is_symlink() { + return Err("pack must contain real directories".into()); + } + let mut actual = fs::read_dir(&dir)? + .map(|r| r.map(|e| e.file_name())) + .collect::>>()?; + actual.sort(); + let mut expected = expected + .into_iter() + .map(std::ffi::OsString::from) + .collect::>(); + expected.sort(); + if actual != expected { + return Err("pack file set differs from receipt schema".into()); + } + } + Ok(()) +} +pub fn write_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> { + let files = FILES + .iter() + .map(|name| Ok((name.to_string(), digest(&output.join(name))?))) + .collect::>>()?; + let receipt = Receipt { + schema: 1, + converter: 1, + sources: sources(manifest), + files, + }; + use std::io::Write; + let mut file = File::create(output.join("receipt.json"))?; + file.write_all(&serde_json::to_vec_pretty(&receipt)?)?; + file.sync_all()?; + Ok(()) +} +pub fn verify_receipt(manifest: &model::Manifest, output: &Path) -> Result<()> { + exact_tree(output)?; + let path = output.join("receipt.json"); + let md = fs::symlink_metadata(&path)?; + if !md.is_file() || md.file_type().is_symlink() || md.len() > 1_048_576 { + return Err("invalid pack receipt file".into()); + } + let r: Receipt = serde_json::from_slice(&fs::read(path)?)?; + if r.schema != 1 + || r.converter != 1 + || r.sources != sources(manifest) + || r.files.len() != FILES.len() + { + return Err("native pack receipt does not match pinned sources/converter".into()); + } + for name in FILES { + if r.files.get(*name) != Some(&digest(&output.join(name))?) { + return Err("native pack checksum mismatch; use a new versioned output".into()); + } + } + Ok(()) +} diff --git a/control-plane/src/native_pack.rs b/control-plane/src/native_pack.rs new file mode 100644 index 00000000..b1d731b0 --- /dev/null +++ b/control-plane/src/native_pack.rs @@ -0,0 +1,496 @@ +//! Native GGUF serving-pack preparation. Quantized tensors remain in source +//! shards; only exact float conversions are accepted. No runtime Python. +use std::{ + collections::{BTreeMap, HashSet}, + error::Error, + fs::{self, File}, + io::Write, + path::{Path, PathBuf}, +}; + +use serde_json::json; +use sha2::{Digest, Sha256}; + +use crate::{gguf, gguf_f32_stream, kar_codec, model, tokenizer, tokenizer_assets}; + +type Result = std::result::Result>; + +struct Shard { + path: PathBuf, + index: gguf::TensorIndex, +} + +fn safe_name(name: &str) -> bool { + !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) +} + +fn align(bytes: u64) -> Result { + Ok(bytes.checked_add(63).ok_or("native pack size overflow")? / 64 * 64) +} + +fn form(name: &str) -> Option { + let name = if let Some(rest) = name.strip_prefix("blk.") { + rest.split_once('.').map_or(name, |(_, suffix)| suffix) + } else { + name + }; + match name { + "ffn_gate_inp.weight" + | "ffn_gate_inp_shexp.weight" + | "hc_attn_down.weight" + | "hc_attn_up.weight" + | "hc_attn_inject.weight" + | "hc_ffn_down.weight" + | "hc_ffn_up.weight" + | "hc_ffn_inject.weight" + | "output_hc_down.weight" + | "output_hc_up.weight" + | "indexer.k_proj.weight" + | "indexer.q_proj.weight" + | "ssm_alpha.weight" + | "ssm_beta.weight" + | "ple_key.weight" + | "ple_value.weight" => Some(30), + "ple_conv1d.weight" => Some(1), + "attn_q_norm.weight" + | "attn_k_norm.weight" + | "hc_attn_norm.weight" + | "hc_ffn_norm.weight" + | "output_hc_norm.weight" + | "indexer.q_norm.weight" + | "indexer.k_norm.weight" + | "ple_norm_conv.weight" + | "ple_norm_key.weight" + | "ple_norm_query.weight" + | "ssm_a" + | "ssm_conv1d.weight" + | "ssm_dt.bias" + | "ssm_norm.weight" => Some(0), + _ => None, + } +} + +fn float_name(kind: u32) -> &'static str { + match kind { + 0 => "F32", + 1 => "F16", + 30 => "BF16", + _ => "unsupported", + } +} + +fn expert(name: &str) -> bool { + name.starts_with("blk.") && name.ends_with("_exps.weight") +} + +fn shards(manifest: &model::Manifest, source: &Path) -> Result> { + let mut shards = Vec::new(); + let mut names = HashSet::new(); + for file in &manifest.files { + if !safe_name(&file.name) || !file.name.ends_with(".gguf") { + return Err("native pack manifest must contain GGUF shard filenames only".into()); + } + let path = source.join(&file.name); + let index = gguf::tensor_index(&path)?; + for tensor in &index.tensors { + if !safe_name(&tensor.name) || !names.insert(tensor.name.clone()) { + return Err("invalid or duplicate tensor name across GGUF shards".into()); + } + } + shards.push(Shard { path, index }); + } + if shards.is_empty() { + return Err("native pack has no source shards".into()); + } + shards.sort_by_key(|s| s.index.summary.split_no.unwrap_or(0)); + let first = &shards[0].index.summary; + if first.architecture.as_deref() != Some("qwen4exp") { + return Err("native pack preparation currently requires qwen4exp architecture".into()); + } + let count = shards.len() as u64; + let total = shards + .iter() + .try_fold(0u64, |sum, s| sum.checked_add(s.index.summary.tensors)) + .ok_or("split tensor count overflow")?; + if count == 1 && (first.split_count.unwrap_or(1) != 1 || first.split_no.unwrap_or(0) != 0) { + return Err("manifest is missing GGUF shards".into()); + } + let filename = shards[0].path.file_name().unwrap().to_str().unwrap(); + let suffix = format!("-00001-of-{count:05}.gguf"); + let prefix = if count > 1 { + Some( + filename + .strip_suffix(&suffix) + .ok_or("first shard filename does not match split count")?, + ) + } else { + None + }; + for (number, shard) in shards.iter().enumerate() { + let summary = &shard.index.summary; + if count > 1 + && (summary.split_no != Some(number as u64) + || summary.split_count != Some(count) + || summary.split_tensors_count != first.split_tensors_count) + { + return Err("inconsistent GGUF split identity".into()); + } + if summary.split_tensors_count.is_some_and(|n| n != total) { + return Err("GGUF split tensor total does not match manifest shards".into()); + } + if summary + .architecture + .as_ref() + .is_some_and(|arch| arch != "qwen4exp") + { + return Err("GGUF shard architecture mismatch".into()); + } + if let Some(prefix) = prefix { + let expected = format!("{prefix}-{:05}-of-{count:05}.gguf", number + 1); + if shard.path.file_name().unwrap() != expected.as_str() { + return Err("GGUF shard names do not form a discoverable family".into()); + } + } + } + Ok(shards) +} + +fn expert_table(shards: &[Shard]) -> Result { + let mut tensors = BTreeMap::new(); + let mut layers = 0u64; + for (shard, source) in shards.iter().enumerate() { + for tensor in &source.index.tensors { + tensors.insert(tensor.name.as_str(), (shard, tensor)); + if expert(&tensor.name) { + let mut parts = tensor.name.split('.'); + parts.next(); + let layer = parts.next().ok_or("expert layer absent")?.parse::()?; + if layer > 1023 { + return Err("unreasonable expert layer count".into()); + } + layers = layers.max(layer + 1); + if !["gate", "up", "down"] + .iter() + .any(|r| tensor.name == format!("blk.{layer}.ffn_{r}_exps.weight")) + { + return Err("unsupported expert role".into()); + } + } + } + } + if layers == 0 { + return Err("native pack requires expert tensors".into()); + } + let (_, router) = tensors + .get("blk.0.ffn_gate_inp.weight") + .ok_or("missing expert router")?; + if router.dimensions.len() != 2 { + return Err("router must have two dimensions".into()); + } + let experts = router.dimensions[1]; + let mut offset = 0u64; + let mut lines = Vec::new(); + let mut split_roles = false; + for layer in 0..layers { + let router_name = format!("blk.{layer}.ffn_gate_inp.weight"); + let (_, router) = tensors + .get(router_name.as_str()) + .ok_or("missing layer router")?; + if router.dimensions.len() != 2 || router.dimensions[1] != experts { + return Err("routers disagree on expert count".into()); + } + let mut roles = Vec::new(); + for role in ["gate", "up", "down"] { + let name = format!("blk.{layer}.ffn_{role}_exps.weight"); + let (shard, tensor) = *tensors.get(name.as_str()).ok_or("missing expert role")?; + if tensor.dimensions.len() != 3 + || tensor.dimensions[2] != experts + || !tensor.bytes.is_multiple_of(experts) + { + return Err("invalid expert shape".into()); + } + roles.push((shard, tensor)); + } + let gate = roles[0].1; + let up = roles[1].1; + let down = roles[2].1; + if gate.kind != up.kind + || gate.dimensions != up.dimensions + || gate.dimensions[0] != down.dimensions[1] + || gate.dimensions[1] != down.dimensions[0] + || router.dimensions[0] != gate.dimensions[0] + { + return Err("expert gate/up/down geometry mismatch".into()); + } + let blob = gate + .bytes + .checked_add(up.bytes) + .and_then(|n| n.checked_add(down.bytes)) + .ok_or("expert byte count overflow")? + / experts; + let absolute = roles + .iter() + .map(|(s, t)| shards[*s].index.summary.data_start + t.offset) + .collect::>(); + let filenames = roles + .iter() + .map(|(s, _)| { + if *s == 0 { + String::new() + } else { + shards[*s] + .path + .file_name() + .unwrap() + .to_str() + .unwrap() + .to_owned() + } + }) + .collect::>(); + let same = filenames.iter().all(|f| f == &filenames[0]); + split_roles |= !same; + let column = if same { + filenames[0].clone() + } else { + filenames.join(",") + }; + let column = if column.is_empty() { + column + } else { + format!(" {column}") + }; + lines.push(format!( + "{layer} {} {} {offset} {blob} {} {} {}{column}\n", + gate.kind, down.kind, absolute[0], absolute[1], absolute[2] + )); + offset = blob + .checked_mul(experts) + .and_then(|n| offset.checked_add(n)) + .ok_or("expert arena overflow")?; + } + let name = shards[0].path.file_name().unwrap().to_str().unwrap(); + let header = if split_roles { + format!( + "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it - per role where the column is gate,up,down)\n" + ) + } else { + format!( + "# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert {experts}, total {offset}; absolute offsets in {name}, or in the named shard beside it)\n" + ) + }; + Ok(header + &lines.concat()) +} + +fn dense_files(shards: &[Shard], output: &Path) -> Result<()> { + let mut dense = File::create(output.join("dense.bin"))?; + let mut at = 0u64; + let mut pool = 0u64; + let mut rows = Vec::new(); + let mut conversions = Vec::new(); + for shard in shards { + let mut input = File::open(&shard.path)?; + for tensor in &shard.index.tensors { + if expert(&tensor.name) || tensor.name == "per_layer_token_embd.weight" { + continue; + } + if tensor.dimensions.len() > 2 { + return Err("dense pack index accepts at most two dimensions".into()); + } + let ne0 = tensor.dimensions[0]; + let ne1 = tensor.dimensions.get(1).copied().unwrap_or(0); + let float = matches!(tensor.kind, 0 | 1 | 30); + let required = form(&tensor.name); + let native = !float + && (required.is_none() + || (tensor.name == "blk.1.ple_key.weight" && matches!(tensor.kind, 8 | 42))); + if native { + rows.push(format!( + "{} 0 0 0 0 {pool} 0 {ne0} {ne1} 8 0 32 0 0 0 0 0 0 0\n", + tensor.name + )); + continue; + } + if !float { + return Err("quantized projection requires unsupported lossy conversion".into()); + } + let target = required.unwrap_or(tensor.kind); + if target != tensor.kind + && !matches!((tensor.kind, target), (0, 30) | (0, 1) | (1 | 30, 0)) + { + return Err("unsupported native pack float conversion".into()); + } + let mut written = 0u64; + let mut digest = Sha256::new(); + gguf_f32_stream::visit( + &mut input, + shard.index.summary.data_start + tensor.offset, + tensor.kind, + tensor.bytes, + |raw, values| { + digest.update(raw); + let mut converted = Vec::new(); + let bytes = if target == tensor.kind { + raw + } else { + for bits in values.as_chunks::<4>().0 { + let value = f32::from_le_bytes(*bits); + if !value.is_finite() { + return Err("non-finite conversion refused".into()); + } + match target { + 30 => { + if value.to_bits() & 0xffff != 0 { + return Err("lossy F32 to BF16 conversion refused".into()); + } + converted.extend_from_slice( + &((value.to_bits() >> 16) as u16).to_le_bytes(), + ); + } + 1 => { + let half = kar_codec::f32_to_f16_bits(value); + if kar_codec::f16_bits_to_f32(half).to_bits() != value.to_bits() + { + return Err("lossy F32 to F16 conversion refused".into()); + } + // Index kind3 stores F32; the existing loader narrows it. + converted.extend_from_slice(bits); + } + 0 => converted.extend_from_slice(bits), + _ => unreachable!(), + } + } + &converted + }; + dense.write_all(bytes).map_err(|e| e.to_string())?; + written += bytes.len() as u64; + Ok(()) + }, + )?; + let kind = if target == 1 && tensor.kind == 0 { + 3 + } else { + match target { + 0 => 2, + 1 => 5, + 30 => 4, + _ => unreachable!(), + } + }; + let dst = if kind == 3 { written / 2 } else { written }; + rows.push(format!( + "{} 0 {kind} {at} {written} {pool} {dst} {ne0} {ne1} 0 0 1 0 0 0 0 0 0 0\n", + tensor.name + )); + let padded = align(written)?; + dense.write_all(&[0u8; 64][..(padded - written) as usize])?; + at = at.checked_add(padded).ok_or("dense file offset overflow")?; + pool = pool.checked_add(align(dst)?).ok_or("dense pool overflow")?; + if target != tensor.kind { + conversions.push(json!({"name":tensor.name, "shard":shard.path.file_name().unwrap().to_str().unwrap(), + "src_type":float_name(tensor.kind), "dst_type":float_name(target), "exact":true, + "max_abs_err":0.0, "source_sha256":hex::encode(digest.finalize())})); + } + } + } + dense.sync_all()?; + let source = shards[0].path.file_name().unwrap().to_str().unwrap(); + let text = format!( + "# strata pack index v3 -- generated by strata-next (native experts) from {source}\n# align 64 pool {pool} tensors {}\n{}", + rows.len(), + rows.concat() + ); + write(output.join("index.txt"), text.as_bytes())?; + write( + output.join("conversions.json"), + &serde_json::to_vec_pretty( + &json!({"schema":1,"tool":"strata-next","compat_bf16":false,"tensors":conversions}), + )?, + )?; + Ok(()) +} + +fn write(path: PathBuf, bytes: &[u8]) -> Result<()> { + let mut file = File::create(path)?; + file.write_all(bytes)?; + file.sync_all()?; + Ok(()) +} + +pub async fn prepare( + manifest: &model::Manifest, + source: &Path, + output: &Path, +) -> Result { + if output.exists() || output.is_symlink() { + return Err("native pack output already exists; choose a new versioned directory".into()); + } + model::verify(manifest, source).await?; + let shards = shards(manifest, source)?; + let experts = expert_table(&shards)?; + // Validate tokenizer before writing any pack files. + tokenizer_assets_preflight(&shards[0].path)?; + let parent = output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + let name = output + .file_name() + .ok_or("native pack output has no filename")?; + let mut stage_name = std::ffi::OsString::from("."); + stage_name.push(name); + stage_name.push(format!(".native-pack-{}.tmp", std::process::id())); + let stage = parent.join(stage_name); + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&stage)?; + let result = (|| -> Result<()> { + dense_files(&shards, &stage)?; + let tokenizer_dir = tokenizer_assets::extract(&shards[0].path, &stage)?; + tokenizer::Tokenizer::from_assets(&tokenizer_dir)?; + write(stage.join("native_experts.txt"), experts.as_bytes())?; + let sources = manifest + .files + .iter() + .map(|f| json!({"name":f.name,"size":f.size,"sha256":f.sha256})) + .collect::>(); + write( + stage.join("source.json"), + &serde_json::to_vec_pretty( + &json!({"schema":1,"kind":"native-gguf","source_shards":sources,"lossy_conversions":false}), + )?, + )?; + crate::native_model::write_receipt(manifest, &stage)?; + File::open(&stage)?.sync_all()?; + if output.exists() || output.is_symlink() { + return Err("native pack destination appeared during preparation".into()); + } + crate::immutable_directory::publish(&stage, output)?; + File::open(parent)?.sync_all()?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_dir_all(&stage); + } + result?; + Ok( + json!({"prepared":true,"format":"native-gguf","source_shards":shards.len(),"lossy_conversions":false,"gpu_validated":false}), + ) +} + +pub fn primary_shard(manifest: &model::Manifest, source: &Path) -> Result { + Ok(shards(manifest, source)?[0].path.clone()) +} + +fn tokenizer_assets_preflight(source: &Path) -> Result<()> { + gguf::tokenizer_metadata(source)?; + Ok(()) +} diff --git a/control-plane/src/preflight.rs b/control-plane/src/preflight.rs new file mode 100644 index 00000000..16838c91 --- /dev/null +++ b/control-plane/src/preflight.rs @@ -0,0 +1,99 @@ +//! Read-only deployment validation; never spawn a worker or acquire a listener. +use std::{env, ffi::OsStr, path::Path}; + +use crate::{config::Config, embedded_engine, tokenizer::Tokenizer}; + +pub fn check(path: Option<&Path>) -> Result { + // Parser errors may contain user-supplied values. Keep diagnostics to stages + // so a malformed config/tokenizer cannot echo credentials into deployment logs. + let config = Config::load_with_path(path) + .map_err(|_| "configuration or API key validation failed; check config fields, environment overrides and key-file permissions")?; + let engine = match &config.worker { + None => "unconfigured", + Some(worker) if worker.executable == OsStr::new("@embedded") => { + if !cfg!(target_os = "linux") { + return Err("embedded execution requires Linux"); + } + if embedded_engine::info()["embedded"] != true { + return Err("this executable has no embedded engine"); + } + "embedded" + } + Some(worker) => { + if !executable_available(&worker.executable) { + return Err( + "engine executable is not an accessible executable file; check its path or PATH", + ); + } + "external" + } + }; + let tokenizer_pending = + config.native_model.is_some() && config.tokenizer_dir.as_ref().is_some_and(|p| !p.exists()); + if let Some(path) = &config.tokenizer_dir + && !tokenizer_pending + { + Tokenizer::from_assets(path).map_err(|_| "tokenizer asset validation failed")?; + } + Ok(serde_json::json!({ + "schema_version": 1, + "configuration_valid": true, + "platform": std::env::consts::OS, + "bind": config.bind.to_string(), + "max_in_flight_requests": config.max_in_flight_requests, + "queue_timeout_s": config.queue_timeout.map(|duration| duration.as_secs()), + "shutdown_grace_s": config.shutdown_grace.as_secs(), + "generation_timeout_s": config.worker.as_ref().and_then(|worker| worker.generation_timeout.map(|duration| duration.as_secs())), + "model": config.model, + "authentication_enabled": config.api_key.is_some(), + "response_history": if config.response_history_dir.is_some() { "durable_unchecked" } else { "memory" }, + "engine": engine, + "tokenizer_validated": config.tokenizer_dir.is_some() && !tokenizer_pending, + "native_model_configured":config.native_model.is_some(), + "native_runtime_profile":config.native_model.as_ref().and_then(|native| native.runtime_profile), + "native_runtime_profile_checked":false, + "mtp_pack": if config.mtp_pack.is_some() { "pinned_structural_check_pending" } else { "unconfigured" }, + "native_model_verified":false, + "inference_configured": config.worker.is_some() && config.tokenizer_dir.is_some() && !tokenizer_pending, + "readiness_checked": false, + "asset_bundles_configured": config.assets.len(), + "assets_verified": false, + "gpu_requirement": config.gpu_requirement, + "gpu_requirement_checked": false, + "cuda_memory": config.cuda_memory, + "cuda_memory_checked": false, + "engine_probe_configured": config.engine_probe, + "engine_probe_checked": false, + })) +} + +fn executable_available(executable: &OsStr) -> bool { + let path = Path::new(executable); + if executable.as_encoded_bytes().contains(&b'/') { + return executable_file(path); + } + // A missing PATH is deliberately not guessed. An explicit path is portable. + env::var_os("PATH").is_some_and(|paths| { + env::split_paths(&paths).any(|directory| executable_file(&directory.join(path))) + }) +} + +fn executable_file(path: &Path) -> bool { + if !path.is_file() { + return false; + } + #[cfg(unix)] + { + use std::{ffi::CString, os::unix::ffi::OsStrExt}; + let Ok(path) = CString::new(path.as_os_str().as_bytes()) else { + return false; + }; + // SAFETY: valid NUL-terminated path, no retained pointers. This is a + // point-in-time access check, not an execution or dependency probe. + unsafe { libc::access(path.as_ptr(), libc::X_OK) == 0 } + } + #[cfg(not(unix))] + { + false + } +} diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs new file mode 100644 index 00000000..a2c44974 --- /dev/null +++ b/control-plane/src/prepare_preview.rs @@ -0,0 +1,2209 @@ +//! Small, explicitly lossy F32 GGUF-to-KAR integration path. It exercises the +//! native acquisition/index/codec/writer chain without claiming target-model +//! support or a quality-approved serving configuration. + +use std::{ + fs::{self, File}, + io::{BufWriter, Read, Seek, SeekFrom, Write}, + path::{Path, PathBuf}, +}; + +use sha2::{Digest, Sha256}; + +use crate::{ + derived_iq3, derived_mixed, gguf, gguf_f32_stream, iq3_s, kar, kar_codec, kar_sample, + kar_stream_encode, kar_writer, + model::{self, Manifest}, + stream_parts, +}; + +const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; +const MAX_TENSORS: usize = 1000; +const MAX_TENSOR_ELEMENTS: u64 = 1_000_000; + +pub(crate) fn minimum_part_payload_bytes(derived_bytes: u64, levels: u8) -> Result { + if !derived_bytes.is_multiple_of(4) || !(1..=8).contains(&levels) { + return Err("invalid KAR part F32 byte count or level".into()); + } + let plane_bytes = (derived_bytes / 4) + .div_ceil(32) + .checked_mul(4 * u64::from(levels)) + .ok_or("KAR minimum payload size overflow")?; + Ok(plane_bytes.min(derived_bytes)) +} + +#[derive(Clone, Copy)] +enum PreviewKind { + F32, + Iq3, + Mixed, +} + +enum DerivedIdentity { + Iq3(derived_iq3::Identity), + Mixed(derived_mixed::Identity), +} + +struct DerivedTensorRef<'a> { + name: &'a str, + source_kind: u32, + source_digest: &'a [u8; 32], + f32_digest: &'a [u8; 32], + offset: u64, + bytes: u64, +} + +impl DerivedIdentity { + fn gguf_digest(&self) -> [u8; 32] { + match self { + Self::Iq3(identity) => identity.gguf_sha256, + Self::Mixed(identity) => identity.gguf_sha256, + } + } + + fn derived_digest(&self) -> [u8; 32] { + match self { + Self::Iq3(identity) => identity.derived_sha256, + Self::Mixed(identity) => identity.derived_sha256, + } + } + + fn derived_bytes(&self) -> u64 { + match self { + Self::Iq3(identity) => identity.derived_bytes, + Self::Mixed(identity) => identity.derived_bytes, + } + } + + fn tensor(&self, number: usize) -> DerivedTensorRef<'_> { + match self { + Self::Iq3(identity) => { + let tensor = &identity.tensors[number]; + DerivedTensorRef { + name: &tensor.name, + source_kind: 21, + source_digest: &tensor.iq3_sha256, + f32_digest: &tensor.f32_sha256, + offset: tensor.derived_offset, + bytes: tensor.derived_bytes, + } + } + Self::Mixed(identity) => { + let tensor = &identity.tensors[number]; + DerivedTensorRef { + name: &tensor.name, + source_kind: tensor.source_kind, + source_digest: &tensor.source_sha256, + f32_digest: &tensor.f32_sha256, + offset: tensor.derived_offset, + bytes: tensor.derived_bytes, + } + } + } + } + + fn tensor_count(&self) -> usize { + match self { + Self::Iq3(identity) => identity.tensors.len(), + Self::Mixed(identity) => identity.tensors.len(), + } + } +} + +#[derive(Debug)] +pub struct PreviewSummary { + pub archive: kar::Summary, + pub archive_digest: [u8; 32], + pub maximum_relative_l2: f64, + pub tensor_distortions: Vec, + pub provenance_path: Option, +} + +#[derive(Debug)] +pub struct TensorDistortion { + pub name: String, + pub relative_l2: f64, + pub source_kind: u32, + pub section_bytes: u64, +} + +struct PreparedTensor { + name: String, + dims: Vec, + source_digest: [u8; 32], + source_offset: u64, + section_path: PathBuf, + section_bytes: u64, + section_digest: [u8; 32], +} + +struct StreamedTensor { + prepared: PreparedTensor, + nested: bool, +} + +struct StagingDir(PathBuf); + +impl Drop for StagingDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +pub fn prepare_f32( + source_path: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare(source_path, destination, levels, PreviewKind::F32) +} + +pub fn prepare_iq3( + source_path: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare(source_path, destination, levels, PreviewKind::Iq3) +} + +pub fn prepare_mixed( + source_path: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare(source_path, destination, levels, PreviewKind::Mixed) +} + +pub fn prepare_sharded( + manifest: &Manifest, + source_dir: &Path, + destination: &Path, + levels: u8, +) -> Result { + if !(1..=8).contains(&levels) { + return Err("sharded preview requires 1..=8 KAR levels".into()); + } + let total_source_bytes = manifest + .files + .iter() + .try_fold(0u64, |sum, file| sum.checked_add(file.size)) + .ok_or("sharded GGUF source byte count overflow")?; + if total_source_bytes > MAX_SOURCE_BYTES { + return Err("sharded preview exceeds its 64 MiB source limit".into()); + } + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + if identity.tensors.is_empty() || identity.tensors.len() > MAX_TENSORS { + return Err("sharded preview exceeds its tensor-count limit".into()); + } + let staging_path = destination.with_file_name(format!( + "{}.parts-{}", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy(), + std::process::id() + )); + fs::create_dir(&staging_path).map_err(|error| error.to_string())?; + let staging = StagingDir(staging_path); + let mut architecture = None::; + let mut maximum_relative_l2 = 0.0f64; + let mut prepared = Vec::with_capacity(identity.tensors.len()); + let mut number = 0usize; + for shard in &identity.shards { + let path = source_dir.join(&shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if let Some(shard_architecture) = index.summary.architecture.as_deref() { + if architecture + .as_deref() + .is_some_and(|expected| expected != shard_architecture) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| shard_architecture.to_owned()); + } + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes + { + return Err("GGUF shard changed after identity derivation".into()); + } + let mut source = File::open(&path).map_err(|error| error.to_string())?; + for tensor in &index.tensors { + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR preview supports up to four dimensions", + tensor.name + )); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if elements > MAX_TENSOR_ELEMENTS { + return Err("sharded preview exceeds its per-tensor element limit".into()); + } + let derived = &identity.tensors[number]; + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + source + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let mut raw = vec![0u8; tensor.bytes as usize]; + source + .read_exact(&mut raw) + .map_err(|error| error.to_string())?; + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(&raw).as_slice() != derived.source_sha256 + || derived.derived_bytes != elements * 4 + { + return Err(format!( + "{}: sharded source tensor identity mismatch", + tensor.name + )); + } + let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; + let mut f32_digest = Sha256::new(); + for value in &weights { + f32_digest.update(value.to_le_bytes()); + } + if f32_digest.finalize().as_slice() != derived.f32_sha256 { + return Err(format!( + "{}: sharded derived F32 tensor mismatch", + tensor.name + )); + } + let section_path = staging.0.join(format!("{number:06}.section")); + let (coded, relative_l2) = encode_preview_tensor( + &tensor.name, + &tensor.dimensions, + &weights, + derived.f32_sha256, + derived.derived_offset, + §ion_path, + levels, + )?; + maximum_relative_l2 = maximum_relative_l2.max(relative_l2); + prepared.push(coded); + number += 1; + } + if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes + || hash_file(&path)? != shard.gguf_sha256 + { + return Err(format!( + "{}: GGUF shard changed during preparation", + shard.name + )); + } + } + let tensors = prepared + .iter() + .map(|tensor| kar_writer::Tensor { + name: &tensor.name, + dims: &tensor.dims, + source_dtype: 0, + source_digest: tensor.source_digest, + source_offset: tensor.source_offset, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + levels, + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + digest: tensor.section_digest, + }, + }) + .collect::>(); + let builder = + format!("strata-next/experimental-sharded-derived-f32-topdown-v1:g32:l{levels}:sample-all"); + let source = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v1", + architecture: architecture + .as_deref() + .ok_or("GGUF shards have no architecture")?, + builder: &builder, + digest: identity.derived_sha256, + total_elements: identity.derived_bytes / 4, + bytes: identity.derived_bytes, + }; + let archive = kar_writer::write_archive(destination, &source, &tensors)?; + let archive_digest = hash_file(destination)?; + let provenance_path = provenance_path(destination)?; + if let Err(error) = write_provenance( + &provenance_path, + &sharded_provenance_value(&identity, archive_digest), + ) { + let _ = fs::remove_file(destination); + return Err(error); + } + Ok(PreviewSummary { + archive, + archive_digest, + maximum_relative_l2, + tensor_distortions: Vec::new(), + provenance_path: Some(provenance_path), + }) +} + +/// Experimental full-size preparation. Tensor payloads are decoded, sampled, +/// and encoded in bounded chunks; each source shard is pinned by the manifest. +/// This path does not grant a model-quality or serving approval. +pub fn prepare_sharded_streamed( + manifest: &Manifest, + source_dir: &Path, + destination: &Path, + levels: u8, +) -> Result { + prepare_sharded_streamed_with_limit( + manifest, + source_dir, + destination, + levels, + stream_parts::MAX_PART_ELEMENTS, + ) +} + +pub fn prepare_sharded_streamed_ple( + manifest: &Manifest, + source_dir: &Path, + destination: &Path, + levels: u8, + ple_part_elements: u64, +) -> Result { + stream_parts::validate_ple_limit(ple_part_elements)?; + prepare_sharded_streamed_with_policy( + manifest, + source_dir, + destination, + levels, + stream_parts::MAX_PART_ELEMENTS, + Some(ple_part_elements), + ) +} + +fn prepare_sharded_streamed_with_limit( + manifest: &Manifest, + source_dir: &Path, + destination: &Path, + levels: u8, + max_part_elements: u64, +) -> Result { + prepare_sharded_streamed_with_policy( + manifest, + source_dir, + destination, + levels, + max_part_elements, + None, + ) +} + +fn prepare_sharded_streamed_with_policy( + manifest: &Manifest, + source_dir: &Path, + destination: &Path, + levels: u8, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result { + if !(1..=8).contains(&levels) { + return Err("streamed sharded preparation requires 1..=8 KAR levels".into()); + } + if fs::symlink_metadata(destination).is_ok() + || fs::symlink_metadata(provenance_path(destination)?).is_ok() + { + return Err("KAR archive or provenance destination already exists".into()); + } + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + let archive_parts = if let Some(limit) = ple_part_elements { + stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? + } else { + stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? + }; + let archive_tensor_count = archive_parts.iter().map(Vec::len).sum::(); + if archive_tensor_count == 0 || archive_tensor_count > 100_000 { + return Err("streamed sharded tensor count exceeds KAR-2 limits".into()); + } + // Every nested part stores at least `levels` four-byte plane words per + // 32 values; a RAW fallback stores four bytes per value. The smaller of + // these is a safe lower bound before section files are created. Passing + // this gate does not guarantee enough space for scales and metadata. + let minimum_payload_bytes = archive_parts + .iter() + .flat_map(|parts| parts.iter()) + .try_fold(0u64, |sum, part| { + sum.checked_add(minimum_part_payload_bytes(part.derived_bytes, levels)?) + .ok_or_else(|| "KAR minimum payload size overflow".to_string()) + })?; + let destination_parent = destination + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + model::require_space(destination_parent, minimum_payload_bytes) + .map_err(|error| format!("KAR minimum payload does not fit: {error}"))?; + let staging_path = destination.with_file_name(format!( + "{}.stream-parts-{}", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy(), + std::process::id() + )); + fs::create_dir(&staging_path).map_err(|error| error.to_string())?; + let staging = StagingDir(staging_path); + let mut architecture = None::; + let mut prepared = Vec::with_capacity(archive_tensor_count); + let mut maximum_relative_l2 = 0.0f64; + let mut tensor_distortions = Vec::with_capacity(archive_tensor_count); + let mut number = 0usize; + for shard in &identity.shards { + let path = source_dir.join(&shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if let Some(shard_architecture) = index.summary.architecture.as_deref() { + if architecture + .as_deref() + .is_some_and(|expected| expected != shard_architecture) + { + return Err("GGUF shard architectures differ".into()); + } + architecture.get_or_insert_with(|| shard_architecture.to_owned()); + } + if index.tensors.len() != shard.tensor_count || index.summary.file_size != shard.gguf_bytes + { + return Err("GGUF shard changed after identity derivation".into()); + } + let mut source = File::open(&path).map_err(|error| error.to_string())?; + for tensor in &index.tensors { + if tensor.dimensions.len() > 4 { + return Err(format!( + "{}: KAR-2 supports up to four dimensions", + tensor.name + )); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |count, dim| count.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + let derived = &identity.tensors[number]; + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || derived.derived_bytes + != elements + .checked_mul(4) + .ok_or("F32 tensor byte count overflow")? + { + return Err(format!("{}: sharded tensor identity mismatch", tensor.name)); + } + let absolute_base = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + for part in &archive_parts[number] { + let absolute = absolute_base + .checked_add(part.source_byte_offset) + .ok_or("GGUF part offset overflow")?; + let sample = kar_sample::sample_normalized( + &mut source, + absolute, + part.source_kind, + part.source_bytes, + part.derived_bytes / 4, + part.source_sha256, + kar_sample::MAX_SAMPLE_VALUES, + )?; + let calibration = kar_codec::fit_topdown(&sample, levels).ok(); + let section_path = staging.0.join(format!("{:06}.section", prepared.len())); + let (section_bytes, section_digest, nested, relative_l2) = + if let Some(calibration) = calibration { + let result = kar_stream_encode::encode_section( + &mut source, + absolute, + part.source_kind, + part.source_bytes, + part.derived_bytes / 4, + &calibration, + §ion_path, + )?; + if result.source_digest != part.source_sha256 + || result.derived_digest != part.f32_sha256 + { + return Err(format!( + "{}: streamed source or F32 digest mismatch", + part.name + )); + } + (result.bytes, result.digest, true, result.relative_l2) + } else { + let result = spool_raw_f32( + &mut source, + absolute, + part.source_kind, + part.source_bytes, + §ion_path, + )?; + if result.0 != part.source_sha256 + || result.1 != part.f32_sha256 + || result.2 != part.derived_bytes + { + return Err(format!( + "{}: streamed RAW source or F32 digest mismatch", + part.name + )); + } + (result.2, result.1, false, 0.0) + }; + maximum_relative_l2 = maximum_relative_l2.max(relative_l2); + tensor_distortions.push(TensorDistortion { + name: part.name.clone(), + relative_l2, + source_kind: part.source_kind, + section_bytes, + }); + prepared.push(StreamedTensor { + prepared: PreparedTensor { + name: part.name.clone(), + dims: part.dimensions.clone(), + source_digest: part.f32_sha256, + source_offset: part.derived_offset, + section_path, + section_bytes, + section_digest, + }, + nested, + }); + } + number += 1; + } + if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes + || hash_file(&path)? != shard.gguf_sha256 + { + return Err(format!( + "{}: GGUF shard changed during preparation", + shard.name + )); + } + } + let tensors = prepared + .iter() + .map(|entry| { + let tensor = &entry.prepared; + kar_writer::Tensor { + name: &tensor.name, + dims: &tensor.dims, + source_dtype: 0, + source_digest: tensor.source_digest, + source_offset: tensor.source_offset, + data: if entry.nested { + kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + levels, + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + digest: tensor.section_digest, + } + } else { + kar_writer::TensorData::RawFile { + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + } + }, + } + }) + .collect::>(); + let builder = if let Some(limit) = ple_part_elements { + format!( + "strata-next/experimental-sharded-stream-v5:g32:l{levels}:sample65536:plepart{limit}" + ) + } else { + format!("strata-next/experimental-sharded-stream-v4:g32:l{levels}:sample65536") + }; + let source_identity = kar_writer::SourceIdentity { + name: "gguf-shards#derived-f32-le-v4", + architecture: architecture + .as_deref() + .ok_or("GGUF shards have no architecture")?, + builder: &builder, + digest: identity.derived_sha256, + total_elements: identity.derived_bytes / 4, + bytes: identity.derived_bytes, + }; + let archive = + kar_writer::write_archive_consuming_files(destination, &source_identity, &tensors)?; + let archive_digest = hash_file(destination)?; + let provenance_path = provenance_path(destination)?; + let mut provenance = sharded_provenance_value(&identity, archive_digest); + provenance["schema"] = serde_json::json!(if ple_part_elements.is_some() { + "strata-next/sharded-stream-provenance-v5" + } else { + "strata-next/sharded-stream-provenance-v4" + }); + provenance["derivation"] = + serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); + provenance["levels"] = serde_json::json!(levels); + provenance["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); + provenance["partitioned_tensors"] = partitioned_provenance(&archive_parts); + if let Some(limit) = ple_part_elements { + provenance["ple_part_elements"] = serde_json::json!(limit); + } + if let Err(error) = write_provenance(&provenance_path, &provenance) { + let _ = fs::remove_file(destination); + return Err(error); + } + Ok(PreviewSummary { + archive, + archive_digest, + maximum_relative_l2, + tensor_distortions, + provenance_path: Some(provenance_path), + }) +} + +fn spool_raw_f32( + reader: &mut R, + absolute: u64, + source_kind: u32, + source_bytes: u64, + path: &Path, +) -> Result<([u8; 32], [u8; 32], u64), String> { + let file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| error.to_string())?; + let result = (|| { + let mut writer = BufWriter::new(file); + let mut source_hash = Sha256::new(); + let mut derived_hash = Sha256::new(); + let bytes = gguf_f32_stream::visit( + reader, + absolute, + source_kind, + source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + derived_hash.update(f32_bytes); + writer + .write_all(f32_bytes) + .map_err(|error| error.to_string()) + }, + )?; + writer.flush().map_err(|error| error.to_string())?; + writer + .get_ref() + .sync_all() + .map_err(|error| error.to_string())?; + Ok(( + source_hash.finalize().into(), + derived_hash.finalize().into(), + bytes, + )) + })(); + if result.is_err() { + let _ = fs::remove_file(path); + } + result +} + +fn prepare( + source_path: &Path, + destination: &Path, + levels: u8, + kind: PreviewKind, +) -> Result { + if !(1..=8).contains(&levels) { + return Err("F32 preview requires 1..=8 KAR levels".into()); + } + let index = gguf::tensor_index(source_path).map_err(|error| error.to_string())?; + if index.summary.file_size > MAX_SOURCE_BYTES + || index.tensors.is_empty() + || index.tensors.len() > MAX_TENSORS + { + return Err("F32 preview exceeds its source or tensor-count limit".into()); + } + let architecture = index + .summary + .architecture + .as_deref() + .ok_or("GGUF source has no architecture")?; + let filename = source_path + .file_name() + .ok_or("GGUF source has no file name")? + .to_string_lossy(); + let derived_identity = match kind { + PreviewKind::F32 => None, + PreviewKind::Iq3 => Some(DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?)), + PreviewKind::Mixed => Some(DerivedIdentity::Mixed(derived_mixed::fingerprint( + source_path, + )?)), + }; + let source_name = match kind { + PreviewKind::F32 => filename.to_string(), + PreviewKind::Iq3 => format!("{filename}#derived-f32-le-v1"), + PreviewKind::Mixed => format!("{filename}#mixed-derived-f32-le-v1"), + }; + let original_digest = match &derived_identity { + Some(identity) => identity.gguf_digest(), + None => hash_file(source_path)?, + }; + let staging_name = format!( + "{}.parts-{}", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy(), + std::process::id() + ); + let staging_path = destination.with_file_name(staging_name); + fs::create_dir(&staging_path).map_err(|error| error.to_string())?; + let staging = StagingDir(staging_path); + let mut source_file = File::open(source_path).map_err(|error| error.to_string())?; + let mut total_elements = 0u64; + let mut maximum_relative_l2 = 0.0f64; + let mut prepared = Vec::with_capacity(index.tensors.len()); + for (number, tensor) in index.tensors.iter().enumerate() { + let supported = match kind { + PreviewKind::F32 => tensor.kind == 0, + PreviewKind::Iq3 => tensor.kind == 21, + PreviewKind::Mixed => matches!(tensor.kind, 0 | 1 | 21 | 30), + }; + if !supported || tensor.dimensions.len() > 4 { + return Err(format!( + "{}: preview supports only {} tensors with up to four dimensions", + tensor.name, + match kind { + PreviewKind::F32 => "F32", + PreviewKind::Iq3 => "IQ3_S", + PreviewKind::Mixed => "F32/F16/BF16/IQ3_S", + } + )); + } + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |product, dim| product.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + total_elements = total_elements + .checked_add(elements) + .ok_or("GGUF model element count overflow")?; + if elements > MAX_TENSOR_ELEMENTS { + return Err("F32 preview exceeds its per-tensor element limit".into()); + } + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("GGUF tensor offset overflow")?; + source_file + .seek(SeekFrom::Start(absolute)) + .map_err(|error| error.to_string())?; + let mut raw = vec![0u8; tensor.bytes as usize]; + source_file + .read_exact(&mut raw) + .map_err(|error| error.to_string())?; + let (weights, tensor_digest, source_offset) = if let Some(identity) = &derived_identity { + let derived = identity.tensor(number); + if derived.name != tensor.name + || derived.source_kind != tensor.kind + || Sha256::digest(&raw).as_slice() != derived.source_digest + { + return Err("GGUF tensor differs from derived source identity".into()); + } + let weights = decode_source_tensor(tensor.kind, &raw, elements as usize)?; + let mut digest = Sha256::new(); + for value in &weights { + digest.update(value.to_le_bytes()); + } + if digest.finalize().as_slice() != derived.f32_digest || derived.bytes != elements * 4 { + return Err("decoded F32 tensor differs from derived source identity".into()); + } + (weights, *derived.f32_digest, derived.offset) + } else { + let digest = Sha256::digest(&raw).into(); + let weights = raw + .as_chunks::<4>() + .0 + .iter() + .map(|chunk| f32::from_le_bytes(*chunk)) + .collect::>(); + (weights, digest, absolute) + }; + drop(raw); + let section_path = staging.0.join(format!("{number:06}.section")); + let (coded, relative_l2) = encode_preview_tensor( + &tensor.name, + &tensor.dimensions, + &weights, + tensor_digest, + source_offset, + §ion_path, + levels, + )?; + maximum_relative_l2 = maximum_relative_l2.max(relative_l2); + prepared.push(coded); + } + if source_file + .metadata() + .map_err(|error| error.to_string())? + .len() + != index.summary.file_size + || hash_file(source_path)? != original_digest + { + return Err("GGUF source changed during F32 preparation".into()); + } + let tensors = prepared + .iter() + .map(|tensor| kar_writer::Tensor { + name: &tensor.name, + dims: &tensor.dims, + source_dtype: 0, + source_digest: tensor.source_digest, + source_offset: tensor.source_offset, + data: kar_writer::TensorData::NestedFile { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + levels, + path: &tensor.section_path, + offset: 0, + bytes: tensor.section_bytes, + digest: tensor.section_digest, + }, + }) + .collect::>(); + let builder = format!( + "strata-next/experimental-{}-topdown-v1:g32:l{levels}:sample-all", + match kind { + PreviewKind::F32 => "f32", + PreviewKind::Iq3 => "iq3-derived-f32", + PreviewKind::Mixed => "mixed-derived-f32", + } + ); + let (source_digest, source_bytes) = derived_identity + .as_ref() + .map(|identity| (identity.derived_digest(), identity.derived_bytes())) + .unwrap_or((original_digest, index.summary.file_size)); + let source = kar_writer::SourceIdentity { + name: &source_name, + architecture, + builder: &builder, + digest: source_digest, + total_elements, + bytes: source_bytes, + }; + let archive = kar_writer::write_archive(destination, &source, &tensors)?; + let archive_digest = hash_file(destination)?; + let provenance_path = if let Some(identity) = derived_identity { + let path = provenance_path(destination)?; + let manifest = provenance_value(&identity, archive_digest); + if let Err(error) = write_provenance(&path, &manifest) { + let _ = fs::remove_file(destination); + return Err(error); + } + Some(path) + } else { + None + }; + Ok(PreviewSummary { + archive, + archive_digest, + maximum_relative_l2, + tensor_distortions: Vec::new(), + provenance_path, + }) +} + +fn encode_preview_tensor( + name: &str, + dimensions: &[u64], + weights: &[f32], + source_digest: [u8; 32], + source_offset: u64, + section_path: &Path, + levels: u8, +) -> Result<(PreparedTensor, f64), String> { + let normalized = kar_codec::normalize_for_calibration(weights, 32)?; + let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; + let encoded = kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?; + let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::>(); + let mut decoded = vec![0.0f32; weights.len()]; + kar_codec::decode_range( + &encoded.scales, + &calibration.books[usize::from(levels) - 1], + &plane_refs, + 32, + 0, + &mut decoded, + )?; + let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold( + (0.0f64, 0.0f64), + |(error_sum, reference_sum), (original, rebuilt)| { + let delta = f64::from(*original) - f64::from(*rebuilt); + ( + error_sum + delta * delta, + reference_sum + f64::from(*original).powi(2), + ) + }, + ); + let relative_l2 = if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }; + let books = calibration + .books + .iter() + .map(Vec::as_slice) + .collect::>(); + let coded_tensor = kar_writer::Tensor { + name, + dims: dimensions, + source_dtype: 0, + source_digest, + source_offset, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + scales: &encoded.scales, + books: &books, + planes: &plane_refs, + }, + }; + let section = kar_writer::write_nested_section(section_path, &coded_tensor)?; + Ok(( + PreparedTensor { + name: name.to_owned(), + dims: dimensions.to_vec(), + source_digest, + source_offset, + section_path: section_path.to_path_buf(), + section_bytes: section.bytes, + section_digest: section.digest, + }, + relative_l2, + )) +} + +pub fn verify_iq3(source_path: &Path, archive_path: &Path) -> Result { + verify_derived(source_path, archive_path, PreviewKind::Iq3) +} + +pub fn verify_mixed(source_path: &Path, archive_path: &Path) -> Result { + verify_derived(source_path, archive_path, PreviewKind::Mixed) +} + +pub fn verify_sharded( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, +) -> Result { + verify_sharded_inner( + manifest, + source_dir, + archive_path, + None, + stream_parts::MAX_PART_ELEMENTS, + None, + ) +} + +pub fn verify_sharded_streamed( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, +) -> Result { + if !(1..=8).contains(&levels) { + return Err("streamed sharded verification requires 1..=8 KAR levels".into()); + } + verify_sharded_inner( + manifest, + source_dir, + archive_path, + Some(levels), + stream_parts::MAX_PART_ELEMENTS, + None, + ) +} + +pub fn verify_sharded_streamed_ple( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + levels: u8, + ple_part_elements: u64, +) -> Result { + stream_parts::validate_ple_limit(ple_part_elements)?; + if !(1..=8).contains(&levels) { + return Err("streamed sharded verification requires 1..=8 KAR levels".into()); + } + verify_sharded_inner( + manifest, + source_dir, + archive_path, + Some(levels), + stream_parts::MAX_PART_ELEMENTS, + Some(ple_part_elements), + ) +} + +fn verify_sharded_inner( + manifest: &Manifest, + source_dir: &Path, + archive_path: &Path, + streamed_levels: Option, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result { + let identity = derived_mixed::fingerprint_shards(manifest, source_dir)?; + let archive_parts = if streamed_levels.is_some() { + Some(if let Some(limit) = ple_part_elements { + stream_parts::plan_shards_with_ple_limit(&identity, source_dir, limit)? + } else { + stream_parts::plan_shards_with_limit(&identity, source_dir, max_part_elements)? + }) + } else { + None + }; + let (summary, sources) = kar::verify_with_sources(archive_path)?; + let expected_count = archive_parts + .as_ref() + .map_or(identity.tensors.len(), |parts| { + parts.iter().map(Vec::len).sum() + }); + if summary.source_digest != identity.derived_sha256 + || summary.source_bytes != identity.derived_bytes + || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes) + || sources.len() != expected_count + { + return Err("KAR header differs from sharded derived source".into()); + } + if let Some(parts) = &archive_parts { + for (record, part) in sources.iter().zip(parts.iter().flatten()) { + let record_bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + if record.name != part.name + || record.dimensions != part.dimensions + || record.dtype != 0 + || record.digest != part.f32_sha256 + || record.offset != part.derived_offset + || record_bytes != part.derived_bytes + { + return Err(format!("{}: sharded KAR part source mismatch", part.name)); + } + } + } else { + for (record, tensor) in sources.iter().zip(&identity.tensors) { + let record_bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + if record.name != tensor.name + || record.dtype != 0 + || record.digest != tensor.f32_sha256 + || record.offset != tensor.derived_offset + || record_bytes != tensor.derived_bytes + { + return Err(format!( + "{}: sharded KAR tensor source mismatch", + tensor.name + )); + } + } + } + let archive_digest = hash_file(archive_path)?; + let provenance = provenance_path(archive_path)?; + let file = File::open(provenance).map_err(|error| error.to_string())?; + let recorded: serde_json::Value = + serde_json::from_reader(file).map_err(|error| error.to_string())?; + let mut expected = sharded_provenance_value(&identity, archive_digest); + if let Some(levels) = streamed_levels { + if summary.max_planes > levels { + return Err("KAR stream levels exceed declared preparation level".into()); + } + expected["schema"] = serde_json::json!(if ple_part_elements.is_some() { + "strata-next/sharded-stream-provenance-v5" + } else { + "strata-next/sharded-stream-provenance-v4" + }); + expected["derivation"] = + serde_json::json!("strata-next/gguf-shards-to-f32-le-v4:ggml-3cf03257"); + expected["levels"] = serde_json::json!(levels); + expected["sampling"] = serde_json::json!("digest-seeded-65536-normalized-v1"); + expected["partitioned_tensors"] = partitioned_provenance( + archive_parts + .as_ref() + .ok_or("missing streamed KAR part plan")?, + ); + if let Some(limit) = ple_part_elements { + expected["ple_part_elements"] = serde_json::json!(limit); + } + } + if recorded != expected { + return Err( + "sharded provenance differs from source, archive, or preparation policy".into(), + ); + } + Ok(summary) +} + +fn verify_derived( + source_path: &Path, + archive_path: &Path, + kind: PreviewKind, +) -> Result { + let identity = match kind { + PreviewKind::F32 => return Err("F32 preview does not use derived provenance".into()), + PreviewKind::Iq3 => DerivedIdentity::Iq3(derived_iq3::fingerprint(source_path)?), + PreviewKind::Mixed => DerivedIdentity::Mixed(derived_mixed::fingerprint(source_path)?), + }; + let (summary, sources) = kar::verify_with_sources(archive_path)?; + if summary.source_digest != identity.derived_digest() + || summary.source_bytes != identity.derived_bytes() + || summary.source_total_elements.checked_mul(4) != Some(identity.derived_bytes()) + || sources.len() != identity.tensor_count() + { + return Err("KAR header differs from derived F32 source identity".into()); + } + for (number, record) in sources.iter().enumerate() { + let tensor = identity.tensor(number); + let record_bytes = record + .dimensions + .iter() + .try_fold(4u64, |size, dim| size.checked_mul(*dim)) + .ok_or("KAR tensor source byte count overflow")?; + if record.name != tensor.name + || record.dtype != 0 + || &record.digest != tensor.f32_digest + || record.offset != tensor.offset + || record_bytes != tensor.bytes + { + return Err(format!( + "{}: KAR tensor source identity mismatch", + tensor.name + )); + } + } + let archive_digest = hash_file(archive_path)?; + let provenance = provenance_path(archive_path)?; + let file = File::open(provenance).map_err(|error| error.to_string())?; + let recorded: serde_json::Value = + serde_json::from_reader(file).map_err(|error| error.to_string())?; + if recorded != provenance_value(&identity, archive_digest) { + return Err("derived preview provenance differs from source or archive".into()); + } + Ok(summary) +} + +fn decode_source_tensor(kind: u32, raw: &[u8], elements: usize) -> Result, String> { + let weights = match kind { + 0 => raw + .as_chunks::<4>() + .0 + .iter() + .map(|chunk| f32::from_le_bytes(*chunk)) + .collect(), + 1 | 30 => raw + .as_chunks::<2>() + .0 + .iter() + .map(|pair| { + let bits = u16::from_le_bytes(*pair); + if kind == 1 { + kar_codec::f16_bits_to_f32(bits) + } else { + f32::from_bits(u32::from(bits) << 16) + } + }) + .collect(), + 21 => { + let mut values = vec![0.0f32; elements]; + iq3_s::decode_into(raw, &mut values)?; + values + } + _ => return Err("unsupported GGUF tensor source kind".into()), + }; + if weights.len() != elements { + return Err("decoded GGUF tensor size differs from shape".into()); + } + Ok(weights) +} + +fn provenance_path(destination: &Path) -> Result { + Ok(destination.with_file_name(format!( + "{}.provenance.json", + destination + .file_name() + .ok_or("KAR destination has no file name")? + .to_string_lossy() + ))) +} + +fn provenance_value(identity: &DerivedIdentity, archive_digest: [u8; 32]) -> serde_json::Value { + match identity { + DerivedIdentity::Iq3(identity) => serde_json::json!({ + "schema": "strata-next/iq3-preview-provenance-v1", + "derivation": "strata-next/iq3_s-to-f32-le-v1", + "original_gguf_sha256": hex::encode(identity.gguf_sha256), + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "archive_sha256": hex::encode(archive_digest), + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "iq3_sha256": hex::encode(tensor.iq3_sha256), + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }), + DerivedIdentity::Mixed(identity) => serde_json::json!({ + "schema": "strata-next/mixed-preview-provenance-v1", + "derivation": "strata-next/gguf-mixed-to-f32-le-v1", + "original_gguf_sha256": hex::encode(identity.gguf_sha256), + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "archive_sha256": hex::encode(archive_digest), + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "source_kind": tensor.source_kind, + "source_sha256": hex::encode(tensor.source_sha256), + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }), + } +} + +fn sharded_provenance_value( + identity: &derived_mixed::ShardedIdentity, + archive_digest: [u8; 32], +) -> serde_json::Value { + serde_json::json!({ + "schema": "strata-next/sharded-preview-provenance-v1", + "derivation": "strata-next/gguf-shards-to-f32-le-v1", + "derived_f32_sha256": hex::encode(identity.derived_sha256), + "derived_f32_bytes": identity.derived_bytes, + "archive_sha256": hex::encode(archive_digest), + "shards": identity.shards.iter().map(|shard| serde_json::json!({ + "name": shard.name, + "gguf_sha256": hex::encode(shard.gguf_sha256), + "gguf_bytes": shard.gguf_bytes, + "tensor_count": shard.tensor_count, + })).collect::>(), + "tensors": identity.tensors.iter().map(|tensor| serde_json::json!({ + "name": tensor.name, + "source_kind": tensor.source_kind, + "source_sha256": hex::encode(tensor.source_sha256), + "derived_offset": tensor.derived_offset, + "derived_bytes": tensor.derived_bytes, + "f32_sha256": hex::encode(tensor.f32_sha256), + })).collect::>(), + }) +} + +fn partitioned_provenance(parts: &[Vec]) -> serde_json::Value { + serde_json::json!( + parts + .iter() + .filter(|group| group.len() > 1) + .map(|group| { + serde_json::json!({ + "parent_name": group[0].parent_name, + "parent_dimensions": group[0].parent_dimensions, + "source_kind": group[0].source_kind, + "parts": group.iter().map(|part| serde_json::json!({ + "name": part.name, + "dimensions": part.dimensions, + "source_byte_offset": part.source_byte_offset, + "source_bytes": part.source_bytes, + "source_sha256": hex::encode(part.source_sha256), + "derived_offset": part.derived_offset, + "derived_bytes": part.derived_bytes, + "f32_sha256": hex::encode(part.f32_sha256), + })).collect::>(), + }) + }) + .collect::>() + ) +} + +fn write_provenance(path: &Path, value: &serde_json::Value) -> Result<(), String> { + if fs::symlink_metadata(path).is_ok() { + return Err("provenance destination already exists".into()); + } + let temporary = path.with_file_name(format!( + "{}.part", + path.file_name() + .ok_or("provenance path has no file name")? + .to_string_lossy() + )); + let result = (|| { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .map_err(|error| error.to_string())?; + serde_json::to_writer_pretty(&mut file, value).map_err(|error| error.to_string())?; + use std::io::Write; + file.write_all(b"\n").map_err(|error| error.to_string())?; + file.sync_all().map_err(|error| error.to_string())?; + fs::hard_link(&temporary, path).map_err(|error| error.to_string())?; + Ok(()) + })(); + let _ = fs::remove_file(&temporary); + result +} + +fn hash_file(path: &Path) -> Result<[u8; 32], String> { + let mut source = File::open(path).map_err(|error| error.to_string())?; + let mut digest = Sha256::new(); + let mut buffer = [0u8; 1024 * 1024]; + loop { + let count = source + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if count == 0 { + break; + } + digest.update(&buffer[..count]); + } + Ok(digest.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kar_payload_preflight_rejects_too_small_volumes_conservatively() { + assert_eq!( + minimum_part_payload_bytes(707_775_598_080, 2).unwrap(), + 44_235_974_880 + ); + assert!(minimum_part_payload_bytes(707_775_598_080, 2).unwrap() > 23 * (1 << 30)); + assert_eq!(minimum_part_payload_bytes(4, 8).unwrap(), 4); + assert!(minimum_part_payload_bytes(u64::MAX, 8).is_err()); + } + use crate::model::ModelFile; + + fn string(out: &mut Vec, value: &str) { + out.extend_from_slice(&(value.len() as u64).to_le_bytes()); + out.extend_from_slice(value.as_bytes()); + } + + fn one_shard(name: &str, kind: u32, elements: u64, payload: &[u8]) -> Vec { + one_shard_with_arch(name, kind, elements, payload, true) + } + + fn one_shard_with_arch( + name: &str, + kind: u32, + elements: u64, + payload: &[u8], + include_architecture: bool, + ) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&u64::from(include_architecture).to_le_bytes()); + if include_architecture { + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + } + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf + } + + fn ple_shard(payload: &[u8]) -> Vec { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, stream_parts::PLE_TENSOR_NAME); + gguf.extend_from_slice(&2u32.to_le_bytes()); + gguf.extend_from_slice(&32u64.to_le_bytes()); + gguf.extend_from_slice(&16u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(payload); + gguf + } + + #[test] + fn converts_two_small_f32_gguf_tensors_and_rejects_duplicate_output() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&2u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + for (name, offset) in [("first", 0u64), ("second", 128)] { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&32u64.to_le_bytes()); + gguf.extend_from_slice(&0u32.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + let data_start = gguf.len().div_ceil(32) * 32; + gguf.resize(data_start, 0); + for index in 0..64 { + let value = [-1.0f32, -0.25, 0.25, 1.0][index % 4]; + gguf.extend_from_slice(&value.to_le_bytes()); + } + let source_path = + std::env::temp_dir().join(format!("strata-preview-{}.gguf", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-preview-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&source_path, &gguf).unwrap(); + let summary = prepare_f32(&source_path, &output, 2).unwrap(); + assert_eq!(summary.archive.tensor_count, 2); + assert_eq!(summary.archive.total_elements, 64); + assert!(summary.maximum_relative_l2.is_finite()); + assert_eq!( + summary.archive.source_digest, + hash_file(&source_path).unwrap() + ); + assert_eq!(summary.archive_digest, hash_file(&output).unwrap()); + let staging = output.with_file_name(format!( + "{}.parts-{}", + output.file_name().unwrap().to_string_lossy(), + std::process::id() + )); + assert!(!staging.exists()); + assert!(prepare_f32(&source_path, &output, 2).is_err()); + assert!(!staging.exists()); + let failed_source = + std::env::temp_dir().join(format!("strata-preview-bad-{}.gguf", std::process::id())); + let failed_output = + std::env::temp_dir().join(format!("strata-preview-bad-{}.kar", std::process::id())); + let _ = fs::remove_file(&failed_output); + let mut broken = gguf.clone(); + let last = broken.len() - 4; + broken[last..].copy_from_slice(&f32::NAN.to_le_bytes()); + fs::write(&failed_source, broken).unwrap(); + assert!( + prepare_f32(&failed_source, &failed_output, 2) + .unwrap_err() + .contains("invalid KAR normalization input") + ); + assert!(!failed_output.exists()); + let failed_staging = failed_output.with_file_name(format!( + "{}.parts-{}", + failed_output.file_name().unwrap().to_string_lossy(), + std::process::id() + )); + assert!(!failed_staging.exists()); + fs::remove_file(failed_source).unwrap(); + fs::remove_file(&output).unwrap(); + fs::remove_file(&source_path).unwrap(); + } + + #[test] + fn refuses_quantized_gguf_until_source_decoder_is_available() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&256u64.to_le_bytes()); + gguf.extend_from_slice(&21u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + gguf.extend_from_slice(&[0u8; 110]); + let source_path = + std::env::temp_dir().join(format!("strata-preview-iq3-{}.gguf", std::process::id())); + let output = + std::env::temp_dir().join(format!("strata-preview-iq3-{}.kar", std::process::id())); + let _ = fs::remove_file(&output); + fs::write(&source_path, gguf).unwrap(); + assert!( + prepare_f32(&source_path, &output, 2) + .unwrap_err() + .contains("supports only F32") + ); + assert!(!output.exists()); + fs::remove_file(source_path).unwrap(); + } + + #[test] + fn prepares_iq3_preview_with_virtual_f32_source_and_provenance() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + string(&mut gguf, "expert"); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&256u64.to_le_bytes()); + gguf.extend_from_slice(&21u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + gguf.extend_from_slice(&block); + let base = + std::env::temp_dir().join(format!("strata-preview-iq3-good-{}", std::process::id())); + let source_path = base.with_extension("gguf"); + let output = base.with_extension("kar"); + let provenance = output.with_file_name(format!( + "{}.provenance.json", + output.file_name().unwrap().to_string_lossy() + )); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source_path, gguf).unwrap(); + let identity = derived_iq3::fingerprint(&source_path).unwrap(); + let result = prepare_iq3(&source_path, &output, 2).unwrap(); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!( + result.provenance_path.as_deref(), + Some(provenance.as_path()) + ); + assert_eq!(kar::verify(&output).unwrap(), result.archive); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!( + record["original_gguf_sha256"], + hex::encode(identity.gguf_sha256) + ); + assert_eq!( + record["derived_f32_sha256"], + hex::encode(identity.derived_sha256) + ); + assert_eq!(record["archive_sha256"], hex::encode(result.archive_digest)); + assert!(result.maximum_relative_l2.is_finite()); + assert_eq!(verify_iq3(&source_path, &output).unwrap(), result.archive); + let saved_provenance = fs::read(&provenance).unwrap(); + let mut changed = record.clone(); + changed["archive_sha256"] = serde_json::Value::String("00".repeat(32)); + fs::write(&provenance, serde_json::to_vec(&changed).unwrap()).unwrap(); + assert!( + verify_iq3(&source_path, &output) + .unwrap_err() + .contains("provenance differs") + ); + fs::write(&provenance, saved_provenance).unwrap(); + assert!(verify_iq3(&source_path, &output).is_ok()); + let blocked_output = base.with_file_name(format!( + "strata-preview-iq3-blocked-{}.kar", + std::process::id() + )); + let blocked_provenance = blocked_output.with_file_name(format!( + "{}.provenance.json", + blocked_output.file_name().unwrap().to_string_lossy() + )); + let _ = fs::remove_file(&blocked_output); + fs::write(&blocked_provenance, b"reserved").unwrap(); + assert!( + prepare_iq3(&source_path, &blocked_output, 2) + .unwrap_err() + .contains("provenance destination already exists") + ); + assert!(!blocked_output.exists()); + fs::remove_file(blocked_provenance).unwrap(); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source_path).unwrap(); + } + + #[test] + fn prepares_and_verifies_mixed_preview_with_each_source_kind() { + let tensors = [ + ("bf16", 30u32, 320u64, 32u64), + ("iq3", 21, 0, 256), + ("f16", 1, 256, 32), + ("f32", 0, 128, 32), + ]; + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&(tensors.len() as u64).to_le_bytes()); + gguf.extend_from_slice(&1u64.to_le_bytes()); + string(&mut gguf, "general.architecture"); + gguf.extend_from_slice(&8u32.to_le_bytes()); + string(&mut gguf, "qwen35"); + for (name, kind, offset, elements) in tensors { + string(&mut gguf, name); + gguf.extend_from_slice(&1u32.to_le_bytes()); + gguf.extend_from_slice(&elements.to_le_bytes()); + gguf.extend_from_slice(&kind.to_le_bytes()); + gguf.extend_from_slice(&offset.to_le_bytes()); + } + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + let mut payload = vec![0u8; 384]; + payload[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in payload[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + payload[74] = 0x55; + let values = [-1.0f32, -0.25, 0.25, 1.0]; + for index in 0..32 { + let value = values[index % values.len()]; + payload[128 + 4 * index..132 + 4 * index].copy_from_slice(&value.to_le_bytes()); + let f16 = kar_codec::f32_to_f16_bits(value).to_le_bytes(); + payload[256 + 2 * index..258 + 2 * index].copy_from_slice(&f16); + let bf16 = (value.to_bits() >> 16) as u16; + payload[320 + 2 * index..322 + 2 * index].copy_from_slice(&bf16.to_le_bytes()); + } + gguf.extend_from_slice(&payload); + let base = + std::env::temp_dir().join(format!("strata-preview-mixed-{}", std::process::id())); + let source_path = base.with_extension("gguf"); + let output = base.with_extension("kar"); + let provenance = provenance_path(&output).unwrap(); + let _ = fs::remove_file(&output); + let _ = fs::remove_file(&provenance); + fs::write(&source_path, gguf).unwrap(); + let identity = derived_mixed::fingerprint(&source_path).unwrap(); + let result = prepare_mixed(&source_path, &output, 2).unwrap(); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!(result.archive.tensor_count, 4); + assert_eq!(verify_mixed(&source_path, &output).unwrap(), result.archive); + assert!(verify_iq3(&source_path, &output).is_err()); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(&provenance).unwrap()).unwrap(); + assert_eq!(record["schema"], "strata-next/mixed-preview-provenance-v1"); + assert_eq!(record["tensors"][0]["source_kind"], 30); + assert!(result.maximum_relative_l2.is_finite()); + fs::remove_file(provenance).unwrap(); + fs::remove_file(output).unwrap(); + fs::remove_file(source_path).unwrap(); + } + + #[tokio::test] + async fn prepares_and_verifies_manifest_pinned_sharded_preview() { + let directory = + std::env::temp_dir().join(format!("strata-preview-shards-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let mut dense = Vec::new(); + for index in 0..32 { + dense.extend_from_slice(&[-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()); + } + let f32 = one_shard("dense", 0, 32, &dense); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + for (index, byte) in block[2..66].iter_mut().enumerate() { + *byte = (index as u8).wrapping_mul(3); + } + block[74] = 0x55; + let iq3 = one_shard_with_arch("expert", 21, 256, &block, false); + fs::write(directory.join("a-f32.gguf"), &f32).unwrap(); + fs::write(directory.join("z-iq3.gguf"), &iq3).unwrap(); + let mut manifest = Manifest { + schema_version: 1, + files: vec![ + ModelFile { + name: "z-iq3.gguf".into(), + url: "https://example.invalid/z".into(), + size: iq3.len() as u64, + sha256: hex::encode(Sha256::digest(&iq3)), + }, + ModelFile { + name: "a-f32.gguf".into(), + url: "https://example.invalid/a".into(), + size: f32.len() as u64, + sha256: hex::encode(Sha256::digest(&f32)), + }, + ], + }; + let output = directory.join("sharded.kar"); + let identity = derived_mixed::fingerprint_shards(&manifest, &directory).unwrap(); + let result = prepare_sharded(&manifest, &directory, &output, 2).unwrap(); + assert_eq!(result.archive.tensor_count, 2); + assert_eq!(result.archive.source_digest, identity.derived_sha256); + assert_eq!(result.archive.source_bytes, identity.derived_bytes); + assert_eq!( + verify_sharded(&manifest, &directory, &output).unwrap(), + result.archive + ); + assert!(matches!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + .await + .unwrap(), + crate::model_pipeline::PreviewOutcome::Reused(_) + )); + assert!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 3) + .await + .is_err() + ); + let record: serde_json::Value = + serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + record["schema"], + "strata-next/sharded-preview-provenance-v1" + ); + assert_eq!(record["shards"][0]["name"], "a-f32.gguf"); + assert_eq!(record["tensors"][1]["derived_offset"], 128); + let streamed_output = directory.join("streamed.kar"); + let streamed = + prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(); + assert_eq!(streamed.archive.source_digest, identity.derived_sha256); + assert_eq!(streamed.archive.tensor_count, 2); + let decoded = kar::decode_preview_tensor(&streamed_output, "dense", 2).unwrap(); + let reference = dense + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)) + .collect::>(); + assert_eq!(decoded.len(), reference.len()); + assert!( + decoded + .iter() + .zip(&reference) + .all(|(actual, expected)| (actual - expected).abs() < 0.1) + ); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).unwrap(), + streamed.archive + ); + let sampled = + crate::kar_quality::analyze(&manifest, &directory, &streamed_output, 2).unwrap(); + assert_eq!( + sampled.records.len(), + streamed.archive.tensor_count as usize + ); + assert!( + sampled + .records + .iter() + .all(|record| { record.sampled_elements > 0 && record.relative_l2.is_finite() }) + ); + let reused = crate::kar_quality::analyze_previously_verified( + &manifest, + &directory, + &streamed_output, + 2, + ) + .unwrap(); + assert!( + reused + .records + .iter() + .zip(&sampled.records) + .all(|(a, b)| { a.name == b.name && a.relative_l2 == b.relative_l2 }) + ); + assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 3).is_err()); + assert!(verify_sharded(&manifest, &directory, &streamed_output).is_err()); + let streamed_record: serde_json::Value = + serde_json::from_slice(&fs::read(streamed.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + streamed_record["schema"], + "strata-next/sharded-stream-provenance-v4" + ); + assert_eq!( + streamed_record["partitioned_tensors"], + serde_json::json!([]) + ); + assert_eq!(streamed_record["levels"], 2); + assert!(prepare_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); + manifest.files[0].sha256 = "00".repeat(32); + assert!(verify_sharded(&manifest, &directory, &output).is_err()); + assert!(verify_sharded_streamed(&manifest, &directory, &streamed_output, 2).is_err()); + manifest.files[0].sha256 = hex::encode(Sha256::digest(&iq3)); + let mut corrupted = fs::read(&output).unwrap(); + let last = corrupted.len() - 1; + corrupted[last] ^= 1; + fs::write(&output, corrupted).unwrap(); + assert!( + crate::model_pipeline::ensure_sharded_preview(&manifest, &directory, &output, 2) + .await + .is_err() + ); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn streamed_preparation_keeps_unsplittable_tensors_exact() { + let directory = + std::env::temp_dir().join(format!("strata-stream-raw-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let mut files = Vec::new(); + for (name, kind, elements, payload) in [ + ("a", 21, 256, vec![0u8; iq3_s::BLOCK_BYTES]), + ("b", 20, 32, vec![0u8; 18]), + ] { + let bytes = one_shard_with_arch(name, kind, elements, &payload, name == "a"); + let filename = format!("{name}.gguf"); + fs::write(directory.join(&filename), &bytes).unwrap(); + files.push(ModelFile { + name: filename, + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + }); + } + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("raw.kar"); + let result = prepare_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(); + assert_eq!(result.archive.max_planes, 0); + assert_eq!(result.maximum_relative_l2, 0.0); + let sampled = crate::kar_quality::analyze(&manifest, &directory, &archive, 2).unwrap(); + assert_eq!(sampled.records.len(), 2); + assert!( + sampled + .records + .iter() + .all(|record| record.relative_l2 == 0.0) + ); + let reused = + crate::kar_quality::analyze_previously_verified(&manifest, &directory, &archive, 2) + .unwrap(); + assert!( + reused + .records + .iter() + .all(|record| record.relative_l2 == 0.0) + ); + assert_eq!( + verify_sharded_streamed(&manifest, &directory, &archive, 2).unwrap(), + result.archive + ); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn selected_overlay_reconstructs_source_and_cleans_staging() { + let directory = std::env::temp_dir().join(format!("strata-overlay-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .collect::>(); + let dense = values + .iter() + .flat_map(|value| value.to_le_bytes()) + .collect::>(); + let files = [ + ("a.gguf", one_shard("dense", 0, 256, &dense)), + ( + "b.gguf", + one_shard_with_arch("extra", 21, 256, &[0u8; iq3_s::BLOCK_BYTES], false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let base = directory.join("base.kar"); + let prepared = prepare_sharded_streamed(&manifest, &directory, &base, 2).unwrap(); + let policy = directory.join("candidates.json"); + fs::write( + &policy, + serde_json::to_vec(&serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": hex::encode(prepared.archive_digest), + "proposed_levels": 3, + "records": [{"name": "dense", "elements": 256}], + })) + .unwrap(), + ) + .unwrap(); + let overlay = directory.join("overlay.kar"); + let result = + crate::kar_overlay::prepare(&manifest, &directory, &base, &policy, &overlay).unwrap(); + assert_eq!(result.record_count, 1); + assert_eq!(kar::verify(&overlay).unwrap().max_planes, 3); + assert!(result.maximum_relative_l2.is_finite()); + let decoded = kar::decode_preview_tensor(&overlay, "dense", 3).unwrap(); + let error_sum = decoded + .iter() + .zip(&values) + .map(|(actual, expected)| f64::from(actual - expected).powi(2)) + .sum::(); + let reference_sum = values + .iter() + .map(|value| f64::from(*value).powi(2)) + .sum::(); + assert!(((error_sum / reference_sum).sqrt() - result.maximum_relative_l2).abs() < 1e-7); + assert!(result.provenance_path.exists()); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &base, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 1); + assert_eq!(comparison.records[0].name, "dense"); + let selection = crate::kar_overlay::resolve_verified(&base, &overlay).unwrap(); + assert_eq!(selection.replacement_count, 1); + assert_eq!(selection.records.len(), 2); + assert_eq!(selection.records[0].name, "dense"); + assert_eq!(selection.records[0].archive, "overlay"); + assert_eq!(selection.records[1].archive, "base"); + let mut provenance: serde_json::Value = + serde_json::from_slice(&fs::read(&result.provenance_path).unwrap()).unwrap(); + provenance["records"][0]["f32_sha256"] = serde_json::json!("00".repeat(32)); + fs::write( + &result.provenance_path, + serde_json::to_vec(&provenance).unwrap(), + ) + .unwrap(); + assert!(crate::kar_overlay::resolve_verified(&base, &overlay).is_err()); + assert!( + (comparison.records[0].overlay_relative_l2 - result.maximum_relative_l2).abs() < 1e-7 + ); + assert!( + !directory + .join(format!( + "overlay.kar.overlay-sections-{}", + std::process::id() + )) + .exists() + ); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn streamed_sharded_archive_roundtrips_partitioned_tensor_records() { + let directory = + std::env::temp_dir().join(format!("strata-stream-split-{}", std::process::id())); + let _ = fs::remove_dir_all(&directory); + fs::create_dir(&directory).unwrap(); + let dense = (0..512) + .flat_map(|index| [-1.0f32, -0.25, 0.25, 1.0][index % 4].to_le_bytes()) + .collect::>(); + let dense_shard = one_shard("dense", 0, 512, &dense); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let iq3_shard = one_shard_with_arch("expert", 21, 256, &block, false); + let files = [("a-dense.gguf", dense_shard), ("z-iq3.gguf", iq3_shard)] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("split.kar"); + let result = + prepare_sharded_streamed_with_limit(&manifest, &directory, &archive, 2, 256).unwrap(); + assert_eq!(result.archive.tensor_count, 3); + assert_eq!(result.tensor_distortions.len(), 3); + assert_eq!( + result.maximum_relative_l2, + result + .tensor_distortions + .iter() + .map(|entry| entry.relative_l2) + .fold(0.0f64, f64::max) + ); + assert!( + result + .tensor_distortions + .iter() + .all(|entry| entry.section_bytes > 0 && entry.relative_l2.is_finite()) + ); + assert_eq!( + verify_sharded_inner(&manifest, &directory, &archive, Some(2), 256, None).unwrap(), + result.archive + ); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + let provenance: serde_json::Value = + serde_json::from_slice(&fs::read(result.provenance_path.unwrap()).unwrap()).unwrap(); + let parts = provenance["partitioned_tensors"][0]["parts"] + .as_array() + .unwrap(); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0]["dimensions"], serde_json::json!([256])); + assert_eq!(parts[1]["derived_offset"], 1024); + for (number, part) in parts.iter().enumerate() { + let name = part["name"].as_str().unwrap(); + let decoded = kar::decode_preview_tensor(&archive, name, 2).unwrap(); + assert_eq!(decoded.len(), 256); + for (actual, original) in decoded.iter().zip( + dense[number * 1024..(number + 1) * 1024] + .as_chunks::<4>() + .0 + .iter() + .map(|word| f32::from_le_bytes(*word)), + ) { + assert!((actual - original).abs() < 0.1); + } + } + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn ple_partition_policy_is_versioned_and_verified() { + let directory = std::env::temp_dir().join(format!( + "strata-ple-parts-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir(&directory).unwrap(); + let ple_values = (0..512) + .flat_map(|index| ((index as f32 - 255.5) / 256.0).to_le_bytes()) + .collect::>(); + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + let dense_values = (0..256) + .map(|index| (index as f32 - 127.5) / 128.0) + .flat_map(f32::to_le_bytes) + .collect::>(); + let files = [ + ("a-ple.gguf", ple_shard(&ple_values)), + ( + "m-dense.gguf", + one_shard_with_arch("dense", 0, 256, &dense_values, false), + ), + ( + "z-expert.gguf", + one_shard_with_arch("expert", 21, 256, &block, false), + ), + ] + .into_iter() + .map(|(name, bytes)| { + fs::write(directory.join(name), &bytes).unwrap(); + ModelFile { + name: name.into(), + url: "https://example.invalid/source".into(), + size: bytes.len() as u64, + sha256: hex::encode(Sha256::digest(&bytes)), + } + }) + .collect(); + let manifest = Manifest { + schema_version: 1, + files, + }; + let archive = directory.join("ple.kar"); + let prepared = + prepare_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(); + assert_eq!(prepared.archive.tensor_count, 6); + assert_eq!( + verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 128).unwrap(), + prepared.archive + ); + assert!(verify_sharded_streamed(&manifest, &directory, &archive, 2).is_err()); + assert!(verify_sharded_streamed_ple(&manifest, &directory, &archive, 2, 256).is_err()); + let provenance: serde_json::Value = + serde_json::from_slice(&fs::read(prepared.provenance_path.unwrap()).unwrap()).unwrap(); + assert_eq!( + provenance["schema"], + "strata-next/sharded-stream-provenance-v5" + ); + assert_eq!(provenance["ple_part_elements"], 128); + assert_eq!( + provenance["partitioned_tensors"][0]["parts"] + .as_array() + .unwrap() + .len(), + 4 + ); + let policy = directory.join("candidates.json"); + fs::write( + &policy, + serde_json::to_vec(&serde_json::json!({ + "schema": "strata-next/proposed-kar-precision-candidates-v1", + "source_archive_sha256": hex::encode(prepared.archive_digest), + "proposed_levels": 3, + "records": [ + {"name": "dense", "elements": 256}, + {"name": "per_layer_token_embd.weight#strata-part-001-of-004", "elements": 128} + ], + })) + .unwrap(), + ) + .unwrap(); + let overlay = directory.join("overlay.kar"); + crate::kar_overlay::prepare(&manifest, &directory, &archive, &policy, &overlay).unwrap(); + let selection = crate::kar_overlay::resolve_verified(&archive, &overlay).unwrap(); + assert_eq!(selection.replacement_count, 2); + assert_eq!(selection.records.len(), 6); + let memory = crate::kar_memory::plan_selected(&archive, &overlay, 2, 3, 1 << 20).unwrap(); + assert_eq!(memory.record_count, 6); + assert_eq!(memory.replacement_count, 2); + assert!(memory.selected_overlay_compressed_bytes > 0); + assert_eq!( + memory + .largest_records + .iter() + .filter(|record| record.archive == "overlay") + .count(), + 2 + ); + assert_eq!( + memory.selected_compressed_bytes, + memory.selected_base_compressed_bytes + memory.selected_overlay_compressed_bytes + ); + let comparison = + crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).unwrap(); + assert_eq!(comparison.records.len(), 2); + assert_eq!(comparison.records[1].elements, 128); + let sidecar = archive.with_file_name("ple.kar.provenance.json"); + let mut corrupted: serde_json::Value = + serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap(); + corrupted["partitioned_tensors"][0]["parts"][0]["source_byte_offset"] = 4.into(); + fs::write(&sidecar, serde_json::to_vec(&corrupted).unwrap()).unwrap(); + assert!(crate::kar_overlay::compare(&manifest, &directory, &archive, &overlay).is_err()); + fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/control-plane/src/prompt.rs b/control-plane/src/prompt.rs new file mode 100644 index 00000000..a7f1e02f --- /dev/null +++ b/control-plane/src/prompt.rs @@ -0,0 +1,288 @@ +//! Supported text subset of the pinned Strata Qwen chat template. +//! The no-tool path and a representative tool continuation are byte-for-byte +//! checked against upstream golden cases. Tool definitions are adapted from +//! Responses function objects. +use serde_json::Value; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + System, + Developer, + User, + Assistant, +} + +#[derive(Clone, Copy, Debug)] +pub struct Message<'a> { + pub role: Role, + pub content: &'a str, + pub reasoning: Option<&'a str>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Effort { + None, + Low, + Medium, + High, + #[default] + XHigh, +} + +const XHIGH: &str = "Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer."; +const LOW: &str = "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration."; + +pub fn render(messages: &[Message<'_>], effort: Effort) -> Result { + render_with_tools(messages, effort, &[]) +} + +pub fn render_with_tools( + messages: &[Message<'_>], + effort: Effort, + tools: &[Value], +) -> Result { + if messages.is_empty() { + return Err("prompt needs a message"); + } + let first_non_system = messages + .iter() + .position(|message| !matches!(message.role, Role::System | Role::Developer)) + .unwrap_or(messages.len()); + if first_non_system == messages.len() + || messages[first_non_system..] + .iter() + .any(|message| matches!(message.role, Role::System | Role::Developer)) + { + return Err("system and developer messages must be at the beginning"); + } + if messages + .last() + .is_none_or(|message| message.role != Role::User) + { + return Err("generation needs a final user message"); + } + + let system = messages[..first_non_system] + .iter() + .map(|message| message.content.trim()) + .filter(|content| !content.is_empty()) + .collect::>() + .join("\n"); + let instruction = match effort { + Effort::None | Effort::Medium => "", + Effort::Low => LOW, + Effort::High | Effort::XHigh => XHIGH, + }; + let mut prompt = String::new(); + if !instruction.is_empty() || !system.is_empty() || !tools.is_empty() { + prompt.push_str("<|im_start|>system\n"); + prompt.push_str(instruction); + if !tools.is_empty() { + if !instruction.is_empty() { + prompt.push_str("\n\n"); + } + prompt.push_str("# Tools\n\nYou have access to the following functions:\n\n"); + for tool in tools { + let name = tool + .get("name") + .and_then(Value::as_str) + .ok_or("tool needs a name")?; + prompt.push('\n'); + prompt.push_str("{\"type\": \"function\", \"function\": {\"name\": "); + prompt.push_str(&serde_json::to_string(name).expect("string JSON")); + if let Some(description) = tool.get("description").and_then(Value::as_str) { + prompt.push_str(", \"description\": "); + prompt.push_str(&serde_json::to_string(description).expect("string JSON")); + } + if let Some(parameters) = tool.get("parameters") { + prompt.push_str(", \"parameters\": "); + write_template_json(parameters, &mut prompt); + } + if let Some(strict) = tool.get("strict") { + prompt.push_str(", \"strict\": "); + write_template_json(strict, &mut prompt); + } + prompt.push_str("}}"); + } + prompt.push_str("\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n"); + } + if !system.is_empty() && (!instruction.is_empty() || !tools.is_empty()) { + prompt.push_str("\n\n"); + } + prompt.push_str(&system); + prompt.push_str("<|im_end|>\n"); + } + for message in &messages[first_non_system..] { + match message.role { + Role::User => { + prompt.push_str("<|im_start|>user\n"); + prompt.push_str(message.content.trim()); + prompt.push_str("<|im_end|>\n"); + } + Role::Assistant => { + prompt.push_str("<|im_start|>assistant\n\n"); + prompt.push_str(message.reasoning.unwrap_or("").trim()); + prompt.push_str("\n\n\n"); + prompt.push_str(message.content.trim()); + prompt.push_str("<|im_end|>\n"); + } + Role::System | Role::Developer => unreachable!(), + } + } + prompt.push_str("<|im_start|>assistant\n\n"); + if effort == Effort::None { + prompt.push_str("\n\n\n"); + } + Ok(prompt) +} + +fn write_template_json(value: &Value, output: &mut String) { + match value { + Value::Object(fields) => { + let mut keys = fields.keys().collect::>(); + if fields.contains_key("type") { + let priority = |key: &str| match key { + "type" => 0, + "properties" => 1, + "required" => 2, + "items" => 3, + "enum" => 4, + "description" => 5, + "additionalProperties" => 6, + _ => 7, + }; + keys.sort_by_key(|key| (priority(key), key.as_str())); + } + output.push('{'); + for (index, key) in keys.into_iter().enumerate() { + if index > 0 { + output.push_str(", "); + } + output.push_str(&serde_json::to_string(key).expect("object key JSON")); + output.push_str(": "); + write_template_json(&fields[key], output); + } + output.push('}'); + } + Value::Array(items) => { + output.push('['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + output.push_str(", "); + } + write_template_json(item, output); + } + output.push(']'); + } + _ => output.push_str(&value.to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + + #[test] + fn text_prompt_matches_upstream_golden_bytes() { + let golden: Vec = + serde_json::from_str(include_str!("../../engine/strata/serve/chat_golden.json")) + .unwrap(); + for name in [ + "single user", + "system + user", + "multi-turn", + "assistant with thinking", + "unicode content", + "empty user", + "whitespace and newlines", + "thinking disabled", + ] { + let case = golden.iter().find(|case| case["name"] == name).unwrap(); + let messages = case["messages"] + .as_array() + .unwrap() + .iter() + .map(|message| Message { + role: match message["role"].as_str().unwrap() { + "system" => Role::System, + "developer" => Role::Developer, + "user" => Role::User, + "assistant" => Role::Assistant, + role => panic!("unsupported role: {role}"), + }, + content: message["content"].as_str().unwrap(), + reasoning: message["reasoning_content"].as_str(), + }) + .collect::>(); + let effort = if name == "thinking disabled" { + Effort::None + } else { + Effort::XHigh + }; + assert_eq!( + render(&messages, effort).unwrap(), + case["rendered"], + "{name}" + ); + } + } + + #[test] + fn representative_tool_prompt_matches_upstream_golden_bytes() { + let golden: Vec = + serde_json::from_str(include_str!("../../engine/strata/serve/chat_golden.json")) + .unwrap(); + let case = golden + .iter() + .find(|case| case["name"] == "tool call and response") + .unwrap(); + let function = &case["tools"][0]["function"]; + let tools = [json!({ + "type":"function", "name":function["name"], "description":function["description"], + "parameters":function["parameters"] + })]; + let messages = [ + Message { + role: Role::User, + content: "Weather in Oslo?", + reasoning: None, + }, + Message { + role: Role::Assistant, + content: "\n\n\nOslo\n\n\n", + reasoning: None, + }, + Message { + role: Role::User, + content: "\n{\"temp\": 3}\n", + reasoning: None, + }, + Message { + role: Role::User, + content: "And in Bergen?", + reasoning: None, + }, + ]; + assert_eq!( + render_with_tools(&messages, Effort::XHigh, &tools).unwrap(), + case["rendered"] + ); + } + + #[test] + fn rejects_unrepresentable_message_order() { + let system = Message { + role: Role::System, + content: "rules", + reasoning: None, + }; + let user = Message { + role: Role::User, + content: "question", + reasoning: None, + }; + assert!(render(&[user, system], Effort::XHigh).is_err()); + assert!(render(&[system], Effort::XHigh).is_err()); + } +} diff --git a/control-plane/src/queue.rs b/control-plane/src/queue.rs new file mode 100644 index 00000000..f00c0776 --- /dev/null +++ b/control-plane/src/queue.rs @@ -0,0 +1,181 @@ +//! Optional queue deadline. Claim and expiration have one atomic winner. +use crate::worker::GenerationCommand; +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; +use std::time::Duration; +use tokio::{ + sync::{mpsc, oneshot}, + time::{Instant, timeout_at}, +}; + +const QUEUED: u8 = 0; +const CLAIMED: u8 = 1; +const EXPIRED: u8 = 2; + +pub struct Ticket { + deadline: Instant, + state: Arc, + started: oneshot::Sender<()>, +} +impl Ticket { + pub(crate) fn claim(self) -> bool { + if self + .state + .compare_exchange(QUEUED, CLAIMED, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return false; + } + // Check after the CAS: a thread may have been preempted across the + // deadline before claiming. The requester waits for acknowledgment + // after losing its expiry CAS, so a late claimant can still refuse. + if Instant::now() >= self.deadline { + self.state.store(EXPIRED, Ordering::Release); + return false; + } + // A requester that disappeared before acknowledgment must not start work. + self.started.send(()).is_ok() + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Error { + Expired, + Closed, +} + +pub async fn enqueue( + sender: &mpsc::Sender, + mut command: GenerationCommand, + budget: Option, +) -> Result<(), Error> { + let Some(budget) = budget else { + return sender.send(command).await.map_err(|_| Error::Closed); + }; + let deadline = Instant::now() + budget; + let state = Arc::new(AtomicU8::new(QUEUED)); + let (started, mut received) = oneshot::channel(); + command.queue = Some(Ticket { + deadline, + state: state.clone(), + started, + }); + match timeout_at(deadline, sender.send(command)).await { + Err(_) => return Err(Error::Expired), + Ok(Err(_)) => return Err(Error::Closed), + Ok(Ok(())) => (), + } + let acknowledged = tokio::select! { + biased; + result = &mut received => result, + _ = tokio::time::sleep_until(deadline) => { + if state.compare_exchange(QUEUED, EXPIRED, Ordering::AcqRel, Ordering::Acquire).is_ok() { + return Err(Error::Expired); + } + // The worker won the claim race. Its synchronous acknowledgment or + // channel closure resolves this wait; the queue clock no longer applies. + received.await + } + }; + acknowledged.map_err(|_| { + if state.load(Ordering::Acquire) == EXPIRED { + Error::Expired + } else { + Error::Closed + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{wire::Generate, worker::GenerationResult}; + fn command() -> ( + GenerationCommand, + oneshot::Receiver, String>>, + ) { + let (result, received) = oneshot::channel(); + ( + GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![65], + max_new: 1, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result), + }, + received, + ) + } + + #[tokio::test] + async fn full_channel_and_unclaimed_jobs_expire_without_claim() { + let (sender, mut pending) = mpsc::channel(1); + let (first, _first_result) = command(); + sender.send(first).await.unwrap(); + let (second, _second_result) = command(); + assert_eq!( + enqueue(&sender, second, Some(Duration::from_millis(10))).await, + Err(Error::Expired) + ); + drop(pending.recv().await.unwrap()); + assert!( + pending.try_recv().is_err(), + "channel-timeout job was never queued" + ); + let (third, _third_result) = command(); + assert_eq!( + enqueue(&sender, third, Some(Duration::from_millis(10))).await, + Err(Error::Expired) + ); + assert!(!pending.recv().await.unwrap().queue.unwrap().claim()); + } + + #[tokio::test] + async fn claim_removes_queue_deadline_and_closed_queue_is_distinct() { + let (sender, mut pending) = mpsc::channel(1); + let (job, _result) = command(); + let submit = + tokio::spawn(async move { enqueue(&sender, job, Some(Duration::from_secs(1))).await }); + let mut job = pending.recv().await.unwrap(); + assert!(job.queue.take().unwrap().claim()); + assert_eq!(submit.await.unwrap(), Ok(())); + // A claimed job has no remaining ticket/timer attached to execution. + assert!(job.queue.is_none()); + let (sender, pending) = mpsc::channel(1); + drop(pending); + let (job, _result) = command(); + assert_eq!( + enqueue(&sender, job, Some(Duration::from_secs(1))).await, + Err(Error::Closed) + ); + } + + #[test] + fn worker_claim_rejects_late_expired_and_abandoned_tickets() { + for (deadline, initial, abandoned) in [ + (Instant::now() - Duration::from_secs(1), QUEUED, false), + (Instant::now() + Duration::from_secs(10), EXPIRED, false), + (Instant::now() + Duration::from_secs(10), QUEUED, true), + ] { + let (started, received) = oneshot::channel(); + let state = Arc::new(AtomicU8::new(initial)); + if abandoned { + drop(received); + } + assert!( + !Ticket { + deadline, + state, + started + } + .claim() + ); + } + } +} diff --git a/control-plane/src/response_tools.rs b/control-plane/src/response_tools.rs new file mode 100644 index 00000000..ed630adb --- /dev/null +++ b/control-plane/src/response_tools.rs @@ -0,0 +1,329 @@ +//! Reversible namespace lowering for Qwen's flat function template. +use std::collections::HashMap; + +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +pub struct Catalog { + pub flat: Vec, + identities: HashMap, bool)>, + grammars: HashMap, + grammar_bytes: usize, +} + +pub fn alias(name: &str, namespace: Option<&str>) -> Result { + fn valid(value: &str) -> bool { + !value.is_empty() + && value.len() <= 64 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + } + if !valid(name) || namespace.is_some_and(|value| !valid(value)) { + return Err( + "tool and namespace names require 1..64 ASCII letters, digits, hyphens or underscores", + ); + } + Ok(match namespace { + None => name.to_owned(), + Some(namespace) => format!( + "ns_{}", + hex::encode(Sha256::digest(format!("{namespace}/{name}")))[..24].to_owned() + ), + }) +} + +impl Catalog { + pub fn new(tools: &[Value]) -> Result { + let mut catalog = Self { + flat: Vec::new(), + identities: HashMap::new(), + grammars: HashMap::new(), + grammar_bytes: 0, + }; + let mut namespaces = std::collections::HashSet::new(); + for tool in tools { + if tool["type"] == "namespace" { + let namespace = tool["name"].as_str().ok_or("namespace needs a name")?; + alias(namespace, None)?; + if !namespaces.insert(namespace) { + return Err("duplicate namespace"); + } + let children = tool["tools"].as_array().ok_or("namespace needs tools")?; + for child in children { + catalog.add(child, Some(namespace))?; + } + } else { + catalog.add(tool, None)?; + } + } + Ok(catalog) + } + + fn add(&mut self, tool: &Value, namespace: Option<&str>) -> Result<(), &'static str> { + let custom = tool["type"] == "custom"; + if tool["type"] != "function" && !custom { + return Err("only function or custom text tools and namespaces are supported"); + } + let mut grammar = None; + if custom { + let fields = tool.as_object().ok_or("custom tool must be an object")?; + if fields + .keys() + .any(|key| !matches!(key.as_str(), "type" | "name" | "description" | "format")) + { + return Err("unsupported custom tool field"); + } + if tool + .get("description") + .is_some_and(|value| !value.is_string()) + { + return Err("custom tool description must be text"); + } + if let Some(format) = tool.get("format") + && format != &json!({"type":"text"}) + { + let fields = format.as_object().ok_or("invalid custom tool format")?; + if fields.len() != 3 || format["type"] != "grammar" || format["syntax"] != "regex" { + return Err( + "custom tools support text or validated regex format; Lark is not implemented", + ); + } + let definition = format["definition"] + .as_str() + .ok_or("regex definition must be text")?; + if self.grammars.len() >= 32 + || self.grammar_bytes.saturating_add(definition.len()) > 64 * 1024 + { + return Err("request exceeds 32 regex tools or 64 KiB of regex definitions"); + } + grammar = Some((definition, compile_regex(definition)?)); + } + } + let name = tool["name"].as_str().ok_or("function needs a name")?; + let alias = alias(name, namespace)?; + if self + .identities + .insert( + alias.clone(), + (name.to_owned(), namespace.map(str::to_owned), custom), + ) + .is_some() + { + return Err("duplicate tool identity or alias collision"); + } + let mut flat = tool.clone(); + if custom { + flat = json!({"type":"function", "name":name, + "description":tool["description"].as_str().unwrap_or(""), + "parameters":{"type":"object","properties":{"input":{"type":"string"}}, + "required":["input"],"additionalProperties":false}}); + if let Some((definition, compiled)) = grammar { + flat["parameters"]["properties"]["input"]["description"] = json!(format!( + "The complete input must match this Rust regex exactly: {}", + serde_json::to_string(definition).expect("string serialization") + )); + self.grammar_bytes += definition.len(); + self.grammars.insert(alias.clone(), compiled); + } + } + flat["name"] = Value::String(alias); + if let Some(namespace) = namespace { + flat["description"] = Value::String(format!( + "{namespace}.{name}\n{}", + tool["description"].as_str().unwrap_or("") + )); + } + self.flat.push(flat); + Ok(()) + } + + pub fn restore(&self, item: &mut Value) -> Result<(), String> { + let name = item["name"].as_str().ok_or("tool item needs a name")?; + let grammar = self.grammars.get(name); + let (name, namespace, custom) = self + .identities + .get(name) + .ok_or("undeclared tool identity")?; + item["name"] = Value::String(name.clone()); + if let Some(namespace) = namespace { + item["namespace"] = Value::String(namespace.clone()); + } + if *custom { + let arguments = item["arguments"] + .as_str() + .ok_or("tool item needs arguments")?; + let input = custom_input(arguments, item["status"] == "in_progress")?; + if item["status"] != "in_progress" + && grammar.is_some_and(|regex| !regex.is_match(&input)) + { + return Err("custom tool input does not match its regex grammar".into()); + } + item.as_object_mut() + .ok_or("tool item must be an object")? + .remove("arguments"); + item["type"] = json!("custom_tool_call"); + item["input"] = json!(input); + } + Ok(()) + } + + pub fn is_custom(&self, name: &str) -> bool { + self.identities + .get(name) + .is_some_and(|(_, _, custom)| *custom) + } +} + +fn compile_regex(definition: &str) -> Result { + use regex_syntax::ast::{Ast, Flag, Flags, FlagsItemKind}; + if definition.is_empty() || definition.len() > 8192 || definition.contains(['\n', '\r']) { + return Err("regex definition requires 1..8192 bytes on one line"); + } + let ast = regex_syntax::ast::parse::ParserBuilder::new() + .nest_limit(64) + .build() + .parse(definition) + .map_err(|_| "invalid or unsupported regex grammar")?; + fn flags_supported(flags: &Flags) -> bool { + !flags.items.iter().any(|item| { + matches!( + item.kind, + FlagsItemKind::Flag(Flag::IgnoreWhitespace | Flag::SwapGreed) + ) + }) + } + let mut pending = vec![&ast]; + while let Some(node) = pending.pop() { + match node { + Ast::Flags(flags) if !flags_supported(&flags.flags) => { + return Err("regex verbose and swap-greed flags are unsupported"); + } + Ast::Group(group) => { + if group.flags().is_some_and(|flags| !flags_supported(flags)) { + return Err("regex verbose and swap-greed flags are unsupported"); + } + pending.push(&group.ast); + } + Ast::Repetition(repetition) => { + if !repetition.greedy { + return Err("lazy regex repetition is unsupported"); + } + pending.push(&repetition.ast); + } + Ast::Concat(concat) => pending.extend(&concat.asts), + Ast::Alternation(alternation) => pending.extend(&alternation.asts), + _ => {} + } + } + regex::RegexBuilder::new(&format!(r"\A(?:{definition})\z")) + .nest_limit(66) + .size_limit(1024 * 1024) + .dfa_size_limit(1024 * 1024) + .build() + .map_err(|_| "invalid regex grammar or compiled regex exceeds 1 MiB") +} + +fn custom_input(arguments: &str, pending: bool) -> Result { + if pending && arguments.is_empty() { + return Ok(String::new()); + } + let parsed: Value = + serde_json::from_str(arguments).map_err(|_| "invalid custom tool input envelope")?; + if parsed.as_object().is_none_or(|object| object.len() != 1) { + return Err("custom tool requires exactly one string input".into()); + } + parsed["input"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| "custom tool requires string input".into()) +} + +/// Public stream event names depend on the declared tool kind. +pub fn input_events(custom: bool) -> (&'static str, &'static str) { + if custom { + ( + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done", + ) + } else { + ( + "response.function_call_arguments.delta", + "response.function_call_arguments.done", + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tool(name: &str, definition: &str) -> Value { + json!({"type":"custom","name":name,"format":{"type":"grammar","syntax":"regex","definition":definition}}) + } + + #[test] + fn regex_whole_input_validation_preserves_unicode_and_namespaces() { + let catalog = Catalog::new(&[ + json!({"type":"namespace","name":"code","tools":[tool("run", r"(?s)\n Привіт 🌍\n")]}), + ]) + .unwrap(); + assert!( + catalog.flat[0]["parameters"]["properties"]["input"]["description"] + .as_str() + .unwrap() + .contains("Rust regex") + ); + for (input, valid) in [ + ("\n Привіт 🌍\n", true), + ("Привіт 🌍", false), + ("\n Привіт 🌍\nextra", false), + ] { + let mut item = json!({"name":alias("run",Some("code")).unwrap(),"status":"completed","arguments":json!({"input":input}).to_string()}); + assert_eq!(catalog.restore(&mut item).is_ok(), valid); + if valid { + assert_eq!(item["input"], input); + assert_eq!(item["namespace"], "code"); + assert_eq!(item["name"], "run"); + } + } + let accepts_empty = compile_regex("a*").unwrap(); + assert!(accepts_empty.is_match("")); + assert!(!compile_regex("a+").unwrap().is_match("")); + let alternation = compile_regex("a|ab").unwrap(); + assert!(alternation.is_match("ab")); + assert!(!alternation.is_match("abc")); + } + + #[test] + fn regex_dialect_and_resource_limits_fail_closed() { + for bad in [ + "", + "[", + "(?=a)", + r"(a)\1", + "a*?", + "a+?", + "a??", + "a{2}?", + "(?x:a)", + "(?U)a", + "a\nb", + r"a{10000000}", + ] { + assert!(compile_regex(bad).is_err(), "accepted {bad}"); + } + assert!(compile_regex(&"a".repeat(8193)).is_err()); + assert!(compile_regex(r"[\*\+\?]+").is_ok()); // Literal punctuation isn't a lazy modifier. + let many: Vec<_> = (0..33).map(|n| tool(&format!("t{n}"), "a")).collect(); + assert!(Catalog::new(&many[..32]).is_ok()); + assert!(Catalog::new(&many).is_err()); + let large: Vec<_> = (0..9) + .map(|n| tool(&format!("t{n}"), &"a".repeat(8192))) + .collect(); + assert!(Catalog::new(&large).is_err()); + let mut extra = tool("run", "a"); + extra["format"]["ignored"] = json!(true); + assert!(Catalog::new(&[extra]).is_err()); + } +} diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs new file mode 100644 index 00000000..4f488a07 --- /dev/null +++ b/control-plane/src/responses.rs @@ -0,0 +1,5170 @@ +use axum::{ + Json, + extract::{Path, Query, RawQuery, State, rejection::JsonRejection}, + http::StatusCode, + response::{ + IntoResponse, Response, + sse::{Event as SseEvent, Sse}, + }, +}; +use futures_core::Stream; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value, json}; +use std::{ + collections::{HashMap, HashSet, VecDeque}, + convert::Infallible, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, + task::{Context, Poll}, + time::{SystemTime, UNIX_EPOCH}, +}; +use tokio::sync::{RwLock, mpsc, oneshot}; + +use crate::{ + app::AppState, + prompt::{self, Effort, Message, Role}, + response_tools::Catalog, + tokenizer::Tokenizer, + tool_output::{self, Incremental, Segment}, + wire::{Event, Finish, Generate}, + worker::{GenerationCommand, GenerationResult, WorkerState}, +}; + +static NEXT_RESPONSE_ID: AtomicU64 = AtomicU64::new(0); + +const MAX_STORED_RESPONSES: usize = 64; +const MAX_HISTORY_BYTES: usize = 128 * 1024 * 1024; + +#[derive(Clone, Default)] +pub struct ResponseHistory { + entries: HashMap>, + order: VecDeque, + bytes: usize, + store: Option>, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct StoredResponse { + model: String, + transcript: Vec, + input_len: usize, + response: Value, + bytes: usize, +} + +impl ResponseHistory { + /// Call before worker acquisition/start. Payloads are never included in errors. + pub fn open(directory: Option<&std::path::Path>) -> Result { + let Some(directory) = directory else { + return Ok(Self::default()); + }; + let store = Arc::new(crate::history_store::Store::open(directory)?); + let mut history = Self::default(); + if let Some(bytes) = store.read()? { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Snapshot { + schema: u32, + sha256: String, + entries: Vec, + } + let snapshot: Snapshot = + serde_json::from_slice(&bytes).map_err(|_| "invalid history snapshot")?; + if snapshot.schema != 1 || snapshot.entries.len() > MAX_STORED_RESPONSES { + return Err("unsupported history snapshot schema or entry count"); + } + use sha2::Digest; + let encoded = + serde_json::to_vec(&snapshot.entries).map_err(|_| "invalid history snapshot")?; + if hex::encode(sha2::Sha256::digest(&encoded)) != snapshot.sha256 { + return Err("history snapshot checksum mismatch"); + } + drop(encoded); + for entry in snapshot.entries { + let id = entry.response["id"] + .as_str() + .ok_or("invalid stored response ID")?; + if !id.starts_with("resp_") + || id.len() > 180 + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + || entry.model.is_empty() + || entry.model.len() > 180 + || entry.input_len > entry.transcript.len() + || entry.response["object"] != "response" + || !matches!( + entry.response["status"].as_str(), + Some("completed" | "incomplete") + ) + { + return Err("invalid stored response metadata"); + } + let input = Value::Array(entry.transcript[..entry.input_len].to_vec()); + if !input.as_array().unwrap().iter().all(Value::is_object) { + return Err("invalid stored response input"); + } + // Rebuild and compare, never trust persisted size or transcript bounds. + let count = history.entries.len(); + history.insert(id, &entry.model, &input, &entry.response)?; + let rebuilt = &history.entries[id]; + if history.entries.len() != count + 1 + || rebuilt.bytes != entry.bytes + || rebuilt.transcript != entry.transcript + { + return Err("inconsistent or oversized history snapshot"); + } + } + } + history.store = Some(store); + Ok(history) + } + + fn persist(&self) -> Result<(), &'static str> { + if let Some(store) = &self.store { + #[derive(Serialize)] + struct Snapshot<'a> { + schema: u32, + sha256: String, + entries: Vec<&'a StoredResponse>, + } + use sha2::Digest; + let entries: Vec<_> = self + .order + .iter() + .map(|id| self.entries[id].as_ref()) + .collect(); + let encoded = + serde_json::to_vec(&entries).map_err(|_| "cannot encode history snapshot")?; + let sha256 = hex::encode(sha2::Sha256::digest(&encoded)); + drop(encoded); + let snapshot = Snapshot { + schema: 1, + sha256, + entries, + }; + let bytes = + serde_json::to_vec(&snapshot).map_err(|_| "cannot encode history snapshot")?; + store.write(&bytes)?; + } + Ok(()) + } + + fn get(&self, id: &str, model: &str) -> Option<&[Value]> { + let response = self.entries.get(id)?; + (response.model == model).then_some(response.transcript.as_slice()) + } + + fn insert( + &mut self, + id: &str, + model: &str, + input: &Value, + response: &Value, + ) -> Result<(), &'static str> { + if self.store.is_none() { + return self.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES); + } + let mut candidate = self.clone(); + candidate.insert_with_limit(id, model, input, response, MAX_HISTORY_BYTES)?; + candidate.persist()?; + *self = candidate; + Ok(()) + } + + fn insert_with_limit( + &mut self, + id: &str, + model: &str, + input: &Value, + response: &Value, + limit: usize, + ) -> Result<(), &'static str> { + if response["id"] != id || response["model"] != model { + return Err("stored response identity mismatch"); + } + let mut transcript = Vec::new(); + append_input(&mut transcript, input); + let input_len = transcript.len(); + if let Some(items) = response["output"].as_array() { + transcript.extend(items.iter().cloned()); + } + let bytes = serde_json::to_vec(&transcript) + .map_err(|_| "response transcript cannot be serialized")? + .len() + .checked_add( + serde_json::to_vec(response) + .map_err(|_| "response cannot be serialized")? + .len(), + ) + .ok_or("response storage size overflow")?; + if bytes > limit { + return Err("response and transcript exceed the in-memory history limit"); + } + if self.entries.contains_key(id) { + return Err("response ID already exists in history"); + } + while self.entries.len() >= MAX_STORED_RESPONSES || self.bytes.saturating_add(bytes) > limit + { + let Some(oldest) = self.order.pop_front() else { + break; + }; + if let Some(removed) = self.entries.remove(&oldest) { + self.bytes -= removed.bytes; + } + } + self.bytes += bytes; + self.order.push_back(id.to_owned()); + self.entries.insert( + id.to_owned(), + Arc::new(StoredResponse { + model: model.to_owned(), + transcript, + input_len, + response: response.clone(), + bytes, + }), + ); + Ok(()) + } + + fn delete_committed(&mut self, id: &str) -> Result { + let mut candidate = self.clone(); + if !candidate.remove(id) { + return Ok(false); + } + candidate.persist()?; + *self = candidate; + Ok(true) + } + + fn remove(&mut self, id: &str) -> bool { + let Some(removed) = self.entries.remove(id) else { + return false; + }; + self.bytes -= removed.bytes; + self.order.retain(|entry| entry != id); + true + } +} + +async fn store_response( + history: &Arc>, + id: &str, + model: &str, + input: &Value, + response: &Value, +) -> Result<(), &'static str> { + let mut guard = history.clone().write_owned().await; + if guard.store.is_none() { + return guard.insert(id, model, input, response); + } + let (id, model, input, response) = ( + id.to_owned(), + model.to_owned(), + input.clone(), + response.clone(), + ); + tokio::task::spawn_blocking(move || guard.insert(&id, &model, &input, &response)) + .await + .map_err(|_| "history storage task failed")? +} + +fn resource_not_found() -> Response { + api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("response_id"), + "the stored response is unavailable", + ) +} + +fn resource_query_error(query: Option) -> Option { + query.filter(|value| !value.is_empty()).map(|_| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_query", + None, + "stored response query options and stream resumption are not supported", + ) + }) +} + +pub async fn retrieve( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + let history = state.response_history.read().await; + let Some(entry) = history.entries.get(&id) else { + return resource_not_found(); + }; + let response = entry.response.clone(); + drop(history); + Json(response).into_response() +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct InputItemsQuery { + after: Option, + limit: Option, + order: Option, +} + +impl InputItemsQuery { + fn parse(query: Option<&str>) -> Result { + let uri = format!("/?{}", query.unwrap_or("")) + .parse::() + .map_err(|_| "invalid input-items query")?; + let Query(options) = Query::::try_from_uri(&uri) + .map_err(|_| "only single after, limit and order query parameters are supported")?; + if options.limit.is_some_and(|n| !(1..=100).contains(&n)) + || options + .order + .as_deref() + .is_some_and(|s| s != "asc" && s != "desc") + || options + .after + .as_ref() + .is_some_and(|s| s.is_empty() || s.len() > 256) + { + return Err("limit must be 1..100, order asc|desc and after a nonempty item ID"); + } + Ok(options) + } +} + +impl StoredResponse { + fn input_page(&self, id: &str, options: &InputItemsQuery) -> Result { + let descending = options.order.as_deref().unwrap_or("desc") == "desc"; + let prefix = format!("input_{id}_"); + let start = match options.after.as_deref() { + None => 0, + Some(cursor) => { + let index = cursor + .strip_prefix(&prefix) + .and_then(|s| s.parse::().ok()) + .filter(|i| *i < self.input_len && format!("{prefix}{i}") == cursor) + .ok_or("after does not identify an input item of this response")?; + if descending { + self.input_len - index + } else { + index + 1 + } + } + }; + let limit = options.limit.unwrap_or(20); + let count = self.input_len.saturating_sub(start).min(limit); + let mut data = Vec::with_capacity(count); + for position in start..start + count { + let index = if descending { + self.input_len - 1 - position + } else { + position + }; + // Project rather than mutate the transcript used for prompt replay. + // IDs identify occurrences in this response, so repeated client IDs + // cannot make a pagination cursor ambiguous. call_id stays intact. + let mut item = self.transcript[index].clone(); + item.as_object_mut() + .ok_or("stored input item is not an object")? + .insert("id".into(), json!(format!("{prefix}{index}"))); + if item.get("role").is_some() + && (item.get("type").is_none() || item["type"] == "message") + { + item["type"] = json!("message"); + if let Some(text) = item["content"].as_str() { + item["content"] = if item["role"] == "assistant" { + json!([{"type":"output_text","text":text,"annotations":[]}]) + } else { + json!([{"type":"input_text","text":text}]) + }; + } + let assistant = item["role"] == "assistant"; + if let Some(parts) = item["content"].as_array_mut() { + for part in parts { + if part["type"] == "input_text" || part["type"] == "output_text" { + part["type"] = json!(if assistant { + "output_text" + } else { + "input_text" + }); + if assistant && part.get("annotations").is_none() { + part["annotations"] = json!([]); + } + } + } + } + if item.get("status").is_none() { + item["status"] = json!("completed"); + } + } + data.push(item); + } + Ok( + json!({"object":"list", "first_id":data.first().map(|item| &item["id"]), + "last_id":data.last().map(|item| &item["id"]), + "has_more":self.input_len.saturating_sub(start) > count,"data":data}), + ) + } +} + +pub async fn input_items( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + let invalid = |message| { + api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_input_items_query", + None, + message, + ) + }; + let options = match InputItemsQuery::parse(query.as_deref()) { + Ok(options) => options, + Err(message) => return invalid(message), + }; + let history = state.response_history.read().await; + let Some(entry) = history.entries.get(&id) else { + return resource_not_found(); + }; + let page = entry.input_page(&id, &options); + drop(history); + match page { + Ok(page) => Json(page).into_response(), + Err(message) => invalid(message), + } +} + +pub async fn delete( + State(state): State, + Path(id): Path, + RawQuery(query): RawQuery, +) -> Response { + if let Some(error) = resource_query_error(query) { + return error; + } + let mut guard = state.response_history.clone().write_owned().await; + let target = id.clone(); + let result = tokio::task::spawn_blocking(move || guard.delete_committed(&target)).await; + match result { + Ok(Ok(true)) => (), + Ok(Ok(false)) => return resource_not_found(), + _ => { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + "cannot commit response deletion; inspect storage and restart", + ); + } + } + Json(json!({"id":id,"object":"response.deleted","deleted":true})).into_response() +} + +fn append_input(transcript: &mut Vec, input: &Value) { + if let Some(items) = input.as_array() { + transcript.extend(items.iter().cloned()); + } else if let Some(text) = input.as_str() { + transcript.push(json!({"role":"user","content":text})); + } +} + +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CreateRequest { + pub model: String, + pub input: Value, + #[serde(default)] + pub stream: bool, + pub instructions: Option, + pub max_output_tokens: Option, + pub previous_response_id: Option, + pub parallel_tool_calls: Option, + pub reasoning: Option, + pub text: Option, + #[serde(default)] + pub tools: Vec, + pub tool_choice: Option, + pub temperature: Option, + pub top_p: Option, + pub truncation: Option, + pub metadata: Option>, + pub store: Option, + #[serde(default)] + pub include: Vec, + pub prompt_cache_key: Option, + pub client_metadata: Option>, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct TextOptions { + pub format: TextFormat, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum TextFormat { + Text, + JsonObject, + JsonSchema { + name: String, + schema: Value, + strict: Option, + }, +} + +impl CreateRequest { + fn forced_tool(&self) -> Option<&str> { + self.tool_choice + .as_ref() + .filter(|choice| choice["type"] == "function" || choice["type"] == "custom")? + .get("name")? + .as_str() + } + + fn allowed_tools(&self) -> Option<&Vec> { + self.tool_choice + .as_ref() + .filter(|choice| choice["type"] == "allowed_tools")? + .get("tools")? + .as_array() + } + + fn declared_selector(&self, choice: &Value) -> bool { + choice.as_object().is_some_and(|fields| fields.len() == 2) + && (choice["type"] == "function" || choice["type"] == "custom") + && choice["name"].is_string() + && self + .tools + .iter() + .any(|tool| tool["type"] == choice["type"] && tool["name"] == choice["name"]) + } + + fn validate_tool_name(&self, name: &str) -> Result<(), String> { + if self.forced_tool().is_some_and(|forced| forced != name) { + return Err("generated tool does not match forced tool choice".into()); + } + if self + .allowed_tools() + .is_some_and(|allowed| !allowed.iter().any(|tool| tool["name"] == name)) + { + return Err("generated tool is not in allowed_tools".into()); + } + Ok(()) + } + + fn tools_required(&self) -> bool { + self.tool_choice.as_ref().is_some_and(|choice| { + choice == "required" + || (choice["type"] == "allowed_tools" && choice["mode"] == "required") + }) || self.forced_tool().is_some() + } + + fn tools_disabled(&self) -> bool { + self.tool_choice + .as_ref() + .is_some_and(|choice| choice == "none") + } + + fn validate_tool_count(&self, count: usize) -> Result<(), String> { + if self.tools_disabled() && count > 0 { + return Err("tool_choice none forbids tool calls".into()); + } + if self.parallel_tool_calls == Some(false) && count > 1 { + return Err("parallel_tool_calls false permits at most one tool call".into()); + } + if self.forced_tool().is_some() && count > 1 { + return Err("forced tool choice permits exactly one tool call".into()); + } + Ok(()) + } + + pub fn validate(&self) -> Result<(), (&'static str, &'static str)> { + if self.model.trim().is_empty() { + return Err(("model", "model must be a nonempty string")); + } + if !self.input.is_string() && !self.input.is_array() { + return Err(("input", "input must be a string or an array")); + } + if self.input.as_str().is_some_and(str::is_empty) + || self.input.as_array().is_some_and(Vec::is_empty) + { + return Err(("input", "input cannot be empty")); + } + if self.max_output_tokens == Some(0) { + return Err(("max_output_tokens", "max_output_tokens must be positive")); + } + if self + .temperature + .is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value)) + { + return Err(("temperature", "temperature must be between 0 and 2")); + } + if self + .top_p + .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) + { + return Err(("top_p", "top_p must be between 0 and 1")); + } + if let Some(TextOptions { + format: TextFormat::JsonSchema { name, schema, .. }, + }) = &self.text + && (name.is_empty() || schema.get("type").and_then(Value::as_str) != Some("object")) + { + return Err(( + "text.format", + "json_schema needs a name and a root schema of type object", + )); + } + if let Some(TextOptions { + format: TextFormat::JsonSchema { schema, .. }, + }) = &self.text + { + if reject_remote_refs(schema).is_err() { + return Err(( + "text.format", + "schema cannot use external $ref/$dynamicRef/$recursiveRef", + )); + } + if jsonschema::validator_for(schema).is_err() { + return Err(("text.format", "json_schema needs a valid local schema")); + } + } + reasoning_effort(self)?; + if self + .include + .iter() + .any(|field| field != "reasoning.encrypted_content") + { + return Err(("include", "unsupported optional response field")); + } + if self + .prompt_cache_key + .as_ref() + .is_some_and(|key| key.len() > 512) + { + return Err(("prompt_cache_key", "cache key exceeds 512 bytes")); + } + let catalog = Catalog::new(&self.tools).map_err(|message| ("tools", message))?; + if self.tools_required() && catalog.flat.is_empty() { + return Err(( + "tool_choice", + "required tool choice needs at least one callable tool", + )); + } + if let Some(choice) = &self.tool_choice + && (choice["type"] == "function" || choice["type"] == "custom") + && !self.declared_selector(choice) + { + return Err(( + "tool_choice", + "forced tool needs only type and the name of a declared top-level tool of the same type", + )); + } + if let Some(choice) = &self.tool_choice + && choice["type"] == "allowed_tools" + { + let allowed = self + .allowed_tools() + .ok_or(("tool_choice", "allowed_tools needs a tools array"))?; + if choice.as_object().is_none_or(|fields| fields.len() != 3) + || (choice["mode"] != "auto" && choice["mode"] != "required") + || (choice["mode"] == "required" && allowed.is_empty()) + { + return Err(( + "tool_choice", + "allowed_tools needs only type, mode auto|required and tools; required needs at least one tool", + )); + } + let mut seen = HashSet::new(); + for selector in allowed { + if !self.declared_selector(selector) || !seen.insert(selector["name"].as_str()) { + return Err(( + "tool_choice", + "allowed_tools needs unique declared top-level function/custom type and name selectors", + )); + } + } + } + let mut names = HashSet::new(); + for tool in &catalog.flat { + let Some(name) = tool.get("name").and_then(Value::as_str) else { + return Err(("tools", "only named function tools are supported")); + }; + if tool.get("type").and_then(Value::as_str) != Some("function") + || name.is_empty() + || name.len() > 64 + || !name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || !names.insert(name) + { + return Err(( + "tools", + "function names must be unique ASCII letters, digits, hyphens or underscores (up to 64 bytes)", + )); + } + if let Some(parameters) = tool.get("parameters") + && (parameters.get("type").and_then(Value::as_str) != Some("object") + || reject_remote_refs(parameters).is_err() + || jsonschema::validator_for(parameters).is_err()) + { + return Err(( + "tools", + "function parameters need a local, valid object schema", + )); + } + } + Ok(()) + } +} + +fn parse_request( + state: &AppState, + body: Result, JsonRejection>, +) -> Result> { + let Json(body) = match body { + Ok(body) => body, + Err(error) => { + return Err(Box::new(api_error( + error.status(), + "invalid_request_error", + "invalid_json", + None, + &error.to_string(), + ))); + } + }; + let request: CreateRequest = match serde_json::from_value(body) { + Ok(request) => request, + Err(error) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + None, + &error.to_string(), + ))); + } + }; + if let Err((param, message)) = request.validate() { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_request", + Some(param), + message, + ))); + } + if state + .model + .as_ref() + .is_some_and(|model| model != &request.model) + { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "model_not_found", + Some("model"), + "the requested model is not served by this runtime", + ))); + } + Ok(request) +} + +// Both endpoints must encode the same expanded transcript and chat template. +async fn prepare_input_tokens( + state: &AppState, + request: &mut CreateRequest, + tokenizer: Arc, +) -> Result, Box> { + if let Some(previous) = &request.previous_response_id { + let history = state.response_history.read().await; + let Some(saved) = history.get(previous, &request.model) else { + return Err(Box::new(api_error( + StatusCode::NOT_FOUND, + "invalid_request_error", + "response_not_found", + Some("previous_response_id"), + "the previous response is unavailable or belongs to a different model", + ))); + }; + let mut transcript = saved.to_vec(); + append_input(&mut transcript, &request.input); + request.input = Value::Array(transcript); + } + let prompt = match render_request_prompt(request) { + Ok(prompt) => prompt, + Err(message) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_prompt", + Some("input"), + &message, + ))); + } + }; + let tokenizer_for_encode = tokenizer.clone(); + let token_ids = match tokio::task::spawn_blocking(move || { + tokenizer_for_encode + .encode(&prompt, true) + .map_err(|error| error.to_string()) + }) + .await + { + Ok(Ok(ids)) => ids, + Ok(Err(message)) => { + return Err(Box::new(api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "tokenization_failed", + Some("input"), + &message, + ))); + } + Err(error) => { + return Err(Box::new(api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "tokenization_failed", + None, + &error.to_string(), + ))); + } + }; + Ok(token_ids) +} + +pub async fn count_input_tokens( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; + if let Err((param, message)) = validate_live_subset(&request) { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "invalid_request_error", + "unsupported_live_feature", + Some(param), + message, + ); + } + let Some(tokenizer) = &state.tokenizer else { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "configure tokenizer_dir to enable input token counting", + ); + }; + match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { + Ok(ids) => Json(json!({"object": "response.input_tokens", "input_tokens": ids.len()})) + .into_response(), + Err(error) => *error, + } +} + +fn queue_error(error: crate::queue::Error) -> Response { + match error { + crate::queue::Error::Expired => api_error( + StatusCode::GATEWAY_TIMEOUT, + "server_error", + "queue_timeout", + None, + "request exceeded the configured queue deadline before worker claim; generation was not started", + ), + crate::queue::Error::Closed => api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker command queue closed before request claim", + ), + } +} + +pub async fn create( + State(state): State, + body: Result, JsonRejection>, +) -> Response { + let mut request = match parse_request(&state, body) { + Ok(request) => request, + Err(error) => return *error, + }; + if state.worker.read().await.state != WorkerState::Ready { + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker is not ready", + ); + } + let (Some(tokenizer), Some(generation)) = (&state.tokenizer, &state.generation) else { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "server_error", + "inference_adapter_missing", + None, + "configure tokenizer_dir to enable the text inference preview", + ); + }; + if let Err((param, message)) = validate_live_subset(&request) { + return api_error( + StatusCode::NOT_IMPLEMENTED, + "invalid_request_error", + "unsupported_live_feature", + Some(param), + message, + ); + } + let token_ids = match prepare_input_tokens(&state, &mut request, tokenizer.clone()).await { + Ok(ids) => ids, + Err(error) => return *error, + }; + let remaining = state + .worker + .read() + .await + .max_context + .map(|context| { + context + .saturating_sub(token_ids.len()) + .min(u32::MAX as usize) as u32 + }) + .unwrap_or(32768); + let generate = Generate { + token_ids, + max_new: request + .max_output_tokens + .unwrap_or(32768.min(remaining).max(1)), + temperature: request.temperature, + top_p: request.top_p, + }; + if request.stream { + let (events, received) = mpsc::channel(16); + if let Err(error) = crate::queue::enqueue( + generation, + GenerationCommand { + queue: None, + activity: Some(state.lifecycle.generation()), + request: generate, + result: GenerationResult::Streaming(events), + }, + state.queue_timeout, + ) + .await + { + return queue_error(error); + } + return stream_live_text( + request, + tokenizer.clone(), + received, + Some(state.response_history.clone()), + ); + } + let (result, received) = oneshot::channel(); + let command = GenerationCommand { + queue: None, + activity: Some(state.lifecycle.generation()), + request: generate, + result: GenerationResult::Buffered(result), + }; + if let Err(error) = crate::queue::enqueue(generation, command, state.queue_timeout).await { + return queue_error(error); + } + let events = match received.await { + Ok(Ok(events)) => events, + Ok(Err(message)) => { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "generation_failed", + None, + &message, + ); + } + Err(_) => { + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + "server_error", + "worker_not_ready", + None, + "the Strata worker stopped before completing the request", + ); + } + }; + let Some(Event::Done(done)) = events.last() else { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "missing_terminal_event", + None, + "the Strata worker did not report DONE", + ); + }; + if done.finish == Finish::Cancel { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "unsupported_finish", + None, + "the text inference preview requires a stop finish", + ); + } + let output_ids = events + .iter() + .filter_map(|event| match event { + Event::Token(id) => Some(*id), + _ => None, + }) + .collect::>(); + let terminal = [ + tokenizer.special_id("<|im_end|>"), + tokenizer.special_id("<|endoftext|>"), + ]; + let output_ids = output_ids + .split(|id| terminal.contains(&Some(*id))) + .next() + .unwrap_or(&[]) + .to_vec(); + let tokenizer_for_decode = tokenizer.clone(); + let thinking = reasoning_enabled(&request); + let finish = done.finish; + let output = match tokio::task::spawn_blocking(move || { + decode_generation(&tokenizer_for_decode, &output_ids, thinking, finish) + }) + .await + { + Ok(Ok(text)) => text, + Ok(Err(message)) => { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "detokenization_failed", + None, + &message, + ); + } + Err(error) => { + return api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "server_error", + "detokenization_failed", + None, + &error.to_string(), + ); + } + }; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let id = format!( + "resp_{:x}_{:x}", + now.as_nanos(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + ); + let (items, reasoning_tokens) = match decoded_items(&request, output, &id) { + Ok(items) => items, + Err(message) => { + return api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "tool_call_parse_failed", + None, + &message, + ); + } + }; + let usage = Usage { + input_tokens: done.prompt_tokens, + output_tokens: done.generated, + reasoning_tokens, + cached_tokens: done.reused.unwrap_or(0), + }; + match ResponseTrace::build_with_terminal( + &request, + &items, + usage, + &id, + now.as_secs(), + now.as_secs(), + done.finish == Finish::Length, + ) { + Ok(trace) => { + if request.store != Some(false) + && let Err(message) = store_response( + &state.response_history, + &id, + &request.model, + &request.input, + &trace.response, + ) + .await + { + return api_error( + StatusCode::INSUFFICIENT_STORAGE, + "server_error", + "response_storage_failed", + None, + message, + ); + } + Json(trace.response).into_response() + } + Err(message) => api_error( + StatusCode::BAD_GATEWAY, + "server_error", + "response_assembly_failed", + None, + &message, + ), + } +} + +fn parse_output_items( + request: &CreateRequest, + output: String, + id: &str, +) -> Result, String> { + if request.tools.is_empty() { + return Ok(vec![OutputItem::Text { + deltas: vec![output], + }]); + } + let catalog = Catalog::new(&request.tools)?; + let mut items = tool_output::parse_complete(&output, &catalog.flat)? + .into_iter() + .enumerate() + .map(|(index, segment)| match segment { + Segment::Text(text) => OutputItem::Text { deltas: vec![text] }, + Segment::Call { name, arguments } => OutputItem::FunctionCall { + name, + call_id: format!("call_{}_{}", &id[5..], index), + argument_deltas: vec![arguments.to_string()], + }, + }) + .collect::>(); + if items.is_empty() { + items.push(OutputItem::Text { + deltas: vec![String::new()], + }); + } + Ok(items) +} + +fn reasoning_effort(request: &CreateRequest) -> Result { + let Some(value) = &request.reasoning else { + return Ok(Effort::XHigh); + }; + let fields = value + .as_object() + .ok_or(("reasoning", "reasoning must be an object"))?; + if fields + .keys() + .any(|key| !matches!(key.as_str(), "effort" | "summary")) + { + return Err(("reasoning", "only effort and summary are supported")); + } + if fields + .get("summary") + .is_some_and(|value| !value.is_null() && value != "auto") + { + return Err(( + "reasoning.summary", + "only auto or null is supported; this runtime returns raw reasoning content with an empty summary", + )); + } + match fields.get("effort") { + None | Some(Value::Null) => Ok(Effort::XHigh), + Some(Value::String(effort)) => match effort.as_str() { + "none" => Ok(Effort::None), + "low" => Ok(Effort::Low), + "medium" => Ok(Effort::Medium), + "high" => Ok(Effort::High), + "xhigh" => Ok(Effort::XHigh), + _ => Err(("reasoning.effort", "use none, low, medium, high or xhigh")), + }, + _ => Err(("reasoning.effort", "effort must be a string or null")), + } +} + +fn reasoning_enabled(request: &CreateRequest) -> bool { + reasoning_effort(request).is_ok_and(|effort| effort != Effort::None) +} + +struct DecodedGeneration { + answer: String, + reasoning: Option<(String, bool)>, + reasoning_tokens: u64, +} + +fn decode_generation( + tokenizer: &Tokenizer, + ids: &[u32], + reasoning: bool, + finish: Finish, +) -> Result { + let bytes = tokenizer.decode_bytes(ids).map_err(|e| e.to_string())?; + if !reasoning { + return Ok(DecodedGeneration { + answer: String::from_utf8_lossy(&bytes).into_owned(), + reasoning: None, + reasoning_tokens: 0, + }); + } + let marker = b""; + let boundary = bytes.windows(marker.len()).position(|part| part == marker); + let Some(boundary) = boundary else { + if finish != Finish::Length { + return Err("reasoning ended without ".into()); + } + return Ok(DecodedGeneration { + answer: String::new(), + reasoning: Some((String::from_utf8_lossy(&bytes).into_owned(), false)), + reasoning_tokens: ids.len() as u64, + }); + }; + let mut consumed = 0; + let mut reasoning_tokens = 0; + for id in ids { + consumed += tokenizer + .decode_bytes(&[*id]) + .map_err(|e| e.to_string())? + .len(); + reasoning_tokens += 1; + if consumed >= boundary + marker.len() { + break; + } + } + Ok(DecodedGeneration { + answer: String::from_utf8_lossy(&bytes[boundary + marker.len()..]) + .trim_start_matches('\n') + .to_owned(), + reasoning: Some(( + String::from_utf8_lossy(&bytes[..boundary]).into_owned(), + true, + )), + reasoning_tokens, + }) +} + +fn decoded_items( + request: &CreateRequest, + decoded: DecodedGeneration, + id: &str, +) -> Result<(Vec, u64), String> { + let mut items = Vec::new(); + let mut reasoning_incomplete = false; + if let Some((text, complete)) = decoded.reasoning { + items.push(OutputItem::Reasoning { + deltas: vec![text], + complete, + }); + reasoning_incomplete = !complete; + } + if !reasoning_incomplete { + items.extend(parse_output_items(request, decoded.answer, id)?); + } + Ok((items, decoded.reasoning_tokens)) +} + +#[derive(Default)] +struct ReasoningStream { + pending: Vec, + ended: bool, +} + +impl ReasoningStream { + fn push(&mut self, bytes: &[u8]) -> String { + if self.ended { + return String::new(); + } + self.pending.extend_from_slice(bytes); + let marker = b""; + if let Some(at) = self + .pending + .windows(marker.len()) + .position(|part| part == marker) + { + let text = String::from_utf8_lossy(&self.pending[..at]).into_owned(); + self.pending.clear(); + self.ended = true; + return text; + } + let keep = (1..marker.len()) + .rev() + .find(|n| self.pending.ends_with(&marker[..*n])) + .unwrap_or(0); + let tail = self.pending.split_off(self.pending.len() - keep); + let text = drain_utf8(&mut self.pending, false); + self.pending.extend_from_slice(&tail); + text + } + + fn finish(&mut self) -> String { + drain_utf8(&mut self.pending, true) + } +} + +fn is_structured(request: &CreateRequest) -> bool { + request + .text + .as_ref() + .is_some_and(|text| !matches!(text.format, TextFormat::Text)) +} + +fn render_request_prompt(request: &CreateRequest) -> Result { + let mut owned = Vec::<(Role, String, Option)>::new(); + if let Some(instructions) = &request.instructions { + owned.push((Role::System, instructions.clone(), None)); + } + if let Some(name) = request.forced_tool() { + let kind = if request + .tool_choice + .as_ref() + .is_some_and(|choice| choice["type"] == "custom") + { + "custom tool" + } else { + "function" + }; + owned.push(( + Role::System, + format!( + "Call exactly one {kind} in this response: {name}. Do not call any other tool." + ), + None, + )); + } else if request.tools_required() { + owned.push(( + Role::System, + "Call at least one tool in this response.".to_owned(), + None, + )); + } + if let Some(allowed) = request.allowed_tools() { + owned.push((Role::System, if allowed.is_empty() { + "Do not call any tools in this response.".to_owned() + } else { + format!("Only these tools may be called in this response: {}. Do not call any other tool.", serde_json::to_string(allowed).expect("selector serialization")) + }, None)); + } + if request.parallel_tool_calls == Some(false) + && !request.tools_disabled() + && !request.tools.is_empty() + { + owned.push(( + Role::System, + "Use at most one tool call in this response.".to_owned(), + None, + )); + } + if let Some(options) = &request.text { + let instruction = match &options.format { + TextFormat::Text => None, + TextFormat::JsonObject => Some("Return exactly one JSON object as your final text response. Do not add Markdown fences or commentary.".to_owned()), + TextFormat::JsonSchema { schema, .. } => Some(format!("Return exactly one JSON object matching this JSON Schema as your final text response. Do not add Markdown fences or commentary.\nJSON Schema: {schema}")), + }; + if let Some(mut instruction) = instruction { + if !request.tools_disabled() && !request.tools.is_empty() { + instruction.push_str(" Function calls still use the tool-call format; this JSON requirement applies to your final text answer after any necessary tool results."); + } + owned.push((Role::System, instruction, None)); + } + } + if let Some(input) = request.input.as_str() { + owned.push((Role::User, input.to_owned(), None)); + } else { + let items = request + .input + .as_array() + .ok_or("input must be a string or array")?; + let mut calls = Vec::<(String, String)>::new(); + let mut outputs = Vec::<(String, String)>::new(); + let mut custom_calls = HashSet::::new(); + let mut reasoning = None::; + for item in items { + let kind = item + .get("type") + .and_then(Value::as_str) + .unwrap_or("message"); + match kind { + "reasoning" => { + if reasoning.is_some() || !calls.is_empty() { + return Err( + "reasoning must precede its assistant message or tool calls".into() + ); + } + if item.get("encrypted_content").is_some_and(|v| !v.is_null()) { + return Err("encrypted reasoning replay is not supported".into()); + } + let parts = item + .get("content") + .and_then(Value::as_array) + .ok_or("reasoning replay requires raw reasoning_text content")?; + let mut text = String::new(); + for part in parts { + if part.get("type").and_then(Value::as_str) != Some("reasoning_text") { + return Err("reasoning replay requires reasoning_text parts".into()); + } + text.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("reasoning_text needs text")?, + ); + } + reasoning = Some(text); + } + "message" => { + if !calls.is_empty() { + return Err( + "every replayed function call needs an output before the next message" + .into(), + ); + } + let role = match item.get("role").and_then(Value::as_str) { + Some("system") => Role::System, + Some("developer") => Role::Developer, + Some("user") => Role::User, + Some("assistant") => Role::Assistant, + _ => return Err("unsupported input message role".into()), + }; + let content = match item.get("content") { + Some(Value::String(text)) => text.clone(), + Some(Value::Array(parts)) => { + let mut text = String::new(); + for part in parts { + if !matches!( + part.get("type").and_then(Value::as_str), + Some("input_text" | "output_text") + ) { + return Err("only text content parts are supported".into()); + } + text.push_str( + part.get("text") + .and_then(Value::as_str) + .ok_or("text part needs text")?, + ); + } + text + } + _ => return Err("input message needs text content".into()), + }; + if role != Role::Assistant + && let Some(thought) = reasoning.take() + { + owned.push((Role::Assistant, String::new(), Some(thought))); + } + if role == Role::Assistant + && let Some((Role::Assistant, previous, thought)) = owned.last_mut() + { + if !previous.is_empty() && !content.is_empty() { + previous.push('\n'); + } + previous.push_str(&content); + if let Some(next) = reasoning.take() { + let current = thought.get_or_insert_with(String::new); + current.push_str(&next); + } + } else { + owned.push((role, content, reasoning.take())); + } + } + "function_call" | "custom_tool_call" => { + if !outputs.is_empty() { + return Err("new function calls cannot interrupt tool outputs".into()); + } + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("function call needs call_id")?; + let name = item + .get("name") + .and_then(Value::as_str) + .ok_or("function call needs name")?; + let namespace = match item.get("namespace") { + None | Some(Value::Null) => None, + Some(Value::String(value)) => Some(value.as_str()), + _ => return Err("function namespace must be a string".into()), + }; + let name = crate::response_tools::alias(name, namespace)?; + if call_id.is_empty() + || name.is_empty() + || !name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' + }) + || calls.iter().any(|(id, _)| id == call_id) + { + return Err("function call has an invalid or duplicate identity".into()); + } + let custom = kind == "custom_tool_call"; + let arguments: Value = if custom { + if item.get("arguments").is_some() { + return Err("custom tool call uses input, not arguments".into()); + } + custom_calls.insert(call_id.to_owned()); + json!({"input":item["input"].as_str().ok_or("custom tool call needs text input")?}) + } else { + if item.get("input").is_some() { + return Err("function call uses arguments, not input".into()); + } + let arguments = item["arguments"] + .as_str() + .ok_or("function call needs JSON arguments")?; + serde_json::from_str(arguments) + .map_err(|_| "function call arguments are not JSON")? + }; + let properties = arguments + .as_object() + .ok_or("function call arguments must be an object")?; + let mut markup = format!("\n\n"); + for (parameter, value) in properties { + if parameter.is_empty() + || !parameter.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' + }) + { + return Err("function argument name cannot be rendered safely".into()); + } + markup.push_str("\n"); + if let Some(text) = value.as_str() { + markup.push_str(text); + } else { + markup.push_str(&value.to_string()); + } + markup.push_str("\n\n"); + } + markup.push_str("\n"); + calls.push((call_id.to_owned(), markup)); + } + "function_call_output" | "custom_tool_call_output" => { + let call_id = item + .get("call_id") + .and_then(Value::as_str) + .ok_or("tool output needs call_id")?; + if custom_calls.contains(call_id) != (kind == "custom_tool_call_output") { + return Err("tool output kind must match its preceding call".into()); + } + let output = match item.get("output") { + Some(Value::String(text)) => text.clone(), + Some(Value::Array(parts)) => parts + .iter() + .map(|part| { + if part["type"] != "input_text" { + return Err( + "tool output supports only input_text content parts", + ); + } + part["text"].as_str().ok_or("tool output part needs text") + }) + .collect::, _>>()? + .join("\n"), + _ => return Err("tool output needs text or input_text parts".into()), + }; + if !calls.iter().any(|(id, _)| id == call_id) + || outputs.iter().any(|(id, _)| id == call_id) + { + return Err( + "tool output must match one preceding unresolved call_id".into() + ); + } + outputs.push((call_id.to_owned(), output.to_owned())); + if outputs.len() == calls.len() { + let call_text = calls + .iter() + .map(|(_, markup)| markup.as_str()) + .collect::>() + .join("\n"); + // Qwen's tool_response blocks carry no call_id. Restore + // call order so parallel results cannot change identity. + let output_text = calls + .iter() + .map(|(call_id, _)| { + let (_, value) = outputs + .iter() + .find(|(id, _)| id == call_id) + .expect("all distinct call IDs have an output"); + format!("\n{value}\n") + }) + .collect::>() + .join("\n"); + if let Some((Role::Assistant, content, thought)) = owned.last_mut() { + content.truncate(content.trim_end().len()); + if !content.is_empty() { + content.push_str("\n\n"); + } + content.push_str(&call_text); + if let Some(next) = reasoning.take() { + thought.get_or_insert_with(String::new).push_str(&next); + } + } else { + owned.push((Role::Assistant, call_text, reasoning.take())); + } + owned.push((Role::User, output_text, None)); + calls.clear(); + outputs.clear(); + custom_calls.clear(); + } + } + _ => return Err("unsupported Responses input item".into()), + } + } + if !calls.is_empty() { + return Err("replayed function calls need all tool outputs".into()); + } + if reasoning.is_some() { + return Err( + "reasoning replay needs a following assistant message, tool call, or user turn" + .into(), + ); + } + } + // The pinned Qwen template only accepts leading instruction messages. + // Keep all instruction text and its order/authority; never demote a late + // developer instruction (including approval criteria) into user content. + owned.sort_by_key(|(role, _, _)| !matches!(role, Role::System | Role::Developer)); + let messages = owned + .iter() + .map(|(role, content, reasoning)| Message { + role: *role, + content, + reasoning: reasoning.as_deref(), + }) + .collect::>(); + let catalog = Catalog::new(&request.tools)?; + prompt::render_with_tools( + &messages, + reasoning_effort(request).map_err(|(_, message)| message.to_owned())?, + if request.tools_disabled() { + &[] + } else { + &catalog.flat + }, + ) + .map_err(str::to_owned) +} + +fn stream_live_text( + request: CreateRequest, + tokenizer: std::sync::Arc, + mut source: mpsc::Receiver>, + history: Option>>, +) -> Response { + if is_structured(&request) || reasoning_enabled(&request) { + return stream_live_buffered(request, tokenizer, source, history); + } + if !request.tools.is_empty() { + return stream_live_tools(request, tokenizer, source, history); + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let id = format!( + "resp_{:x}_{:x}", + now.as_nanos(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + ); + let created_at = now.as_secs(); + let initial = ResponseTrace::build( + &request, + &[OutputItem::Text { deltas: vec![] }], + Usage { + input_tokens: 0, + output_tokens: 0, + reasoning_tokens: 0, + cached_tokens: 0, + }, + &id, + created_at, + created_at, + ) + .expect("validated text request has a valid initial trace"); + let pending_response = initial.events[0]["response"].clone(); + let item_id = initial.events[2]["item"]["id"].as_str().unwrap().to_owned(); + let (sender, receiver) = mpsc::channel::(16); + tokio::spawn(async move { + let mut sequence = 0usize; + for event in initial.events.into_iter().take(4) { + if sender.send(event).await.is_err() { + return; + } + sequence += 1; + } + let terminal = [ + tokenizer.special_id("<|im_end|>"), + tokenizer.special_id("<|endoftext|>"), + ]; + let mut output = String::new(); + let mut pending_bytes = Vec::new(); + let mut text_ended = false; + let mut done = None; + let mut failure = None; + while let Some(result) = tokio::select! { + biased; + _ = sender.closed() => return, + result = source.recv() => result, + } { + match result { + Ok(Event::Token(id_token)) if !text_ended => { + if terminal.contains(&Some(id_token)) { + text_ended = true; + continue; + } + let decoded = tokenizer + .decode_bytes(&[id_token]) + .map_err(|error| error.to_string()); + match decoded { + Ok(bytes) => { + pending_bytes.extend_from_slice(&bytes); + let delta = drain_utf8(&mut pending_bytes, false); + if !delta.is_empty() { + output.push_str(&delta); + if !send_stream_event(&sender, &mut sequence, "response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": 0, "content_index": 0, "delta": delta, "logprobs": []})).await { return; } + } + } + Err(error) => { + failure = Some(error); + break; + } + } + } + Ok(Event::Done(value)) => { + done = Some(value); + break; + } + Ok(Event::Error(message)) | Err(message) => { + failure = Some(message); + break; + } + _ => {} + } + } + if let Some(value) = done.filter(|value| value.finish != Finish::Cancel) { + let delta = drain_utf8(&mut pending_bytes, true); + if !delta.is_empty() { + output.push_str(&delta); + if !send_stream_event(&sender, &mut sequence, "response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": 0, "content_index": 0, "delta": delta, "logprobs": []})).await { return; } + } + let completed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let usage = Usage { + input_tokens: value.prompt_tokens, + output_tokens: value.generated, + reasoning_tokens: 0, + cached_tokens: value.reused.unwrap_or(0), + }; + match ResponseTrace::build_with_terminal( + &request, + &[OutputItem::Text { + deltas: vec![output], + }], + usage, + &id, + created_at, + completed_at, + value.finish == Finish::Length, + ) { + Ok(trace) => { + if request.store != Some(false) + && let Some(history) = &history + && let Err(error) = store_response( + history, + &id, + &request.model, + &request.input, + &trace.response, + ) + .await + { + failure = Some(error.to_owned()); + } + if failure.is_none() { + for mut event in trace.events.into_iter().skip(5) { + event["sequence_number"] = json!(sequence); + if sender.send(event).await.is_err() { + return; + } + sequence += 1; + } + return; + } + } + Err(message) => failure = Some(message), + } + } + let message = failure + .unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned()); + let mut failed = pending_response; + failed["status"] = json!("failed"); + failed["error"] = json!({"code": "generation_failed", "message": message}); + let _ = send_stream_event( + &sender, + &mut sequence, + "response.failed", + json!({"response": failed}), + ) + .await; + }); + Sse::new(ResponseEventStream { receiver }) + .keep_alive(crate::native_events::keep_alive()) + .into_response() +} + +// Structured output is withheld until DONE so schema-invalid text cannot be +// mistaken for a successful result by a streaming client. Disconnect still +// drops the live engine receiver immediately. +fn stream_live_buffered( + request: CreateRequest, + tokenizer: Arc, + mut source: mpsc::Receiver>, + history: Option>>, +) -> Response { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let id = format!( + "resp_{:x}_{:x}", + now.as_nanos(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + ); + let created_at = now.as_secs(); + let thinking = reasoning_enabled(&request); + let initial_item = if thinking { + OutputItem::Reasoning { + deltas: vec![], + complete: false, + } + } else { + OutputItem::Text { deltas: vec![] } + }; + let reasoning_id = format!("rs_{}_0", &id[5..]); + // An incomplete trace permits empty text; only its in-progress envelope + // is sent here. Completed output is validated separately below. + let initial = ResponseTrace::build_with_terminal( + &request, + &[initial_item], + Usage { + input_tokens: 0, + output_tokens: 0, + reasoning_tokens: 0, + cached_tokens: 0, + }, + &id, + created_at, + created_at, + true, + ) + .expect("validated structured request has a valid initial envelope"); + let pending = initial.events[0]["response"].clone(); + let (sender, receiver) = mpsc::channel(16); + tokio::spawn(async move { + let mut sequence = 0; + for event in initial + .events + .into_iter() + .take(if thinking { 4 } else { 2 }) + { + if sender.send(event).await.is_err() { + return; + } + sequence += 1; + } + let terminal = [ + tokenizer.special_id("<|im_end|>"), + tokenizer.special_id("<|endoftext|>"), + ]; + let mut reasoning_stream = ReasoningStream::default(); + let mut tokens = Vec::new(); + let mut ended = false; + let mut done = None; + let mut failure = None; + while let Some(event) = tokio::select! { + biased; + _ = sender.closed() => return, + event = source.recv() => event, + } { + match event { + Ok(Event::Token(token)) if !ended => { + if terminal.contains(&Some(token)) { + ended = true; + } else { + if thinking { + let bytes = match tokenizer.decode_bytes(&[token]) { + Ok(bytes) => bytes, + Err(error) => { + failure = Some(error.to_string()); + break; + } + }; + let delta = reasoning_stream.push(&bytes); + if !delta.is_empty() && !send_stream_event(&sender, &mut sequence, "response.reasoning_text.delta", json!({"response_id":id,"item_id":reasoning_id,"output_index":0,"content_index":0,"delta":delta})).await { return; } + } + tokens.push(token); + } + } + Ok(Event::Done(value)) => { + done = Some(value); + break; + } + Ok(Event::Error(message)) | Err(message) => { + failure = Some(message); + break; + } + _ => {} + } + } + if let Some(done) = done.filter(|done| done.finish != Finish::Cancel) { + if thinking && done.finish == Finish::Length { + let delta = reasoning_stream.finish(); + if !delta.is_empty() && !send_stream_event(&sender, &mut sequence, "response.reasoning_text.delta", json!({"response_id":id,"item_id":reasoning_id,"output_index":0,"content_index":0,"delta":delta})).await { return; } + } + let decoded = tokio::task::spawn_blocking(move || { + decode_generation(&tokenizer, &tokens, thinking, done.finish) + }) + .await + .map_err(|e| e.to_string()) + .and_then(|result| result); + let assembled = decoded + .and_then(|output| decoded_items(&request, output, &id)) + .and_then(|(items, reasoning_tokens)| { + ResponseTrace::build_with_terminal( + &request, + &items, + Usage { + input_tokens: done.prompt_tokens, + output_tokens: done.generated, + reasoning_tokens, + cached_tokens: done.reused.unwrap_or(0), + }, + &id, + created_at, + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + done.finish == Finish::Length, + ) + }); + match assembled { + Ok(trace) => { + if request.store != Some(false) + && let Some(history) = &history + && let Err(error) = store_response( + history, + &id, + &request.model, + &request.input, + &trace.response, + ) + .await + { + failure = Some(error.to_owned()); + } + if failure.is_none() { + for mut event in trace.events.into_iter().skip(if thinking { 4 } else { 2 }) + { + if thinking && event["type"] == "response.reasoning_text.delta" { + continue; + } + event["sequence_number"] = json!(sequence); + if sender.send(event).await.is_err() { + return; + } + sequence += 1; + } + return; + } + } + Err(error) => failure = Some(error), + } + } + let mut failed = pending; + failed["status"] = json!("failed"); + failed["error"] = json!({"code":"generation_failed", "message":failure.unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned())}); + let _ = send_stream_event( + &sender, + &mut sequence, + "response.failed", + json!({"response":failed}), + ) + .await; + }); + Sse::new(ResponseEventStream { receiver }) + .keep_alive(crate::native_events::keep_alive()) + .into_response() +} + +struct ToolStream { + sender: mpsc::Sender, + sequence: usize, + response_id: String, + items: Vec, +} + +impl ToolStream { + async fn event(&mut self, kind: &'static str, fields: Value) -> Result<(), String> { + if send_stream_event(&self.sender, &mut self.sequence, kind, fields).await { + Ok(()) + } else { + Err("stream client disconnected".into()) + } + } + + async fn text(&mut self, delta: String) -> Result<(), String> { + if !matches!(self.items.last(), Some(OutputItem::Text { .. })) { + let index = self.items.len(); + let item_id = format!("msg_{}_{}", &self.response_id[5..], index); + self.event("response.output_item.added", json!({"response_id":self.response_id,"output_index":index,"item":{"id":item_id,"type":"message","status":"in_progress","role":"assistant","content":[]}})).await?; + self.event("response.content_part.added", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"content_index":0,"part":text_part("")})).await?; + self.items.push(OutputItem::Text { deltas: Vec::new() }); + } + let index = self.items.len() - 1; + let item_id = format!("msg_{}_{}", &self.response_id[5..], index); + if !delta.is_empty() { + self.event("response.output_text.delta", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"content_index":0,"delta":delta,"logprobs":[]})).await?; + if let Some(OutputItem::Text { deltas }) = self.items.last_mut() { + deltas.push(delta); + } + } + Ok(()) + } + + async fn finish_text(&mut self, incomplete: bool) -> Result<(), String> { + let Some(OutputItem::Text { deltas }) = self.items.last() else { + return Ok(()); + }; + let text = deltas.concat(); + let index = self.items.len() - 1; + let item_id = format!("msg_{}_{}", &self.response_id[5..], index); + self.event("response.output_text.done", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"content_index":0,"text":text,"logprobs":[]})).await?; + self.event("response.content_part.done", json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"content_index":0,"part":text_part(&text)})).await?; + self.event("response.output_item.done", json!({"response_id":self.response_id,"output_index":index,"item":{"id":item_id,"type":"message","status":if incomplete { "incomplete" } else { "completed" },"role":"assistant","content":[text_part(&text)]}})).await + } + + async fn segment( + &mut self, + request: &CreateRequest, + segment: Segment, + created_at: u64, + ) -> Result<(), String> { + match segment { + Segment::Text(text) => self.text(text).await, + Segment::Call { name, arguments } => { + request.validate_tool_count( + self.items + .iter() + .filter(|item| matches!(item, OutputItem::FunctionCall { .. })) + .count() + + 1, + )?; + let index = self.items.len(); + let call_id = format!("call_{}_{}", &self.response_id[5..], index); + let arguments = arguments.to_string(); + let item = OutputItem::FunctionCall { + name: name.clone(), + call_id: call_id.clone(), + argument_deltas: vec![arguments.clone()], + }; + // Validate the complete arguments before exposing a callable item to clients. + ResponseTrace::build( + request, + &[item], + Usage { + input_tokens: 0, + output_tokens: 0, + reasoning_tokens: 0, + cached_tokens: 0, + }, + &self.response_id, + created_at, + created_at, + )?; + self.finish_text(false).await?; + let index = self.items.len(); + let catalog = Catalog::new(&request.tools)?; + let custom = catalog.is_custom(&name); + let prefix = if custom { "ctc" } else { "fc" }; + let item_id = format!("{prefix}_{}_{}", &self.response_id[5..], index); + let mut completed = json!({"id":item_id,"type":"function_call","status":"completed","call_id":call_id,"name":name,"arguments":arguments}); + catalog.restore(&mut completed)?; + let mut pending = json!({"id":item_id,"type":"function_call","status":"in_progress","call_id":call_id,"name":name,"arguments":""}); + catalog.restore(&mut pending)?; + self.event( + "response.output_item.added", + json!({"response_id":self.response_id,"output_index":index,"item":pending}), + ) + .await?; + let field = if custom { "input" } else { "arguments" }; + let (delta_event, done_event) = crate::response_tools::input_events(custom); + self.event(delta_event, json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,"delta":completed[field]})).await?; + self.event(done_event, json!({"response_id":self.response_id,"item_id":item_id,"output_index":index,field:completed[field]})).await?; + self.event( + "response.output_item.done", + json!({"response_id":self.response_id,"output_index":index,"item":completed}), + ) + .await?; + self.items.push(OutputItem::FunctionCall { + name, + call_id, + argument_deltas: vec![arguments], + }); + Ok(()) + } + } + } +} + +fn stream_live_tools( + request: CreateRequest, + tokenizer: std::sync::Arc, + mut source: mpsc::Receiver>, + history: Option>>, +) -> Response { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + let id = format!( + "resp_{:x}_{:x}", + now.as_nanos(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + ); + let created_at = now.as_secs(); + let initial = ResponseTrace::build_with_terminal( + &request, + &[OutputItem::Text { deltas: vec![] }], + Usage { + input_tokens: 0, + output_tokens: 0, + reasoning_tokens: 0, + cached_tokens: 0, + }, + &id, + created_at, + created_at, + true, + ) + .expect("validated request has a valid initial trace"); + let pending_response = initial.events[0]["response"].clone(); + let (sender, receiver) = mpsc::channel::(16); + tokio::spawn(async move { + let mut stream = ToolStream { + sender, + sequence: 0, + response_id: id.clone(), + items: Vec::new(), + }; + for event in initial.events.into_iter().take(2) { + if stream.sender.send(event).await.is_err() { + return; + } + stream.sequence += 1; + } + let terminal = [ + tokenizer.special_id("<|im_end|>"), + tokenizer.special_id("<|endoftext|>"), + ]; + let catalog = Catalog::new(&request.tools).expect("validated tools"); + let mut parser = Incremental::new(&catalog.flat); + let mut pending_bytes = Vec::new(); + let mut text_ended = false; + let mut done = None; + let mut failure = None; + while let Some(result) = tokio::select! { + biased; + _ = stream.sender.closed() => return, + result = source.recv() => result, + } { + match result { + Ok(Event::Token(token)) if !text_ended => { + if terminal.contains(&Some(token)) { + text_ended = true; + continue; + } + match tokenizer + .decode_bytes(&[token]) + .map_err(|error| error.to_string()) + { + Ok(bytes) => { + pending_bytes.extend_from_slice(&bytes); + let delta = drain_utf8(&mut pending_bytes, false); + if !delta.is_empty() { + match parser.feed(&delta) { + Ok(segments) => { + for segment in segments { + if let Err(error) = + stream.segment(&request, segment, created_at).await + { + failure = Some(error); + break; + } + } + } + Err(error) => failure = Some(error), + } + } + if failure.is_some() { + break; + } + } + Err(error) => { + failure = Some(error); + break; + } + } + } + Ok(Event::Done(value)) => { + done = Some(value); + break; + } + Ok(Event::Error(message)) | Err(message) => { + failure = Some(message); + break; + } + _ => {} + } + } + if let Some(value) = done.filter(|value| value.finish != Finish::Cancel) { + let remaining = drain_utf8(&mut pending_bytes, true); + let parsed = parser.feed(&remaining).and_then(|mut segments| { + segments.extend(parser.finish()?); + Ok(segments) + }); + match parsed { + Ok(segments) => { + for segment in segments { + if let Err(error) = stream.segment(&request, segment, created_at).await { + failure = Some(error); + break; + } + } + if failure.is_none() { + if stream.items.is_empty() + && let Err(error) = stream.text(String::new()).await + { + failure = Some(error); + } + if failure.is_none() + && let Err(error) = + stream.finish_text(value.finish == Finish::Length).await + { + failure = Some(error); + } + } + if failure.is_none() { + let completed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let usage = Usage { + input_tokens: value.prompt_tokens, + output_tokens: value.generated, + reasoning_tokens: 0, + cached_tokens: value.reused.unwrap_or(0), + }; + match ResponseTrace::build_with_terminal( + &request, + &stream.items, + usage, + &id, + created_at, + completed_at, + value.finish == Finish::Length, + ) { + Ok(trace) => { + if request.store != Some(false) + && let Some(history) = &history + && let Err(error) = store_response( + history, + &id, + &request.model, + &request.input, + &trace.response, + ) + .await + { + failure = Some(error.to_owned()); + } + if failure.is_none() { + let mut terminal = + trace.events.last().expect("trace has terminal").clone(); + terminal["sequence_number"] = json!(stream.sequence); + let _ = stream.sender.send(terminal).await; + return; + } + } + Err(error) => failure = Some(error), + } + } + } + Err(error) => failure = Some(error), + } + } + let message = failure + .unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned()); + let mut failed = pending_response; + failed["status"] = json!("failed"); + failed["error"] = json!({"code":"generation_failed","message":message}); + let _ = stream + .event("response.failed", json!({"response":failed})) + .await; + }); + Sse::new(ResponseEventStream { receiver }) + .keep_alive(crate::native_events::keep_alive()) + .into_response() +} + +struct ResponseEventStream { + receiver: mpsc::Receiver, +} + +impl Stream for ResponseEventStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.receiver).poll_recv(context).map(|item| { + item.map(|value| { + let kind = value["type"].as_str().unwrap_or("error").to_owned(); + Ok(SseEvent::default().event(kind).data(value.to_string())) + }) + }) + } +} + +fn drain_utf8(pending: &mut Vec, finish: bool) -> String { + let mut output = String::new(); + while !pending.is_empty() { + match std::str::from_utf8(pending) { + Ok(text) => { + output.push_str(text); + pending.clear(); + } + Err(error) => { + let valid = error.valid_up_to(); + if valid > 0 { + output.push_str(std::str::from_utf8(&pending[..valid]).expect("UTF-8 prefix")); + pending.drain(..valid); + } + if let Some(invalid) = error.error_len() { + output.push('\u{fffd}'); + pending.drain(..invalid); + } else if finish { + output.push('\u{fffd}'); + pending.clear(); + } else { + break; + } + } + } + } + output +} + +async fn send_stream_event( + sender: &mpsc::Sender, + sequence: &mut usize, + kind: &'static str, + fields: Value, +) -> bool { + let mut value = fields + .as_object() + .cloned() + .expect("event fields are an object"); + value.insert("type".to_owned(), json!(kind)); + value.insert("sequence_number".to_owned(), json!(*sequence)); + *sequence += 1; + sender.send(Value::Object(value)).await.is_ok() +} + +fn validate_live_subset(request: &CreateRequest) -> Result<(), (&'static str, &'static str)> { + if request.tool_choice.as_ref().is_some_and(|choice| { + choice != "auto" + && choice != "none" + && choice != "required" + && choice["type"] != "function" + && choice["type"] != "custom" + && choice["type"] != "allowed_tools" + }) { + return Err(( + "tool_choice", + "only auto, none, required, allowed_tools and forced top-level function/custom choices are connected", + )); + } + if request + .truncation + .as_deref() + .is_some_and(|value| value != "disabled") + { + return Err(("truncation", "automatic truncation is not connected yet")); + } + Ok(()) +} + +fn api_error( + status: StatusCode, + kind: &'static str, + code: &'static str, + param: Option<&'static str>, + message: &str, +) -> Response { + ( + status, + Json(json!({"error": {"message": message, "type": kind, "param": param, "code": code}})), + ) + .into_response() +} + +#[derive(Clone, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum OutputItem { + Reasoning { + deltas: Vec, + complete: bool, + }, + Text { + deltas: Vec, + }, + FunctionCall { + name: String, + call_id: String, + argument_deltas: Vec, + }, +} + +#[derive(Clone, Copy, Deserialize)] +pub struct Usage { + pub input_tokens: u64, + pub output_tokens: u64, + pub reasoning_tokens: u64, + pub cached_tokens: u64, +} + +#[derive(Debug)] +pub struct ResponseTrace { + pub response: Value, + pub events: Vec, +} + +impl ResponseTrace { + pub fn build( + request: &CreateRequest, + items: &[OutputItem], + usage: Usage, + id: &str, + created_at: u64, + completed_at: u64, + ) -> Result { + Self::build_with_terminal(request, items, usage, id, created_at, completed_at, false) + } + + fn build_with_terminal( + request: &CreateRequest, + items: &[OutputItem], + usage: Usage, + id: &str, + created_at: u64, + completed_at: u64, + incomplete: bool, + ) -> Result { + request + .validate() + .map_err(|(param, message)| format!("{param}: {message}"))?; + let mut call_count = 0; + for item in items { + if let OutputItem::FunctionCall { name, .. } = item { + call_count += 1; + request.validate_tool_name(name)?; + } + } + request.validate_tool_count(call_count)?; + if !incomplete && request.tools_required() && call_count == 0 { + return Err("required tool choice produced no tool call".into()); + } + if items.is_empty() { + return Err("a completed response needs an output item".to_owned()); + } + if !id.starts_with("resp_") + || id.len() <= 5 + || !id[5..] + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + || completed_at < created_at + { + return Err("invalid response identity or timestamps".to_owned()); + } + if usage.cached_tokens > usage.input_tokens || usage.reasoning_tokens > usage.output_tokens + { + return Err("usage detail counters exceed their parent count".to_owned()); + } + let text = request + .text + .as_ref() + .map(serde_json::to_value) + .transpose() + .map_err(|error| error.to_string())? + .unwrap_or_else(|| json!({"format": {"type": "text"}})); + let mut response = json!({ + "id": id, + "object": "response", + "created_at": created_at, + "status": "in_progress", + "error": null, + "incomplete_details": null, + "instructions": request.instructions, + "max_output_tokens": request.max_output_tokens, + "model": request.model, + "output": [], + "parallel_tool_calls": request.parallel_tool_calls.unwrap_or(true), + "previous_response_id": request.previous_response_id, + "reasoning": request.reasoning.clone().unwrap_or_else(|| json!({"effort": null, "summary": null})), + "store": request.store.unwrap_or(true), + "temperature": request.temperature.unwrap_or(0.0), + "text": text, + "tool_choice": request.tool_choice.clone().unwrap_or_else(|| json!("auto")), + "tools": request.tools, + "top_p": request.top_p.unwrap_or(1.0), + "truncation": request.truncation.as_deref().unwrap_or("disabled"), + "usage": null, + "user": null, + "metadata": request.metadata.clone().unwrap_or_default(), + }); + let mut emitter = Emitter::default(); + emitter.push("response.created", json!({"response": response})); + emitter.push("response.in_progress", json!({"response": response})); + + let mut output = Vec::with_capacity(items.len()); + let mut all_text = String::new(); + let mut has_text = false; + let mut call_ids = HashSet::new(); + let catalog = Catalog::new(&request.tools)?; + let allowed_tools: HashSet<&str> = catalog + .flat + .iter() + .filter_map(|tool| tool.get("name").and_then(Value::as_str)) + .collect(); + for (index, item) in items.iter().enumerate() { + match item { + OutputItem::Reasoning { deltas, complete } => { + if !complete && !incomplete { + return Err("unfinished reasoning needs an incomplete response".into()); + } + let item_id = format!("rs_{}_{}", &id[5..], index); + let pending = json!({"id":item_id,"type":"reasoning","status":"in_progress","summary":[],"content":[]}); + emitter.push( + "response.output_item.added", + json!({"response_id":id,"output_index":index,"item":pending}), + ); + emitter.push("response.content_part.added", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":{"type":"reasoning_text","text":""}})); + let whole = deltas.concat(); + for delta in deltas { + emitter.push("response.reasoning_text.delta", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"delta":delta})); + } + emitter.push("response.reasoning_text.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"text":whole})); + let part = json!({"type":"reasoning_text","text":whole}); + emitter.push("response.content_part.done", json!({"response_id":id,"item_id":item_id,"output_index":index,"content_index":0,"part":part})); + let done = json!({"id":item_id,"type":"reasoning","status":if *complete {"completed"} else {"incomplete"},"summary":[],"content":[part]}); + emitter.push( + "response.output_item.done", + json!({"response_id":id,"output_index":index,"item":done}), + ); + output.push(done); + } + OutputItem::Text { deltas } => { + has_text = true; + let item_id = format!("msg_{}_{}", &id[5..], index); + let mut whole = String::new(); + let pending = json!({"id": item_id, "type": "message", "status": "in_progress", "role": "assistant", "content": []}); + emitter.push( + "response.output_item.added", + json!({"response_id": id, "output_index": index, "item": pending}), + ); + emitter.push("response.content_part.added", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part("")})); + for delta in deltas { + whole.push_str(delta); + emitter.push("response.output_text.delta", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "delta": delta, "logprobs": []})); + } + all_text.push_str(&whole); + emitter.push("response.output_text.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "text": whole, "logprobs": []})); + emitter.push("response.content_part.done", json!({"response_id": id, "item_id": item_id, "output_index": index, "content_index": 0, "part": text_part(&whole)})); + let item_status = if incomplete { + "incomplete" + } else { + "completed" + }; + let done = json!({"id": item_id, "type": "message", "status": item_status, "role": "assistant", "content": [text_part(&whole)]}); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + OutputItem::FunctionCall { + name, + call_id, + argument_deltas, + } => { + if name.is_empty() || call_id.is_empty() { + return Err("function calls need a name and call_id".to_owned()); + } + if !allowed_tools.contains(name.as_str()) { + return Err(format!("function call names an undeclared tool: {name}")); + } + if !call_ids.insert(call_id) { + return Err("function call_id must be unique".to_owned()); + } + let custom = catalog.is_custom(name); + let prefix = if custom { "ctc" } else { "fc" }; + let item_id = format!("{prefix}_{}_{}", &id[5..], index); + let arguments = argument_deltas.concat(); + let parsed_arguments: Value = serde_json::from_str(&arguments) + .map_err(|_| "function call arguments must be a JSON object")?; + if !parsed_arguments.is_object() { + return Err("function call arguments must be a JSON object".to_owned()); + } + if let Some(schema) = catalog + .flat + .iter() + .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name)) + .and_then(|tool| tool.get("parameters")) + { + reject_remote_refs(schema)?; + let validator = jsonschema::validator_for(schema).map_err(|error| { + format!("invalid function parameter schema: {error}") + })?; + validator.validate(&parsed_arguments).map_err(|error| { + format!("function call arguments violate schema: {error}") + })?; + } + let mut done = json!({"id": item_id, "type": "function_call", "status": "completed", "call_id": call_id, "name": name, "arguments": arguments}); + catalog.restore(&mut done)?; + let field = if custom { "input" } else { "arguments" }; + let (delta_event, done_event) = crate::response_tools::input_events(custom); + let mut pending = done.clone(); + pending["status"] = json!("in_progress"); + pending[field] = json!(""); + emitter.push( + "response.output_item.added", + json!({"response_id":id,"output_index":index,"item":pending}), + ); + let deltas = if custom { + vec![done["input"].as_str().expect("restored input").to_owned()] + } else { + argument_deltas.clone() + }; + for delta in deltas { + emitter.push(delta_event, json!({"response_id":id,"item_id":item_id,"output_index":index,"delta":delta})); + } + emitter.push(done_event, json!({"response_id":id,"item_id":item_id,"output_index":index,field:done[field]})); + emitter.push( + "response.output_item.done", + json!({"response_id": id, "output_index": index, "item": done}), + ); + output.push(done); + } + } + } + + if has_text && !incomplete { + validate_text_format(request, &all_text)?; + } + let total_tokens = usage + .input_tokens + .checked_add(usage.output_tokens) + .ok_or("total token count overflows u64")?; + + response["status"] = json!(if incomplete { + "incomplete" + } else { + "completed" + }); + if incomplete { + response["incomplete_details"] = json!({"reason": "max_output_tokens"}); + } else { + response["completed_at"] = json!(completed_at); + } + response["output"] = json!(output); + response["usage"] = json!({ + "input_tokens": usage.input_tokens, + "input_tokens_details": {"cached_tokens": usage.cached_tokens}, + "output_tokens": usage.output_tokens, + "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens}, + "total_tokens": total_tokens, + }); + emitter.push( + if incomplete { + "response.incomplete" + } else { + "response.completed" + }, + json!({"response": response}), + ); + Ok(Self { + response, + events: emitter.events, + }) + } + + pub fn sse_frames(&self) -> Vec { + self.events + .iter() + .map(|event| { + format!( + "event: {}\ndata: {}\n\n", + event["type"].as_str().unwrap_or("error"), + event + ) + }) + .collect() + } +} + +fn validate_text_format(request: &CreateRequest, text: &str) -> Result<(), String> { + let Some(options) = &request.text else { + return Ok(()); + }; + match &options.format { + TextFormat::Text => Ok(()), + TextFormat::JsonObject => { + if serde_json::from_str::(text).is_ok_and(|value| value.is_object()) { + Ok(()) + } else { + Err("text.format requires a JSON object".to_owned()) + } + } + TextFormat::JsonSchema { schema, .. } => { + reject_remote_refs(schema)?; + let validator = jsonschema::validator_for(schema) + .map_err(|error| format!("invalid text.format schema: {error}"))?; + let value: Value = serde_json::from_str(text) + .map_err(|error| format!("text.format output is not JSON: {error}"))?; + validator + .validate(&value) + .map_err(|error| format!("text.format output violates schema: {error}")) + } + } +} + +fn reject_remote_refs(value: &Value) -> Result<(), String> { + match value { + Value::Object(fields) => { + for key in ["$ref", "$dynamicRef", "$recursiveRef"] { + if fields + .get(key) + .and_then(Value::as_str) + .is_some_and(|reference| !reference.starts_with('#')) + { + return Err(format!("text.format schema cannot use external {key}")); + } + } + for child in fields.values() { + reject_remote_refs(child)?; + } + } + Value::Array(values) => { + for child in values { + reject_remote_refs(child)?; + } + } + _ => {} + } + Ok(()) +} + +fn text_part(text: &str) -> Value { + json!({"type": "output_text", "text": text, "annotations": [], "logprobs": []}) +} + +#[derive(Default)] +struct Emitter { + events: Vec, +} + +impl Emitter { + fn push(&mut self, kind: &'static str, fields: Value) { + let mut fields = fields + .as_object() + .cloned() + .expect("event fields are an object"); + fields.insert("type".to_owned(), json!(kind)); + fields.insert("sequence_number".to_owned(), json!(self.events.len())); + self.events.push(Value::Object(fields)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{tokenizer::Tokenizer, tokenizer_assets::QWEN35_PATTERN, wire::Done}; + use axum::{body::to_bytes, extract::State}; + use http_body_util::BodyExt; + use std::{fs, sync::Arc}; + use tokio::sync::mpsc; + + fn make_request(extra: Value) -> CreateRequest { + let mut value = json!({"model": "strata-local", "input": "test", "stream": true}); + value + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value(value).unwrap() + } + + fn usage() -> Usage { + Usage { + input_tokens: 7, + output_tokens: 3, + reasoning_tokens: 1, + cached_tokens: 2, + } + } + + #[test] + fn tool_policies_preserve_prompt_history_and_reject_excess_calls() { + let request = make_request(json!({"reasoning":{"effort":"none"},"tools":[ + {"type":"function","name":"lookup","description":"UNIQUE_TOOL_DECLARATION","parameters":{"type":"object"}}, + {"type":"namespace","name":"code","tools":[{"type":"custom","name":"run"}]} + ]})); + let calls = vec![ + OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "c1".into(), + argument_deltas: vec!["{}".into()], + }, + OutputItem::FunctionCall { + name: crate::response_tools::alias("run", Some("code")).unwrap(), + call_id: "c2".into(), + argument_deltas: vec![json!({"input":"print(1)"}).to_string()], + }, + ]; + assert!(ResponseTrace::build(&request, &calls, usage(), "resp_policy", 1, 2).is_ok()); + let mut required = request.clone(); + required.tool_choice = Some(json!("required")); + let text = [OutputItem::Text { + deltas: vec!["OK".into()], + }]; + assert!( + render_request_prompt(&required) + .unwrap() + .contains("Call at least one tool") + ); + assert!(ResponseTrace::build(&required, &calls, usage(), "resp_policy", 1, 2).is_ok()); + assert!(ResponseTrace::build(&required, &text, usage(), "resp_policy", 1, 2).is_err()); + assert!( + ResponseTrace::build_with_terminal( + &required, + &text, + usage(), + "resp_policy", + 1, + 2, + true + ) + .is_ok() + ); + let mut forced = request.clone(); + forced.tool_choice = Some(json!({"type":"function", "name":"lookup"})); + assert!( + render_request_prompt(&forced) + .unwrap() + .contains("Call exactly one function in this response: lookup.") + ); + assert!(ResponseTrace::build(&forced, &calls[..1], usage(), "resp_policy", 1, 2).is_ok()); + assert!(ResponseTrace::build(&forced, &calls[1..], usage(), "resp_policy", 1, 2).is_err()); + assert!(ResponseTrace::build(&forced, &calls, usage(), "resp_policy", 1, 2).is_err()); + assert!(ResponseTrace::build(&forced, &text, usage(), "resp_policy", 1, 2).is_err()); + assert!( + ResponseTrace::build_with_terminal(&forced, &text, usage(), "resp_policy", 1, 2, true) + .is_ok() + ); + let mut single = request.clone(); + single.parallel_tool_calls = Some(false); + assert!( + render_request_prompt(&single) + .unwrap() + .contains("Use at most one tool call") + ); + assert!(ResponseTrace::build(&single, &calls, usage(), "resp_policy", 1, 2).is_err()); + for call in &calls { + assert!( + ResponseTrace::build( + &single, + std::slice::from_ref(call), + usage(), + "resp_policy", + 1, + 2 + ) + .is_ok() + ); + } + let mut disabled = request.clone(); + disabled.tool_choice = Some(json!("none")); + validate_live_subset(&disabled).unwrap(); + let mut no_tools = disabled.clone(); + no_tools.tools.clear(); + assert_eq!( + render_request_prompt(&disabled).unwrap(), + render_request_prompt(&no_tools).unwrap() + ); + assert!( + !render_request_prompt(&disabled) + .unwrap() + .contains("UNIQUE_TOOL_DECLARATION") + ); + assert!( + ResponseTrace::build(&disabled, &calls[..1], usage(), "resp_policy", 1, 2).is_err() + ); + disabled.input = json!([ + {"role":"user","content":"Look up a value"}, + {"type":"function_call","name":"lookup","call_id":"old","arguments":"{}"}, + {"type":"function_call_output","call_id":"old","output":"EXACT_RESULT"} + ]); + let prompt = render_request_prompt(&disabled).unwrap(); + assert!(prompt.contains("") && prompt.contains("EXACT_RESULT")); + assert!(!prompt.contains("UNIQUE_TOOL_DECLARATION")); + let trace = ResponseTrace::build( + &disabled, + &[OutputItem::Text { + deltas: vec!["OK".into()], + }], + usage(), + "resp_policy", + 1, + 2, + ) + .unwrap(); + assert_eq!(trace.response["tool_choice"], "none"); + assert_eq!(trace.response["tools"], json!(disabled.tools)); + disabled.tools = vec![json!({"type":"custom","name":"bad name"})]; + assert!(disabled.validate().is_err()); + } + + #[test] + fn allowed_tools_preserves_catalog_and_history_but_gates_new_calls() { + let request = make_request(json!({ + "tools":[ + {"type":"function","name":"lookup","description":"UNIQUE_LOOKUP_DECLARATION","parameters":{"type":"object"}}, + {"type":"custom","name":"patch"} + ], + "tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"custom","name":"patch"}]}, + "input":[ + {"role":"user","content":"Look up a value"}, + {"type":"function_call","name":"lookup","call_id":"old","arguments":"{}"}, + {"type":"function_call_output","call_id":"old","output":"OLD_RESULT"} + ] + })); + request.validate().unwrap(); + validate_live_subset(&request).unwrap(); + let prompt = render_request_prompt(&request).unwrap(); + assert!(prompt.contains("UNIQUE_LOOKUP_DECLARATION")); + assert!(prompt.contains("") && prompt.contains("OLD_RESULT")); + assert!( + prompt.contains("Only these tools may be called") + && prompt.contains("Call at least one tool") + ); + let text = [OutputItem::Text { + deltas: vec!["OK".into()], + }]; + assert!(ResponseTrace::build(&request, &text, usage(), "resp_subset", 1, 2).is_err()); + let old_name = [OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "new".into(), + argument_deltas: vec!["{}".into()], + }]; + assert!(ResponseTrace::build(&request, &old_name, usage(), "resp_subset", 1, 2).is_err()); + let accepted = [OutputItem::FunctionCall { + name: "patch".into(), + call_id: "new".into(), + argument_deltas: vec![json!({"input":" keep\n\tbytes "}).to_string()], + }]; + let result = ResponseTrace::build(&request, &accepted, usage(), "resp_subset", 1, 2) + .unwrap() + .response; + assert_eq!(result["tools"], json!(request.tools)); + assert_eq!(result["tool_choice"], json!(request.tool_choice)); + assert_eq!(result["output"][0]["input"], " keep\n\tbytes "); + let mut empty = request; + empty.tools.clear(); + empty.input = json!("Only text"); + empty.tool_choice = Some(json!({"type":"allowed_tools","mode":"auto","tools":[]})); + assert!(ResponseTrace::build(&empty, &text, usage(), "resp_subset", 1, 2).is_ok()); + } + + #[test] + fn forced_custom_preserves_input_and_enforces_declared_kind() { + let mut request = make_request(json!({ + "tools":[{"type":"custom","name":"patch","format":{"type":"text"}}], + "tool_choice":{"type":"custom","name":"patch"} + })); + request.validate().unwrap(); + validate_live_subset(&request).unwrap(); + assert!(render_request_prompt(&request).unwrap().contains( + "Call exactly one custom tool in this response: patch. Do not call any other tool." + )); + let input = " Привіт 🌍\n\ttext\n "; + let calls = [OutputItem::FunctionCall { + name: "patch".into(), + call_id: "custom1".into(), + argument_deltas: vec![json!({"input":input}).to_string()], + }]; + let trace = ResponseTrace::build(&request, &calls, usage(), "resp_custom", 1, 2).unwrap(); + assert_eq!(trace.response["output"][0]["type"], "custom_tool_call"); + assert_eq!(trace.response["output"][0]["input"], input); + assert_eq!(trace.response["output"][0]["call_id"], "custom1"); + for choice in [ + json!({"type":"function","name":"patch"}), + json!({"type":"custom","name":"missing"}), + json!({"type":"custom","name":"patch","namespace":"ns"}), + json!({"type":"custom"}), + ] { + request.tool_choice = Some(choice); + assert_eq!(request.validate().unwrap_err().0, "tool_choice"); + } + } + + #[tokio::test] + async fn console_envelope_namespaced_calls_preserve_identity_and_replay() { + let request = make_request(json!({ + "include":["reasoning.encrypted_content"], "client_metadata":{"session_id":"fixture"}, + "prompt_cache_key":"fixture", "store":false, "parallel_tool_calls":true, + "tool_choice":"auto", "reasoning":{"effort":"none"}, + "tools":[{"type":"namespace","name":"files","tools":[ + {"type":"function","name":"read","parameters":{"type":"object", + "properties":{"path":{"type":"string"}},"required":["path"],"additionalProperties":false}} + ]},{"type":"function","name":"read","parameters":{"type":"object"}}] + })); + request.validate().unwrap(); + let alias = crate::response_tools::alias("read", Some("files")).unwrap(); + let prompt = render_request_prompt(&request).unwrap(); + assert!(prompt.contains(&alias)); + assert!(prompt.contains("files.read")); + let markup = format!( + "\n\n\nanswer.txt\n\n\n" + ); + let items = parse_output_items(&request, markup.clone(), "resp_console").unwrap(); + let trace = ResponseTrace::build(&request, &items, usage(), "resp_console", 1, 2).unwrap(); + let output = trace.response["output"][0].clone(); + assert_eq!(output["name"], "read"); + assert_eq!(output["namespace"], "files"); + let mut replay = request.clone(); + replay.input = json!([{"role":"user","content":"Read the file"},output, + {"type":"function_call_output","call_id":output["call_id"],"output":[{"type":"input_text","text":"42"},{"type":"input_text","text":"verified"}]}]); + let replayed = render_request_prompt(&replay).unwrap(); + assert!(replayed.contains(&markup)); + assert!(replayed.contains("42\nverified")); + let (tokenizer, root) = test_tokenizer(); + let (sender, source) = mpsc::channel(4096); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + for id in tokenizer.encode(&markup, false).unwrap() { + sender.send(Ok(Event::Token(id))).await.unwrap(); + } + // Inspect the real incremental path before DONE, where callable items escape. + loop { + let frame = tokio::time::timeout(std::time::Duration::from_secs(2), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event = parse_sse(&frame.into_data().unwrap()); + if event["type"] == "response.output_item.done" { + assert_eq!(event["item"]["name"], "read"); + assert_eq!(event["item"]["namespace"], "files"); + assert_eq!(event["item"]["arguments"], "{\"path\":\"answer.txt\"}"); + break; + } + } + drop(body); + sender.closed().await; + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn custom_text_tools_preserve_input_events_namespaces_and_replay() { + let input = "\n print(\"Привіт 🌍\")\n # braces {} and tabs\t\n"; + for format in [None, Some(json!({"type":"text"}))] { + let mut tool = json!({"type":"custom","name":"run","description":"Run source text"}); + if let Some(format) = format { + tool["format"] = format; + } + let request = + make_request(json!({"tools":[{"type":"namespace","name":"code","tools":[tool]}]})); + request.validate().unwrap(); + let alias = crate::response_tools::alias("run", Some("code")).unwrap(); + let markup = format!( + "\n\n\n{input}\n\n\n" + ); + let items = parse_output_items(&request, markup.clone(), "resp_custom").unwrap(); + let trace = + ResponseTrace::build(&request, &items, usage(), "resp_custom", 1, 2).unwrap(); + let call = trace.response["output"][0].clone(); + assert_eq!(call["type"], "custom_tool_call"); + assert_eq!(call["name"], "run"); + assert_eq!(call["namespace"], "code"); + assert_eq!(call["input"], input); + assert!(call.get("arguments").is_none()); + assert!(call["id"].as_str().unwrap().starts_with("ctc_")); + let deltas = trace + .events + .iter() + .filter(|e| e["type"] == "response.custom_tool_call_input.delta") + .map(|e| e["delta"].as_str().unwrap()) + .collect::(); + assert_eq!(deltas, input); + let done = trace + .events + .iter() + .find(|e| e["type"] == "response.custom_tool_call_input.done") + .unwrap(); + assert_eq!(done["input"], input); + assert!(done.get("arguments").is_none()); + assert!(trace.events.iter().all(|e| { + !e["type"] + .as_str() + .unwrap() + .contains("function_call_arguments") + })); + let mut replay = request.clone(); + replay.input = json!([{"role":"user","content":"Run code"},call, + {"type":"custom_tool_call_output","call_id":call["call_id"],"output":[{"type":"input_text","text":"ok"}]}]); + assert!(render_request_prompt(&replay).unwrap().contains(&markup)); + replay.input[2]["type"] = json!("function_call_output"); + assert!(render_request_prompt(&replay).unwrap_err().contains("kind")); + } + } + + #[test] + fn custom_tools_fail_closed_on_grammar_bad_envelopes_and_mixed_output_kinds() { + for tool in [ + json!({"type":"custom","name":"run","format":{"type":"grammar","syntax":"lark","definition":"start: WORD"}}), + json!({"type":"custom","name":"run","format":{"type":"text","syntax":"ignored"}}), + json!({"type":"custom","name":"run","parameters":{"type":"object"}}), + json!({"type":"custom","name":"run","description":12}), + ] { + assert!(make_request(json!({"tools":[tool]})).validate().is_err()); + } + let request = make_request(json!({"tools":[{"type":"custom","name":"run"}]})); + for arguments in [ + json!({}), + json!({"input":12}), + json!({"input":"x","extra":"discard me"}), + ] { + let item = OutputItem::FunctionCall { + name: "run".into(), + call_id: "c".into(), + argument_deltas: vec![arguments.to_string()], + }; + assert!(ResponseTrace::build(&request, &[item], usage(), "resp_bad", 1, 2).is_err()); + } + let mut replay = make_request(json!({"input":[ + {"type":"custom_tool_call","call_id":"c","name":"run","input":"print(1)"}, + {"type":"function_call","call_id":"f","name":"read","arguments":"{}"}, + {"type":"function_call_output","call_id":"f","output":"file"}, + {"type":"custom_tool_call_output","call_id":"c","output":"1"} + ]})); + let original = render_request_prompt(&replay).unwrap(); + replay.input.as_array_mut().unwrap().swap(2, 3); + assert_eq!(render_request_prompt(&replay).unwrap(), original); + replay.input[2]["type"] = json!("function_call_output"); + assert!(render_request_prompt(&replay).is_err()); + } + + #[tokio::test] + async fn custom_live_stream_emits_plain_input_before_done_and_preserves_terminal() { + let (tokenizer, root) = test_tokenizer(); + let (sender, source) = mpsc::channel(4096); + let request = make_request( + json!({"reasoning":{"effort":"none"},"tools":[{"type":"custom","name":"run"}]}), + ); + let input = " print(\"🌍\")\n"; + let markup = format!( + "\n\n\n{input}\n\n\n" + ); + let ids = tokenizer.encode(&markup, false).unwrap(); + let generated = ids.len() as u64; + let mut body = stream_live_text(request, tokenizer, source, None).into_body(); + for id in ids { + sender.send(Ok(Event::Token(id))).await.unwrap(); + } + let mut events = Vec::new(); + loop { + let frame = tokio::time::timeout(std::time::Duration::from_secs(2), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event = parse_sse(&frame.into_data().unwrap()); + let done = event["type"] == "response.output_item.done"; + events.push(event); + if done { + break; + } + } + let item = events.last().unwrap()["item"].clone(); + assert_eq!(item["type"], "custom_tool_call"); + assert_eq!(item["input"], input); + assert!(events.iter().any(|e| e["type"] == "response.custom_tool_call_input.done" && e["input"] == input)); + assert_eq!( + events + .iter() + .filter(|e| e["type"] == "response.custom_tool_call_input.delta") + .map(|e| e["delta"].as_str().unwrap()) + .collect::(), + input + ); + assert!(!events.iter().any(|e| { + e["type"] + .as_str() + .unwrap() + .contains("function_call_arguments") + })); + let Event::Done(mut done) = crate::wire::parse_line("DONE 1 7 1.0 2.0 stop") + .unwrap() + .unwrap() + else { + panic!() + }; + done.generated = generated; + sender.send(Ok(Event::Done(done))).await.unwrap(); + drop(sender); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + let terminal = events.last().unwrap(); + assert_eq!(terminal["type"], "response.completed"); + assert_eq!(terminal["response"]["output"][0], item); + for (index, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], index); + } + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn response_reports_the_engines_greedy_default_sampling() { + for (extra, temperature) in [(json!({}), 0.0), (json!({"temperature":0.6}), 0.6)] { + let request = make_request(extra); + let trace = ResponseTrace::build( + &request, + &[OutputItem::Text { + deltas: vec!["OK".into()], + }], + usage(), + "resp_sampling", + 1, + 2, + ) + .unwrap(); + assert_eq!(trace.response["temperature"], temperature); + } + } + + #[test] + fn parallel_results_replay_by_call_identity_not_arrival_order() { + let mut request = make_request(json!({"input":[ + {"role":"user","content":"Temperature in Oslo and Paris?"}, + {"type":"function_call","call_id":"oslo","name":"lookup","arguments":"{\"city\":\"Oslo\"}"}, + {"type":"function_call","call_id":"paris","name":"lookup","arguments":"{\"city\":\"Paris\"}"}, + {"type":"function_call_output","call_id":"oslo","output":"3°C"}, + {"type":"function_call_output","call_id":"paris","output":"17°C"} + ]})); + let ordered = render_request_prompt(&request).unwrap(); + request.input.as_array_mut().unwrap().swap(3, 4); + let reversed = render_request_prompt(&request).unwrap(); + assert_eq!( + ordered, reversed, + "arrival order must not swap city temperatures" + ); + assert!(reversed.contains( + "\n3°C\n\n\n17°C\n" + )); + } + + #[test] + fn commentary_reasoning_and_tools_match_pinned_template_as_one_assistant_turn() { + let golden: Value = serde_json::from_str(include_str!( + "../../benchmarks/fixtures/responses/commentary-tool-prompt.json" + )) + .unwrap(); + let request: CreateRequest = serde_json::from_value(golden["request"].clone()).unwrap(); + assert_eq!(render_request_prompt(&request).unwrap(), golden["rendered"]); + } + + #[test] + fn console_late_approval_instructions_retain_authority_and_content() { + let request = make_request(json!({"instructions":"Initial instructions", "input":[ + {"role":"user","content":"Review the proposed read"}, + {"role":"developer","content":"Apply the approval criteria strictly"}, + {"role":"developer","content":"Return the structured decision"} + ]})); + let rendered = render_request_prompt(&request).unwrap(); + let expected = prompt::render( + &[ + Message { + role: Role::System, + content: "Initial instructions", + reasoning: None, + }, + Message { + role: Role::Developer, + content: "Apply the approval criteria strictly", + reasoning: None, + }, + Message { + role: Role::Developer, + content: "Return the structured decision", + reasoning: None, + }, + Message { + role: Role::User, + content: "Review the proposed read", + reasoning: None, + }, + ], + Effort::XHigh, + ) + .unwrap(); + assert_eq!(rendered, expected); + } + + #[test] + fn console_tool_catalog_rejects_collisions_and_unknown_features() { + for tools in [ + json!([{"type":"namespace","name":"files","tools":[{"type":"function","name":"read"},{"type":"function","name":"read"}]}]), + json!([{"type":"namespace","name":"files","tools":[{"type":"namespace","name":"nested","tools":[]}]}]), + json!([{"type":"web_search"}]), + ] { + assert!(make_request(json!({"tools":tools})).validate().is_err()); + } + let alias = crate::response_tools::alias("read", Some("files")).unwrap(); + let collision = make_request(json!({"tools":[{"type":"function","name":alias}, + {"type":"namespace","name":"files","tools":[{"type":"function","name":"read"}]}]})); + assert!(collision.validate().is_err()); + assert!( + make_request(json!({"include":["unsupported"]})) + .validate() + .is_err() + ); + } + + #[test] + fn input_items_paginate_without_mutating_prompt_history() { + let mut history = ResponseHistory::default(); + let input = json!([ + {"role":"user","content":"exact text"}, + {"type":"function_call","id":"client_id","call_id":"call_exact","namespace":"files","name":"read","arguments":"{\"x\": 1}"}, + {"type":"function_call_output","id":"client_id","call_id":"call_exact","output":"exact result"} + ]); + let response = json!({"id":"resp_page","model":"model","output":[{"type":"message","role":"assistant","content":"new answer"}]}); + history + .insert("resp_page", "model", &input, &response) + .unwrap(); + let entry = &history.entries["resp_page"]; + let original = entry.transcript.clone(); + let desc = entry + .input_page("resp_page", &InputItemsQuery::default()) + .unwrap(); + assert_eq!(desc["data"].as_array().unwrap().len(), 3); + assert_eq!(desc["data"][0]["output"], "exact result"); + assert_eq!(desc["data"][1]["arguments"], "{\"x\": 1}"); + assert_eq!(desc["data"][1]["namespace"], "files"); + assert_eq!(desc["data"][1]["call_id"], "call_exact"); + assert_ne!(desc["data"][0]["id"], desc["data"][1]["id"]); + let first = entry + .input_page( + "resp_page", + &InputItemsQuery::parse(Some("order=asc&limit=1")).unwrap(), + ) + .unwrap(); + assert_eq!(first["data"][0]["content"][0]["text"], "exact text"); + assert_eq!(first["has_more"], true); + let after = first["last_id"].as_str().unwrap(); + let page = entry + .input_page( + "resp_page", + &InputItemsQuery::parse(Some(&format!("order=asc&after={after}"))).unwrap(), + ) + .unwrap(); + assert_eq!(page["data"].as_array().unwrap().len(), 2); + assert_eq!(page["has_more"], false); + let empty = entry + .input_page( + "resp_page", + &InputItemsQuery::parse(Some(&format!("after={after}"))).unwrap(), + ) + .unwrap(); + assert_eq!(empty["data"], json!([])); + assert!(empty["first_id"].is_null() && empty["last_id"].is_null()); + assert_eq!(empty["has_more"], false); + for cursor in [ + "input_resp_other_0", + "input_resp_page_3", + "input_resp_page_00", + ] { + assert!( + entry + .input_page( + "resp_page", + &InputItemsQuery::parse(Some(&format!("after={cursor}"))).unwrap() + ) + .is_err() + ); + } + assert_eq!(entry.transcript, original); + assert_eq!(entry.response, response); + } + + #[test] + fn input_items_query_rejects_ambiguous_or_unsupported_options() { + for query in [ + "limit=0", + "limit=101", + "limit=-1", + "limit=x", + "limit=1&limit=2", + "order=asc&order=desc", + "order=ASC", + "after=", + "after=a&after=b", + "include=reasoning.encrypted_content", + "stream=true", + ] { + assert!(InputItemsQuery::parse(Some(query)).is_err(), "{query}"); + } + for query in [ + "", + "limit=100", + "order=desc", + "order=asc&limit=1&after=input_resp_0", + ] { + assert!(InputItemsQuery::parse(Some(query)).is_ok(), "{query}"); + } + } + + #[cfg(unix)] + #[test] + fn durable_history_roundtrip_delete_eviction_and_faults() { + use std::os::unix::fs::PermissionsExt; + let root = std::env::temp_dir().join(format!( + "strata-durable-{}-{}", + std::process::id(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + )); + let mut history = ResponseHistory::open(Some(&root)).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + let input = json!([{"role":"user","content":"exact"}, + {"type":"custom_tool_call","call_id":"call_x","namespace":"files","name":"run","input":"a\nb"}, + {"type":"custom_tool_call_output","call_id":"call_x","output":"done"}]); + for i in 0..65 { + let id = format!("resp_{i}"); + history.insert(&id, "model", &input, &json!({"id":id,"model":"model", + "object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":"A"}]})).unwrap(); + } + let before = history.entries["resp_64"].response.clone(); + assert!(history.delete_committed("resp_1").unwrap()); + drop(history); + let mut history = ResponseHistory::open(Some(&root)).unwrap(); + assert_eq!(history.entries.len(), 63); + assert!(history.get("resp_0", "model").is_none()); + assert!(history.get("resp_1", "model").is_none()); + assert!(history.get("resp_64", "other-model").is_none()); + assert_eq!(history.entries["resp_64"].response, before); + assert_eq!( + &history.entries["resp_64"].transcript[..3], + input.as_array().unwrap() + ); + let committed = std::fs::read(root.join("history-v1.json")).unwrap(); + // A non-file destination fails closed without mutating memory or committed bytes. + std::fs::create_dir(root.join("history-v1.pending")).unwrap(); + assert!(history.delete_committed("resp_64").is_err()); + assert!(history.get("resp_64", "model").is_some()); + assert_eq!( + std::fs::read(root.join("history-v1.json")).unwrap(), + committed + ); + std::fs::remove_dir(root.join("history-v1.pending")).unwrap(); + assert!(history.delete_committed("resp_64").is_err()); // failed store stays fenced + drop(history); + let snapshot = root.join("history-v1.json"); + for corruption in [b"{".to_vec(), b"{\"schema\":2,\"entries\":[]}".to_vec()] { + std::fs::write(&snapshot, &corruption).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + assert_eq!(std::fs::read(&snapshot).unwrap(), corruption); + } + std::fs::write(&snapshot, &committed).unwrap(); + let mut forged: Value = serde_json::from_slice(&committed).unwrap(); + forged["entries"][0]["input_len"] = json!(999999); + std::fs::write(&snapshot, serde_json::to_vec(&forged).unwrap()).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::write(&snapshot, &committed).unwrap(); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o600)).unwrap(); + let history = ResponseHistory::open(Some(&root)).unwrap(); + assert_eq!(history.entries["resp_64"].response, before); + drop(history); + let link = root.with_extension("symlink"); + std::os::unix::fs::symlink(&root, &link).unwrap(); + assert!(ResponseHistory::open(Some(&link)).is_err()); + std::fs::remove_file(link).unwrap(); + let file = std::fs::OpenOptions::new() + .write(true) + .open(&snapshot) + .unwrap(); + file.set_len(crate::history_store::MAX_SNAPSHOT_BYTES + 1) + .unwrap(); + drop(file); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::remove_file(&snapshot).unwrap(); + std::os::unix::fs::symlink("missing", &snapshot).unwrap(); + assert!(ResponseHistory::open(Some(&root)).is_err()); + std::fs::remove_file(&snapshot).unwrap(); + std::fs::write(&snapshot, &committed).unwrap(); + std::fs::set_permissions(&snapshot, std::fs::Permissions::from_mode(0o600)).unwrap(); + // Interrupted unpublished data is never replayed. + let stage = root.join("history-v1.pending"); + std::fs::write(&stage, "incomplete").unwrap(); + std::fs::set_permissions(&stage, std::fs::Permissions::from_mode(0o600)).unwrap(); + let history = ResponseHistory::open(Some(&root)).unwrap(); + assert!(!stage.exists()); + assert_eq!(history.entries["resp_64"].response, before); + drop(history); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn history_counts_response_and_transcript_and_reclaims_deleted_entries() { + let mut history = ResponseHistory::default(); + let first = json!({"id":"resp_a","model":"model","output":[],"metadata":{"tag":"kept"}}); + let input = json!("hi"); + history.insert("resp_a", "model", &input, &first).unwrap(); + let expected = serde_json::to_vec(&json!([{"role":"user","content":"hi"}])) + .unwrap() + .len() + + serde_json::to_vec(&first).unwrap().len(); + assert_eq!(history.bytes, expected); + assert_eq!(history.entries["resp_a"].response, first); + let second = json!({"id":"resp_b", "model":"model","output":[],"metadata":{"tag":"kept"}}); + assert!( + history + .insert_with_limit("resp_b", "model", &input, &second, expected - 1) + .is_err() + ); + assert!(history.get("resp_a", "model").is_some()); + history + .insert_with_limit("resp_b", "model", &input, &second, expected) + .unwrap(); + assert!(history.get("resp_a", "model").is_none()); + assert!(history.remove("resp_b")); + assert!(!history.remove("resp_b")); + assert_eq!(history.bytes, 0); + assert!(history.order.is_empty() && history.entries.is_empty()); + assert!(history.insert("wrong", "model", &input, &first).is_err()); + } + + #[test] + fn bounded_history_evicts_oldest_response() { + let mut history = ResponseHistory::default(); + for index in 0..=MAX_STORED_RESPONSES { + history + .insert( + &format!("resp_{index}"), + "model", + &json!("hi"), + &json!({"id":format!("resp_{index}"),"model":"model","output":[]}), + ) + .unwrap(); + } + assert_eq!(history.entries.len(), MAX_STORED_RESPONSES); + assert!(history.get("resp_0", "model").is_none()); + assert!(history.get("resp_1", "other-model").is_none()); + assert!(history.get("resp_1", "model").is_some()); + } + + #[tokio::test] + async fn input_count_requires_tokenizer_but_not_worker_or_generation_channel() { + let state = AppState::default(); + let body = json!({"model":"fixture", "input":"Hello", "reasoning":{"effort":"none"}}); + let missing = count_input_tokens(State(state.clone()), Ok(Json(body.clone()))).await; + assert_eq!(missing.status(), StatusCode::NOT_IMPLEMENTED); + let (tokenizer, root) = test_tokenizer(); + let state = AppState { + tokenizer: Some(tokenizer), + ..state + }; + let response = count_input_tokens(State(state.clone()), Ok(Json(body))).await; + assert_eq!(response.status(), StatusCode::OK); + let value: Value = + serde_json::from_slice(&to_bytes(response.into_body(), 4096).await.unwrap()).unwrap(); + assert_eq!(value["object"], "response.input_tokens"); + assert!(value["input_tokens"].as_u64().unwrap() > 0); + assert!(state.response_history.read().await.entries.is_empty()); + assert_eq!(state.lifecycle.snapshot().generation_jobs, 0); + fs::remove_dir_all(root).unwrap(); + } + + fn test_tokenizer() -> (Arc, std::path::PathBuf) { + let root = std::env::temp_dir().join(format!( + "strata-response-preview-{}-{}", + std::process::id(), + NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&root).unwrap(); + let mut vocabulary = Map::new(); + for (id, ch) in crate::tokenizer::byte_alphabet().0.iter().enumerate() { + vocabulary.insert(ch.to_string(), json!(id)); + } + for (offset, token) in ["<|im_start|>", "<|im_end|>", "", ""] + .iter() + .enumerate() + { + vocabulary.insert((*token).into(), json!(256 + offset)); + } + fs::write( + root.join("vocab.json"), + serde_json::to_vec(&vocabulary).unwrap(), + ) + .unwrap(); + fs::write(root.join("merges.txt"), "").unwrap(); + let mut token_types = vec![1u8; 260]; + token_types[256..].fill(3); + fs::write( + root.join("token_type.json"), + serde_json::to_vec(&token_types).unwrap(), + ) + .unwrap(); + fs::write( + root.join("tokenizer.json"), + serde_json::to_vec(&json!({ + "model": "gpt2", "pre": "qwen35", "vocab_size": 260, + "n_merges": 0, "pre_pattern": QWEN35_PATTERN, + "special_ids": {"tokenizer.ggml.eos_token_id": 257} + })) + .unwrap(), + ) + .unwrap(); + (Arc::new(Tokenizer::from_assets(&root).unwrap()), root) + } + + #[test] + fn replay_preserves_text_and_tool_arguments_and_terminates() { + let request = make_request(json!({"tools": [{"type": "function", "name": "lookup"}]})); + let trace = ResponseTrace::build( + &request, + &[ + OutputItem::Text { + deltas: vec!["Hello".into(), " there".into()], + }, + OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{\"x\":".into(), "1}".into()], + }, + ], + usage(), + "resp_test", + 1, + 2, + ) + .unwrap(); + assert_eq!(trace.response["status"], "completed"); + assert_eq!(trace.response["usage"]["total_tokens"], 10); + assert_eq!( + trace.response["output"][0]["content"][0]["text"], + "Hello there" + ); + assert_eq!(trace.response["output"][1]["arguments"], "{\"x\":1}"); + for (index, event) in trace.events.iter().enumerate() { + assert_eq!(event["sequence_number"], json!(index)); + } + assert_eq!(trace.events.first().unwrap()["type"], "response.created"); + assert_eq!(trace.events.last().unwrap()["type"], "response.completed"); + let frames = trace.sse_frames(); + assert_eq!(frames.len(), trace.events.len()); + assert!( + frames + .last() + .unwrap() + .starts_with("event: response.completed\ndata: ") + ); + assert!(frames.iter().all(|frame| frame.ends_with("\n\n"))); + } + + #[test] + fn structured_output_rejects_invalid_json_and_external_refs() { + let request = make_request( + json!({"text": {"format": {"type": "json_schema", "name": "result", "schema": {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"]}}}}), + ); + let item = OutputItem::Text { + deltas: vec!["{\"ok\":false}".into()], + }; + assert!(ResponseTrace::build(&request, &[item], usage(), "resp_valid", 1, 2).is_ok()); + let item = OutputItem::Text { + deltas: vec!["{\"ok\":1}".into()], + }; + assert!( + ResponseTrace::build(&request, &[item], usage(), "resp_invalid", 1, 2) + .unwrap_err() + .contains("violates schema") + ); + let request = make_request( + json!({"text": {"format": {"type": "json_schema", "name": "result", "schema": {"type": "object", "$ref": "https://example.invalid/schema.json"}}}}), + ); + let item = OutputItem::Text { + deltas: vec!["{}".into()], + }; + assert!( + ResponseTrace::build(&request, &[item], usage(), "resp_remote", 1, 2) + .unwrap_err() + .contains("external $ref") + ); + } + + #[test] + fn token_budget_creates_incomplete_terminal_response() { + let request = make_request(json!({})); + let trace = ResponseTrace::build_with_terminal( + &request, + &[OutputItem::Text { + deltas: vec!["partial".into()], + }], + usage(), + "resp_limited", + 1, + 2, + true, + ) + .unwrap(); + assert_eq!(trace.response["status"], "incomplete"); + assert_eq!( + trace.response["incomplete_details"]["reason"], + "max_output_tokens" + ); + assert_eq!(trace.response["output"][0]["status"], "incomplete"); + assert_eq!(trace.events.last().unwrap()["type"], "response.incomplete"); + } + + #[test] + fn malformed_tool_calls_never_produce_a_completed_trace() { + let request = make_request(json!({"tools": [{"type": "function", "name": "lookup"}]})); + let call = OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{bad".into()], + }; + assert!( + ResponseTrace::build(&request, &[call], usage(), "resp_bad", 1, 2) + .unwrap_err() + .contains("JSON object") + ); + let request = make_request( + json!({"tools": [{"type": "function", "name": "lookup", "parameters": { + "type":"object", "properties":{"n":{"type":"integer"}}, "required":["n"], "additionalProperties":false + }}]}), + ); + let call = OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_2".into(), + argument_deltas: vec!["{\"n\":\"wrong\"}".into()], + }; + assert!( + ResponseTrace::build(&request, &[call], usage(), "resp_bad_schema", 1, 2) + .unwrap_err() + .contains("violate schema") + ); + } + + #[test] + fn function_declarations_reject_ambiguous_names_and_remote_schemas() { + let duplicate = make_request(json!({"tools":[ + {"type":"function","name":"lookup"}, {"type":"function","name":"lookup"} + ]})); + assert!(duplicate.validate().is_err()); + let unsafe_name = + make_request(json!({"tools":[{"type":"function","name":"x>\n"}]})); + assert!(unsafe_name.validate().is_err()); + let remote = make_request( + json!({"tools":[{"type":"function","name":"lookup","parameters":{ + "type":"object","$ref":"https://example.invalid/schema.json" + }}]}), + ); + assert!(remote.validate().is_err()); + } + + #[test] + fn stateless_function_result_replay_keeps_call_ids_and_text() { + let request = make_request(json!({ + "reasoning":{"effort":"none"}, + "input": [ + {"role":"user","content":[{"type":"input_text","text":"Weather in Oslo?"}]}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"city\":\"Oslo\",\"days\":2}"}, + {"type":"function_call_output","call_id":"call_1","output":"{\"temp\":3}"} + ], + "tools": [{"type":"function","name":"lookup"}] + })); + let prompt = render_request_prompt(&request).unwrap(); + assert!(prompt.contains("")); + assert!(prompt.contains("\nOslo\n")); + assert!(prompt.contains("\n2\n")); + assert!(prompt.contains("\n{\"temp\":3}\n")); + assert!(prompt.ends_with("<|im_start|>assistant\n\n\n\n\n")); + let missing = make_request(json!({"input":[ + {"role":"user","content":"Weather?"}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}, + {"type":"function_call_output","call_id":"wrong","output":"x"} + ]})); + assert!( + render_request_prompt(&missing) + .unwrap_err() + .contains("call_id") + ); + } + + #[tokio::test] + async fn endpoint_accepts_stateless_function_result_replay() { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + let prompt = tokenizer.decode(&command.request.token_ids).unwrap(); + assert!(prompt.contains("")); + assert!(prompt.contains("\n3°C\n")); + let prompt_tokens = command.request.token_ids.len() as u64; + let GenerationResult::Buffered(result) = command.result else { + panic!("expected buffered generation"); + }; + result + .send(Ok(vec![ + Event::Token(79), + Event::Token(75), + Event::Done(Done { + generated: 2, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }), + ])) + .unwrap(); + }); + let response = create( + State(state), + Ok(Json(json!({ + "model":"strata-local", "reasoning":{"effort":"none"}, + "input":[ + {"role":"user","content":"Weather?"}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_1","output":"3°C"} + ] + }))), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(body["output"][0]["content"][0]["text"], "OK"); + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn stored_response_id_replays_function_and_custom_calls_into_next_prompt() { + for custom in [false, true] { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let worker = tokio::spawn(async move { + for turn in 0..2 { + let command = received.recv().await.unwrap(); + let prompt = tokenizer.decode(&command.request.token_ids).unwrap(); + if turn == 1 { + assert!(prompt.contains("Weather in Oslo?")); + assert!(prompt.contains("")); + assert!(prompt.contains("\n3°C\n")); + } + let prompt_tokens = command.request.token_ids.len() as u64; + let output = if turn == 0 && custom { + "\n\n\nOslo\n\n\n" + } else if turn == 0 { + "\n\n\nOslo\n\n\n" + } else { + "3°C" + }; + let ids = tokenizer.encode(output, false).unwrap(); + let generated = ids.len() as u64; + let GenerationResult::Buffered(result) = command.result else { + panic!("expected buffered generation"); + }; + let mut events = ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + result.send(Ok(events)).unwrap(); + } + }); + let response = create(State(state.clone()), Ok(Json(json!({ + "model":"strata-local", "reasoning":{"effort":"none"}, + "input":"Weather in Oslo?", + "tools":[if custom { json!({"type":"custom","name":"lookup"}) } else { json!({"type":"function","name":"lookup","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}) }] + })))).await; + assert_eq!(response.status(), StatusCode::OK); + let first: Value = + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()) + .unwrap(); + assert_eq!(first["store"], true); + assert_eq!( + first["output"][0]["type"], + if custom { + "custom_tool_call" + } else { + "function_call" + } + ); + if custom { + assert_eq!(first["output"][0]["input"], "Oslo"); + } + let id = first["id"].as_str().unwrap(); + let call_id = first["output"][0]["call_id"].as_str().unwrap(); + let response = create( + State(state.clone()), + Ok(Json(json!({ + "model":"strata-local", "reasoning":{"effort":"none"}, + "previous_response_id":id, "store":true, + "input":[{"type":if custom { "custom_tool_call_output" } else { "function_call_output" },"call_id":call_id,"output":"3°C"}] + }))), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let second: Value = + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()) + .unwrap(); + assert_eq!(second["previous_response_id"], id); + assert_eq!(second["output"][0]["content"][0]["text"], "3°C"); + let missing = create( + State(state), + Ok(Json(json!({ + "model":"strata-local", "reasoning":{"effort":"none"}, + "previous_response_id":"resp_missing", "input":"next" + }))), + ) + .await; + assert_eq!(missing.status(), StatusCode::NOT_FOUND); + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + + #[test] + fn tool_only_response_can_precede_structured_text() { + let request = make_request(json!({ + "text": {"format": {"type": "json_object"}}, + "tools": [{"type": "function", "name": "lookup"}] + })); + let call = OutputItem::FunctionCall { + name: "lookup".into(), + call_id: "call_1".into(), + argument_deltas: vec!["{}".into()], + }; + assert!(ResponseTrace::build(&request, &[call], usage(), "resp_tool", 1, 2).is_ok()); + } + + #[tokio::test] + async fn endpoint_reports_unavailable_and_missing_adapter_truthfully() { + let state = AppState::default(); + let payload = json!({"model": "strata-local", "input": "Hello"}); + let response = create(State(state.clone()), Ok(Json(payload.clone()))).await; + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["error"]["code"], + "worker_not_ready" + ); + + state.worker.write().await.state = WorkerState::Ready; + let response = create(State(state.clone()), Ok(Json(payload))).await; + assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap()["error"]["code"], + "inference_adapter_missing" + ); + + let response = create( + State(state), + Ok(Json(json!({"model": "", "input": "Hello"}))), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn text_preview_encodes_prompt_and_returns_live_worker_tokens() { + let (tokenizer, root) = test_tokenizer(); + let (sender, mut receiver) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer); + state.generation = Some(sender); + let expected_prompt = prompt::render( + &[Message { + role: Role::User, + content: "Hello", + reasoning: None, + }], + Effort::None, + ) + .unwrap(); + let expected_ids = state + .tokenizer + .as_ref() + .unwrap() + .encode(&expected_prompt, true) + .unwrap(); + let worker = tokio::spawn(async move { + let command: GenerationCommand = receiver.recv().await.unwrap(); + assert_eq!(command.request.token_ids, expected_ids); + let prompt_tokens = command.request.token_ids.len() as u64; + let GenerationResult::Buffered(result) = command.result else { + panic!("expected buffered generation"); + }; + result + .send(Ok(vec![ + Event::Token(79), + Event::Token(75), + Event::Token(257), + Event::Done(Done { + generated: 3, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: Some(0), + expert_hits: None, + expert_lookups: None, + }), + ])) + .unwrap(); + }); + let response = create( + State(state.clone()), + Ok(Json(json!({ + "model": "strata-local", "input": "Hello", "reasoning": {"effort": "none"} + }))), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let response: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(response["status"], "completed"); + assert_eq!(response["output"][0]["content"][0]["text"], "OK"); + assert_eq!(response["usage"]["output_tokens"], 3); + assert!( + state + .response_history + .read() + .await + .get(response["id"].as_str().unwrap(), "strata-local") + .is_some() + ); + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn nonstreaming_tool_call_keeps_typed_arguments() { + let (tokenizer, root) = test_tokenizer(); + let output = "\n\n\nOslo\n\n\n2\n\n\n"; + let output_ids = tokenizer.encode(output, false).unwrap(); + let (commands, mut received) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + let prompt = tokenizer.decode(&command.request.token_ids).unwrap(); + assert!(prompt.contains("# Tools")); + assert!(prompt.contains("lookup")); + let prompt_tokens = command.request.token_ids.len() as u64; + let generated = output_ids.len() as u64; + let mut events = output_ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + let GenerationResult::Buffered(result) = command.result else { + panic!("expected buffered generation"); + }; + result.send(Ok(events)).unwrap(); + }); + let response = create(State(state), Ok(Json(json!({ + "model": "strata-local", "input": "Weather?", "reasoning": {"effort": "none"}, + "tools": [{"type":"function","name":"lookup","description":"Check weather","parameters":{ + "type":"object","properties":{"city":{"type":"string"},"days":{"type":"integer"}} + }}] + })))).await; + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let response: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(response["output"][0]["type"], "function_call"); + assert_eq!(response["output"][0]["name"], "lookup"); + let args: Value = + serde_json::from_str(response["output"][0]["arguments"].as_str().unwrap()).unwrap(); + assert_eq!(args, json!({"city":"Oslo","days":2})); + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn nullable_tool_arguments_agree_across_json_and_live_sse() { + for stream in [false, true] { + for thinking in [false, true] { + for valid in [false, true] { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel::(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let output = format!( + "{}123null\"123\"2", + if thinking { "Think.\n\n" } else { "" } + ); + let mut payload = json!({ + "model":"strata-local", "input":"Lookup", "stream":stream, + "reasoning":{"effort":if thinking { "low" } else { "none" }}, + "tools":[{"type":"function","name":"lookup","parameters":{ + "type":"object","properties":{ + "id":{"type":["string","null"],"enum":[if valid { "123" } else { "456" },null]}, + "empty":{"type":["string","null"]}, + "quoted":{"type":["string","null"]}, + "days":{"type":"integer"} + },"required":["id","empty","quoted","days"],"additionalProperties":false + }}],"store":false + }); + // Streaming is transport only; neither mode rewrites the schema/prompt. + payload["stream"] = json!(false); + let expected_prompt = + render_request_prompt(&serde_json::from_value(payload.clone()).unwrap()) + .unwrap(); + payload["stream"] = json!(stream); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + assert_eq!( + tokenizer.decode(&command.request.token_ids).unwrap(), + expected_prompt + ); + let ids = tokenizer.encode(&output, false).unwrap(); + let generated = ids.len() as u64; + let mut events = ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens: command.request.token_ids.len() as u64, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + match command.result { + GenerationResult::Buffered(sender) => { + sender.send(Ok(events)).unwrap(); + } + GenerationResult::Streaming(sender) => { + for event in events { + // Early validation failure may close the generation receiver. + if sender.send(Ok(event)).await.is_err() { + break; + } + } + } + GenerationResult::Finished => panic!("unexpected finished command"), + } + }); + let response = create(State(state), Ok(Json(payload))).await; + let expected_args = r#"{"days":2,"empty":null,"id":"123","quoted":"\"123\""}"#; + let final_response = + if stream { + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + for (n, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], n); + } + let terminal = if valid { + "response.completed" + } else { + "response.failed" + }; + assert_eq!(events.last().unwrap()["type"], terminal); + assert_eq!(events.iter().filter(|e| e["type"] == terminal).count(), 1); + let calls = events + .iter() + .filter(|e| e["type"] == "response.function_call_arguments.done") + .collect::>(); + if valid { + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["arguments"], expected_args); + } else { + assert!(calls.is_empty()); + assert!(!events.iter().any(|e| e["type"] + == "response.function_call_arguments.delta" + || (e["type"] == "response.output_item.added" + && e["item"]["type"] == "function_call"))); + } + events.last().unwrap()["response"].clone() + } else { + assert_eq!( + response.status(), + if valid { + StatusCode::OK + } else { + StatusCode::BAD_GATEWAY + } + ); + serde_json::from_slice::( + &to_bytes(response.into_body(), usize::MAX).await.unwrap(), + ) + .unwrap() + }; + if valid { + let calls = final_response["output"] + .as_array() + .unwrap() + .iter() + .filter(|i| i["type"] == "function_call") + .collect::>(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0]["arguments"], expected_args); + } + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + } + } + + #[tokio::test] + async fn streaming_endpoint_sends_text_before_done_and_finishes_in_order() { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer); + state.generation = Some(commands); + let response = create( + State(state.clone()), + Ok(Json(json!({ + "model": "strata-local", "input": "Hello", "stream": true, + "reasoning": {"effort": "none"} + }))), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "text/event-stream"); + let command = received.recv().await.unwrap(); + let prompt_tokens = command.request.token_ids.len() as u64; + let GenerationResult::Streaming(engine_events) = command.result else { + panic!("expected streaming generation"); + }; + let mut body = response.into_body(); + let mut observed = Vec::new(); + for _ in 0..4 { + let frame = body.frame().await.unwrap().unwrap().into_data().unwrap(); + observed.push(parse_sse(&frame)); + } + engine_events.send(Ok(Event::Token(79))).await.unwrap(); + let early = tokio::time::timeout(std::time::Duration::from_secs(1), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap() + .into_data() + .unwrap(); + let early = parse_sse(&early); + assert_eq!(early["type"], "response.output_text.delta"); + assert_eq!(early["delta"], "O"); + observed.push(early); + engine_events.send(Ok(Event::Token(75))).await.unwrap(); + engine_events + .send(Ok(Event::Done(Done { + generated: 2, + prompt_tokens, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: Some(0), + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(engine_events); + while let Some(frame) = body.frame().await { + observed.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + for (index, event) in observed.iter().enumerate() { + assert_eq!(event["sequence_number"], json!(index)); + } + assert_eq!(observed.first().unwrap()["type"], "response.created"); + let final_event = observed.last().unwrap(); + assert_eq!(final_event["type"], "response.completed"); + assert_eq!( + final_event["response"]["output"][0]["content"][0]["text"], + "OK" + ); + assert!( + state + .response_history + .read() + .await + .get( + final_event["response"]["id"].as_str().unwrap(), + "strata-local" + ) + .is_some() + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn reasoning_marker_and_unicode_split_at_every_byte() { + let input = "Коротка думка\n\n4".as_bytes(); + for split in 0..=input.len() { + let mut stream = ReasoningStream::default(); + let text = stream.push(&input[..split]) + &stream.push(&input[split..]); + assert_eq!(text, "Коротка думка"); + assert!(stream.ended); + assert!(stream.finish().is_empty()); + } + let (tokenizer, root) = test_tokenizer(); + for special in [false, true] { + let ids = tokenizer.encode("Reason.\n\n4", special).unwrap(); + let decoded = decode_generation(&tokenizer, &ids, true, Finish::Stop).unwrap(); + assert_eq!(decoded.reasoning, Some(("Reason.".into(), true))); + assert_eq!(decoded.answer, "4"); + assert_eq!(decoded.reasoning_tokens, if special { 8 } else { 15 }); + } + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn reasoning_effort_uses_pinned_template_and_validates_options() { + let default = make_request(json!({})); + assert_eq!(reasoning_effort(&default).unwrap(), Effort::XHigh); + assert!( + render_request_prompt(&default) + .unwrap() + .ends_with("\n") + ); + for effort in ["none", "low", "medium", "high", "xhigh"] { + let r = make_request(json!({"reasoning":{"effort":effort,"summary":"auto"}})); + assert!(r.validate().is_ok()); + let prompt = render_request_prompt(&r).unwrap(); + assert_eq!(prompt.ends_with("\n\n"), effort == "none"); + if effort == "low" { + assert!(prompt.contains("Keep your thinking brief")); + } + } + for value in [ + json!({"effort":"invalid"}), + json!({"effort":7}), + json!({"summary":"detailed"}), + json!("low"), + ] { + assert!(make_request(json!({"reasoning":value})).validate().is_err()); + } + } + + #[tokio::test] + async fn live_reasoning_routes_separate_content_usage_tools_and_structured_output() { + for stream in [false, true] { + for (answer, finish, expected, structured) in [ + ("Сума.\n\n4", Finish::Stop, "completed", false), + ( + "Сума.\n\n{\"answer\":4}", + Finish::Stop, + "completed", + true, + ), + ( + "Tool.\n\n\n\n\nOslo\n\n\n", + Finish::Stop, + "completed", + false, + ), + ( + "Custom.\n\n\n\n\nOslo\n\n\n", + Finish::Stop, + "completed", + false, + ), + ("Not finished(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + assert!( + tokenizer + .decode(&command.request.token_ids) + .unwrap() + .ends_with("\n") + ); + let generated = ids.len() as u64; + let mut events = ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens: command.request.token_ids.len() as u64, + prompt_ms: 1.0, + decode_ms: 2.0, + finish, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + match command.result { + GenerationResult::Finished => panic!("fixture received finished command"), + GenerationResult::Buffered(sender) => { + sender.send(Ok(events)).unwrap(); + } + GenerationResult::Streaming(sender) => { + for event in events { + sender.send(Ok(event)).await.unwrap(); + } + } + } + }); + let mut payload = json!({"model":"strata-local","input":"Compute","stream":stream,"reasoning":{"effort":"low","summary":"auto"},"tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}); + if answer.starts_with("Custom") { + payload["tools"] = json!([{"type":"custom","name":"lookup"}]); + } + if structured { + payload["text"] = json!({"format":{"type":"json_object"}}); + } + let response = create(State(state.clone()), Ok(Json(payload))).await; + let mut deltas = String::new(); + let final_response = if stream { + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + let event = parse_sse(&frame.unwrap().into_data().unwrap()); + if event["type"] == "response.reasoning_text.delta" { + deltas.push_str(event["delta"].as_str().unwrap()); + } + events.push(event); + } + for (n, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], n); + } + assert_eq!( + events.last().unwrap()["type"], + format!("response.{expected}") + ); + assert_eq!( + events + .iter() + .filter(|e| matches!( + e["type"].as_str(), + Some( + "response.completed" + | "response.incomplete" + | "response.failed" + ) + )) + .count(), + 1 + ); + events.last().unwrap()["response"].clone() + } else { + assert_eq!( + response.status(), + if expected == "failed" { + StatusCode::BAD_GATEWAY + } else { + StatusCode::OK + } + ); + serde_json::from_slice::( + &to_bytes(response.into_body(), usize::MAX).await.unwrap(), + ) + .unwrap() + }; + if expected != "failed" { + let reasoning = &final_response["output"][0]; + assert_eq!(reasoning["type"], "reasoning"); + assert_eq!(reasoning["summary"], json!([])); + let thought = answer.split("").next().unwrap(); + assert_eq!(reasoning["content"][0]["text"], thought); + if stream { + assert_eq!(deltas, thought); + } + let count = + final_response["usage"]["output_tokens_details"]["reasoning_tokens"] + .as_u64() + .unwrap(); + assert_eq!( + count, + if finish == Finish::Length { + answer.len() + } else { + thought.len() + 8 + } as u64 + ); + assert!(count <= final_response["usage"]["output_tokens"].as_u64().unwrap()); + if finish == Finish::Length { + assert_eq!(final_response["output"].as_array().unwrap().len(), 1); + assert_eq!(reasoning["status"], "incomplete"); + } else if answer.starts_with("Custom") { + assert_eq!(final_response["output"][1]["type"], "custom_tool_call"); + assert_eq!(final_response["output"][1]["input"], "Oslo"); + } else if answer.starts_with("Tool") { + assert_eq!(final_response["output"][1]["type"], "function_call"); + } else { + assert_eq!( + final_response["output"][1]["content"][0]["text"], + answer.split("\n\n").nth(1).unwrap() + ); + } + } else { + assert!(state.response_history.read().await.entries.is_empty()); + } + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + } + + #[tokio::test] + async fn reasoning_stream_publishes_thought_before_done_and_keeps_final_separate() { + let (tokenizer, root) = test_tokenizer(); + let (sender, source) = mpsc::channel(128); + let request = make_request(json!({"reasoning":{"effort":"low"}})); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + for _ in 0..4 { + body.frame().await.unwrap().unwrap(); + } + sender.send(Ok(Event::Token(65))).await.unwrap(); + let frame = tokio::time::timeout(std::time::Duration::from_secs(1), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event = parse_sse(&frame.into_data().unwrap()); + assert_eq!(event["type"], "response.reasoning_text.delta"); + assert_eq!(event["delta"], "A"); + for id in tokenizer.encode("\n\n4", false).unwrap() { + sender.send(Ok(Event::Token(id))).await.unwrap(); + } + assert!( + tokio::time::timeout(std::time::Duration::from_millis(25), body.frame()) + .await + .is_err() + ); + sender + .send(Ok(Event::Done(Done { + generated: 12, + prompt_tokens: 4, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(sender); + let mut last = None; + while let Some(frame) = body.frame().await { + last = Some(parse_sse(&frame.unwrap().into_data().unwrap())); + } + assert_eq!( + last.unwrap()["response"]["output"][1]["content"][0]["text"], + "4" + ); + fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn reasoning_replay_preserves_tool_context_and_rejects_opaque_substitution() { + let output = json!([ + {"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"Need the checked code."}]}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"} + ]); + let mut history = ResponseHistory::default(); + history + .insert( + "resp_checked", + "strata-local", + &json!("Check the code"), + &json!({"id":"resp_checked","model":"strata-local","output":output}), + ) + .unwrap(); + let mut transcript = history + .get("resp_checked", "strata-local") + .unwrap() + .to_vec(); + transcript.push(json!({"type":"function_call_output","call_id":"call_1","output":"731"})); + let request = make_request(json!({"input":transcript,"reasoning":{"effort":"low"}})); + let prompt = render_request_prompt(&request).unwrap(); + assert!(prompt.contains("\nNeed the checked code.\n\n\n")); + assert!(prompt.contains("\n731\n")); + let mut invalid = request.clone(); + invalid.input[1] = + json!({"type":"reasoning","summary":[{"type":"summary_text","text":"short"}]}); + assert!(render_request_prompt(&invalid).is_err()); + invalid.input[1] = json!({"type":"reasoning","content":[],"encrypted_content":"opaque"}); + assert!(render_request_prompt(&invalid).is_err()); + let truncated = make_request( + json!({"input":[{"role":"user","content":"Check"},{"type":"reasoning","content":[{"type":"reasoning_text","text":"Unfinished"}]},{"role":"user","content":"Continue"}]}), + ); + assert!( + render_request_prompt(&truncated) + .unwrap() + .contains("\nUnfinished\n") + ); + } + + #[tokio::test] + async fn structured_live_routes_validate_text_and_preserve_tools_and_length() { + let tool_xml = "\n\n\nOslo\n\n\n"; + for stream in [false, true] { + for (output, finish, expected) in [ + ("{\"ok\":true}", Finish::Stop, "completed"), + ("{\"ok\":1}", Finish::Stop, "failed"), + ("not JSON", Finish::Stop, "failed"), + ("{\"ok\":", Finish::Length, "incomplete"), + (tool_xml, Finish::Stop, "completed"), + ] { + let (tokenizer, root) = test_tokenizer(); + let (commands, mut received) = mpsc::channel::(1); + let mut state = AppState::default(); + state.worker.write().await.state = WorkerState::Ready; + state.tokenizer = Some(tokenizer.clone()); + state.generation = Some(commands); + let worker = tokio::spawn(async move { + let command = received.recv().await.unwrap(); + let prompt = tokenizer.decode(&command.request.token_ids).unwrap(); + assert!(prompt.contains("JSON Schema:")); + assert!(prompt.contains("\"required\":[\"ok\"]")); + let ids = tokenizer.encode(output, false).unwrap(); + let generated = ids.len() as u64; + let mut events = ids.into_iter().map(Event::Token).collect::>(); + events.push(Event::Done(Done { + generated, + prompt_tokens: command.request.token_ids.len() as u64, + prompt_ms: 1.0, + decode_ms: 2.0, + finish, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + })); + match command.result { + GenerationResult::Finished => panic!("fixture received finished command"), + GenerationResult::Buffered(sender) => { + sender.send(Ok(events)).unwrap(); + } + GenerationResult::Streaming(sender) => { + for event in events { + sender.send(Ok(event)).await.unwrap(); + } + } + } + }); + let response = create(State(state.clone()), Ok(Json(json!({ + "model":"strata-local", "input":"Provide the result", "stream":stream, + "reasoning":{"effort":"none"}, + "text":{"format":{"type":"json_schema","name":"result","strict":true, + "schema":{"type":"object","properties":{"ok":{"type":"boolean"}},"required":["ok"],"additionalProperties":false}}}, + "tools":[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}] + })))).await; + let final_response = if stream { + assert_eq!(response.status(), StatusCode::OK); + let mut body = response.into_body(); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + for (index, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], index); + } + assert_eq!( + events.last().unwrap()["type"], + format!("response.{expected}") + ); + if expected == "failed" { + assert_eq!( + events.len(), + 3, + "invalid output must not publish text or tools" + ); + } + events.last().unwrap()["response"].clone() + } else { + assert_eq!( + response.status(), + if expected == "failed" { + StatusCode::BAD_GATEWAY + } else { + StatusCode::OK + } + ); + serde_json::from_slice::( + &to_bytes(response.into_body(), usize::MAX).await.unwrap(), + ) + .unwrap() + }; + if expected != "failed" { + assert_eq!(final_response["status"], expected); + if output == tool_xml { + assert_eq!(final_response["output"][0]["type"], "function_call"); + assert_eq!( + serde_json::from_str::( + final_response["output"][0]["arguments"].as_str().unwrap() + ) + .unwrap(), + json!({"city":"Oslo"}) + ); + } else { + assert_eq!(final_response["output"][0]["content"][0]["text"], output); + } + assert!( + state + .response_history + .read() + .await + .get(final_response["id"].as_str().unwrap(), "strata-local") + .is_some() + ); + } else { + assert!(state.response_history.read().await.entries.is_empty()); + } + worker.await.unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + } + + #[tokio::test] + async fn structured_stream_waits_for_done_before_publishing_json() { + let (tokenizer, root) = test_tokenizer(); + let (sender, source) = mpsc::channel(32); + let request = make_request( + json!({"reasoning":{"effort":"none"},"text":{"format":{"type":"json_object"}}}), + ); + assert!( + render_request_prompt(&request) + .unwrap() + .contains("exactly one JSON object") + ); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + for _ in 0..2 { + body.frame().await.unwrap().unwrap(); + } + for id in tokenizer.encode("{\"ok\":true}", false).unwrap() { + sender.send(Ok(Event::Token(id))).await.unwrap(); + } + assert!( + tokio::time::timeout(std::time::Duration::from_millis(25), body.frame()) + .await + .is_err() + ); + sender + .send(Ok(Event::Done(Done { + generated: 11, + prompt_tokens: 8, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(sender); + let mut last = None; + while let Some(frame) = body.frame().await { + last = Some(parse_sse(&frame.unwrap().into_data().unwrap())); + } + assert_eq!(last.unwrap()["type"], "response.completed"); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn invalid_structured_schema_is_rejected_before_worker_admission() { + for schema in [ + json!({"type":"object","$ref":"https://example.invalid/schema"}), + json!({"type":"object","properties":{"x":{"type":"invalid"}}}), + ] { + let response=create(State(AppState::default()),Ok(Json(json!({"model":"strata-local","input":"Hello","text":{"format":{"type":"json_schema","name":"result","schema":schema}}})))).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + } + } + + #[tokio::test] + async fn worker_error_terminates_stream_as_failed() { + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(2); + let request = make_request(json!({"reasoning": {"effort": "none"}})); + let mut body = stream_live_text(request, tokenizer, source, None).into_body(); + engine_events + .send(Err("mock worker failure".to_owned())) + .await + .unwrap(); + drop(engine_events); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + assert_eq!(events.len(), 5); + assert_eq!(events[4]["type"], "response.failed"); + assert_eq!(events[4]["response"]["status"], "failed"); + assert_eq!( + events[4]["response"]["error"]["message"], + "mock worker failure" + ); + assert_eq!(events[4]["sequence_number"], 4); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn disconnected_sse_cancels_idle_text_and_tool_sources() { + for mode in 0..4 { + let with_tools = mode == 1; + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(2); + let mut value = json!({"reasoning": {"effort": "none"}}); + if with_tools { + value["tools"] = json!([{"type": "function", "name": "lookup", + "parameters": {"type": "object", "properties": {}}}]); + } + if mode == 2 { + value["text"] = json!({"format":{"type":"json_object"}}); + } + if mode == 3 { + value["reasoning"] = json!({"effort":"low"}); + } + let request = make_request(value); + let mut body = stream_live_text(request, tokenizer, source, None).into_body(); + // Read the initial events so the relay reaches its idle source read. + for _ in 0..if mode == 1 || mode == 2 { 2 } else { 4 } { + tokio::time::timeout(std::time::Duration::from_secs(1), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap(); + } + tokio::task::yield_now().await; + drop(body); + tokio::time::timeout(std::time::Duration::from_secs(1), engine_events.closed()) + .await + .expect("disconnect must cancel without waiting for another engine token"); + fs::remove_dir_all(root).unwrap(); + } + } + + #[tokio::test] + async fn token_budget_terminates_live_stream_as_incomplete() { + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(2); + let request = make_request(json!({"reasoning": {"effort": "none"}})); + let mut body = stream_live_text(request, tokenizer, source, None).into_body(); + engine_events.send(Ok(Event::Token(79))).await.unwrap(); + engine_events + .send(Ok(Event::Done(Done { + generated: 1, + prompt_tokens: 4, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Length, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(engine_events); + let mut last = None; + while let Some(frame) = body.frame().await { + last = Some(parse_sse(&frame.unwrap().into_data().unwrap())); + } + let last = last.unwrap(); + assert_eq!(last["type"], "response.incomplete"); + assert_eq!( + last["response"]["incomplete_details"]["reason"], + "max_output_tokens" + ); + assert_eq!(last["response"]["output"][0]["content"][0]["text"], "O"); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn live_tool_stream_emits_validated_call_before_done() { + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(4096); + let request = make_request(json!({ + "reasoning": {"effort": "none"}, + "tools": [{"type":"function","name":"lookup","parameters":{ + "type":"object","properties":{"city":{"type":"string"}}, + "required":["city"],"additionalProperties":false + }}] + })); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + let first = "Checking.\n\n\n\nOslo\n\n\n"; + let ids = tokenizer.encode(first, false).unwrap(); + for id in &ids { + engine_events.send(Ok(Event::Token(*id))).await.unwrap(); + } + let mut events = Vec::new(); + loop { + let frame = tokio::time::timeout(std::time::Duration::from_secs(2), body.frame()) + .await + .unwrap() + .unwrap() + .unwrap() + .into_data() + .unwrap(); + let event = parse_sse(&frame); + let done = event["type"] == "response.function_call_arguments.done"; + events.push(event); + if done { + break; + } + } + assert!( + events + .iter() + .any(|event| event["type"] == "response.output_text.delta") + ); + assert!( + events + .iter() + .all(|event| event["type"] != "response.completed") + ); + let call = events.last().unwrap(); + assert_eq!(call["arguments"], "{\"city\":\"Oslo\"}"); + engine_events + .send(Ok(Event::Done(Done { + generated: ids.len() as u64, + prompt_tokens: 5, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(engine_events); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + for (index, event) in events.iter().enumerate() { + assert_eq!(event["sequence_number"], index); + } + assert_eq!(events.last().unwrap()["type"], "response.completed"); + let output = &events.last().unwrap()["response"]["output"]; + assert_eq!(output[0]["content"][0]["text"], "Checking."); + assert_eq!(output[1]["type"], "function_call"); + assert_eq!(output[1]["name"], "lookup"); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn unfinished_live_tool_call_fails_without_publishing_arguments() { + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(4096); + let request = make_request(json!({ + "reasoning": {"effort": "none"}, + "tools": [{"type":"function","name":"lookup"}] + })); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + let ids = tokenizer + .encode("Os", false) + .unwrap(); + for id in &ids { + engine_events.send(Ok(Event::Token(*id))).await.unwrap(); + } + engine_events + .send(Ok(Event::Done(Done { + generated: ids.len() as u64, + prompt_tokens: 5, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Length, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(engine_events); + let mut kinds = Vec::new(); + while let Some(frame) = body.frame().await { + kinds.push(parse_sse(&frame.unwrap().into_data().unwrap())["type"].clone()); + } + assert_eq!(kinds.last(), Some(&json!("response.failed"))); + assert!(!kinds.contains(&json!("response.function_call_arguments.delta"))); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn live_tool_stream_rejects_schema_violation_before_call_events() { + let (tokenizer, root) = test_tokenizer(); + let (engine_events, source) = mpsc::channel(4096); + let request = make_request(json!({ + "reasoning": {"effort": "none"}, + "tools": [{"type":"function","name":"lookup","parameters":{ + "type":"object","properties":{"days":{"type":"integer"}}, + "required":["days"],"additionalProperties":false + }}] + })); + assert!(validate_live_subset(&request).is_ok()); + let mut body = stream_live_text(request, tokenizer.clone(), source, None).into_body(); + let text = + "wrong"; + let ids = tokenizer.encode(text, false).unwrap(); + for id in &ids { + engine_events.send(Ok(Event::Token(*id))).await.unwrap(); + } + engine_events + .send(Ok(Event::Done(Done { + generated: ids.len() as u64, + prompt_tokens: 5, + prompt_ms: 1.0, + decode_ms: 2.0, + finish: Finish::Stop, + drafts_accepted: None, + drafts_offered: None, + reused: None, + expert_hits: None, + expert_lookups: None, + }))) + .await + .unwrap(); + drop(engine_events); + let mut events = Vec::new(); + while let Some(frame) = body.frame().await { + events.push(parse_sse(&frame.unwrap().into_data().unwrap())); + } + assert_eq!(events.last().unwrap()["type"], "response.failed"); + assert!( + events.last().unwrap()["response"]["error"]["message"] + .as_str() + .unwrap() + .contains("violate schema") + ); + assert!( + !events + .iter() + .any(|event| event["type"] == "response.function_call_arguments.delta") + ); + fs::remove_dir_all(root).unwrap(); + } + + fn parse_sse(bytes: &[u8]) -> Value { + let text = std::str::from_utf8(bytes).unwrap(); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .unwrap(); + serde_json::from_str(data).unwrap() + } + + #[test] + fn utf8_deltas_wait_for_complete_character_and_match_lossy_decode() { + let mut pending = Vec::new(); + pending.extend_from_slice(&[0xe2, 0x82]); + assert_eq!(drain_utf8(&mut pending, false), ""); + pending.push(0xac); + assert_eq!(drain_utf8(&mut pending, false), "€"); + pending.extend_from_slice(&[0xf0, 0x9f]); + assert_eq!(drain_utf8(&mut pending, true), "�"); + } +} diff --git a/control-plane/src/service_install.rs b/control-plane/src/service_install.rs new file mode 100644 index 00000000..07891f4a --- /dev/null +++ b/control-plane/src/service_install.rs @@ -0,0 +1,935 @@ +//! Explicit per-user systemd installation. Never replaces a different unit. +use std::path::{Path, PathBuf}; + +const USAGE: &str = "usage: strata-next service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start]"; +const INSTALL_READY_USAGE: &str = "service-install --start-ready requires --ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]; do not combine with --start"; + +#[derive(Debug)] +struct Options { + config: PathBuf, + working_dir: PathBuf, + env_file: Option, + unit: String, + start: bool, + enable: bool, +} + +fn parse(args: &[String]) -> Result { + let mut values = std::collections::BTreeMap::new(); + let mut start = false; + let mut enable = false; + let mut args = args.iter(); + while let Some(flag) = args.next() { + if flag == "--start" && !start { + start = true; + } else if flag == "--enable" && !enable { + enable = true; + } else if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + let value = args.next().ok_or(USAGE)?; + if values.insert(flag.as_str(), value).is_some() { + return Err(USAGE.into()); + } + } else { + return Err(USAGE.into()); + } + } + let unit = values + .get("--unit") + .map(|s| s.as_str()) + .unwrap_or("strata-next.service"); + validate_name(unit)?; + Ok(Options { + config: PathBuf::from(values.get("--config").ok_or(USAGE)?), + working_dir: PathBuf::from(values.get("--working-dir").ok_or(USAGE)?), + env_file: values.get("--env-file").map(PathBuf::from), + unit: unit.into(), + start, + enable, + }) +} + +fn validate_name(name: &str) -> Result<(), String> { + let suffix = name + .strip_prefix("strata-next") + .and_then(|s| s.strip_suffix(".service")); + if name.len() <= 120 + && suffix.is_some_and(|s| { + s.is_empty() + || (s.starts_with('-') + && s.len() > 1 + && s[1..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) + }) + { + Ok(()) + } else { + Err("unit must be strata-next.service or strata-next-NAME.service (ASCII letters, digits, dash, underscore)".into()) + } +} + +fn install_options(args: &[String]) -> Result<(Options, Option>), String> { + let mut service = Vec::new(); + let mut readiness = Vec::new(); + let mut start_ready = false; + let mut args = args.iter(); + while let Some(flag) = args.next() { + if flag == "--start-ready" { + if start_ready { + return Err(INSTALL_READY_USAGE.into()); + } + start_ready = true; + } else if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness.push(flag.replacen("--ready-", "--", 1)); + readiness.push(args.next().ok_or(INSTALL_READY_USAGE)?.clone()); + } else { + service.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service.push(args.next().ok_or(USAGE)?.clone()); + } + } + } + let mut options = parse(&service)?; + if start_ready { + if options.start { + return Err(INSTALL_READY_USAGE.into()); + } + crate::wait_ready::validate(&readiness)?; + options.start = true; + } else if !readiness.is_empty() { + return Err(INSTALL_READY_USAGE.into()); + } + Ok((options, start_ready.then_some(readiness))) +} + +fn ready_control_args(options: &Options, readiness: &[String]) -> Vec { + let mut args = vec![ + "start-ready".into(), + "--config".into(), + options.config.to_string_lossy().into_owned(), + "--working-dir".into(), + options.working_dir.to_string_lossy().into_owned(), + "--unit".into(), + options.unit.clone(), + ]; + if let Some(file) = &options.env_file { + args.extend(["--env-file".into(), file.to_string_lossy().into_owned()]); + } + for [flag, value] in readiness.as_chunks::<2>().0 { + args.extend([flag.replacen("--", "--ready-", 1), value.clone()]); + } + args +} + +const CONTROL_USAGE: &str = "usage: strata-next service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]"; + +fn control_options(args: &[String]) -> Result<(&str, Options, Option>), String> { + let (action, args) = args.split_first().ok_or(CONTROL_USAGE)?; + if !matches!( + action.as_str(), + "status" + | "start" + | "stop" + | "restart" + | "enable" + | "disable" + | "start-ready" + | "restart-ready" + | "drain-stop" + | "resume" + ) { + return Err(CONTROL_USAGE.into()); + } + let mut service_args = Vec::new(); + let mut readiness_args = Vec::new(); + let mut args = args.iter(); + while let Some(flag) = args.next() { + if matches!( + flag.as_str(), + "--ready-url" | "--ready-model" | "--ready-key-file" | "--ready-timeout-s" + ) { + readiness_args.push(flag.replacen("--ready-", "--", 1)); + readiness_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } else { + service_args.push(flag.clone()); + if matches!( + flag.as_str(), + "--config" | "--working-dir" | "--env-file" | "--unit" + ) { + service_args.push(args.next().ok_or(CONTROL_USAGE)?.clone()); + } + } + } + let ready = matches!( + action.as_str(), + "start-ready" | "restart-ready" | "drain-stop" | "resume" + ); + if ready { + crate::wait_ready::validate(&readiness_args)?; + } else if !readiness_args.is_empty() { + return Err(CONTROL_USAGE.into()); + } + let options = + parse(&service_args).map_err(|e| if e == USAGE { CONTROL_USAGE.into() } else { e })?; + if options.start || options.enable { + return Err(CONTROL_USAGE.into()); + } + Ok((action, options, ready.then_some(readiness_args))) +} + +#[cfg(unix)] +fn unit_directory() -> Result { + let config = match std::env::var_os("XDG_CONFIG_HOME") { + Some(value) if !value.is_empty() => PathBuf::from(value), + _ => PathBuf::from(std::env::var_os("HOME").ok_or("HOME is missing")?).join(".config"), + }; + if !config.is_absolute() { + return Err("user config directory must be absolute".into()); + } + Ok(config.join("systemd/user")) +} + +pub async fn control(args: &[String]) -> Result { + let (action, options, readiness_args) = control_options(args)?; + if !cfg!(target_os = "linux") { + return Err("service-control requires Linux with a running systemd user manager".into()); + } + let waiter = readiness_args + .as_ref() + .map(|args| crate::wait_ready::Waiter::new(args)) + .transpose()?; + #[cfg(unix)] + { + let content = crate::service_unit::render( + &std::env::current_exe().map_err(|e| e.to_string())?, + &options.config, + &options.working_dir, + options.env_file.as_deref(), + )?; + let directory = unit_directory()?; + unix::check_directory(&directory)?; + let path = directory.join(&options.unit); + unix::same_file(&path, content.as_bytes()) + .map_err(|e| format!("refusing service control: {e}; use the installed executable and exact unit configuration"))?; + unix::verify_loaded_unit(&options.unit, &path).await?; + if matches!(action, "enable" | "disable") { + unix::check_activation_link(&path)?; + } + if matches!(action, "drain-stop" | "resume") { + let manager = unix::status(&options.unit).await?; + let pid = active_pid(&manager)?; + let admission = waiter.ok_or("missing lifecycle client")?.admission(pid, action == "drain-stop").await + .map_err(|e| format!("{e}; no manager stop requested; admission may have changed, reconcile explicitly"))?; + unix::same_file(&path, content.as_bytes()) + .map_err(|_| "unit changed during drain; no stop requested")?; + unix::verify_loaded_unit(&options.unit, &path).await?; + let current = unix::status(&options.unit).await?; + if active_pid(¤t)? != pid { + return Err( + "managed process changed; no stop requested, reconcile admission explicitly" + .into(), + ); + } + let manager = if action == "drain-stop" { + unix::systemctl("stop", &options.unit, std::time::Duration::from_secs(60)) + .await + .map_err(|e| { + format!("{e}; stop may be pending; inspect status before retrying") + })?; + unix::status(&options.unit).await? + } else { + current + }; + if action == "drain-stop" + && (manager["main_pid"] != 0 || manager["active_state"] != "inactive") + { + return Err( + "stop was requested but service is not inactive; reconcile explicitly".into(), + ); + } + return Ok( + serde_json::json!({"unit":options.unit,"action":action,"manager":manager, + "action_requested":true,"model_readiness":"not_checked", "admission":admission}), + ); + } + if action != "status" { + let manager_action = match action { + "start-ready" => "start", + "restart-ready" => "restart", + other => other, + }; + unix::systemctl(manager_action, &options.unit, std::time::Duration::from_secs(60)).await + .map_err(|e| format!("{e}; manager action may be pending; inspect service-control status before retrying"))?; + } + if matches!(action, "enable" | "disable") { + unix::verify_loaded_unit(&options.unit, &path) + .await + .map_err(|e| { + format!( + "{e}; {action} was requested; reconcile identity before further control" + ) + })?; + } + let manager = unix::status(&options.unit).await.map_err(|e| { + format!("{e}; {action} outcome needs reconciliation; no action was replayed") + })?; + let mut result = serde_json::json!({"unit":options.unit,"action":action,"manager":manager, + "action_requested":action != "status", "model_readiness":"not_checked"}); + if let Some(waiter) = waiter { + let pid = active_pid(&manager)?; + let readiness = waiter.wait(Some(pid)).await.map_err(|error| format!( + "{error}; {action} was requested; service left for explicit reconciliation, no lifecycle action was replayed" + ))?; + unix::same_file(&path, content.as_bytes()) + .map_err(|_| "unit changed during readiness wait; reconcile explicitly")?; + unix::verify_loaded_unit(&options.unit, &path).await?; + let current = unix::status(&options.unit).await?; + if active_pid(¤t)? != pid { + return Err( + "managed process changed during readiness wait; reconcile explicitly".into(), + ); + } + result["manager"] = current; + result["model_readiness"] = serde_json::json!("ready"); + result["readiness"] = readiness; + } + Ok(result) + } + #[cfg(not(unix))] + Err("service-control requires Linux".into()) +} + +fn active_pid(manager: &serde_json::Value) -> Result { + if manager["active_state"] != "active" || manager["sub_state"] != "running" { + return Err("managed service is not running; readiness cannot be confirmed".into()); + } + manager["main_pid"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| "managed service has no valid active PID".into()) +} + +pub async fn run(args: &[String]) -> Result { + let (options, readiness) = install_options(args)?; + // Validate private credentials and client policy before publishing anything. + if let Some(args) = &readiness { + let _ = crate::wait_ready::Waiter::new(args)?; + } + let content = crate::service_unit::render( + &std::env::current_exe().map_err(|e| e.to_string())?, + &options.config, + &options.working_dir, + options.env_file.as_deref(), + )?; + if !cfg!(target_os = "linux") { + return Err("service-install requires Linux with a running systemd user manager".into()); + } + #[cfg(unix)] + { + let directory = unit_directory()?; + let path = directory.join(&options.unit); + let created = unix::publish(&directory, &options.unit, content.as_bytes())?; + let mut actions = vec!["daemon-reload"]; + if options.enable { + actions.push("enable"); + } + if options.start && readiness.is_none() { + actions.push("start"); + } + for action in actions { + if matches!(action, "start" | "enable") { + unix::verify_loaded_unit(&options.unit, &path) + .await + .map_err(|e| { + format!( + "{e}; unit retained at {}; {action} was not requested", + path.display() + ) + })?; + } + if action == "enable" { + unix::check_activation_link(&path)?; + } + unix::systemctl(action, &options.unit, std::time::Duration::from_secs(30)).await + .map_err(|e| format!("{e}; unit retained at {} for explicit retry. Activation may be pending; inspect systemctl --user status {}. Model readiness has not been checked", path.display(), options.unit))?; + if action == "enable" { + unix::verify_loaded_unit(&options.unit, &path).await?; + } + } + let mut result = serde_json::json!({"unit":options.unit,"path":path,"created":created,"reused":!created,"daemon_reloaded":true,"start_requested":options.start,"model_readiness":"not_checked","enable_requested":options.enable}); + if let Some(readiness) = readiness { + let started = control(&ready_control_args(&options, &readiness)).await + .map_err(|error| format!("{error}; installed unit retained at {}; inspect status before another lifecycle action",path.display()))?; + result["model_readiness"] = started["model_readiness"].clone(); + result["manager"] = started["manager"].clone(); + result["readiness"] = started["readiness"].clone(); + } + Ok(result) + } + #[cfg(not(unix))] + Err("service-install requires Linux".into()) +} + +#[cfg(unix)] +mod unix { + use super::*; + use std::{ + fs::{self, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + process::Stdio, + time::Duration, + }; + + pub(super) fn publish(directory: &Path, name: &str, content: &[u8]) -> Result { + validate_name(name)?; + let mut builder = fs::DirBuilder::new(); + builder.recursive(true).mode(0o700); + builder + .create(directory) + .map_err(|e| format!("create user unit directory: {e}"))?; + check_directory(directory)?; + let path = directory.join(name); + match same_file(&path, content) { + Ok(()) => return Ok(false), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(e) => return Err(format!("refusing existing unit {}: {e}", path.display())), + } + let temp = directory.join(format!( + ".strata-unit-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_nanos() + )); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temp) + .map_err(|e| e.to_string())?; + let result = (|| { + file.write_all(content)?; + file.sync_all()?; + let created = match fs::hard_link(&temp, &path) { + Ok(()) => true, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + same_file(&path, content)?; + false + } + Err(e) => return Err(e), + }; + fs::File::open(directory)?.sync_all()?; + Ok(created) + })(); + let cleanup = fs::remove_file(&temp); + result + .map_err(|e: std::io::Error| format!("publish unit: {e}")) + .and_then(|created| { + cleanup.map_err(|e| format!("remove unit staging file: {e}"))?; + Ok(created) + }) + } + + pub(super) fn check_directory(directory: &Path) -> Result<(), String> { + let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?; + if !metadata.is_dir() + || metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o022 != 0 + { + return Err( + "user unit directory must be an owned directory, not writable by other users" + .into(), + ); + } + Ok(()) + } + + pub(super) fn same_file(path: &Path, content: &[u8]) -> std::io::Result<()> { + let mut file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() + || metadata.uid() != unsafe { libc::geteuid() } + || metadata.mode() & 0o077 != 0 + || metadata.len() != content.len() as u64 + { + return Err(std::io::Error::other( + "requires an owned private regular file with identical content", + )); + } + let mut actual = Vec::new(); + (&mut file) + .take(content.len() as u64 + 1) + .read_to_end(&mut actual)?; + if actual != content { + return Err(std::io::Error::other( + "different unit content; choose a new unit name", + )); + } + Ok(()) + } + + // Never replace/remove a conflicting activation link even for a valid unit. + pub(super) fn check_activation_link(path: &Path) -> Result<(), String> { + let directory = path + .parent() + .ok_or("unit parent absent")? + .join("default.target.wants"); + match fs::symlink_metadata(&directory) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Ok(meta) if meta.is_dir() && meta.uid() == unsafe { libc::geteuid() } + && meta.mode() & 0o022 == 0 => (), + _ => return Err("activation directory must be an owned real directory without group/other write access".into()), + } + let link = directory.join(path.file_name().ok_or("unit name absent")?); + match fs::symlink_metadata(&link) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Ok(meta) + if meta.file_type().is_symlink() + && link.canonicalize().ok() + == Some(path.canonicalize().map_err(|e| e.to_string())?) => + { + Ok(()) + } + _ => Err( + "conflicting activation link; reconcile it explicitly before enable/disable".into(), + ), + } + } + + // The manager may have different XDG paths or higher-priority runtime units. + // Refuse to start a different service or a unit modified by existing drop-ins. + pub(super) async fn verify_loaded_unit(unit: &str, path: &Path) -> Result<(), String> { + let output = show(unit, &["FragmentPath", "DropInPaths", "NeedDaemonReload"]).await?; + let fragment = output + .lines() + .find_map(|s| s.strip_prefix("FragmentPath=")) + .ok_or("manager has no unit fragment")?; + let drop_ins = output + .lines() + .find_map(|s| s.strip_prefix("DropInPaths=")) + .ok_or("manager did not report drop-ins")?; + let reload = output + .lines() + .find_map(|s| s.strip_prefix("NeedDaemonReload=")); + if reload != Some("no") { + return Err("systemd unit is stale or reload state is unknown; reconcile the unit and run daemon-reload explicitly before control".into()); + } + if !drop_ins.is_empty() + || Path::new(fragment).canonicalize().ok() + != Some(path.canonicalize().map_err(|e| e.to_string())?) + { + return Err("systemd resolves a different unit or existing drop-ins; use the manager's config directory and a new unit name".into()); + } + Ok(()) + } + + async fn show(unit: &str, properties: &[&str]) -> Result { + use tokio::io::AsyncReadExt; + let mut child = tokio::process::Command::new("systemctl") + .args(["--user", "--no-pager", "show"]) + .args(properties.iter().map(|p| format!("--property={p}"))) + .args(["--", unit]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|e| format!("verify loaded unit: {e}"))?; + let mut stdout = child + .stdout + .take() + .ok_or("missing systemctl output pipe")? + .take(16385); + let mut bytes = Vec::new(); + let result = tokio::time::timeout(Duration::from_secs(30), async { + stdout.read_to_end(&mut bytes).await?; + if bytes.len() > 16384 { + return Err(std::io::Error::other("systemctl output exceeded limit")); + } + let status = child.wait().await?; + if !status.success() { + return Err(std::io::Error::other("systemctl show failed")); + } + Ok(()) + }) + .await; + if !matches!(result, Ok(Ok(()))) { + let _ = child.kill().await; + return Err(format!("verify loaded unit failed: {result:?}")); + } + String::from_utf8(bytes).map_err(|_| "invalid systemctl output".into()) + } + + pub(super) async fn status(unit: &str) -> Result { + parse_status( + &show( + unit, + &["ActiveState", "SubState", "MainPID", "UnitFileState"], + ) + .await?, + ) + } + + fn parse_status(output: &str) -> Result { + let mut values = std::collections::BTreeMap::new(); + for line in output.lines() { + let (key, value) = line.split_once('=').ok_or("malformed manager status")?; + if !matches!( + key, + "ActiveState" | "SubState" | "MainPID" | "UnitFileState" + ) || values.insert(key, value).is_some() + { + return Err("unexpected or duplicate manager status property".into()); + } + } + let state = |key| -> Result<&str, String> { + let value = *values.get(key).ok_or("incomplete manager status")?; + if value.is_empty() + || value.len() > 64 + || !value + .bytes() + .all(|b| b.is_ascii_lowercase() || b"-_".contains(&b)) + { + return Err("invalid manager state".into()); + } + Ok(value) + }; + let pid = *values.get("MainPID").ok_or("manager PID absent")?; + if pid.is_empty() || !pid.bytes().all(|b| b.is_ascii_digit()) { + return Err("invalid manager PID".into()); + } + let pid = pid.parse::().map_err(|_| "invalid manager PID")?; + Ok( + serde_json::json!({"active_state":state("ActiveState")?,"sub_state":state("SubState")?,"main_pid":pid,"unit_file_state":state("UnitFileState")?}), + ) + } + + pub(super) async fn systemctl( + action: &str, + unit: &str, + timeout: Duration, + ) -> Result<(), String> { + let mut command = tokio::process::Command::new("systemctl"); + command.args(["--user", "--no-pager", action]); + match action { + "daemon-reload" => (), + "start" | "stop" | "restart" | "enable" | "disable" => { + command.args(["--", unit]); + } + _ => return Err("unsupported systemctl action".into()), + } + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true); + bounded(&mut command, timeout) + .await + .map_err(|e| format!("systemctl --user {action}: {e}")) + } + + async fn bounded( + command: &mut tokio::process::Command, + timeout: Duration, + ) -> Result<(), String> { + let mut child = command.spawn().map_err(|e| e.to_string())?; + match tokio::time::timeout(timeout, child.wait()).await { + Ok(Ok(status)) if status.success() => Ok(()), + Ok(result) => Err(format!("command failed: {result:?}")), + Err(_) => { + child + .kill() + .await + .map_err(|e| format!("timed out; kill/reap failed: {e}"))?; + Err("timed out; client killed and reaped (manager job may still be pending)".into()) + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use std::os::unix::fs::{PermissionsExt, symlink}; + #[test] + fn atomic_reuse_and_conflicts_preserve_bytes() { + let root = std::env::temp_dir().join(format!( + "strata-unit-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let name = "strata-next-test.service"; + assert!(publish(&root, name, b"one").unwrap()); + let path = root.join(name); + let inode = fs::metadata(&path).unwrap().ino(); + assert!(!publish(&root, name, b"one").unwrap()); + assert!(publish(&root, name, b"two").is_err()); + assert_eq!(fs::read(&path).unwrap(), b"one"); + assert_eq!(fs::metadata(&path).unwrap().ino(), inode); + assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + fs::remove_file(&path).unwrap(); + symlink(root.join("missing"), &path).unwrap(); + assert!(publish(&root, name, b"one").is_err()); + fs::remove_file(&path).unwrap(); + fs::create_dir(&path).unwrap(); + assert!(publish(&root, name, b"one").is_err()); + fs::remove_dir(&path).unwrap(); + assert!(publish(&root, name, b"one").unwrap()); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(publish(&root, name, b"one").is_err()); + assert_eq!(fs::read_dir(&root).unwrap().count(), 1); + fs::remove_dir_all(root).unwrap(); + } + #[test] + fn manager_status_is_limited_and_strict() { + let good = + "ActiveState=active\nSubState=running\nMainPID=123\nUnitFileState=disabled\n"; + let value = parse_status(good).unwrap(); + assert_eq!(value["main_pid"], 123); + assert_eq!(value["active_state"], "active"); + assert_eq!(value["unit_file_state"], "disabled"); + assert_eq!( + parse_status( + "MainPID=0\nSubState=dead\nActiveState=inactive\nUnitFileState=enabled\n" + ) + .unwrap()["main_pid"], + 0 + ); + for bad in [ + "", + "MainPID=1\n", + "ActiveState=active\nSubState=running\nMainPID=-1\n", + "ActiveState=active\nSubState=running\nMainPID=4294967296\n", + "ActiveState=active\nSubState=running\nMainPID=+1\n", + "ActiveState=active\nSubState=secret text\nMainPID=1\n", + ] { + assert!(parse_status(bad).is_err()); + } + assert!(parse_status(&format!("{good}MainPID=2\n")).is_err()); + assert!(parse_status(&format!("{good}Environment=secret\n")).is_err()); + assert!(parse_status(&good.replace("disabled", "")).is_err()); + assert!(parse_status(&format!("{good}UnitFileState=enabled\n")).is_err()); + } + + #[test] + fn activation_link_conflicts_are_preserved() { + let root = std::env::temp_dir().join(format!( + "strata-activation-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let name = "strata-next-activation.service"; + publish(&root, name, b"owned unit").unwrap(); + let path = root.join(name); + assert!(check_activation_link(&path).is_ok()); + let wants = root.join("default.target.wants"); + fs::create_dir(&wants).unwrap(); + fs::set_permissions(&wants, fs::Permissions::from_mode(0o755)).unwrap(); + let link = wants.join(name); + symlink(Path::new("..").join(name), &link).unwrap(); + assert!(check_activation_link(&path).is_ok()); + fs::remove_file(&link).unwrap(); + symlink(root.join("foreign"), &link).unwrap(); + let inode = fs::symlink_metadata(&link).unwrap().ino(); + assert!(check_activation_link(&path).is_err()); + assert_eq!(fs::symlink_metadata(&link).unwrap().ino(), inode); + fs::remove_file(&link).unwrap(); + fs::write(&link, "foreign bytes").unwrap(); + assert!(check_activation_link(&path).is_err()); + assert_eq!(fs::read(&link).unwrap(), b"foreign bytes"); + fs::remove_file(&link).unwrap(); + fs::set_permissions(&wants, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(check_activation_link(&path).is_err()); + fs::remove_dir(&wants).unwrap(); + symlink(&root, &wants).unwrap(); + assert!(check_activation_link(&path).is_err()); + fs::remove_file(&wants).unwrap(); + fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn failed_and_timed_out_clients_are_reported_and_reaped() { + assert!( + bounded( + tokio::process::Command::new("false").kill_on_drop(true), + Duration::from_secs(1) + ) + .await + .is_err() + ); + let mut command = tokio::process::Command::new("sleep"); + command.arg("30").kill_on_drop(true); + let start = std::time::Instant::now(); + let error = bounded(&mut command, Duration::from_millis(20)) + .await + .unwrap_err(); + assert!(error.contains("killed and reaped")); + assert!(start.elapsed() < Duration::from_secs(2)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ready_install_is_explicit_and_control_compatible() { + let base = ["--config", "/config", "--working-dir", "/work"] + .map(str::to_owned) + .to_vec(); + let ready = [ + "--start-ready", + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "test", + ] + .map(str::to_owned); + let mut args = base.clone(); + args.extend(ready.clone()); + let (options, readiness) = install_options(&args).unwrap(); + assert!(options.start && !options.enable); + let control = ready_control_args(&options, &readiness.unwrap()); + assert_eq!(control_options(&control).unwrap().0, "start-ready"); + for suffix in [ + vec!["--start"], + vec!["--start-ready"], + vec!["--ready-timeout-s", "0"], + vec!["--ready-model", "duplicate"], + ] { + let mut bad = args.clone(); + bad.extend(suffix.into_iter().map(str::to_owned)); + assert!(install_options(&bad).is_err()); + } + let mut without = base.clone(); + without.extend(ready[1..].iter().cloned()); + assert!(install_options(&without).is_err()); + let mut missing = base.clone(); + missing.push("--start-ready".into()); + assert!(install_options(&missing).is_err()); + assert!(install_options(&base).unwrap().1.is_none()); + let mut old = base; + old.push("--start".into()); + assert!(install_options(&old).unwrap().0.start); + } + #[test] + fn control_only_explicit_scoped_actions() { + let args = ["--config", "/a", "--working-dir", "/b"]; + for action in ["status", "start", "stop", "restart", "enable", "disable"] { + let values = std::iter::once(action) + .chain(args) + .map(str::to_owned) + .collect::>(); + assert_eq!(control_options(&values).unwrap().0, action); + let mut values = values; + values.push("--start".into()); + assert!(control_options(&values).is_err()); + } + for action in ["kill", "daemon-reload", "--all", ""] { + let values = std::iter::once(action) + .chain(args) + .map(str::to_owned) + .collect::>(); + assert!(control_options(&values).is_err()); + } + } + + #[test] + fn arguments_and_scoped_names() { + for name in ["strata-next.service", "strata-next-prod_2.service"] { + assert!(validate_name(name).is_ok()); + } + for name in [ + "other.service", + "strata-next-.service", + "strata-next@a.service", + "strata-next-../a.service", + "strata-next-a\n.service", + ] { + assert!(validate_name(name).is_err()); + } + for args in [ + vec![], + vec!["--start", "--start"], + vec!["--enable", "--enable"], + vec!["--config", "/a", "--config", "/b"], + vec!["--enable"], + ] { + assert!(parse(&args.iter().map(|s| s.to_string()).collect::>()).is_err()); + } + let options = + parse(&["--config", "/a", "--working-dir", "/b", "--start"].map(str::to_owned)) + .unwrap(); + assert!(options.start); + assert!(!options.enable); + let enabled = + parse(&["--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned)) + .unwrap(); + assert!(enabled.enable && !enabled.start); + let invalid_control = + ["start", "--config", "/a", "--working-dir", "/b", "--enable"].map(str::to_owned); + assert!(control_options(&invalid_control).is_err()); + assert_eq!(options.unit, "strata-next.service"); + } + #[test] + fn managed_readiness_options_and_active_process_are_strict() { + let base = ["start-ready", "--config", "/a", "--working-dir", "/b"]; + let mut args = base.map(str::to_owned).to_vec(); + assert!(control_options(&args).is_err()); + args.extend( + [ + "--ready-url", + "http://127.0.0.1:8080", + "--ready-model", + "fixture", + ] + .map(str::to_owned), + ); + assert!(control_options(&args).unwrap().2.is_some()); + for action in ["restart-ready", "drain-stop", "resume"] { + args[0] = action.into(); + assert!(control_options(&args).is_ok()); + } + for action in ["status", "start", "restart", "enable"] { + args[0] = action.into(); + assert!(control_options(&args).is_err()); + } + args[0] = "start-ready".into(); + args.extend(["--ready-timeout-s", "0"].map(str::to_owned)); + assert!(control_options(&args).is_err()); + let good = + serde_json::json!({"active_state":"active", "sub_state":"running", "main_pid":123}); + assert_eq!(active_pid(&good).unwrap(), 123); + for (key, value) in [ + ("main_pid", serde_json::json!(0)), + ("main_pid", serde_json::json!(4294967296u64)), + ("main_pid", serde_json::json!("123")), + ("active_state", serde_json::json!("inactive")), + ("sub_state", serde_json::json!("dead")), + ] { + let mut bad = good.clone(); + bad[key] = value; + assert!(active_pid(&bad).is_err()); + } + } +} diff --git a/control-plane/src/service_switch.rs b/control-plane/src/service_switch.rs new file mode 100644 index 00000000..f38087f9 --- /dev/null +++ b/control-plane/src/service_switch.rs @@ -0,0 +1,792 @@ +//! Explicit transaction between installed native user services. Never replay an +//! interrupted lifecycle operation; retained phases require reconciliation. +use serde::Deserialize; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + time::Duration, +}; + +const USAGE: &str = + "usage: strata-next service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR"; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Catalog { + schema_version: u32, + profiles: BTreeMap, + #[serde(default = "provision_budget")] + provision_timeout_s: u64, +} +fn provision_budget() -> u64 { + 3600 +} +fn ready_budget() -> u64 { + 300 +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Profile { + unit: String, + config: PathBuf, + working_dir: PathBuf, + url: String, + model: String, + key_file: Option, + #[serde(default = "ready_budget")] + timeout_s: u64, +} +impl Profile { + fn readiness(&self) -> Vec { + let mut args = vec![ + "--url".into(), + self.url.clone(), + "--model".into(), + self.model.clone(), + "--timeout-s".into(), + self.timeout_s.to_string(), + ]; + if let Some(key) = &self.key_file { + args.extend(["--key-file".into(), key.to_string_lossy().into_owned()]); + } + args + } + async fn control(&self, action: &str) -> Result { + let mut args = vec![ + action.into(), + "--config".into(), + self.config.to_string_lossy().into_owned(), + "--working-dir".into(), + self.working_dir.to_string_lossy().into_owned(), + "--unit".into(), + self.unit.clone(), + ]; + if matches!(action, "start-ready" | "drain-stop") { + let ready = self.readiness(); + for pair in ready.as_chunks::<2>().0 { + args.extend([pair[0].replacen("--", "--ready-", 1), pair[1].clone()]); + } + } + crate::service_install::control(&args).await + } +} +fn arguments(args: &[String]) -> Result, String> { + let mut values = BTreeMap::new(); + let mut iter = args.iter(); + while let Some(flag) = iter.next() { + if !matches!( + flag.as_str(), + "--catalog" | "--from" | "--to" | "--state-dir" + ) { + return Err(USAGE.into()); + } + if values + .insert(flag.clone(), iter.next().ok_or(USAGE)?.clone()) + .is_some() + { + return Err(USAGE.into()); + } + } + if !["--catalog", "--to", "--state-dir"] + .iter() + .all(|k| values.contains_key(*k)) + { + return Err(USAGE.into()); + } + for key in ["--from", "--to"] { + let Some(id) = values.get(key) else { continue }; + if id.is_empty() + || id.len() > 64 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + { + return Err("profile IDs need 1..64 ASCII letters, digits, dash or underscore".into()); + } + } + if values.get("--from") == values.get("--to") { + return Err("switch needs distinct previous and target profiles".into()); + } + Ok(values) +} +fn pid(value: &Value) -> Result { + if value["manager"]["active_state"] != "active" || value["manager"]["sub_state"] != "running" { + return Err("previous managed service is not running".into()); + } + value["manager"]["main_pid"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n > 0) + .ok_or_else(|| "previous service PID invalid".into()) +} +fn inactive(value: &Value) -> bool { + value["manager"]["main_pid"] == 0 && value["manager"]["active_state"] == "inactive" +} + +fn select_active(states: &[(String, Value)]) -> Result, String> { + let mut active = None; + for (id, state) in states { + if inactive(state) { + continue; + } + let running = pid(state).map_err(|_| "catalog contains a failed, transitional or unknown service; reconcile before selection")?; + if active.replace((id.clone(), running)).is_some() { + return Err("multiple catalog services are active; selection is ambiguous".into()); + } + } + Ok(active) +} + +async fn discover(catalog: &Catalog) -> Result, String> { + let mut states = Vec::new(); + for (id, profile) in &catalog.profiles { + states.push((id.clone(), profile.control("status").await?)); + } + select_active(&states) +} + +#[cfg(unix)] +fn validate_auto(catalog: &Catalog, target: &Profile) -> Result, String> { + use std::collections::BTreeSet; + let mut units = BTreeSet::new(); + let mut paths = BTreeSet::new(); + let mut digests = BTreeMap::new(); + for (id, profile) in &catalog.profiles { + if profile.key_file.as_ref().is_some_and(|k| !k.is_absolute()) { + return Err("catalog key_file paths must be absolute".into()); + } + let _ = crate::wait_ready::Waiter::new(&profile.readiness())?; + if !units.insert(&profile.unit) + || !paths.insert( + profile + .config + .canonicalize() + .map_err(|_| "cannot resolve catalog config")?, + ) + || reqwest::Url::parse(&profile.url).ok() != reqwest::Url::parse(&target.url).ok() + { + return Err( + "automatic selection needs distinct units/configs sharing one loopback origin" + .into(), + ); + } + digests.insert(id.clone(), storage::digest(&profile.config)?); + } + Ok(digests) +} + +#[cfg(unix)] +mod storage { + use super::*; + use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + }; + pub(super) fn read(path: &Path, private: bool, max: u64) -> Result, String> { + if !path.is_absolute() { + return Err("profile paths must be absolute".into()); + } + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + .map_err(|_| "cannot open profile file")?; + let meta = file.metadata().map_err(|_| "cannot inspect profile file")?; + if !meta.is_file() + || meta.uid() != unsafe { libc::geteuid() } + || meta.mode() & if private { 0o077 } else { 0o022 } != 0 + || meta.len() > max + { + return Err( + "profile file must be owned, regular, bounded and have safe permissions".into(), + ); + } + let mut bytes = Vec::new(); + file.take(max + 1) + .read_to_end(&mut bytes) + .map_err(|_| "cannot read profile file")?; + if bytes.len() as u64 > max { + return Err("profile file exceeds limit".into()); + } + Ok(bytes) + } + pub(super) fn digest(path: &Path) -> Result { + Ok(hex::encode(Sha256::digest(read(path, false, 1024 * 1024)?))) + } + pub(super) struct Journal { + dir: PathBuf, + directory: File, + _lock: File, + pub(super) value: Value, + } + impl Journal { + pub(super) fn open(path: &Path, value: Value) -> Result { + Self::open_inner(path, value, false) + } + pub(super) fn reconciliation(path: &Path) -> Result { + read(&path.join("transaction.json"), true, 65536)?; + Self::open_inner(path, json!({}), true) + } + fn open_inner(path: &Path, value: Value, reconciliation: bool) -> Result { + if !path.is_absolute() || path.file_name().is_none() { + return Err("state directory must be absolute and non-root".into()); + } + match fs::DirBuilder::new().mode(0o700).create(path) { + Ok(()) => (), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (), + Err(_) => { + return Err("cannot create private state directory; parent must exist".into()); + } + } + let m = fs::symlink_metadata(path).map_err(|_| "cannot inspect state directory")?; + if !m.is_dir() + || m.file_type().is_symlink() + || m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o777 != 0o700 + { + return Err( + "state directory must be owned, private mode0700 and not a symlink".into(), + ); + } + let dir = path + .canonicalize() + .map_err(|_| "cannot resolve state directory")?; + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(dir.join("switch.lock")) + .map_err(|_| "cannot open switch lock")?; + let m = lock.metadata().map_err(|_| "cannot inspect switch lock")?; + if !m.is_file() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o077 != 0 { + return Err("unsafe switch lock".into()); + } + lock.try_lock() + .map_err(|_| "another switch is running or lock is unavailable")?; + let previous = dir.join("transaction.json"); + match fs::symlink_metadata(&previous) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(_) => return Err("cannot inspect prior transaction".into()), + Ok(_) => { + let prior: Value = serde_json::from_slice(&read(&previous, true, 65536)?) + .map_err(|_| "invalid prior transaction; reconcile explicitly")?; + if !reconciliation + && (prior["schema_version"] != 1 + || !matches!( + prior["phase"].as_str(), + Some( + "committed" + | "rolled_back" + | "preflight_failed" + | "cold_failed" + | "reused" + | "reconciled" + ) + )) + { + return Err("unfinished or unknown switch transaction; inspect services and archive journal only after explicit reconciliation".into()); + } + } + } + let directory = File::open(&dir).map_err(|_| "cannot open state directory")?; + Ok(Self { + dir, + directory, + _lock: lock, + value, + }) + } + pub(super) fn phase(&mut self, phase: &str) -> Result<(), String> { + self.value["phase"] = json!(phase); + let bytes = + serde_json::to_vec(&self.value).map_err(|_| "cannot encode switch journal")?; + let temp = self.dir.join(format!( + ".transaction-{}-{}.tmp", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| "invalid clock")? + .as_nanos() + )); + let write = (|| -> std::io::Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temp)?; + file.write_all(&bytes)?; + file.sync_all()?; + fs::rename(&temp, self.dir.join("transaction.json"))?; + self.directory.sync_all() + })(); + if write.is_err() { + let _ = fs::remove_file(&temp); + return Err( + "cannot durably record switch phase; no further action performed".into(), + ); + } + Ok(()) + } + } +} + +async fn prepare(profile: &Profile, budget: u64) -> Result<(), String> { + use std::process::Stdio; + let mut command = tokio::process::Command::new( + std::env::current_exe().map_err(|_| "cannot locate native executable")?, + ); + command + .arg("provision") + .arg("--config") + .arg(&profile.config) + .arg("--defer-memory-check") + .current_dir(&profile.working_dir) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true); + for (key, _) in std::env::vars_os() { + if key.to_string_lossy().starts_with("STRATA_") { + command.env_remove(key); + } + } + let mut child = command + .spawn() + .map_err(|_| "cannot start target provision")?; + match tokio::time::timeout(Duration::from_secs(budget), child.wait()).await { + Ok(Ok(status)) if status.success() => Ok(()), + Ok(_) => Err("target provision failed before previous service drain".into()), + Err(_) => { + child + .kill() + .await + .map_err(|_| "provision timed out; kill/reap failed")?; + Err("target provision timed out before previous service drain".into()) + } + } +} + +pub async fn run(args: &[String]) -> Result { + if args.first().is_some_and(|arg| arg == "reconcile") { + return reconcile(&args[1..]).await; + } + let args = arguments(args)?; + if !cfg!(target_os = "linux") { + return Err("service-switch requires Linux systemd user services".into()); + } + #[cfg(unix)] + { + use storage::{Journal, digest, read}; + let bytes = read(Path::new(&args["--catalog"]), true, 65536)?; + let catalog: Catalog = + serde_json::from_slice(&bytes).map_err(|_| "invalid native service catalog")?; + if catalog.schema_version != 1 + || catalog.profiles.is_empty() + || catalog.profiles.len() > 16 + || !(1..=86400).contains(&catalog.provision_timeout_s) + { + return Err("invalid catalog version/count/provision budget".into()); + } + let to = &args["--to"]; + let new = catalog.profiles.get(to).ok_or("target profile absent")?; + let auto = !args.contains_key("--from"); + let auto_digests = if auto { + Some(validate_auto(&catalog, new)?) + } else { + None + }; + let mut journal = Journal::open( + Path::new(&args["--state-dir"]), + json!({"schema_version":1,"from":args.get("--from"),"to":to,"catalog_sha256":hex::encode(Sha256::digest(&bytes))}), + )?; + let discovered = if auto { + discover(&catalog).await? + } else { + None + }; + let from = args + .get("--from") + .cloned() + .or_else(|| discovered.as_ref().map(|(id, _)| id.clone())); + if auto && from.as_ref() == Some(to) { + let expected_pid = discovered.as_ref().unwrap().1; + let readiness = crate::wait_ready::Waiter::new(&new.readiness())? + .wait(Some(expected_pid)) + .await?; + if discover(&catalog).await? != discovered + || Some(validate_auto(&catalog, new)?) != auto_digests + { + return Err("catalog changed during readiness; selection refused".into()); + } + journal.value["from"] = json!(to); + journal.phase("reused")?; + return Ok(json!({"profile":to,"reused":true,"switched":false,"readiness":readiness})); + } + if from.is_none() { + journal.value["target_config_sha256"] = json!(digest(&new.config)?); + journal.phase("preparing")?; + if let Err(error) = prepare(new, catalog.provision_timeout_s).await { + journal.phase("preflight_failed")?; + return Err(error); + } + if discover(&catalog).await?.is_some() + || Some(validate_auto(&catalog, new)?) != auto_digests + { + journal.phase("needs_reconciliation")?; + return Err("catalog changed during cold preparation; target not started".into()); + } + journal.phase("starting_target")?; + if let Ok(target) = new.control("start-ready").await { + journal.phase("committed")?; + return Ok( + json!({"profile":to,"cold_started":true,"switched":false,"manager":target["manager"],"readiness":target["readiness"]}), + ); + } + journal.phase("stopping_failed_target")?; + if !new.control("stop").await.as_ref().is_ok_and(inactive) { + journal.phase("needs_reconciliation")?; + return Err( + "cold start failed; target stop unconfirmed, reconcile services".into(), + ); + } + journal.phase("cold_failed")?; + return Err("cold start failed; target stopped (cold_failed)".into()); + } + let from = from.unwrap(); + let old = catalog + .profiles + .get(&from) + .ok_or("previous profile absent")?; + if [old, new] + .iter() + .any(|p| p.key_file.as_ref().is_some_and(|key| !key.is_absolute())) + { + return Err("catalog key_file paths must be absolute".into()); + } + // Construct both clients before any admission or manager mutation. + let old_ready = crate::wait_ready::Waiter::new(&old.readiness())?; + let _ = crate::wait_ready::Waiter::new(&new.readiness())?; + if old.unit == new.unit + || reqwest::Url::parse(&old.url).ok() != reqwest::Url::parse(&new.url).ok() + || old.config.canonicalize().ok() == new.config.canonicalize().ok() + { + return Err("profiles need distinct units/configs and the same loopback origin".into()); + } + let old_sha = digest(&old.config)?; + let new_sha = digest(&new.config)?; + journal.value["from"] = json!(from); + journal.value["previous_config_sha256"] = json!(old_sha); + journal.value["target_config_sha256"] = json!(new_sha); + let previous = old.control("status").await?; + let old_pid = pid(&previous)?; + if !inactive(&new.control("status").await?) { + return Err("target service must be installed and inactive before switch".into()); + } + old_ready.wait(Some(old_pid)).await?; + journal.phase("preparing")?; + if let Err(error) = prepare(new, catalog.provision_timeout_s).await { + journal.phase("preflight_failed")?; + return Err(error); + } + if digest(&old.config)? != old_sha + || digest(&new.config)? != new_sha + || pid(&old.control("status").await?)? != old_pid + || !inactive(&new.control("status").await?) + || (auto + && (discover(&catalog).await? != discovered + || Some(validate_auto(&catalog, new)?) != auto_digests)) + { + journal.phase("needs_reconciliation")?; + return Err("profile or service changed during preparation; no drain requested".into()); + } + journal.phase("draining_previous")?; + if old.control("drain-stop").await.is_err() { + journal.phase("needs_reconciliation")?; + return Err( + "previous drain/stop outcome needs reconciliation; target was not started".into(), + ); + } + journal.phase("starting_target")?; + let target = if digest(&new.config)? == new_sha { + new.control("start-ready").await + } else { + Err("target config changed".into()) + }; + if let Ok(target) = target { + journal.phase("committed")?; + return Ok( + json!({"switched":true,"profile":to,"previous_profile":from,"manager":target["manager"],"readiness":target["readiness"]}), + ); + } + journal.phase("stopping_failed_target")?; + let stopped = new.control("stop").await; + if !stopped.as_ref().is_ok_and(inactive) { + journal.phase("needs_reconciliation")?; + return Err("target failed; target stop unconfirmed, previous restart withheld".into()); + } + journal.phase("restoring_previous")?; + if digest(&old.config)? != old_sha || old.control("start-ready").await.is_err() { + journal.phase("needs_reconciliation")?; + return Err( + "target failed and previous readiness could not be restored; reconcile services" + .into(), + ); + } + journal.phase("rolled_back")?; + Err( + "target startup failed; previous native profile restored and ready (rolled_back)" + .into(), + ) + } + #[cfg(not(unix))] + Err("service-switch requires Linux".into()) +} + +fn reconcile_arguments(args: &[String]) -> Result, String> { + const HELP: &str = "usage: service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256"; + let mut result = BTreeMap::new(); + let (pairs, remainder) = args.as_chunks::<2>(); + if !remainder.is_empty() { + return Err(HELP.into()); + } + for [flag, value] in pairs { + if !matches!( + flag.as_str(), + "--catalog" | "--state-dir" | "--expected-journal-sha" + ) || result.insert(flag.clone(), value.clone()).is_some() + { + return Err(HELP.into()); + } + } + if result.len() != 3 { + return Err(HELP.into()); + } + let sha = &result["--expected-journal-sha"]; + if sha.len() != 64 + || !sha + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err("expected journal SHA must be 64 lowercase hex digits".into()); + } + Ok(result) +} + +async fn reconcile(args: &[String]) -> Result { + let args = reconcile_arguments(args)?; + if !cfg!(target_os = "linux") { + return Err("reconciliation requires Linux systemd user services".into()); + } + #[cfg(unix)] + { + use storage::{Journal, read}; + let state = Path::new(&args["--state-dir"]); + let mut journal = Journal::reconciliation(state)?; + let path = state.join("transaction.json"); + let bytes = read(&path, true, 65536)?; + let sha = hex::encode(Sha256::digest(&bytes)); + if sha != args["--expected-journal-sha"] { + return Err("journal acknowledgment mismatch; no reconciliation recorded".into()); + } + let prior: Value = + serde_json::from_slice(&bytes).map_err(|_| "invalid transaction journal")?; + if prior["schema_version"] != 1 + || !matches!( + prior["phase"].as_str(), + Some( + "preparing" + | "draining_previous" + | "starting_target" + | "stopping_failed_target" + | "restoring_previous" + | "needs_reconciliation" + ) + ) + { + return Err("reconciliation requires a known interrupted phase".into()); + } + let catalog_bytes = read(Path::new(&args["--catalog"]), true, 65536)?; + if prior["catalog_sha256"] != hex::encode(Sha256::digest(&catalog_bytes)) { + return Err("catalog differs from interrupted transaction".into()); + } + let catalog: Catalog = + serde_json::from_slice(&catalog_bytes).map_err(|_| "invalid native catalog")?; + if catalog.schema_version != 1 || catalog.profiles.is_empty() || catalog.profiles.len() > 16 + { + return Err("invalid catalog schema/count".into()); + } + let target = prior["to"] + .as_str() + .and_then(|id| catalog.profiles.get(id)) + .ok_or("journal target absent from catalog")?; + let digests = validate_auto(&catalog, target)?; + for (id_field, sha_field) in [ + ("from", "previous_config_sha256"), + ("to", "target_config_sha256"), + ] { + if let Some(id) = prior[id_field].as_str() { + if !digests + .get(id) + .is_some_and(|digest| prior[sha_field].as_str() == Some(digest.as_str())) + { + return Err( + "recorded configuration differs; reconcile configuration explicitly first" + .into(), + ); + } + } else if !prior[id_field].is_null() { + return Err("invalid recorded profile identity".into()); + } + } + let current = discover(&catalog).await?; + let readiness = if let Some((id, pid)) = ¤t { + Some( + crate::wait_ready::Waiter::new(&catalog.profiles[id].readiness())? + .wait(Some(*pid)) + .await?, + ) + } else { + None + }; + if discover(&catalog).await? != current + || validate_auto(&catalog, target)? != digests + || read(&path, true, 65536)? != bytes + { + return Err("state changed during reconciliation; no record written".into()); + } + journal.value = json!({"schema_version":1,"catalog_sha256":prior["catalog_sha256"], + "prior_journal_sha256":sha,"prior_phase":prior["phase"],"from":prior["from"],"to":prior["to"], + "verified_profile":current.as_ref().map(|(id,_)|id),"verified_pid":current.as_ref().map(|(_,pid)|pid)}); + journal.phase("reconciled")?; + Ok( + json!({"reconciled":true,"lifecycle_action_requested":false,"profile":current.as_ref().map(|(id,_)|id), + "pid":current.as_ref().map(|(_,pid)|pid),"prior_journal_sha256":sha,"readiness":readiness}), + ) + } + #[cfg(not(unix))] + Err("reconciliation requires Linux".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn reconciliation_requires_explicit_exact_digest_arguments() { + let args = vec![ + "--catalog".into(), + "/catalog".into(), + "--state-dir".into(), + "/state".into(), + "--expected-journal-sha".into(), + "a".repeat(64), + ]; + assert!(reconcile_arguments(&args).is_ok()); + for digest in ["a".repeat(63), "A".repeat(64), "z".repeat(64)] { + let mut bad = args.clone(); + bad[5] = digest; + assert!(reconcile_arguments(&bad).is_err()); + } + assert!(reconcile_arguments(&args[..5]).is_err()); + let mut duplicate = args.clone(); + duplicate.extend(args[..2].iter().cloned()); + assert!(reconcile_arguments(&duplicate).is_err()); + } + #[test] + fn explicit_distinct_profiles_and_strict_catalog() { + assert!(arguments(&[]).is_err()); + let mut args = [ + "--catalog", + "/catalog", + "--from", + "a", + "--to", + "b", + "--state-dir", + "/state", + ] + .map(str::to_owned); + assert!(arguments(&args).is_ok()); + assert!( + arguments(&[ + args[0].clone(), + args[1].clone(), + args[4].clone(), + args[5].clone(), + args[6].clone(), + args[7].clone() + ]) + .is_ok() + ); + args[5] = "a".into(); + assert!(arguments(&args).is_err()); + assert!(serde_json::from_value::(json!({"unit":"a","config":"/a","working_dir":"/a","url":"http://127.0.0.1","model":"a","env_file":"/unsupported"})).is_err()); + } + #[test] + fn selection_refuses_ambiguous_or_unsettled_manager_state() { + let running = + json!({"manager":{"main_pid":42,"active_state":"active","sub_state":"running"}}); + let stopped = + json!({"manager":{"main_pid":0,"active_state":"inactive","sub_state":"dead"}}); + assert_eq!( + select_active(&[("a".into(), stopped.clone())]).unwrap(), + None + ); + assert_eq!( + select_active(&[("a".into(), stopped), ("b".into(), running.clone())]).unwrap(), + Some(("b".into(), 42)) + ); + assert!(select_active(&[("a".into(), running.clone()), ("b".into(), running)]).is_err()); + for state in ["failed", "activating", "deactivating", "unknown"] { + assert!( + select_active(&[( + "a".into(), + json!({"manager":{"main_pid":0,"active_state":state}}) + )]) + .is_err() + ); + } + } + #[cfg(unix)] + #[test] + fn durable_phases_lock_and_private_inputs_fail_closed() { + use std::{ + fs, + os::unix::fs::{PermissionsExt, symlink}, + }; + let root = std::env::temp_dir().join(format!( + "strata-switch-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); + assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); + journal.phase("preparing").unwrap(); + let path = root.join("transaction.json"); + let state: Value = + serde_json::from_slice(&storage::read(&path, true, 65536).unwrap()).unwrap(); + assert_eq!(state["phase"], "preparing"); + journal.phase("rolled_back").unwrap(); + drop(journal); + let mut journal = storage::Journal::open(&root, json!({"schema_version":1})).unwrap(); + journal.phase("starting_target").unwrap(); + drop(journal); + assert!(storage::Journal::open(&root, json!({"schema_version":1})).is_err()); + let alias = root.join("alias"); + symlink(&path, &alias).unwrap(); + assert!(storage::read(&alias, true, 65536).is_err()); + assert!(storage::read(&path, true, 1).is_err()); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(storage::read(&path, true, 65536).is_err()); + assert!(storage::read(&path, false, 65536).is_ok()); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/control-plane/src/service_unit.rs b/control-plane/src/service_unit.rs new file mode 100644 index 00000000..ce5235e5 --- /dev/null +++ b/control-plane/src/service_unit.rs @@ -0,0 +1,135 @@ +//! Render only: installation and lifecycle remain explicit operator actions. +use std::path::Path; + +pub fn render( + executable: &Path, + config: &Path, + working_dir: &Path, + env_file: Option<&Path>, +) -> Result { + let executable = checked_path(executable, false)?; + if executable.contains(['\'', '"', '\\']) { + return Err( + "systemd executable paths cannot contain quotes or backslashes; relocate the binary" + .into(), + ); + } + let executable = quote(&executable); + let config = quote(&checked_path(config, false)?); + checked_path(working_dir, true)?; + let canonical_dir = working_dir.canonicalize().map_err(|e| e.to_string())?; + // These path directives are not shell-style token lists. Quotes and + // backslashes are literal; a final '/.' prevents line continuation/trim. + let working_dir = format!( + "{}/.", + checked_path(&canonical_dir, true)?.trim_end_matches('/') + ) + .replace('%', "%%"); + let environment = match env_file { + Some(path) => { + let value = checked_path(path, false)?; + // EnvironmentFile supports globs. Fail rather than load a different + // file, or silently treat a missing optional file as success. + if value.contains(['*', '?', '[', '\\']) || value.ends_with(char::is_whitespace) { + return Err("environment-file paths cannot contain glob characters/backslashes or end in whitespace".into()); + } + format!("EnvironmentFile={}\n", value.replace('%', "%%")) + } + None => String::new(), + }; + // ':' disables ExecStart environment-variable substitution; %% escapes + // specifiers. Do not wrap this in a shell or reset the worker restart budget. + Ok(format!( + "# Generated by strata-next service-unit; install as a user unit.\n\ + [Unit]\n\ + Description=Strata Next native Responses runtime\n\ + \n\ + [Service]\n\ + Type=exec\n\ + WorkingDirectory={working_dir}\n\ + {environment}\ + ExecStart=:{executable} serve --config {config}\n\ + UMask=0077\n\ + NoNewPrivileges=yes\n\ + KillSignal=SIGTERM\n\ + KillMode=mixed\n\ + TimeoutStopSec=45\n\ + SendSIGKILL=yes\n\ + Restart=no\n\ + StandardOutput=journal\n\ + StandardError=journal\n\ + \n\ + [Install]\n\ + WantedBy=default.target\n" + )) +} + +fn checked_path(path: &Path, directory: bool) -> Result { + let value = path.to_str().ok_or("service paths must be valid UTF-8")?; + if !path.is_absolute() || value.chars().any(char::is_control) { + return Err("service paths must be absolute and contain no control characters".into()); + } + if if directory { + !path.is_dir() + } else { + !path.is_file() + } { + return Err(format!( + "service path has wrong type or does not exist: {value}" + )); + } + Ok(value.to_owned()) +} + +fn quote(value: &str) -> String { + format!( + "\"{}\"", + value + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('%', "%%") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn special_characters_are_literal() { + assert_eq!( + quote("/srv/a b/%n/${HOME}/\"quoted\"/back\\slash"), + "\"/srv/a b/%%n/${HOME}/\\\"quoted\\\"/back\\\\slash\"" + ); + } + + #[test] + fn refuses_relative_control_and_missing_paths() { + for path in ["relative.json", "/tmp/line\nbreak", "/tmp/zero\0byte"] { + assert!(checked_path(Path::new(path), false).is_err()); + } + let missing = std::env::temp_dir().join(format!( + "strata-service-missing-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + assert!(checked_path(&missing, false).is_err()); + } + + #[test] + fn render_does_not_require_or_launch_an_engine() { + let executable = std::env::current_exe().unwrap(); + let directory = executable.parent().unwrap(); + let unit = render(&executable, &executable, directory, Some(&executable)).unwrap(); + assert!(unit.contains("ExecStart=:")); + assert!(unit.contains(" serve --config ")); + assert!(unit.contains("EnvironmentFile=")); + assert!(unit.contains("KillMode=mixed\nTimeoutStopSec=45\n")); + assert!(unit.contains("Restart=no\n")); + assert!(render(&executable, directory, directory, None).is_err()); + assert!(render(&executable, &executable, &executable, None).is_err()); + } +} diff --git a/control-plane/src/stream_parts.rs b/control-plane/src/stream_parts.rs new file mode 100644 index 00000000..7752baed --- /dev/null +++ b/control-plane/src/stream_parts.rs @@ -0,0 +1,357 @@ +//! KAR-2 uses a u32 byte stride for each bit plane. Very large GGUF tensors +//! must become adjacent archive records while retaining one virtual F32 stream. + +use std::{collections::HashSet, fs::File, path::Path}; + +use sha2::{Digest, Sha256}; + +use crate::{derived_mixed, gguf, gguf_f32_stream}; + +// A 32-billion-element part has a 4-billion-byte plane, below KAR-2's u32 +// stride limit. The margin also accommodates the required 16-byte alignment. +pub const MAX_PART_ELEMENTS: u64 = 32_000_000_000; +pub const PLE_TENSOR_NAME: &str = "per_layer_token_embd.weight"; + +pub fn validate_ple_limit(limit: u64) -> Result<(), String> { + if !(32..=MAX_PART_ELEMENTS).contains(&limit) { + return Err("PLE part element limit must be 32..=32,000,000,000".into()); + } + Ok(()) +} + +#[derive(Clone, Debug)] +pub struct PartIdentity { + pub name: String, + pub parent_name: String, + pub parent_dimensions: Vec, + pub dimensions: Vec, + pub source_kind: u32, + pub source_byte_offset: u64, + pub source_bytes: u64, + pub source_sha256: [u8; 32], + pub derived_offset: u64, + pub derived_bytes: u64, + pub f32_sha256: [u8; 32], +} + +#[derive(Debug)] +struct Layout { + name: String, + dimensions: Vec, + source_byte_offset: u64, + source_bytes: u64, + derived_offset: u64, + derived_bytes: u64, +} + +fn layout_with_limit( + tensor: &gguf::TensorInfo, + derived_offset: u64, + max_part_elements: u64, +) -> Result, String> { + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |n, d| n.checked_mul(*d)) + .ok_or("GGUF tensor element count overflow")?; + let (block_elements, block_bytes) = gguf::block_geometry(tensor.kind) + .ok_or_else(|| format!("unsupported GGUF source kind {}", tensor.kind))?; + if elements == 0 || !elements.is_multiple_of(block_elements) { + return Err(format!("{}: invalid GGUF block geometry", tensor.name)); + } + let source_bytes = (elements / block_elements) + .checked_mul(block_bytes) + .ok_or("GGUF tensor source byte count overflow")?; + if source_bytes != tensor.bytes { + return Err(format!( + "{}: GGUF tensor span differs from geometry", + tensor.name + )); + } + if elements <= max_part_elements { + return Ok(vec![Layout { + name: tensor.name.clone(), + dimensions: tensor.dimensions.clone(), + source_byte_offset: 0, + source_bytes, + derived_offset, + derived_bytes: elements.checked_mul(4).ok_or("F32 byte count overflow")?, + }]); + } + let (&rows, inner_dimensions) = tensor + .dimensions + .split_last() + .ok_or("GGUF tensor has no dimensions")?; + let row_elements = inner_dimensions + .iter() + .try_fold(1u64, |n, d| n.checked_mul(*d)) + .ok_or("GGUF tensor row size overflow")?; + let alignment = block_elements.max(32); + let row_multiple = alignment / gcd(row_elements, alignment); + let max_rows = max_part_elements / row_elements; + let rows_per_part = max_rows / row_multiple * row_multiple; + if rows_per_part == 0 { + return Err(format!( + "{}: one GGUF row exceeds KAR-2 part limit", + tensor.name + )); + } + let count = rows.div_ceil(rows_per_part); + if count > 100_000 { + return Err("KAR-2 part count exceeds tensor limit".into()); + } + let mut result = Vec::with_capacity(count as usize); + let mut source_cursor = 0u64; + let mut derived_cursor = derived_offset; + for number in 0..count { + let row_start = number * rows_per_part; + let part_rows = rows.saturating_sub(row_start).min(rows_per_part); + let part_elements = row_elements + .checked_mul(part_rows) + .ok_or("KAR part element count overflow")?; + if !part_elements.is_multiple_of(block_elements) { + return Err("KAR part does not end on a GGUF block boundary".into()); + } + let bytes = part_elements / block_elements * block_bytes; + let derived_bytes = part_elements + .checked_mul(4) + .ok_or("KAR part F32 byte count overflow")?; + let mut dimensions = tensor.dimensions.clone(); + *dimensions + .last_mut() + .ok_or("GGUF tensor has no dimensions")? = part_rows; + result.push(Layout { + name: format!( + "{}#strata-part-{:03}-of-{:03}", + tensor.name, + number + 1, + count + ), + dimensions, + source_byte_offset: source_cursor, + source_bytes: bytes, + derived_offset: derived_cursor, + derived_bytes, + }); + source_cursor = source_cursor + .checked_add(bytes) + .ok_or("KAR part source offset overflow")?; + derived_cursor = derived_cursor + .checked_add(derived_bytes) + .ok_or("KAR part derived offset overflow")?; + } + let expected_end = derived_offset + .checked_add(elements.checked_mul(4).ok_or("F32 byte count overflow")?) + .ok_or("F32 offset overflow")?; + if source_cursor != tensor.bytes || derived_cursor != expected_end { + return Err("KAR parts do not cover their GGUF tensor".into()); + } + Ok(result) +} + +fn gcd(mut left: u64, mut right: u64) -> u64 { + while right != 0 { + (left, right) = (right, left % right); + } + left +} + +/// Plan and fingerprint all archive records, including any parts of oversized +/// tensors. Unsplit tensor hashes come from the independently verified source +/// identity; split parts are re-read and checked against their parent hashes. +pub fn plan_shards( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, +) -> Result>, String> { + plan_shards_with_limit(identity, source_dir, MAX_PART_ELEMENTS) +} + +pub(crate) fn plan_shards_with_limit( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + max_part_elements: u64, +) -> Result>, String> { + plan_shards_with_limits(identity, source_dir, max_part_elements, None) +} + +pub fn plan_shards_with_ple_limit( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + ple_part_elements: u64, +) -> Result>, String> { + validate_ple_limit(ple_part_elements)?; + plan_shards_with_limits( + identity, + source_dir, + MAX_PART_ELEMENTS, + Some(ple_part_elements), + ) +} + +fn plan_shards_with_limits( + identity: &derived_mixed::ShardedIdentity, + source_dir: &Path, + max_part_elements: u64, + ple_part_elements: Option, +) -> Result>, String> { + let mut result = Vec::with_capacity(identity.tensors.len()); + let mut names = HashSet::new(); + let mut number = 0usize; + let mut saw_ple = false; + for shard in &identity.shards { + let path = source_dir.join(&shard.name); + let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?; + if index.tensors.len() != shard.tensor_count { + return Err("GGUF shard changed during KAR part planning".into()); + } + let mut source = File::open(&path).map_err(|error| error.to_string())?; + for tensor in &index.tensors { + let original = identity + .tensors + .get(number) + .ok_or("GGUF tensor count differs from virtual source")?; + if original.name != tensor.name || original.source_kind != tensor.kind { + return Err("GGUF tensor differs from virtual source".into()); + } + let part_limit = if tensor.name == PLE_TENSOR_NAME { + saw_ple = true; + ple_part_elements.unwrap_or(max_part_elements) + } else { + max_part_elements + }; + let layouts = layout_with_limit(tensor, original.derived_offset, part_limit)?; + if tensor.name == PLE_TENSOR_NAME && ple_part_elements.is_some() && layouts.len() < 2 { + return Err("PLE part limit must split the PLE tensor".into()); + } + let split = layouts.len() > 1; + let mut parent_source = Sha256::new(); + let mut parent_f32 = Sha256::new(); + let mut parts = Vec::with_capacity(layouts.len()); + for part in layouts { + if !names.insert(part.name.clone()) { + return Err(format!("duplicate KAR part name: {}", part.name)); + } + let (source_sha256, f32_sha256) = if split { + let absolute = index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|n| n.checked_add(part.source_byte_offset)) + .ok_or("GGUF part offset overflow")?; + let mut source_hash = Sha256::new(); + let mut f32_hash = Sha256::new(); + let count = gguf_f32_stream::visit( + &mut source, + absolute, + tensor.kind, + part.source_bytes, + |raw, f32_bytes| { + source_hash.update(raw); + f32_hash.update(f32_bytes); + parent_source.update(raw); + parent_f32.update(f32_bytes); + Ok(()) + }, + )?; + if count != part.derived_bytes { + return Err("GGUF part derived byte count mismatch".into()); + } + (source_hash.finalize().into(), f32_hash.finalize().into()) + } else { + (original.source_sha256, original.f32_sha256) + }; + parts.push(PartIdentity { + name: part.name, + parent_name: tensor.name.clone(), + parent_dimensions: tensor.dimensions.clone(), + dimensions: part.dimensions, + source_kind: tensor.kind, + source_byte_offset: part.source_byte_offset, + source_bytes: part.source_bytes, + source_sha256, + derived_offset: part.derived_offset, + derived_bytes: part.derived_bytes, + f32_sha256, + }); + } + if split + && (parent_source.finalize().as_slice() != original.source_sha256 + || parent_f32.finalize().as_slice() != original.f32_sha256) + { + return Err(format!( + "{}: KAR part hashes differ from source", + tensor.name + )); + } + result.push(parts); + number += 1; + } + } + if number != identity.tensors.len() { + return Err("GGUF tensor count differs from virtual source".into()); + } + if ple_part_elements.is_some() && !saw_ple { + return Err("PLE partition policy requires per_layer_token_embd.weight".into()); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn giant_per_layer_tensor_becomes_two_contiguous_kar_parts() { + let tensor = gguf::TensorInfo { + name: "per_layer_token_embd.weight".into(), + dimensions: vec![160, 320_001_536], + kind: 20, + offset: 0, + bytes: 28_800_138_240, + }; + let parts = layout_with_limit(&tensor, 17, MAX_PART_ELEMENTS).unwrap(); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0].dimensions, [160, 200_000_000]); + assert_eq!(parts[1].dimensions, [160, 120_001_536]); + assert_eq!(parts[0].source_byte_offset, 0); + assert_eq!(parts[0].source_bytes, 18_000_000_000); + assert_eq!(parts[1].source_byte_offset, parts[0].source_bytes); + assert_eq!(parts[1].source_bytes, 10_800_138_240); + assert_eq!(parts[0].derived_offset, 17); + assert_eq!(parts[1].derived_offset, 17 + parts[0].derived_bytes); + assert_eq!( + parts[1].derived_offset + parts[1].derived_bytes, + 17 + 204_800_983_040 + ); + } + + #[test] + fn ple_budget_partition_keeps_rows_and_source_offsets_contiguous() { + let tensor = gguf::TensorInfo { + name: PLE_TENSOR_NAME.into(), + dimensions: vec![160, 320_001_536], + kind: 20, + offset: 0, + bytes: 28_800_138_240, + }; + let parts = layout_with_limit(&tensor, 17, 100_000_000).unwrap(); + assert_eq!(parts.len(), 513); + assert_eq!(parts[0].dimensions, [160, 625_000]); + assert_eq!(parts.last().unwrap().dimensions, [160, 1_536]); + assert!(parts.iter().all(|part| part.dimensions[0] == 160)); + for pair in parts.windows(2) { + assert_eq!( + pair[0].source_byte_offset + pair[0].source_bytes, + pair[1].source_byte_offset + ); + assert_eq!( + pair[0].derived_offset + pair[0].derived_bytes, + pair[1].derived_offset + ); + } + assert_eq!( + parts.last().unwrap().source_byte_offset + parts.last().unwrap().source_bytes, + tensor.bytes + ); + } +} diff --git a/control-plane/src/tensor_export.rs b/control-plane/src/tensor_export.rs new file mode 100644 index 00000000..928b5778 --- /dev/null +++ b/control-plane/src/tensor_export.rs @@ -0,0 +1,94 @@ +//! Lossless, bounded projection export for offline Keyless conversion. + +use crate::{gguf, gguf_f32_stream}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::{ + fs::{File, OpenOptions}, + io::Write, + path::Path, +}; + +#[derive(Serialize)] +pub struct Export { + pub tensor: String, + pub dimensions: Vec, + pub source_kind: u32, + pub source_bytes: u64, + pub source_tensor_sha256: String, + pub source_fnv1a64: String, + pub f32_bytes: u64, + pub f32_sha256: String, + pub decoder: &'static str, +} + +pub fn export(source: &Path, name: &str, destination: &Path) -> Result { + let index = gguf::tensor_index(source).map_err(|e| e.to_string())?; + let tensor = index + .tensors + .iter() + .find(|t| t.name == name) + .ok_or_else(|| format!("GGUF tensor not found: {name}"))?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |n, d| n.checked_mul(*d)) + .ok_or("tensor element count overflow")?; + let expected = elements.checked_mul(4).ok_or("F32 byte count overflow")?; + let offset = index + .summary + .data_start + .checked_add(tensor.offset) + .ok_or("tensor offset overflow")?; + let mut input = File::open(source).map_err(|e| e.to_string())?; + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut output = options.open(destination).map_err(|e| e.to_string())?; + let mut source_hash = Sha256::new(); + let mut decoded_hash = Sha256::new(); + let mut source_fnv = 0xcbf29ce484222325u64; + let result = (|| { + let bytes = + gguf_f32_stream::visit(&mut input, offset, tensor.kind, tensor.bytes, |raw, f32| { + if f32 + .as_chunks::<4>() + .0 + .iter() + .any(|bits| !f32::from_le_bytes(*bits).is_finite()) + { + return Err("projection contains nonfinite values".into()); + } + source_hash.update(raw); + for byte in raw { + source_fnv = (source_fnv ^ u64::from(*byte)).wrapping_mul(0x100000001b3); + } + decoded_hash.update(f32); + output.write_all(f32).map_err(|e| e.to_string()) + })?; + if bytes != expected { + return Err("decoded tensor size does not match GGUF dimensions".into()); + } + output.sync_all().map_err(|e| e.to_string())?; + Ok(Export { + tensor: name.into(), + dimensions: tensor.dimensions.clone(), + source_kind: tensor.kind, + source_bytes: tensor.bytes, + source_tensor_sha256: hex::encode(source_hash.finalize()), + source_fnv1a64: format!("{source_fnv:016x}"), + f32_bytes: bytes, + f32_sha256: hex::encode(decoded_hash.finalize()), + decoder: "strata-next/gguf-f32-stream:ggml-3cf03257", + }) + })(); + drop(output); + if result.is_err() { + let _ = std::fs::remove_file(destination); + } + result +} diff --git a/control-plane/src/tokenizer.rs b/control-plane/src/tokenizer.rs new file mode 100644 index 00000000..56dafd2d --- /dev/null +++ b/control-plane/src/tokenizer.rs @@ -0,0 +1,486 @@ +//! Native qwen35 byte-level BPE, matching the pinned Strata tokenizer oracle. + +use std::{ + cmp::Reverse, + collections::{BinaryHeap, HashMap}, + error::Error, + fs, + path::Path, +}; + +use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind}; +use fancy_regex::Regex; +use serde::Deserialize; + +use crate::tokenizer_assets::QWEN35_PATTERN; + +type Result = std::result::Result>; + +#[derive(Deserialize)] +struct Config { + model: String, + pre: String, + vocab_size: usize, + n_merges: usize, + pre_pattern: String, + special_ids: HashMap, +} + +struct LiteralMatcher { + search: AhoCorasick, + ids: Vec, +} + +pub struct Tokenizer { + tokens: Vec, + vocab: HashMap, + ranks: HashMap, + pattern: Regex, + always: Option, + special: Option, + byte_chars: [char; 256], + char_bytes: HashMap, +} + +impl Tokenizer { + pub fn from_assets(path: &Path) -> Result { + let config: Config = serde_json::from_slice(&fs::read(path.join("tokenizer.json"))?)?; + if config.model != "gpt2" || config.pre != "qwen35" || config.pre_pattern != QWEN35_PATTERN + { + return Err("unsupported tokenizer model, pre-tokenizer, or pattern".into()); + } + let vocab: HashMap = + serde_json::from_slice(&fs::read(path.join("vocab.json"))?)?; + if vocab.len() != config.vocab_size || vocab.is_empty() { + return Err("tokenizer vocabulary size mismatch".into()); + } + let mut ordered = vec![None; vocab.len()]; + for (token, &id) in &vocab { + let slot = ordered + .get_mut(id as usize) + .ok_or("tokenizer ID exceeds vocabulary length")?; + if slot.replace(token.clone()).is_some() { + return Err("duplicate tokenizer ID".into()); + } + } + let tokens = ordered + .into_iter() + .collect::>>() + .ok_or("tokenizer IDs are not contiguous")?; + if tokens.iter().any(|token| token.contains('\0')) { + return Err("tokenizer vocabulary contains a NUL character".into()); + } + let merge_text = fs::read_to_string(path.join("merges.txt"))?; + let merges: Vec<&str> = if merge_text.is_empty() { + Vec::new() + } else { + merge_text.split('\n').collect() + }; + if merges.len() != config.n_merges { + return Err("tokenizer merge count mismatch".into()); + } + let token_types: Option> = + serde_json::from_slice(&fs::read(path.join("token_type.json"))?)?; + if token_types + .as_ref() + .is_some_and(|types| types.len() != tokens.len()) + { + return Err("token type count mismatch".into()); + } + let mut ranks = HashMap::with_capacity(merges.len()); + for (rank, merge) in merges.iter().enumerate() { + let Some((left, right)) = merge.split_once(' ') else { + return Err("BPE merge is not a pair".into()); + }; + if left.is_empty() + || right.is_empty() + || right.contains(' ') + || !vocab.contains_key(left) + || !vocab.contains_key(right) + || ranks.insert(pair_key(left, right), rank).is_some() + { + return Err("BPE merge is invalid or duplicated".into()); + } + } + for &id in config.special_ids.values() { + if id as usize >= tokens.len() { + return Err("special token ID exceeds vocabulary".into()); + } + } + let types = token_types.unwrap_or_default(); + let always = literal_matcher(&tokens, &types, false)?; + let special = literal_matcher(&tokens, &types, true)?; + let pattern = Regex::new(QWEN35_PATTERN)?; + let (byte_chars, char_bytes) = byte_alphabet(); + Ok(Self { + tokens, + vocab, + ranks, + pattern, + always, + special, + byte_chars, + char_bytes, + }) + } + + pub fn special_id(&self, token: &str) -> Option { + self.vocab.get(token).copied() + } + + pub fn encode(&self, text: &str, parse_special: bool) -> Result> { + let matcher = if parse_special { + &self.special + } else { + &self.always + }; + let Some(matcher) = matcher else { + return self.encode_plain(text); + }; + let mut ids = Vec::new(); + let mut offset = 0; + for found in matcher.search.find_iter(text) { + ids.extend(self.encode_plain(&text[offset..found.start()])?); + ids.push(matcher.ids[found.pattern().as_usize()]); + offset = found.end(); + } + ids.extend(self.encode_plain(&text[offset..])?); + Ok(ids) + } + + pub fn decode(&self, ids: &[u32]) -> Result { + Ok(String::from_utf8_lossy(&self.decode_bytes(ids)?).into_owned()) + } + + pub fn decode_bytes(&self, ids: &[u32]) -> Result> { + let mut bytes = Vec::new(); + for &id in ids { + let token = self + .tokens + .get(id as usize) + .ok_or("token ID exceeds vocabulary")?; + for ch in token.chars() { + bytes.push( + *self + .char_bytes + .get(&ch) + .ok_or("token is outside byte alphabet")?, + ); + } + } + Ok(bytes) + } + + fn encode_plain(&self, text: &str) -> Result> { + let mut ids = Vec::new(); + let mut offset = 0; + for found in self.pattern.find_iter(text) { + let piece = found?; + if piece.start() != offset || piece.end() == offset { + return Err("qwen35 pre-tokenizer left an unmatched text span".into()); + } + let mapped: String = piece + .as_str() + .as_bytes() + .iter() + .map(|byte| self.byte_chars[*byte as usize]) + .collect(); + let parts = if mapped.chars().count() > 64 { + self.bpe_heap(&mapped) + } else { + self.bpe_scan(&mapped) + }; + for token in parts { + ids.push( + *self + .vocab + .get(&token) + .ok_or("BPE produced a token outside the vocabulary")?, + ); + } + offset = piece.end(); + } + if offset != text.len() { + return Err("qwen35 pre-tokenizer left an unmatched text suffix".into()); + } + Ok(ids) + } + + fn rank(&self, left: &str, right: &str) -> Option { + self.ranks.get(&pair_key(left, right)).copied() + } + + fn bpe_scan(&self, word: &str) -> Vec { + let mut parts: Vec = word.chars().map(|ch| ch.to_string()).collect(); + while parts.len() > 1 { + let mut best = None; + for index in 0..parts.len() - 1 { + if let Some(rank) = self.rank(&parts[index], &parts[index + 1]) + && best.is_none_or(|(_, current)| rank < current) + { + best = Some((index, rank)); + } + } + let Some((index, _)) = best else { break }; + let right = parts.remove(index + 1); + parts[index].push_str(&right); + } + parts + } + + fn bpe_heap(&self, word: &str) -> Vec { + let mut nodes: Vec = word + .chars() + .enumerate() + .map(|(index, ch)| Node { + text: ch.to_string(), + prev: index.checked_sub(1), + next: Some(index + 1), + version: 0, + alive: true, + }) + .collect(); + if let Some(last) = nodes.last_mut() { + last.next = None; + } + let mut heap = BinaryHeap::new(); + for left in 0..nodes.len().saturating_sub(1) { + self.push_pair(&nodes, left, &mut heap); + } + while let Some(Reverse((_, left, right, left_version, right_version))) = heap.pop() { + if !nodes[left].alive + || !nodes[right].alive + || nodes[left].next != Some(right) + || nodes[left].version != left_version + || nodes[right].version != right_version + { + continue; + } + let successor = nodes[right].next; + let merged = std::mem::take(&mut nodes[right].text); + nodes[left].text.push_str(&merged); + nodes[left].next = successor; + nodes[left].version += 1; + nodes[right].alive = false; + if let Some(next) = successor { + nodes[next].prev = Some(left); + } + self.push_pair(&nodes, left, &mut heap); + if let Some(prev) = nodes[left].prev { + self.push_pair(&nodes, prev, &mut heap); + } + } + let mut parts = Vec::new(); + let mut current = (!nodes.is_empty()).then_some(0); + while let Some(index) = current { + parts.push(std::mem::take(&mut nodes[index].text)); + current = nodes[index].next; + } + parts + } + + fn push_pair(&self, nodes: &[Node], left: usize, heap: &mut BinaryHeap>) { + if let Some(right) = nodes[left].next + && let Some(rank) = self.rank(&nodes[left].text, &nodes[right].text) + { + heap.push(Reverse(( + rank, + left, + right, + nodes[left].version, + nodes[right].version, + ))); + } + } +} + +type HeapEntry = (usize, usize, usize, u64, u64); + +struct Node { + text: String, + prev: Option, + next: Option, + version: u64, + alive: bool, +} + +fn pair_key(left: &str, right: &str) -> String { + let mut key = String::with_capacity(left.len() + right.len() + 1); + key.push_str(left); + key.push('\0'); + key.push_str(right); + key +} + +fn literal_matcher( + tokens: &[String], + types: &[u32], + include_control: bool, +) -> Result> { + let selected: Vec<(u32, &str)> = types + .iter() + .enumerate() + .filter(|(_, kind)| **kind == 4 || (include_control && **kind == 3)) + .map(|(id, _)| (id as u32, tokens[id].as_str())) + .collect(); + if selected.iter().any(|(_, token)| token.is_empty()) { + return Err("empty special token literal".into()); + } + if selected.is_empty() { + return Ok(None); + } + let ids = selected.iter().map(|(id, _)| *id).collect(); + let search = AhoCorasickBuilder::new() + .match_kind(MatchKind::LeftmostLongest) + .build(selected.iter().map(|(_, token)| *token))?; + Ok(Some(LiteralMatcher { search, ids })) +} + +pub(crate) fn byte_alphabet() -> ([char; 256], HashMap) { + let mut chars = ['\0'; 256]; + for byte in (0x21..=0x7e).chain(0xa1..=0xac).chain(0xae..=0xff) { + chars[byte] = char::from_u32(byte as u32).expect("byte code point"); + } + let mut next = 0; + for mapped in &mut chars { + if *mapped == '\0' { + *mapped = char::from_u32(256 + next).expect("shifted byte code point"); + next += 1; + } + } + let reverse = chars + .iter() + .enumerate() + .map(|(byte, &ch)| (ch, byte as u8)) + .collect(); + (chars, reverse) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn byte_alphabet_is_bijective() { + let (forward, reverse) = byte_alphabet(); + assert_eq!(reverse.len(), 256); + for (byte, ch) in forward.iter().enumerate() { + assert_eq!(reverse[ch], byte as u8); + } + assert_eq!(forward[b' ' as usize], 'Ġ'); + } + + #[test] + fn heap_and_scan_choose_the_same_rank_order() { + let mut ranks = HashMap::new(); + ranks.insert(pair_key("a", "b"), 1); + ranks.insert(pair_key("b", "a"), 2); + ranks.insert(pair_key("ab", "a"), 3); + let (byte_chars, char_bytes) = byte_alphabet(); + let tokenizer = Tokenizer { + tokens: vec![], + vocab: HashMap::new(), + ranks, + pattern: Regex::new(QWEN35_PATTERN).unwrap(), + always: None, + special: None, + byte_chars, + char_bytes, + }; + for word in [ + "aba", + "ababa", + "aaabbb", + "abababab", + "ab".repeat(100).as_str(), + ] { + assert_eq!(tokenizer.bpe_scan(word), tokenizer.bpe_heap(word)); + } + } + + #[test] + fn qwen35_matches_oracle_ids_for_merges_unicode_and_specials() { + let root = std::env::temp_dir().join(format!("strata-bpe-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let (alphabet, _) = byte_alphabet(); + let mut tokens: Vec = alphabet.iter().map(char::to_string).collect(); + tokens.extend( + [ + "He", + "Hel", + "ll", + "llo", + "xx", + "xxxx", + "<|im_end|>", + "", + ] + .map(str::to_owned), + ); + let vocab: HashMap<_, _> = tokens + .iter() + .enumerate() + .map(|(id, token)| (token, id as u32)) + .collect(); + let mut types = vec![1; tokens.len()]; + types[262] = 3; + types[263] = 4; + fs::write(root.join("vocab.json"), serde_json::to_vec(&vocab).unwrap()).unwrap(); + fs::write(root.join("merges.txt"), "H e\nHe l\nl l\nll o\nx x\nxx xx").unwrap(); + fs::write( + root.join("token_type.json"), + serde_json::to_vec(&types).unwrap(), + ) + .unwrap(); + fs::write( + root.join("tokenizer.json"), + serde_json::to_vec(&json!({ + "model": "gpt2", "pre": "qwen35", "vocab_size": tokens.len(), + "n_merges": 6, "pre_pattern": QWEN35_PATTERN, + "special_ids": {"tokenizer.ggml.eos_token_id": 262}, + })) + .unwrap(), + ) + .unwrap(); + let tokenizer = Tokenizer::from_assets(&root).unwrap(); + assert_eq!( + tokenizer.encode("Hello, world!", false).unwrap(), + vec![257, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] + ); + assert_eq!( + tokenizer + .encode("e\u{301}\u{301} combining", false) + .unwrap(), + vec![ + 101, 204, 129, 204, 129, 32, 99, 111, 109, 98, 105, 110, 105, 110, 103 + ] + ); + assert_eq!( + tokenizer.encode("<|im_end|>", false).unwrap(), + vec![60, 124, 105, 109, 95, 101, 110, 100, 124, 62] + ); + assert_eq!(tokenizer.encode("<|im_end|>", true).unwrap(), vec![262]); + assert_eq!( + tokenizer.encode("", false).unwrap(), + vec![263] + ); + assert_eq!(tokenizer.decode(&[226]).unwrap(), "�"); + assert_eq!(tokenizer.decode_bytes(&[226]).unwrap(), vec![226]); + assert_eq!( + tokenizer.encode(&"x".repeat(65), false).unwrap(), + [vec![261; 16], vec![120]].concat() + ); + for sample in [ + "你好,世界", + "😀🚀🇺🇸", + "\0\x01\x7f", + "x".repeat(5000).as_str(), + ] { + let ids = tokenizer.encode(sample, false).unwrap(); + assert_eq!(tokenizer.decode(&ids).unwrap(), sample); + } + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/control-plane/src/tokenizer_assets.rs b/control-plane/src/tokenizer_assets.rs new file mode 100644 index 00000000..a0cec9a5 --- /dev/null +++ b/control-plane/src/tokenizer_assets.rs @@ -0,0 +1,161 @@ +//! Extract the Qwen tokenizer assets from GGUF without a Python runtime. + +use std::{ + collections::BTreeMap, + error::Error, + fs::{self, File}, + io::Write, + path::{Path, PathBuf}, +}; + +use serde_json::json; + +use crate::gguf; + +type Result = std::result::Result>; + +// Kept byte-for-byte equivalent to the upstream qwen35 oracle pattern. +pub(crate) const QWEN35_PATTERN: &str = concat!( + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])", + r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+", + r"|\p{N}", + r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*", + r"|\s*[\r\n]+", + r"|\s+(?!\S)", + r"|\s+", +); + +pub fn extract(gguf_path: &Path, output: &Path) -> Result { + let metadata = gguf::tokenizer_metadata(gguf_path)?; + fs::create_dir_all(output)?; + let destination = output.join("tokenizer"); + if destination.exists() || destination.is_symlink() { + return Err(format!( + "tokenizer destination already exists: {}", + destination.display() + ) + .into()); + } + let stage = output.join(format!(".tokenizer-{}.tmp", std::process::id())); + fs::create_dir(&stage)?; + let result = (|| -> Result<()> { + let mut vocab = BTreeMap::new(); + for (id, token) in metadata.tokens.iter().enumerate() { + vocab.insert(token, id); + } + write_synced(&stage.join("vocab.json"), &serde_json::to_vec(&vocab)?)?; + write_synced( + &stage.join("merges.txt"), + metadata.merges.join("\n").as_bytes(), + )?; + write_synced( + &stage.join("token_type.json"), + &serde_json::to_vec(&metadata.token_types)?, + )?; + let config = json!({ + "model": metadata.model, + "pre": metadata.pre, + "vocab_size": metadata.tokens.len(), + "n_merges": metadata.merges.len(), + "special_ids": metadata.special_ids, + "add_bos_token": false, + "pre_pattern": QWEN35_PATTERN, + "pre_pattern_source": ".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)", + }); + write_synced( + &stage.join("tokenizer.json"), + &serde_json::to_vec_pretty(&config)?, + )?; + write_synced( + &stage.join("chat_template.jinja"), + metadata.chat_template.as_bytes(), + )?; + File::open(&stage)?.sync_all()?; + crate::immutable_directory::publish(&stage, &destination)?; + File::open(output)?.sync_all()?; + Ok(()) + })(); + if result.is_err() { + let _ = fs::remove_dir_all(&stage); + } + result?; + Ok(destination) +} + +fn write_synced(path: &Path, bytes: &[u8]) -> Result<()> { + let mut file = File::create(path)?; + file.write_all(bytes)?; + file.sync_all()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gguf_string(bytes: &mut Vec, value: &str) { + bytes.extend_from_slice(&(value.len() as u64).to_le_bytes()); + bytes.extend_from_slice(value.as_bytes()); + } + + fn string_field(bytes: &mut Vec, key: &str, value: &str) { + gguf_string(bytes, key); + bytes.extend_from_slice(&8u32.to_le_bytes()); + gguf_string(bytes, value); + } + + fn string_array(bytes: &mut Vec, key: &str, values: &[&str]) { + gguf_string(bytes, key); + bytes.extend_from_slice(&9u32.to_le_bytes()); + bytes.extend_from_slice(&8u32.to_le_bytes()); + bytes.extend_from_slice(&(values.len() as u64).to_le_bytes()); + for value in values { + gguf_string(bytes, value); + } + } + + #[test] + fn exports_checked_tokenizer_assets() { + let mut gguf = b"GGUF".to_vec(); + gguf.extend_from_slice(&3u32.to_le_bytes()); + gguf.extend_from_slice(&0u64.to_le_bytes()); // no tensors + gguf.extend_from_slice(&7u64.to_le_bytes()); + string_field(&mut gguf, "tokenizer.ggml.model", "gpt2"); + string_field(&mut gguf, "tokenizer.ggml.pre", "qwen35"); + string_array( + &mut gguf, + "tokenizer.ggml.tokens", + &["a", "b", "ab", "<|im_end|>"], + ); + string_array(&mut gguf, "tokenizer.ggml.merges", &["a b"]); + gguf_string(&mut gguf, "tokenizer.ggml.token_type"); + gguf.extend_from_slice(&9u32.to_le_bytes()); + gguf.extend_from_slice(&4u32.to_le_bytes()); + gguf.extend_from_slice(&4u64.to_le_bytes()); + for value in [1u32, 1, 1, 3] { + gguf.extend_from_slice(&value.to_le_bytes()); + } + gguf_string(&mut gguf, "tokenizer.ggml.eos_token_id"); + gguf.extend_from_slice(&4u32.to_le_bytes()); + gguf.extend_from_slice(&3u32.to_le_bytes()); + string_field(&mut gguf, "tokenizer.chat_template", "{{ messages }}"); + gguf.resize(gguf.len().div_ceil(32) * 32, 0); + + let root = std::env::temp_dir().join(format!("strata-tokens-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir(&root).unwrap(); + let source = root.join("tiny.gguf"); + fs::write(&source, &gguf).unwrap(); + let dir = extract(&source, &root).unwrap(); + let vocab: BTreeMap = + serde_json::from_slice(&fs::read(dir.join("vocab.json")).unwrap()).unwrap(); + assert_eq!(vocab["<|im_end|>"], 3); + assert_eq!(fs::read_to_string(dir.join("merges.txt")).unwrap(), "a b"); + let config: serde_json::Value = + serde_json::from_slice(&fs::read(dir.join("tokenizer.json")).unwrap()).unwrap(); + assert_eq!(config["special_ids"]["tokenizer.ggml.eos_token_id"], 3); + assert_eq!(config["pre_pattern"], QWEN35_PATTERN); + assert!(extract(&source, &root).is_err()); + fs::remove_dir_all(root).unwrap(); + } +} diff --git a/control-plane/src/tool_output.rs b/control-plane/src/tool_output.rs new file mode 100644 index 00000000..b1ed49d1 --- /dev/null +++ b/control-plane/src/tool_output.rs @@ -0,0 +1,371 @@ +//! Complete Qwen tool-call parsing for the pinned Strata chat-template format. +//! A call is publishable only after its function and outer call delimiters close. + +use serde_json::{Map, Value}; + +#[derive(Debug, PartialEq)] +pub enum Segment { + Text(String), + Call { name: String, arguments: Value }, +} + +pub struct Incremental<'a> { + tools: &'a [Value], + buffer: String, + in_call: bool, + after_call: bool, +} + +impl<'a> Incremental<'a> { + pub fn new(tools: &'a [Value]) -> Self { + Self { + tools, + buffer: String::new(), + in_call: false, + after_call: false, + } + } + + pub fn feed(&mut self, delta: &str) -> Result, String> { + self.buffer.push_str(delta); + let mut out = Vec::new(); + loop { + if self.after_call && !self.in_call { + self.buffer = self.buffer.trim_start_matches('\n').to_owned(); + if !self.buffer.is_empty() { + self.after_call = false; + } + } + if self.in_call { + if self.buffer.len() > 16 * 1024 * 1024 { + return Err("tool call exceeds the 16 MiB streaming buffer".into()); + } + let mut search = 0; + let mut completed = None; + while let Some(relative) = self.buffer[search..].find("") { + let end = search + relative + "".len(); + let candidate = format!("{}", &self.buffer[..end]); + if let Ok(mut parsed) = parse_complete(&candidate, self.tools) + && parsed.len() == 1 + && matches!(parsed[0], Segment::Call { .. }) + { + completed = Some((end, parsed.remove(0))); + break; + } + search = end; + } + let Some((end, call)) = completed else { + break; + }; + out.push(call); + self.buffer.drain(..end); + self.in_call = false; + self.after_call = true; + } else if let Some(start) = self.buffer.find("") { + let prefix = self.buffer[..start].trim_end_matches('\n'); + if !prefix.is_empty() { + out.push(Segment::Text(prefix.to_owned())); + } + self.buffer.drain(..start + "".len()); + self.in_call = true; + } else { + let mut safe = self.buffer.len() - held_tag_prefix(&self.buffer, ""); + while safe > 0 && self.buffer.as_bytes()[safe - 1] == b'\n' { + safe -= 1; + } + if safe > 0 { + out.push(Segment::Text(self.buffer[..safe].to_owned())); + self.buffer.drain(..safe); + } + break; + } + } + Ok(out) + } + + pub fn finish(mut self) -> Result, String> { + if self.in_call { + return Err("generation ended inside a tool call".into()); + } + if self.after_call || self.buffer.is_empty() { + Ok(Vec::new()) + } else { + Ok(vec![Segment::Text(std::mem::take(&mut self.buffer))]) + } + } +} + +fn held_tag_prefix(text: &str, tag: &str) -> usize { + (1..tag.len()) + .rev() + .find(|&len| text.ends_with(&tag[..len])) + .unwrap_or(0) +} + +pub fn parse_complete(mut text: &str, tools: &[Value]) -> Result, String> { + let mut segments = Vec::new(); + while let Some(start) = text.find("") { + let prefix = text[..start].trim_end_matches('\n'); + if !prefix.is_empty() { + segments.push(Segment::Text(prefix.to_owned())); + } + let (call, consumed) = parse_call(&text[start + "".len()..], tools)?; + segments.push(call); + text = &text[start + "".len() + consumed..]; + text = text.trim_start_matches('\n'); + } + if !text.is_empty() { + segments.push(Segment::Text(text.to_owned())); + } + Ok(segments) +} + +fn parse_call(text: &str, tools: &[Value]) -> Result<(Segment, usize), String> { + let mut offset = text.len() - text.trim_start().len(); + let rest = &text[offset..]; + let rest = rest + .strip_prefix("")?; + let name_end = rest + .find('>') + .ok_or("tool call function name is incomplete")?; + let name = &rest[..name_end]; + if name.is_empty() { + return Err("tool call function name is empty".to_owned()); + } + let tool = tools + .iter() + .find(|tool| tool.get("name").and_then(Value::as_str) == Some(name)) + .ok_or_else(|| format!("undeclared function in tool call: {name}"))?; + offset += "") { + offset += "".len(); + offset += after.len() - after.trim_start().len(); + if !text[offset..].starts_with("") { + return Err("tool call is missing ".to_owned()); + } + offset += "".len(); + return Ok(( + Segment::Call { + name: name.to_owned(), + arguments: Value::Object(arguments), + }, + offset, + )); + } + let after = rest + .strip_prefix("').ok_or("tool parameter name is incomplete")?; + let parameter = &after[..end]; + if parameter.is_empty() { + return Err("tool parameter name is empty".to_owned()); + } + offset += "".len(); + } +} + +fn parameter_value(raw: &str, declared: Option<&Value>) -> Value { + let text = || Value::String(raw.to_owned()); + if declared.is_some_and(|kind| kind == "string") { + return text(); + } + let parsed = serde_json::from_str(raw).unwrap_or_else(|_| text()); + if let Some(types) = declared.and_then(Value::as_array) + && types.iter().any(|kind| kind == "string") + { + // Qwen's string parameters are raw text, not JSON string literals. + // A union may opt into another JSON type, but must not turn a nullable + // string such as 123 into an undeclared number (or strip its quotes). + let declared_non_string = types.iter().any(|kind| match kind.as_str() { + Some("null") => parsed.is_null(), + Some("boolean") => parsed.is_boolean(), + Some("number") => parsed.is_number(), + Some("integer") => parsed.as_f64().is_some_and(|n| n.fract() == 0.0), + Some("object") => parsed.is_object(), + Some("array") => parsed.is_array(), + _ => false, + }); + if !declared_non_string { + return text(); + } + } + parsed +} + +fn find_parameter_end(text: &str) -> Option { + let mut search = 0; + while let Some(relative) = text[search..].find("") { + let at = search + relative; + let after = text[at + "".len()..].trim_start(); + if after.starts_with("") { + return Some(at); + } + search = at + 1; + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_upstream_terminator_fixture_without_truncating_content() { + let content = "Close each value with and the call with .\n\nnot a parameter\n\nend"; + let output = format!( + "\n\n\ndoc.md\n\n\n{content}\n\n\n" + ); + let tools = [ + json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}}), + ]; + assert_eq!( + parse_complete(&output, &tools).unwrap(), + vec![Segment::Call { + name: "write".into(), + arguments: json!({"path":"doc.md","content":content}), + }] + ); + } + + #[test] + fn parses_typed_values_and_preserves_text_around_calls() { + let tools = [ + json!({"name":"lookup","parameters":{"properties":{"n":{"type":"integer"},"term":{"type":"string"}}}}), + ]; + let output = "Let me check.\n\n\n\n\n12\n\n\n12\n\n\n\nanswer"; + assert_eq!( + parse_complete(output, &tools).unwrap(), + vec![ + Segment::Text("Let me check.".into()), + Segment::Call { + name: "lookup".into(), + arguments: json!({"n":12,"term":"12"}) + }, + Segment::Text("answer".into()), + ] + ); + } + + #[test] + fn string_type_unions_preserve_raw_text_and_decode_declared_json_types() { + for (types, raw, expected) in [ + (json!(["string", "null"]), "123", json!("123")), + (json!(["null", "string"]), "false", json!("false")), + (json!(["string", "null"]), "{}", json!("{}")), + (json!(["string", "null"]), "[]", json!("[]")), + (json!(["string", "null"]), "null", Value::Null), + (json!(["string", "null"]), "\"123\"", json!("\"123\"")), + (json!(["string", "null"]), " 123 ", json!(" 123 ")), + (json!(["string", "integer"]), "12", json!(12)), + (json!(["string", "integer"]), "1.5", json!("1.5")), + (json!(["string", "integer"]), "1.0", json!(1.0)), + (json!(["string", "number"]), "1.5", json!(1.5)), + (json!(["string", "boolean"]), "false", json!(false)), + (json!(["string", "object"]), "{}", json!({})), + (json!(["string", "array"]), "[]", json!([])), + (json!(["string"]), "null", json!("null")), + (json!("string"), "null", json!("null")), + (json!("string"), "\"x\"", json!("\"x\"")), + (json!(["integer", "null"]), "12", json!(12)), + ] { + let tools = + [json!({"name":"lookup","parameters":{"properties":{"value":{"type":types}}}})]; + let text = format!( + "{raw}" + ); + let expected = vec![Segment::Call { + name: "lookup".into(), + arguments: json!({"value":expected}), + }]; + assert_eq!( + parse_complete(&text, &tools).unwrap(), + expected, + "{types}: {raw}" + ); + let mut parser = Incremental::new(&tools); + let mut streamed = Vec::new(); + for ch in text.chars() { + streamed.extend(parser.feed(&ch.to_string()).unwrap()); + } + streamed.extend(parser.finish().unwrap()); + assert_eq!(streamed, expected, "stream {types}: {raw}"); + } + } + + #[test] + fn incomplete_or_undeclared_calls_are_never_published() { + let tools = [json!({"name":"write","parameters":{"properties":{}}})]; + assert!(parse_complete("half", &tools).is_err()); + assert!( + parse_complete("", &tools).is_err() + ); + assert!(parse_complete("", &tools).is_err()); + } + + #[test] + fn incremental_parser_holds_partial_markers_and_nested_tag_examples() { + let content = + "Close with and .\n\nexample\n\nend"; + let output = format!( + "First.\n\n\n\n\n{content}\n\n\n\nDone." + ); + let tools = + [json!({"name":"write","parameters":{"properties":{"content":{"type":"string"}}}})]; + let mut parser = Incremental::new(&tools); + let mut segments = Vec::new(); + for ch in output.chars() { + segments.extend(parser.feed(&ch.to_string()).unwrap()); + } + segments.extend(parser.finish().unwrap()); + let text = segments + .iter() + .filter_map(|segment| match segment { + Segment::Text(value) => Some(value.as_str()), + _ => None, + }) + .collect::(); + let calls = segments + .iter() + .filter_map(|segment| match segment { + Segment::Call { arguments, .. } => Some(arguments), + _ => None, + }) + .collect::>(); + assert_eq!(text, "First.Done."); + assert_eq!(calls, vec![&json!({"content":content})]); + assert!( + segments + .iter() + .filter_map(|segment| match segment { + Segment::Text(value) => Some(value), + _ => None, + }) + .all(|text| !text.contains("half") + .unwrap(); + assert!(cut.finish().is_err()); + } +} diff --git a/control-plane/src/wait_ready.rs b/control-plane/src/wait_ready.rs new file mode 100644 index 00000000..656baddf --- /dev/null +++ b/control-plane/src/wait_ready.rs @@ -0,0 +1,444 @@ +//! GET-only deployment readiness: exact identity and one network wait deadline. +use std::{collections::BTreeMap, net::IpAddr, path::Path, time::Duration}; + +use reqwest::{Client, Url, header::HeaderValue}; +use serde_json::{Value, json}; + +const USAGE: &str = "usage: strata-next wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]"; +const MAX_BODY: usize = 64 * 1024; + +struct Options { + url: Url, + model: String, + key_file: Option, + timeout: Duration, +} + +fn parse(args: &[String]) -> Result { + let mut values = BTreeMap::new(); + let mut args = args.iter(); + while let Some(flag) = args.next() { + if !matches!( + flag.as_str(), + "--url" | "--model" | "--key-file" | "--timeout-s" + ) { + return Err(USAGE.into()); + } + let value = args.next().ok_or(USAGE)?; + if values.insert(flag.as_str(), value).is_some() { + return Err(USAGE.into()); + } + } + let mut url = + Url::parse(values.get("--url").ok_or(USAGE)?).map_err(|_| "invalid readiness URL")?; + let loopback = url + .host_str() + .and_then(|host| { + host.trim_start_matches('[') + .trim_end_matches(']') + .parse::() + .ok() + }) + .is_some_and(|ip| ip.is_loopback()); + if url.scheme() != "http" + || !loopback + || !url.username().is_empty() + || url.password().is_some() + || url.path() != "/" + || url.query().is_some() + || url.fragment().is_some() + || url.port_or_known_default().is_none_or(|port| port == 0) + { + return Err("readiness URL must be an HTTP literal loopback origin without credentials, path, query or fragment; use an SSH tunnel for remote nodes".into()); + } + url.set_path("/status"); + let model = values.get("--model").ok_or(USAGE)?.to_string(); + if model.trim().is_empty() || model.len() > 4096 || model.chars().any(char::is_control) { + return Err("model ID must contain 1..4096 bytes without control characters".into()); + } + let seconds = match values.get("--timeout-s") { + Some(value) => value + .parse::() + .map_err(|_| "timeout-s must be 1..3600")?, + None => 300, + }; + if !(1..=3600).contains(&seconds) { + return Err("timeout-s must be 1..3600".into()); + } + Ok(Options { + url, + model, + timeout: Duration::from_secs(seconds), + key_file: values.get("--key-file").map(|s| s.to_string()), + }) +} + +pub(crate) fn validate(args: &[String]) -> Result<(), String> { + parse(args).map(|_| ()) +} + +async fn probe( + client: &Client, + url: &Url, + key: Option<&HeaderValue>, + model: &str, + expected_pid: Option, +) -> Result { + let mut request = client.get(url.clone()); + if let Some(key) = key { + request = request.header(reqwest::header::AUTHORIZATION, key.clone()); + } + // Do not return reqwest errors: their URLs or peer text are not diagnostics. + let mut response = match request.send().await { + Ok(response) => response, + Err(_) => return Ok(false), + }; + let status = response.status(); + if status == 401 || status == 403 { + return Err("readiness authentication rejected; check --key-file".into()); + } + if status.is_redirection() { + return Err("readiness redirects are not allowed".into()); + } + if status.is_server_error() || status == 429 { + return Ok(false); + } + if status != 200 { + return Err(format!( + "unexpected readiness HTTP status {}", + status.as_u16() + )); + } + if response + .content_length() + .is_some_and(|n| n > MAX_BODY as u64) + { + return Err("readiness response exceeds 64 KiB".into()); + } + let mut bytes = Vec::new(); + loop { + let chunk = match response.chunk().await { + Ok(Some(chunk)) => chunk, + Ok(None) => break, + Err(_) => return Ok(false), + }; + if chunk.len() > MAX_BODY - bytes.len() { + return Err("readiness response exceeds 64 KiB".into()); + } + bytes.extend_from_slice(&chunk); + } + let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid readiness JSON")?; + if value.get("service").and_then(Value::as_str) != Some("strata-control") + || value.get("model").and_then(Value::as_str) != Some(model) + { + return Err("readiness service or model does not match the requested deployment".into()); + } + if expected_pid + .is_some_and(|pid| value.get("server_pid").and_then(Value::as_u64) != Some(u64::from(pid))) + { + return Err("readiness endpoint does not match the managed server PID".into()); + } + let ready = value + .get("ready") + .and_then(Value::as_bool) + .ok_or("invalid readiness flag")?; + let worker = value + .get("worker") + .and_then(Value::as_str) + .ok_or("invalid readiness worker state")?; + if !matches!( + worker, + "unconfigured" | "starting" | "ready" | "restarting" | "failed" | "stopping" | "stopped" + ) { + return Err("invalid readiness worker state".into()); + } + if ready && worker != "ready" { + return Err("inconsistent readiness worker state".into()); + } + Ok(ready) +} + +pub(crate) struct Waiter { + options: Options, + key: Option, + client: Client, +} + +impl Waiter { + pub(crate) fn new(args: &[String]) -> Result { + let options = parse(args)?; + let key = options + .key_file + .as_ref() + .map(|file| { + let token = crate::auth::read_token(Path::new(file)) + .map_err(|_| "unable to read a valid private API key file")?; + let mut header = HeaderValue::from_str(&format!("Bearer {token}")) + .map_err(|_| "invalid API key")?; + header.set_sensitive(true); + Ok::<_, String>(header) + }) + .transpose()?; + let client = Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(3)) + .timeout(Duration::from_secs(3)) + .build() + .map_err(|_| "unable to initialize readiness HTTP client")?; + Ok(Self { + options, + key, + client, + }) + } + + async fn lifecycle_request( + &self, + path: &str, + mutation_pid: Option, + ) -> Result { + let mut url = self.options.url.clone(); + url.set_path(path); + let mut request = if let Some(pid) = mutation_pid { + self.client + .post(url) + .header("x-strata-expected-pid", pid.to_string()) + } else { + self.client.get(url) + }; + if let Some(key) = &self.key { + request = request.header(reqwest::header::AUTHORIZATION, key.clone()); + } + let mut response = request + .send() + .await + .map_err(|_| "lifecycle HTTP request failed; mutation outcome may be unknown")?; + if response.status() != 200 { + return Err(format!( + "lifecycle HTTP status {}; no request replayed", + response.status().as_u16() + )); + } + if response + .content_length() + .is_some_and(|n| n > MAX_BODY as u64) + { + return Err("lifecycle response exceeds 64 KiB".into()); + } + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| "lifecycle response interrupted; mutation outcome may be unknown")? + { + if chunk.len() > MAX_BODY - bytes.len() { + return Err("lifecycle response exceeds 64 KiB".into()); + } + bytes.extend_from_slice(&chunk); + } + serde_json::from_slice(&bytes).map_err(|_| "invalid lifecycle JSON".into()) + } + + fn lifecycle_identity(&self, value: &Value, pid: u32) -> Result<(), String> { + if value["service"] != "strata-control" + || value["model"] != self.options.model + || value["server_pid"].as_u64() != Some(u64::from(pid)) + { + return Err("lifecycle endpoint does not match managed service, model and PID".into()); + } + if value["shutting_down"] != false { + return Err("managed lifecycle is shutting down or invalid".into()); + } + if !value["draining"].is_boolean() + || !value["drained"].is_boolean() + || value["requests_in_flight"].as_u64().is_none() + || value["generation_jobs"].as_u64().is_none() + { + return Err("invalid lifecycle state".into()); + } + Ok(()) + } + + pub(crate) async fn admission(self, pid: u32, drain: bool) -> Result { + tokio::time::timeout(self.options.timeout, async { + let before = self.lifecycle_request("/admin/lifecycle", None).await?; + self.lifecycle_identity(&before, pid)?; + // Never replay a mutation after a lost response. The operator can + // explicitly reconcile or resume admission using the same PID check. + let path = if drain { + "/admin/drain" + } else { + "/admin/resume" + }; + let mut state = self.lifecycle_request(path, Some(pid)).await?; + loop { + self.lifecycle_identity(&state, pid)?; + if state["draining"] != drain { + return Err("admission state does not match requested action".into()); + } + if !drain { + return Ok(state); + } + if state["drained"] == true { + if state["requests_in_flight"] != 0 + || state["generation_jobs"] != 0 + || !matches!(state["worker"].as_str(), Some("ready" | "unconfigured")) + { + return Err("inconsistent drained lifecycle state".into()); + } + return Ok(state); + } + tokio::time::sleep(Duration::from_millis(100)).await; + state = self.lifecycle_request("/admin/lifecycle", None).await?; + } + }) + .await + .map_err(|_| "admission deadline expired; inspect lifecycle before retrying or resuming")? + } + + pub(crate) async fn wait(self, expected_pid: Option) -> Result { + let Self { + options, + key, + client, + } = self; + // Includes connect, headers, every body chunk, and all retry sleeps. A peer + // sending bytes more often than a socket timeout cannot prolong this budget. + tokio::time::timeout(options.timeout, async { + let mut attempts = 0u64; + loop { + attempts += 1; + if probe(&client, &options.url, key.as_ref(), &options.model, expected_pid).await? { + let mut result = json!({"ready":true, "service":"strata-control", "model":options.model, "attempts":attempts}); + if let Some(pid) = expected_pid { result["server_pid"] = json!(pid); } + return Ok(result); + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + }).await.map_err(|_| "readiness deadline expired; model did not become ready within timeout-s")? + } +} + +pub async fn run(args: &[String]) -> Result { + Waiter::new(args)?.wait(None).await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(url: &str) -> Vec { + ["--url", url, "--model", "fixture"] + .map(str::to_owned) + .to_vec() + } + + #[tokio::test] + async fn managed_readiness_requires_exact_numeric_pid_but_plain_wait_is_compatible() { + for reported in [ + None, + Some(json!(123)), + Some(json!(124)), + Some(json!("123")), + Some(json!(0)), + ] { + let mut body = json!({"service":"strata-control", "model":"fixture", "ready":true, "worker":"ready"}); + if let Some(value) = reported.clone() { + body["server_pid"] = value; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let router = axum::Router::new().route( + "/status", + axum::routing::get(move || async move { axum::Json(body) }), + ); + let server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + let managed = Waiter::new(&args(&url)).unwrap().wait(Some(123)).await; + assert_eq!(managed.is_ok(), reported == Some(json!(123))); + if let Ok(value) = managed { + assert_eq!(value["server_pid"], 123); + } + let plain = run(&args(&url)).await.unwrap(); + assert_eq!(plain["ready"], true); + assert!(plain.get("server_pid").is_none()); + server.abort(); + let _ = server.await; + } + } + + #[tokio::test] + async fn admission_refuses_wrong_endpoint_and_never_replays_failed_post() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + for reported_pid in [124, 123] { + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let value = json!({"service":"strata-control","model":"fixture","server_pid":reported_pid, + "shutting_down":false,"draining":false,"drained":false,"requests_in_flight":0,"generation_jobs":0,"worker":"ready"}); + let app = axum::Router::new() + .route( + "/admin/lifecycle", + axum::routing::get(move || async move { axum::Json(value) }), + ) + .route( + "/admin/drain", + axum::routing::post(move |headers: axum::http::HeaderMap| async move { + assert_eq!(headers["x-strata-expected-pid"], "123"); + observed.fetch_add(1, Ordering::SeqCst); + axum::http::StatusCode::INTERNAL_SERVER_ERROR + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + assert!( + Waiter::new(&args(&url)) + .unwrap() + .admission(123, true) + .await + .is_err() + ); + assert_eq!( + calls.load(Ordering::SeqCst), + usize::from(reported_pid == 123) + ); + server.abort(); + let _ = server.await; + } + } + + #[test] + fn validates_origin_and_budgets_before_network_or_credentials() { + for url in ["http://127.0.0.1:18082", "http://[::1]:18082/"] { + let options = parse(&args(url)).unwrap(); + assert_eq!(options.url.path(), "/status"); + } + for url in [ + "https://127.0.0.1", + "http://localhost", + "http://192.0.2.1", + "http://key@127.0.0.1", + "http://127.0.0.1/status", + "http://127.0.0.1?key=x", + "http://127.0.0.1#x", + "http://127.0.0.1:0", + ] { + assert!(parse(&args(url)).is_err()); + } + for budget in ["0", "3601", "-1", "nan"] { + let mut args = args("http://127.0.0.1"); + args.extend(["--timeout-s".into(), budget.into()]); + assert!(parse(&args).is_err()); + } + let mut repeated = args("http://127.0.0.1"); + repeated.extend(["--model".into(), "other".into()]); + assert!(parse(&repeated).is_err()); + } +} diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs new file mode 100644 index 00000000..c49b696b --- /dev/null +++ b/control-plane/src/wire.rs @@ -0,0 +1,238 @@ +//! Typed boundary for the resident Strata `--serve` stdin/stdout protocol. + +#[derive(Debug, Clone, PartialEq)] +pub struct Generate { + pub token_ids: Vec, + pub max_new: u32, + pub temperature: Option, + pub top_p: Option, +} + +impl Generate { + pub fn line(&self) -> Result { + if self.token_ids.is_empty() || self.max_new == 0 { + return Err("GEN needs prompt tokens and a positive max_new"); + } + if self + .temperature + .is_some_and(|value| !value.is_finite() || !(0.0..=2.0).contains(&value)) + { + return Err("temperature must be finite and between 0 and 2"); + } + if self + .top_p + .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) + { + return Err("top_p must be finite and between 0 and 1"); + } + let mut line = format!("GEN {}", self.max_new); + if let Some(value) = self.temperature.filter(|value| *value > 0.0) { + line.push_str(&format!(" temperature={value}")); + } + if let Some(value) = self.top_p.filter(|value| *value < 1.0) { + line.push_str(&format!(" top_p={value}")); + } + line.push(' '); + for (index, id) in self.token_ids.iter().enumerate() { + if index > 0 { + line.push(','); + } + line.push_str(&id.to_string()); + } + line.push('\n'); + Ok(line) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + Token(u32), + PromptProgress { read: u64, total: u64 }, + Done(Done), + Error(String), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Done { + pub generated: u64, + pub prompt_tokens: u64, + pub prompt_ms: f64, + pub decode_ms: f64, + pub finish: Finish, + pub drafts_accepted: Option, + pub drafts_offered: Option, + pub reused: Option, + pub expert_hits: Option, + pub expert_lookups: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Finish { + Stop, + Length, + Cancel, +} + +pub fn parse_line(line: &str) -> Result, String> { + let line = line.trim_end_matches(['\r', '\n']); + let Some((tag, rest)) = line.split_once(' ') else { + return Err(format!("invalid engine line: {line}")); + }; + match tag { + "T" => Ok(Some(Event::Token( + rest.parse().map_err(|_| "invalid T token id")?, + ))), + "PP" => { + let fields: Vec<_> = rest.split_whitespace().collect(); + if fields.len() < 2 { + return Err("invalid PP progress line".to_owned()); + } + let read: u64 = fields[0].parse().map_err(|_| "invalid PP read count")?; + let total: u64 = fields[1].parse().map_err(|_| "invalid PP total count")?; + if read > total { + return Err("PP read count exceeds total".to_owned()); + } + Ok(Some(Event::PromptProgress { read, total })) + } + "DONE" => Ok(Some(Event::Done(parse_done(rest)?))), + "ERR" => Ok(Some(Event::Error(rest.to_owned()))), + // Upstream announces prefix reuse both before and after prefill. + // Final usage is reported by DONE; these are nonterminal metadata. + "RESUME" | "REUSED" => { + rest.parse::() + .map_err(|_| format!("invalid {tag} prefix count"))?; + Ok(None) + } + "INFO" => Ok(None), + _ => Err(format!("unknown engine line tag: {tag}")), + } +} + +fn parse_done(rest: &str) -> Result { + let fields: Vec<_> = rest.split_whitespace().collect(); + if fields.len() < 5 { + return Err("DONE needs generated, prompt, timings, and finish".to_owned()); + } + let count = |index: usize| -> Result { + fields[index] + .parse() + .map_err(|_| format!("invalid DONE count at field {index}")) + }; + let timing = |index: usize| -> Result { + let value: f64 = fields[index] + .parse() + .map_err(|_| format!("invalid DONE timing at field {index}"))?; + if !value.is_finite() || value < 0.0 { + return Err(format!("invalid DONE timing at field {index}")); + } + Ok(value) + }; + let optional_count = |index: usize| -> Result, String> { + if fields.len() > index { + count(index).map(Some) + } else { + Ok(None) + } + }; + let finish = match fields[4] { + "stop" => Finish::Stop, + "length" => Finish::Length, + "cancel" => Finish::Cancel, + other => return Err(format!("unknown DONE finish: {other}")), + }; + let done = Done { + generated: count(0)?, + prompt_tokens: count(1)?, + prompt_ms: timing(2)?, + decode_ms: timing(3)?, + finish, + drafts_accepted: optional_count(5)?, + drafts_offered: optional_count(6)?, + reused: optional_count(7)?, + expert_hits: optional_count(8)?, + expert_lookups: optional_count(9)?, + }; + if done + .drafts_accepted + .zip(done.drafts_offered) + .is_some_and(|(a, b)| a > b) + || done + .reused + .is_some_and(|reused| reused > done.prompt_tokens) + { + return Err("inconsistent DONE counters".to_owned()); + } + Ok(done) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gen_line_uses_upstream_sampling_spelling() { + let request = Generate { + token_ids: vec![101, 42, 7], + max_new: 256, + temperature: Some(0.7), + top_p: Some(0.9), + }; + assert_eq!( + request.line().unwrap(), + "GEN 256 temperature=0.7 top_p=0.9 101,42,7\n" + ); + assert!( + Generate { + token_ids: vec![], + ..request + } + .line() + .is_err() + ); + } + + #[test] + fn parses_current_and_older_done_lines() { + let current = parse_line("DONE 12 300 45.1 88.2 stop 7 10 240 90 100 2 0 0.0\n") + .unwrap() + .unwrap(); + let Event::Done(done) = current else { + panic!("expected DONE") + }; + assert_eq!(done.finish, Finish::Stop); + assert_eq!(done.drafts_accepted, Some(7)); + assert_eq!(done.reused, Some(240)); + assert_eq!(done.expert_hits, Some(90)); + assert_eq!(done.expert_lookups, Some(100)); + let Event::Done(older) = parse_line("DONE 2 4 1.0 3.0 length\n").unwrap().unwrap() else { + panic!("expected DONE") + }; + assert_eq!(older.reused, None); + assert_eq!(older.finish, Finish::Length); + } + + #[test] + fn parses_tokens_progress_and_errors_without_losing_terminal_state() { + assert_eq!(parse_line("T 123\n").unwrap(), Some(Event::Token(123))); + assert_eq!( + parse_line("PP 64 128 10 5.0\n").unwrap(), + Some(Event::PromptProgress { + read: 64, + total: 128 + }) + ); + assert_eq!( + parse_line("ERR bad request\n").unwrap(), + Some(Event::Error("bad request".into())) + ); + assert_eq!(parse_line("INFO engine=0.1.8\n").unwrap(), None); + assert_eq!(parse_line("RESUME 0\n").unwrap(), None); + assert_eq!(parse_line("REUSED 262144\n").unwrap(), None); + assert!(parse_line("RESUME -1").is_err()); + assert!(parse_line("REUSED 1 2").is_err()); + assert!(parse_line("REUSED 18446744073709551616").is_err()); + assert!(parse_line("UNKNOWN 0").is_err()); + assert!(parse_line("DONE 1 2 NaN 3 stop").is_err()); + assert!(parse_line("PP 129 128").is_err()); + } +} diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs new file mode 100644 index 00000000..216a7a00 --- /dev/null +++ b/control-plane/src/worker.rs @@ -0,0 +1,1272 @@ +use std::{ffi::OsString, process::Stdio, sync::Arc, time::Duration}; + +use serde::Serialize; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + process::{Child, ChildStdin, Command}, + sync::{RwLock, mpsc, oneshot, watch}, + time::timeout, +}; + +use crate::wire::{self, Event, Generate}; + +const STOP_DRAIN_TIMEOUT: Duration = Duration::from_secs(20); + +pub struct GenerationCommand { + pub queue: Option, + pub activity: Option, + pub request: Generate, + pub result: GenerationResult, +} + +pub enum GenerationResult { + Buffered(oneshot::Sender, String>>), + Streaming(mpsc::Sender>), + Finished, +} + +impl GenerationResult { + fn take(&mut self) -> Self { + std::mem::replace(self, Self::Finished) + } + + fn is_closed(&self) -> bool { + match self { + Self::Buffered(sender) => sender.is_closed(), + Self::Streaming(sender) => sender.is_closed(), + Self::Finished => true, + } + } + + async fn closed(&mut self) { + match self { + Self::Buffered(sender) => sender.closed().await, + Self::Streaming(sender) => sender.closed().await, + Self::Finished => {} + } + } + + async fn send_event(&self, event: Event) { + if let Self::Streaming(sender) = self { + let _ = sender.send(Ok(event)).await; + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkerState { + Unconfigured, + Starting, + Restarting, + Ready, + Stopping, + Failed, +} + +#[derive(Clone, Copy)] +pub struct WorkerStatus { + pub state: WorkerState, + pub max_context: Option, + pub metrics: crate::metrics::GenerationMetrics, +} + +impl Default for WorkerStatus { + fn default() -> Self { + Self { + state: WorkerState::Unconfigured, + max_context: None, + metrics: Default::default(), + } + } +} + +pub struct WorkerConfig { + pub cuda_memory: Option, + pub executable: OsString, + pub args: Vec, + pub startup_timeout: Duration, + pub generation_timeout: Option, + pub max_restarts: u32, +} + +pub async fn run( + config: WorkerConfig, + status: Arc>, + shutdown: watch::Receiver, +) { + let (sender, receiver) = mpsc::channel(1); + run_with_requests(config, status, shutdown, receiver).await; + drop(sender); +} + +pub async fn run_with_requests( + config: WorkerConfig, + status: Arc>, + mut shutdown: watch::Receiver, + mut requests: mpsc::Receiver, +) { + if config.max_restarts > 3 { + eprintln!("worker max_restarts must be between 0 and 3"); + update(&status, WorkerState::Failed, None).await; + return; + } + for attempt in 0..=config.max_restarts { + match run_session(&config, &status, &mut shutdown, &mut requests).await { + SessionExit::Stopped | SessionExit::StartupFailed => return, + SessionExit::RuntimeFailed if attempt == config.max_restarts => return, + SessionExit::RuntimeFailed => {} + } + update(&status, WorkerState::Restarting, None).await; + let delay = Duration::from_secs(2 << attempt); + eprintln!( + "Strata engine restart {}/{} in {} seconds", + attempt + 1, + config.max_restarts, + delay.as_secs() + ); + while let Ok(command) = requests.try_recv() { + send_failure( + command.result, + "worker failed; request was not replayed".to_owned(), + ) + .await; + } + let backoff = tokio::time::sleep(delay); + tokio::pin!(backoff); + let mut requests_closed = requests.is_closed() && requests.is_empty(); + loop { + tokio::select! { + biased; + _ = shutdown.changed() => { + update(&status, WorkerState::Stopping, None).await; + return; + } + _ = &mut backoff => break, + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is restarting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + } + } + } + } +} + +enum SessionExit { + Stopped, + StartupFailed, + RuntimeFailed, +} + +async fn run_session( + config: &WorkerConfig, + status: &RwLock, + shutdown: &mut watch::Receiver, + requests: &mut mpsc::Receiver, +) -> SessionExit { + if *shutdown.borrow() { + update(status, WorkerState::Stopping, None).await; + return SessionExit::Stopped; + } + update(status, WorkerState::Starting, None).await; + let mut command = Command::new(&config.executable); + if let Some(selection) = &config.cuda_memory { + if let Err(error) = selection.recheck().await { + eprintln!("GPU admission failed before worker spawn: {error}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + command.env("CUDA_VISIBLE_DEVICES", &selection.uuid); + } + if *shutdown.borrow() { + update(status, WorkerState::Stopping, None).await; + return SessionExit::Stopped; + } + let mut child = match command + .arg("--serve") + .args(&config.args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .kill_on_drop(true) + .spawn() + { + Ok(child) => child, + Err(error) => { + eprintln!("failed to start Strata engine: {error}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + }; + + // Keep stdin outside Child: Child::wait closes any stdin it still owns. + let mut stdin = child.stdin.take(); + let stdout = child.stdout.take().expect("piped engine stdout"); + let mut lines = BufReader::new(stdout).lines(); + let startup_deadline = tokio::time::sleep(config.startup_timeout); + tokio::pin!(startup_deadline); + let mut requests_closed = false; + let max_context = loop { + let line = tokio::select! { + biased; + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop(&mut child, &mut stdin).await; + return SessionExit::Stopped; + } + _ = &mut startup_deadline => { + eprintln!("Strata engine did not become ready before the startup timeout"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + command = requests.recv(), if !requests_closed => { + match command { + Some(command) => send_failure(command.result, + "worker is starting; request was not replayed".to_owned()).await, + None => requests_closed = true, + } + continue; + } + line = lines.next_line() => line, + }; + match line { + Ok(Some(line)) if line.starts_with("READY") => { + if let Some(max_context) = parse_ready(&line) { + update(status, WorkerState::Ready, Some(max_context)).await; + break max_context; + } + eprintln!("Strata engine sent an invalid READY line"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + Ok(Some(_)) => {} + Ok(None) => { + eprintln!("Strata engine exited before READY"); + terminate(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + Err(error) => { + eprintln!("failed to read Strata engine output: {error}"); + stop(&mut child, &mut stdin).await; + update(status, WorkerState::Failed, None).await; + return SessionExit::StartupFailed; + } + } + }; + + loop { + tokio::select! { + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop(&mut child, &mut stdin).await; + return SessionExit::Stopped; + }, + result = child.wait() => { + eprintln!("Strata engine exited: {result:?}"); + update(status, WorkerState::Failed, None).await; + return SessionExit::RuntimeFailed; + }, + command = requests.recv(), if !requests_closed => { + match command { + Some(mut command) => { + if command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim()) { + continue; + } + // Retain the command activity until protocol cleanup, + // including STOP/QUIT and failed-process termination. + let _activity = command.activity.take(); + tokio::select! { + (timed_out, result) = async { + let generation = generate(&mut stdin, &mut lines, &mut command, max_context, status); + match config.generation_timeout { + Some(duration) => match timeout(duration, generation).await { + Ok(result) => (false, result), + Err(_) => (true, Err("generation exceeded configured execution deadline".to_owned())), + }, + None => (false, generation.await), + } + } => { + if let Err(error) = result { + eprintln!("Strata engine protocol failed: {error}"); + update(status, WorkerState::Failed, None).await; + terminate(&mut child, &mut stdin).await; + // A full streaming channel must not delay process cleanup + // or finite restart indefinitely. Closing it also signals + // failure to the response adapter once buffered tokens drain. + if timed_out { + let _ = timeout(Duration::from_secs(1), send_failure(command.result, error)).await; + } + return SessionExit::RuntimeFailed; + } + } + _ = shutdown.changed() => { + update(status, WorkerState::Stopping, None).await; + stop_active(&mut child, &mut stdin).await; + return SessionExit::Stopped; + } + } + } + None => requests_closed = true, + } + } + } + } +} + +async fn generate( + stdin: &mut Option, + lines: &mut tokio::io::Lines>, + command: &mut GenerationCommand, + max_context: usize, + status: &RwLock, +) -> Result<(), String> { + if command.result.is_closed() { + return Ok(()); + } + let fits_context = usize::try_from(command.request.max_new) + .ok() + .and_then(|new| command.request.token_ids.len().checked_add(new)) + .and_then(|total| total.checked_add(8)) + .is_some_and(|total| total <= max_context); + if !fits_context { + send_failure( + command.result.take(), + "prompt, output budget, and 8-token margin exceed context".to_owned(), + ) + .await; + return Ok(()); + } + let request = match command.request.line() { + Ok(line) => line, + Err(error) => { + send_failure(command.result.take(), error.to_owned()).await; + return Ok(()); + } + }; + status.write().await.metrics.start(); + let pipe = stdin.as_mut().ok_or("engine stdin is closed")?; + pipe.write_all(request.as_bytes()) + .await + .map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + let mut events = Vec::new(); + let mut stopped = false; + let stop_deadline = tokio::time::sleep(STOP_DRAIN_TIMEOUT); + tokio::pin!(stop_deadline); + loop { + let line = tokio::select! { + biased; + _ = &mut stop_deadline, if stopped => { + return Err("engine did not terminate generation within 20 seconds of STOP".to_owned()); + } + _ = command.result.closed(), if !stopped => { + pipe.write_all(b"STOP\n").await.map_err(|error| error.to_string())?; + pipe.flush().await.map_err(|error| error.to_string())?; + stopped = true; + stop_deadline.as_mut().reset(tokio::time::Instant::now() + STOP_DRAIN_TIMEOUT); + continue; + } + line = lines.next_line() => line.map_err(|error| error.to_string())?, + } + .ok_or("engine exited before a terminal line")?; + match wire::parse_line(&line)? { + Some(Event::Error(message)) => { + status.write().await.metrics.fail(); + send_failure(command.result.take(), message).await; + return Ok(()); + } + Some(event @ Event::Done(_)) => { + let Event::Done(done) = &event else { + unreachable!() + }; + let done = done.clone(); + let disconnected = stopped || command.result.is_closed(); + match command.result.take() { + GenerationResult::Buffered(sender) => { + events.push(event); + let _ = sender.send(Ok(events)); + } + GenerationResult::Streaming(sender) => { + let _ = sender.send(Ok(event)).await; + } + GenerationResult::Finished => {} + } + status.write().await.metrics.finish(&done, disconnected); + return Ok(()); + } + Some(_) if stopped => {} + Some(event) => match &command.result { + GenerationResult::Buffered(_) => events.push(event), + GenerationResult::Streaming(_) => command.result.send_event(event).await, + GenerationResult::Finished => {} + }, + None => {} + } + } +} + +async fn send_failure(result: GenerationResult, message: String) { + match result { + GenerationResult::Buffered(sender) => { + let _ = sender.send(Err(message)); + } + GenerationResult::Streaming(sender) => { + let _ = sender.send(Err(message)).await; + } + GenerationResult::Finished => {} + } +} + +fn parse_ready(line: &str) -> Option { + let mut fields = line.split_whitespace(); + if fields.next() != Some("READY") { + return None; + } + let context = fields.next()?.parse::().ok()?; + (context > 0).then_some(context) +} + +async fn update(status: &RwLock, state: WorkerState, max_context: Option) { + let mut status = status.write().await; + if state != WorkerState::Ready { + status.metrics.fail(); + } + status.state = state; + status.max_context = max_context; +} + +async fn stop(child: &mut Child, stdin: &mut Option) { + if let Some(mut pipe) = stdin.take() { + let _ = pipe.write_all(b"QUIT\n").await; + let _ = pipe.flush().await; + } + if timeout(Duration::from_secs(20), child.wait()) + .await + .is_err() + { + let _ = child.start_kill(); + let _ = child.wait().await; + } +} + +async fn stop_active(child: &mut Child, stdin: &mut Option) { + if let Some(pipe) = stdin.as_mut() { + let _ = pipe.write_all(b"STOP\n").await; + let _ = pipe.flush().await; + } + stop(child, stdin).await; +} + +// Protocol alignment is lost: never reuse this process or add another graceful +// wait after an expired STOP deadline. Dropping the request receiver releases +// queued clients when the supervisor returns. +async fn terminate(child: &mut Child, stdin: &mut Option) { + stdin.take(); + let _ = child.start_kill(); + let _ = child.wait().await; +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::path::Path; + + fn fixture_config(mode: &str, timeout_s: u64) -> WorkerConfig { + let script = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/mock_engine.sh") + .into_os_string(); + WorkerConfig { + cuda_memory: None, + executable: script, + args: vec![mode.to_owned()], + startup_timeout: Duration::from_secs(timeout_s), + generation_timeout: None, + max_restarts: 0, + } + } + + async fn wait_for(status: &RwLock, wanted: WorkerState) { + timeout(Duration::from_secs(5), async { + loop { + if status.read().await.state == wanted { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("worker state transition"); + } + + #[tokio::test] + async fn execution_deadline_covers_blocked_engine_stdin() { + let mut config = fixture_config("blocked-input", 5); + config.generation_timeout = Some(Duration::from_millis(100)); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop, stop_rx) = watch::channel(false); + let (requests, requests_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + requests_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (result, received) = oneshot::channel(); + requests + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10000; 200000], + max_new: 1, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result), + }) + .await + .unwrap(); + let error = timeout(Duration::from_secs(5), received) + .await + .unwrap() + .unwrap() + .unwrap_err(); + assert_eq!(error, "generation exceeded configured execution deadline"); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.metrics.failed_or_interrupted, 1); + } + + #[tokio::test] + async fn execution_deadline_covers_full_stream_channel_and_releases_activity() { + let mut config = fixture_config("flood", 5); + config.generation_timeout = Some(Duration::from_millis(100)); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop, stop_rx) = watch::channel(false); + let (requests, requests_rx) = mpsc::channel(2); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + requests_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let lifecycle = crate::lifecycle::Lifecycle::default(); + let (events, mut received) = mpsc::channel(1); + requests + .send(GenerationCommand { + queue: None, + activity: Some(lifecycle.generation()), + request: Generate { + token_ids: vec![10], + max_new: 100, + temperature: None, + top_p: None, + }, + result: GenerationResult::Streaming(events), + }) + .await + .unwrap(); + // Do not read until the worker exits: channel backpressure must not mask timeout. + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.metrics.failed_or_interrupted, 1); + assert_eq!(status.read().await.metrics.completed, 0); + assert_eq!(lifecycle.snapshot().generation_jobs, 0); + assert!(matches!(received.recv().await, Some(Ok(Event::Token(31))))); + assert!(received.recv().await.is_none()); + } + + #[tokio::test] + async fn ready_requires_handshake_and_shutdown_sends_quit() { + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let task = tokio::spawn(run(fixture_config("ready", 5), status.clone(), stop_rx)); + wait_for(&status, WorkerState::Ready).await; + assert_eq!(status.read().await.max_context, Some(262144)); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Stopping); + } + + #[tokio::test] + async fn worker_exit_revokes_readiness() { + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + run(fixture_config("crash", 5), status.clone(), stop_rx).await; + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.max_context, None); + } + + #[tokio::test] + async fn startup_timeout_never_sets_ready() { + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + run(fixture_config("slow", 1), status.clone(), stop_rx).await; + assert_eq!(status.read().await.state, WorkerState::Failed); + } + + #[test] + fn ready_line_requires_positive_context() { + assert_eq!(parse_ready("READY 262144 stop"), Some(262144)); + assert_eq!(parse_ready("READY 0 stop"), None); + assert_eq!(parse_ready("READY nope stop"), None); + } + + #[tokio::test] + async fn supervisor_exchanges_one_generation_and_stays_ready() { + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + fixture_config("exchange", 5), + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: Some(0.5), + top_p: Some(0.9), + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + let events = timeout(Duration::from_secs(5), result_rx) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(events.len(), 4); + assert_eq!(events[1], Event::Token(31)); + assert_eq!(events[2], Event::Token(32)); + assert!(matches!(events[3], Event::Done(_))); + let metrics = status.read().await.metrics; + assert_eq!(metrics.started, 1); + assert_eq!(metrics.completed, 1); + assert_eq!(metrics.done_generated_tokens, 2); + assert_eq!(metrics.done_prompt_tokens, 2); + assert_eq!( + metrics.last_done.unwrap().decode_tokens_per_second, + Some(1000.0) + ); + assert!(metrics.active_since.is_none()); + assert_eq!(status.read().await.state, WorkerState::Ready); + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 300_000, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + assert!( + result_rx + .await + .unwrap() + .unwrap_err() + .contains("exceed context") + ); + assert_eq!(status.read().await.metrics.started, 1); + let (invalid, result) = command(vec![99], 1); + commands_tx.send(invalid).await.unwrap(); + assert_eq!(result.await.unwrap().unwrap_err(), "unexpected request"); + let metrics = status.read().await.metrics; + assert_eq!( + ( + metrics.started, + metrics.completed, + metrics.failed_or_interrupted + ), + (2, 1, 1) + ); + assert!(metrics.active_since.is_none()); + assert_eq!(status.read().await.state, WorkerState::Ready); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn dropped_generation_receiver_sends_stop_and_preserves_worker() { + let marker = + std::env::temp_dir().join(format!("strata-cancel-drop-{}", std::process::id())); + let _ = std::fs::remove_file(&marker); + let mut config = fixture_config("cancel", 5); + config.args.push(marker.display().to_string()); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + timeout(Duration::from_secs(5), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert!(status.read().await.metrics.active_since.is_some()); + drop(result_rx); + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![99], + max_new: 1, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + let events = timeout(Duration::from_secs(5), result_rx) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(events[0], Event::Token(42)); + let metrics = status.read().await.metrics; + assert_eq!( + (metrics.started, metrics.completed, metrics.cancelled), + (2, 1, 1) + ); + assert_eq!(metrics.failed_or_interrupted, 0); + assert!(metrics.active_since.is_none()); + assert_eq!(status.read().await.state, WorkerState::Ready); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + std::fs::remove_file(marker).unwrap(); + } + + #[tokio::test] + async fn dropped_stream_receiver_stops_generation_and_preserves_worker() { + let marker = + std::env::temp_dir().join(format!("strata-stream-cancel-{}", std::process::id())); + let mut config = fixture_config("cancel", 5); + config.args.push(marker.display().to_string()); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (events_tx, mut events_rx) = mpsc::channel(2); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: None, + top_p: None, + }, + result: GenerationResult::Streaming(events_tx), + }) + .await + .unwrap(); + assert_eq!( + timeout(Duration::from_secs(5), events_rx.recv()) + .await + .unwrap() + .unwrap() + .unwrap(), + Event::Token(31) + ); + drop(events_rx); + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![99], + max_new: 1, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + let next = timeout(Duration::from_secs(5), result_rx) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(next[0], Event::Token(42)); + let metrics = status.read().await.metrics; + assert_eq!( + (metrics.started, metrics.completed, metrics.cancelled), + (2, 1, 1) + ); + assert_eq!(metrics.failed_or_interrupted, 0); + assert!(metrics.active_since.is_none()); + assert_eq!(status.read().await.state, WorkerState::Ready); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + std::fs::remove_file(marker).unwrap(); + } + + #[tokio::test] + async fn shutdown_interrupts_active_generation() { + let marker = + std::env::temp_dir().join(format!("strata-cancel-shutdown-{}", std::process::id())); + let _ = std::fs::remove_file(&marker); + let mut config = fixture_config("cancel", 5); + config.args.push(marker.display().to_string()); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + timeout(Duration::from_secs(5), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Stopping); + assert!(result_rx.await.is_err()); + let metrics = status.read().await.metrics; + assert_eq!(metrics.failed_or_interrupted, 1); + assert!(metrics.active_since.is_none()); + std::fs::remove_file(marker).unwrap(); + } + + #[tokio::test] + async fn uncooperative_stop_revokes_readiness_and_releases_queued_request() { + let marker = + std::env::temp_dir().join(format!("strata-stalled-cancel-{}", std::process::id())); + let _ = std::fs::remove_file(&marker); + let mut config = fixture_config("cancel-stall", 5); + config.args.push(marker.display().to_string()); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (events_tx, mut events_rx) = mpsc::channel(1); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: None, + top_p: None, + }, + result: GenerationResult::Streaming(events_tx), + }) + .await + .unwrap(); + assert_eq!( + timeout(Duration::from_secs(5), events_rx.recv()) + .await + .unwrap() + .unwrap() + .unwrap(), + Event::Token(31) + ); + let cancel_at = tokio::time::Instant::now(); + drop(events_rx); + timeout(Duration::from_secs(5), async { + while !marker.exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let (result_tx, result_rx) = oneshot::channel(); + commands_tx + .send(GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids: vec![99], + max_new: 1, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(result_tx), + }) + .await + .unwrap(); + timeout(STOP_DRAIN_TIMEOUT + Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + assert!(cancel_at.elapsed() >= STOP_DRAIN_TIMEOUT); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.max_context, None); + assert!( + result_rx.await.is_err(), + "must not reuse the unaligned worker" + ); + assert!(commands_tx.is_closed()); + drop(stop_tx); + std::fs::remove_file(marker).unwrap(); + } + + fn restart_fixture( + mode: &str, + label: &str, + max_restarts: u32, + ) -> (WorkerConfig, std::path::PathBuf) { + let root = + std::env::temp_dir().join(format!("strata-restart-{label}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir(&root).unwrap(); + let mut config = fixture_config(mode, 5); + config.max_restarts = max_restarts; + config.args.push(root.display().to_string()); + (config, root) + } + + fn command( + token_ids: Vec, + max_new: u32, + ) -> ( + GenerationCommand, + oneshot::Receiver, String>>, + ) { + let (sender, receiver) = oneshot::channel(); + ( + GenerationCommand { + queue: None, + activity: None, + request: Generate { + token_ids, + max_new, + temperature: None, + top_p: None, + }, + result: GenerationResult::Buffered(sender), + }, + receiver, + ) + } + + #[tokio::test] + async fn crash_restarts_worker_without_replaying_active_or_queued_requests() { + let (config, root) = restart_fixture("restart-once", "once", 1); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (first, failed) = command(vec![10, 20], 3); + commands_tx.send(first).await.unwrap(); + timeout(Duration::from_secs(5), async { + while !root.join("active").exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let (queued, rejected) = command(vec![99], 1); + commands_tx.send(queued).await.unwrap(); + std::fs::write(root.join("release"), "").unwrap(); + assert!( + timeout(Duration::from_secs(5), failed) + .await + .unwrap() + .is_err() + ); + assert!( + timeout(Duration::from_secs(5), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("not replayed") + ); + wait_for(&status, WorkerState::Restarting).await; + let (during_backoff, rejected) = command(vec![99], 1); + commands_tx.send(during_backoff).await.unwrap(); + assert!( + timeout(Duration::from_secs(1), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("restarting") + ); + wait_for(&status, WorkerState::Starting).await; + assert_eq!(status.read().await.max_context, None); + let (during_startup, rejected) = command(vec![99], 1); + commands_tx.send(during_startup).await.unwrap(); + assert!( + timeout(Duration::from_secs(1), rejected) + .await + .unwrap() + .unwrap() + .unwrap_err() + .contains("starting") + ); + wait_for(&status, WorkerState::Ready).await; + let (fresh, result) = command(vec![99], 1); + commands_tx.send(fresh).await.unwrap(); + let events = timeout(Duration::from_secs(5), result) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(events[0], Event::Token(42)); + let metrics = status.read().await.metrics; + assert_eq!( + ( + metrics.started, + metrics.completed, + metrics.failed_or_interrupted + ), + (2, 1, 1) + ); + assert_eq!(metrics.cancelled, 0); + assert!(metrics.active_since.is_none()); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 2 + ); + assert_eq!( + std::fs::read_to_string(root.join("requests")).unwrap(), + "GEN 3 10,20\nGEN 1 99\n" + ); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn cancelled_command_keeps_drain_guard_until_stop_terminal() { + let (config, root) = restart_fixture("cancel-drain", "drain", 0); + let lifecycle = crate::lifecycle::Lifecycle::default(); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let (commands_tx, commands_rx) = mpsc::channel(1); + let task = tokio::spawn(run_with_requests( + config, + status.clone(), + stop_rx, + commands_rx, + )); + wait_for(&status, WorkerState::Ready).await; + let (events_tx, mut events_rx) = mpsc::channel(2); + commands_tx + .send(GenerationCommand { + queue: None, + activity: Some(lifecycle.generation()), + request: Generate { + token_ids: vec![10, 20], + max_new: 3, + temperature: None, + top_p: None, + }, + result: GenerationResult::Streaming(events_tx), + }) + .await + .unwrap(); + assert_eq!(events_rx.recv().await.unwrap().unwrap(), Event::Token(31)); + lifecycle.set_draining(true); + drop(events_rx); + timeout(Duration::from_secs(5), async { + while !root.join("stopped").exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(lifecycle.snapshot().generation_jobs, 1); + assert!(status.read().await.metrics.active_since.is_some()); + std::fs::write(root.join("release"), "").unwrap(); + timeout(Duration::from_secs(5), async { + while lifecycle.snapshot().generation_jobs != 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(status.read().await.metrics.cancelled, 1); + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn repeated_crashes_exhaust_lifetime_restart_budget() { + let (config, root) = restart_fixture("restart-loop", "loop", 2); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + timeout( + Duration::from_secs(10), + run(config, status.clone(), stop_rx), + ) + .await + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!(status.read().await.max_context, None); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 3 + ); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn shutdown_during_backoff_prevents_respawn() { + let (config, root) = restart_fixture("restart-loop", "shutdown", 3); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (stop_tx, stop_rx) = watch::channel(false); + let task = tokio::spawn(run(config, status.clone(), stop_rx)); + wait_for(&status, WorkerState::Restarting).await; + stop_tx.send(true).unwrap(); + timeout(Duration::from_secs(1), task) + .await + .unwrap() + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Stopping); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 1 + ); + std::fs::remove_dir_all(root).unwrap(); + } + + #[tokio::test] + async fn startup_failure_is_not_restarted() { + let (config, root) = restart_fixture("restart-bad", "startup", 3); + let status = Arc::new(RwLock::new(WorkerStatus::default())); + let (_stop_tx, stop_rx) = watch::channel(false); + timeout(Duration::from_secs(5), run(config, status.clone(), stop_rx)) + .await + .unwrap(); + assert_eq!(status.read().await.state, WorkerState::Failed); + assert_eq!( + std::fs::read_to_string(root.join("boots")) + .unwrap() + .lines() + .count(), + 1 + ); + std::fs::remove_dir_all(root).unwrap(); + } +} diff --git a/control-plane/tests/fixtures/mock_engine.sh b/control-plane/tests/fixtures/mock_engine.sh new file mode 100755 index 00000000..c2234e57 --- /dev/null +++ b/control-plane/tests/fixtures/mock_engine.sh @@ -0,0 +1,126 @@ +#!/bin/sh +if [ "$1" != "--serve" ]; then + exit 2 +fi +case "$2" in + ready) + printf 'INFO engine=mock\nREADY 262144 stop\n' + while IFS= read -r line; do + if [ "$line" = QUIT ]; then + exit 0 + fi + done + ;; + crash) + printf 'READY 262144 stop\n' + exit 7 + ;; + slow) + sleep 2 + ;; + exchange) + printf 'READY 262144 stop\n' + while IFS= read -r line; do + case "$line" in + 'GEN 3 temperature=0.5 top_p=0.9 10,20') + printf 'RESUME 0\nPP 2 2 1 2.0\nREUSED 0\nT 31\nT 32\nDONE 2 2 1.0 2.0 stop 0 0 0 0 0 0 0 0.0\n' + ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + blocked-input) + printf 'READY 262144 stop\n' + exec sleep 30 + ;; + flood) + printf 'READY 262144 stop\n' + IFS= read -r line || exit 3 + while :; do printf 'T 31\n'; done + ;; + cancel) + printf 'READY 262144 stop\n' + while IFS= read -r line; do + case "$line" in + 'GEN 3 10,20') + : > "$3" + printf 'T 31\n' + IFS= read -r stop || exit 3 + [ "$stop" = STOP ] || exit 4 + printf 'DONE 1 2 1.0 2.0 cancel\n' + ;; + 'GEN 1 99') + printf 'T 42\nDONE 1 1 1.0 2.0 stop\n' + ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + cancel-drain) + printf 'READY 262144 stop\n' + IFS= read -r line || exit 3 + printf 'T 31\n' + IFS= read -r line || exit 3 + [ "$line" = STOP ] || exit 4 + : > "$3/stopped" + while [ ! -e "$3/release" ]; do sleep 0.01; done + printf 'DONE 1 2 1.0 2.0 cancel\n' + while IFS= read -r line; do + [ "$line" = QUIT ] && exit 0 + done + ;; + cancel-stall) + printf 'READY 262144 stop\n' + IFS= read -r line || exit 3 + [ "$line" = 'GEN 3 10,20' ] || exit 4 + printf 'T 31\n' + IFS= read -r stop || exit 3 + [ "$stop" = STOP ] || exit 4 + : > "$3" + printf 'T 32\nPP 2 2 1 2.0\n' + # Consume STOP but never report DONE. A following GEN would demonstrate + # unsafe reuse of this still-active generation. + while IFS= read -r line; do + case "$line" in + 'GEN 1 99') printf 'T 42\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + esac + done + ;; + restart-once) + printf 'boot\n' >> "$3/boots" + if [ ! -e "$3/crashed" ]; then + printf 'READY 262144 stop\n' + IFS= read -r line || exit 3 + printf '%s\n' "$line" >> "$3/requests" + printf 'T 31\n' + : > "$3/active" + while [ ! -e "$3/release" ]; do sleep 0.01; done + : > "$3/crashed" + exit 7 + fi + sleep 1 + printf 'READY 262144 stop\n' + while IFS= read -r line; do + case "$line" in + 'GEN 1 99') + printf '%s\n' "$line" >> "$3/requests" + printf 'T 42\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + *) printf 'ERR unexpected request\n' ;; + esac + done + ;; + restart-loop) + printf 'boot\n' >> "$3/boots" + printf 'READY 262144 stop\n' + exit 7 + ;; + restart-bad) + printf 'boot\n' >> "$3/boots" + printf 'READY invalid\n' + ;; + *) exit 2 ;; +esac diff --git a/control-plane/third_party/ggml/LICENSE b/control-plane/third_party/ggml/LICENSE new file mode 100644 index 00000000..e7dca554 --- /dev/null +++ b/control-plane/third_party/ggml/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/control-plane/third_party/ggml/SHA256SUMS b/control-plane/third_party/ggml/SHA256SUMS new file mode 100644 index 00000000..cdd4a2c5 --- /dev/null +++ b/control-plane/third_party/ggml/SHA256SUMS @@ -0,0 +1,10 @@ +07143d7068936ae46b3c528b2f3d4bbb666e74d88992165716174d243573965d ggml-quants.c +94e4cd069b9313b2ceb35dacec901981e0bb478d8bb31035b7126be091998c23 ggml-alloc.h +46d84cb998105f871240864fd0f55446939a2fe86c5c281afa63a010fb1f65a2 ggml-backend.h +0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c ggml-common.h +316279e004cdeb8e6ef78599acb602bf79a8abdf897fed9fd1914808c1518c6e ggml-cpu.h +43564db0238aebb7ed68501e346c194866b5dac218d1d37b26baff9f458c00d3 ggml-impl.h +28ae5fca1f3be636b36cd6c4fa2ca74fd42d229bfbd5352eaf66f3727bb8a6da ggml-quants.h +12ee71f99db7db9b353bc02b1fbb57c344ee17c01ac5fb7952b41a637a747ea9 ggml.h +e56714aab702e5ce62ee587a409643c08f7e93e8fbb77f48ef7cc85075f96fa4 gguf.h +785a19aac84bd35671d34b1986b920baadccdf61cd8b81e787028f6ac24cae60 ggml-cpu/ggml-cpu-impl.h diff --git a/control-plane/third_party/ggml/UPSTREAM.md b/control-plane/third_party/ggml/UPSTREAM.md new file mode 100644 index 00000000..d7bc7ed9 --- /dev/null +++ b/control-plane/third_party/ggml/UPSTREAM.md @@ -0,0 +1,13 @@ +# Pinned ggml CPU quantization source + +These unmodified source and header files come from `ggml-org/llama.cpp` commit +`3cf03257f219afbe7334045ff7c6a06ac68c627d`, the same commit pinned by +the imported Strata engine in `engine/strata/third_party/ggml/VERSION.txt`. +Their original repository paths are under `ggml/src/` or `ggml/include/`; +`ggml-cpu-impl.h` came from `ggml/src/ggml-cpu/`. `SHA256SUMS` records every +vendored file. The upstream MIT license is in `LICENSE`. + +`control-plane/src/ggml_bridge.c` is the local, separate dispatch adapter. +`control-plane/build.rs` links the pinned C implementation statically into +the Rust executable for offline model preparation. Serving does not call this +CPU decoder. diff --git a/control-plane/third_party/ggml/ggml-alloc.h b/control-plane/third_party/ggml/ggml-alloc.h new file mode 100644 index 00000000..a7926a21 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-alloc.h @@ -0,0 +1,86 @@ +#pragma once + +#include "ggml.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct ggml_backend_buffer_type * ggml_backend_buffer_type_t; +typedef struct ggml_backend_buffer * ggml_backend_buffer_t; +typedef struct ggml_backend * ggml_backend_t; + +// Tensor allocator +struct ggml_tallocr { + ggml_backend_buffer_t buffer; + void * base; + size_t alignment; + size_t offset; +}; + +GGML_API struct ggml_tallocr ggml_tallocr_new(ggml_backend_buffer_t buffer); +GGML_API enum ggml_status ggml_tallocr_alloc(struct ggml_tallocr * talloc, struct ggml_tensor * tensor); + +// Graph allocator +/* + Example usage: + ggml_gallocr_t galloc = ggml_gallocr_new(ggml_backend_cpu_buffer_type()); + + // optional: create a worst-case graph and reserve the buffers to avoid reallocations + ggml_gallocr_reserve(galloc, build_graph(max_batch)); + + // allocate the graph + struct ggml_cgraph * graph = build_graph(batch); + ggml_gallocr_alloc_graph(galloc, graph); + + printf("compute buffer size: %zu bytes\n", ggml_gallocr_get_buffer_size(galloc, 0)); + + // evaluate the graph + ggml_backend_graph_compute(backend, graph); +*/ + +// special tensor flags for use with the graph allocator: +// ggml_set_input(): all input tensors are allocated at the beginning of the graph in non-overlapping addresses +// ggml_set_output(): output tensors are never freed and never overwritten + +typedef struct ggml_gallocr * ggml_gallocr_t; + +GGML_API ggml_gallocr_t ggml_gallocr_new(ggml_backend_buffer_type_t buft); +GGML_API ggml_gallocr_t ggml_gallocr_new_n(ggml_backend_buffer_type_t * bufts, int n_bufs); +GGML_API void ggml_gallocr_free(ggml_gallocr_t galloc); + +// pre-allocate buffers from a measure graph - does not allocate or modify the graph +// call with a worst-case graph to avoid buffer reallocations +// not strictly required for single buffer usage: ggml_gallocr_alloc_graph will reallocate the buffers automatically if needed +// returns false if the buffer allocation failed +// ggml_gallocr_resrve_n_size writes the buffer sizes per galloc buffer that would be allocated by ggml_gallocr_reserve_n to sizes +GGML_API bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph * graph); +GGML_API void ggml_gallocr_reserve_n_size( + ggml_gallocr_t galloc, + struct ggml_cgraph * graph, + const int * node_buffer_ids, + const int * leaf_buffer_ids, + size_t * sizes); +GGML_API bool ggml_gallocr_reserve_n( + ggml_gallocr_t galloc, + struct ggml_cgraph * graph, + const int * node_buffer_ids, + const int * leaf_buffer_ids); + +// automatic reallocation if the topology changes when using a single buffer +// returns false if using multiple buffers and a re-allocation is needed (call ggml_gallocr_reserve_n first to set the node buffers) +GGML_API bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph); + +GGML_API size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id); + +// Utils +// Create a buffer and allocate all the tensors in a ggml_context +// ggml_backend_alloc_ctx_tensors_from_buft_size returns the size of the buffer that would be allocated by ggml_backend_alloc_ctx_tensors_from_buft +// ggml_backend_alloc_ctx_tensors_from_buft returns NULL on failure or if all tensors in ctx are already allocated or zero-sized +GGML_API size_t ggml_backend_alloc_ctx_tensors_from_buft_size(struct ggml_context * ctx, ggml_backend_buffer_type_t buft); +GGML_API struct ggml_backend_buffer * ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft); +GGML_API struct ggml_backend_buffer * ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/ggml-backend.h b/control-plane/third_party/ggml/ggml-backend.h new file mode 100644 index 00000000..cc3f8cd3 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-backend.h @@ -0,0 +1,437 @@ +#pragma once + +#include "ggml.h" +#include "ggml-alloc.h" + +#ifdef GGML_BACKEND_SHARED +# if defined(_WIN32) && !defined(__MINGW32__) +# ifdef GGML_BACKEND_BUILD +# define GGML_BACKEND_API __declspec(dllexport) extern +# else +# define GGML_BACKEND_API __declspec(dllimport) extern +# endif +# else +# define GGML_BACKEND_API __attribute__ ((visibility ("default"))) extern +# endif +#else +# define GGML_BACKEND_API extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + typedef struct ggml_backend_buffer_type * ggml_backend_buffer_type_t; + typedef struct ggml_backend_buffer * ggml_backend_buffer_t; + typedef struct ggml_backend_event * ggml_backend_event_t; + typedef struct ggml_backend * ggml_backend_t; + typedef void * ggml_backend_graph_plan_t; + typedef struct ggml_backend_reg * ggml_backend_reg_t; + typedef struct ggml_backend_device * ggml_backend_dev_t; + + + // + // Backend buffer type + // + + GGML_API const char * ggml_backend_buft_name (ggml_backend_buffer_type_t buft); + GGML_API ggml_backend_buffer_t ggml_backend_buft_alloc_buffer (ggml_backend_buffer_type_t buft, size_t size); + GGML_API size_t ggml_backend_buft_get_alignment (ggml_backend_buffer_type_t buft); + GGML_API size_t ggml_backend_buft_get_max_size (ggml_backend_buffer_type_t buft); + GGML_API size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * tensor); + GGML_API bool ggml_backend_buft_is_host (ggml_backend_buffer_type_t buft); + GGML_API ggml_backend_dev_t ggml_backend_buft_get_device (ggml_backend_buffer_type_t buft); + + // + // Backend buffer + // + + enum ggml_backend_buffer_usage { + GGML_BACKEND_BUFFER_USAGE_ANY = 0, + GGML_BACKEND_BUFFER_USAGE_WEIGHTS = 1, + GGML_BACKEND_BUFFER_USAGE_COMPUTE = 2, + }; + + GGML_API const char * ggml_backend_buffer_name (ggml_backend_buffer_t buffer); + GGML_API void ggml_backend_buffer_free (ggml_backend_buffer_t buffer); + GGML_API void * ggml_backend_buffer_get_base (ggml_backend_buffer_t buffer); + GGML_API size_t ggml_backend_buffer_get_size (ggml_backend_buffer_t buffer); + GGML_API enum ggml_status ggml_backend_buffer_init_tensor (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor); + GGML_API size_t ggml_backend_buffer_get_alignment (ggml_backend_buffer_t buffer); + GGML_API size_t ggml_backend_buffer_get_max_size (ggml_backend_buffer_t buffer); + GGML_API size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor); + GGML_API void ggml_backend_buffer_clear (ggml_backend_buffer_t buffer, uint8_t value); + GGML_API bool ggml_backend_buffer_is_host (ggml_backend_buffer_t buffer); + GGML_API void ggml_backend_buffer_set_usage (ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage); + GGML_API enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage (ggml_backend_buffer_t buffer); + GGML_API ggml_backend_buffer_type_t ggml_backend_buffer_get_type (ggml_backend_buffer_t buffer); + GGML_API void ggml_backend_buffer_reset (ggml_backend_buffer_t buffer); + + // tensor copy between different backends + GGML_API void ggml_backend_tensor_copy(const struct ggml_tensor * src, struct ggml_tensor * dst); + + // + // Backend (stream) + // + + GGML_API ggml_guid_t ggml_backend_guid(ggml_backend_t backend); + GGML_API const char * ggml_backend_name(ggml_backend_t backend); + GGML_API void ggml_backend_free(ggml_backend_t backend); + + GGML_API ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend); + GGML_API ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size); + GGML_API size_t ggml_backend_get_alignment(ggml_backend_t backend); + GGML_API size_t ggml_backend_get_max_size(ggml_backend_t backend); + + GGML_API void ggml_backend_tensor_set_async (ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); + GGML_API void ggml_backend_tensor_get_async (ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); + GGML_API void ggml_backend_tensor_set_2d_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); + GGML_API void ggml_backend_tensor_get_2d_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); + + // "offset" refers to the offset in tensor->data for setting/getting data + GGML_API void ggml_backend_tensor_set ( struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); + GGML_API void ggml_backend_tensor_get (const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); + GGML_API void ggml_backend_tensor_set_2d( struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); + GGML_API void ggml_backend_tensor_get_2d(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); + GGML_API void ggml_backend_tensor_memset( struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size); + + GGML_API void ggml_backend_synchronize(ggml_backend_t backend); + + GGML_API ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph); + GGML_API void ggml_backend_graph_plan_free (ggml_backend_t backend, ggml_backend_graph_plan_t plan); + + GGML_API enum ggml_status ggml_backend_graph_plan_compute (ggml_backend_t backend, ggml_backend_graph_plan_t plan); + GGML_API enum ggml_status ggml_backend_graph_compute (ggml_backend_t backend, struct ggml_cgraph * cgraph); + GGML_API enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph); + + // NOTE: will be removed, use device version instead + GGML_API bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op); + GGML_API bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft); + GGML_API bool ggml_backend_offload_op(ggml_backend_t backend, const struct ggml_tensor * op); + + // asynchronous copy + // the copy is performed after all the currently queued operations in backend_src + // backend_dst will wait for the copy to complete before performing other operations + // automatic fallback to sync copy if async is not supported + GGML_API void ggml_backend_tensor_copy_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const struct ggml_tensor * src, struct ggml_tensor * dst); + + GGML_API ggml_backend_dev_t ggml_backend_get_device(ggml_backend_t backend); + + // + // Events + // + + GGML_API ggml_backend_event_t ggml_backend_event_new(ggml_backend_dev_t device); + GGML_API void ggml_backend_event_free(ggml_backend_event_t event); + GGML_API void ggml_backend_event_record(ggml_backend_event_t event, ggml_backend_t backend); + GGML_API void ggml_backend_event_synchronize(ggml_backend_event_t event); + GGML_API void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event); + + // + // Backend device + // + + enum ggml_backend_dev_type { + // CPU device using system memory + GGML_BACKEND_DEVICE_TYPE_CPU, + // GPU device using dedicated memory + GGML_BACKEND_DEVICE_TYPE_GPU, + // integrated GPU device using host memory + GGML_BACKEND_DEVICE_TYPE_IGPU, + // accelerator devices intended to be used together with the CPU backend (e.g. BLAS or AMX) + GGML_BACKEND_DEVICE_TYPE_ACCEL, + // "meta" device wrapping multiple other devices for tensor parallelism + GGML_BACKEND_DEVICE_TYPE_META, + }; + + // functionality supported by the device + struct ggml_backend_dev_caps { + // asynchronous operations + bool async; + // pinned host buffer + bool host_buffer; + // creating buffers from host ptr + bool buffer_from_host_ptr; + // event synchronization + bool events; + // mmap is supported for loading + bool mmap_support; + }; + + // all the device properties + struct ggml_backend_dev_props { + // device name + const char * name; + // device description + const char * description; + // device free memory in bytes + size_t memory_free; + // device total memory in bytes + size_t memory_total; + // device type + enum ggml_backend_dev_type type; + // device id + // for PCI devices, this should be the lower-case PCI bus id formatted as "domain:bus:device.function" (e.g. "0000:c1:00.0") + // if the id is unknown, this should be NULL + const char * device_id; + // device capabilities + struct ggml_backend_dev_caps caps; + }; + + GGML_API const char * ggml_backend_dev_name(ggml_backend_dev_t device); + GGML_API const char * ggml_backend_dev_description(ggml_backend_dev_t device); + GGML_API void ggml_backend_dev_memory(ggml_backend_dev_t device, size_t * free, size_t * total); + GGML_API enum ggml_backend_dev_type ggml_backend_dev_type(ggml_backend_dev_t device); + GGML_API void ggml_backend_dev_get_props(ggml_backend_dev_t device, struct ggml_backend_dev_props * props); + GGML_API ggml_backend_reg_t ggml_backend_dev_backend_reg(ggml_backend_dev_t device); + GGML_API ggml_backend_t ggml_backend_dev_init(ggml_backend_dev_t device, const char * params); + GGML_API ggml_backend_buffer_type_t ggml_backend_dev_buffer_type(ggml_backend_dev_t device); + GGML_API ggml_backend_buffer_type_t ggml_backend_dev_host_buffer_type(ggml_backend_dev_t device); + GGML_API ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t device, void * ptr, size_t size, size_t max_tensor_size); + + GGML_API bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op); + GGML_API bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft); + GGML_API bool ggml_backend_dev_offload_op(ggml_backend_dev_t device, const struct ggml_tensor * op); + + // + // Backend (reg) + // + + GGML_API const char * ggml_backend_reg_name(ggml_backend_reg_t reg); + GGML_API size_t ggml_backend_reg_dev_count(ggml_backend_reg_t reg); + GGML_API ggml_backend_dev_t ggml_backend_reg_dev_get(ggml_backend_reg_t reg, size_t index); + GGML_API void * ggml_backend_reg_get_proc_address(ggml_backend_reg_t reg, const char * name); + + // Common functions that may be obtained using ggml_backend_reg_get_proc_address + + // Context management and operations for faster communication between backends, used for tensor parallelism (meta backend) + typedef void * (*ggml_backend_comm_init_t)(ggml_backend_t * backends, size_t n_backends); + typedef void (*ggml_backend_comm_free_t)(void * comm_ctx); + typedef bool (*ggml_backend_comm_allreduce_tensor_t)(void * comm_ctx, struct ggml_tensor ** tensors); + + // Split buffer type for tensor parallelism (old) + typedef ggml_backend_buffer_type_t (*ggml_backend_split_buffer_type_t)(int main_device, const float * tensor_split); + // Set the number of threads for the backend + typedef void (*ggml_backend_set_n_threads_t)(ggml_backend_t backend, int n_threads); + // Get additional buffer types provided by the device (returns a NULL-terminated array) + typedef ggml_backend_buffer_type_t * (*ggml_backend_dev_get_extra_bufts_t)(ggml_backend_dev_t device); + // Set the abort callback for the backend + typedef void (*ggml_backend_set_abort_callback_t)(ggml_backend_t backend, ggml_abort_callback abort_callback, void * abort_callback_data); + // Get a list of feature flags supported by the backend (returns a NULL-terminated array) + struct ggml_backend_feature { + const char * name; + const char * value; + }; + typedef struct ggml_backend_feature * (*ggml_backend_get_features_t)(ggml_backend_reg_t reg); + + // + // Backend registry + // + + GGML_API void ggml_backend_register(ggml_backend_reg_t reg); + + GGML_API void ggml_backend_device_register(ggml_backend_dev_t device); + + // Backend (reg) enumeration + GGML_API size_t ggml_backend_reg_count(void); + GGML_API ggml_backend_reg_t ggml_backend_reg_get(size_t index); + GGML_API ggml_backend_reg_t ggml_backend_reg_by_name(const char * name); + + // Device enumeration + GGML_API size_t ggml_backend_dev_count(void); + GGML_API ggml_backend_dev_t ggml_backend_dev_get(size_t index); + GGML_API ggml_backend_dev_t ggml_backend_dev_by_name(const char * name); + GGML_API ggml_backend_dev_t ggml_backend_dev_by_type(enum ggml_backend_dev_type type); + + // Direct backend (stream) initialization + // = ggml_backend_dev_init(ggml_backend_dev_by_name(name), params) + GGML_API ggml_backend_t ggml_backend_init_by_name(const char * name, const char * params); + // = ggml_backend_dev_init(ggml_backend_dev_by_type(type), params) + GGML_API ggml_backend_t ggml_backend_init_by_type(enum ggml_backend_dev_type type, const char * params); + // = ggml_backend_dev_init(ggml_backend_dev_by_type(GPU) OR ggml_backend_dev_by_type(CPU), NULL) + GGML_API ggml_backend_t ggml_backend_init_best(void); + + // Load a backend from a dynamic library and register it + GGML_API ggml_backend_reg_t ggml_backend_load(const char * path); + // Unload a backend if loaded dynamically and unregister it + GGML_API void ggml_backend_unload(ggml_backend_reg_t reg); + // Load all known backends from dynamic libraries + GGML_API void ggml_backend_load_all(void); + GGML_API void ggml_backend_load_all_from_path(const char * dir_path); + + // + // Backend scheduler + // + + // The backend scheduler allows for multiple backend devices to be used together + // Handles compute buffer allocation, assignment of tensors to backends, and copying of tensors between backends + // The backends are selected based on: + // - the backend that supports the operation + // - the location of the pre-allocated tensors (e.g. the weights) + /* + Example usage: + + // operations that use tensors allocated in a buffer with USAGE_WEIGHTS will be assigned + // preferably to run on the same backend as the buffer + ggml_backend_buffer_set_usage(buf_weights, GGML_BACKEND_BUFFER_USAGE_WEIGHTS); + + sched = ggml_backend_sched_new({backend_gpu, backend_gpu2, backend_cpu}, NULL, num_backends, GGML_DEFAULT_GRAPH_SIZE, false, true); + + // initialize buffers from a max size graph (optional) + reserve_graph = build_graph(sched, max_batch_size); + + // manually assign nodes to a backend (optional, should not be needed in most cases) + struct ggml_tensor * node = ggml_mul_mat(ctx, ...); + ggml_backend_sched_set_tensor_backend(sched, node, backend_gpu); + + ggml_backend_sched_reserve(sched, reserve_graph); + + // compute + graph = build_graph(sched); // the graph and its tensors are single-use in terms of allocation, multi-use in terms of computation + for (int i = 0; i < 10; ++i) { + ggml_backend_sched_graph_compute(sched, graph); // on the first iteration the graph is allocated automatically + } + + // if there are graph inputs: + graph = build_graph(sched); // get a new graph that is not allocated (the metadata for the old graph is freed once ggml_free is called) + ggml_backend_sched_reset(sched); // clear the allocation of the previous graph + ggml_backend_sched_alloc_graph(sched, graph); // explicitly allocate the new graph but do not execute it + ggml_backend_tensor_set(input_tensor, ...); // copy data to the newly allocated graph tensors + ggml_backend_sched_graph_compute(sched, graph); // execute the graph + + // as an alternative to the above it is also possible to assign the inputs to a dedicated context and + // allocate them statically via ggml_backend_alloc_ctx_tensors + } + */ + + typedef struct ggml_backend_sched * ggml_backend_sched_t; + + // Evaluation callback for each node in the graph (set with ggml_backend_sched_set_eval_callback) + // when ask == true, the scheduler wants to know if the user wants to observe this node + // this allows the scheduler to batch nodes together in order to evaluate them in a single call + // + // when ask == false, the scheduler is passing the node tensor to the user for observation + // if the user returns false, the scheduler will cancel the graph compute + // + typedef bool (*ggml_backend_sched_eval_callback)(struct ggml_tensor * t, bool ask, void * user_data); + + // Initialize a backend scheduler, backends with low index are given priority over backends with high index + GGML_API ggml_backend_sched_t ggml_backend_sched_new(ggml_backend_t * backends, ggml_backend_buffer_type_t * bufts, int n_backends, size_t graph_size, bool parallel, bool op_offload); + GGML_API void ggml_backend_sched_free(ggml_backend_sched_t sched); + + // Initialize backend buffers from a measure graph + GGML_API void ggml_backend_sched_reserve_size(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph, size_t * sizes); + GGML_API bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph); // returns success + + GGML_API int ggml_backend_sched_get_n_backends(ggml_backend_sched_t sched); + GGML_API ggml_backend_t ggml_backend_sched_get_backend(ggml_backend_sched_t sched, int i); + + // Get the number of splits of the last graph + GGML_API int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched); + GGML_API int ggml_backend_sched_get_n_copies(ggml_backend_sched_t sched); + + GGML_API ggml_backend_buffer_type_t ggml_backend_sched_get_buffer_type(ggml_backend_sched_t sched, ggml_backend_t backend); + GGML_API size_t ggml_backend_sched_get_buffer_size(ggml_backend_sched_t sched, ggml_backend_t backend); + + GGML_API void ggml_backend_sched_set_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend); + GGML_API ggml_backend_t ggml_backend_sched_get_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node); + + // Split graph without allocating it + GGML_API void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph); + + // Allocate and compute graph on the backend scheduler + GGML_API bool ggml_backend_sched_alloc_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph); // returns success + GGML_API enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph); + GGML_API enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph); + GGML_API void ggml_backend_sched_synchronize(ggml_backend_sched_t sched); + + // Reset all assignments and allocators - must be called before changing the node backends or allocating a new graph. + // This in effect deallocates all tensors that were previously allocated and leaves them with dangling pointers. + // The correct way to use this API is to discard the deallocated tensors and create new ones. + GGML_API void ggml_backend_sched_reset(ggml_backend_sched_t sched); + + // Set a callback to be called for each resulting node during graph compute + GGML_API void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data); + + // + // Meta backend + // + +#define GGML_BACKEND_META_MAX_DEVICES 16 + + enum ggml_backend_meta_split_axis { + // tensor split by tensor dimensions: + GGML_BACKEND_SPLIT_AXIS_0 = 0, + GGML_BACKEND_SPLIT_AXIS_1 = 1, + GGML_BACKEND_SPLIT_AXIS_2 = 2, + GGML_BACKEND_SPLIT_AXIS_3 = 3, + + GGML_BACKEND_SPLIT_AXIS_MIRRORED = 10, // all values on all backends + GGML_BACKEND_SPLIT_AXIS_PARTIAL = 11, // each backend has a partial sum + + // for internal bookkeeping only: + GGML_BACKEND_SPLIT_AXIS_NONE = 98, + GGML_BACKEND_SPLIT_AXIS_UNKNOWN = 99, + }; + GGML_API const char * ggml_backend_meta_split_axis_name(enum ggml_backend_meta_split_axis split_axis); + + struct ggml_backend_meta_split_state { + enum ggml_backend_meta_split_axis axis; + + // for tensors with axis >= 0 && axis < GGML_MAX_DIMS: + // - each device has a slice of the tensor along the split axis + // - most tensors have n_segments == 1 and a contiguous slice of the tensor data + // - some tensors have an inhomogenenous data layout along the split axis, + // those tensors are divided into segments which are each individually split across devices + // - ne has one entry per segment and device and that segment repeats nr times, + // in total when accounting for repetitions the segments add up to ggml_tensor::ne for that axis, + // the outer/inner loops are over segments/devices like [seg0_dev0_r0, seg0_dev1_r0, seg0_dev0_r1, seg0_dev1_r1, seg1_dev0_r0, seg1_dev1_r0], + // - for example, a transformer may have a fused QKV matrix rather than 3 matrices, those would be 3 separate segments + // that each need to be split individually across devices so that each device gets a slice of Q, K, and V, + // the Q matrix can be larger than the K and V matrices so this can either be expressed as 3 segments or as 2 segments + // where the segment for K/V repeats twice + int64_t ne[16*GGML_BACKEND_META_MAX_DEVICES]; + uint32_t nr[16]; + uint32_t n_segments; + }; + + // function to assign split states for statically allocated tensors, compute tensor split states will be assigned to be compatible: + typedef struct ggml_backend_meta_split_state(*ggml_backend_meta_get_split_state_t)(const struct ggml_tensor * tensor, void * userdata); + + // create a new meta device from "simple" devices, meta buffer type/buffer/backend is then derived from this: + // TODO: this looks a bit strange - a backend API creates a device. I think we should try + // express this as a backend registry functionality instead + GGML_API ggml_backend_dev_t ggml_backend_meta_device( + ggml_backend_dev_t * devs, size_t n_devs, ggml_backend_meta_get_split_state_t get_split_state, void * get_split_state_ud); + + // + // Utils + // + + struct ggml_backend_graph_copy { + ggml_backend_buffer_t buffer; + struct ggml_context * ctx_allocated; + struct ggml_context * ctx_unallocated; + struct ggml_cgraph * graph; + }; + + // Copy a graph to a different backend + GGML_API struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph); + GGML_API void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy); + + typedef bool (*ggml_backend_eval_callback)(int node_index, struct ggml_tensor * t1, struct ggml_tensor * t2, void * user_data); + + // Compare the output of two backends + GGML_API bool ggml_backend_compare_graph_backend(ggml_backend_t backend1, ggml_backend_t backend2, struct ggml_cgraph * graph, ggml_backend_eval_callback callback, void * user_data, struct ggml_tensor const * const * test_nodes, size_t num_test_nodes); + + // Tensor initialization + GGML_API enum ggml_status ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr); + GGML_API enum ggml_status ggml_backend_view_init(struct ggml_tensor * tensor); + + // CPU buffer types are always available + GGML_API ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size); + GGML_API ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/ggml-common.h b/control-plane/third_party/ggml/ggml-common.h new file mode 100644 index 00000000..1dbbe326 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-common.h @@ -0,0 +1,1911 @@ +#ifndef GGML_COMMON_DECL + +#if defined(GGML_COMMON_DECL_C) +#include + +typedef uint16_t ggml_half; +typedef uint32_t ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_CPP) +#include + +typedef uint16_t ggml_half; +typedef uint32_t ggml_half2; + +// std-c++ allow anonymous unions but some compiler warn on it +#define GGML_COMMON_AGGR_U data +// std-c++ do not allow it. +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_METAL) +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_CUDA) +#if defined(GGML_COMMON_DECL_MUSA) +#include +#else +#include +#endif +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_HIP) +#include +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_SYCL) +#include +#include + +typedef sycl::half ggml_half; +typedef sycl::half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#endif + +#if defined(GGML_COMMON_DECL) + +#ifndef __cplusplus +#ifndef static_assert +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L) +#define static_assert(cond, msg) _Static_assert(cond, msg) +#else +#define static_assert(cond, msg) struct global_scope_noop_trick +#endif +#endif +#endif // __cplusplus + +// QK = number of values after dequantization +// QK_K = super-block size + +#define QK_K 256 +#define K_SCALE_SIZE 12 + +#if defined(GGML_COMMON_DECL_CUDA) || defined(GGML_COMMON_DECL_HIP) || defined(GGML_COMMON_DECL_SYCL) +// QR = QK / number of values before dequantization +// QI = number of 32 bit integers before dequantization + +#define QI1_0 (QK1_0 / 32) +#define QR1_0 1 + +#define QI2_0 (QK2_0 / 32) +#define QR2_0 1 + + +#define QI4_0 (QK4_0 / (4 * QR4_0)) +#define QR4_0 2 + +#define QI4_1 (QK4_1 / (4 * QR4_1)) +#define QR4_1 2 + +#define QI_MXFP4 (QK_MXFP4 / (4 * QR_MXFP4)) +#define QR_MXFP4 2 + +#define QI_NVFP4 (QK_NVFP4 / (4 * QR_NVFP4)) +#define QR_NVFP4 2 + +#define QI5_0 (QK5_0 / (4 * QR5_0)) +#define QR5_0 2 + +#define QI5_1 (QK5_1 / (4 * QR5_1)) +#define QR5_1 2 + +#define QI8_0 (QK8_0 / (4 * QR8_0)) +#define QR8_0 1 + +#define QI8_1 (QK8_1 / (4 * QR8_1)) +#define QR8_1 1 + +#define QI2_K (QK_K / (4*QR2_K)) +#define QR2_K 4 + +#define QI3_K (QK_K / (4*QR3_K)) +#define QR3_K 4 + +#define QI4_K (QK_K / (4*QR4_K)) +#define QR4_K 2 + +#define QI5_K (QK_K / (4*QR5_K)) +#define QR5_K 2 + +#define QI6_K (QK_K / (4*QR6_K)) +#define QR6_K 2 + +#define QI2_XXS (QK_K / (4*QR2_XXS)) +#define QR2_XXS 4 + +#define QI2_XS (QK_K / (4*QR2_XS)) +#define QR2_XS 4 + +#define QI2_S (QK_K / (4*QR2_S)) +#define QR2_S 4 + +#define QI3_XXS (QK_K / (4*QR3_XXS)) +#define QR3_XXS 4 + +#define QI3_XS (QK_K / (4*QR3_XS)) +#define QR3_XS 4 + +#define QI1_S (QK_K / (4*QR1_S)) +#define QR1_S 8 + +#define QI1_M (QK_K / (4*QR1_M)) +#define QR1_M 8 + +#define QI4_NL (QK4_NL / (4*QR4_NL)) +#define QR4_NL 2 + +#define QI4_XS (QK_K / (4*QR4_XS)) +#define QR4_XS 2 + +#define QI3_S (QK_K / (4*QR3_S)) +#define QR3_S 4 + +#endif // GGML_COMMON_DECL_CUDA || GGML_COMMON_DECL_HIP + +#ifdef _MSC_VER +#define GGML_EXTENSION +#else // _MSC_VER +#define GGML_EXTENSION __extension__ +#endif // _MSC_VER + +#define QK1_0 128 +typedef struct { + ggml_half d; // delta + uint8_t qs[QK1_0 / 8]; // bits / quants +} block_q1_0; +static_assert(sizeof(block_q1_0) == sizeof(ggml_half) + QK1_0 / 8, "wrong q1_0 block size/padding"); + +#define QK2_0 64 +typedef struct { + ggml_half d; // delta (scale) + uint8_t qs[QK2_0 / 4]; // 2 bits per element +} block_q2_0; +static_assert(sizeof(block_q2_0) == sizeof(ggml_half) + QK2_0 / 4, "wrong q2_0 block size/padding"); + +#define QK4_0 32 +typedef struct { + ggml_half d; // delta + uint8_t qs[QK4_0 / 2]; // nibbles / quants +} block_q4_0; +static_assert(sizeof(block_q4_0) == sizeof(ggml_half) + QK4_0 / 2, "wrong q4_0 block size/padding"); + +#define QK4_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half m; // min + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t qs[QK4_1 / 2]; // nibbles / quants +} block_q4_1; +static_assert(sizeof(block_q4_1) == 2 * sizeof(ggml_half) + QK4_1 / 2, "wrong q4_1 block size/padding"); + +#define QK_MXFP4 32 +typedef struct { + uint8_t e; // E8M0 + uint8_t qs[QK_MXFP4/2]; +} block_mxfp4; +static_assert(sizeof(block_mxfp4) == sizeof(uint8_t) + QK_MXFP4/2, "wrong mxfp4 block size/padding"); + +#define QK_NVFP4 64 +#define QK_NVFP4_SUB 16 // sub-block size for per-group scales +typedef struct { + uint8_t d[QK_NVFP4/QK_NVFP4_SUB]; // UE4M3 scales (4 bytes, one per 16-element sub-block) + uint8_t qs[QK_NVFP4/2]; // packed 4-bit E2M1 values (32 bytes) +} block_nvfp4; +static_assert(sizeof(block_nvfp4) == sizeof(uint8_t)*(QK_NVFP4/QK_NVFP4_SUB) + QK_NVFP4/2, "wrong nvfp4 block size/padding"); + +#define QK5_0 32 +typedef struct { + ggml_half d; // delta + uint8_t qh[4]; // 5-th bit of quants + uint8_t qs[QK5_0 / 2]; // nibbles / quants +} block_q5_0; +static_assert(sizeof(block_q5_0) == sizeof(ggml_half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding"); + +#define QK5_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half m; // min + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t qh[4]; // 5-th bit of quants + uint8_t qs[QK5_1 / 2]; // nibbles / quants +} block_q5_1; +static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding"); + +#define QK8_0 32 +typedef struct { + ggml_half d; // delta + int8_t qs[QK8_0]; // quants +} block_q8_0; +static_assert(sizeof(block_q8_0) == sizeof(ggml_half) + QK8_0, "wrong q8_0 block size/padding"); + +#define QK8_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half s; // d * sum(qs[i]) + } GGML_COMMON_AGGR_S; + ggml_half2 ds; + } GGML_COMMON_AGGR_U; + int8_t qs[QK8_1]; // quants +} block_q8_1; +static_assert(sizeof(block_q8_1) == 2*sizeof(ggml_half) + QK8_1, "wrong q8_1 block size/padding"); + +// +// Ternary quantization +// + +// 1.6875 bpw +typedef struct { + uint8_t qs[(QK_K - 4 * QK_K / 64) / 5]; // 5 elements per byte (3^5 = 243 < 256) + uint8_t qh[QK_K/64]; // 4 elements per byte + ggml_half d; +} block_tq1_0; +static_assert(sizeof(block_tq1_0) == sizeof(ggml_half) + QK_K / 64 + (QK_K - 4 * QK_K / 64) / 5, "wrong tq1_0 block size/padding"); + +// 2.0625 bpw +typedef struct { + uint8_t qs[QK_K/4]; // 2 bits per element + ggml_half d; +} block_tq2_0; +static_assert(sizeof(block_tq2_0) == sizeof(ggml_half) + QK_K / 4, "wrong tq2_0 block size/padding"); + +// +// Super-block quantization structures +// + +// 2-bit quantization +// weight is represented as x = a * q + b +// 16 blocks of 16 elements each +// Effectively 2.625 bits per weight +typedef struct { + uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits + uint8_t qs[QK_K/4]; // quants + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; +} block_q2_K; +static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding"); + +// 3-bit quantization +// weight is represented as x = a * q +// 16 blocks of 16 elements each +// Effectively 3.4375 bits per weight +typedef struct { + uint8_t hmask[QK_K/8]; // quants - high bit + uint8_t qs[QK_K/4]; // quants - low 2 bits + uint8_t scales[12]; // scales, quantized with 6 bits + ggml_half d; // super-block scale +} block_q3_K; +static_assert(sizeof(block_q3_K) == sizeof(ggml_half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding"); + +// 4-bit quantization +// 8 blocks of 32 elements each +// weight is represented as x = a * q + b +// Effectively 4.5 bits per weight +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits + uint8_t qs[QK_K/2]; // 4--bit quants +} block_q4_K; +static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding"); + +// 5-bit quantization +// 8 blocks of 32 elements each +// weight is represented as x = a * q + b +// Effectively 5.5 bits per weight +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits + uint8_t qh[QK_K/8]; // quants, high bit + uint8_t qs[QK_K/2]; // quants, low 4 bits +} block_q5_K; +static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding"); + +// 6-bit quantization +// weight is represented as x = a * q +// 16 blocks of 16 elements each +// Effectively 6.5625 bits per weight +typedef struct { + uint8_t ql[QK_K/2]; // quants, lower 4 bits + uint8_t qh[QK_K/4]; // quants, upper 2 bits + int8_t scales[QK_K/16]; // scales, quantized with 8 bits + ggml_half d; // super-block scale +} block_q6_K; +static_assert(sizeof(block_q6_K) == sizeof(ggml_half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding"); + +// This is only used for intermediate quantization and dot products +typedef struct { + float d; // delta + int8_t qs[QK_K]; // quants + int16_t bsums[QK_K/16]; // sum of quants in groups of 16 +} block_q8_K; +static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding"); + +// (Almost) "true" 2-bit quantization. +// Due to the need to use blocks as per ggml design, it ends up using +// 2.0625 bpw because of the 16-bit scale for each block of 256. +typedef struct { + ggml_half d; + uint16_t qs[QK_K/8]; +} block_iq2_xxs; +static_assert(sizeof(block_iq2_xxs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding"); + +// 2.3125 bpw quants +typedef struct { + ggml_half d; + uint16_t qs[QK_K/8]; + uint8_t scales[QK_K/32]; +} block_iq2_xs; +static_assert(sizeof(block_iq2_xs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding"); + +// 2.5625 bpw quants +typedef struct { + ggml_half d; + uint8_t qs[QK_K/4]; + uint8_t qh[QK_K/32]; + uint8_t scales[QK_K/32]; +} block_iq2_s; +static_assert(sizeof(block_iq2_s) == sizeof(ggml_half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding"); + +// (Almost) "true" 3-bit quantization. +// Due to the need to use blocks as per ggml design, it ends up using +// 3.0625 bpw because of the 16-bit scale for each block of 256. +typedef struct { + ggml_half d; + uint8_t qs[3*QK_K/8]; +} block_iq3_xxs; +static_assert(sizeof(block_iq3_xxs) == sizeof(ggml_half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding"); + +// 3.4375 bpw +#define IQ3S_N_SCALE QK_K/64 +typedef struct { + ggml_half d; + uint8_t qs[QK_K/4]; + uint8_t qh[QK_K/32]; + uint8_t signs[QK_K/8]; + uint8_t scales[IQ3S_N_SCALE]; +} block_iq3_s; +static_assert(sizeof(block_iq3_s) == sizeof(ggml_half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding"); + +// 1.5625 bpw +typedef struct { + ggml_half d; + uint8_t qs[QK_K/8]; + uint16_t qh[QK_K/32]; +} block_iq1_s; +static_assert(sizeof(block_iq1_s) == sizeof(ggml_half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding"); + +// 1.75 bpw +typedef struct { + uint8_t qs[QK_K/8]; // grid index, low 8 bits + uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8) + uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64) +} block_iq1_m; +static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding"); + +// Used by IQ1_M quants +typedef union { + ggml_half f16; + uint16_t u16; +} iq1m_scale_t; + +// Non-linear quants +#define QK4_NL 32 +typedef struct { + ggml_half d; + uint8_t qs[QK4_NL/2]; +} block_iq4_nl; +static_assert(sizeof(block_iq4_nl) == sizeof(ggml_half) + QK4_NL/2, "wrong iq4_nl block size/padding"); + +typedef struct { + ggml_half d; + uint16_t scales_h; + uint8_t scales_l[QK_K/64]; + uint8_t qs[QK_K/2]; +} block_iq4_xs; +static_assert(sizeof(block_iq4_xs) == sizeof(ggml_half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding"); + +#endif // GGML_COMMON_DECL +#endif // GGML_COMMON_DECL + +//////////////////////////////////////////////////////////////////////////////// + +#ifndef GGML_COMMON_IMPL + +#if defined(GGML_COMMON_IMPL_C) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_CPP) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_METAL) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const constant type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_CUDA) || defined(GGML_COMMON_IMPL_HIP) || defined(GGML_COMMON_IMPL_MUSA) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const __device__ type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_SYCL) + +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#endif + +#if defined(GGML_COMMON_IMPL) + +GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8) + 1, 2, 4, 8, 16, 32, 64, 128 +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128) + 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, + 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, + 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, + 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, + 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, + 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, + 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, + 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, ksigns64, 128) + 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff, + 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff, + 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff, + 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff, + 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff, + 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff, + 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff, + 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff, + 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff, + 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff, + 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff, + 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff, + 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff, + 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff, + 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff, + 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff, + 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff, + 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff, + 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff, + 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff, + 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff, + 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff, + 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff, + 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff, + 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff, + 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff, + 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff, + 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff, + 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff, + 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff, + 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff, + 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff, +GGML_TABLE_END() + + +GGML_TABLE_BEGIN(uint64_t, iq2xxs_grid, 256) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, + 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, + 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, + 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, + 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, + 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, + 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, + 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, + 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, + 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, + 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, + 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, + 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, + 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, + 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, + 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, + 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, + 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, + 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, + 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, + 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, + 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, + 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, + 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, + 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, + 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, + 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, + 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, + 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, + 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, + 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, + 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, + 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, + 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, + 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, + 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, + 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, + 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, + 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, + 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, + 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, + 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, + 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, + 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, + 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, + 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, + 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, + 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, + 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, + 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, + 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, + 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, + 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, + 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, + 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, + 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, + 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, + 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, + 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, + 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, + 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, + 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, + 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, iq2xs_grid, 512) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, + 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, + 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, + 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, + 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, + 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, + 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, + 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, + 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, + 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, + 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, + 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, + 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, + 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, + 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, + 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, + 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, + 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, + 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, + 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, + 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, + 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, + 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, + 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, + 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, + 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, + 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, + 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, + 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, + 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, + 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, + 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, + 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, + 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, + 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, + 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, + 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, + 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, + 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, + 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, + 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, + 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, + 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, + 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, + 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, + 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, + 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, + 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, + 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, + 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, + 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, + 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, + 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, + 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, + 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, + 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, + 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, + 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, + 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, + 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, + 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, + 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, + 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, + 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, + 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, + 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, + 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, + 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, + 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, + 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, + 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, + 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, + 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, + 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, + 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, + 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, + 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, + 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, + 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, + 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, + 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, + 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, + 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, + 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, + 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, + 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, + 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, + 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, + 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, + 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, + 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, + 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, + 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, + 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, + 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, + 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, + 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, + 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, + 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, + 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, + 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, + 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, + 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, + 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, + 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, + 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, + 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, + 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, + 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, + 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, + 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, + 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, + 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, + 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, + 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, + 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, + 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, + 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, + 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, + 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, + 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, + 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, + 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, + 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, + 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, + 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, + 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, + 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, + 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, + 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, + 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, + 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, + 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, + 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, + 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, + 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, + 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, + 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, + 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, + 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, + 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, + 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, + 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, + 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, + 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, + 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, + 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, + 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, + 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, + 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, + 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, + 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, + 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, + 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, + 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, + 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, + 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, + 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, + 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, + 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, + 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, + 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, + 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, + 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, + 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, + 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, + 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, + 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, + 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, + 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, + 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, + 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, + 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, + 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, + 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, + 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, + 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, + 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, + 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, + 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, + 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, + 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, + 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, + 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, + 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, + 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, + 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, + 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, + 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, + 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, + 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, + 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, + 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, + 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, + 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, + 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, + 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, + 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, + 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, + 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, + 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, + 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, + 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, + 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, + 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, + 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, + 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, + 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, + 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, + 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, + 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, + 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, + 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, + 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, + 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, + 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, + 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, + 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, + 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, + 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, + 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, + 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, + 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, + 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, + 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, + 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, + 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, + 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, + 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, + 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, + 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, + 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, + 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, + 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, + 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, + 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, + 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, + 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, + 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, + 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, + 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, + 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, + 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, + 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, + 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, + 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, + 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, + 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, + 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, + 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, + 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, + 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, + 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, + 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, + 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, + 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, + 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, + 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, + 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, + 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, + 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, + 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, + 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, + 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, + 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, + 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, + 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, + 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, + 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, + 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, + 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, + 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, + 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, + 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, + 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, + 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, + 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, + 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, + 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, + 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, + 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, + 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, + 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, + 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, + 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, + 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, + 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, + 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, + 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, + 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, + 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, + 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, + 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, + 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, + 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, + 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, + 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, + 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, + 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, + 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, + 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, + 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, + 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, + 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, + 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, + 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, + 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, + 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, + 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, + 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, + 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, + 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, + 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, + 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, + 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, + 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, + 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, + 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, + 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, + 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, + 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, + 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, + 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, + 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, + 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, + 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, + 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, + 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, + 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, + 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, + 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, + 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, + 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, + 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, + 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, + 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, + 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, + 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, + 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, + 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, + 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, + 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, + 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, + 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, + 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, + 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, + 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, + 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, + 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, + 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, + 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, + 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, + 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, + 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, + 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, + 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, + 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, + 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, + 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, + 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, + 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, + 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, + 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, + 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, + 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, + 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, + 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, + 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, + 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, + 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, + 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, + 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, + 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, + 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, + 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, + 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, + 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, + 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, + 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, + 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, + 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256) + 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, + 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, + 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, + 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, + 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, + 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, + 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, + 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, + 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, + 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, + 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, + 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, + 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, + 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, + 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, + 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, + 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, + 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, + 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, + 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, + 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, + 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, + 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, + 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, + 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, + 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, + 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, + 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, + 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, + 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, + 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, + 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512) + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, + 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, + 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, + 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, + 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, + 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, + 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, + 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, + 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, + 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, + 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, + 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, + 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, + 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, + 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, + 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, + 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, + 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, + 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, + 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, + 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, + 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, + 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, + 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, + 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, + 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, + 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, + 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, + 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, + 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, + 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, + 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, + 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, + 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, + 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, + 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, + 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, + 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, + 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, + 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, + 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, + 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, + 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, + 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, + 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, + 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, + 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, + 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, + 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, + 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, + 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, + 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, + 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, + 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, + 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, + 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, + 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, +GGML_TABLE_END() + +// TODO: fix name to kvalues_iq4_nl +GGML_TABLE_BEGIN(int8_t, kvalues_iq4nl, 16) + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, +GGML_TABLE_END() + +// e2m1 values (doubled), shared by MXFP4 and NVFP4 +// ref: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +GGML_TABLE_BEGIN(int8_t, kvalues_fp4, 16) + 0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12, +GGML_TABLE_END() +#define kvalues_mxfp4 kvalues_fp4 + +#define NGRID_IQ1S 2048 +#define IQ1S_DELTA 0.125f +#define IQ1M_DELTA 0.125f +#if defined(GGML_COMMON_IMPL_C) || defined(GGML_COMMON_IMPL_CPP) +GGML_TABLE_BEGIN(uint64_t, iq1s_grid, NGRID_IQ1S) + 0xffffffffffffffff, 0xffffffffffffff01, 0xffffffffffff0000, 0xffffffffffff01ff, + 0xffffffffffff0101, 0xffffffffff00ff00, 0xffffffffff000000, 0xffffffffff01ffff, + 0xffffffffff01ff01, 0xffffffffff0101ff, 0xffffffffff010101, 0xffffffff00ff0000, + 0xffffffff0000ff00, 0xffffffff000000ff, 0xffffffff00000001, 0xffffffff00010000, + 0xffffffff01ffffff, 0xffffffff01ffff01, 0xffffffff01ff01ff, 0xffffffff01ff0101, + 0xffffffff01000000, 0xffffffff0101ffff, 0xffffffff0101ff01, 0xffffffff010101ff, + 0xffffffff01010101, 0xffffff00ffff00ff, 0xffffff00ffff0000, 0xffffff00ff00ff00, + 0xffffff00ff0000ff, 0xffffff00ff000001, 0xffffff00ff000100, 0xffffff00ff000101, + 0xffffff00ff010000, 0xffffff0000ffff00, 0xffffff0000ff0001, 0xffffff0000ff0100, + 0xffffff000000ff01, 0xffffff0000000000, 0xffffff0000000101, 0xffffff000001ff00, + 0xffffff00000100ff, 0xffffff0000010001, 0xffffff00000101ff, 0xffffff0001ff0000, + 0xffffff000100ff00, 0xffffff00010000ff, 0xffffff0001000001, 0xffffff0001010000, + 0xffffff01ffffffff, 0xffffff01ffffff01, 0xffffff01ffff01ff, 0xffffff01ffff0101, + 0xffffff01ff000000, 0xffffff01ff01ffff, 0xffffff01ff01ff01, 0xffffff01ff0101ff, + 0xffffff01ff010101, 0xffffff0100ff0000, 0xffffff010000ff00, 0xffffff0100000100, + 0xffffff01000100ff, 0xffffff0100010100, 0xffffff0101ffffff, 0xffffff0101ffff01, + 0xffffff0101ff01ff, 0xffffff0101ff0101, 0xffffff010100ff00, 0xffffff0101000000, + 0xffffff0101000100, 0xffffff010101ffff, 0xffffff010101ff01, 0xffffff01010101ff, + 0xffffff0101010101, 0xffff00ffff00ff00, 0xffff00ffff0000ff, 0xffff00ffff000001, + 0xffff00ffff010000, 0xffff00ff00ffff00, 0xffff00ff00ff0100, 0xffff00ff00000000, + 0xffff00ff00000101, 0xffff00ff000100ff, 0xffff00ff00010000, 0xffff00ff0100ff00, + 0xffff00ff01000100, 0xffff00ff01010000, 0xffff0000ffffff00, 0xffff0000ffff00ff, + 0xffff0000ffff0000, 0xffff0000ffff0001, 0xffff0000ff000000, 0xffff0000ff0001ff, + 0xffff0000ff000101, 0xffff0000ff010100, 0xffff000000ffffff, 0xffff000000ff0000, + 0xffff000000ff0101, 0xffff00000000ffff, 0xffff00000000ff00, 0xffff0000000000ff, + 0xffff000000000000, 0xffff000000000001, 0xffff000000000100, 0xffff00000001ffff, + 0xffff00000001ff01, 0xffff000000010000, 0xffff0000000101ff, 0xffff000000010101, + 0xffff000001ffff00, 0xffff00000100ff00, 0xffff000001000000, 0xffff0000010001ff, + 0xffff000001000101, 0xffff00000101ff00, 0xffff0000010100ff, 0xffff000001010000, + 0xffff000001010001, 0xffff000001010100, 0xffff0001ff0000ff, 0xffff0001ff000100, + 0xffff000100ffff00, 0xffff000100ff00ff, 0xffff00010000ffff, 0xffff00010000ff01, + 0xffff000100000000, 0xffff0001000001ff, 0xffff00010001ffff, 0xffff00010001ff00, + 0xffff000100010001, 0xffff000100010100, 0xffff000101ff0000, 0xffff00010100ff00, + 0xffff0001010000ff, 0xffff000101000100, 0xffff01ffffffffff, 0xffff01ffffffff01, + 0xffff01ffffff01ff, 0xffff01ffffff0101, 0xffff01ffff000000, 0xffff01ffff01ffff, + 0xffff01ffff01ff01, 0xffff01ffff0101ff, 0xffff01ffff010101, 0xffff01ff00ff0000, + 0xffff01ff0000ff00, 0xffff01ff00000001, 0xffff01ff00010000, 0xffff01ff01ffffff, + 0xffff01ff01ffff01, 0xffff01ff01ff01ff, 0xffff01ff01ff0101, 0xffff01ff01000000, + 0xffff01ff0101ffff, 0xffff01ff0101ff01, 0xffff01ff010101ff, 0xffff01ff01010101, + 0xffff0100ffff0000, 0xffff0100ff00ff00, 0xffff0100ff0000ff, 0xffff0100ff000100, + 0xffff0100ff0100ff, 0xffff0100ff010000, 0xffff010000ffff00, 0xffff01000000ffff, + 0xffff01000000ff00, 0xffff010000000000, 0xffff01000001ff00, 0xffff0100000100ff, + 0xffff010000010100, 0xffff01000100ff00, 0xffff0100010000ff, 0xffff010001000001, + 0xffff010001000100, 0xffff010001010000, 0xffff0101ffffffff, 0xffff0101ffffff01, + 0xffff0101ffff01ff, 0xffff0101ffff0101, 0xffff0101ff000000, 0xffff0101ff01ffff, + 0xffff0101ff01ff01, 0xffff0101ff0101ff, 0xffff0101ff010101, 0xffff010100ff0000, + 0xffff01010000ff00, 0xffff010100000100, 0xffff01010001ff00, 0xffff010100010000, + 0xffff010101ffffff, 0xffff010101ffff01, 0xffff010101ff0000, 0xffff010101ff01ff, + 0xffff010101ff0101, 0xffff010101000000, 0xffff01010101ffff, 0xffff01010101ff01, + 0xffff0101010101ff, 0xffff010101010101, 0xff00ffffff00ffff, 0xff00ffffff00ff00, + 0xff00ffffff0000ff, 0xff00ffffff000100, 0xff00ffffff0100ff, 0xff00ffffff010000, + 0xff00ffff00ffff00, 0xff00ffff00ff00ff, 0xff00ffff0000ffff, 0xff00ffff00000000, + 0xff00ffff000001ff, 0xff00ffff0001ff00, 0xff00ffff000100ff, 0xff00ffff00010000, + 0xff00ffff00010100, 0xff00ffff0100ff00, 0xff00ffff010000ff, 0xff00ffff01000001, + 0xff00ffff0101ff00, 0xff00ffff01010000, 0xff00ff00ffffff00, 0xff00ff00ffff00ff, + 0xff00ff00ffff0001, 0xff00ff00ffff0100, 0xff00ff00ff00ffff, 0xff00ff00ff00ff01, + 0xff00ff00ff000000, 0xff00ff00ff0001ff, 0xff00ff00ff01ff00, 0xff00ff00ff0100ff, + 0xff00ff00ff010100, 0xff00ff0000ff0000, 0xff00ff0000ff0101, 0xff00ff000000ffff, + 0xff00ff000000ff00, 0xff00ff000000ff01, 0xff00ff00000000ff, 0xff00ff0000000000, + 0xff00ff0000000001, 0xff00ff0000000100, 0xff00ff000001ffff, 0xff00ff0000010000, + 0xff00ff0001ff00ff, 0xff00ff000100ff01, 0xff00ff0001000000, 0xff00ff000101ff00, + 0xff00ff00010100ff, 0xff00ff01ff00ff00, 0xff00ff01ff0000ff, 0xff00ff01ff000001, + 0xff00ff01ff010000, 0xff00ff0100ffffff, 0xff00ff0100ff0001, 0xff00ff0100ff0100, + 0xff00ff010000ff01, 0xff00ff0100000000, 0xff00ff01000001ff, 0xff00ff0100000101, + 0xff00ff01000100ff, 0xff00ff0100010001, 0xff00ff0101ff0000, 0xff00ff010100ff00, + 0xff00ff01010000ff, 0xff00ff0101000001, 0xff00ff0101010000, 0xff0000ffffffff00, + 0xff0000ffffff0001, 0xff0000ffffff0100, 0xff0000ffff0000ff, 0xff0000ffff000000, + 0xff0000ffff0001ff, 0xff0000ffff000100, 0xff0000ffff01ff00, 0xff0000ffff010001, + 0xff0000ff00ffff00, 0xff0000ff00ff0000, 0xff0000ff00ff0001, 0xff0000ff00ff01ff, + 0xff0000ff00ff0101, 0xff0000ff0000ff00, 0xff0000ff000000ff, 0xff0000ff00000000, + 0xff0000ff00000001, 0xff0000ff00000100, 0xff0000ff0001ff01, 0xff0000ff00010000, + 0xff0000ff000101ff, 0xff0000ff01ff00ff, 0xff0000ff01ff0100, 0xff0000ff0100ffff, + 0xff0000ff010000ff, 0xff0000ff01000000, 0xff0000ff010001ff, 0xff0000ff01000100, + 0xff0000ff01000101, 0xff0000ff0101ff00, 0xff0000ff010100ff, 0xff0000ff01010000, + 0xff0000ff01010100, 0xff000000ffffff01, 0xff000000ffff0000, 0xff000000ffff0101, + 0xff000000ff00ff00, 0xff000000ff0000ff, 0xff000000ff000000, 0xff000000ff000001, + 0xff000000ff000100, 0xff000000ff01ffff, 0xff000000ff01ff01, 0xff000000ff010000, + 0xff000000ff0101ff, 0xff000000ff010101, 0xff00000000ffff00, 0xff00000000ff00ff, + 0xff00000000ff0000, 0xff00000000ff0001, 0xff0000000000ff00, 0xff0000000000ff01, + 0xff000000000000ff, 0xff00000000000000, 0xff00000000000001, 0xff00000000000100, + 0xff00000000000101, 0xff0000000001ff00, 0xff000000000100ff, 0xff00000000010000, + 0xff00000000010001, 0xff00000000010100, 0xff00000001ffffff, 0xff00000001ffff01, + 0xff00000001ff00ff, 0xff00000001ff0000, 0xff00000001ff01ff, 0xff00000001ff0101, + 0xff0000000100ffff, 0xff0000000100ff00, 0xff000000010000ff, 0xff00000001000000, + 0xff00000001000001, 0xff00000001000100, 0xff00000001000101, 0xff0000000101ffff, + 0xff0000000101ff01, 0xff00000001010000, 0xff000001ffffff00, 0xff000001ffff00ff, + 0xff000001ffff0000, 0xff000001ffff0001, 0xff000001ff000000, 0xff000001ff000001, + 0xff000001ff0001ff, 0xff000001ff000101, 0xff000001ff01ff00, 0xff000001ff010001, + 0xff00000100ffffff, 0xff00000100ffff01, 0xff00000100ff00ff, 0xff00000100ff0000, + 0xff00000100ff01ff, 0xff00000100ff0101, 0xff0000010000ff00, 0xff00000100000000, + 0xff00000100000001, 0xff000001000001ff, 0xff00000100000100, 0xff0000010001ff00, + 0xff000001000100ff, 0xff00000100010000, 0xff000001000101ff, 0xff00000100010100, + 0xff00000100010101, 0xff00000101ff0001, 0xff00000101ff0101, 0xff0000010100ff01, + 0xff00000101000000, 0xff000001010100ff, 0xff00000101010100, 0xff0001ffff00ff00, + 0xff0001ffff000001, 0xff0001ffff010000, 0xff0001ff00ffff00, 0xff0001ff00ff00ff, + 0xff0001ff00ff0001, 0xff0001ff00ff0100, 0xff0001ff0000ffff, 0xff0001ff00000000, + 0xff0001ff000001ff, 0xff0001ff00000101, 0xff0001ff0001ffff, 0xff0001ff0001ff00, + 0xff0001ff000100ff, 0xff0001ff00010001, 0xff0001ff00010100, 0xff0001ff01ff0000, + 0xff0001ff0100ff00, 0xff0001ff010000ff, 0xff0001ff01010000, 0xff000100ff00ffff, + 0xff000100ff00ff01, 0xff000100ff000000, 0xff000100ff000101, 0xff000100ff01ff00, + 0xff000100ff010000, 0xff00010000ffff01, 0xff00010000ff00ff, 0xff00010000ff0000, + 0xff00010000ff01ff, 0xff0001000000ff00, 0xff000100000000ff, 0xff00010000000000, + 0xff00010000000001, 0xff00010000000100, 0xff00010000000101, 0xff0001000001ffff, + 0xff00010000010000, 0xff00010000010101, 0xff00010001ff0100, 0xff0001000100ff00, + 0xff0001000100ff01, 0xff00010001000000, 0xff000100010001ff, 0xff0001000101ff00, + 0xff00010001010001, 0xff00010001010100, 0xff000101ffff0100, 0xff000101ff000001, + 0xff000101ff0100ff, 0xff000101ff010001, 0xff00010100ff00ff, 0xff00010100ff0001, + 0xff00010100ff0100, 0xff0001010000ffff, 0xff0001010000ff01, 0xff00010100000000, + 0xff000101000001ff, 0xff0001010001ff00, 0xff00010100010001, 0xff00010100010100, + 0xff00010101ff0000, 0xff0001010100ff00, 0xff00010101000001, 0xff00010101000101, + 0xff01ffffffffffff, 0xff01ffffffffff01, 0xff01ffffffff01ff, 0xff01ffffffff0101, + 0xff01ffffff000000, 0xff01ffffff01ffff, 0xff01ffffff01ff01, 0xff01ffffff010000, + 0xff01ffffff0101ff, 0xff01ffffff010101, 0xff01ffff00ff0000, 0xff01ffff0000ff00, + 0xff01ffff00000100, 0xff01ffff0001ff00, 0xff01ffff00010000, 0xff01ffff01ffffff, + 0xff01ffff01ffff01, 0xff01ffff01ff01ff, 0xff01ffff01ff0101, 0xff01ffff01000000, + 0xff01ffff0101ffff, 0xff01ffff0101ff01, 0xff01ffff01010000, 0xff01ffff010101ff, + 0xff01ffff01010101, 0xff01ff00ffff0000, 0xff01ff00ff00ff00, 0xff01ff00ff0000ff, + 0xff01ff00ff000100, 0xff01ff00ff010000, 0xff01ff0000ffff01, 0xff01ff0000ff00ff, + 0xff01ff0000ff0100, 0xff01ff0000000000, 0xff01ff00000001ff, 0xff01ff0000000101, + 0xff01ff000001ff00, 0xff01ff00000100ff, 0xff01ff0000010000, 0xff01ff0000010001, + 0xff01ff0001ff0000, 0xff01ff000100ffff, 0xff01ff0001000001, 0xff01ff0001000100, + 0xff01ff0001010000, 0xff01ff01ffffff00, 0xff01ff01ffff01ff, 0xff01ff01ffff0101, + 0xff01ff01ff00ff00, 0xff01ff01ff000000, 0xff01ff01ff01ffff, 0xff01ff01ff01ff01, + 0xff01ff01ff0101ff, 0xff01ff01ff010101, 0xff01ff0100ff0000, 0xff01ff010000ff00, + 0xff01ff0100000001, 0xff01ff0100000100, 0xff01ff0100010000, 0xff01ff0101ffff00, + 0xff01ff0101ff01ff, 0xff01ff0101ff0101, 0xff01ff010100ff00, 0xff01ff0101000000, + 0xff01ff010101ffff, 0xff01ff010101ff01, 0xff01ff01010101ff, 0xff01ff0101010101, + 0xff0100ffffff0000, 0xff0100ffff0000ff, 0xff0100ffff000001, 0xff0100ffff000100, + 0xff0100ffff010000, 0xff0100ff00ff00ff, 0xff0100ff00ff0000, 0xff0100ff00ff0001, + 0xff0100ff00ff0100, 0xff0100ff0000ff01, 0xff0100ff00000000, 0xff0100ff000001ff, + 0xff0100ff00000101, 0xff0100ff00010001, 0xff0100ff01ff0000, 0xff0100ff0100ff00, + 0xff0100ff010000ff, 0xff0100ff01000100, 0xff0100ff0101ff00, 0xff0100ff01010000, + 0xff010000ffff0100, 0xff010000ff000000, 0xff010000ff01ff00, 0xff010000ff010100, + 0xff01000000ffffff, 0xff01000000ff0000, 0xff01000000ff01ff, 0xff0100000000ff00, + 0xff010000000000ff, 0xff01000000000000, 0xff01000000000100, 0xff0100000001ff01, + 0xff01000000010000, 0xff010000000101ff, 0xff01000001ff0100, 0xff0100000100ffff, + 0xff010000010000ff, 0xff01000001000000, 0xff010000010001ff, 0xff01000001000101, + 0xff0100000101ff00, 0xff010000010100ff, 0xff01000001010001, 0xff01000001010100, + 0xff010001ffff0000, 0xff010001ff00ffff, 0xff010001ff00ff01, 0xff010001ff000100, + 0xff010001ff010000, 0xff01000100ffff00, 0xff01000100ff0100, 0xff01000100000000, + 0xff0100010001ffff, 0xff0100010001ff00, 0xff01000100010100, 0xff01000101ff00ff, + 0xff01000101ff0001, 0xff0100010100ffff, 0xff01000101000101, 0xff0101ffffffffff, + 0xff0101ffffffff01, 0xff0101ffffff01ff, 0xff0101ffffff0101, 0xff0101ffff000000, + 0xff0101ffff01ffff, 0xff0101ffff01ff01, 0xff0101ffff0101ff, 0xff0101ffff010101, + 0xff0101ff00ff0000, 0xff0101ff0000ff00, 0xff0101ff000000ff, 0xff0101ff00010000, + 0xff0101ff01ffffff, 0xff0101ff01ffff01, 0xff0101ff01ff01ff, 0xff0101ff01ff0101, + 0xff0101ff0101ffff, 0xff0101ff0101ff01, 0xff0101ff010101ff, 0xff0101ff01010101, + 0xff010100ffff0100, 0xff010100ff00ff00, 0xff010100ff0000ff, 0xff010100ff000100, + 0xff010100ff010000, 0xff01010000ff0001, 0xff01010000ff0100, 0xff0101000000ff01, + 0xff01010000000000, 0xff0101000001ff00, 0xff010100000100ff, 0xff01010000010001, + 0xff01010000010100, 0xff01010001ff0000, 0xff0101000100ffff, 0xff01010001000001, + 0xff01010001000100, 0xff010100010100ff, 0xff01010001010000, 0xff010101ffffffff, + 0xff010101ffffff01, 0xff010101ffff01ff, 0xff010101ffff0101, 0xff010101ff01ffff, + 0xff010101ff01ff01, 0xff010101ff0101ff, 0xff010101ff010101, 0xff01010100ff0000, + 0xff0101010000ff00, 0xff01010100000001, 0xff01010100000100, 0xff01010100010000, + 0xff01010101ffffff, 0xff01010101ffff01, 0xff01010101ff01ff, 0xff01010101ff0101, + 0xff01010101000000, 0xff0101010101ffff, 0xff0101010101ff01, 0xff010101010101ff, + 0xff01010101010101, 0x00ffffffffff0000, 0x00ffffffff00ff00, 0x00ffffffff000001, + 0x00ffffffff010000, 0x00ffffff00ff0100, 0x00ffffff0000ff01, 0x00ffffff00000000, + 0x00ffffff000001ff, 0x00ffffff00000101, 0x00ffffff0001ff00, 0x00ffffff000100ff, + 0x00ffffff00010001, 0x00ffffff010000ff, 0x00ffffff01000100, 0x00ffffff0101ff00, + 0x00ffffff01010001, 0x00ffff00ffffffff, 0x00ffff00ffffff00, 0x00ffff00ffff00ff, + 0x00ffff00ffff0001, 0x00ffff00ffff0100, 0x00ffff00ff00ff01, 0x00ffff00ff000000, + 0x00ffff00ff000001, 0x00ffff00ff0001ff, 0x00ffff00ff000101, 0x00ffff00ff01ff00, + 0x00ffff00ff010001, 0x00ffff00ff010100, 0x00ffff0000ff0000, 0x00ffff0000ff01ff, + 0x00ffff0000ff0101, 0x00ffff000000ff00, 0x00ffff00000000ff, 0x00ffff0000000000, + 0x00ffff0000000001, 0x00ffff0000000100, 0x00ffff0000000101, 0x00ffff0000010000, + 0x00ffff00000101ff, 0x00ffff0000010101, 0x00ffff0001ffff00, 0x00ffff0001ff00ff, + 0x00ffff0001ff0001, 0x00ffff000100ffff, 0x00ffff000100ff01, 0x00ffff0001000000, + 0x00ffff000101ffff, 0x00ffff000101ff00, 0x00ffff000101ff01, 0x00ffff01ffff0000, + 0x00ffff01ff00ff00, 0x00ffff01ff0000ff, 0x00ffff01ff000001, 0x00ffff01ff010000, + 0x00ffff0100ffff00, 0x00ffff010000ff01, 0x00ffff0100000000, 0x00ffff0100000101, + 0x00ffff01000100ff, 0x00ffff0100010100, 0x00ffff0101ff0100, 0x00ffff01010000ff, + 0x00ffff0101010000, 0x00ff00ffffffff00, 0x00ff00ffff000000, 0x00ff00ffff000100, + 0x00ff00ffff010100, 0x00ff00ff00ff0000, 0x00ff00ff00ff01ff, 0x00ff00ff00ff0101, + 0x00ff00ff0000ff00, 0x00ff00ff000000ff, 0x00ff00ff00000000, 0x00ff00ff00000001, + 0x00ff00ff0001ff00, 0x00ff00ff0001ff01, 0x00ff00ff00010000, 0x00ff00ff000101ff, + 0x00ff00ff00010101, 0x00ff00ff01ffff00, 0x00ff00ff01ff0001, 0x00ff00ff01ff0100, + 0x00ff00ff0100ffff, 0x00ff00ff0100ff01, 0x00ff00ff01000000, 0x00ff00ff0101ffff, + 0x00ff00ff0101ff00, 0x00ff00ff01010100, 0x00ff0000ffffff00, 0x00ff0000ffffff01, + 0x00ff0000ffff0000, 0x00ff0000ffff0101, 0x00ff0000ff00ff00, 0x00ff0000ff0000ff, + 0x00ff0000ff000000, 0x00ff0000ff000001, 0x00ff0000ff000100, 0x00ff0000ff01ffff, + 0x00ff0000ff010000, 0x00ff0000ff010101, 0x00ff000000ffff00, 0x00ff000000ff00ff, + 0x00ff000000ff0000, 0x00ff000000ff0001, 0x00ff000000ff0100, 0x00ff00000000ffff, + 0x00ff00000000ff00, 0x00ff0000000000ff, 0x00ff000000000000, 0x00ff000000000001, + 0x00ff0000000001ff, 0x00ff000000000100, 0x00ff00000001ff00, 0x00ff0000000100ff, + 0x00ff000000010000, 0x00ff000000010001, 0x00ff000000010100, 0x00ff000001ffff01, + 0x00ff000001ff00ff, 0x00ff000001ff0000, 0x00ff000001ff01ff, 0x00ff00000100ff00, + 0x00ff0000010000ff, 0x00ff000001000000, 0x00ff000001000001, 0x00ff000001000100, + 0x00ff000001000101, 0x00ff000001010000, 0x00ff0000010101ff, 0x00ff000001010101, + 0x00ff0001ffffff00, 0x00ff0001ffff0000, 0x00ff0001ffff0100, 0x00ff0001ff0000ff, + 0x00ff0001ff000000, 0x00ff0001ff0001ff, 0x00ff0001ff000101, 0x00ff0001ff01ff00, + 0x00ff0001ff0100ff, 0x00ff0001ff010100, 0x00ff000100ffffff, 0x00ff000100ffff01, + 0x00ff000100ff0000, 0x00ff000100ff01ff, 0x00ff00010000ffff, 0x00ff00010000ff00, + 0x00ff00010000ff01, 0x00ff000100000000, 0x00ff000100000001, 0x00ff000100000100, + 0x00ff00010001ff01, 0x00ff000100010000, 0x00ff0001000101ff, 0x00ff000101ffff00, + 0x00ff000101ff0000, 0x00ff000101ff0101, 0x00ff0001010000ff, 0x00ff000101000000, + 0x00ff00010101ff00, 0x00ff0001010100ff, 0x00ff000101010001, 0x00ff01ffffff0000, + 0x00ff01ffff00ff00, 0x00ff01ffff000000, 0x00ff01ffff000101, 0x00ff01ffff010000, + 0x00ff01ff00ffff01, 0x00ff01ff00ff0100, 0x00ff01ff0000ffff, 0x00ff01ff00000000, + 0x00ff01ff000001ff, 0x00ff01ff0001ff00, 0x00ff01ff000100ff, 0x00ff01ff00010001, + 0x00ff01ff00010100, 0x00ff01ff01ff0000, 0x00ff01ff0100ff00, 0x00ff01ff010000ff, + 0x00ff01ff01000001, 0x00ff01ff01000100, 0x00ff01ff01010000, 0x00ff0100ffffff00, + 0x00ff0100ffff0000, 0x00ff0100ffff0001, 0x00ff0100ffff0101, 0x00ff0100ff00ffff, + 0x00ff0100ff0000ff, 0x00ff0100ff000000, 0x00ff0100ff0001ff, 0x00ff0100ff01ff00, + 0x00ff0100ff0100ff, 0x00ff0100ff010001, 0x00ff010000ffffff, 0x00ff010000ff0000, + 0x00ff010000ff0101, 0x00ff01000000ff00, 0x00ff01000000ff01, 0x00ff0100000000ff, + 0x00ff010000000000, 0x00ff010000000001, 0x00ff010000000100, 0x00ff01000001ffff, + 0x00ff01000001ff01, 0x00ff010000010000, 0x00ff010000010001, 0x00ff010000010101, + 0x00ff010001ff0001, 0x00ff010001ff0100, 0x00ff01000100ff01, 0x00ff010001000000, + 0x00ff010001000001, 0x00ff0100010001ff, 0x00ff01000101ff00, 0x00ff0100010100ff, + 0x00ff010001010001, 0x00ff010001010100, 0x00ff0101ff000001, 0x00ff010100ff00ff, + 0x00ff010100ff0001, 0x00ff010100ff0100, 0x00ff010100000000, 0x00ff0101000001ff, + 0x00ff010100000101, 0x00ff0101000100ff, 0x00ff010100010100, 0x00ff0101010000ff, + 0x00ff010101010000, 0x0000ffffffffff00, 0x0000ffffffff00ff, 0x0000ffffffff0000, + 0x0000ffffffff0001, 0x0000ffffffff0100, 0x0000ffffff00ff01, 0x0000ffffff000000, + 0x0000ffffff000101, 0x0000ffffff01ff00, 0x0000ffffff0100ff, 0x0000ffffff010100, + 0x0000ffff00ffffff, 0x0000ffff00ff0000, 0x0000ffff00ff01ff, 0x0000ffff0000ff00, + 0x0000ffff000000ff, 0x0000ffff00000000, 0x0000ffff00000001, 0x0000ffff00000100, + 0x0000ffff00010000, 0x0000ffff000101ff, 0x0000ffff01ff0001, 0x0000ffff01ff0100, + 0x0000ffff01000000, 0x0000ffff010001ff, 0x0000ffff0101ffff, 0x0000ffff0101ff00, + 0x0000ffff01010001, 0x0000ffff01010100, 0x0000ff00ffff0000, 0x0000ff00ffff01ff, + 0x0000ff00ffff0100, 0x0000ff00ffff0101, 0x0000ff00ff00ff00, 0x0000ff00ff0000ff, + 0x0000ff00ff000000, 0x0000ff00ff000001, 0x0000ff00ff0001ff, 0x0000ff00ff000100, + 0x0000ff00ff01ffff, 0x0000ff00ff010000, 0x0000ff00ff010001, 0x0000ff00ff0101ff, + 0x0000ff00ff010101, 0x0000ff0000ffff00, 0x0000ff0000ff00ff, 0x0000ff0000ff0000, + 0x0000ff0000ff0001, 0x0000ff0000ff0100, 0x0000ff000000ffff, 0x0000ff000000ff00, + 0x0000ff000000ff01, 0x0000ff00000000ff, 0x0000ff0000000000, 0x0000ff0000000001, + 0x0000ff00000001ff, 0x0000ff0000000100, 0x0000ff0000000101, 0x0000ff000001ff00, + 0x0000ff00000100ff, 0x0000ff0000010000, 0x0000ff0000010001, 0x0000ff0000010100, + 0x0000ff0001ffff01, 0x0000ff0001ff0000, 0x0000ff000100ff00, 0x0000ff00010000ff, + 0x0000ff0001000000, 0x0000ff0001000001, 0x0000ff0001000100, 0x0000ff000101ffff, + 0x0000ff0001010000, 0x0000ff0001010101, 0x0000ff01ffffff00, 0x0000ff01ffff0001, + 0x0000ff01ff00ff01, 0x0000ff01ff000000, 0x0000ff01ff000101, 0x0000ff01ff01ff00, + 0x0000ff01ff0100ff, 0x0000ff0100ffff01, 0x0000ff0100ff0000, 0x0000ff0100ff0101, + 0x0000ff010000ff00, 0x0000ff01000000ff, 0x0000ff0100000000, 0x0000ff0100000001, + 0x0000ff0100000100, 0x0000ff010001ff01, 0x0000ff0100010000, 0x0000ff0101ff0000, + 0x0000ff010100ffff, 0x0000ff010100ff01, 0x0000ff0101000000, 0x0000ff0101000100, + 0x0000ff0101000101, 0x0000ff01010100ff, 0x000000ffffff00ff, 0x000000ffffff0000, + 0x000000ffff00ff00, 0x000000ffff0000ff, 0x000000ffff000000, 0x000000ffff000001, + 0x000000ffff0001ff, 0x000000ffff000100, 0x000000ffff01ff00, 0x000000ffff010000, + 0x000000ffff0101ff, 0x000000ffff010101, 0x000000ff00ffff00, 0x000000ff00ff00ff, + 0x000000ff00ff0000, 0x000000ff00ff0001, 0x000000ff00ff0100, 0x000000ff00ff0101, + 0x000000ff0000ffff, 0x000000ff0000ff00, 0x000000ff000000ff, 0x000000ff00000000, + 0x000000ff00000001, 0x000000ff000001ff, 0x000000ff00000100, 0x000000ff00000101, + 0x000000ff0001ff00, 0x000000ff0001ff01, 0x000000ff000100ff, 0x000000ff00010000, + 0x000000ff00010001, 0x000000ff00010100, 0x000000ff01ffffff, 0x000000ff01ff01ff, + 0x000000ff01ff0101, 0x000000ff0100ff00, 0x000000ff010000ff, 0x000000ff01000000, + 0x000000ff01000001, 0x000000ff01000100, 0x000000ff0101ff00, 0x000000ff010100ff, + 0x000000ff01010000, 0x000000ff01010101, 0x00000000ffffff00, 0x00000000ffffff01, + 0x00000000ffff00ff, 0x00000000ffff0000, 0x00000000ffff0001, 0x00000000ffff0100, + 0x00000000ff00ffff, 0x00000000ff00ff00, 0x00000000ff00ff01, 0x00000000ff0000ff, + 0x00000000ff000000, 0x00000000ff000001, 0x00000000ff000100, 0x00000000ff000101, + 0x00000000ff01ff00, 0x00000000ff0100ff, 0x00000000ff010000, 0x00000000ff010001, + 0x00000000ff010100, 0x0000000000ffffff, 0x0000000000ffff00, 0x0000000000ffff01, + 0x0000000000ff00ff, 0x0000000000ff0000, 0x0000000000ff0001, 0x0000000000ff01ff, + 0x0000000000ff0100, 0x000000000000ffff, 0x000000000000ff00, 0x000000000000ff01, + 0x00000000000000ff, 0x0000000000000000, 0x0000000000000001, 0x00000000000001ff, + 0x0000000000000100, 0x0000000000000101, 0x000000000001ffff, 0x000000000001ff00, + 0x00000000000100ff, 0x0000000000010000, 0x0000000000010001, 0x00000000000101ff, + 0x0000000000010100, 0x0000000000010101, 0x0000000001ffff00, 0x0000000001ff00ff, + 0x0000000001ff0000, 0x0000000001ff0100, 0x0000000001ff0101, 0x000000000100ffff, + 0x000000000100ff00, 0x00000000010000ff, 0x0000000001000000, 0x0000000001000001, + 0x00000000010001ff, 0x0000000001000100, 0x000000000101ff00, 0x00000000010100ff, + 0x0000000001010000, 0x0000000001010001, 0x0000000001010100, 0x00000001ffffffff, + 0x00000001ffffff00, 0x00000001ffffff01, 0x00000001ffff00ff, 0x00000001ffff0001, + 0x00000001ffff01ff, 0x00000001ffff0100, 0x00000001ff00ff00, 0x00000001ff0000ff, + 0x00000001ff000000, 0x00000001ff0001ff, 0x00000001ff000100, 0x00000001ff01ffff, + 0x00000001ff01ff00, 0x00000001ff01ff01, 0x00000001ff0100ff, 0x00000001ff010000, + 0x00000001ff010001, 0x00000001ff0101ff, 0x00000001ff010100, 0x0000000100ffff00, + 0x0000000100ff0000, 0x0000000100ff0001, 0x0000000100ff01ff, 0x0000000100ff0100, + 0x0000000100ff0101, 0x000000010000ffff, 0x000000010000ff00, 0x000000010000ff01, + 0x00000001000000ff, 0x0000000100000000, 0x0000000100000001, 0x00000001000001ff, + 0x0000000100000100, 0x0000000100000101, 0x000000010001ff00, 0x00000001000100ff, + 0x0000000100010000, 0x0000000100010100, 0x0000000101ffff01, 0x0000000101ff0000, + 0x0000000101ff0001, 0x0000000101ff01ff, 0x0000000101ff0100, 0x0000000101ff0101, + 0x000000010100ff00, 0x0000000101000000, 0x0000000101000101, 0x000000010101ff01, + 0x0000000101010000, 0x0000000101010001, 0x00000001010101ff, 0x0000000101010100, + 0x000001ffffff00ff, 0x000001ffffff0000, 0x000001ffffff0001, 0x000001ffffff0100, + 0x000001ffff00ffff, 0x000001ffff000000, 0x000001ffff0001ff, 0x000001ffff01ff00, + 0x000001ffff010101, 0x000001ff00ff0000, 0x000001ff00ff01ff, 0x000001ff00ff0101, + 0x000001ff0000ff00, 0x000001ff000000ff, 0x000001ff00000000, 0x000001ff00000001, + 0x000001ff000001ff, 0x000001ff00000100, 0x000001ff0001ffff, 0x000001ff0001ff01, + 0x000001ff000100ff, 0x000001ff00010000, 0x000001ff01ffff01, 0x000001ff01ff0100, + 0x000001ff0100ffff, 0x000001ff0100ff01, 0x000001ff01000000, 0x000001ff010001ff, + 0x000001ff0101ff00, 0x000001ff01010100, 0x00000100ffffff00, 0x00000100ffffff01, + 0x00000100ffff0000, 0x00000100ffff0101, 0x00000100ff00ff00, 0x00000100ff0000ff, + 0x00000100ff000000, 0x00000100ff000001, 0x00000100ff000100, 0x00000100ff010000, + 0x0000010000ffff00, 0x0000010000ff00ff, 0x0000010000ff0000, 0x0000010000ff0001, + 0x0000010000ff0100, 0x000001000000ffff, 0x000001000000ff00, 0x000001000000ff01, + 0x00000100000000ff, 0x0000010000000000, 0x0000010000000001, 0x00000100000001ff, + 0x0000010000000100, 0x0000010000000101, 0x000001000001ff00, 0x00000100000100ff, + 0x0000010000010000, 0x0000010000010001, 0x0000010000010100, 0x0000010001ffff00, + 0x0000010001ff0000, 0x0000010001ff0100, 0x000001000100ff00, 0x00000100010000ff, + 0x0000010001000000, 0x0000010001000001, 0x00000100010001ff, 0x0000010001000100, + 0x0000010001010000, 0x00000101ffff00ff, 0x00000101ffff01ff, 0x00000101ff000000, + 0x00000101ff000101, 0x00000101ff01ffff, 0x00000101ff010000, 0x00000101ff010001, + 0x00000101ff010100, 0x0000010100ff0000, 0x0000010100ff01ff, 0x0000010100ff0100, + 0x000001010000ff00, 0x0000010100000000, 0x0000010100000001, 0x00000101000001ff, + 0x0000010100000100, 0x000001010001ff01, 0x0000010100010000, 0x00000101000101ff, + 0x0000010100010101, 0x0000010101ffff00, 0x0000010101ff0101, 0x000001010100ff01, + 0x0000010101000000, 0x0000010101000001, 0x00000101010001ff, 0x0000010101000101, + 0x000001010101ff00, 0x0001ffffffff0000, 0x0001ffffff0000ff, 0x0001ffffff000001, + 0x0001ffffff000100, 0x0001ffffff010000, 0x0001ffff00ff00ff, 0x0001ffff0000ffff, + 0x0001ffff00000000, 0x0001ffff00000001, 0x0001ffff000001ff, 0x0001ffff00000101, + 0x0001ffff0001ff00, 0x0001ffff000100ff, 0x0001ffff00010001, 0x0001ffff00010100, + 0x0001ffff01ffff00, 0x0001ffff01000001, 0x0001ffff01010000, 0x0001ff00ffffff00, + 0x0001ff00ffff00ff, 0x0001ff00ffff0001, 0x0001ff00ffff0100, 0x0001ff00ff00ff01, + 0x0001ff00ff000000, 0x0001ff00ff01ff00, 0x0001ff00ff01ff01, 0x0001ff00ff010001, + 0x0001ff00ff010100, 0x0001ff0000ff0000, 0x0001ff0000ff0100, 0x0001ff000000ff00, + 0x0001ff0000000000, 0x0001ff0000000001, 0x0001ff0000000100, 0x0001ff0000010000, + 0x0001ff0000010001, 0x0001ff0000010101, 0x0001ff0001ff00ff, 0x0001ff0001ff0101, + 0x0001ff000100ff01, 0x0001ff0001000000, 0x0001ff000101ff00, 0x0001ff0001010001, + 0x0001ff0001010100, 0x0001ff01ff00ff00, 0x0001ff01ff000001, 0x0001ff01ff000100, + 0x0001ff0100ffffff, 0x0001ff0100ffff00, 0x0001ff0100ff0001, 0x0001ff0100000000, + 0x0001ff0100000001, 0x0001ff01000001ff, 0x0001ff010001ffff, 0x0001ff0101ff0000, + 0x0001ff010100ff00, 0x0001ff0101000001, 0x0001ff0101010000, 0x000100ffff00ff00, + 0x000100ffff00ff01, 0x000100ffff000000, 0x000100ffff000001, 0x000100ffff000101, + 0x000100ffff01ff00, 0x000100ffff010001, 0x000100ffff010100, 0x000100ff00ffffff, + 0x000100ff00ffff01, 0x000100ff00ff0000, 0x000100ff00ff01ff, 0x000100ff00ff0101, + 0x000100ff0000ff00, 0x000100ff000000ff, 0x000100ff00000000, 0x000100ff00000001, + 0x000100ff00000100, 0x000100ff00000101, 0x000100ff0001ffff, 0x000100ff0001ff01, + 0x000100ff00010000, 0x000100ff01ff00ff, 0x000100ff01ff0000, 0x000100ff01ff0100, + 0x000100ff0100ffff, 0x000100ff0100ff01, 0x000100ff010000ff, 0x000100ff01000000, + 0x000100ff01000001, 0x000100ff010001ff, 0x000100ff01000101, 0x000100ff0101ff00, + 0x000100ff010100ff, 0x000100ff01010100, 0x00010000ffff0000, 0x00010000ffff01ff, + 0x00010000ffff0101, 0x00010000ff00ff00, 0x00010000ff000000, 0x00010000ff000001, + 0x00010000ff000100, 0x0001000000ff00ff, 0x0001000000ff0000, 0x0001000000ff0001, + 0x0001000000ff0100, 0x000100000000ffff, 0x000100000000ff00, 0x00010000000000ff, + 0x0001000000000000, 0x0001000000000001, 0x0001000000000100, 0x000100000001ff00, + 0x00010000000100ff, 0x0001000000010000, 0x0001000000010001, 0x0001000000010100, + 0x0001000001ff0001, 0x0001000001ff0100, 0x0001000001ff0101, 0x000100000100ff00, + 0x0001000001000000, 0x0001000001000001, 0x0001000001000100, 0x0001000001000101, + 0x000100000101ff01, 0x0001000001010000, 0x0001000001010001, 0x00010000010101ff, + 0x00010001ffffff01, 0x00010001ffff0100, 0x00010001ff000000, 0x00010001ff01ffff, + 0x00010001ff010001, 0x00010001ff0101ff, 0x00010001ff010100, 0x0001000100ffffff, + 0x0001000100ff0000, 0x0001000100ff01ff, 0x0001000100ff0101, 0x000100010000ff00, + 0x00010001000000ff, 0x0001000100000000, 0x0001000100000001, 0x00010001000001ff, + 0x0001000100000101, 0x000100010001ffff, 0x0001000100010000, 0x00010001000101ff, + 0x0001000101ffffff, 0x0001000101ffff01, 0x0001000101ff0000, 0x0001000101ff0101, + 0x00010001010000ff, 0x0001000101000001, 0x00010001010001ff, 0x0001000101000100, + 0x000100010101ffff, 0x00010001010100ff, 0x0001000101010001, 0x0001000101010101, + 0x000101ffff000001, 0x000101ffff000100, 0x000101ffff010000, 0x000101ff00ffff00, + 0x000101ff0000ff01, 0x000101ff00000000, 0x000101ff00000101, 0x000101ff0001ff00, + 0x000101ff00010100, 0x000101ff01ff0000, 0x000101ff0100ff00, 0x000101ff010001ff, + 0x000101ff01010001, 0x00010100ffffff00, 0x00010100ffff00ff, 0x00010100ff00ffff, + 0x00010100ff000000, 0x00010100ff01ff00, 0x00010100ff0100ff, 0x00010100ff010001, + 0x00010100ff010100, 0x0001010000ffffff, 0x0001010000ffff00, 0x0001010000ff0000, + 0x0001010000ff0001, 0x0001010000ff01ff, 0x000101000000ff00, 0x00010100000000ff, + 0x0001010000000000, 0x0001010000000001, 0x0001010000000100, 0x000101000001ffff, + 0x0001010000010000, 0x0001010000010101, 0x0001010001ffff01, 0x0001010001ff00ff, + 0x0001010001ff0101, 0x0001010001000000, 0x000101000101ff00, 0x00010100010100ff, + 0x0001010001010000, 0x0001010001010100, 0x00010101ff00ff00, 0x00010101ff000001, + 0x00010101ff0001ff, 0x0001010100ffff00, 0x0001010100ff00ff, 0x0001010100ff0100, + 0x000101010000ffff, 0x0001010100000000, 0x00010101000001ff, 0x0001010100000101, + 0x00010101000100ff, 0x0001010100010000, 0x0001010100010100, 0x0001010101ff0001, + 0x00010101010000ff, 0x00010101010001ff, 0x0001010101000101, 0x0001010101010001, + 0x01ffffffffffffff, 0x01ffffffffffff01, 0x01ffffffffff01ff, 0x01ffffffffff0101, + 0x01ffffffff01ffff, 0x01ffffffff01ff01, 0x01ffffffff0101ff, 0x01ffffffff010101, + 0x01ffffff00ff0000, 0x01ffffff0000ffff, 0x01ffffff0000ff00, 0x01ffffff000000ff, + 0x01ffffff00000001, 0x01ffffff00000100, 0x01ffffff00010000, 0x01ffffff01ffffff, + 0x01ffffff01ffff01, 0x01ffffff01ff01ff, 0x01ffffff01ff0101, 0x01ffffff01000000, + 0x01ffffff0101ffff, 0x01ffffff0101ff01, 0x01ffffff010101ff, 0x01ffffff01010101, + 0x01ffff00ffff0000, 0x01ffff00ff00ff00, 0x01ffff00ff0000ff, 0x01ffff00ff000001, + 0x01ffff00ff000100, 0x01ffff00ff010000, 0x01ffff0000ffff00, 0x01ffff0000ff00ff, + 0x01ffff0000ff0100, 0x01ffff000000ffff, 0x01ffff000000ff01, 0x01ffff0000000000, + 0x01ffff0000000001, 0x01ffff00000001ff, 0x01ffff0000000100, 0x01ffff00000100ff, + 0x01ffff0000010001, 0x01ffff0000010100, 0x01ffff0001ff0000, 0x01ffff0001ff0100, + 0x01ffff00010000ff, 0x01ffff0001000001, 0x01ffff0001000100, 0x01ffff0001010000, + 0x01ffff01ffffffff, 0x01ffff01ffffff01, 0x01ffff01ffff01ff, 0x01ffff01ffff0101, + 0x01ffff01ff000000, 0x01ffff01ff01ffff, 0x01ffff01ff01ff01, 0x01ffff01ff0101ff, + 0x01ffff01ff010101, 0x01ffff010000ff00, 0x01ffff01000000ff, 0x01ffff0100000100, + 0x01ffff0100010000, 0x01ffff0101ffffff, 0x01ffff0101ffff01, 0x01ffff0101ff01ff, + 0x01ffff0101ff0101, 0x01ffff0101000000, 0x01ffff010101ffff, 0x01ffff010101ff01, + 0x01ffff01010101ff, 0x01ffff0101010101, 0x01ff00ffff0000ff, 0x01ff00ffff000100, + 0x01ff00ff00ffff00, 0x01ff00ff00ff00ff, 0x01ff00ff0000ff00, 0x01ff00ff00000000, + 0x01ff00ff00000101, 0x01ff00ff0001ff00, 0x01ff00ff000100ff, 0x01ff00ff00010100, + 0x01ff00ff010000ff, 0x01ff00ff01000100, 0x01ff0000ffffff00, 0x01ff0000ffff0100, + 0x01ff0000ff00ff01, 0x01ff0000ff000000, 0x01ff0000ff000101, 0x01ff0000ff010001, + 0x01ff0000ff010100, 0x01ff000000ffffff, 0x01ff000000ffff00, 0x01ff000000ff0000, + 0x01ff000000ff01ff, 0x01ff00000000ff00, 0x01ff0000000000ff, 0x01ff000000000000, + 0x01ff000000000001, 0x01ff000000000100, 0x01ff000000000101, 0x01ff000000010000, + 0x01ff000000010001, 0x01ff0000000101ff, 0x01ff000000010101, 0x01ff000001ffff00, + 0x01ff000001ff00ff, 0x01ff000001ff0001, 0x01ff000001ff0100, 0x01ff00000100ffff, + 0x01ff00000100ff01, 0x01ff000001000000, 0x01ff0000010001ff, 0x01ff000001010001, + 0x01ff0001ff00ff00, 0x01ff0001ff000001, 0x01ff0001ff000100, 0x01ff0001ff010000, + 0x01ff000100ffff00, 0x01ff000100ff00ff, 0x01ff000100ff0100, 0x01ff000100ff0101, + 0x01ff00010000ffff, 0x01ff000100000000, 0x01ff000100000100, 0x01ff000100000101, + 0x01ff00010001ff00, 0x01ff000100010001, 0x01ff000100010101, 0x01ff000101ff0000, + 0x01ff00010100ff00, 0x01ff000101000101, 0x01ff0001010100ff, 0x01ff01ffffffffff, + 0x01ff01ffffffff01, 0x01ff01ffffff01ff, 0x01ff01ffffff0101, 0x01ff01ffff000000, + 0x01ff01ffff01ffff, 0x01ff01ffff01ff01, 0x01ff01ffff0101ff, 0x01ff01ffff010101, + 0x01ff01ff00ffff00, 0x01ff01ff00ff0000, 0x01ff01ff0000ff00, 0x01ff01ff000000ff, + 0x01ff01ff00000100, 0x01ff01ff00010000, 0x01ff01ff00010100, 0x01ff01ff01ffffff, + 0x01ff01ff01ffff01, 0x01ff01ff01ff01ff, 0x01ff01ff01ff0101, 0x01ff01ff01000000, + 0x01ff01ff0101ffff, 0x01ff01ff0101ff01, 0x01ff01ff010101ff, 0x01ff01ff01010101, + 0x01ff0100ffff0000, 0x01ff0100ffff0001, 0x01ff0100ff00ff00, 0x01ff0100ff0000ff, + 0x01ff0100ff000001, 0x01ff0100ff010000, 0x01ff010000ffff00, 0x01ff010000ff00ff, + 0x01ff010000ff0001, 0x01ff010000ff0100, 0x01ff01000000ffff, 0x01ff01000000ff01, + 0x01ff010000000000, 0x01ff010000000101, 0x01ff01000001ff00, 0x01ff0100000100ff, + 0x01ff010001ff0000, 0x01ff010001000001, 0x01ff010001000100, 0x01ff010001010000, + 0x01ff0101ffffffff, 0x01ff0101ffffff01, 0x01ff0101ffff01ff, 0x01ff0101ffff0101, + 0x01ff0101ff000000, 0x01ff0101ff01ffff, 0x01ff0101ff01ff01, 0x01ff0101ff0101ff, + 0x01ff0101ff010101, 0x01ff010100ff0000, 0x01ff01010000ff00, 0x01ff0101000000ff, + 0x01ff010100000001, 0x01ff010101ffffff, 0x01ff010101ffff01, 0x01ff010101ff01ff, + 0x01ff010101ff0101, 0x01ff010101000000, 0x01ff01010101ffff, 0x01ff01010101ff01, + 0x01ff0101010101ff, 0x01ff010101010101, 0x0100ffffffff0000, 0x0100ffffff00ff00, + 0x0100ffffff000001, 0x0100ffffff0001ff, 0x0100ffffff000100, 0x0100ffffff010000, + 0x0100ffff00ffff00, 0x0100ffff00ff0001, 0x0100ffff00ff0100, 0x0100ffff00000000, + 0x0100ffff000001ff, 0x0100ffff00000101, 0x0100ffff00010100, 0x0100ffff00010101, + 0x0100ffff01ff0000, 0x0100ffff0100ff00, 0x0100ffff010000ff, 0x0100ffff01000001, + 0x0100ffff01000100, 0x0100ffff01010000, 0x0100ff00ffffff00, 0x0100ff00ffff00ff, + 0x0100ff00ffff0001, 0x0100ff00ffff0100, 0x0100ff00ff00ffff, 0x0100ff00ff000000, + 0x0100ff00ff0001ff, 0x0100ff00ff000101, 0x0100ff00ff01ff00, 0x0100ff00ff0100ff, + 0x0100ff00ff010001, 0x0100ff00ff010100, 0x0100ff0000ffffff, 0x0100ff0000ff0000, + 0x0100ff000000ffff, 0x0100ff000000ff00, 0x0100ff00000000ff, 0x0100ff0000000000, + 0x0100ff0000000001, 0x0100ff0000000100, 0x0100ff000001ff01, 0x0100ff0000010000, + 0x0100ff0001ff00ff, 0x0100ff0001ff0001, 0x0100ff000100ff01, 0x0100ff0001000000, + 0x0100ff00010001ff, 0x0100ff000101ff00, 0x0100ff00010100ff, 0x0100ff0001010001, + 0x0100ff0001010100, 0x0100ff01ffff0000, 0x0100ff01ff00ff00, 0x0100ff01ff0000ff, + 0x0100ff01ff000100, 0x0100ff01ff010000, 0x0100ff0100ff00ff, 0x0100ff0100ff0001, + 0x0100ff0100ff0100, 0x0100ff010000ffff, 0x0100ff010000ff01, 0x0100ff0100000000, + 0x0100ff01000001ff, 0x0100ff0100010001, 0x0100ff0100010100, 0x0100ff0101ff0000, + 0x0100ff01010000ff, 0x0100ff0101000001, 0x0100ff0101010100, 0x010000ffffffff00, + 0x010000ffffff00ff, 0x010000ffffff0001, 0x010000ffff00ffff, 0x010000ffff000000, + 0x010000ffff0001ff, 0x010000ffff010001, 0x010000ff00ffffff, 0x010000ff00ff0101, + 0x010000ff0000ff00, 0x010000ff000000ff, 0x010000ff00000000, 0x010000ff00000001, + 0x010000ff000001ff, 0x010000ff00000100, 0x010000ff0001ffff, 0x010000ff0001ff00, + 0x010000ff0001ff01, 0x010000ff00010000, 0x010000ff01ff00ff, 0x010000ff01ff0001, + 0x010000ff0100ff01, 0x010000ff010000ff, 0x010000ff01000000, 0x010000ff010001ff, + 0x010000ff0101ff00, 0x010000ff01010100, 0x01000000ffffffff, 0x01000000ffff0000, + 0x01000000ffff01ff, 0x01000000ffff0101, 0x01000000ff00ffff, 0x01000000ff00ff00, + 0x01000000ff0000ff, 0x01000000ff000000, 0x01000000ff000001, 0x01000000ff000100, + 0x01000000ff01ff00, 0x01000000ff010000, 0x01000000ff010100, 0x01000000ff010101, + 0x0100000000ffff00, 0x0100000000ff00ff, 0x0100000000ff0000, 0x0100000000ff0001, + 0x0100000000ff0100, 0x010000000000ffff, 0x010000000000ff00, 0x010000000000ff01, + 0x01000000000000ff, 0x0100000000000000, 0x0100000000000001, 0x01000000000001ff, + 0x0100000000000100, 0x0100000000000101, 0x010000000001ff00, 0x01000000000100ff, + 0x0100000000010000, 0x0100000000010001, 0x0100000000010100, 0x0100000001ffff00, + 0x0100000001ff0000, 0x0100000001ff01ff, 0x010000000100ff00, 0x010000000100ff01, + 0x01000000010000ff, 0x0100000001000000, 0x0100000001000001, 0x0100000001000100, + 0x0100000001000101, 0x010000000101ffff, 0x010000000101ff01, 0x0100000001010000, + 0x01000000010101ff, 0x0100000001010101, 0x01000001ffffff00, 0x01000001ffff00ff, + 0x01000001ff00ffff, 0x01000001ff000000, 0x01000001ff000100, 0x01000001ff01ffff, + 0x01000001ff010001, 0x01000001ff010100, 0x0100000100ff0000, 0x0100000100ff01ff, + 0x0100000100ff0100, 0x010000010000ff00, 0x010000010000ff01, 0x0100000100000000, + 0x0100000100000001, 0x0100000100000100, 0x0100000100010000, 0x01000001000101ff, + 0x0100000101ffff01, 0x0100000101ff00ff, 0x0100000101ff0100, 0x0100000101ff0101, + 0x010000010100ff01, 0x01000001010000ff, 0x0100000101000000, 0x01000001010100ff, + 0x0100000101010001, 0x0100000101010100, 0x010001ffffff0000, 0x010001ffff000001, + 0x010001ffff000100, 0x010001ffff010000, 0x010001ff00ffff00, 0x010001ff00ff0001, + 0x010001ff0000ffff, 0x010001ff0000ff01, 0x010001ff00000000, 0x010001ff00000001, + 0x010001ff00000101, 0x010001ff000100ff, 0x010001ff00010000, 0x010001ff01ff0000, + 0x010001ff0100ff00, 0x010001ff01000001, 0x010001ff01000100, 0x010001ff01010000, + 0x01000100ffff00ff, 0x01000100ffff0001, 0x01000100ffff0100, 0x01000100ff00ffff, + 0x01000100ff00ff01, 0x01000100ff000000, 0x01000100ff0001ff, 0x01000100ff000101, + 0x01000100ff01ffff, 0x01000100ff01ff00, 0x01000100ff0100ff, 0x01000100ff010001, + 0x0100010000ffffff, 0x0100010000ffff01, 0x0100010000ff0000, 0x0100010000ff01ff, + 0x0100010000ff0101, 0x010001000000ff00, 0x01000100000000ff, 0x0100010000000000, + 0x0100010000000001, 0x0100010000000100, 0x010001000001ff01, 0x0100010000010000, + 0x0100010000010001, 0x0100010000010101, 0x0100010001ffff00, 0x0100010001ff00ff, + 0x010001000100ffff, 0x010001000100ff01, 0x0100010001000000, 0x0100010001000101, + 0x010001000101ff00, 0x0100010001010001, 0x01000101ffff0000, 0x01000101ff000000, + 0x01000101ff010000, 0x0100010100ff00ff, 0x0100010100ff0001, 0x0100010100ff0100, + 0x010001010000ffff, 0x0100010100000000, 0x01000101000001ff, 0x010001010001ff00, + 0x0100010101ff0000, 0x010001010100ff00, 0x01000101010000ff, 0x0100010101000000, + 0x0100010101000001, 0x0101ffffffffffff, 0x0101ffffffffff01, 0x0101ffffffff01ff, + 0x0101ffffffff0101, 0x0101ffffff000000, 0x0101ffffff01ffff, 0x0101ffffff01ff01, + 0x0101ffffff0101ff, 0x0101ffffff010101, 0x0101ffff00ff0000, 0x0101ffff0000ff00, + 0x0101ffff000000ff, 0x0101ffff00000001, 0x0101ffff00000100, 0x0101ffff01ffffff, + 0x0101ffff01ffff01, 0x0101ffff01ff01ff, 0x0101ffff01ff0101, 0x0101ffff01000000, + 0x0101ffff0101ffff, 0x0101ffff0101ff01, 0x0101ffff010101ff, 0x0101ffff01010101, + 0x0101ff00ffff0000, 0x0101ff00ffff0100, 0x0101ff00ff00ff00, 0x0101ff00ff0000ff, + 0x0101ff00ff000001, 0x0101ff00ff000100, 0x0101ff00ff000101, 0x0101ff0000ff0001, + 0x0101ff0000ff0100, 0x0101ff000000ff00, 0x0101ff0000000000, 0x0101ff00000001ff, + 0x0101ff0000000101, 0x0101ff000001ff00, 0x0101ff00000100ff, 0x0101ff0001ff0000, + 0x0101ff000100ffff, 0x0101ff000100ff01, 0x0101ff0001000001, 0x0101ff0001000100, + 0x0101ff01ffffff01, 0x0101ff01ffff01ff, 0x0101ff01ffff0101, 0x0101ff01ff00ffff, + 0x0101ff01ff000100, 0x0101ff01ff01ff01, 0x0101ff01ff0101ff, 0x0101ff01ff010101, + 0x0101ff0100ff0000, 0x0101ff010000ff00, 0x0101ff0100000001, 0x0101ff0100000100, + 0x0101ff0100010000, 0x0101ff0101ffffff, 0x0101ff0101ffff01, 0x0101ff0101ff01ff, + 0x0101ff0101ff0101, 0x0101ff0101000000, 0x0101ff010101ffff, 0x0101ff010101ff01, + 0x0101ff01010101ff, 0x0101ff0101010101, 0x010100ffff000100, 0x010100ffff010000, + 0x010100ff00ffff00, 0x010100ff00ff00ff, 0x010100ff0000ffff, 0x010100ff000000ff, + 0x010100ff00000000, 0x010100ff000001ff, 0x010100ff00000101, 0x010100ff0001ff00, + 0x010100ff00010000, 0x010100ff00010001, 0x010100ff000101ff, 0x010100ff00010100, + 0x010100ff01ff0000, 0x01010000ffff0001, 0x01010000ffff0100, 0x01010000ff00ffff, + 0x01010000ff00ff01, 0x01010000ff000000, 0x01010000ff0001ff, 0x01010000ff010001, + 0x01010000ff010100, 0x0101000000ffff01, 0x0101000000ff0000, 0x010100000000ff00, + 0x01010000000000ff, 0x0101000000000000, 0x0101000000000001, 0x0101000000000100, + 0x0101000000010000, 0x0101000000010101, 0x0101000001ffff00, 0x0101000001ff00ff, + 0x0101000001ff0000, 0x0101000001ff0001, 0x0101000001ff0100, 0x010100000100ff01, + 0x0101000001000000, 0x01010000010001ff, 0x01010001ffff0000, 0x01010001ff00ff00, + 0x01010001ff000001, 0x01010001ff000101, 0x01010001ff01ff00, 0x01010001ff010000, + 0x0101000100ff00ff, 0x0101000100ff0001, 0x0101000100ff0101, 0x010100010000ff01, + 0x0101000100000000, 0x0101000100000001, 0x01010001000001ff, 0x010100010001ffff, + 0x010100010001ff01, 0x0101000101ff0001, 0x010100010100ffff, 0x0101000101000000, + 0x0101000101000001, 0x0101000101000100, 0x010100010101ff00, 0x01010001010100ff, + 0x0101000101010001, 0x010101ffffffffff, 0x010101ffffffff01, 0x010101ffffff01ff, + 0x010101ffffff0101, 0x010101ffff01ffff, 0x010101ffff01ff01, 0x010101ffff0101ff, + 0x010101ffff010101, 0x010101ff0000ff00, 0x010101ff000000ff, 0x010101ff00000001, + 0x010101ff00000100, 0x010101ff01ffffff, 0x010101ff01ffff01, 0x010101ff01ff01ff, + 0x010101ff01ff0101, 0x010101ff01000000, 0x010101ff0101ffff, 0x010101ff0101ff01, + 0x010101ff010101ff, 0x010101ff01010101, 0x01010100ffff0000, 0x01010100ff0000ff, + 0x01010100ff000100, 0x01010100ff01ff00, 0x01010100ff010000, 0x0101010000ffff00, + 0x010101000000ffff, 0x0101010000000000, 0x0101010000000101, 0x010101000001ff00, + 0x0101010000010001, 0x0101010000010100, 0x010101000100ffff, 0x0101010001000001, + 0x01010101ffffffff, 0x01010101ffffff01, 0x01010101ffff01ff, 0x01010101ffff0101, + 0x01010101ff01ffff, 0x01010101ff01ff01, 0x01010101ff0101ff, 0x01010101ff010101, + 0x010101010000ff00, 0x01010101000000ff, 0x0101010100000001, 0x0101010101ffffff, + 0x0101010101ffff01, 0x0101010101ff01ff, 0x0101010101ff0101, 0x0101010101000000, + 0x010101010101ffff, 0x010101010101ff01, 0x01010101010101ff, 0x0101010101010101, +GGML_TABLE_END() +#else +GGML_TABLE_BEGIN(uint32_t, iq1s_grid_gpu, NGRID_IQ1S) + 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, + 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, + 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, + 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, + 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, + 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, + 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, + 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, + 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, + 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, + 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, + 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, + 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, + 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, + 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, + 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, + 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, + 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, + 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, + 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, + 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, + 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, + 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, + 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, + 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, + 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, + 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, + 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, + 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, + 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, + 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, + 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, + 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, + 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, + 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, + 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, + 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, + 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, + 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, + 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, + 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, + 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, + 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, + 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, + 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, + 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, + 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, + 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, + 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, + 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, + 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, + 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, + 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, + 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, + 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, + 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, + 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, + 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, + 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, + 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, + 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, + 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, + 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, + 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, + 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, + 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, + 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, + 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, + 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, + 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, + 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, + 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, + 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, + 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, + 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, + 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, + 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, + 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, + 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, + 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, + 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, + 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, + 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, + 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, + 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, + 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, + 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, + 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, + 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, + 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, + 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, + 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, + 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, + 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, + 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, + 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, + 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, + 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, + 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, + 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, + 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, + 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, + 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, + 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, + 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, + 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, + 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, + 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, + 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, + 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, + 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, + 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, + 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, + 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, + 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, + 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, + 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, + 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, + 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, + 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, + 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, + 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, + 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, + 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, + 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, + 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, + 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, + 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, + 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, + 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, + 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, + 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, + 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, + 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, + 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, + 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, + 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, + 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, + 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, + 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, + 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, + 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, + 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, + 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, + 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, + 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, + 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, + 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, + 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, + 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, + 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, + 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, + 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, + 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, + 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, + 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, + 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, + 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, + 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, + 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, + 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, + 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, + 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, + 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, + 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, + 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, + 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, + 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, + 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, + 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, + 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, + 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, + 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, + 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, + 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, + 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, + 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, + 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, + 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, + 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, + 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, + 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, + 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, + 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, + 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, + 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, + 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, + 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, + 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, + 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, + 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, + 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, + 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, + 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, + 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, + 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, + 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, + 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, + 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, + 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, + 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, + 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, + 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, + 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, + 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, + 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, + 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, + 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, + 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, + 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, + 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, + 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, + 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, + 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, + 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, + 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, + 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, + 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, + 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, + 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, + 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, + 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, + 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, + 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, + 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, + 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, + 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, + 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, + 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, + 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, + 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, + 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, + 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, + 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, + 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, + 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, + 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, + 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, + 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, + 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, + 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, + 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, + 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, + 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, + 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, + 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, + 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, + 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, + 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, + 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, + 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, + 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, + 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, + 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, + 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, + 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, +GGML_TABLE_END() +#endif + +#endif // GGML_COMMON_IMPL +#endif // GGML_COMMON_IMPL diff --git a/control-plane/third_party/ggml/ggml-cpu.h b/control-plane/third_party/ggml/ggml-cpu.h new file mode 100644 index 00000000..dc6453c6 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-cpu.h @@ -0,0 +1,152 @@ +#pragma once + +#include "ggml.h" +#include "ggml-backend.h" + +#ifdef __cplusplus +extern "C" { +#endif + + // the compute plan that needs to be prepared for ggml_graph_compute() + // since https://github.com/ggml-org/ggml/issues/287 + struct ggml_cplan { + size_t work_size; // size of work buffer, calculated by `ggml_graph_plan()` + uint8_t * work_data; // work buffer, to be allocated by caller before calling to `ggml_graph_compute()` + + int n_threads; + struct ggml_threadpool * threadpool; + + // abort ggml_graph_compute when true + ggml_abort_callback abort_callback; + void * abort_callback_data; + + // use only reference implementations + bool use_ref; + }; + + // numa strategies + enum ggml_numa_strategy { + GGML_NUMA_STRATEGY_DISABLED = 0, + GGML_NUMA_STRATEGY_DISTRIBUTE = 1, + GGML_NUMA_STRATEGY_ISOLATE = 2, + GGML_NUMA_STRATEGY_NUMACTL = 3, + GGML_NUMA_STRATEGY_MIRROR = 4, + GGML_NUMA_STRATEGY_COUNT + }; + + GGML_BACKEND_API void ggml_numa_init(enum ggml_numa_strategy numa); // call once for better performance on NUMA systems + GGML_BACKEND_API bool ggml_is_numa(void); // true if init detected that system has >1 NUMA node + + GGML_BACKEND_API struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value); + GGML_BACKEND_API struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value); + + GGML_BACKEND_API struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value); + GGML_BACKEND_API struct ggml_tensor * ggml_set_f32 (struct ggml_tensor * tensor, float value); + + GGML_BACKEND_API int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i); + GGML_BACKEND_API void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value); + + GGML_BACKEND_API int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3); + GGML_BACKEND_API void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value); + + GGML_BACKEND_API float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i); + GGML_BACKEND_API void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value); + + GGML_BACKEND_API float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3); + GGML_BACKEND_API void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value); + + GGML_BACKEND_API struct ggml_threadpool * ggml_threadpool_new (struct ggml_threadpool_params * params); + GGML_BACKEND_API void ggml_threadpool_free (struct ggml_threadpool * threadpool); + GGML_BACKEND_API int ggml_threadpool_get_n_threads (struct ggml_threadpool * threadpool); + GGML_BACKEND_API void ggml_threadpool_pause (struct ggml_threadpool * threadpool); + GGML_BACKEND_API void ggml_threadpool_resume (struct ggml_threadpool * threadpool); + + // ggml_graph_plan() has to be called before ggml_graph_compute() + // when plan.work_size > 0, caller must allocate memory for plan.work_data + GGML_BACKEND_API struct ggml_cplan ggml_graph_plan( + const struct ggml_cgraph * cgraph, + int n_threads, /* = GGML_DEFAULT_N_THREADS */ + struct ggml_threadpool * threadpool /* = NULL */ ); + GGML_BACKEND_API enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan); + + // same as ggml_graph_compute() but the work data is allocated as a part of the context + // note: the drawback of this API is that you must have ensured that the context has enough memory for the work data + GGML_BACKEND_API enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads); + + // + // system info + // + + // x86 + GGML_BACKEND_API int ggml_cpu_has_sse3 (void); + GGML_BACKEND_API int ggml_cpu_has_ssse3 (void); + GGML_BACKEND_API int ggml_cpu_has_avx (void); + GGML_BACKEND_API int ggml_cpu_has_avx_vnni (void); + GGML_BACKEND_API int ggml_cpu_has_avx2 (void); + GGML_BACKEND_API int ggml_cpu_has_bmi2 (void); + GGML_BACKEND_API int ggml_cpu_has_f16c (void); + GGML_BACKEND_API int ggml_cpu_has_fma (void); + GGML_BACKEND_API int ggml_cpu_has_avx512 (void); + GGML_BACKEND_API int ggml_cpu_has_avx512_vbmi(void); + GGML_BACKEND_API int ggml_cpu_has_avx512_vnni(void); + GGML_BACKEND_API int ggml_cpu_has_avx512_bf16(void); + GGML_BACKEND_API int ggml_cpu_has_amx_int8 (void); + // ARM + GGML_BACKEND_API int ggml_cpu_has_neon (void); + GGML_BACKEND_API int ggml_cpu_has_arm_fma (void); + GGML_BACKEND_API int ggml_cpu_has_fp16_va (void); + GGML_BACKEND_API int ggml_cpu_has_dotprod (void); + GGML_BACKEND_API int ggml_cpu_has_matmul_int8(void); + GGML_BACKEND_API int ggml_cpu_has_sve (void); + GGML_BACKEND_API int ggml_cpu_get_sve_cnt (void); // sve vector length in bytes + GGML_BACKEND_API int ggml_cpu_has_sme (void); + GGML_BACKEND_API int ggml_cpu_has_sme2 (void); + // other + GGML_BACKEND_API int ggml_cpu_has_riscv_v (void); + GGML_BACKEND_API int ggml_cpu_get_rvv_vlen (void); // risc-v vector length in bytes + GGML_BACKEND_API int ggml_cpu_has_vsx (void); + GGML_BACKEND_API int ggml_cpu_has_vxe (void); + GGML_BACKEND_API int ggml_cpu_has_wasm_simd (void); + GGML_BACKEND_API int ggml_cpu_has_llamafile (void); + + // Internal types and functions exposed for tests and benchmarks + + typedef void (*ggml_vec_dot_t) (int n, float * GGML_RESTRICT s, size_t bs, const void * GGML_RESTRICT x, size_t bx, + const void * GGML_RESTRICT y, size_t by, int nrc); + + struct ggml_type_traits_cpu { + ggml_from_float_t from_float; + ggml_vec_dot_t vec_dot; + enum ggml_type vec_dot_type; + int64_t nrows; // number of rows to process simultaneously + }; + + GGML_BACKEND_API const struct ggml_type_traits_cpu * ggml_get_type_traits_cpu(enum ggml_type type); + + GGML_BACKEND_API void ggml_cpu_init(void); + + // + // CPU backend + // + + GGML_BACKEND_API ggml_backend_t ggml_backend_cpu_init(void); + + GGML_BACKEND_API bool ggml_backend_is_cpu (ggml_backend_t backend); + GGML_BACKEND_API void ggml_backend_cpu_set_n_threads (ggml_backend_t backend_cpu, int n_threads); + GGML_BACKEND_API void ggml_backend_cpu_set_threadpool (ggml_backend_t backend_cpu, ggml_threadpool_t threadpool); + GGML_BACKEND_API void ggml_backend_cpu_set_abort_callback(ggml_backend_t backend_cpu, ggml_abort_callback abort_callback, void * abort_callback_data); + + GGML_BACKEND_API void ggml_backend_cpu_set_use_ref(ggml_backend_t backend_cpu, bool use_ref); + + GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cpu_reg(void); + + GGML_BACKEND_API void ggml_cpu_fp32_to_fp32(const float *, float *, int64_t); + GGML_BACKEND_API void ggml_cpu_fp32_to_i32 (const float *, int32_t *, int64_t); + GGML_BACKEND_API void ggml_cpu_fp32_to_fp16(const float *, ggml_fp16_t *, int64_t); + GGML_BACKEND_API void ggml_cpu_fp16_to_fp32(const ggml_fp16_t *, float *, int64_t); + GGML_BACKEND_API void ggml_cpu_fp32_to_bf16(const float *, ggml_bf16_t *, int64_t); + GGML_BACKEND_API void ggml_cpu_bf16_to_fp32(const ggml_bf16_t *, float *, int64_t); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/ggml-cpu/ggml-cpu-impl.h b/control-plane/third_party/ggml/ggml-cpu/ggml-cpu-impl.h new file mode 100644 index 00000000..5dd9ec8e --- /dev/null +++ b/control-plane/third_party/ggml/ggml-cpu/ggml-cpu-impl.h @@ -0,0 +1,539 @@ +#pragma once + +// GGML CPU internal header + +#include "ggml.h" +#include "ggml-impl.h" + +#include // load `stdlib.h` before other headers to work around MinGW bug: https://sourceforge.net/p/mingw-w64/bugs/192/ +//#include +#include +#include // memcpy +#include // fabsf + +#ifdef __cplusplus +extern "C" { +#endif + +struct ggml_compute_params { + // ith = thread index, nth = number of threads + int ith, nth; + + // work buffer for all threads + size_t wsize; + void * wdata; + + struct ggml_threadpool * threadpool; + + // use reference implementation + bool use_ref; +}; + + +#if defined(_MSC_VER) + +#define m512bh(p) p +#define m512i(p) p + +#else + +#define m512bh(p) (__m512bh)(p) +#define m512i(p) (__m512i)(p) + +#endif + +// __FMA__ and __F16C__ are not defined in MSVC, however they are implied with AVX2/AVX512 +#if defined(_MSC_VER) && (defined(__AVX2__) || defined(__AVX512F__)) +#ifndef __FMA__ +#define __FMA__ +#endif +#ifndef __F16C__ +#define __F16C__ +#endif +#endif + +// __SSE3__ and __SSSE3__ are not defined in MSVC, but SSE3/SSSE3 are present when AVX/AVX2/AVX512 are available +#if defined(_MSC_VER) && (defined(__AVX__) || defined(__AVX2__) || defined(__AVX512F__)) +#ifndef __SSE3__ +#define __SSE3__ +#endif +#ifndef __SSSE3__ +#define __SSSE3__ +#endif +#endif + +#if defined(__s390x__) && defined(__VEC__) +#ifndef __VXE__ +#define __VXE__ +#endif // __VXE__ +#ifndef __VXE2__ +#define __VXE2__ +#endif // __VXE2__ +#endif // __s390x__ && __VEC__ + +#if defined(__ARM_FEATURE_SVE) && defined(__linux__) +#include +#endif + +#if defined(__ARM_NEON) + +// ref: https://github.com/ggml-org/llama.cpp/pull/5404 +#if defined(_MSC_VER) && !defined(__clang__) +#define ggml_vld1q_u32(w,x,y,z) { ((w) + ((uint64_t)(x) << 32)), ((y) + ((uint64_t)(z) << 32)) } +#else +#define ggml_vld1q_u32(w,x,y,z) { (w), (x), (y), (z) } +#endif // _MSC_VER + +#if !defined(__aarch64__) + +// 32-bit ARM compatibility + +// vaddlvq_s16 +// vpaddq_s16 +// vpaddq_s32 +// vaddvq_s32 +// vaddvq_f32 +// vmaxvq_f32 +// vcvtnq_s32_f32 +// vzip1_u8 +// vzip2_u8 + +inline static int32_t vaddlvq_s16(int16x8_t v) { + int32x4_t v0 = vreinterpretq_s32_s64(vpaddlq_s32(vpaddlq_s16(v))); + return vgetq_lane_s32(v0, 0) + vgetq_lane_s32(v0, 2); +} + +inline static int16x8_t vpaddq_s16(int16x8_t a, int16x8_t b) { + int16x4_t a0 = vpadd_s16(vget_low_s16(a), vget_high_s16(a)); + int16x4_t b0 = vpadd_s16(vget_low_s16(b), vget_high_s16(b)); + return vcombine_s16(a0, b0); +} + +inline static int32x4_t vpaddq_s32(int32x4_t a, int32x4_t b) { + int32x2_t a0 = vpadd_s32(vget_low_s32(a), vget_high_s32(a)); + int32x2_t b0 = vpadd_s32(vget_low_s32(b), vget_high_s32(b)); + return vcombine_s32(a0, b0); +} + +inline static int32_t vaddvq_s32(int32x4_t v) { + return vgetq_lane_s32(v, 0) + vgetq_lane_s32(v, 1) + vgetq_lane_s32(v, 2) + vgetq_lane_s32(v, 3); +} + +inline static float vaddvq_f32(float32x4_t v) { + return vgetq_lane_f32(v, 0) + vgetq_lane_f32(v, 1) + vgetq_lane_f32(v, 2) + vgetq_lane_f32(v, 3); +} + +inline static float vmaxvq_f32(float32x4_t v) { + return + MAX(MAX(vgetq_lane_f32(v, 0), vgetq_lane_f32(v, 1)), + MAX(vgetq_lane_f32(v, 2), vgetq_lane_f32(v, 3))); +} + +inline static int32x4_t vcvtnq_s32_f32(float32x4_t v) { + int32x4_t res; + + res[0] = roundf(vgetq_lane_f32(v, 0)); + res[1] = roundf(vgetq_lane_f32(v, 1)); + res[2] = roundf(vgetq_lane_f32(v, 2)); + res[3] = roundf(vgetq_lane_f32(v, 3)); + + return res; +} + +inline static uint8x8_t vzip1_u8(uint8x8_t a, uint8x8_t b) { + uint8x8_t res; + + res[0] = a[0]; res[1] = b[0]; + res[2] = a[1]; res[3] = b[1]; + res[4] = a[2]; res[5] = b[2]; + res[6] = a[3]; res[7] = b[3]; + + return res; +} + +inline static uint8x8_t vzip2_u8(uint8x8_t a, uint8x8_t b) { + uint8x8_t res; + + res[0] = a[4]; res[1] = b[4]; + res[2] = a[5]; res[3] = b[5]; + res[4] = a[6]; res[5] = b[6]; + res[6] = a[7]; res[7] = b[7]; + + return res; +} + +// vld1q_s16_x2 +// vld1q_u8_x2 +// vld1q_u8_x4 +// vld1q_s8_x2 +// vld1q_s8_x4 +// TODO: double-check these work correctly + +typedef struct ggml_int16x8x2_t { + int16x8_t val[2]; +} ggml_int16x8x2_t; + +inline static ggml_int16x8x2_t ggml_vld1q_s16_x2(const int16_t * ptr) { + ggml_int16x8x2_t res; + + res.val[0] = vld1q_s16(ptr + 0); + res.val[1] = vld1q_s16(ptr + 8); + + return res; +} + +typedef struct ggml_uint8x16x2_t { + uint8x16_t val[2]; +} ggml_uint8x16x2_t; + +inline static ggml_uint8x16x2_t ggml_vld1q_u8_x2(const uint8_t * ptr) { + ggml_uint8x16x2_t res; + + res.val[0] = vld1q_u8(ptr + 0); + res.val[1] = vld1q_u8(ptr + 16); + + return res; +} + +typedef struct ggml_uint8x16x4_t { + uint8x16_t val[4]; +} ggml_uint8x16x4_t; + +inline static ggml_uint8x16x4_t ggml_vld1q_u8_x4(const uint8_t * ptr) { + ggml_uint8x16x4_t res; + + res.val[0] = vld1q_u8(ptr + 0); + res.val[1] = vld1q_u8(ptr + 16); + res.val[2] = vld1q_u8(ptr + 32); + res.val[3] = vld1q_u8(ptr + 48); + + return res; +} + +typedef struct ggml_int8x16x2_t { + int8x16_t val[2]; +} ggml_int8x16x2_t; + +inline static ggml_int8x16x2_t ggml_vld1q_s8_x2(const int8_t * ptr) { + ggml_int8x16x2_t res; + + res.val[0] = vld1q_s8(ptr + 0); + res.val[1] = vld1q_s8(ptr + 16); + + return res; +} + +typedef struct ggml_int8x16x4_t { + int8x16_t val[4]; +} ggml_int8x16x4_t; + +inline static ggml_int8x16x4_t ggml_vld1q_s8_x4(const int8_t * ptr) { + ggml_int8x16x4_t res; + + res.val[0] = vld1q_s8(ptr + 0); + res.val[1] = vld1q_s8(ptr + 16); + res.val[2] = vld1q_s8(ptr + 32); + res.val[3] = vld1q_s8(ptr + 48); + + return res; +} + +// NOTE: not tested +inline static int8x16_t ggml_vqtbl1q_s8(int8x16_t a, uint8x16_t b) { + int8x16_t res; + + res[ 0] = a[b[ 0]]; + res[ 1] = a[b[ 1]]; + res[ 2] = a[b[ 2]]; + res[ 3] = a[b[ 3]]; + res[ 4] = a[b[ 4]]; + res[ 5] = a[b[ 5]]; + res[ 6] = a[b[ 6]]; + res[ 7] = a[b[ 7]]; + res[ 8] = a[b[ 8]]; + res[ 9] = a[b[ 9]]; + res[10] = a[b[10]]; + res[11] = a[b[11]]; + res[12] = a[b[12]]; + res[13] = a[b[13]]; + res[14] = a[b[14]]; + res[15] = a[b[15]]; + + return res; +} + +// NOTE: not tested +inline static uint8x16_t ggml_vqtbl1q_u8(uint8x16_t a, uint8x16_t b) { + uint8x16_t res; + + res[ 0] = a[b[ 0]]; + res[ 1] = a[b[ 1]]; + res[ 2] = a[b[ 2]]; + res[ 3] = a[b[ 3]]; + res[ 4] = a[b[ 4]]; + res[ 5] = a[b[ 5]]; + res[ 6] = a[b[ 6]]; + res[ 7] = a[b[ 7]]; + res[ 8] = a[b[ 8]]; + res[ 9] = a[b[ 9]]; + res[10] = a[b[10]]; + res[11] = a[b[11]]; + res[12] = a[b[12]]; + res[13] = a[b[13]]; + res[14] = a[b[14]]; + res[15] = a[b[15]]; + + return res; +} + +#else + +#define ggml_int16x8x2_t int16x8x2_t +#define ggml_uint8x16x2_t uint8x16x2_t +#define ggml_uint8x16x4_t uint8x16x4_t +#define ggml_int8x16x2_t int8x16x2_t +#define ggml_int8x16x4_t int8x16x4_t + +#define ggml_vld1q_s16_x2 vld1q_s16_x2 +#define ggml_vld1q_u8_x2 vld1q_u8_x2 +#define ggml_vld1q_u8_x4 vld1q_u8_x4 +#define ggml_vld1q_s8_x2 vld1q_s8_x2 +#define ggml_vld1q_s8_x4 vld1q_s8_x4 +#define ggml_vqtbl1q_s8 vqtbl1q_s8 +#define ggml_vqtbl1q_u8 vqtbl1q_u8 + +#endif // !defined(__aarch64__) + +#if !defined(__ARM_FEATURE_DOTPROD) + +// NOTE: this fallback produces the same total sum as native vdotq_s32 but with different per-lane grouping — do not use when individual lane values matter. +inline static int32x4_t ggml_vdotq_s32(int32x4_t acc, int8x16_t a, int8x16_t b) { + const int16x8_t p0 = vmull_s8(vget_low_s8 (a), vget_low_s8 (b)); + const int16x8_t p1 = vmull_s8(vget_high_s8(a), vget_high_s8(b)); + + return vaddq_s32(acc, vaddq_s32(vpaddlq_s16(p0), vpaddlq_s16(p1))); +} + +#else + +#define ggml_vdotq_s32(a, b, c) vdotq_s32(a, b, c) + +#endif // !defined(__ARM_FEATURE_DOTPROD) + +static inline int32x4_t ggml_nvfp4_dot8(const int8x8_t q4_lo, const int8x8_t q8_lo, + const int8x8_t q4_hi, const int8x8_t q8_hi) { + const int16x8_t p_lo = vmull_s8(q4_lo, q8_lo); + const int16x8_t p_hi = vmull_s8(q4_hi, q8_hi); + const int32x4_t sum_lo = vpaddlq_s16(p_lo); + const int32x4_t sum_hi = vpaddlq_s16(p_hi); + return vaddq_s32(sum_lo, sum_hi); +} + +#endif // defined(__ARM_NEON) + +#ifdef __wasm_simd128__ +#include +#endif + +#ifdef __POWER9_VECTOR__ +#include +#endif + +#if defined(_MSC_VER) || defined(__MINGW32__) +#include +#elif defined(__SSE__) || defined(__SSE3__) || defined(__SSSE3__) || defined(__AVX__) || defined(__F16C__) || defined(__AVX2__) || defined(__AVX512F__) || defined(__AVX512BF16__) +#include +#endif + +#ifdef __riscv_v_intrinsic +#include +#endif + +#if defined(__loongarch64) +#if defined(__loongarch_asx) +#include +#endif +#if defined(__loongarch_sx) +#include +#endif +#endif + +#if defined(__VXE__) || defined(__VXE2__) +#include + +#define vec_neg(a) (-(a)) // Vector Negate +#define vec_add(a, b) ((a) + (b)) // Vector Add +#define vec_sub(a, b) ((a) - (b)) // Vector Subtract +#define vec_mul(a, b) ((a) * (b)) // Vector Multiply +#define vec_div(a, b) ((a) / (b)) // Vector Divide +#define vec_sl(a, b) ((a) << (b)) // Vector Shift Left +#define vec_sra(a, b) ((a) >> (b)) // Vector Shift Right +#define vec_sr(a, b) ((a) >> (b)) // Vector Shift Right Algebraic +#define vec_slo(a, b) vec_slb(a, (b) << 64) // Vector Shift Left by Octet +#define vec_sro(a, b) vec_srb(a, (b) << 64) // Vector Shift Right by Octet + +#ifndef vec_and +#define vec_and(a, b) ((a) & (b)) // Vector AND +#endif + +#ifndef vec_or +#define vec_or(a, b) ((a) | (b)) // Vector OR +#endif + +#ifndef vec_xor +#define vec_xor(a, b) ((a) ^ (b)) // Vector XOR +#endif + +typedef signed char char8x16_t __attribute__((vector_size(16))); +typedef unsigned char uchar8x16_t __attribute__((vector_size(16))); + +typedef int8_t int8x16_t __attribute__((vector_size(16))); +typedef int16_t int16x8_t __attribute__((vector_size(16))); +typedef int32_t int32x4_t __attribute__((vector_size(16))); + +typedef uint8_t uint8x16_t __attribute__((vector_size(16))); +typedef uint16_t uint16x8_t __attribute__((vector_size(16))); +typedef uint32_t uint32x4_t __attribute__((vector_size(16))); + +typedef float float32x4_t __attribute__((vector_size(16))); +typedef double double64x2_t __attribute__((vector_size(16))); + +typedef signed long long long64x2_t __attribute__((vector_size(16))); +typedef unsigned long long ulong64x2_t __attribute__((vector_size(16))); + +typedef struct ggml_uint8x16x2_t { + uint8x16_t val[2]; +} ggml_uint8x16x2_t; + +inline static ggml_uint8x16x2_t ggml_vec_xl_u8x2(const uint8_t * ptr) { + ggml_uint8x16x2_t res; + + res.val[0] = vec_xl( 0, ptr); + res.val[1] = vec_xl(16, ptr); + + return res; +} + +typedef struct ggml_uint8x16x4_t { + uint8x16_t val[4]; +} ggml_uint8x16x4_t; + +inline static ggml_uint8x16x4_t ggml_vec_xl_u8x4(const uint8_t * ptr) { + ggml_uint8x16x4_t res; + + res.val[0] = vec_xl( 0, ptr); + res.val[1] = vec_xl(16, ptr); + res.val[2] = vec_xl(32, ptr); + res.val[3] = vec_xl(48, ptr); + + return res; +} + +typedef struct ggml_int8x16x4_t { + int8x16_t val[4]; +} ggml_int8x16x4_t; + +inline static ggml_int8x16x4_t ggml_vec_xl_s8x4(const int8_t * ptr) { + ggml_int8x16x4_t res; + + res.val[0] = vec_xl( 0, ptr); + res.val[1] = vec_xl(16, ptr); + res.val[2] = vec_xl(32, ptr); + res.val[3] = vec_xl(48, ptr); + + return res; +} + +typedef struct ggml_int16x8x2_t { + int16x8_t val[2]; +} ggml_int16x8x2_t; + +inline static ggml_int16x8x2_t ggml_vec_xl_s16x2(const int16_t * ptr) { + ggml_int16x8x2_t res; + + res.val[0] = vec_xl( 0, ptr); + res.val[1] = vec_xl(16, ptr); + + return res; +} + +/* + ! WARNING: Very slow. Use vec_perm if possible. Refer to iq4_xs + ! or iq4_nl for example implementation. +*/ +inline static int8x16_t ggml_vec_tbl(int8x16_t a, uint8x16_t b) { + int8x16_t res; + + res[ 0] = a[b[ 0]]; + res[ 1] = a[b[ 1]]; + res[ 2] = a[b[ 2]]; + res[ 3] = a[b[ 3]]; + res[ 4] = a[b[ 4]]; + res[ 5] = a[b[ 5]]; + res[ 6] = a[b[ 6]]; + res[ 7] = a[b[ 7]]; + res[ 8] = a[b[ 8]]; + res[ 9] = a[b[ 9]]; + res[10] = a[b[10]]; + res[11] = a[b[11]]; + res[12] = a[b[12]]; + res[13] = a[b[13]]; + res[14] = a[b[14]]; + res[15] = a[b[15]]; + + return res; +} + +inline static int16x8_t vec_padd_s16(int16x8_t a, int16x8_t b) { + const uchar8x16_t v_maske = { 0, 1, 4, 5, 8, 9, 12, 13, + 16, 17, 20, 21, 24, 25, 28, 29 }; + + const int16x8_t v_abo = vec_pack((int32x4_t)a, (int32x4_t)b); + const int16x8_t v_abe = vec_perm(a, b, v_maske); + return v_abo + v_abe; +} + +/** + * @see https://github.com/ggml-org/llama.cpp/pull/14037 + */ +inline static float vec_hsum_f32x4(float32x4_t v) { + float32x4_t v_temp = v + vec_reve(v); + return v_temp[0] + v_temp[1]; +} + +inline static int32_t vec_hsum_i32x4(int32x4_t v) { + int32x4_t v_temp = v + vec_reve(v); + return v_temp[0] + v_temp[1]; +} + +inline static int32x4_t ggml_vec_dot(int32x4_t acc, int8x16_t a, int8x16_t b) { + const int16x8_t p = vec_mule(a, b) + vec_mulo(a, b); + return acc + (vec_unpackh(p) + vec_unpackl(p)); +} + +#endif + +#if defined(__loongarch_sx) +/* float type data load instructions */ +static __m128 __lsx_vreplfr2vr_s(const float val) { + v4f32 res = {val, val, val, val}; + return (__m128)res; +} +#endif + +#if defined(__loongarch_asx) +static __m256 __lasx_xvreplfr2vr_s(const float val) { + v8f32 res = {val, val, val, val, val, val, val, val}; + return (__m256)res; +} +#endif + +// TODO: move to ggml-threading +void ggml_barrier(struct ggml_threadpool * tp); + +void ggml_threadpool_chunk_set(struct ggml_threadpool * tp, int value); +int ggml_threadpool_chunk_add(struct ggml_threadpool * tp, int value); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/ggml-impl.h b/control-plane/third_party/ggml/ggml-impl.h new file mode 100644 index 00000000..ae26e0c2 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-impl.h @@ -0,0 +1,795 @@ +#pragma once + +// GGML internal header + +#include "ggml.h" +#include "gguf.h" + +#include +#include +#include // load `stdlib.h` before other headers to work around MinGW bug: https://sourceforge.net/p/mingw-w64/bugs/192/ +#include +#include +#include + +#ifdef __ARM_FEATURE_SVE +#include +#endif // __ARM_FEATURE_SVE + +#if defined(__ARM_NEON) && !defined(__CUDACC__) && !defined(__MUSACC__) +// if YCM cannot find , make a symbolic link to it, for example: +// +// $ ln -sfn /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include/arm_neon.h ./src/ +// +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +void ggml_print_backtrace(void); + +uint64_t ggml_graph_next_uid(void); + +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef MAX +# define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif + +// required for mmap as gguf only guarantees 32-byte alignment +#define TENSOR_ALIGNMENT 32 + +// static_assert should be a #define, but if it's not, +// fall back to the _Static_assert C11 keyword. +// if C99 - static_assert is noop +// ref: https://stackoverflow.com/a/53923785/4039976 +#ifndef __cplusplus + #ifndef static_assert + #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L) + #define static_assert(cond, msg) _Static_assert(cond, msg) + #else + #define static_assert(cond, msg) struct global_scope_noop_trick + #endif + #endif +#endif + +static inline int ggml_up32(int n) { + return (n + 31) & ~31; +} + +//static inline int ggml_up64(int n) { +// return (n + 63) & ~63; +//} + +static inline int ggml_up(int n, int m) { + // assert m is a power of 2 + GGML_ASSERT((m & (m - 1)) == 0); + return (n + m - 1) & ~(m - 1); +} + +// TODO: move to ggml.h? (won't be able to inline) +static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) { + if (a->type != b->type) { + return false; + } + for (int i = 0; i < GGML_MAX_DIMS; i++) { + if (a->ne[i] != b->ne[i]) { + return false; + } + if (a->nb[i] != b->nb[i]) { + return false; + } + } + return true; +} + +static bool ggml_op_is_empty(enum ggml_op op) { + switch (op) { + case GGML_OP_NONE: + case GGML_OP_RESHAPE: + case GGML_OP_TRANSPOSE: + case GGML_OP_VIEW: + case GGML_OP_PERMUTE: + return true; + default: + return false; + } +} + +static inline bool ggml_impl_is_view(const struct ggml_tensor * t) { + return t->view_src != NULL; +} + +static inline float ggml_compute_softplus_f32(float input) { + return (input > 20.0f) ? input : logf(1 + expf(input)); +} +// +// logging +// + +GGML_ATTRIBUTE_FORMAT(2, 3) +GGML_API void ggml_log_internal (enum ggml_log_level level, const char * format, ...); +GGML_API void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data); + +#define GGML_LOG(...) ggml_log_internal(GGML_LOG_LEVEL_NONE , __VA_ARGS__) +#define GGML_LOG_INFO(...) ggml_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__) +#define GGML_LOG_WARN(...) ggml_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__) +#define GGML_LOG_ERROR(...) ggml_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__) +#define GGML_LOG_DEBUG(...) ggml_log_internal(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__) +#define GGML_LOG_CONT(...) ggml_log_internal(GGML_LOG_LEVEL_CONT , __VA_ARGS__) + +#define GGML_DEBUG 0 + +#if (GGML_DEBUG >= 1) +#define GGML_PRINT_DEBUG(...) GGML_LOG_DEBUG(__VA_ARGS__) +#else +#define GGML_PRINT_DEBUG(...) +#endif + +#if (GGML_DEBUG >= 5) +#define GGML_PRINT_DEBUG_5(...) GGML_LOG_DEBUG(__VA_ARGS__) +#else +#define GGML_PRINT_DEBUG_5(...) +#endif + +#if (GGML_DEBUG >= 10) +#define GGML_PRINT_DEBUG_10(...) GGML_LOG_DEBUG(__VA_ARGS__) +#else +#define GGML_PRINT_DEBUG_10(...) +#endif + +// tensor params + +static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) { + GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings + assert(params_size <= GGML_MAX_OP_PARAMS); + memcpy(tensor->op_params, params, params_size); +} + +static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) { + assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t)); + return ((const int32_t *)(tensor->op_params))[i]; +} + +static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) { + assert(i < GGML_MAX_OP_PARAMS / sizeof(float)); + return ((const float *)(tensor->op_params))[i]; +} + +// [TAG_GGML_PREC] +// - GGML_OP_MUL_MAT +// 0 - acc +// 1 - hint +// 2 - src0 precision +// 3 - src1 precision +// +// - GGML_OP_MUL_MAT_ID +// 0 - acc +// 1 - hint +// 2 - src0 precision +// 3 - src1 precision +static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) { + assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t)); + ((int32_t *)(tensor->op_params))[i] = value; +} + +static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) { + assert(i < GGML_MAX_OP_PARAMS / sizeof(float)); + ((float *)(tensor->op_params))[i] = value; +} + +struct ggml_map_custom1_op_params { + ggml_custom1_op_t fun; + int n_tasks; + void * userdata; +}; + +struct ggml_map_custom2_op_params { + ggml_custom2_op_t fun; + int n_tasks; + void * userdata; +}; + +struct ggml_map_custom3_op_params { + ggml_custom3_op_t fun; + int n_tasks; + void * userdata; +}; + +struct ggml_custom_op_params { + ggml_custom_op_t fun; + int n_tasks; + void * userdata; +}; + +// bitset + +typedef uint32_t ggml_bitset_t; + +static_assert(sizeof(ggml_bitset_t) == 4, "bitset_t constants must be updated"); +#define BITSET_SHR 5 // log2(sizeof(ggml_bitset_t)*8) +#define BITSET_MASK (sizeof(ggml_bitset_t)*8 - 1) + +static size_t ggml_bitset_size(size_t n) { + return (n + BITSET_MASK) >> BITSET_SHR; +} + +static inline bool ggml_bitset_get(const ggml_bitset_t * bitset, size_t i) { + return !!(bitset[i >> BITSET_SHR] & (1u << (i & BITSET_MASK))); +} + +static inline void ggml_bitset_set(ggml_bitset_t * bitset, size_t i) { + bitset[i >> BITSET_SHR] |= (1u << (i & BITSET_MASK)); +} + +static inline void ggml_bitset_clear(ggml_bitset_t * bitset, size_t i) { + bitset[i >> BITSET_SHR] &= ~(1u << (i & BITSET_MASK)); +} + +// hash set + +#define GGML_HASHSET_FULL ((size_t)-1) +#define GGML_HASHSET_ALREADY_EXISTS ((size_t)-2) + +struct ggml_hash_set { + size_t size; + ggml_bitset_t * used; // whether or not the keys are in use i.e. set + struct ggml_tensor ** keys; // actual tensors in the set, keys[i] is only defined if ggml_bitset_get(used, i) +}; + +struct ggml_hash_set ggml_hash_set_new(size_t size); +void ggml_hash_set_free(struct ggml_hash_set * hash_set); + +// returns the minimum size for a hash set that can hold min_sz elements +size_t ggml_hash_size(size_t min_sz); + +// remove all elements from the hash set +void ggml_hash_set_reset(struct ggml_hash_set * hash_set); + +// returns true if key is in the hash set +static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key); + +// returns GGML_HASHSET_FULL if table is full, otherwise the current index of the key or where it should be inserted +static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key); + +// returns GGML_HASHSET_ALREADY_EXISTS if key already exists, index otherwise, asserts if table is full +static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key); + +// return index, asserts if table is full +static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key); + +// hash function for ggml_tensor +static inline size_t ggml_hash(const struct ggml_tensor * p) { + // the last 4 bits are always zero due to alignment + return (size_t)(uintptr_t)p >> 4; +} + +static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key) { + size_t h = ggml_hash(key) % hash_set->size; + + // linear probing + size_t i = h; + while (ggml_bitset_get(hash_set->used, i) && hash_set->keys[i] != key) { + i = (i + 1) % hash_set->size; + if (i == h) { + // visited all hash table entries -> not found + return GGML_HASHSET_FULL; + } + } + return i; +} + +static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key) { + size_t i = ggml_hash_find(hash_set, key); + return i != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, i); +} + +static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) { + size_t h = ggml_hash(key) % hash_set->size; + + // linear probing + size_t i = h; + do { + if (!ggml_bitset_get(hash_set->used, i)) { + ggml_bitset_set(hash_set->used, i); + hash_set->keys[i] = key; + return i; + } + if (hash_set->keys[i] == key) { + return GGML_HASHSET_ALREADY_EXISTS; + } + i = (i + 1) % hash_set->size; + } while (i != h); + + // visited all hash table entries -> not found + GGML_ABORT("fatal error"); +} + +static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) { + size_t h = ggml_hash(key) % hash_set->size; + + // linear probing + size_t i = h; + do { + if (!ggml_bitset_get(hash_set->used, i)) { + ggml_bitset_set(hash_set->used, i); + hash_set->keys[i] = key; + return i; + } + if (hash_set->keys[i] == key) { + return i; + } + i = (i + 1) % hash_set->size; + } while (i != h); + + // visited all hash table entries -> not found + GGML_ABORT("fatal error"); +} + +// computation graph + +enum ggml_cgraph_eval_order { + GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT = 0, + GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT, + GGML_CGRAPH_EVAL_ORDER_COUNT +}; + +struct ggml_cgraph { + int size; // maximum number of nodes/leafs/grads/grad_accs + int n_nodes; // number of nodes currently in use + int n_leafs; // number of leafs currently in use + + struct ggml_tensor ** nodes; // tensors with data that can change if the graph is evaluated + struct ggml_tensor ** grads; // the outputs of these tensors are the gradients of the nodes + struct ggml_tensor ** grad_accs; // accumulators for node gradients + struct ggml_tensor ** leafs; // tensors with constant data + int32_t * use_counts;// number of uses of each tensor, indexed by hash table slot + + struct ggml_hash_set visited_hash_set; + + enum ggml_cgraph_eval_order order; + + // an optional identifier that can be utilized to recognize same graphs if two non-zero values match + // a value of 0 means it is not set and should be ignored + uint64_t uid; +}; + +// returns a slice of cgraph with nodes [i0, i1) +// the slice does not have leafs or gradients +// if you need the gradients, get them from the original graph +struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph, int i0, int i1); + +// ggml-alloc.c: true if the operation can reuse memory from its sources +GGML_API bool ggml_op_can_inplace(enum ggml_op op); + + +// Memory allocation + +GGML_API void * ggml_aligned_malloc(size_t size); +GGML_API void ggml_aligned_free(void * ptr, size_t size); + +// FP16 <-> FP32 +// ref: https://github.com/Maratyszcza/FP16 + +static inline float fp32_from_bits(uint32_t w) { + union { + uint32_t as_bits; + float as_value; + } fp32; + fp32.as_bits = w; + return fp32.as_value; +} + +static inline uint32_t fp32_to_bits(float f) { + union { + float as_value; + uint32_t as_bits; + } fp32; + fp32.as_value = f; + return fp32.as_bits; +} + +static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) { + const uint32_t w = (uint32_t) h << 16; + const uint32_t sign = w & UINT32_C(0x80000000); + const uint32_t two_w = w + w; + + const uint32_t exp_offset = UINT32_C(0xE0) << 23; +#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L) + const float exp_scale = 0x1.0p-112f; +#else + const float exp_scale = fp32_from_bits(UINT32_C(0x7800000)); +#endif + const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale; + + const uint32_t magic_mask = UINT32_C(126) << 23; + const float magic_bias = 0.5f; + const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias; + + const uint32_t denormalized_cutoff = UINT32_C(1) << 27; + const uint32_t result = sign | + (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value)); + return fp32_from_bits(result); +} + +static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) { +#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L) + const float scale_to_inf = 0x1.0p+112f; + const float scale_to_zero = 0x1.0p-110f; +#else + const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000)); + const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000)); +#endif + float base = (fabsf(f) * scale_to_inf) * scale_to_zero; + + const uint32_t w = fp32_to_bits(f); + const uint32_t shl1_w = w + w; + const uint32_t sign = w & UINT32_C(0x80000000); + uint32_t bias = shl1_w & UINT32_C(0xFF000000); + if (bias < UINT32_C(0x71000000)) { + bias = UINT32_C(0x71000000); + } + + base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base; + const uint32_t bits = fp32_to_bits(base); + const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00); + const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF); + const uint32_t nonsign = exp_bits + mantissa_bits; + return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign); +} + +#define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x) +#define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x) + +#define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x) +#define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x) + +static inline float ggml_e8m0_to_fp32(uint8_t x) { + uint32_t bits; // Stores the raw bit representation of the float + + // Handle special case for minimum exponent (denormalized float) + if (x == 0) { + // Bit pattern for 2^(-127): + // - Sign bit: 0 (positive) + // - Exponent: 0 (denormalized number) + // - Mantissa: 0x400000 (0.5 in fractional form) + // Value = 0.5 * 2^(-126) = 2^(-127) + bits = 0x00400000; + } + // note: disabled as we don't need to handle NaNs + //// Handle special case for NaN (all bits set) + //else if (x == 0xFF) { + // // Standard quiet NaN pattern: + // // - Sign bit: 0 + // // - Exponent: all 1s (0xFF) + // // - Mantissa: 0x400000 (quiet NaN flag) + // bits = 0x7FC00000; + //} + // Normalized values (most common case) + else { + // Construct normalized float by shifting exponent into position: + // - Exponent field: 8 bits (positions 30-23) + // - Mantissa: 0 (implicit leading 1) + // Value = 2^(x - 127) + bits = (uint32_t) x << 23; + } + + float result; // Final float value + // Safely reinterpret bit pattern as float without type-punning issues + memcpy(&result, &bits, sizeof(float)); + return result; +} + +// Equal to ggml_e8m0_to_fp32/2 +// Useful with MXFP4 quantization since the E0M2 values are doubled +static inline float ggml_e8m0_to_fp32_half(uint8_t x) { + uint32_t bits; + + // For x < 2: use precomputed denormal patterns + if (x < 2) { + // 0x00200000 = 2^(-128), 0x00400000 = 2^(-127) + bits = 0x00200000 << x; + } + // For x >= 2: normalized exponent adjustment + else { + // 0.5 * 2^(x-127) = 2^(x-128) = normalized with exponent (x-1) + bits = (uint32_t)(x - 1) << 23; + } + // Note: NaNs are not handled here + + float result; + memcpy(&result, &bits, sizeof(float)); + return result; +} + +#define GGML_E8M0_TO_FP32(x) ggml_e8m0_to_fp32(x) +#define GGML_E8M0_TO_FP32_HALF(x) ggml_e8m0_to_fp32_half(x) + +// UE4M3: unsigned, 4 exp bits (bias=7), 3 mantissa bits +// Returns value * 0.5 to match kvalues_mxfp4 convention (kvalues = 2 * E2M1_float) +static inline float ggml_ue4m3_to_fp32(uint8_t x) { + if (x == 0 || x == 0x7F) { + return 0.0f; + } + int exp = (x >> 3) & 0xF; + int man = x & 0x7; + float raw; + if (exp == 0) { + raw = ldexpf((float) man, -9); + } else { + raw = ldexpf(1.0f + (float) man / 8.0f, exp - 7); + } + return raw * 0.5f; +} + +static inline uint8_t ggml_fp32_to_ue4m3(float x) { + if (!(x > 0.0f)) { + return 0; + } + if (x > 448.0f) { + x = 448.0f; + } + uint32_t bits; + memcpy(&bits, &x, 4); + int fp32_exp = ((bits >> 23) & 0xFF) - 127; + int fp32_man = (bits >> 20) & 0x7; + int ue4m3_exp = fp32_exp + 7; + if (ue4m3_exp <= 0) { + // subnormal: value = man * 2^-9, man = round(x * 2^9) + int man = (int) (x * 512.0f + 0.5f); + if (man > 7) { + man = 7; + } + if (man < 1) { + return 0; + } + return (uint8_t) man; + } + if (ue4m3_exp >= 15) { + return 0x7E; + } + int round_bit = (bits >> 19) & 1; + int ue4m3_man = fp32_man + round_bit; + if (ue4m3_man > 7) { + ue4m3_man = 0; + ue4m3_exp++; + if (ue4m3_exp >= 15) { + return 0x7E; + } + } + return (uint8_t) ((ue4m3_exp << 3) | ue4m3_man); +} + +/** + * Converts brain16 to float32. + * + * The bfloat16 floating point format has the following structure: + * + * ┌sign + * │ + * │ ┌exponent + * │ │ + * │ │ ┌mantissa + * │ │ │ + * │┌──┴───┐┌─┴───┐ + * 0b0000000000000000 brain16 + * + * Since bf16 has the same number of exponent bits as a 32bit float, + * encoding and decoding numbers becomes relatively straightforward. + * + * ┌sign + * │ + * │ ┌exponent + * │ │ + * │ │ ┌mantissa + * │ │ │ + * │┌──┴───┐┌─┴───────────────────┐ + * 0b00000000000000000000000000000000 IEEE binary32 + * + * For comparison, the standard fp16 format has fewer exponent bits. + * + * ┌sign + * │ + * │ ┌exponent + * │ │ + * │ │ ┌mantissa + * │ │ │ + * │┌─┴─┐┌─┴──────┐ + * 0b0000000000000000 IEEE binary16 + * + * @see IEEE 754-2008 + */ +static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) { + union { + float f; + uint32_t i; + } u; + u.i = (uint32_t)h.bits << 16; + return u.f; +} + +/** + * Converts float32 to brain16. + * + * This is binary identical with Google Brain float conversion. + * Floats shall round to nearest even, and NANs shall be quiet. + * Subnormals aren't flushed to zero, except perhaps when used. + * This code should vectorize nicely if using modern compilers. + */ +static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) { + ggml_bf16_t h; + union { + float f; + uint32_t i; + } u; + u.f = s; + if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */ + h.bits = (u.i >> 16) | 64; /* force to quiet */ + return h; + } + h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16; + return h; +} + +#define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x) +#define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x) + +static inline int32_t ggml_node_get_use_count(const struct ggml_cgraph * cgraph, int node_idx) { + const struct ggml_tensor * node = cgraph->nodes[node_idx]; + + size_t hash_pos = ggml_hash_find(&cgraph->visited_hash_set, node); + if (!ggml_bitset_get(cgraph->visited_hash_set.used, hash_pos)) { + return 0; + } + return cgraph->use_counts[hash_pos]; +} + +// return true if the node's results are only used by N other nodes +// and can be fused into their calculations. +static inline bool ggml_node_has_n_uses(const struct ggml_cgraph * cgraph, int node_idx, int32_t n_uses) { + const struct ggml_tensor * node = cgraph->nodes[node_idx]; + + // check the use count against how many we're replacing + if (ggml_node_get_use_count(cgraph, node_idx) != n_uses) { + return false; + } + + // if node is a view, some other node might be using the intermediate result + // via the view source. + if (node->view_src) { + return false; + } + + // If the user requested output for the node, can't fuse + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + return false; + } + + return true; +} + +// Returns true if nodes with indices { node_idxs } are the sequence of ggml_ops in ops[] +// and are fusable. Nodes are considered fusable according to this function if: +// - all nodes except the last have only one use and are not views/outputs (see ggml_node_has_N_uses). +// - all nodes except the last are a src of the following node. +// - all nodes are the same shape. +// TODO: Consider allowing GGML_OP_NONE nodes in between +static inline bool ggml_can_fuse_ext(const struct ggml_cgraph * cgraph, const int * node_idxs, const enum ggml_op * ops, int num_ops) { + for (int i = 0; i < num_ops; ++i) { + if (node_idxs[i] >= cgraph->n_nodes) { + return false; + } + + struct ggml_tensor * node = cgraph->nodes[node_idxs[i]]; + if (node->op != ops[i]) { + return false; + } + if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { + return false; + } + if (i < num_ops - 1 && !ggml_node_has_n_uses(cgraph, node_idxs[i], 1)) { + return false; + } + if (i > 0) { + struct ggml_tensor * prev = cgraph->nodes[node_idxs[i - 1]]; + if (node->src[0] != prev && node->src[1] != prev) { + return false; + } + if (!ggml_are_same_shape(node, prev)) { + return false; + } + } + } + return true; +} + +// same as above, for sequential indices starting at node_idx +static inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, const enum ggml_op * ops, int num_ops) { + assert(num_ops < 32); + + if (node_idx + num_ops > cgraph->n_nodes) { + return false; + } + + int idxs[32]; + for (int i = 0; i < num_ops; ++i) { + idxs[i] = node_idx + i; + } + + return ggml_can_fuse_ext(cgraph, idxs, ops, num_ops); +} + +GGML_API bool ggml_can_fuse_subgraph_ext(const struct ggml_cgraph * cgraph, + const int * node_idxs, + int count, + const enum ggml_op * ops, + const int * outputs, + int num_outputs); + +// Returns true if the subgraph formed by {node_idxs} can be fused +// checks whethers all nodes which are not part of outputs can be elided +// by checking if their num_uses are confined to the subgraph +static inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph, + int node_idx, + int count, + const enum ggml_op * ops, + const int * outputs, + int num_outputs) { + GGML_ASSERT(count < 32); + if (node_idx + count > cgraph->n_nodes) { + return false; + } + + int idxs[32]; + + for (int i = 0; i < count; ++i) { + idxs[i] = node_idx + i; + } + + return ggml_can_fuse_subgraph_ext(cgraph, idxs, count, ops, outputs, num_outputs); +} + +#ifdef __cplusplus +} +#endif + +#ifdef __cplusplus +#include +#include +#include + +// nicer C++ syntax for ggml_can_fuse +inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { + return ggml_can_fuse(cgraph, node_idx, ops.begin(), (int)ops.size()); +} + +inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph, + int start_idx, + std::initializer_list ops, + std::initializer_list outputs = {}) { + return ggml_can_fuse_subgraph(cgraph, start_idx, ops.size(), ops.begin(), outputs.begin(), outputs.size()); +} + +// Return true if the edges in the graph match expectations. +inline bool ggml_check_edges(const struct ggml_cgraph * cgraph, + int start_idx, + std::initializer_list> edges) { + for (const auto & edge : edges) { + int dst_node = edge[0]; + int src_idx = edge[1]; + int src_node = edge[2]; + if (cgraph->nodes[start_idx + dst_node]->src[src_idx] != cgraph->nodes[start_idx + src_node]) { + return false; + } + } + return true; +} + +// expose GGUF internals for test code +GGML_API size_t gguf_type_size(enum gguf_type type); +GGML_API void gguf_write_to_buf(const struct gguf_context * ctx, std::vector & buf, bool only_meta); +#endif // __cplusplus diff --git a/control-plane/third_party/ggml/ggml-quants.c b/control-plane/third_party/ggml/ggml-quants.c new file mode 100644 index 00000000..1ebc50a7 --- /dev/null +++ b/control-plane/third_party/ggml/ggml-quants.c @@ -0,0 +1,5667 @@ +#define GGML_COMMON_IMPL_C +#include "ggml-common.h" + +#include "ggml-quants.h" +#include "ggml-impl.h" +#include "ggml-cpu/ggml-cpu-impl.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include // for qsort +#include // for GGML_ASSERT + +#ifdef GGML_USE_OPENMP +#include +#endif + +#define GROUP_MAX_EPS 1e-15f +#define GROUP_MAX_EPS_IQ3_XXS 1e-8f +#define GROUP_MAX_EPS_IQ2_S 1e-8f +#define GROUP_MAX_EPS_IQ1_M 1e-7f +#define GROUP_MAX_EPS_IQ1_S 1e-12f + +#define UNUSED GGML_UNUSED + +static inline int best_index_int8(int n, const int8_t * val, float x) { + if (x <= val[0]) return 0; + if (x >= val[n-1]) return n-1; + int ml = 0, mu = n-1; + while (mu-ml > 1) { + int mav = (ml+mu)/2; + if (x < val[mav]) mu = mav; else ml = mav; + } + return x - val[mu-1] < val[mu] - x ? mu-1 : mu; +} + +// reference implementation for deterministic creation of model files +void quantize_row_q1_0_ref(const float * GGML_RESTRICT x, block_q1_0 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK1_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float sum_abs = 0.0f; + for (int j = 0; j < qk; j++) { + sum_abs += fabsf(x[i*qk + j]); + } + const float d = sum_abs / qk; + + y[i].d = GGML_FP32_TO_FP16(d); + + // Clear all bits first + for (int j = 0; j < qk / 8; ++j) { + y[i].qs[j] = 0; + } + + // Just store sign of each weight directly (no normalization) + for (int j = 0; j < qk; ++j) { + const int bit_index = j; + const int byte_index = bit_index / 8; + const int bit_offset = bit_index % 8; + + if (x[i*qk + j] >= 0.0f) { + y[i].qs[byte_index] |= (1 << bit_offset); + } + } + } +} + +void quantize_row_q2_0_ref(const float * GGML_RESTRICT x, block_q2_0 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK2_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + // Compute scale as max absolute value in the block + float amax = 0.0f; + for (int j = 0; j < qk; j++) { + const float a = fabsf(x[i*qk + j]); + if (a > amax) amax = a; + } + const float d = amax; + const float id = d > 0.0f ? 1.0f / d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + // Clear quant bytes + for (int j = 0; j < qk / 4; ++j) { + y[i].qs[j] = 0; + } + + // Encode 2-bit values: round(w/d) clamped to [-1, 2], then add 1 + // 00 (-1) = -scale, 01 (0) = 0, 10 (+1) = +scale, 11 (+2) = 2*scale + for (int j = 0; j < qk; ++j) { + const float w = x[i*qk + j]; + int q = (int)roundf(w * id) + 1; + if (q < 0) q = 0; + if (q > 3) q = 3; + const int byte_index = j / 4; + const int bit_offset = (j % 4) * 2; + y[i].qs[byte_index] |= ((uint8_t)q << bit_offset); + } + } +} + +// reference implementation for deterministic creation of model files +void quantize_row_q4_0_ref(const float * GGML_RESTRICT x, block_q4_0 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK4_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + float max = 0.0f; + + for (int j = 0; j < qk; j++) { + const float v = x[i*qk + j]; + if (amax < fabsf(v)) { + amax = fabsf(v); + max = v; + } + } + + const float d = max / -8; + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + for (int j = 0; j < qk/2; ++j) { + const float x0 = x[i*qk + 0 + j]*id; + const float x1 = x[i*qk + qk/2 + j]*id; + + const uint8_t xi0 = MIN(15, (int8_t)(x0 + 8.5f)); + const uint8_t xi1 = MIN(15, (int8_t)(x1 + 8.5f)); + + y[i].qs[j] = xi0; + y[i].qs[j] |= xi1 << 4; + } + } +} + +void quantize_row_q4_1_ref(const float * GGML_RESTRICT x, block_q4_1 * GGML_RESTRICT y, int64_t k) { + const int qk = QK4_1; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float min = FLT_MAX; + float max = -FLT_MAX; + + for (int j = 0; j < qk; j++) { + const float v = x[i*qk + j]; + + if (v < min) min = v; + if (v > max) max = v; + } + + const float d = (max - min) / ((1 << 4) - 1); + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + y[i].m = GGML_FP32_TO_FP16(min); + + for (int j = 0; j < qk/2; ++j) { + const float x0 = (x[i*qk + 0 + j] - min)*id; + const float x1 = (x[i*qk + qk/2 + j] - min)*id; + + const uint8_t xi0 = MIN(15, (int8_t)(x0 + 0.5f)); + const uint8_t xi1 = MIN(15, (int8_t)(x1 + 0.5f)); + + y[i].qs[j] = xi0; + y[i].qs[j] |= xi1 << 4; + } + } +} + +void quantize_row_q5_0_ref(const float * GGML_RESTRICT x, block_q5_0 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK5_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + float max = 0.0f; + + for (int j = 0; j < qk; j++) { + const float v = x[i*qk + j]; + if (amax < fabsf(v)) { + amax = fabsf(v); + max = v; + } + } + + const float d = max / -16; + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + uint32_t qh = 0; + + for (int j = 0; j < qk/2; ++j) { + const float x0 = x[i*qk + 0 + j]*id; + const float x1 = x[i*qk + qk/2 + j]*id; + + const uint8_t xi0 = MIN(31, (int8_t)(x0 + 16.5f)); + const uint8_t xi1 = MIN(31, (int8_t)(x1 + 16.5f)); + + y[i].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4); + + // get the 5-th bit and store it in qh at the right position + qh |= ((xi0 & 0x10u) >> 4) << (j + 0); + qh |= ((xi1 & 0x10u) >> 4) << (j + qk/2); + } + + memcpy(&y[i].qh, &qh, sizeof(qh)); + } +} + +void quantize_row_q5_1_ref(const float * GGML_RESTRICT x, block_q5_1 * GGML_RESTRICT y, int64_t k) { + const int qk = QK5_1; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float min = FLT_MAX; + float max = -FLT_MAX; + + for (int j = 0; j < qk; j++) { + const float v = x[i*qk + j]; + + if (v < min) min = v; + if (v > max) max = v; + } + + const float d = (max - min) / ((1 << 5) - 1); + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + y[i].m = GGML_FP32_TO_FP16(min); + + uint32_t qh = 0; + + for (int j = 0; j < qk/2; ++j) { + const float x0 = (x[i*qk + 0 + j] - min)*id; + const float x1 = (x[i*qk + qk/2 + j] - min)*id; + + const uint8_t xi0 = (uint8_t)(x0 + 0.5f); + const uint8_t xi1 = (uint8_t)(x1 + 0.5f); + + y[i].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4); + + // get the 5-th bit and store it in qh at the right position + qh |= ((xi0 & 0x10u) >> 4) << (j + 0); + qh |= ((xi1 & 0x10u) >> 4) << (j + qk/2); + } + + memcpy(&y[i].qh, &qh, sizeof(y[i].qh)); + } +} + +// reference implementation for deterministic creation of model files +void quantize_row_q8_0_ref(const float * GGML_RESTRICT x, block_q8_0 * GGML_RESTRICT y, int64_t k) { + assert(k % QK8_0 == 0); + const int nb = k / QK8_0; + + for (int i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + + for (int j = 0; j < QK8_0; j++) { + const float v = x[i*QK8_0 + j]; + amax = MAX(amax, fabsf(v)); + } + + const float d = amax / ((1 << 7) - 1); + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + for (int j = 0; j < QK8_0; ++j) { + const float x0 = x[i*QK8_0 + j]*id; + + y[i].qs[j] = roundf(x0); + } + } +} + +// reference implementation for deterministic creation of model files +void quantize_row_q8_1_ref(const float * GGML_RESTRICT x, block_q8_1 * GGML_RESTRICT y, int64_t k) { + assert(QK8_1 == 32); + assert(k % QK8_1 == 0); + const int nb = k / QK8_1; + + for (int i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + + for (int j = 0; j < QK8_1; j++) { + const float v = x[i*QK8_1 + j]; + amax = MAX(amax, fabsf(v)); + } + + const float d = amax / ((1 << 7) - 1); + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + int sum = 0; + + for (int j = 0; j < QK8_1/2; ++j) { + const float v0 = x[i*QK8_1 + j]*id; + const float v1 = x[i*QK8_1 + QK8_1/2 + j]*id; + + y[i].qs[ j] = roundf(v0); + y[i].qs[QK8_1/2 + j] = roundf(v1); + + sum += y[i].qs[ j]; + sum += y[i].qs[QK8_1/2 + j]; + } + + y[i].s = GGML_FP32_TO_FP16(sum*d); + } +} + +static inline int best_index_mxfp4(float x, float e) { + int best_index = 0; + float best_err = fabsf(kvalues_mxfp4[0]*e - x); + for (int i = 1; i < 16; i++) { + float err = fabsf(kvalues_mxfp4[i]*e - x); + if (err < best_err) { + best_index = i; + best_err = err; + } + } + return best_index; +} + +void quantize_row_mxfp4_ref(const float * GGML_RESTRICT x, block_mxfp4 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK_MXFP4; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + + for (int j = 0; j < qk; j++) { + const float v = x[i*qk + j]; + + if (amax < fabsf(v)) { + amax = fabsf(v); + } + } + + const uint8_t e = amax > 0.0f ? (uint8_t) (floorf(log2f(amax)) - 2 + 127) : 0; + + const float d = GGML_E8M0_TO_FP32_HALF(e); + + y[i].e = e; + + for (int j = 0; j < qk/2; ++j) { + const uint8_t x0 = best_index_mxfp4(x[i*qk + 0 + j], d); + const uint8_t x1 = best_index_mxfp4(x[i*qk + qk/2 + j], d); + + y[i].qs[j] = x0; + y[i].qs[j] |= x1 << 4; + } + } +} + +void quantize_row_nvfp4_ref(const float * GGML_RESTRICT x, block_nvfp4 * GGML_RESTRICT y, int64_t k) { + static const int qk = QK_NVFP4; + static const int qk_sub = QK_NVFP4_SUB; + static const int n_sub = QK_NVFP4 / QK_NVFP4_SUB; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + for (int s = 0; s < n_sub; s++) { + const float * xb = x + i*qk + s*qk_sub; + + float amax = 0.0f; + for (int j = 0; j < qk_sub; j++) { + if (amax < fabsf(xb[j])) { + amax = fabsf(xb[j]); + } + } + + // UE4M3 scale: amax / 6.0 maps the max E2M1 value (6.0) to amax + const uint8_t ue = ggml_fp32_to_ue4m3(amax / 6.0f); + y[i].d[s] = ue; + const float d = ggml_ue4m3_to_fp32(ue); + + for (int j = 0; j < qk_sub/2; ++j) { + const uint8_t x0 = best_index_mxfp4(xb[0 + j], d); + const uint8_t x1 = best_index_mxfp4(xb[qk_sub/2 + j], d); + + y[i].qs[s*(qk_sub/2) + j] = x0 | (x1 << 4); + } + } + } +} + +void dequantize_row_q1_0(const block_q1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK1_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + const float neg_d = -d; + + for (int j = 0; j < qk; ++j) { + const int byte_index = j / 8; + const int bit_offset = j % 8; + const uint8_t bit = (x[i].qs[byte_index] >> bit_offset) & 1; + y[i*qk + j] = bit ? d : neg_d; + } + } +} + +void dequantize_row_q2_0(const block_q2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK2_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int j = 0; j < qk; ++j) { + const int byte_index = j / 4; + const int bit_offset = (j % 4) * 2; + const uint8_t q = (x[i].qs[byte_index] >> bit_offset) & 0x03; + // 00=-1, 01=0, 10=+1, 11=+2 + y[i*qk + j] = ((int)q - 1) * d; + } + } +} + +void dequantize_row_q4_0(const block_q4_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK4_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int j = 0; j < qk/2; ++j) { + const int x0 = (x[i].qs[j] & 0x0F) - 8; + const int x1 = (x[i].qs[j] >> 4) - 8; + + y[i*qk + j + 0 ] = x0*d; + y[i*qk + j + qk/2] = x1*d; + } + } +} + +void dequantize_row_q4_1(const block_q4_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK4_1; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + const float m = GGML_FP16_TO_FP32(x[i].m); + + for (int j = 0; j < qk/2; ++j) { + const int x0 = (x[i].qs[j] & 0x0F); + const int x1 = (x[i].qs[j] >> 4); + + y[i*qk + j + 0 ] = x0*d + m; + y[i*qk + j + qk/2] = x1*d + m; + } + } +} + +void dequantize_row_q5_0(const block_q5_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK5_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + + uint32_t qh; + memcpy(&qh, x[i].qh, sizeof(qh)); + + for (int j = 0; j < qk/2; ++j) { + const uint8_t xh_0 = ((qh >> (j + 0)) << 4) & 0x10; + const uint8_t xh_1 = ((qh >> (j + 12)) ) & 0x10; + + const int32_t x0 = ((x[i].qs[j] & 0x0F) | xh_0) - 16; + const int32_t x1 = ((x[i].qs[j] >> 4) | xh_1) - 16; + + y[i*qk + j + 0 ] = x0*d; + y[i*qk + j + qk/2] = x1*d; + } + } +} + +void dequantize_row_q5_1(const block_q5_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK5_1; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + const float m = GGML_FP16_TO_FP32(x[i].m); + + uint32_t qh; + memcpy(&qh, x[i].qh, sizeof(qh)); + + for (int j = 0; j < qk/2; ++j) { + const uint8_t xh_0 = ((qh >> (j + 0)) << 4) & 0x10; + const uint8_t xh_1 = ((qh >> (j + 12)) ) & 0x10; + + const int x0 = (x[i].qs[j] & 0x0F) | xh_0; + const int x1 = (x[i].qs[j] >> 4) | xh_1; + + y[i*qk + j + 0 ] = x0*d + m; + y[i*qk + j + qk/2] = x1*d + m; + } + } +} + +void dequantize_row_q8_0(const block_q8_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK8_0; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int j = 0; j < qk; ++j) { + y[i*qk + j] = x[i].qs[j]*d; + } + } +} + +void dequantize_row_mxfp4(const block_mxfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK_MXFP4; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + const float d = GGML_E8M0_TO_FP32_HALF(x[i].e); + + for (int j = 0; j < qk/2; ++j) { + const int8_t x0 = kvalues_mxfp4[x[i].qs[j] & 0x0F]; + const int8_t x1 = kvalues_mxfp4[x[i].qs[j] >> 4]; + + y[i*qk + j + 0 ] = x0*d; + y[i*qk + j + qk/2] = x1*d; + } + } +} + +void dequantize_row_nvfp4(const block_nvfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + static const int qk = QK_NVFP4; + static const int qk_sub = QK_NVFP4_SUB; + static const int n_sub = QK_NVFP4 / QK_NVFP4_SUB; + + assert(k % qk == 0); + + const int nb = k / qk; + + for (int i = 0; i < nb; i++) { + for (int s = 0; s < n_sub; s++) { + const float d = ggml_ue4m3_to_fp32(x[i].d[s]); + float * yb = y + i*qk + s*qk_sub; + + for (int j = 0; j < qk_sub/2; ++j) { + const int8_t v0 = kvalues_mxfp4[x[i].qs[s*(qk_sub/2) + j] & 0x0F]; + const int8_t v1 = kvalues_mxfp4[x[i].qs[s*(qk_sub/2) + j] >> 4]; + + yb[j + 0 ] = v0*d; + yb[j + qk_sub/2] = v1*d; + } + } + } +} + +// +// 2-6 bit quantization in super-blocks +// + +// +// ===================== Helper functions +// +static inline int nearest_int(float fval) { + assert(fabsf(fval) <= 4194303.f); + float val = fval + 12582912.f; + int i; memcpy(&i, &val, sizeof(int)); + return (i & 0x007fffff) - 0x00400000; +} + +static float make_qx_quants(int n, int nmax, const float * GGML_RESTRICT x, int8_t * GGML_RESTRICT L, int rmse_type, + const float * GGML_RESTRICT qw) { + float max = 0; + float amax = 0; + for (int i = 0; i < n; ++i) { + float ax = fabsf(x[i]); + if (ax > amax) { amax = ax; max = x[i]; } + } + if (amax < GROUP_MAX_EPS) { // all zero + for (int i = 0; i < n; ++i) { + L[i] = 0; + } + return 0.f; + } + float iscale = -nmax / max; + if (rmse_type == 0) { + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + L[i] = nmax + MAX(-nmax, MIN(nmax-1, l)); + } + return 1/iscale; + } + bool return_early = false; + if (rmse_type < 0) { + rmse_type = -rmse_type; + return_early = true; + } + float sumlx = 0; + float suml2 = 0; +#ifdef HAVE_BUGGY_APPLE_LINKER + // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7 + for (volatile int i = 0; i < n; ++i) { +#else + for (int i = 0; i < n; ++i) { +#endif + int l = nearest_int(iscale * x[i]); + l = MAX(-nmax, MIN(nmax-1, l)); + L[i] = l + nmax; + float w = qw ? qw[i] : rmse_type == 1 ? x[i] * x[i] : rmse_type == 2 ? 1 : rmse_type == 3 ? fabsf(x[i]) : sqrtf(fabsf(x[i])); + sumlx += w*x[i]*l; + suml2 += w*l*l; + } + float scale = suml2 ? sumlx/suml2 : 0.0f; + if (return_early) return suml2 > 0 ? 0.5f*(scale + 1/iscale) : 1/iscale; + float best = scale * sumlx; + for (int is = -9; is <= 9; ++is) { + if (is == 0) { + continue; + } + iscale = -(nmax + 0.1f*is) / max; + sumlx = suml2 = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + l = MAX(-nmax, MIN(nmax-1, l)); + float w = qw ? qw[i] : rmse_type == 1 ? x[i] * x[i] : rmse_type == 2 ? 1 : rmse_type == 3 ? fabsf(x[i]) : sqrtf(fabsf(x[i])); + sumlx += w*x[i]*l; + suml2 += w*l*l; + } + if (suml2 > 0 && sumlx*sumlx > best*suml2) { + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + L[i] = nmax + MAX(-nmax, MIN(nmax-1, l)); + } + scale = sumlx/suml2; best = scale*sumlx; + } + } + return scale; +} + +static float make_q3_quants(int n, int nmax, const float * GGML_RESTRICT x, int8_t * GGML_RESTRICT L, bool do_rmse) { + float max = 0; + float amax = 0; + for (int i = 0; i < n; ++i) { + float ax = fabsf(x[i]); + if (ax > amax) { amax = ax; max = x[i]; } + } + if (amax < GROUP_MAX_EPS) { // all zero + for (int i = 0; i < n; ++i) { L[i] = 0; } + return 0.f; + } + float iscale = -nmax / max; + if (do_rmse) { + float sumlx = 0; + float suml2 = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + l = MAX(-nmax, MIN(nmax-1, l)); + L[i] = l; + float w = x[i]*x[i]; + sumlx += w*x[i]*l; + suml2 += w*l*l; + } + for (int itry = 0; itry < 5; ++itry) { + int n_changed = 0; + for (int i = 0; i < n; ++i) { + float w = x[i]*x[i]; + float slx = sumlx - w*x[i]*L[i]; + if (slx > 0) { + float sl2 = suml2 - w*L[i]*L[i]; + int new_l = nearest_int(x[i] * sl2 / slx); + new_l = MAX(-nmax, MIN(nmax-1, new_l)); + if (new_l != L[i]) { + slx += w*x[i]*new_l; + sl2 += w*new_l*new_l; + if (sl2 > 0 && slx*slx*suml2 > sumlx*sumlx*sl2) { + L[i] = new_l; sumlx = slx; suml2 = sl2; + ++n_changed; + } + } + } + } + if (!n_changed) { + break; + } + } + for (int i = 0; i < n; ++i) { + L[i] += nmax; + } + return suml2 > 0.0f ? sumlx / suml2 : 0.0f; + } + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + l = MAX(-nmax, MIN(nmax-1, l)); + L[i] = l + nmax; + } + return 1/iscale; +} + +static float make_qkx1_quants(int n, int nmax, const float * GGML_RESTRICT x, uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min, + int ntry, float alpha) { + float min = x[0]; + float max = x[0]; + for (int i = 1; i < n; ++i) { + if (x[i] < min) min = x[i]; + if (x[i] > max) max = x[i]; + } + if (max == min) { + for (int i = 0; i < n; ++i) L[i] = 0; + *the_min = 0; + return 0.f; + } + if (min > 0) min = 0; + float iscale = nmax/(max - min); + float scale = 1/iscale; + for (int itry = 0; itry < ntry; ++itry) { + float sumlx = 0; int suml2 = 0; + bool did_change = false; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale*(x[i] - min)); + l = MAX(0, MIN(nmax, l)); + if (l != L[i]) { + L[i] = l; + did_change = true; + } + sumlx += (x[i] - min)*l; + suml2 += l*l; + } + scale = sumlx/suml2; + float sum = 0; + for (int i = 0; i < n; ++i) { + sum += x[i] - scale*L[i]; + } + min = alpha*min + (1 - alpha)*sum/n; + if (min > 0) min = 0; + iscale = 1/scale; + if (!did_change) break; + } + *the_min = -min; + return scale; +} + +static float make_qkx2_quants(int n, int nmax, const float * GGML_RESTRICT x, const float * GGML_RESTRICT weights, + uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min, uint8_t * GGML_RESTRICT Laux, + float rmin, float rdelta, int nstep, bool use_mad) { + float min = x[0]; + float max = x[0]; + float sum_w = weights[0]; + float sum_x = sum_w * x[0]; +#ifdef HAVE_BUGGY_APPLE_LINKER + // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7 + for (volatile int i = 1; i < n; ++i) { +#else + for (int i = 1; i < n; ++i) { +#endif + if (x[i] < min) min = x[i]; + if (x[i] > max) max = x[i]; + float w = weights[i]; + sum_w += w; + sum_x += w * x[i]; + } + if (min > 0) min = 0; + if (max == min) { + for (int i = 0; i < n; ++i) L[i] = 0; + *the_min = -min; + return 0.f; + } + float iscale = nmax/(max - min); + float scale = 1/iscale; + float best_error = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale*(x[i] - min)); + L[i] = MAX(0, MIN(nmax, l)); + float diff = scale * L[i] + min - x[i]; + diff = use_mad ? fabsf(diff) : diff * diff; + float w = weights[i]; + best_error += w * diff; + } + if (nstep < 1) { + *the_min = -min; + return scale; + } + for (int is = 0; is <= nstep; ++is) { + iscale = (rmin + rdelta*is + nmax)/(max - min); + float sum_l = 0, sum_l2 = 0, sum_xl = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale*(x[i] - min)); + l = MAX(0, MIN(nmax, l)); + Laux[i] = l; + float w = weights[i]; + sum_l += w*l; + sum_l2 += w*l*l; + sum_xl += w*l*x[i]; + } + float D = sum_w * sum_l2 - sum_l * sum_l; + if (D > 0) { + float this_scale = (sum_w * sum_xl - sum_x * sum_l)/D; + float this_min = (sum_l2 * sum_x - sum_l * sum_xl)/D; + if (this_min > 0) { + this_min = 0; + this_scale = sum_xl / sum_l2; + } + float cur_error = 0; + for (int i = 0; i < n; ++i) { + float diff = this_scale * Laux[i] + this_min - x[i]; + diff = use_mad ? fabsf(diff) : diff * diff; + float w = weights[i]; + cur_error += w * diff; + } + if (cur_error < best_error) { + for (int i = 0; i < n; ++i) { + L[i] = Laux[i]; + } + best_error = cur_error; + scale = this_scale; + min = this_min; + } + } + } + *the_min = -min; + return scale; +} + +static inline void get_scale_min_k4(int j, const uint8_t * GGML_RESTRICT q, uint8_t * GGML_RESTRICT d, uint8_t * GGML_RESTRICT m) { + if (j < 4) { + *d = q[j] & 63; *m = q[j + 4] & 63; + } else { + *d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4); + *m = (q[j+4] >> 4) | ((q[j-0] >> 6) << 4); + } +} + +//========================- 2-bit (de)-quantization + +void quantize_row_q2_K_ref(const float * GGML_RESTRICT x, block_q2_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + uint8_t L[QK_K]; + uint8_t Laux[16]; + float weights[16]; + float mins[QK_K/16]; + float scales[QK_K/16]; + + const float q4scale = 15.f; + + for (int i = 0; i < nb; i++) { + float max_scale = 0; // as we are deducting the min, scales are always positive + float max_min = 0; + for (int j = 0; j < QK_K/16; ++j) { + for (int l = 0; l < 16; ++l) weights[l] = fabsf(x[16*j + l]); + scales[j] = make_qkx2_quants(16, 3, x + 16*j, weights, L + 16*j, &mins[j], Laux, -0.5f, 0.1f, 15, true); + float scale = scales[j]; + if (scale > max_scale) { + max_scale = scale; + } + float min = mins[j]; + if (min > max_min) { + max_min = min; + } + } + + if (max_scale > 0) { + float iscale = q4scale/max_scale; + for (int j = 0; j < QK_K/16; ++j) { + int l = nearest_int(iscale*scales[j]); + y[i].scales[j] = l; + } + y[i].d = GGML_FP32_TO_FP16(max_scale/q4scale); + } else { + for (int j = 0; j < QK_K/16; ++j) y[i].scales[j] = 0; + y[i].d = GGML_FP32_TO_FP16(0.f); + } + if (max_min > 0) { + float iscale = q4scale/max_min; + for (int j = 0; j < QK_K/16; ++j) { + int l = nearest_int(iscale*mins[j]); + y[i].scales[j] |= (l << 4); + } + y[i].dmin = GGML_FP32_TO_FP16(max_min/q4scale); + } else { + y[i].dmin = GGML_FP32_TO_FP16(0.f); + } + for (int j = 0; j < QK_K/16; ++j) { + const float d = GGML_FP16_TO_FP32(y[i].d) * (y[i].scales[j] & 0xF); + if (!d) continue; + const float dm = GGML_FP16_TO_FP32(y[i].dmin) * (y[i].scales[j] >> 4); + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int((x[16*j + ii] + dm)/d); + l = MAX(0, MIN(3, l)); + L[16*j + ii] = l; + } + } + + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6); + } + } + + x += QK_K; + } +} + +void dequantize_row_q2_K(const block_q2_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + const float min = GGML_FP16_TO_FP32(x[i].dmin); + + const uint8_t * q = x[i].qs; + + int is = 0; + float dl, ml; + for (int n = 0; n < QK_K; n += 128) { + int shift = 0; + for (int j = 0; j < 4; ++j) { + + uint8_t sc = x[i].scales[is++]; + dl = d * (sc & 0xF); ml = min * (sc >> 4); + for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l] >> shift) & 3)) - ml; + + sc = x[i].scales[is++]; + dl = d * (sc & 0xF); ml = min * (sc >> 4); + for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l+16] >> shift) & 3)) - ml; + + shift += 2; + } + q += 32; + } + } +} + +static float make_qkx3_quants(int n, int nmax, const float * GGML_RESTRICT x, const float * GGML_RESTRICT weights, + uint8_t * GGML_RESTRICT L, float * GGML_RESTRICT the_min, uint8_t * GGML_RESTRICT Laux, + float rmin, float rdelta, int nstep, bool use_mad) { + float min = x[0]; + float max = x[0]; + float sum_w = weights ? weights[0] : x[0]*x[0]; + float sum_x = sum_w * x[0]; +#ifdef HAVE_BUGGY_APPLE_LINKER + // use 'volatile' to prevent unroll and work around a bug in Apple ld64 1015.7 + for (volatile int i = 1; i < n; ++i) { +#else + for (int i = 1; i < n; ++i) { +#endif + if (x[i] < min) min = x[i]; + if (x[i] > max) max = x[i]; + float w = weights ? weights[i] : x[i]*x[i]; + sum_w += w; + sum_x += w * x[i]; + } + if (min > 0) { + min = 0; + } + if (max <= min) { + memset(L, 0, n); + *the_min = -min; + return 0.f; + } + float iscale = nmax/(max - min); + float scale = 1/iscale; + float best_mad = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale*(x[i] - min)); + L[i] = MAX(0, MIN(nmax, l)); + float diff = scale * L[i] + min - x[i]; + diff = use_mad ? fabsf(diff) : diff*diff; + float w = weights ? weights[i] : x[i]*x[i]; + best_mad += w * diff; + } + if (nstep < 1) { + *the_min = -min; + return scale; + } + for (int is = 0; is <= nstep; ++is) { + iscale = (rmin + rdelta*is + nmax)/(max - min); + float sum_l = 0, sum_l2 = 0, sum_xl = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale*(x[i] - min)); + l = MAX(0, MIN(nmax, l)); + Laux[i] = l; + float w = weights ? weights[i] : x[i]*x[i]; + sum_l += w*l; + sum_l2 += w*l*l; + sum_xl += w*l*x[i]; + } + float D = sum_w * sum_l2 - sum_l * sum_l; + if (D > 0) { + float this_scale = (sum_w * sum_xl - sum_x * sum_l)/D; + float this_min = (sum_l2 * sum_x - sum_l * sum_xl)/D; + if (this_min > 0) { + this_min = 0; + this_scale = sum_xl / sum_l2; + } + float mad = 0; + for (int i = 0; i < n; ++i) { + float diff = this_scale * Laux[i] + this_min - x[i]; + diff = use_mad ? fabsf(diff) : diff*diff; + float w = weights ? weights[i] : x[i]*x[i]; + mad += w * diff; + } + if (mad < best_mad) { + for (int i = 0; i < n; ++i) { + L[i] = Laux[i]; + } + best_mad = mad; + scale = this_scale; + min = this_min; + } + } + } + *the_min = -min; + return scale; +} + +static float make_qp_quants(int n, int nmax, const float * GGML_RESTRICT x, uint8_t * GGML_RESTRICT L, const float * quant_weights) { + float max = 0; + for (int i = 0; i < n; ++i) { + max = MAX(max, x[i]); + } + if (max < GROUP_MAX_EPS) { // all zero + for (int i = 0; i < n; ++i) { L[i] = 0; } + return 0.f; + } + float iscale = nmax / max; + for (int i = 0; i < n; ++i) { + L[i] = nearest_int(iscale * x[i]); + } + float scale = 1/iscale; + float best_mse = 0; + for (int i = 0; i < n; ++i) { + float diff = x[i] - scale*L[i]; + float w = quant_weights[i]; + best_mse += w*diff*diff; + } + for (int is = -4; is <= 4; ++is) { + if (is == 0) continue; + float iscale_is = (0.1f*is + nmax)/max; + float scale_is = 1/iscale_is; + float mse = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale_is*x[i]); + l = MIN(nmax, l); + float diff = x[i] - scale_is*l; + float w = quant_weights[i]; + mse += w*diff*diff; + } + if (mse < best_mse) { + best_mse = mse; + iscale = iscale_is; + } + } + float sumlx = 0; + float suml2 = 0; + for (int i = 0; i < n; ++i) { + int l = nearest_int(iscale * x[i]); + l = MIN(nmax, l); + L[i] = l; + float w = quant_weights[i]; + sumlx += w*x[i]*l; + suml2 += w*l*l; + } + for (int itry = 0; itry < 5; ++itry) { + int n_changed = 0; + for (int i = 0; i < n; ++i) { + float w = quant_weights[i]; + float slx = sumlx - w*x[i]*L[i]; + float sl2 = suml2 - w*L[i]*L[i]; + if (slx > 0 && sl2 > 0) { + int new_l = nearest_int(x[i] * sl2 / slx); + new_l = MIN(nmax, new_l); + if (new_l != L[i]) { + slx += w*x[i]*new_l; + sl2 += w*new_l*new_l; + if (slx*slx*suml2 > sumlx*sumlx*sl2) { + L[i] = new_l; sumlx = slx; suml2 = sl2; + ++n_changed; + } + } + } + } + if (!n_changed) { + break; + } + } + return suml2 > 0.0f ? sumlx / suml2 : 0.0f; +} + +static void quantize_row_q2_K_impl(const float * GGML_RESTRICT x, block_q2_K * GGML_RESTRICT y, int k, const float * GGML_RESTRICT quant_weights) { + GGML_ASSERT(quant_weights); + assert(k % QK_K == 0); + const int nb = k / QK_K; + const bool requantize = true; + + uint8_t L[QK_K]; + uint8_t Laux[16]; + float mins[QK_K/16]; + float scales[QK_K/16]; + float sw[QK_K/16]; + float weight[16]; + uint8_t Ls[QK_K/16], Lm[QK_K/16]; + + for (int i = 0; i < nb; i++) { + memset(sw, 0, QK_K/16*sizeof(float)); + float sumx2 = 0; + for (int j = 0; j < QK_K; ++j) sumx2 += x[j]*x[j]; + float sigma2 = sumx2/QK_K; + for (int j = 0; j < QK_K/16; ++j) { + const float * GGML_RESTRICT qw = quant_weights + QK_K * i + 16*j; + for (int l = 0; l < 16; ++l) weight[l] = qw[l] * sqrtf(sigma2 + x[16*j + l]*x[16*j + l]); + for (int l = 0; l < QK_K/16; ++l) sw[j] += weight[l]; + scales[j] = make_qkx3_quants(16, 3, x + 16*j, weight, L + 16*j, &mins[j], Laux, -0.9f, 0.05f, 36, false); + } + + float dm, mm; + dm = make_qp_quants(QK_K/16, 15, scales, Ls, sw); + mm = make_qp_quants(QK_K/16, 15, mins, Lm, sw); + + y[i].d = GGML_FP32_TO_FP16(dm); + y[i].dmin = GGML_FP32_TO_FP16(mm); + dm = GGML_FP16_TO_FP32(y[i].d); + mm = GGML_FP16_TO_FP32(y[i].dmin); + + for (int j = 0; j < QK_K/16; ++j) { + y[i].scales[j] = Ls[j] | (Lm[j] << 4); + } + + if (requantize) { + for (int j = 0; j < QK_K/16; ++j) { + const float d = dm * (y[i].scales[j] & 0xF); + if (!d) continue; + const float m = mm * (y[i].scales[j] >> 4); + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int((x[16*j + ii] + m)/d); + l = MAX(0, MIN(3, l)); + L[16*j + ii] = l; + } + } + } + + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6); + } + } + + x += QK_K; + } +} + +size_t quantize_q2_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + size_t row_size = ggml_row_size(GGML_TYPE_Q2_K, n_per_row); + if (!quant_weights) { + quantize_row_q2_K_ref(src, dst, (int64_t)nrow*n_per_row); + } + else { + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q2_K_impl(src, (block_q2_K*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + } + return nrow * row_size; +} + +//========================= 3-bit (de)-quantization + +void quantize_row_q3_K_ref(const float * GGML_RESTRICT x, block_q3_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + int8_t L[QK_K]; + float scales[QK_K / 16]; + + for (int i = 0; i < nb; i++) { + + float max_scale = 0; + float amax = 0; + for (int j = 0; j < QK_K/16; ++j) { + scales[j] = make_q3_quants(16, 4, x + 16*j, L + 16*j, true); + float scale = fabsf(scales[j]); + if (scale > amax) { + amax = scale; max_scale = scales[j]; + } + } + + memset(y[i].scales, 0, 12); + if (max_scale) { + float iscale = -32.f/max_scale; + for (int j = 0; j < QK_K/16; ++j) { + int8_t l = nearest_int(iscale*scales[j]); + l = MAX(-32, MIN(31, l)) + 32; + if (j < 8) { + y[i].scales[j] = l & 0xF; + } else { + y[i].scales[j-8] |= ((l & 0xF) << 4); + } + l >>= 4; + y[i].scales[j%4 + 8] |= (l << (2*(j/4))); + } + y[i].d = GGML_FP32_TO_FP16(1/iscale); + } else { + y[i].d = GGML_FP32_TO_FP16(0.f); + } + + int8_t sc; + for (int j = 0; j < QK_K/16; ++j) { + sc = j < 8 ? y[i].scales[j] & 0xF : y[i].scales[j-8] >> 4; + sc = (sc | (((y[i].scales[8 + j%4] >> (2*(j/4))) & 3) << 4)) - 32; + float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) { + continue; + } + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int(x[16*j + ii]/d); + l = MAX(-4, MIN(3, l)); + L[16*j + ii] = l + 4; + } + } + + memset(y[i].hmask, 0, QK_K/8); + // We put the high-bit for the 1st 8 quants into bit 0, the next 8 into bit 1, etc. + int m = 0; + uint8_t hm = 1; + for (int j = 0; j < QK_K; ++j) { + if (L[j] > 3) { + y[i].hmask[m] |= hm; + L[j] -= 4; + } + if (++m == QK_K/8) { + m = 0; hm <<= 1; + } + } + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6); + } + } + + x += QK_K; + } +} + +void dequantize_row_q3_K(const block_q3_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + const uint32_t kmask1 = 0x03030303; + const uint32_t kmask2 = 0x0f0f0f0f; + + uint32_t aux[4]; + const int8_t * scales = (const int8_t*)aux; + + for (int i = 0; i < nb; i++) { + + const float d_all = GGML_FP16_TO_FP32(x[i].d); + + const uint8_t * GGML_RESTRICT q = x[i].qs; + const uint8_t * GGML_RESTRICT hm = x[i].hmask; + uint8_t m = 1; + + memcpy(aux, x[i].scales, 12); + uint32_t tmp = aux[2]; + aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); + aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); + aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); + aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); + + int is = 0; + float dl; + for (int n = 0; n < QK_K; n += 128) { + int shift = 0; + for (int j = 0; j < 4; ++j) { + + dl = d_all * (scales[is++] - 32); + for (int l = 0; l < 16; ++l) { + *y++ = dl * ((int8_t)((q[l+ 0] >> shift) & 3) - ((hm[l+ 0] & m) ? 0 : 4)); + } + + dl = d_all * (scales[is++] - 32); + for (int l = 0; l < 16; ++l) { + *y++ = dl * ((int8_t)((q[l+16] >> shift) & 3) - ((hm[l+16] & m) ? 0 : 4)); + } + + shift += 2; + m <<= 1; + } + q += 32; + } + + } +} + +static void quantize_row_q3_K_impl(const float * GGML_RESTRICT x, block_q3_K * GGML_RESTRICT y, int64_t n_per_row, const float * GGML_RESTRICT quant_weights) { + assert(n_per_row % QK_K == 0); + const int nb = n_per_row / QK_K; + + int8_t L[QK_K]; + float scales[QK_K / 16]; + float weight[16]; + float sw[QK_K / 16]; + int8_t Ls[QK_K / 16]; + + for (int i = 0; i < nb; i++) { + + float sumx2 = 0; + for (int j = 0; j < QK_K; ++j) sumx2 += x[j]*x[j]; + float sigma2 = 2*sumx2/QK_K; + + for (int j = 0; j < QK_K/16; ++j) { + if (quant_weights) { + const float * qw = quant_weights + QK_K * i + 16*j; + for (int l = 0; l < 16; ++l) weight[l] = qw[l] * sqrtf(sigma2 + x[16*j+l]*x[16*j+l]); + } else { + for (int l = 0; l < 16; ++l) weight[l] = x[16*j+l]*x[16*j+l]; + } + float sumw = 0; + for (int l = 0; l < 16; ++l) sumw += weight[l]; + sw[j] = sumw; + + scales[j] = make_qx_quants(16, 4, x + 16*j, L + 16*j, 1, weight); + + } + + memset(y[i].scales, 0, 12); + + float d_block = make_qx_quants(QK_K/16, 32, scales, Ls, 1, sw); + for (int j = 0; j < QK_K/16; ++j) { + int l = Ls[j]; + if (j < 8) { + y[i].scales[j] = l & 0xF; + } else { + y[i].scales[j-8] |= ((l & 0xF) << 4); + } + l >>= 4; + y[i].scales[j%4 + 8] |= (l << (2*(j/4))); + } + y[i].d = GGML_FP32_TO_FP16(d_block); + + int8_t sc; + for (int j = 0; j < QK_K/16; ++j) { + sc = j < 8 ? y[i].scales[j] & 0xF : y[i].scales[j-8] >> 4; + sc = (sc | (((y[i].scales[8 + j%4] >> (2*(j/4))) & 3) << 4)) - 32; + float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) { + continue; + } + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int(x[16*j + ii]/d); + l = MAX(-4, MIN(3, l)); + L[16*j + ii] = l + 4; + } + } + + memset(y[i].hmask, 0, QK_K/8); + // We put the high-bit for the 1st 8 quants into bit 0, the next 8 into bit 1, etc. + int m = 0; + uint8_t hm = 1; + for (int j = 0; j < QK_K; ++j) { + if (L[j] > 3) { + y[i].hmask[m] |= hm; + L[j] -= 4; + } + if (++m == QK_K/8) { + m = 0; hm <<= 1; + } + } + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + y[i].qs[j/4 + l] = L[j + l] | (L[j + l + 32] << 2) | (L[j + l + 64] << 4) | (L[j + l + 96] << 6); + } + } + + x += QK_K; + } +} + +size_t quantize_q3_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + size_t row_size = ggml_row_size(GGML_TYPE_Q3_K, n_per_row); + if (!quant_weights) { + quantize_row_q3_K_ref(src, dst, (int64_t)nrow*n_per_row); + } + else { + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q3_K_impl(src, (block_q3_K*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + } + return nrow * row_size; +} + +// ====================== 4-bit (de)-quantization + +void quantize_row_q4_K_ref(const float * GGML_RESTRICT x, block_q4_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + uint8_t L[QK_K]; + uint8_t Laux[32]; + float weights[32]; + float mins[QK_K/32]; + float scales[QK_K/32]; + + for (int i = 0; i < nb; i++) { + float max_scale = 0; // as we are deducting the min, scales are always positive + float max_min = 0; + for (int j = 0; j < QK_K/32; ++j) { + //scales[j] = make_qkx1_quants(32, 15, x + 32*j, L + 32*j, &mins[j], 9, 0.5f); + float sum_x2 = 0; + for (int l = 0; l < 32; ++l) sum_x2 += x[32*j + l] * x[32*j + l]; + float av_x = sqrtf(sum_x2/32); + for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]); + scales[j] = make_qkx2_quants(32, 15, x + 32*j, weights, L + 32*j, &mins[j], Laux, -1.f, 0.1f, 20, false); + float scale = scales[j]; + if (scale > max_scale) { + max_scale = scale; + } + float min = mins[j]; + if (min > max_min) { + max_min = min; + } + } + + float inv_scale = max_scale > 0 ? 63.f/max_scale : 0.f; + float inv_min = max_min > 0 ? 63.f/max_min : 0.f; + for (int j = 0; j < QK_K/32; ++j) { + uint8_t ls = nearest_int(inv_scale*scales[j]); + uint8_t lm = nearest_int(inv_min*mins[j]); + ls = MIN(63, ls); + lm = MIN(63, lm); + if (j < 4) { + y[i].scales[j] = ls; + y[i].scales[j+4] = lm; + } else { + y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4); + y[i].scales[j-4] |= ((ls >> 4) << 6); + y[i].scales[j-0] |= ((lm >> 4) << 6); + } + } + y[i].d = GGML_FP32_TO_FP16(max_scale/63.f); + y[i].dmin = GGML_FP32_TO_FP16(max_min/63.f); + + uint8_t sc, m; + for (int j = 0; j < QK_K/32; ++j) { + get_scale_min_k4(j, y[i].scales, &sc, &m); + const float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) continue; + const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m; + for (int ii = 0; ii < 32; ++ii) { + int l = nearest_int((x[32*j + ii] + dm)/d); + l = MAX(0, MIN(15, l)); + L[32*j + ii] = l; + } + } + + uint8_t * q = y[i].qs; + for (int j = 0; j < QK_K; j += 64) { + for (int l = 0; l < 32; ++l) q[l] = L[j + l] | (L[j + l + 32] << 4); + q += 32; + } + + x += QK_K; + } +} + +void dequantize_row_q4_K(const block_q4_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + const uint8_t * q = x[i].qs; + + const float d = GGML_FP16_TO_FP32(x[i].d); + const float min = GGML_FP16_TO_FP32(x[i].dmin); + + int is = 0; + uint8_t sc, m; + for (int j = 0; j < QK_K; j += 64) { + get_scale_min_k4(is + 0, x[i].scales, &sc, &m); + const float d1 = d * sc; const float m1 = min * m; + get_scale_min_k4(is + 1, x[i].scales, &sc, &m); + const float d2 = d * sc; const float m2 = min * m; + for (int l = 0; l < 32; ++l) *y++ = d1 * (q[l] & 0xF) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * (q[l] >> 4) - m2; + q += 32; is += 2; + } + } +} + +static void quantize_row_q4_K_impl(const float * GGML_RESTRICT x, block_q4_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + assert(n_per_row % QK_K == 0); + const int64_t nb = n_per_row / QK_K; + + uint8_t L[QK_K]; + uint8_t Laux[32]; + uint8_t Ls[QK_K/32]; + uint8_t Lm[QK_K/32]; + float weights[32]; + float sw[QK_K/32]; + float mins[QK_K/32]; + float scales[QK_K/32]; + + for (int i = 0; i < nb; i++) { + + float sum_x2 = 0; + for (int l = 0; l < QK_K; ++l) sum_x2 += x[l] * x[l]; + float sigma2 = 2*sum_x2/QK_K; + float av_x = sqrtf(sigma2); + + for (int j = 0; j < QK_K/32; ++j) { + if (quant_weights) { + const float * qw = quant_weights + QK_K*i + 32*j; + for (int l = 0; l < 32; ++l) weights[l] = qw[l] * sqrtf(sigma2 + x[32*j + l]*x[32*j + l]); + } else { + for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]); + } + float sumw = 0; + for (int l = 0; l < 32; ++l) sumw += weights[l]; + sw[j] = sumw; + scales[j] = make_qkx3_quants(32, 15, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.9f, 0.05f, 36, false); + } + + float d_block = make_qp_quants(QK_K/32, 63, scales, Ls, sw); + float m_block = make_qp_quants(QK_K/32, 63, mins, Lm, sw); + for (int j = 0; j < QK_K/32; ++j) { + uint8_t ls = Ls[j]; + uint8_t lm = Lm[j]; + if (j < 4) { + y[i].scales[j] = ls; + y[i].scales[j+4] = lm; + } else { + y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4); + y[i].scales[j-4] |= ((ls >> 4) << 6); + y[i].scales[j-0] |= ((lm >> 4) << 6); + } + } + y[i].d = GGML_FP32_TO_FP16(d_block); + y[i].dmin = GGML_FP32_TO_FP16(m_block); + + uint8_t sc, m; + for (int j = 0; j < QK_K/32; ++j) { + get_scale_min_k4(j, y[i].scales, &sc, &m); + const float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) continue; + const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m; + for (int ii = 0; ii < 32; ++ii) { + int l = nearest_int((x[32*j + ii] + dm)/d); + l = MAX(0, MIN(15, l)); + L[32*j + ii] = l; + } + } + uint8_t * q = y[i].qs; + for (int j = 0; j < QK_K; j += 64) { + for (int l = 0; l < 32; ++l) q[l] = L[j + l] | (L[j + l + 32] << 4); + q += 32; + } + + x += QK_K; + + } +} + +size_t quantize_q4_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + size_t row_size = ggml_row_size(GGML_TYPE_Q4_K, n_per_row); + if (!quant_weights) { + quantize_row_q4_K_ref(src, dst, (int64_t)nrow*n_per_row); + } + else { + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q4_K_impl(src, (block_q4_K*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + } + return nrow * row_size; +} + +// ====================== 5-bit (de)-quantization + +void quantize_row_q5_K_ref(const float * GGML_RESTRICT x, block_q5_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + uint8_t L[QK_K]; + float mins[QK_K/32]; + float scales[QK_K/32]; + float weights[32]; + uint8_t Laux[32]; + + for (int i = 0; i < nb; i++) { + float max_scale = 0; // as we are deducting the min, scales are always positive + float max_min = 0; + for (int j = 0; j < QK_K/32; ++j) { + //scales[j] = make_qkx1_quants(32, 31, x + 32*j, L + 32*j, &mins[j], 9, 0.5f); + float sum_x2 = 0; + for (int l = 0; l < 32; ++l) sum_x2 += x[32*j + l] * x[32*j + l]; + float av_x = sqrtf(sum_x2/32); + for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]); + scales[j] = make_qkx2_quants(32, 31, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.5f, 0.1f, 15, false); + float scale = scales[j]; + if (scale > max_scale) { + max_scale = scale; + } + float min = mins[j]; + if (min > max_min) { + max_min = min; + } + } + + float inv_scale = max_scale > 0 ? 63.f/max_scale : 0.f; + float inv_min = max_min > 0 ? 63.f/max_min : 0.f; + for (int j = 0; j < QK_K/32; ++j) { + uint8_t ls = nearest_int(inv_scale*scales[j]); + uint8_t lm = nearest_int(inv_min*mins[j]); + ls = MIN(63, ls); + lm = MIN(63, lm); + if (j < 4) { + y[i].scales[j] = ls; + y[i].scales[j+4] = lm; + } else { + y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4); + y[i].scales[j-4] |= ((ls >> 4) << 6); + y[i].scales[j-0] |= ((lm >> 4) << 6); + } + } + y[i].d = GGML_FP32_TO_FP16(max_scale/63.f); + y[i].dmin = GGML_FP32_TO_FP16(max_min/63.f); + + uint8_t sc, m; + for (int j = 0; j < QK_K/32; ++j) { + get_scale_min_k4(j, y[i].scales, &sc, &m); + const float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) continue; + const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m; + for (int ii = 0; ii < 32; ++ii) { + int l = nearest_int((x[32*j + ii] + dm)/d); + l = MAX(0, MIN(31, l)); + L[32*j + ii] = l; + } + } + + uint8_t * GGML_RESTRICT qh = y[i].qh; + uint8_t * GGML_RESTRICT ql = y[i].qs; + memset(qh, 0, QK_K/8); + + uint8_t m1 = 1, m2 = 2; + for (int n = 0; n < QK_K; n += 64) { + for (int j = 0; j < 32; ++j) { + int l1 = L[n + j]; + if (l1 > 15) { + l1 -= 16; qh[j] |= m1; + } + int l2 = L[n + j + 32]; + if (l2 > 15) { + l2 -= 16; qh[j] |= m2; + } + ql[j] = l1 | (l2 << 4); + } + m1 <<= 2; m2 <<= 2; + ql += 32; + } + + x += QK_K; + } +} + +void dequantize_row_q5_K(const block_q5_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + const uint8_t * ql = x[i].qs; + const uint8_t * qh = x[i].qh; + + const float d = GGML_FP16_TO_FP32(x[i].d); + const float min = GGML_FP16_TO_FP32(x[i].dmin); + + int is = 0; + uint8_t sc, m; + uint8_t u1 = 1, u2 = 2; + for (int j = 0; j < QK_K; j += 64) { + get_scale_min_k4(is + 0, x[i].scales, &sc, &m); + const float d1 = d * sc; const float m1 = min * m; + get_scale_min_k4(is + 1, x[i].scales, &sc, &m); + const float d2 = d * sc; const float m2 = min * m; + for (int l = 0; l < 32; ++l) *y++ = d1 * ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * ((ql[l] >> 4) + (qh[l] & u2 ? 16 : 0)) - m2; + ql += 32; is += 2; + u1 <<= 2; u2 <<= 2; + } + } +} + +static void quantize_row_q5_K_impl(const float * GGML_RESTRICT x, block_q5_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + assert(n_per_row % QK_K == 0); + const int64_t nb = n_per_row / QK_K; + + uint8_t L[QK_K]; + uint8_t Laux[32]; + uint8_t Ls[QK_K/32]; + uint8_t Lm[QK_K/32]; + float mins[QK_K/32]; + float scales[QK_K/32]; + float sw[QK_K/32]; + float weights[32]; + + for (int i = 0; i < nb; i++) { + + float sum_x2 = 0; + for (int l = 0; l < QK_K; ++l) sum_x2 += x[l] * x[l]; + float sigma2 = 2*sum_x2/QK_K; + float av_x = sqrtf(sigma2); + + for (int j = 0; j < QK_K/32; ++j) { + if (quant_weights) { + const float * qw = quant_weights + QK_K*i + 32*j; + for (int l = 0; l < 32; ++l) weights[l] = qw[l] * sqrtf(sigma2 + x[32*j + l]*x[32*j + l]); + } else { + for (int l = 0; l < 32; ++l) weights[l] = av_x + fabsf(x[32*j + l]); + } + float sumw = 0; + for (int l = 0; l < 32; ++l) sumw += weights[l]; + sw[j] = sumw; + + scales[j] = make_qkx3_quants(32, 31, x + 32*j, weights, L + 32*j, &mins[j], Laux, -0.9f, 0.05f, 36, false); + } + + float d_block = make_qp_quants(QK_K/32, 63, scales, Ls, sw); + float m_block = make_qp_quants(QK_K/32, 63, mins, Lm, sw); + + for (int j = 0; j < QK_K/32; ++j) { + uint8_t ls = Ls[j]; + uint8_t lm = Lm[j]; + ls = MIN(63, ls); + lm = MIN(63, lm); + if (j < 4) { + y[i].scales[j] = ls; + y[i].scales[j+4] = lm; + } else { + y[i].scales[j+4] = (ls & 0xF) | ((lm & 0xF) << 4); + y[i].scales[j-4] |= ((ls >> 4) << 6); + y[i].scales[j-0] |= ((lm >> 4) << 6); + } + } + y[i].d = GGML_FP32_TO_FP16(d_block); + y[i].dmin = GGML_FP32_TO_FP16(m_block); + + uint8_t sc, m; + for (int j = 0; j < QK_K/32; ++j) { + get_scale_min_k4(j, y[i].scales, &sc, &m); + const float d = GGML_FP16_TO_FP32(y[i].d) * sc; + if (!d) continue; + const float dm = GGML_FP16_TO_FP32(y[i].dmin) * m; + for (int ii = 0; ii < 32; ++ii) { + int l = nearest_int((x[32*j + ii] + dm)/d); + l = MAX(0, MIN(31, l)); + L[32*j + ii] = l; + } + } + + uint8_t * GGML_RESTRICT qh = y[i].qh; + uint8_t * GGML_RESTRICT ql = y[i].qs; + memset(qh, 0, QK_K/8); + + uint8_t m1 = 1, m2 = 2; + for (int n = 0; n < QK_K; n += 64) { + for (int j = 0; j < 32; ++j) { + int l1 = L[n + j]; + if (l1 > 15) { + l1 -= 16; qh[j] |= m1; + } + int l2 = L[n + j + 32]; + if (l2 > 15) { + l2 -= 16; qh[j] |= m2; + } + ql[j] = l1 | (l2 << 4); + } + m1 <<= 2; m2 <<= 2; + ql += 32; + } + + x += QK_K; + + } +} + +size_t quantize_q5_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + size_t row_size = ggml_row_size(GGML_TYPE_Q5_K, n_per_row); + if (!quant_weights) { + quantize_row_q5_K_ref(src, dst, (int64_t)nrow*n_per_row); + } + else { + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q5_K_impl(src, (block_q5_K*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + } + return nrow * row_size; +} + +// ====================== 6-bit (de)-quantization + +void quantize_row_q6_K_ref(const float * GGML_RESTRICT x, block_q6_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + int8_t L[QK_K]; + float scales[QK_K/16]; + + for (int i = 0; i < nb; i++) { + + float max_scale = 0; + float max_abs_scale = 0; + + for (int ib = 0; ib < QK_K/16; ++ib) { + + const float scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, NULL); + scales[ib] = scale; + + const float abs_scale = fabsf(scale); + if (abs_scale > max_abs_scale) { + max_abs_scale = abs_scale; + max_scale = scale; + } + + } + + if (max_abs_scale < GROUP_MAX_EPS) { + memset(&y[i], 0, sizeof(block_q6_K)); + y[i].d = GGML_FP32_TO_FP16(0.f); + x += QK_K; + continue; + } + + float iscale = -128.f/max_scale; + y[i].d = GGML_FP32_TO_FP16(1/iscale); + for (int ib = 0; ib < QK_K/16; ++ib) { + y[i].scales[ib] = MIN(127, nearest_int(iscale*scales[ib])); + } + + for (int j = 0; j < QK_K/16; ++j) { + float d = GGML_FP16_TO_FP32(y[i].d) * y[i].scales[j]; + if (!d) { + continue; + } + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int(x[16*j + ii]/d); + l = MAX(-32, MIN(31, l)); + L[16*j + ii] = l + 32; + } + } + + uint8_t * GGML_RESTRICT ql = y[i].ql; + uint8_t * GGML_RESTRICT qh = y[i].qh; + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + const uint8_t q1 = L[j + l + 0] & 0xF; + const uint8_t q2 = L[j + l + 32] & 0xF; + const uint8_t q3 = L[j + l + 64] & 0xF; + const uint8_t q4 = L[j + l + 96] & 0xF; + ql[l+ 0] = q1 | (q3 << 4); + ql[l+32] = q2 | (q4 << 4); + qh[l] = (L[j + l] >> 4) | ((L[j + l + 32] >> 4) << 2) | ((L[j + l + 64] >> 4) << 4) | ((L[j + l + 96] >> 4) << 6); + } + ql += 64; + qh += 32; + } + + x += QK_K; + } +} + +void dequantize_row_q6_K(const block_q6_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + const float d = GGML_FP16_TO_FP32(x[i].d); + + const uint8_t * GGML_RESTRICT ql = x[i].ql; + const uint8_t * GGML_RESTRICT qh = x[i].qh; + const int8_t * GGML_RESTRICT sc = x[i].scales; + + for (int n = 0; n < QK_K; n += 128) { + for (int l = 0; l < 32; ++l) { + int is = l/16; + const int8_t q1 = (int8_t)((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32; + const int8_t q2 = (int8_t)((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32; + const int8_t q3 = (int8_t)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32; + const int8_t q4 = (int8_t)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32; + y[l + 0] = d * sc[is + 0] * q1; + y[l + 32] = d * sc[is + 2] * q2; + y[l + 64] = d * sc[is + 4] * q3; + y[l + 96] = d * sc[is + 6] * q4; + } + y += 128; + ql += 64; + qh += 32; + sc += 8; + } + } +} + +static void quantize_row_q6_K_impl(const float * GGML_RESTRICT x, block_q6_K * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + assert(n_per_row % QK_K == 0); + const int64_t nb = n_per_row / QK_K; + + int8_t L[QK_K]; + float scales[QK_K/16]; + //float weights[16]; + + for (int i = 0; i < nb; i++) { + + //float sum_x2 = 0; + //for (int j = 0; j < QK_K; ++j) sum_x2 += x[j]*x[j]; + //float sigma2 = sum_x2/QK_K; + + float max_scale = 0; + float max_abs_scale = 0; + + for (int ib = 0; ib < QK_K/16; ++ib) { + + float scale; + if (quant_weights) { + const float * qw = quant_weights + QK_K*i + 16*ib; + //for (int j = 0; j < 16; ++j) weights[j] = qw[j] * sqrtf(sigma2 + x[16*ib + j]*x[16*ib + j]); + //scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, weights); + scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, qw); + } else { + scale = make_qx_quants(16, 32, x + 16*ib, L + 16*ib, 1, NULL); + } + scales[ib] = scale; + + const float abs_scale = fabsf(scale); + if (abs_scale > max_abs_scale) { + max_abs_scale = abs_scale; + max_scale = scale; + } + + } + + if (max_abs_scale < GROUP_MAX_EPS) { + memset(&y[i], 0, sizeof(block_q6_K)); + y[i].d = GGML_FP32_TO_FP16(0.f); + x += QK_K; + continue; + } + + float iscale = -128.f/max_scale; + y[i].d = GGML_FP32_TO_FP16(1/iscale); + for (int ib = 0; ib < QK_K/16; ++ib) { + y[i].scales[ib] = MIN(127, nearest_int(iscale*scales[ib])); + } + + for (int j = 0; j < QK_K/16; ++j) { + float d = GGML_FP16_TO_FP32(y[i].d) * y[i].scales[j]; + if (!d) { + continue; + } + for (int ii = 0; ii < 16; ++ii) { + int l = nearest_int(x[16*j + ii]/d); + l = MAX(-32, MIN(31, l)); + L[16*j + ii] = l + 32; + } + } + + uint8_t * GGML_RESTRICT ql = y[i].ql; + uint8_t * GGML_RESTRICT qh = y[i].qh; + for (int j = 0; j < QK_K; j += 128) { + for (int l = 0; l < 32; ++l) { + const uint8_t q1 = L[j + l + 0] & 0xF; + const uint8_t q2 = L[j + l + 32] & 0xF; + const uint8_t q3 = L[j + l + 64] & 0xF; + const uint8_t q4 = L[j + l + 96] & 0xF; + ql[l+ 0] = q1 | (q3 << 4); + ql[l+32] = q2 | (q4 << 4); + qh[l] = (L[j + l] >> 4) | ((L[j + l + 32] >> 4) << 2) | ((L[j + l + 64] >> 4) << 4) | ((L[j + l + 96] >> 4) << 6); + } + ql += 64; + qh += 32; + } + + x += QK_K; + + } +} + +size_t quantize_q6_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + size_t row_size = ggml_row_size(GGML_TYPE_Q6_K, n_per_row); + if (!quant_weights) { + quantize_row_q6_K_ref(src, dst, (int64_t)nrow*n_per_row); + } + else { + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q6_K_impl(src, (block_q6_K*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + } + return nrow * row_size; +} + +static void quantize_row_q4_0_impl(const float * GGML_RESTRICT x, block_q4_0 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + static_assert(QK4_0 == 32, "QK4_0 must be 32"); + + if (!quant_weights) { + quantize_row_q4_0_ref(x, y, n_per_row); + return; + } + + float weight[QK4_0]; + int8_t L[QK4_0]; + + float sum_x2 = 0; + for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j]; + float sigma2 = sum_x2/n_per_row; + + const int64_t nb = n_per_row/QK4_0; + for (int ib = 0; ib < nb; ++ib) { + const float * xb = x + QK4_0 * ib; + const float * qw = quant_weights + QK4_0 * ib; + for (int j = 0; j < QK4_0; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]); + float d = make_qx_quants(QK4_0, 8, xb, L, 1, weight); + y[ib].d = GGML_FP32_TO_FP16(d); + for (int j = 0; j < 16; ++j) { + y[ib].qs[j] = L[j] | (L[j+16] << 4); + } + } +} + +size_t quantize_q1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q1_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q1_0, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q1_0, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q1_0_ref(src, (block_q1_0*)qrow, n_per_row); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +size_t quantize_q2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q2_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q2_0, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q2_0, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q2_0_ref(src, (block_q2_0*)qrow, n_per_row); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +size_t quantize_q4_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q4_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q4_0, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q4_0, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q4_0_impl(src, (block_q4_0*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +static void quantize_row_q4_1_impl(const float * GGML_RESTRICT x, block_q4_1 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + static_assert(QK4_1 == 32, "QK4_1 must be 32"); + + if (!quant_weights) { + quantize_row_q4_1_ref(x, y, n_per_row); + return; + } + + float weight[QK4_1]; + uint8_t L[QK4_1], Laux[QK4_1]; + + float sum_x2 = 0; + for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j]; + float sigma2 = sum_x2/n_per_row; + + const int64_t nb = n_per_row/QK4_1; + for (int ib = 0; ib < nb; ++ib) { + const float * xb = x + QK4_1 * ib; + const float * qw = quant_weights + QK4_1 * ib; + for (int j = 0; j < QK4_1; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]); + float min; + float d = make_qkx3_quants(QK4_1, 15, xb, weight, L, &min, Laux, -0.9f, 0.05f, 36, false); + y[ib].d = GGML_FP32_TO_FP16(d); + y[ib].m = GGML_FP32_TO_FP16(-min); + for (int j = 0; j < 16; ++j) { + y[ib].qs[j] = L[j] | (L[j+16] << 4); + } + } +} + +size_t quantize_q4_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q4_1_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q4_1, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q4_1, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q4_1_impl(src, (block_q4_1*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +static void quantize_row_q5_0_impl(const float * GGML_RESTRICT x, block_q5_0 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + static_assert(QK5_0 == 32, "QK5_0 must be 32"); + + if (!quant_weights) { + quantize_row_q5_0_ref(x, y, n_per_row); + return; + } + + float weight[QK5_0]; + int8_t L[QK5_0]; + + float sum_x2 = 0; + for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j]; + float sigma2 = sum_x2/n_per_row; + + const int64_t nb = n_per_row/QK5_0; + for (int ib = 0; ib < nb; ++ib) { + const float * xb = x + QK5_0 * ib; + const float * qw = quant_weights + QK5_0 * ib; + for (int j = 0; j < QK5_0; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]); + float d = make_qx_quants(QK5_0, 16, xb, L, 1, weight); + y[ib].d = GGML_FP32_TO_FP16(d); + + uint32_t qh = 0; + + for (int j = 0; j < 16; ++j) { + const uint8_t xi0 = L[j]; + const uint8_t xi1 = L[j+16]; + y[ib].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4); + + // get the 5-th bit and store it in qh at the right position + qh |= ((xi0 & 0x10u) >> 4) << (j + 0); + qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2); + } + + memcpy(&y[ib].qh, &qh, sizeof(qh)); + } +} + +size_t quantize_q5_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q5_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q5_0, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q5_0, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q5_0_impl(src, (block_q5_0*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +static void quantize_row_q5_1_impl(const float * GGML_RESTRICT x, block_q5_1 * GGML_RESTRICT y, int64_t n_per_row, const float * quant_weights) { + static_assert(QK5_1 == 32, "QK5_1 must be 32"); + + if (!quant_weights) { + quantize_row_q5_1_ref(x, y, n_per_row); + return; + } + + float weight[QK5_1]; + uint8_t L[QK5_1], Laux[QK5_1]; + + float sum_x2 = 0; + for (int j = 0; j < n_per_row; ++j) sum_x2 += x[j]*x[j]; + float sigma2 = sum_x2/n_per_row; + + const int64_t nb = n_per_row/QK5_1; + for (int ib = 0; ib < nb; ++ib) { + const float * xb = x + QK5_1 * ib; + const float * qw = quant_weights + QK5_1 * ib; + for (int j = 0; j < QK5_1; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]); + float min; + float d = make_qkx3_quants(QK5_1, 31, xb, weight, L, &min, Laux, -0.9f, 0.05f, 36, false); + y[ib].d = GGML_FP32_TO_FP16(d); + y[ib].m = GGML_FP32_TO_FP16(-min); + + uint32_t qh = 0; + for (int j = 0; j < 16; ++j) { + const uint8_t xi0 = L[j]; + const uint8_t xi1 = L[j+16]; + y[ib].qs[j] = (xi0 & 0x0F) | ((xi1 & 0x0F) << 4); + // get the 5-th bit and store it in qh at the right position + qh |= ((xi0 & 0x10u) >> 4) << (j + 0); + qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2); + } + memcpy(&y[ib].qh, &qh, sizeof(qh)); + } +} + +size_t quantize_q5_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + if (!quant_weights) { + quantize_row_q5_1_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_Q5_1, n_per_row); + } + size_t row_size = ggml_row_size(GGML_TYPE_Q5_1, n_per_row); + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_q5_1_impl(src, (block_q5_1*)qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += row_size; + } + return nrow * row_size; +} + +size_t quantize_q8_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + (void)quant_weights; // not used + const size_t row_size = ggml_row_size(GGML_TYPE_Q8_0, n_per_row); + quantize_row_q8_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * row_size; +} + +size_t quantize_mxfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_UNUSED(quant_weights); + quantize_row_mxfp4_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_MXFP4, n_per_row); +} + +size_t quantize_nvfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_UNUSED(quant_weights); + quantize_row_nvfp4_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * ggml_row_size(GGML_TYPE_NVFP4, n_per_row); +} + +// ====================== Ternary (de)-quantization (BitNet b1.58 and TriLMs) + +void quantize_row_tq1_0_ref(const float * GGML_RESTRICT x, block_tq1_0 * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int64_t i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + + for (int j = 0; j < QK_K; j++) { + const float v = x[j]; + amax = MAX(amax, fabsf(v)); + } + + const float d = amax; + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + // 5 elements per byte, along 32 bytes + for (size_t j = 0; j < sizeof(y->qs) - sizeof(y->qs) % 32; j += 32) { + for (size_t m = 0; m < 32; ++m) { + uint8_t q = 0; + for (size_t n = 0; n < 5; ++n) { + int xi = lroundf(x[m + n*32] * id) + 1; // -1, 0, 1 -> 0, 1, 2 + q *= 3; + q += xi; + } + // ceiling division (243 == pow(3, 5)) + q = ((uint16_t)q * 256 + (243 - 1)) / 243; + y[i].qs[j + m] = q; + } + x += 5*32; + } + // along 16 bytes + for (size_t j = sizeof(y->qs) - sizeof(y->qs) % 32; j < sizeof(y->qs); j += 16) { + for (size_t m = 0; m < 16; ++m) { + uint8_t q = 0; + for (size_t n = 0; n < 5; ++n) { + int xi = lroundf(x[m + n*16] * id) + 1; // -1, 0, 1 -> 0, 1, 2 + q *= 3; + q += xi; + } + // ceiling division (243 == pow(3, 5)) + q = ((uint16_t)q * 256 + (243 - 1)) / 243; + y[i].qs[j + m] = q; + } + x += 5*16; + } + // 4 elements per byte + for (size_t j = 0; j < sizeof(y->qh); ++j) { + uint8_t q = 0; + for (size_t m = 0; m < 4; ++m) { + // -1, 0, 1 -> 0, 1, 2 + int xi = lroundf(x[j + m*sizeof(y->qh)] * id) + 1; + q *= 3; + q += xi; + } + // shift the first value to the most significant trit + q *= 3; + // ceiling division (243 == pow(3, 5)) + q = ((uint16_t)q * 256 + (243 - 1)) / 243; + y[i].qh[j] = q; + } + x += 4*sizeof(y->qh); + } +} + +void quantize_row_tq2_0_ref(const float * GGML_RESTRICT x, block_tq2_0 * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int64_t i = 0; i < nb; i++) { + float amax = 0.0f; // absolute max + + for (int j = 0; j < QK_K; j++) { + const float v = x[j]; + amax = MAX(amax, fabsf(v)); + } + + const float d = amax; + const float id = d ? 1.0f/d : 0.0f; + + y[i].d = GGML_FP32_TO_FP16(d); + + for (size_t j = 0; j < sizeof(y->qs); j += 32) { + for (size_t m = 0; m < 32; ++m) { + uint8_t q = 0; + for (size_t n = 0; n < 4; ++n) { + // -1, 0, 1 -> 0, 1, 2 + int xi = lroundf(x[m + n*32] * id) + 1; + q += (xi & 3) << (2*n); + } + y[i].qs[j + m] = q; + } + x += 4*32; + } + } +} + +size_t quantize_tq1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + (void)quant_weights; // not used + const size_t row_size = ggml_row_size(GGML_TYPE_TQ1_0, n_per_row); + quantize_row_tq1_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * row_size; +} + +size_t quantize_tq2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + (void)quant_weights; // not used + const size_t row_size = ggml_row_size(GGML_TYPE_TQ2_0, n_per_row); + quantize_row_tq2_0_ref(src, dst, (int64_t)nrow*n_per_row); + return nrow * row_size; +} + +void dequantize_row_tq1_0(const block_tq1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + const uint8_t pow3[6] = {1, 3, 9, 27, 81, 243}; + + for (int64_t i = 0; i < nb; ++i) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (size_t j = 0; j < sizeof(x->qs) - sizeof(x->qs) % 32; j += 32) { + for (size_t n = 0; n < 5; ++n) { + for (size_t m = 0; m < 32; ++m) { + uint8_t q = x[i].qs[j + m] * pow3[n]; + int16_t xi = ((uint16_t) q * 3) >> 8; + *y++ = (float) (xi - 1) * d; + } + } + } + for (size_t j = sizeof(x->qs) - sizeof(x->qs) % 32; j < sizeof(x->qs); j += 16) { + for (size_t n = 0; n < 5; ++n) { + for (size_t m = 0; m < 16; ++m) { + uint8_t q = x[i].qs[j + m] * pow3[n]; + int16_t xi = ((uint16_t) q * 3) >> 8; + *y++ = (float) (xi - 1) * d; + } + } + } + + for (size_t n = 0; n < 4; ++n) { + for (size_t j = 0; j < sizeof(x->qh); ++j) { + uint8_t q = x[i].qh[j] * pow3[n]; + int16_t xi = ((uint16_t) q * 3) >> 8; + *y++ = (float) (xi - 1) * d; + } + } + } +} + +void dequantize_row_tq2_0(const block_tq2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int64_t i = 0; i < nb; ++i) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (size_t j = 0; j < sizeof(x->qs); j += 32) { + for (size_t l = 0; l < 4; ++l) { + for (size_t m = 0; m < 32; ++m) { + int8_t q = (x[i].qs[j + m] >> (l*2)) & 3; + *y++ = (float) (q - 1) * d; + } + } + } + } +} + +// ====================== "True" 2-bit (de)-quantization + +void dequantize_row_iq2_xxs(const block_iq2_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + uint32_t aux32[2]; + const uint8_t * aux8 = (const uint8_t *)aux32; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int ib32 = 0; ib32 < QK_K/32; ++ib32) { + memcpy(aux32, x[i].qs + 4*ib32, 2*sizeof(uint32_t)); + const float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const uint8_t * grid = (const uint8_t *)(iq2xxs_grid + aux8[l]); + const uint8_t signs = ksigns_iq2xs[(aux32[1] >> 7*l) & 127]; + for (int j = 0; j < 8; ++j) { + y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + } + y += 8; + } + } + } +} + +// ====================== 2.3125 bpw (de)-quantization + +void dequantize_row_iq2_xs(const block_iq2_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + float db[2]; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int ib32 = 0; ib32 < QK_K/32; ++ib32) { + db[0] = d * (0.5f + (x[i].scales[ib32] & 0xf)) * 0.25f; + db[1] = d * (0.5f + (x[i].scales[ib32] >> 4)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const uint8_t * grid = (const uint8_t *)(iq2xs_grid + (x[i].qs[4*ib32 + l] & 511)); + const uint8_t signs = ksigns_iq2xs[x[i].qs[4*ib32 + l] >> 9]; + for (int j = 0; j < 8; ++j) { + y[j] = db[l/2] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + } + y += 8; + } + } + } +} + +// ====================== 2.5625 bpw (de)-quantization + +void dequantize_row_iq2_s(const block_iq2_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + float db[2]; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + const uint8_t * qs = x[i].qs; + const uint8_t * qh = x[i].qh; + const uint8_t * signs = qs + QK_K/8; + + for (int ib32 = 0; ib32 < QK_K/32; ++ib32) { + db[0] = d * (0.5f + (x[i].scales[ib32] & 0xf)) * 0.25f; + db[1] = d * (0.5f + (x[i].scales[ib32] >> 4)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const float dl = db[l/2]; + const uint8_t * grid = (const uint8_t *)(iq2s_grid + (qs[l] | (qh[ib32] << (8-2*l) & 0x300))); + for (int j = 0; j < 8; ++j) { + y[j] = dl * grid[j] * (signs[l] & kmask_iq2xs[j] ? -1.f : 1.f); + } + y += 8; + } + qs += 4; + signs += 4; + } + } +} + +// ====================== 3.0625 bpw (de)-quantization + +void dequantize_row_iq3_xxs(const block_iq3_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + uint32_t aux32; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + const uint8_t * qs = x[i].qs; + const uint8_t * scales_and_signs = qs + QK_K/4; + + for (int ib32 = 0; ib32 < QK_K/32; ++ib32) { + memcpy(&aux32, scales_and_signs + 4*ib32, sizeof(uint32_t)); + const float db = d * (0.5f + (aux32 >> 28)) * 0.5f; + for (int l = 0; l < 4; ++l) { + const uint8_t signs = ksigns_iq2xs[(aux32 >> 7*l) & 127]; + const uint8_t * grid1 = (const uint8_t *)(iq3xxs_grid + qs[2*l+0]); + const uint8_t * grid2 = (const uint8_t *)(iq3xxs_grid + qs[2*l+1]); + for (int j = 0; j < 4; ++j) { + y[j+0] = db * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f); + y[j+4] = db * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f); + } + y += 8; + } + qs += 8; + } + } +} + +// ====================== 3.3125 bpw (de)-quantization + +void dequantize_row_iq3_s(const block_iq3_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + const uint8_t * qs = x[i].qs; + const uint8_t * qh = x[i].qh; + const uint8_t * signs = x[i].signs; + + for (int ib32 = 0; ib32 < QK_K/32; ib32 += 2) { + const float db1 = d * (1 + 2*(x[i].scales[ib32/2] & 0xf)); + const float db2 = d * (1 + 2*(x[i].scales[ib32/2] >> 4)); + for (int l = 0; l < 4; ++l) { + const uint8_t * grid1 = (const uint8_t *)(iq3s_grid + (qs[2*l+0] | ((qh[0] << (8-2*l)) & 256))); + const uint8_t * grid2 = (const uint8_t *)(iq3s_grid + (qs[2*l+1] | ((qh[0] << (7-2*l)) & 256))); + for (int j = 0; j < 4; ++j) { + y[j+0] = db1 * grid1[j] * (signs[l] & kmask_iq2xs[j+0] ? -1.f : 1.f); + y[j+4] = db1 * grid2[j] * (signs[l] & kmask_iq2xs[j+4] ? -1.f : 1.f); + } + y += 8; + } + qs += 8; + signs += 4; + for (int l = 0; l < 4; ++l) { + const uint8_t * grid1 = (const uint8_t *)(iq3s_grid + (qs[2*l+0] | ((qh[1] << (8-2*l)) & 256))); + const uint8_t * grid2 = (const uint8_t *)(iq3s_grid + (qs[2*l+1] | ((qh[1] << (7-2*l)) & 256))); + for (int j = 0; j < 4; ++j) { + y[j+0] = db2 * grid1[j] * (signs[l] & kmask_iq2xs[j+0] ? -1.f : 1.f); + y[j+4] = db2 * grid2[j] * (signs[l] & kmask_iq2xs[j+4] ? -1.f : 1.f); + } + y += 8; + } + qh += 2; + qs += 8; + signs += 4; + } + } +} + +// ====================== 1.5625 bpw (de)-quantization + +void dequantize_row_iq1_s(const block_iq1_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + + const float d = GGML_FP16_TO_FP32(x[i].d); + const uint8_t * qs = x[i].qs; + const uint16_t * qh = x[i].qh; + + for (int ib = 0; ib < QK_K/32; ++ib) { + const float dl = d * (2*((qh[ib] >> 12) & 7) + 1); + const float delta = qh[ib] & 0x8000 ? -IQ1S_DELTA : IQ1S_DELTA; + for (int l = 0; l < 4; ++l) { + const int8_t * grid = (const int8_t *)(iq1s_grid + (qs[l] | (((qh[ib] >> 3*l) & 7) << 8))); + for (int j = 0; j < 8; ++j) { + y[j] = dl * (grid[j] + delta); + } + y += 8; + } + qs += 4; + } + } +} + +void dequantize_row_iq1_m(const block_iq1_m * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + float delta[4]; + uint16_t idx[4]; + + iq1m_scale_t scale; + + for (int i = 0; i < nb; i++) { + + const uint16_t * sc = (const uint16_t *)x[i].scales; + scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); + const float d = GGML_FP16_TO_FP32(scale.f16); + + const uint8_t * qs = x[i].qs; + const uint8_t * qh = x[i].qh; + + for (int ib = 0; ib < QK_K/32; ++ib) { + const float dl1 = d * (2*((sc[ib/2] >> (6*(ib%2)+0)) & 0x7) + 1); + const float dl2 = d * (2*((sc[ib/2] >> (6*(ib%2)+3)) & 0x7) + 1); + + idx[0] = qs[0] | ((qh[0] << 8) & 0x700); + idx[1] = qs[1] | ((qh[0] << 4) & 0x700); + idx[2] = qs[2] | ((qh[1] << 8) & 0x700); + idx[3] = qs[3] | ((qh[1] << 4) & 0x700); + delta[0] = qh[0] & 0x08 ? -IQ1S_DELTA : IQ1S_DELTA; + delta[1] = qh[0] & 0x80 ? -IQ1S_DELTA : IQ1S_DELTA; + delta[2] = qh[1] & 0x08 ? -IQ1S_DELTA : IQ1S_DELTA; + delta[3] = qh[1] & 0x80 ? -IQ1S_DELTA : IQ1S_DELTA; + for (int l = 0; l < 2; ++l) { + const int8_t * grid = (const int8_t *)(iq1s_grid + idx[l]); + for (int j = 0; j < 8; ++j) { + y[j] = dl1 * (grid[j] + delta[l]); + } + y += 8; + } + for (int l = 2; l < 4; ++l) { + const int8_t * grid = (const int8_t *)(iq1s_grid + idx[l]); + for (int j = 0; j < 8; ++j) { + y[j] = dl2 * (grid[j] + delta[l]); + } + y += 8; + } + qs += 4; + qh += 2; + } + } +} + +void dequantize_row_iq4_nl(const block_iq4_nl * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK4_NL == 0); + const int64_t nb = k / QK4_NL; + + for (int i = 0; i < nb; i++) { + + const uint8_t * qs = x[i].qs; + + const float d = GGML_FP16_TO_FP32(x[i].d); + for (int j = 0; j < QK4_NL/2; ++j) { + y[j+ 0] = d * kvalues_iq4nl[qs[j] & 0xf]; + y[j+QK4_NL/2] = d * kvalues_iq4nl[qs[j] >> 4]; + } + y += QK4_NL; + qs += QK4_NL/2; + } +} + +void dequantize_row_iq4_xs(const block_iq4_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + + const uint8_t * qs = x[i].qs; + + const float d = GGML_FP16_TO_FP32(x[i].d); + + for (int ib = 0; ib < QK_K/32; ++ib) { + const int ls = ((x[i].scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((x[i].scales_h >> 2*ib) & 3) << 4); + const float dl = d * (ls - 32); + for (int j = 0; j < 16; ++j) { + y[j+ 0] = dl * kvalues_iq4nl[qs[j] & 0xf]; + y[j+16] = dl * kvalues_iq4nl[qs[j] >> 4]; + } + y += 32; + qs += 16; + } + } +} + +//===================================== Q8_K ============================================== + +void quantize_row_q8_K_ref(const float * GGML_RESTRICT x, block_q8_K * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + + float max = 0; + float amax = 0; + for (int j = 0; j < QK_K; ++j) { + float ax = fabsf(x[j]); + if (ax > amax) { + amax = ax; max = x[j]; + } + } + if (!amax) { + y[i].d = 0; + memset(y[i].qs, 0, QK_K); + x += QK_K; + continue; + } + //const float iscale = -128.f/max; + // We need this change for IQ2_XXS, else the AVX implementation becomes very awkward + const float iscale = -127.f/max; + for (int j = 0; j < QK_K; ++j) { + int v = nearest_int(iscale*x[j]); + y[i].qs[j] = MIN(127, v); + } + for (int j = 0; j < QK_K/16; ++j) { + int sum = 0; + for (int ii = 0; ii < 16; ++ii) { + sum += y[i].qs[j*16 + ii]; + } + y[i].bsums[j] = sum; + } + y[i].d = 1/iscale; + x += QK_K; + } +} + +void dequantize_row_q8_K(const block_q8_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + const int64_t nb = k / QK_K; + + for (int i = 0; i < nb; i++) { + for (int j = 0; j < QK_K; ++j) { + *y++ = x[i].d * x[i].qs[j]; + } + } +} + +// ================================ IQ2 quantization ============================================= + +typedef struct { + uint64_t * grid; + int * map; + uint16_t * neighbours; +} iq2_entry_t; + +static iq2_entry_t iq2_data[4] = { + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, +}; + +static inline int iq2_data_index(enum ggml_type type) { + GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S); + return type == GGML_TYPE_IQ2_XXS ? 0 : + type == GGML_TYPE_IQ2_XS ? 1 : + type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? 2 : 3; +} + +static inline int iq2_grid_size(enum ggml_type type) { + GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S); + return type == GGML_TYPE_IQ2_XXS ? 256 : + type == GGML_TYPE_IQ2_XS ? 512 : + type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? NGRID_IQ1S : 1024; +} + +static int iq2_compare_func(const void * left, const void * right) { + const int * l = (const int *)left; + const int * r = (const int *)right; + return l[0] < r[0] ? -1 : l[0] > r[0] ? 1 : l[1] < r[1] ? -1 : l[1] > r[1] ? 1 : 0; +} + +void iq2xs_init_impl(enum ggml_type type) { + const int gindex = iq2_data_index(type); + const int grid_size = iq2_grid_size(type); + if (iq2_data[gindex].grid) { + return; + } + static const uint16_t kgrid_2bit_256[256] = { + 0, 2, 5, 8, 10, 17, 20, 32, 34, 40, 42, 65, 68, 80, 88, 97, + 100, 128, 130, 138, 162, 257, 260, 272, 277, 320, 388, 408, 512, 514, 546, 642, + 1025, 1028, 1040, 1057, 1060, 1088, 1090, 1096, 1120, 1153, 1156, 1168, 1188, 1280, 1282, 1288, + 1312, 1350, 1385, 1408, 1425, 1545, 1552, 1600, 1668, 1700, 2048, 2053, 2056, 2068, 2088, 2113, + 2116, 2128, 2130, 2184, 2308, 2368, 2562, 2580, 4097, 4100, 4112, 4129, 4160, 4192, 4228, 4240, + 4245, 4352, 4360, 4384, 4432, 4442, 4480, 4644, 4677, 5120, 5128, 5152, 5157, 5193, 5248, 5400, + 5474, 5632, 5654, 6145, 6148, 6160, 6208, 6273, 6400, 6405, 6560, 6737, 8192, 8194, 8202, 8260, + 8289, 8320, 8322, 8489, 8520, 8704, 8706, 9217, 9220, 9232, 9280, 9302, 9472, 9537, 9572, 9872, + 10248, 10272, 10388, 10820, 16385, 16388, 16400, 16408, 16417, 16420, 16448, 16456, 16470, 16480, 16513, 16516, + 16528, 16640, 16672, 16737, 16768, 16773, 16897, 16912, 16968, 16982, 17000, 17408, 17416, 17440, 17536, 17561, + 17682, 17700, 17920, 18433, 18436, 18448, 18496, 18501, 18688, 18776, 18785, 18818, 19013, 19088, 20480, 20488, + 20497, 20505, 20512, 20608, 20616, 20740, 20802, 20900, 21137, 21648, 21650, 21770, 22017, 22100, 22528, 22545, + 22553, 22628, 22848, 23048, 24580, 24592, 24640, 24680, 24832, 24917, 25112, 25184, 25600, 25605, 25872, 25874, + 25988, 26690, 32768, 32770, 32778, 32833, 32898, 33028, 33048, 33088, 33297, 33793, 33796, 33808, 33813, 33856, + 33888, 34048, 34118, 34196, 34313, 34368, 34400, 34818, 35076, 35345, 36868, 36880, 36900, 36928, 37025, 37142, + 37248, 37445, 37888, 37922, 37956, 38225, 39041, 39200, 40962, 41040, 41093, 41225, 41472, 42008, 43088, 43268, + }; + static const uint16_t kgrid_2bit_512[512] = { + 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70, + 73, 80, 82, 85, 88, 97, 100, 128, 130, 133, 136, 145, 148, 153, 160, 257, + 260, 262, 265, 272, 274, 277, 280, 282, 289, 292, 320, 322, 325, 328, 337, 340, + 352, 360, 385, 388, 400, 512, 514, 517, 520, 529, 532, 544, 577, 580, 592, 597, + 640, 650, 1025, 1028, 1030, 1033, 1040, 1042, 1045, 1048, 1057, 1060, 1088, 1090, 1093, 1096, + 1105, 1108, 1110, 1120, 1153, 1156, 1168, 1280, 1282, 1285, 1288, 1297, 1300, 1312, 1345, 1348, + 1360, 1377, 1408, 1537, 1540, 1552, 1574, 1600, 1602, 1668, 2048, 2050, 2053, 2056, 2058, 2065, + 2068, 2080, 2085, 2113, 2116, 2128, 2136, 2176, 2208, 2218, 2305, 2308, 2320, 2368, 2433, 2441, + 2560, 2592, 2600, 2710, 2720, 4097, 4100, 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4160, + 4162, 4165, 4168, 4177, 4180, 4192, 4202, 4225, 4228, 4240, 4352, 4354, 4357, 4360, 4369, 4372, + 4384, 4417, 4420, 4432, 4480, 4500, 4502, 4609, 4612, 4614, 4624, 4672, 4704, 5120, 5122, 5125, + 5128, 5137, 5140, 5152, 5185, 5188, 5193, 5200, 5220, 5248, 5377, 5380, 5392, 5440, 5632, 5652, + 5705, 6145, 6148, 6160, 6162, 6208, 6228, 6278, 6400, 6405, 6502, 6737, 6825, 8192, 8194, 8197, + 8200, 8202, 8209, 8212, 8224, 8257, 8260, 8272, 8320, 8352, 8449, 8452, 8464, 8512, 8520, 8549, + 8704, 8738, 8832, 8872, 9217, 9220, 9232, 9257, 9280, 9472, 9537, 9554, 9625, 9729, 9754, 9894, + 10240, 10248, 10250, 10272, 10325, 10376, 10402, 10600, 10640, 10760, 10784, 10882, 10888, 10890, 16385, 16388, + 16390, 16393, 16400, 16402, 16405, 16408, 16417, 16420, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16480, + 16485, 16513, 16516, 16528, 16640, 16642, 16645, 16648, 16657, 16660, 16672, 16705, 16708, 16720, 16768, 16773, + 16802, 16897, 16900, 16912, 16914, 16937, 16960, 17408, 17410, 17413, 17416, 17425, 17428, 17433, 17440, 17473, + 17476, 17488, 17536, 17556, 17665, 17668, 17680, 17700, 17728, 17818, 17920, 17930, 17988, 18000, 18433, 18436, + 18448, 18496, 18501, 18516, 18530, 18688, 18705, 18756, 18768, 18793, 18948, 20480, 20482, 20485, 20488, 20497, + 20500, 20512, 20520, 20545, 20548, 20560, 20608, 20737, 20740, 20752, 20757, 20800, 20802, 20992, 21060, 21162, + 21505, 21508, 21520, 21537, 21568, 21600, 21633, 21665, 21760, 21768, 21888, 21896, 22049, 22120, 22177, 22528, + 22548, 22593, 22608, 22681, 22810, 22848, 22850, 23173, 24577, 24580, 24592, 24640, 24660, 24674, 24710, 24745, + 24832, 25124, 25162, 25234, 25600, 25622, 25872, 25920, 25925, 26020, 26625, 26730, 26917, 27142, 27220, 27234, + 32768, 32770, 32773, 32776, 32785, 32788, 32800, 32810, 32833, 32836, 32848, 32896, 32898, 32936, 32938, 33025, + 33028, 33030, 33040, 33088, 33105, 33113, 33280, 33312, 33408, 33410, 33440, 33448, 33793, 33796, 33808, 33810, + 33813, 33856, 33888, 33929, 34048, 34116, 34213, 34328, 34410, 34816, 34824, 34853, 34906, 34944, 34946, 34984, + 35078, 35362, 35456, 35464, 35478, 35496, 36865, 36868, 36880, 36928, 36950, 36996, 37120, 37154, 37220, 37462, + 37513, 37888, 37893, 37956, 37968, 37976, 38185, 38288, 38290, 38465, 38993, 39078, 39241, 39445, 39520, 40960, + 40962, 40968, 40970, 40992, 41002, 41120, 41297, 41305, 41382, 41472, 41474, 41480, 41514, 41600, 41632, 42048, + 42133, 42597, 42648, 43018, 43040, 43042, 43048, 43168, 43176, 43268, 43396, 43398, 43560, 43562, 43665, 43690, + }; + static const uint16_t kgrid_1bit_2048[NGRID_IQ1S] = { + 0, 2, 5, 8, 10, 17, 21, 32, 34, 40, 42, 69, 81, 84, 86, 101, + 128, 130, 136, 138, 149, 160, 162, 168, 170, 260, 261, 273, 276, 278, 281, 282, + 293, 321, 326, 329, 338, 341, 346, 353, 356, 358, 360, 389, 401, 404, 406, 421, + 512, 514, 520, 522, 533, 544, 546, 552, 554, 581, 593, 601, 612, 617, 640, 642, + 648, 650, 657, 661, 665, 672, 674, 680, 682, 1041, 1044, 1046, 1061, 1089, 1097, 1109, + 1114, 1124, 1125, 1169, 1177, 1189, 1281, 1284, 1285, 1286, 1301, 1304, 1306, 1321, 1344, 1349, + 1354, 1360, 1361, 1364, 1365, 1366, 1369, 1376, 1378, 1381, 1384, 1386, 1409, 1425, 1429, 1432, + 1434, 1441, 1444, 1445, 1446, 1449, 1556, 1561, 1601, 1604, 1616, 1618, 1621, 1624, 1632, 1633, + 1638, 1641, 1669, 1681, 1684, 1689, 2048, 2050, 2056, 2058, 2069, 2080, 2082, 2088, 2090, 2117, + 2129, 2134, 2149, 2176, 2178, 2184, 2186, 2197, 2208, 2210, 2216, 2218, 2309, 2321, 2324, 2329, + 2340, 2341, 2369, 2384, 2385, 2389, 2401, 2404, 2409, 2449, 2452, 2454, 2457, 2469, 2560, 2562, + 2568, 2570, 2581, 2592, 2594, 2600, 2602, 2629, 2641, 2649, 2657, 2661, 2688, 2690, 2693, 2696, + 2698, 2709, 2720, 2722, 2728, 2730, 4112, 4113, 4116, 4121, 4132, 4133, 4161, 4164, 4176, 4181, + 4184, 4193, 4196, 4197, 4201, 4241, 4244, 4246, 4257, 4261, 4353, 4356, 4358, 4361, 4368, 4370, + 4373, 4376, 4385, 4388, 4393, 4421, 4426, 4432, 4433, 4434, 4436, 4437, 4438, 4441, 4448, 4453, + 4484, 4498, 4501, 4513, 4516, 4625, 4628, 4630, 4645, 4672, 4678, 4681, 4690, 4693, 4696, 4698, + 4708, 4710, 4741, 4753, 4756, 4758, 4773, 5121, 5126, 5129, 5140, 5141, 5144, 5145, 5153, 5158, + 5185, 5189, 5190, 5192, 5194, 5201, 5204, 5205, 5206, 5209, 5218, 5221, 5224, 5252, 5257, 5264, + 5268, 5269, 5272, 5273, 5274, 5281, 5284, 5285, 5289, 5378, 5381, 5386, 5393, 5396, 5397, 5398, + 5401, 5408, 5410, 5413, 5416, 5418, 5441, 5444, 5445, 5446, 5457, 5458, 5460, 5461, 5462, 5465, + 5466, 5473, 5476, 5477, 5478, 5481, 5504, 5506, 5508, 5509, 5512, 5514, 5520, 5521, 5524, 5525, + 5526, 5529, 5530, 5536, 5538, 5541, 5633, 5636, 5637, 5638, 5653, 5654, 5656, 5658, 5665, 5670, + 5696, 5698, 5700, 5701, 5704, 5706, 5713, 5717, 5718, 5720, 5721, 5729, 5732, 5733, 5736, 5737, + 5738, 5766, 5770, 5778, 5781, 5796, 5801, 6161, 6166, 6181, 6209, 6212, 6214, 6217, 6224, 6229, + 6232, 6234, 6240, 6241, 6244, 6246, 6249, 6277, 6289, 6292, 6309, 6416, 6418, 6421, 6426, 6433, + 6437, 6466, 6468, 6469, 6472, 6481, 6484, 6485, 6486, 6489, 6490, 6496, 6501, 6506, 6537, 6545, + 6546, 6549, 6552, 6561, 6566, 6569, 6665, 6678, 6692, 6694, 6724, 6726, 6729, 6736, 6738, 6741, + 6744, 6753, 6758, 6761, 6789, 6801, 6806, 6810, 8192, 8194, 8200, 8202, 8213, 8224, 8226, 8229, + 8232, 8234, 8261, 8273, 8281, 8289, 8293, 8320, 8322, 8328, 8330, 8341, 8352, 8354, 8357, 8360, + 8362, 8453, 8465, 8468, 8473, 8485, 8514, 8516, 8521, 8533, 8536, 8538, 8545, 8548, 8549, 8550, + 8581, 8592, 8598, 8601, 8613, 8705, 8712, 8714, 8721, 8725, 8736, 8738, 8744, 8746, 8773, 8785, + 8790, 8793, 8805, 8833, 8840, 8842, 8849, 8853, 8864, 8866, 8872, 8874, 9221, 9236, 9238, 9241, + 9253, 9284, 9285, 9286, 9289, 9298, 9301, 9304, 9306, 9318, 9349, 9361, 9364, 9369, 9377, 9381, + 9481, 9493, 9505, 9513, 9536, 9541, 9544, 9553, 9556, 9557, 9561, 9570, 9573, 9576, 9609, 9616, + 9620, 9621, 9624, 9626, 9633, 9636, 9638, 9641, 9733, 9744, 9746, 9753, 9765, 9793, 9801, 9813, + 9824, 9825, 9833, 9860, 9862, 9872, 9882, 10240, 10242, 10248, 10250, 10261, 10272, 10274, 10280, 10282, + 10309, 10321, 10324, 10341, 10368, 10370, 10376, 10378, 10400, 10402, 10408, 10410, 10505, 10513, 10516, 10521, + 10533, 10566, 10569, 10578, 10581, 10593, 10596, 10598, 10601, 10629, 10640, 10646, 10649, 10660, 10661, 10752, + 10754, 10760, 10762, 10784, 10786, 10792, 10794, 10821, 10833, 10838, 10841, 10853, 10880, 10882, 10888, 10890, + 10901, 10912, 10914, 10920, 10922, 16389, 16401, 16406, 16421, 16457, 16466, 16469, 16472, 16474, 16481, 16484, + 16486, 16532, 16537, 16545, 16550, 16640, 16641, 16644, 16646, 16649, 16658, 16661, 16662, 16664, 16666, 16673, + 16678, 16681, 16709, 16712, 16714, 16721, 16724, 16725, 16726, 16729, 16730, 16741, 16744, 16746, 16769, 16772, + 16774, 16784, 16786, 16789, 16800, 16801, 16802, 16901, 16913, 16916, 16918, 16933, 16961, 16978, 16981, 16986, + 16996, 17001, 17033, 17044, 17061, 17409, 17429, 17433, 17449, 17477, 17480, 17482, 17489, 17492, 17493, 17494, + 17505, 17506, 17509, 17512, 17514, 17537, 17542, 17545, 17552, 17554, 17557, 17568, 17569, 17577, 17665, 17666, + 17669, 17674, 17681, 17684, 17685, 17686, 17689, 17696, 17701, 17706, 17729, 17732, 17733, 17734, 17737, 17744, + 17745, 17748, 17749, 17750, 17752, 17753, 17761, 17764, 17765, 17766, 17769, 17794, 17796, 17797, 17800, 17809, + 17812, 17813, 17814, 17817, 17818, 17829, 17832, 17834, 17921, 17925, 17929, 17940, 17941, 17944, 17946, 17953, + 17956, 17961, 17984, 17986, 17989, 17992, 18000, 18001, 18002, 18005, 18006, 18009, 18018, 18021, 18024, 18049, + 18053, 18058, 18068, 18069, 18081, 18084, 18086, 18437, 18449, 18453, 18458, 18469, 18498, 18505, 18512, 18517, + 18520, 18529, 18532, 18534, 18537, 18565, 18577, 18580, 18582, 18585, 18597, 18689, 18693, 18694, 18698, 18704, + 18708, 18709, 18712, 18721, 18724, 18726, 18752, 18757, 18762, 18769, 18770, 18772, 18773, 18774, 18777, 18784, + 18786, 18789, 18790, 18794, 18822, 18825, 18834, 18837, 18838, 18840, 18849, 18852, 18854, 18857, 18966, 19012, + 19014, 19017, 19029, 19032, 19034, 19044, 19049, 19092, 19109, 20481, 20484, 20485, 20486, 20489, 20498, 20501, + 20506, 20513, 20516, 20521, 20544, 20549, 20552, 20561, 20564, 20565, 20566, 20569, 20581, 20584, 20614, 20617, + 20629, 20632, 20640, 20641, 20646, 20649, 20741, 20744, 20745, 20746, 20753, 20756, 20757, 20758, 20760, 20761, + 20768, 20773, 20774, 20776, 20778, 20801, 20804, 20805, 20806, 20809, 20816, 20817, 20818, 20820, 20821, 20822, + 20824, 20825, 20826, 20833, 20836, 20837, 20838, 20841, 20866, 20869, 20881, 20884, 20885, 20886, 20889, 20896, + 20901, 20906, 20993, 20998, 21010, 21013, 21018, 21025, 21028, 21058, 21061, 21066, 21073, 21076, 21077, 21078, + 21081, 21090, 21093, 21125, 21136, 21138, 21141, 21145, 21146, 21156, 21508, 21509, 21521, 21524, 21525, 21526, + 21528, 21529, 21537, 21541, 21544, 21546, 21569, 21572, 21573, 21574, 21577, 21578, 21584, 21585, 21588, 21589, + 21590, 21592, 21593, 21594, 21601, 21602, 21604, 21605, 21606, 21609, 21632, 21640, 21642, 21649, 21652, 21653, + 21654, 21657, 21665, 21668, 21669, 21674, 21761, 21762, 21764, 21765, 21766, 21769, 21776, 21777, 21778, 21780, + 21781, 21782, 21785, 21786, 21793, 21796, 21797, 21798, 21801, 21824, 21825, 21826, 21828, 21829, 21830, 21832, + 21833, 21840, 21841, 21842, 21844, 21845, 21846, 21848, 21849, 21850, 21856, 21857, 21860, 21861, 21862, 21864, + 21865, 21866, 21889, 21892, 21893, 21897, 21898, 21904, 21905, 21908, 21909, 21910, 21912, 21913, 21921, 21924, + 21925, 21926, 21929, 22016, 22017, 22018, 22020, 22022, 22024, 22025, 22033, 22036, 22037, 22040, 22041, 22048, + 22049, 22050, 22052, 22053, 22054, 22056, 22057, 22081, 22085, 22086, 22088, 22089, 22090, 22096, 22097, 22098, + 22100, 22101, 22102, 22104, 22105, 22106, 22113, 22116, 22117, 22121, 22146, 22149, 22150, 22152, 22153, 22154, + 22161, 22165, 22170, 22178, 22181, 22182, 22184, 22185, 22532, 22533, 22534, 22537, 22544, 22549, 22552, 22561, + 22570, 22597, 22600, 22602, 22609, 22612, 22613, 22614, 22616, 22617, 22624, 22626, 22628, 22629, 22658, 22665, + 22672, 22674, 22677, 22680, 22689, 22697, 22785, 22786, 22789, 22794, 22801, 22804, 22805, 22806, 22809, 22821, + 22849, 22852, 22853, 22854, 22857, 22864, 22865, 22866, 22868, 22869, 22870, 22872, 22873, 22874, 22881, 22884, + 22885, 22886, 22889, 22913, 22917, 22921, 22929, 22932, 22933, 22934, 22936, 22937, 22949, 23044, 23048, 23061, + 23066, 23072, 23077, 23078, 23081, 23109, 23112, 23113, 23121, 23125, 23126, 23128, 23129, 23138, 23141, 23144, + 23146, 23169, 23178, 23186, 23189, 23190, 23192, 23194, 23201, 24581, 24596, 24598, 24601, 24613, 24644, 24656, + 24661, 24662, 24664, 24666, 24673, 24676, 24678, 24681, 24705, 24726, 24741, 24833, 24836, 24838, 24841, 24850, + 24853, 24865, 24866, 24870, 24873, 24901, 24905, 24913, 24917, 24918, 24921, 24933, 24934, 24938, 24964, 24970, + 24978, 24981, 24993, 24998, 25001, 25105, 25110, 25113, 25152, 25153, 25158, 25173, 25174, 25176, 25184, 25221, + 25233, 25238, 25253, 25617, 25618, 25621, 25622, 25626, 25633, 25638, 25641, 25664, 25666, 25669, 25672, 25674, + 25681, 25684, 25685, 25686, 25689, 25690, 25696, 25698, 25701, 25732, 25733, 25737, 25744, 25746, 25748, 25749, + 25750, 25752, 25754, 25761, 25764, 25769, 25861, 25864, 25866, 25873, 25877, 25878, 25881, 25924, 25925, 25926, + 25929, 25936, 25937, 25940, 25941, 25942, 25945, 25953, 25956, 25957, 25958, 25961, 25990, 25993, 25994, 26001, + 26005, 26006, 26009, 26010, 26018, 26021, 26022, 26024, 26114, 26121, 26133, 26144, 26150, 26152, 26153, 26176, + 26181, 26184, 26186, 26193, 26196, 26197, 26198, 26200, 26202, 26208, 26213, 26216, 26240, 26242, 26245, 26250, + 26260, 26262, 26264, 26265, 26272, 26276, 26278, 26282, 26646, 26649, 26661, 26689, 26706, 26709, 26714, 26721, + 26729, 26757, 26769, 26776, 26790, 26881, 26884, 26896, 26901, 26913, 26916, 26918, 26921, 26944, 26945, 26949, + 26950, 26952, 26961, 26964, 26965, 26966, 26969, 26976, 26981, 26986, 27010, 27012, 27018, 27029, 27041, 27044, + 27045, 27049, 27153, 27158, 27160, 27201, 27204, 27209, 27216, 27221, 27224, 27226, 27236, 27237, 27241, 27270, + 27284, 27288, 27290, 27302, 32768, 32770, 32776, 32778, 32800, 32802, 32808, 32810, 32837, 32848, 32849, 32852, + 32854, 32857, 32869, 32896, 32898, 32904, 32906, 32917, 32928, 32930, 32936, 32938, 33029, 33041, 33044, 33046, + 33049, 33061, 33089, 33092, 33097, 33104, 33106, 33109, 33110, 33112, 33113, 33124, 33126, 33129, 33157, 33161, + 33172, 33174, 33177, 33189, 33280, 33282, 33288, 33290, 33301, 33312, 33314, 33320, 33322, 33361, 33364, 33369, + 33381, 33408, 33410, 33416, 33418, 33429, 33440, 33442, 33448, 33450, 33812, 33817, 33857, 33860, 33873, 33877, + 33882, 33889, 33892, 33897, 33940, 33945, 34049, 34057, 34066, 34069, 34074, 34086, 34089, 34112, 34113, 34117, + 34120, 34129, 34132, 34133, 34134, 34137, 34138, 34149, 34150, 34152, 34154, 34177, 34180, 34182, 34185, 34192, + 34194, 34197, 34200, 34214, 34321, 34326, 34329, 34341, 34369, 34372, 34377, 34378, 34384, 34389, 34393, 34394, + 34401, 34406, 34410, 34437, 34449, 34458, 34468, 34816, 34818, 34824, 34826, 34837, 34848, 34850, 34856, 34858, + 34881, 34885, 34897, 34900, 34905, 34917, 34921, 34944, 34946, 34952, 34954, 34965, 34976, 34978, 34984, 34986, + 35077, 35078, 35089, 35092, 35094, 35109, 35137, 35140, 35142, 35145, 35152, 35154, 35157, 35162, 35169, 35172, + 35205, 35222, 35225, 35237, 35328, 35330, 35336, 35338, 35349, 35360, 35362, 35368, 35370, 35397, 35409, 35412, + 35414, 35456, 35458, 35464, 35466, 35477, 35488, 35490, 35496, 35498, 36869, 36881, 36886, 36888, 36889, 36901, + 36929, 36934, 36937, 36949, 36952, 36954, 36969, 36970, 36997, 37009, 37012, 37014, 37017, 37029, 37121, 37124, + 37126, 37129, 37136, 37141, 37144, 37146, 37153, 37156, 37158, 37161, 37184, 37189, 37200, 37201, 37204, 37205, + 37206, 37209, 37218, 37221, 37252, 37254, 37266, 37269, 37272, 37281, 37284, 37286, 37289, 37381, 37393, 37396, + 37401, 37413, 37444, 37446, 37449, 37456, 37458, 37461, 37464, 37478, 37481, 37509, 37524, 37526, 37545, 37889, + 37892, 37894, 37904, 37909, 37912, 37926, 37952, 37962, 37969, 37972, 37973, 37974, 37976, 37977, 37984, 37985, + 37986, 37989, 38020, 38022, 38034, 38036, 38037, 38040, 38049, 38057, 38144, 38149, 38152, 38154, 38160, 38161, + 38164, 38165, 38166, 38169, 38177, 38181, 38185, 38186, 38209, 38212, 38213, 38214, 38217, 38224, 38225, 38226, + 38228, 38229, 38230, 38232, 38233, 38234, 38241, 38244, 38245, 38246, 38249, 38273, 38277, 38280, 38289, 38290, + 38292, 38293, 38294, 38297, 38298, 38304, 38306, 38309, 38312, 38314, 38401, 38404, 38416, 38421, 38425, 38432, + 38438, 38441, 38469, 38472, 38473, 38481, 38482, 38485, 38486, 38489, 38501, 38504, 38530, 38532, 38537, 38538, + 38546, 38548, 38549, 38564, 38566, 38569, 38917, 38934, 38937, 38949, 38977, 38982, 38992, 38994, 38997, 38998, + 39002, 39012, 39013, 39045, 39057, 39062, 39065, 39077, 39172, 39174, 39177, 39184, 39186, 39189, 39192, 39194, + 39200, 39201, 39204, 39206, 39232, 39234, 39237, 39240, 39242, 39249, 39252, 39253, 39254, 39257, 39266, 39269, + 39270, 39274, 39297, 39300, 39312, 39314, 39317, 39322, 39329, 39334, 39429, 39445, 39461, 39492, 39494, 39497, + 39504, 39509, 39512, 39521, 39557, 39569, 39572, 39573, 39574, 40960, 40962, 40968, 40970, 40981, 40992, 40994, + 41000, 41002, 41029, 41041, 41044, 41046, 41049, 41088, 41090, 41096, 41098, 41109, 41120, 41122, 41128, 41130, + 41221, 41225, 41233, 41236, 41238, 41241, 41242, 41286, 41289, 41297, 41301, 41304, 41306, 41313, 41316, 41349, + 41360, 41362, 41366, 41369, 41474, 41480, 41482, 41488, 41497, 41506, 41512, 41514, 41541, 41553, 41558, 41561, + 41573, 41600, 41602, 41608, 41610, 41621, 41632, 41634, 41640, 41642, 42009, 42021, 42049, 42052, 42064, 42068, + 42069, 42072, 42074, 42081, 42085, 42086, 42088, 42089, 42117, 42246, 42249, 42256, 42258, 42261, 42264, 42278, + 42281, 42306, 42309, 42321, 42324, 42325, 42326, 42329, 42341, 42346, 42369, 42372, 42373, 42374, 42377, 42386, + 42389, 42392, 42501, 42513, 42518, 42522, 42529, 42533, 42564, 42566, 42570, 42578, 42581, 42582, 42584, 42592, + 42594, 42630, 42640, 42645, 42646, 42649, 42657, 42660, 42662, 43008, 43010, 43016, 43018, 43040, 43042, 43048, + 43050, 43089, 43092, 43094, 43097, 43136, 43138, 43144, 43146, 43157, 43168, 43170, 43176, 43178, 43269, 43284, + 43289, 43297, 43301, 43329, 43344, 43349, 43354, 43361, 43366, 43369, 43408, 43414, 43520, 43522, 43528, 43530, + 43552, 43554, 43560, 43562, 43601, 43604, 43606, 43648, 43650, 43656, 43658, 43669, 43680, 43682, 43688, 43690, + }; + static const uint16_t kgrid_2bit_1024[1024] = { + 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70, + 73, 80, 82, 85, 88, 97, 100, 102, 105, 128, 130, 133, 136, 145, 148, 160, + 165, 170, 257, 260, 262, 265, 272, 274, 277, 280, 289, 292, 320, 322, 325, 328, + 337, 340, 342, 345, 352, 357, 360, 385, 388, 400, 402, 405, 417, 420, 512, 514, + 517, 520, 529, 532, 544, 554, 577, 580, 582, 585, 592, 597, 640, 645, 650, 660, + 674, 1025, 1028, 1030, 1033, 1040, 1042, 1045, 1048, 1057, 1060, 1062, 1065, 1088, 1090, 1093, + 1096, 1098, 1105, 1108, 1110, 1113, 1120, 1122, 1125, 1153, 1156, 1158, 1161, 1168, 1173, 1176, + 1185, 1188, 1280, 1282, 1285, 1288, 1290, 1297, 1300, 1302, 1305, 1312, 1317, 1320, 1345, 1348, + 1350, 1353, 1360, 1362, 1365, 1368, 1377, 1380, 1408, 1410, 1413, 1416, 1425, 1428, 1440, 1537, + 1540, 1542, 1545, 1552, 1557, 1600, 1605, 1608, 1617, 1620, 1632, 1665, 1668, 1680, 2048, 2050, + 2053, 2056, 2065, 2068, 2070, 2073, 2080, 2085, 2090, 2113, 2116, 2118, 2121, 2128, 2130, 2133, + 2136, 2145, 2148, 2176, 2181, 2196, 2218, 2305, 2308, 2320, 2322, 2325, 2328, 2337, 2368, 2373, + 2376, 2385, 2388, 2400, 2433, 2448, 2560, 2577, 2580, 2594, 2600, 2602, 2640, 2713, 4097, 4100, + 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4134, 4160, 4162, 4165, 4168, 4177, 4180, 4182, + 4185, 4192, 4194, 4197, 4200, 4225, 4228, 4230, 4240, 4245, 4248, 4257, 4260, 4352, 4354, 4357, + 4360, 4362, 4369, 4372, 4374, 4377, 4384, 4386, 4389, 4392, 4417, 4420, 4422, 4425, 4432, 4434, + 4437, 4440, 4449, 4452, 4480, 4482, 4485, 4488, 4497, 4500, 4609, 4612, 4617, 4624, 4629, 4641, + 4644, 4672, 4677, 4689, 4692, 4737, 4740, 4752, 5120, 5122, 5125, 5128, 5137, 5140, 5142, 5145, + 5152, 5157, 5160, 5185, 5188, 5190, 5193, 5200, 5202, 5205, 5208, 5217, 5220, 5248, 5250, 5253, + 5256, 5265, 5268, 5280, 5377, 5380, 5382, 5385, 5392, 5394, 5397, 5400, 5409, 5412, 5440, 5442, + 5445, 5448, 5457, 5460, 5472, 5505, 5508, 5520, 5632, 5637, 5640, 5649, 5652, 5664, 5697, 5700, + 5712, 5760, 5802, 6145, 6148, 6150, 6153, 6160, 6165, 6168, 6177, 6208, 6210, 6213, 6216, 6225, + 6228, 6240, 6273, 6276, 6400, 6402, 6405, 6408, 6417, 6420, 6432, 6465, 6468, 6480, 6505, 6562, + 6660, 6672, 6720, 6742, 8192, 8194, 8197, 8200, 8209, 8212, 8214, 8217, 8224, 8229, 8234, 8257, + 8260, 8272, 8274, 8277, 8292, 8320, 8330, 8340, 8362, 8449, 8452, 8464, 8466, 8469, 8481, 8512, + 8514, 8517, 8529, 8532, 8544, 8577, 8580, 8592, 8704, 8714, 8738, 8744, 8746, 8772, 8784, 8840, + 8842, 8872, 9217, 9220, 9222, 9225, 9232, 9237, 9240, 9249, 9252, 9280, 9282, 9285, 9288, 9297, + 9300, 9312, 9345, 9348, 9360, 9472, 9477, 9480, 9489, 9492, 9504, 9537, 9540, 9552, 9574, 9600, + 9729, 9732, 9744, 9792, 9817, 10240, 10245, 10257, 10260, 10305, 10308, 10320, 10378, 10410, 10497, 10500, + 10512, 10645, 10762, 10786, 10852, 10888, 10890, 16385, 16388, 16390, 16393, 16400, 16402, 16405, 16408, 16410, + 16417, 16420, 16422, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16470, 16473, 16480, 16482, 16485, 16513, + 16516, 16528, 16533, 16536, 16545, 16548, 16640, 16642, 16645, 16648, 16657, 16660, 16662, 16665, 16672, 16674, + 16677, 16705, 16708, 16710, 16713, 16720, 16722, 16725, 16728, 16737, 16740, 16768, 16770, 16773, 16776, 16785, + 16788, 16800, 16897, 16900, 16912, 16914, 16917, 16920, 16932, 16960, 16965, 16968, 16977, 16980, 16992, 17025, + 17028, 17408, 17410, 17413, 17416, 17418, 17425, 17428, 17430, 17433, 17440, 17442, 17445, 17448, 17473, 17476, + 17478, 17481, 17488, 17490, 17493, 17496, 17505, 17508, 17536, 17538, 17541, 17544, 17553, 17556, 17568, 17665, + 17668, 17670, 17673, 17680, 17682, 17685, 17688, 17697, 17700, 17728, 17730, 17733, 17736, 17745, 17748, 17760, + 17770, 17793, 17796, 17808, 17920, 17922, 17925, 17928, 17937, 17940, 17952, 17985, 17988, 18000, 18048, 18085, + 18433, 18436, 18441, 18448, 18450, 18453, 18456, 18465, 18468, 18496, 18498, 18501, 18504, 18513, 18516, 18528, + 18564, 18576, 18688, 18690, 18693, 18696, 18705, 18708, 18720, 18753, 18756, 18768, 18816, 18838, 18945, 18948, + 18960, 19008, 20480, 20482, 20485, 20488, 20497, 20500, 20502, 20505, 20512, 20514, 20517, 20520, 20545, 20548, + 20550, 20553, 20560, 20562, 20565, 20568, 20577, 20580, 20608, 20610, 20613, 20616, 20625, 20628, 20737, 20740, + 20742, 20745, 20752, 20754, 20757, 20760, 20769, 20772, 20800, 20802, 20805, 20808, 20817, 20820, 20832, 20865, + 20868, 20880, 20992, 20997, 21000, 21009, 21012, 21024, 21057, 21060, 21072, 21097, 21120, 21505, 21508, 21510, + 21513, 21520, 21522, 21525, 21528, 21537, 21540, 21568, 21570, 21573, 21576, 21585, 21588, 21600, 21633, 21636, + 21648, 21760, 21762, 21765, 21768, 21777, 21780, 21792, 21825, 21828, 21840, 21888, 22017, 22020, 22032, 22054, + 22080, 22528, 22530, 22533, 22536, 22545, 22548, 22560, 22593, 22596, 22608, 22618, 22656, 22785, 22788, 22800, + 22848, 23040, 23065, 23173, 23208, 24577, 24580, 24582, 24592, 24594, 24597, 24600, 24609, 24612, 24640, 24645, + 24648, 24657, 24660, 24672, 24708, 24720, 24832, 24834, 24837, 24840, 24849, 24852, 24864, 24897, 24900, 24912, + 24960, 24985, 25092, 25104, 25152, 25174, 25249, 25600, 25605, 25608, 25617, 25620, 25632, 25665, 25668, 25680, + 25728, 25857, 25860, 25872, 25920, 25930, 25960, 26002, 26112, 26260, 26625, 26628, 26640, 26725, 26776, 26880, + 26922, 27202, 27297, 32768, 32770, 32773, 32776, 32785, 32788, 32793, 32800, 32805, 32833, 32836, 32848, 32850, + 32853, 32856, 32865, 32896, 32901, 32913, 32916, 33025, 33028, 33033, 33040, 33042, 33045, 33048, 33057, 33060, + 33088, 33090, 33093, 33096, 33105, 33108, 33153, 33156, 33168, 33193, 33280, 33285, 33290, 33297, 33300, 33345, + 33348, 33360, 33793, 33796, 33798, 33801, 33808, 33810, 33813, 33816, 33825, 33856, 33858, 33861, 33864, 33873, + 33876, 33888, 33921, 33924, 33936, 34048, 34050, 34053, 34056, 34065, 34068, 34080, 34113, 34116, 34128, 34176, + 34186, 34305, 34308, 34320, 34345, 34368, 34816, 34821, 34833, 34836, 34881, 34884, 34896, 34978, 35073, 35076, + 35136, 35173, 35362, 35416, 35418, 35458, 35490, 36865, 36868, 36873, 36880, 36882, 36885, 36888, 36900, 36928, + 36930, 36933, 36936, 36945, 36948, 36960, 36993, 36996, 37008, 37120, 37125, 37137, 37140, 37185, 37188, 37200, + 37210, 37377, 37380, 37392, 37440, 37542, 37888, 37890, 37893, 37896, 37905, 37908, 37920, 37953, 37956, 37968, + 38016, 38038, 38145, 38148, 38160, 38208, 38296, 38305, 38400, 38470, 38500, 38913, 38916, 38928, 38950, 38976, + 39081, 39168, 39241, 39250, 39568, 40960, 40965, 40970, 40980, 40994, 41002, 41025, 41028, 41040, 41122, 41130, + 41280, 41317, 41474, 41482, 41506, 41512, 41514, 41602, 41608, 41610, 41640, 41985, 41988, 42000, 42048, 42121, + 42148, 42240, 42265, 42577, 43018, 43048, 43170, 43348, 43398, 43528, 43530, 43552, 43554, 43560, 43656, 43690, + }; + + const int kmap_size = 43692; + //const int nwant = type == GGML_TYPE_IQ1_S ? 3 : 2; + const int nwant = type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? 3 : type == GGML_TYPE_IQ2_S ? 1 : 2; + const uint16_t * kgrid = type == GGML_TYPE_IQ2_XXS ? kgrid_2bit_256 : + type == GGML_TYPE_IQ2_XS ? kgrid_2bit_512 : + type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M ? kgrid_1bit_2048 : kgrid_2bit_1024; + uint64_t * kgrid_q2xs; + int * kmap_q2xs; + uint16_t * kneighbors_q2xs; + + //printf("================================================================= %s(grid_size = %d)\n", __func__, grid_size); + uint64_t * the_grid = (uint64_t *)malloc(grid_size*sizeof(uint64_t)); + for (int k = 0; k < grid_size; ++k) { + int8_t * pos = (int8_t *)(the_grid + k); + for (int i = 0; i < 8; ++i) { + int l = (kgrid[k] >> 2*i) & 0x3; + pos[i] = 2*l + 1; + } + } + kgrid_q2xs = the_grid; + iq2_data[gindex].grid = the_grid; + kmap_q2xs = (int *)malloc(kmap_size*sizeof(int)); + iq2_data[gindex].map = kmap_q2xs; + for (int i = 0; i < kmap_size; ++i) kmap_q2xs[i] = -1; + uint64_t aux64; + uint8_t * aux8 = (uint8_t *)&aux64; + for (int i = 0; i < grid_size; ++i) { + aux64 = kgrid_q2xs[i]; + uint16_t index = 0; + for (int k=0; k<8; ++k) { + uint16_t q = (aux8[k] - 1)/2; + index |= (q << 2*k); + } + kmap_q2xs[index] = i; + } + // The neighbour search runs in three passes: + // 1. Parallel: for each i, qsort and count its neighbours into n_per_i, + // and reduce the totals (num_neighbors, num_not_in_map). + // 2. Serial: prefix-sum n_per_i into offsets[], so each i has a + // pre-assigned slice of kneighbors_q2xs to write into. + // 3. Parallel: redo the qsort and write each i's neighbour list at + // offsets[i]. + int * n_per_i = (int *)malloc(kmap_size*sizeof(int)); + GGML_ASSERT(n_per_i); + int num_neighbors = 0, num_not_in_map = 0; +#ifdef GGML_USE_OPENMP + #pragma omp parallel reduction(+:num_neighbors,num_not_in_map) +#endif + { + int * dist2 = (int *)malloc(2*grid_size*sizeof(int)); + GGML_ASSERT(dist2); + int8_t pos[8]; + int i; +#ifdef GGML_USE_OPENMP + #pragma omp for schedule(dynamic, 64) +#endif + for (i = 0; i < kmap_size; ++i) { + if (kmap_q2xs[i] >= 0) { + n_per_i[i] = 0; + continue; + } + ++num_not_in_map; + for (int k = 0; k < 8; ++k) { + int l = (i >> 2*k) & 0x3; + pos[k] = 2*l + 1; + } + for (int j = 0; j < grid_size; ++j) { + const int8_t * pg = (const int8_t *)(kgrid_q2xs + j); + int d2 = 0; + for (int k = 0; k < 8; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]); + dist2[2*j+0] = d2; + dist2[2*j+1] = j; + } + qsort(dist2, grid_size, 2*sizeof(int), iq2_compare_func); + int n = 0; int d2 = dist2[0]; + int nhave = 1; + for (int j = 0; j < grid_size; ++j) { + if (dist2[2*j] > d2) { + if (nhave == nwant) break; + d2 = dist2[2*j]; + ++nhave; + } + ++n; + } + n_per_i[i] = n; + num_neighbors += n; + } + free(dist2); + } + //printf("%s: %d neighbours in total\n", __func__, num_neighbors); + kneighbors_q2xs = (uint16_t *)malloc((num_neighbors + num_not_in_map)*sizeof(uint16_t)); + iq2_data[gindex].neighbours = kneighbors_q2xs; + + int * offsets = (int *)malloc(kmap_size*sizeof(int)); + GGML_ASSERT(offsets); + int counter = 0; + for (int i = 0; i < kmap_size; ++i) { + if (kmap_q2xs[i] >= 0) { + offsets[i] = -1; + continue; + } + offsets[i] = counter; + counter += 1 + n_per_i[i]; + } + +#ifdef GGML_USE_OPENMP + #pragma omp parallel +#endif + { + int * dist2 = (int *)malloc(2*grid_size*sizeof(int)); + GGML_ASSERT(dist2); + int8_t pos[8]; + int i; +#ifdef GGML_USE_OPENMP + #pragma omp for schedule(dynamic, 64) +#endif + for (i = 0; i < kmap_size; ++i) { + if (kmap_q2xs[i] >= 0) continue; + for (int k = 0; k < 8; ++k) { + int l = (i >> 2*k) & 0x3; + pos[k] = 2*l + 1; + } + for (int j = 0; j < grid_size; ++j) { + const int8_t * pg = (const int8_t *)(kgrid_q2xs + j); + int d2 = 0; + for (int k = 0; k < 8; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]); + dist2[2*j+0] = d2; + dist2[2*j+1] = j; + } + qsort(dist2, grid_size, 2*sizeof(int), iq2_compare_func); + int local_counter = offsets[i]; + kmap_q2xs[i] = -(local_counter + 1); + int d2 = dist2[0]; + uint16_t * start = &kneighbors_q2xs[local_counter++]; + int n = 0, nhave = 1; + for (int j = 0; j < grid_size; ++j) { + if (dist2[2*j] > d2) { + if (nhave == nwant) break; + d2 = dist2[2*j]; + ++nhave; + } + kneighbors_q2xs[local_counter++] = dist2[2*j+1]; + ++n; + } + *start = n; + } + free(dist2); + } + free(offsets); + free(n_per_i); +} + +void iq2xs_free_impl(enum ggml_type type) { + GGML_ASSERT(type == GGML_TYPE_IQ2_XXS || type == GGML_TYPE_IQ2_XS || type == GGML_TYPE_IQ1_S || type == GGML_TYPE_IQ1_M || type == GGML_TYPE_IQ2_S); + const int gindex = iq2_data_index(type); + if (iq2_data[gindex].grid) { + free(iq2_data[gindex].grid); iq2_data[gindex].grid = NULL; + free(iq2_data[gindex].map); iq2_data[gindex].map = NULL; + free(iq2_data[gindex].neighbours); iq2_data[gindex].neighbours = NULL; + } +} + +static int iq2_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid, + const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, int8_t * GGML_RESTRICT L) { + int num_neighbors = neighbours[0]; + GGML_ASSERT(num_neighbors > 0); + float best_d2 = FLT_MAX; + int grid_index = -1; + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float d2 = 0; + for (int i = 0; i < 8; ++i) { + float q = pg[i]; + float diff = scale*q - xval[i]; + d2 += weight[i]*diff*diff; + } + if (d2 < best_d2) { + best_d2 = d2; grid_index = neighbours[j]; + } + } + GGML_ASSERT(grid_index >= 0); + const int8_t * pg = (const int8_t *)(grid + grid_index); + for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2; + return grid_index; +} + +static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) { + + const int gindex = iq2_data_index(GGML_TYPE_IQ2_XXS); + + const uint64_t * kgrid_q2xs = iq2_data[gindex].grid; + const int * kmap_q2xs = iq2_data[gindex].map; + const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours; + + GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kgrid_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kmap_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + const int kMaxQ = 3; + + const int64_t nbl = n/QK_K; + + block_iq2_xxs * y = vy; + + float scales[QK_K/32]; + float weight[32]; + float xval[32]; + int8_t L[32]; + int8_t Laux[32]; + float waux[32]; + uint8_t block_signs[4]; + uint32_t q2[2*(QK_K/32)]; + + for (int ibl = 0; ibl < nbl; ++ibl) { + + y[ibl].d = GGML_FP32_TO_FP16(0.f); + memset(q2, 0, QK_K/4); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = sumx2/QK_K; + + for (int ib = 0; ib < QK_K/32; ++ib) { + const float * xb = xbl + 32*ib; + const float * qw = quant_weights + QK_K*ibl + 32*ib; + for (int i = 0; i < 32; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + for (int i = 0; i < 32; ++i) waux[i] = sqrtf(weight[i]); + for (int k = 0; k < 4; ++k) { + int nflip = 0; + uint8_t s = 0; + for (int i = 0; i < 8; ++i) { + if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i]; + else { + xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i); + } + } + if (nflip%2) { + int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin]; + for (int i = 1; i < 8; ++i) { + float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i]; + if (ax < min) { + min = ax; imin = i; + } + } + xval[8*k+imin] = -xval[8*k+imin]; + s ^= (1 << imin); + } + block_signs[k] = s & 127; + } + float max = xval[0]; + for (int i = 1; i < 32; ++i) max = MAX(max, xval[i]); + if (max < GROUP_MAX_EPS) { + scales[ib] = 0; + memset(L, 0, 32); + continue; + } + float scale = make_qp_quants(32, kMaxQ+1, xval, (uint8_t*)L, weight); + float eff_max = scale*kMaxQ; + if (eff_max <= 0) { + scales[ib] = 0; + memset(L, 0, 32); + continue; + } + float best = 0; + for (int is = -6; is <= 6; ++is) { + float id = (2*kMaxQ-1+is*0.1f)/eff_max; + float this_scale = 1/id; + for (int k = 0; k < 4; ++k) { + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l)); + } + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 32; ++i) { + float w = weight[i]; + float q = 2*Laux[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + scale = sumqx/sumq2; best = scale*sumqx; + memcpy(L, Laux, 32); + } + } + if (scale > 0) { + float id = 1/scale; + for (int k = 0; k < 4; ++k) { + uint16_t u = 0; + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + l = MAX(0, MIN(kMaxQ-1, l)); + u |= (l << 2*i); + } + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + } + const int8_t * pg = (const int8_t *)(kgrid_q2xs + grid_index); + for (int i = 0; i < 8; ++i) L[8*k+i] = (pg[i] - 1)/2; + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 32; ++i) { + float w = weight[i]; + float q = 2*L[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0) scale = sumqx/sumq2; + } + if (scale < 0) { + // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale) + // and correspondingly flip quant signs. + scale = -scale; + for (int k = 0; k < 4; ++k) block_signs[k] = (~block_signs[k]) & 127; + } + for (int k = 0; k < 4; ++k) { + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + printf("Oops: found point %u not on grid:", u); + for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]); + printf("\n"); + GGML_ABORT("fatal error"); + } + q2[2*ib+0] |= ((uint32_t) grid_index << 8*k); + q2[2*ib+1] |= (block_signs[k] << 7*k); + } + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + memset(y[ibl].qs, 0, QK_K/4); + continue; + } + + float d = max_scale/31; + y[ibl].d = GGML_FP32_TO_FP16(d); + float id = 1/d; + for (int ib = 0; ib < QK_K/32; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib]-1)); + l = MAX(0, MIN(15, l)); + q2[2*ib+1] |= ((uint32_t)l << 28); + } + memcpy(y[ibl].qs, q2, QK_K/4); + } +} + +static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) { + + const int gindex = iq2_data_index(GGML_TYPE_IQ2_XS); + + const uint64_t * kgrid_q2xs = iq2_data[gindex].grid; + const int * kmap_q2xs = iq2_data[gindex].map; + const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours; + + GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kmap_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kgrid_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + const int kMaxQ = 3; + + const int64_t nbl = n/QK_K; + + block_iq2_xs * y = vy; + + float scales[QK_K/16]; + float weight[16]; + float xval[16]; + int8_t L[16]; + int8_t Laux[16]; + float waux[16]; + bool is_on_grid[2]; + bool is_on_grid_aux[2]; + uint8_t block_signs[2]; + uint16_t q2[2*(QK_K/16)]; + + for (int ibl = 0; ibl < nbl; ++ibl) { + + y[ibl].d = GGML_FP32_TO_FP16(0.f); + memset(q2, 0, QK_K/4); + memset(y[ibl].scales, 0, QK_K/32); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = sumx2/QK_K; + + for (int ib = 0; ib < QK_K/16; ++ib) { + const float * xb = xbl + 16*ib; + const float * qw = quant_weights + QK_K*ibl + 16*ib; + for (int i = 0; i < 16; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + for (int i = 0; i < 16; ++i) waux[i] = sqrtf(weight[i]); + for (int k = 0; k < 2; ++k) { + int nflip = 0; + uint8_t s = 0; + for (int i = 0; i < 8; ++i) { + if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i]; + else { + xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i); + } + } + if (nflip%2) { + int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin]; + for (int i = 1; i < 8; ++i) { + float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i]; + if (ax < min) { + min = ax; imin = i; + } + } + xval[8*k+imin] = -xval[8*k+imin]; + s ^= (1 << imin); + } + block_signs[k] = s & 127; + } + float max = xval[0]; + for (int i = 1; i < 16; ++i) max = MAX(max, xval[i]); + memset(L, 0, 16); + if (max < GROUP_MAX_EPS) { + scales[ib] = 0; + continue; + } + float best = 0; + float scale = max/(2*kMaxQ-1); + is_on_grid[0] = is_on_grid[1] = true; + for (int is = -9; is <= 9; ++is) { + float id = (2*kMaxQ-1+is*0.1f)/max; + float this_scale = 1/id; + for (int k = 0; k < 2; ++k) { + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l)); + } + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + is_on_grid_aux[k] = true; + if (grid_index < 0) { + is_on_grid_aux[k] = false; + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 16; ++i) { + float w = weight[i]; + float q = 2*Laux[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + scale = sumqx/sumq2; best = scale*sumqx; + for (int i = 0; i < 16; ++i) L[i] = Laux[i]; + for (int k = 0; k < 2; ++k) is_on_grid[k] = is_on_grid_aux[k]; + } + } + int n_not_ongrid = 0; + for (int k = 0; k < 2; ++k) if (!is_on_grid[k]) ++n_not_ongrid; + if (n_not_ongrid > 0 && scale > 0) { + float id = 1/scale; + for (int k = 0; k < 2; ++k) { + if (is_on_grid[k]) continue; + uint16_t u = 0; + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + l = MAX(0, MIN(kMaxQ-1, l)); + u |= (l << 2*i); + L[8*k + i] = l; + } + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 16; ++i) { + float w = weight[i]; + float q = 2*L[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0) scale = sumqx/sumq2; + } + if (scale < 0) { + scale = -scale; + for (int k = 0; k < 2; ++k) block_signs[k] = (~block_signs[k]) & 127; + } + for (int k = 0; k < 2; ++k) { + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + printf("Oops: found point %u not on grid:", u); + for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]); + printf("\n"); + GGML_ABORT("fatal error"); + } + q2[2*ib+k] = grid_index | (block_signs[k] << 9); + } + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + memset(y[ibl].qs, 0, QK_K/4); + continue; + } + + float d = max_scale/31; + y[ibl].d = GGML_FP32_TO_FP16(d); + float id = 1/d; + for (int ib = 0; ib < QK_K/16; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib]-1)); + l = MAX(0, MIN(15, l)); + if (ib%2 == 0) y[ibl].scales[ib/2] = l; + else y[ibl].scales[ib/2] |= (l << 4); + } + memcpy(y[ibl].qs, q2, QK_K/4); + + } +} + +size_t quantize_iq2_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq2_xxs_impl(src, qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += nblock*sizeof(block_iq2_xxs); + } + return nrow * nblock * sizeof(block_iq2_xxs); +} + +size_t quantize_iq2_xs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq2_xs_impl(src, qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += nblock*sizeof(block_iq2_xs); + } + return nrow * nblock * sizeof(block_iq2_xs); +} + +// +// ============================================= 3-bit using D4 lattice +// + +typedef struct { + uint32_t * grid; + int * map; + uint16_t * neighbours; +} iq3_entry_t; + +static iq3_entry_t iq3_data[2] = { + {NULL, NULL, NULL}, + {NULL, NULL, NULL}, +}; + +static inline int iq3_data_index(int grid_size) { + (void)grid_size; + GGML_ASSERT(grid_size == 256 || grid_size == 512); + return grid_size == 256 ? 0 : 1; +} + +static int iq3_compare_func(const void * left, const void * right) { + const int * l = (const int *)left; + const int * r = (const int *)right; + return l[0] < r[0] ? -1 : l[0] > r[0] ? 1 : l[1] < r[1] ? -1 : l[1] > r[1] ? 1 : 0; +} + +void iq3xs_init_impl(int grid_size) { + const int gindex = iq3_data_index(grid_size); + if (iq3_data[gindex].grid) { + return; + } + static const uint16_t kgrid_256[256] = { + 0, 2, 4, 9, 11, 15, 16, 18, 25, 34, 59, 61, 65, 67, 72, 74, + 81, 85, 88, 90, 97, 108, 120, 128, 130, 132, 137, 144, 146, 153, 155, 159, + 169, 175, 189, 193, 199, 200, 202, 213, 248, 267, 287, 292, 303, 315, 317, 321, + 327, 346, 362, 413, 436, 456, 460, 462, 483, 497, 513, 515, 520, 522, 529, 531, + 536, 538, 540, 551, 552, 576, 578, 585, 592, 594, 641, 643, 648, 650, 657, 664, + 698, 704, 706, 720, 729, 742, 758, 769, 773, 808, 848, 852, 870, 889, 901, 978, + 992, 1024, 1026, 1033, 1035, 1040, 1042, 1046, 1049, 1058, 1089, 1091, 1093, 1096, 1098, 1105, + 1112, 1139, 1143, 1144, 1152, 1154, 1161, 1167, 1168, 1170, 1183, 1184, 1197, 1217, 1224, 1228, + 1272, 1276, 1309, 1323, 1347, 1367, 1377, 1404, 1473, 1475, 1486, 1509, 1537, 1544, 1546, 1553, + 1555, 1576, 1589, 1594, 1600, 1602, 1616, 1625, 1636, 1638, 1665, 1667, 1672, 1685, 1706, 1722, + 1737, 1755, 1816, 1831, 1850, 1856, 1862, 1874, 1901, 1932, 1950, 1971, 2011, 2032, 2052, 2063, + 2077, 2079, 2091, 2095, 2172, 2192, 2207, 2208, 2224, 2230, 2247, 2277, 2308, 2345, 2356, 2389, + 2403, 2424, 2501, 2504, 2506, 2520, 2570, 2593, 2616, 2624, 2630, 2646, 2669, 2700, 2714, 2746, + 2754, 2795, 2824, 2835, 2839, 2874, 2882, 2905, 2984, 3028, 3042, 3092, 3108, 3110, 3124, 3153, + 3185, 3215, 3252, 3288, 3294, 3364, 3397, 3434, 3483, 3523, 3537, 3587, 3589, 3591, 3592, 3610, + 3626, 3670, 3680, 3722, 3749, 3754, 3776, 3789, 3803, 3824, 3857, 3873, 3904, 3906, 3924, 3992, + }; + static const uint16_t kgrid_512[512] = { + 0, 1, 2, 5, 7, 8, 9, 10, 12, 14, 16, 17, 21, 27, 32, 34, + 37, 39, 41, 43, 48, 50, 57, 60, 63, 64, 65, 66, 68, 72, 73, 77, + 80, 83, 87, 89, 93, 100, 113, 117, 122, 128, 129, 133, 135, 136, 139, 142, + 145, 149, 152, 156, 162, 165, 167, 169, 171, 184, 187, 195, 201, 205, 208, 210, + 217, 219, 222, 228, 232, 234, 247, 249, 253, 256, 267, 271, 273, 276, 282, 288, + 291, 297, 312, 322, 324, 336, 338, 342, 347, 353, 357, 359, 374, 379, 390, 393, + 395, 409, 426, 441, 448, 450, 452, 464, 466, 470, 475, 488, 492, 512, 513, 514, + 516, 520, 521, 523, 525, 527, 528, 530, 537, 540, 542, 556, 558, 561, 570, 576, + 577, 579, 582, 584, 588, 593, 600, 603, 609, 616, 618, 632, 638, 640, 650, 653, + 655, 656, 660, 666, 672, 675, 685, 688, 698, 705, 708, 711, 712, 715, 721, 727, + 728, 732, 737, 754, 760, 771, 773, 778, 780, 793, 795, 802, 806, 808, 812, 833, + 840, 843, 849, 856, 858, 873, 912, 916, 919, 932, 934, 961, 963, 968, 970, 977, + 989, 993, 1010, 1016, 1024, 1025, 1027, 1029, 1031, 1032, 1034, 1036, 1038, 1041, 1043, 1047, + 1048, 1050, 1057, 1059, 1061, 1064, 1066, 1079, 1080, 1083, 1085, 1088, 1090, 1096, 1099, 1103, + 1106, 1109, 1113, 1116, 1122, 1129, 1153, 1156, 1159, 1169, 1171, 1176, 1183, 1185, 1195, 1199, + 1209, 1212, 1216, 1218, 1221, 1225, 1234, 1236, 1241, 1243, 1250, 1256, 1270, 1281, 1287, 1296, + 1299, 1306, 1309, 1313, 1338, 1341, 1348, 1353, 1362, 1375, 1376, 1387, 1400, 1408, 1410, 1415, + 1425, 1453, 1457, 1477, 1481, 1494, 1496, 1507, 1512, 1538, 1545, 1547, 1549, 1551, 1554, 1561, + 1563, 1565, 1570, 1572, 1575, 1577, 1587, 1593, 1601, 1603, 1605, 1612, 1617, 1619, 1632, 1648, + 1658, 1662, 1664, 1674, 1680, 1690, 1692, 1704, 1729, 1736, 1740, 1745, 1747, 1751, 1752, 1761, + 1763, 1767, 1773, 1787, 1795, 1801, 1806, 1810, 1817, 1834, 1840, 1844, 1857, 1864, 1866, 1877, + 1882, 1892, 1902, 1915, 1934, 1953, 1985, 1987, 2000, 2002, 2013, 2048, 2052, 2058, 2064, 2068, + 2071, 2074, 2081, 2088, 2104, 2114, 2119, 2121, 2123, 2130, 2136, 2141, 2147, 2153, 2157, 2177, + 2179, 2184, 2189, 2193, 2203, 2208, 2223, 2226, 2232, 2244, 2249, 2251, 2256, 2258, 2265, 2269, + 2304, 2306, 2324, 2335, 2336, 2361, 2373, 2375, 2385, 2418, 2443, 2460, 2480, 2504, 2509, 2520, + 2531, 2537, 2562, 2568, 2572, 2578, 2592, 2596, 2599, 2602, 2614, 2620, 2625, 2627, 2629, 2634, + 2641, 2650, 2682, 2688, 2697, 2707, 2712, 2718, 2731, 2754, 2759, 2760, 2775, 2788, 2793, 2805, + 2811, 2817, 2820, 2832, 2842, 2854, 2890, 2902, 2921, 2923, 2978, 3010, 3012, 3026, 3081, 3083, + 3085, 3097, 3099, 3120, 3136, 3152, 3159, 3188, 3210, 3228, 3234, 3245, 3250, 3256, 3264, 3276, + 3281, 3296, 3349, 3363, 3378, 3392, 3395, 3420, 3440, 3461, 3488, 3529, 3531, 3584, 3588, 3591, + 3600, 3602, 3614, 3616, 3628, 3634, 3650, 3657, 3668, 3683, 3685, 3713, 3716, 3720, 3726, 3729, + 3736, 3753, 3778, 3802, 3805, 3819, 3841, 3845, 3851, 3856, 3880, 3922, 3938, 3970, 3993, 4032, + }; + + const int kmap_size = 4096; + const int nwant = grid_size == 256 ? 2 : 3; + const uint16_t * kgrid = grid_size == 256 ? kgrid_256 : kgrid_512; + uint32_t * kgrid_q3xs; + int * kmap_q3xs; + uint16_t * kneighbors_q3xs; + + //printf("================================================================= %s(grid_size = %d)\n", __func__, grid_size); + uint32_t * the_grid = (uint32_t *)malloc(grid_size*sizeof(uint32_t)); + for (int k = 0; k < grid_size; ++k) { + int8_t * pos = (int8_t *)(the_grid + k); + for (int i = 0; i < 4; ++i) { + int l = (kgrid[k] >> 3*i) & 0x7; + pos[i] = 2*l + 1; + } + } + kgrid_q3xs = the_grid; + iq3_data[gindex].grid = the_grid; + kmap_q3xs = (int *)malloc(kmap_size*sizeof(int)); + iq3_data[gindex].map = kmap_q3xs; + for (int i = 0; i < kmap_size; ++i) kmap_q3xs[i] = -1; + uint32_t aux32; + uint8_t * aux8 = (uint8_t *)&aux32; + for (int i = 0; i < grid_size; ++i) { + aux32 = kgrid_q3xs[i]; + uint16_t index = 0; + for (int k=0; k<4; ++k) { + uint16_t q = (aux8[k] - 1)/2; + index |= (q << 3*k); + } + kmap_q3xs[index] = i; + } + // See explanation of parallelism in iq2xs_init_impl + int * n_per_i = (int *)malloc(kmap_size*sizeof(int)); + GGML_ASSERT(n_per_i); + int num_neighbors = 0, num_not_in_map = 0; +#ifdef GGML_USE_OPENMP + #pragma omp parallel reduction(+:num_neighbors,num_not_in_map) +#endif + { + int * dist2 = (int *)malloc(2*grid_size*sizeof(int)); + GGML_ASSERT(dist2); + int8_t pos[4]; + int i; +#ifdef GGML_USE_OPENMP + #pragma omp for schedule(dynamic, 64) +#endif + for (i = 0; i < kmap_size; ++i) { + if (kmap_q3xs[i] >= 0) { + n_per_i[i] = 0; + continue; + } + ++num_not_in_map; + for (int k = 0; k < 4; ++k) { + int l = (i >> 3*k) & 0x7; + pos[k] = 2*l + 1; + } + for (int j = 0; j < grid_size; ++j) { + const int8_t * pg = (const int8_t *)(kgrid_q3xs + j); + int d2 = 0; + for (int k = 0; k < 4; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]); + dist2[2*j+0] = d2; + dist2[2*j+1] = j; + } + qsort(dist2, grid_size, 2*sizeof(int), iq3_compare_func); + int n = 0; int d2 = dist2[0]; + int nhave = 1; + for (int j = 0; j < grid_size; ++j) { + if (dist2[2*j] > d2) { + if (nhave == nwant) break; + d2 = dist2[2*j]; + ++nhave; + } + ++n; + } + n_per_i[i] = n; + num_neighbors += n; + } + free(dist2); + } + //printf("%s: %d neighbours in total\n", __func__, num_neighbors); + kneighbors_q3xs = (uint16_t *)malloc((num_neighbors + num_not_in_map)*sizeof(uint16_t)); + iq3_data[gindex].neighbours = kneighbors_q3xs; + + int * offsets = (int *)malloc(kmap_size*sizeof(int)); + GGML_ASSERT(offsets); + int counter = 0; + for (int i = 0; i < kmap_size; ++i) { + if (kmap_q3xs[i] >= 0) { + offsets[i] = -1; + continue; + } + offsets[i] = counter; + counter += 1 + n_per_i[i]; + } + +#ifdef GGML_USE_OPENMP + #pragma omp parallel +#endif + { + int * dist2 = (int *)malloc(2*grid_size*sizeof(int)); + GGML_ASSERT(dist2); + int8_t pos[4]; + int i; +#ifdef GGML_USE_OPENMP + #pragma omp for schedule(dynamic, 64) +#endif + for (i = 0; i < kmap_size; ++i) { + if (kmap_q3xs[i] >= 0) continue; + for (int k = 0; k < 4; ++k) { + int l = (i >> 3*k) & 0x7; + pos[k] = 2*l + 1; + } + for (int j = 0; j < grid_size; ++j) { + const int8_t * pg = (const int8_t *)(kgrid_q3xs + j); + int d2 = 0; + for (int k = 0; k < 4; ++k) d2 += (pg[k] - pos[k])*(pg[k] - pos[k]); + dist2[2*j+0] = d2; + dist2[2*j+1] = j; + } + qsort(dist2, grid_size, 2*sizeof(int), iq3_compare_func); + int local_counter = offsets[i]; + kmap_q3xs[i] = -(local_counter + 1); + int d2 = dist2[0]; + uint16_t * start = &kneighbors_q3xs[local_counter++]; + int n = 0, nhave = 1; + for (int j = 0; j < grid_size; ++j) { + if (dist2[2*j] > d2) { + if (nhave == nwant) break; + d2 = dist2[2*j]; + ++nhave; + } + kneighbors_q3xs[local_counter++] = dist2[2*j+1]; + ++n; + } + *start = n; + } + free(dist2); + } + free(offsets); + free(n_per_i); +} + +void iq3xs_free_impl(int grid_size) { + GGML_ASSERT(grid_size == 256 || grid_size == 512); + const int gindex = iq3_data_index(grid_size); + if (iq3_data[gindex].grid) { + free(iq3_data[gindex].grid); iq3_data[gindex].grid = NULL; + free(iq3_data[gindex].map); iq3_data[gindex].map = NULL; + free(iq3_data[gindex].neighbours); iq3_data[gindex].neighbours = NULL; + } +} + +static int iq3_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint32_t * GGML_RESTRICT grid, + const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, int8_t * GGML_RESTRICT L) { + int num_neighbors = neighbours[0]; + GGML_ASSERT(num_neighbors > 0); + float best_d2 = FLT_MAX; + int grid_index = -1; + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float d2 = 0; + for (int i = 0; i < 4; ++i) { + float q = pg[i]; + float diff = scale*q - xval[i]; + d2 += weight[i]*diff*diff; + } + if (d2 < best_d2) { + best_d2 = d2; grid_index = neighbours[j]; + } + } + GGML_ASSERT(grid_index >= 0); + const int8_t * pg = (const int8_t *)(grid + grid_index); + for (int i = 0; i < 4; ++i) L[i] = (pg[i] - 1)/2; + return grid_index; +} + +static void quantize_row_iq3_xxs_impl(int grid_size, const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, + const float * GGML_RESTRICT quant_weights) { + + const int gindex = iq3_data_index(grid_size); + + const uint32_t * kgrid_q3xs = iq3_data[gindex].grid; + const int * kmap_q3xs = iq3_data[gindex].map; + const uint16_t * kneighbors_q3xs = iq3_data[gindex].neighbours; + + //GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kgrid_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kmap_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + const int kMaxQ = 8; + + const int64_t nbl = n/QK_K; + + ggml_fp16_t * dh; + uint8_t * qs; + int block_size; + if (grid_size == 256) { + block_iq3_xxs * y = vy; + dh = &y->d; + qs = y->qs; + block_size = sizeof(block_iq3_xxs); + } else { + block_iq3_s * y = vy; + dh = &y->d; + qs = y->qs; + block_size = sizeof(block_iq3_s); + } + int quant_size = block_size - sizeof(ggml_fp16_t); + + float scales[QK_K/32]; + float weight[32]; + float xval[32]; + int8_t L[32]; + int8_t Laux[32]; + float waux[32]; + bool is_on_grid[8]; + bool is_on_grid_aux[8]; + uint8_t block_signs[8]; + uint8_t q3[3*(QK_K/8)+QK_K/32]; + uint32_t * scales_and_signs = (uint32_t *)(q3 + QK_K/4); + uint8_t * qh = q3 + 3*(QK_K/8); + + for (int ibl = 0; ibl < nbl; ++ibl) { + + dh[0] = GGML_FP32_TO_FP16(0.f); + memset(q3, 0, 3*QK_K/8+QK_K/32); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = 2*sumx2/QK_K; + + for (int ib = 0; ib < QK_K/32; ++ib) { + const float * xb = xbl + 32*ib; + if (quant_weights) { + const float * qw = quant_weights + QK_K*ibl + 32*ib; + for (int i = 0; i < 32; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + } else { + for (int i = 0; i < 32; ++i) weight[i] = xb[i]*xb[i]; + } + for (int i = 0; i < 32; ++i) waux[i] = sqrtf(weight[i]); + for (int k = 0; k < 4; ++k) { + int nflip = 0; + uint8_t s = 0; + for (int i = 0; i < 8; ++i) { + if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i]; + else { + xval[8*k + i] = -xb[8*k + i]; ++nflip; s |= (1 << i); + } + } + if (nflip%2) { + int imin = 0; float min = weight[8*k+imin]*xb[8*k+imin]*xb[8*k+imin]; + for (int i = 1; i < 8; ++i) { + float ax = weight[8*k+i]*xb[8*k+i]*xb[8*k+i]; + if (ax < min) { + min = ax; imin = i; + } + } + xval[8*k+imin] = -xval[8*k+imin]; + s ^= (1 << imin); + } + block_signs[k] = s & 127; + } + float max = xval[0]; + for (int i = 1; i < 32; ++i) max = MAX(max, xval[i]); + memset(L, 0, 32); + if (max < GROUP_MAX_EPS_IQ3_XXS) { + scales[ib] = 0; + continue; + } + float best = 0; + float scale = max/(2*kMaxQ-1); + for (int k = 0; k < 8; ++k) is_on_grid[k] = true; + for (int is = -15; is <= 15; ++is) { + float id = (2*kMaxQ-1+is*0.2f)/max; + float this_scale = 1/id; + for (int k = 0; k < 8; ++k) { + for (int i = 0; i < 4; ++i) { + int l = nearest_int(0.5f*(id*xval[4*k+i]-1)); + Laux[4*k+i] = MAX(0, MIN(kMaxQ-1, l)); + } + uint16_t u = 0; + for (int i = 0; i < 4; ++i) u |= (Laux[4*k+i] << 3*i); + int grid_index = kmap_q3xs[u]; + is_on_grid_aux[k] = true; + if (grid_index < 0) { + is_on_grid_aux[k] = false; + const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1; + grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, this_scale, Laux + 4*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 32; ++i) { + float w = weight[i]; + float q = 2*Laux[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + scale = sumqx/sumq2; best = scale*sumqx; + for (int i = 0; i < 32; ++i) L[i] = Laux[i]; + for (int k = 0; k < 8; ++k) is_on_grid[k] = is_on_grid_aux[k]; + } + } + int n_not_ongrid = 0; + for (int k = 0; k < 8; ++k) if (!is_on_grid[k]) ++n_not_ongrid; + if (n_not_ongrid > 0 && scale > 0) { + float id = 1/scale; + for (int k = 0; k < 8; ++k) { + if (is_on_grid[k]) continue; + uint16_t u = 0; + for (int i = 0; i < 4; ++i) { + int l = nearest_int(0.5f*(id*xval[4*k+i]-1)); + l = MAX(0, MIN(kMaxQ-1, l)); + u |= (l << 3*i); + } + int grid_index = kmap_q3xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1; + grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, scale, L + 4*k); + } + const int8_t * pg = (const int8_t *)(kgrid_q3xs + grid_index); + for (int i = 0; i < 4; ++i) L[4*k+i] = (pg[i] - 1)/2; + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 32; ++i) { + float w = weight[i]; + float q = 2*L[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0) scale = sumqx/sumq2; + } + if (scale < 0) { + // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale) + // and correspondingly flip quant signs. + scale = -scale; + for (int k = 0; k < 4; ++k) block_signs[k] = (~block_signs[k]) & 127; + } + for (int k = 0; k < 8; ++k) { + uint16_t u = 0; + for (int i = 0; i < 4; ++i) u |= (L[4*k+i] << 3*i); + int grid_index = kmap_q3xs[u]; + if (grid_index < 0) { + printf("Oops: found point %u not on grid:", u); + for (int i = 0; i < 4; ++i) printf(" %d", L[4*k+i]); + printf("\n"); + GGML_ABORT("fatal error"); + } + if (grid_size == 256) { + q3[8*ib+k] = grid_index; + } else { + q3[8*ib+k] = grid_index & 255; + qh[ib] |= ((grid_index >> 8) << k); + } + + } + scales_and_signs[ib] = block_signs[0] | (block_signs[1] << 7) | (block_signs[2] << 14) | (block_signs[3] << 21); + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + memset(qs, 0, quant_size); + dh += block_size/sizeof(ggml_fp16_t); + qs += block_size; + continue; + } + + float d = max_scale/31; + dh[0] = GGML_FP32_TO_FP16(d * 1.0125f); // small improvement via this fudge factor + float id = 1/d; + for (int ib = 0; ib < QK_K/32; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib]-1)); + l = MAX(0, MIN(15, l)); + scales_and_signs[ib] |= ((uint32_t)l << 28); + } + memcpy(qs, q3, quant_size); + + dh += block_size/sizeof(ggml_fp16_t); + qs += block_size; + + } +} + +size_t quantize_iq3_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq3_xxs_impl(256, src, qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += nblock*sizeof(block_iq3_xxs); + } + return nrow * nblock * sizeof(block_iq3_xxs); +} + +void quantize_row_iq3_xxs_ref(const float * GGML_RESTRICT x, block_iq3_xxs * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + quantize_row_iq3_xxs_impl(256, x, y, k, NULL); +} + +static void quantize_row_iq3_s_impl(int block_size, const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int n, + const float * GGML_RESTRICT quant_weights, + float * scales, + float * weight, + float * xval, + int8_t * L, + int8_t * Laux, + float * waux, + bool * is_on_grid, + bool * is_on_grid_aux, + uint8_t * block_signs) { + + const int gindex = iq3_data_index(512); + + const uint32_t * kgrid_q3xs = iq3_data[gindex].grid; + const int * kmap_q3xs = iq3_data[gindex].map; + const uint16_t * kneighbors_q3xs = iq3_data[gindex].neighbours; + + //GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kgrid_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kmap_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q3xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + const int kMaxQ = 8; + + const int64_t nbl = n/QK_K; + + block_iq3_s * y = vy; + + const int bs4 = block_size/4; + const int bs8 = block_size/8; + + for (int ibl = 0; ibl < nbl; ++ibl) { + + memset(&y[ibl], 0, sizeof(block_iq3_s)); + y[ibl].d = GGML_FP32_TO_FP16(0.f); + + uint8_t * qs = y[ibl].qs; + uint8_t * qh = y[ibl].qh; + uint8_t * signs = y[ibl].signs; + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = 2*sumx2/QK_K; + + for (int ib = 0; ib < QK_K/block_size; ++ib) { + const float * xb = xbl + block_size*ib; + if (quant_weights) { + const float * qw = quant_weights + QK_K*ibl + block_size*ib; + for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + } else { + for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i]; + } + for (int i = 0; i < block_size; ++i) waux[i] = sqrtf(weight[i]); + for (int k = 0; k < bs8; ++k) { + uint8_t s = 0; + for (int i = 0; i < 8; ++i) { + if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i]; + else { + xval[8*k + i] = -xb[8*k + i]; s |= (1 << i); + } + } + block_signs[k] = s; + } + float max = xval[0]; + for (int i = 1; i < block_size; ++i) max = MAX(max, xval[i]); + memset(L, 0, block_size); + if (!max) { + scales[ib] = 0; + continue; + } + float best = 0; + float scale = max/(2*kMaxQ-1); + for (int k = 0; k < bs4; ++k) is_on_grid[k] = false; + for (int is = -9; is <= 9; ++is) { + float id = (2*kMaxQ-1+is*0.2f)/max; + float this_scale = 1/id; + for (int k = 0; k < bs4; ++k) { + for (int i = 0; i < 4; ++i) { + int l = nearest_int(0.5f*(id*xval[4*k+i]-1)); + Laux[4*k+i] = MAX(0, MIN(kMaxQ-1, l)); + } + uint16_t u = 0; + for (int i = 0; i < 4; ++i) u |= (Laux[4*k+i] << 3*i); + int grid_index = kmap_q3xs[u]; + is_on_grid_aux[k] = true; + if (grid_index < 0) { + is_on_grid_aux[k] = false; + const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1; + grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, this_scale, Laux + 4*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < block_size; ++i) { + float w = weight[i]; + float q = 2*Laux[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + scale = sumqx/sumq2; best = scale*sumqx; + for (int i = 0; i < block_size; ++i) L[i] = Laux[i]; + for (int k = 0; k < bs4; ++k) is_on_grid[k] = is_on_grid_aux[k]; + } + } + int n_not_ongrid = 0; + for (int k = 0; k < bs4; ++k) if (!is_on_grid[k]) ++n_not_ongrid; + if (n_not_ongrid > 0 && scale > 0) { + float id = 1/scale; + for (int k = 0; k < bs4; ++k) { + //if (is_on_grid[k]) continue; + uint16_t u = 0; + for (int i = 0; i < 4; ++i) { + int l = nearest_int(0.5f*(id*xval[4*k+i]-1)); + l = MAX(0, MIN(kMaxQ-1, l)); + u |= (l << 3*i); + } + int grid_index = kmap_q3xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q3xs - kmap_q3xs[u] - 1; + grid_index = iq3_find_best_neighbour(neighbours, kgrid_q3xs, xval + 4*k, waux + 4*k, scale, L + 4*k); + } + const int8_t * pg = (const int8_t *)(kgrid_q3xs + grid_index); + for (int i = 0; i < 4; ++i) L[4*k+i] = (pg[i] - 1)/2; + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < block_size; ++i) { + float w = weight[i]; + float q = 2*L[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0) scale = sumqx/sumq2; + } + if (scale < 0) { + // This should never happen, but just in case, flip scale so that it is positive (we use uint's to encode the scale) + // and correspondingly flip quant signs. + scale = -scale; + for (int k = 0; k < bs8; ++k) block_signs[k] = ~block_signs[k]; + } + for (int k = 0; k < bs4; ++k) { + uint16_t u = 0; + for (int i = 0; i < 4; ++i) u |= (L[4*k+i] << 3*i); + int grid_index = kmap_q3xs[u]; + if (grid_index < 0) { + printf("Oops: found point %u not on grid:", u); + for (int i = 0; i < 4; ++i) printf(" %d", L[4*k+i]); + printf("\n"); + GGML_ABORT("fatal error"); + } + qs[k] = grid_index & 255; + qh[(ib*bs4+k)/8] |= ((grid_index >> 8) << ((ib*bs4+k)%8)); + } + qs += bs4; + for (int k = 0; k < bs8; ++k) signs[k] = block_signs[k]; + signs += bs8; + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + continue; + } + + float d = max_scale/31; + y[ibl].d = GGML_FP32_TO_FP16(d * 1.033f); + float id = 1/d; + for (int ib = 0; ib < QK_K/block_size; ib += 2) { + int l1 = nearest_int(0.5f*(id*scales[ib+0]-1)); + l1 = MAX(0, MIN(15, l1)); + int l2 = nearest_int(0.5f*(id*scales[ib+1]-1)); + l2 = MAX(0, MIN(15, l2)); + y[ibl].scales[ib/2] = l1 | (l2 << 4); + } + + } +} + +#define IQ3S_BLOCK_SIZE 32 +size_t quantize_iq3_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + float scales[QK_K/IQ3S_BLOCK_SIZE]; + float weight[IQ3S_BLOCK_SIZE]; + float xval[IQ3S_BLOCK_SIZE]; + int8_t L[IQ3S_BLOCK_SIZE]; + int8_t Laux[IQ3S_BLOCK_SIZE]; + float waux[IQ3S_BLOCK_SIZE]; + bool is_on_grid[IQ3S_BLOCK_SIZE/4]; + bool is_on_grid_aux[IQ3S_BLOCK_SIZE/4]; + uint8_t block_signs[IQ3S_BLOCK_SIZE/8]; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq3_s_impl(IQ3S_BLOCK_SIZE, src, qrow, n_per_row, quant_weights, + scales, weight, xval, L, Laux, waux, is_on_grid, is_on_grid_aux, block_signs); + src += n_per_row; + qrow += nblock*sizeof(block_iq3_s); + } + return nrow * nblock * sizeof(block_iq3_s); +} + +void quantize_row_iq3_s_ref(const float * GGML_RESTRICT x, block_iq3_s * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + quantize_iq3_s(x, y, 1, k, NULL); +} + + +// =================================== 1.5 bpw =================================================== + +static int iq1_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid, + const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float * scale, int8_t * GGML_RESTRICT L, int ngrid) { + int num_neighbors = neighbours[0]; + GGML_ASSERT(num_neighbors > 0); + float best_score = -FLT_MAX; + int grid_index = -1; + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 8; ++i) { + float q = (pg[i] - 3)/2; + float w = weight[i]; + sumqx += w*q*xval[i]; + sumq2 += w*q*q; + } + if (sumqx > 0 && sumq2 > 0 && sumqx*sumqx > best_score*sumq2) { + *scale = sumqx/sumq2; best_score = *scale * sumqx; + grid_index = neighbours[j]; + } + } + if (grid_index < 0) { + for (int i = 0; i < ngrid; ++i) { + const int8_t * grid_i = (const int8_t *)(grid + i); + float sumqx = 0, sumq2 = 0; + for (int j = 0; j < 8; ++j) { + float w = weight[j]; + float q = (grid_i[j] - 3)/2; + sumqx += w*q*xval[j]; + sumq2 += w*q*q; + } + if (sumqx > 0 && sumq2 > 0 && sumqx*sumqx > best_score*sumq2) { + *scale = sumqx/sumq2; best_score = *scale*sumqx; + grid_index = i; + } + } + } + if (grid_index < 0) { + printf("Oops, did not find grid point\n"); + printf("Have %d neighbours\n", num_neighbors); + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 8; ++i) { + float q = (pg[i] - 3)/2; + float w = weight[i]; + sumqx += w*q*xval[i]; + sumq2 += w*q*q; + } + printf(" neighbour %d: sumqx = %g sumq2 = %g\n", j, (double)sumqx, (double)sumq2); + } + } + GGML_ASSERT(grid_index >= 0); + //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + *scale *= 1.05f; // This is a fudge factor. Don't ask me why it improves the result. + //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + const int8_t * pg = (const int8_t *)(grid + grid_index); + for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2; + return grid_index; +} + +static int iq1_find_best_neighbour2(const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid, + const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, const float * GGML_RESTRICT xg, int8_t * GGML_RESTRICT L, int ngrid) { + int num_neighbors = neighbours[0]; + GGML_ASSERT(num_neighbors > 0); + float best_score = FLT_MAX; + int grid_index = -1; + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float d2 = 0; + for (int i = 0; i < 8; ++i) { + float q = xg[(pg[i] - 1)/2]; + float w = weight[i]; + float diff = scale*q - xval[i]; + d2 += w*diff*diff; + } + if (d2 < best_score) { + best_score = d2; + grid_index = neighbours[j]; + } + } + if (grid_index < 0) { + for (int i = 0; i < ngrid; ++i) { + const int8_t * grid_i = (const int8_t *)(grid + i); + float d2 = 0; + for (int j = 0; j < 8; ++j) { + float w = weight[j]; + float q = xg[(grid_i[j] - 1)/2]; + float diff = scale*q - xval[i]; + d2 += w*diff*diff; + } + if (d2 < best_score) { + best_score = d2; + grid_index = i; + } + } + } + if (grid_index < 0) { + printf("Oops, did not find grid point\n"); + printf("Have %d neighbours\n", num_neighbors); + for (int j = 1; j <= num_neighbors; ++j) { + const int8_t * pg = (const int8_t *)(grid + neighbours[j]); + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 8; ++i) { + float q = xg[(pg[i] - 1)/2]; + float w = weight[i]; + sumqx += w*q*xval[i]; + sumq2 += w*q*q; + } + printf(" neighbour %d: sumqx = %g sumq2 = %g\n", j, (double)sumqx, (double)sumq2); + } + } + GGML_ASSERT(grid_index >= 0); + const int8_t * pg = (const int8_t *)(grid + grid_index); + for (int i = 0; i < 8; ++i) L[i] = (pg[i] - 1)/2; + return grid_index; +} + +static int iq1_sort_helper(const void * left, const void * right) { + const float * l = left; + const float * r = right; + return *l < *r ? -1 : *l > *r ? 1 : 0; +} + +#define IQ1S_BLOCK_SIZE 32 +#define IQ1M_BLOCK_SIZE 16 +static void quantize_row_iq1_s_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights, + float * scales, + float * weight, + float * sumx, + float * sumw, + float * pairs, + int8_t * L, + uint16_t * index, + int8_t * shifts) { + + const int gindex = iq2_data_index(GGML_TYPE_IQ1_S); + + const uint64_t * kgrid_q2xs = iq2_data[gindex].grid; + const int * kmap_q2xs = iq2_data[gindex].map; + const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours; + + GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kgrid_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kmap_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + block_iq1_s * y = vy; + + const int64_t nbl = n/QK_K; + + const int block_size = IQ1S_BLOCK_SIZE; + + const float x_p[3] = {-1 + IQ1S_DELTA, IQ1S_DELTA, 1 + IQ1S_DELTA}; + const float x_m[3] = {-1 - IQ1S_DELTA, -IQ1S_DELTA, 1 - IQ1S_DELTA}; + + + int * idx = (int *)(pairs + 1); + + for (int ibl = 0; ibl < nbl; ++ibl) { + + y[ibl].d = GGML_FP32_TO_FP16(0.f); + memset(y[ibl].qs, 0, QK_K/8); + memset(y[ibl].qh, 0, QK_K/16); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = 2*sumx2/QK_K; + + for (int ib = 0; ib < QK_K/block_size; ++ib) { + const float * xb = xbl + block_size*ib; + const float * qw = quant_weights + QK_K*ibl + block_size*ib; + for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + float max = fabsf(xb[0]); + for (int i = 1; i < block_size; ++i) max = MAX(max, fabsf(xb[i])); + if (max < GROUP_MAX_EPS_IQ1_S) { + scales[ib] = 0; + shifts[ib] = 1; + memset(L, 1, block_size); + continue; + } + // Here we solve exactly the sum of squared difference (SSD) weighted minimization problem. + // With just 3 allowed quant values (-1, 0, 1), we can search exhaustively for the two + // boundaries that split the weights xb[i] into 3 groups. To do so, we sort the weights + // in ascending order, compute Si = sum[weight[j] xb[j], j = 0...i] and + // Wi = sum[weight[j], j = 0...i], and use these to quckly get get the optimum scale + // for each possible and score for each split. + for (int j = 0; j < block_size; ++j) { + pairs[2*j] = xb[j]; + idx[2*j] = j; + } + qsort(pairs, block_size, 2*sizeof(float), iq1_sort_helper); + { + sumx[0] = sumw[0] = 0; + for (int j = 0; j < block_size; ++j) { + int i = idx[2*j]; + sumx[j+1] = sumx[j] + weight[i]*xb[i]; + sumw[j+1] = sumw[j] + weight[i]; + } + } + float best_score = -FLT_MAX, scale = max; + int besti1 = -1, besti2 = -1, best_shift = 0; + for (int i1 = 0; i1 <= block_size; ++i1) { + for (int i2 = i1; i2 <= block_size; ++i2) { + float sumqx = (sumx[i1] - sumx[0])*x_p[0] + (sumx[i2] - sumx[i1])*x_p[1] + (sumx[block_size] - sumx[i2])*x_p[2]; + float sumq2 = (sumw[i1] - sumw[0])*x_p[0]*x_p[0] + (sumw[i2] - sumw[i1])*x_p[1]*x_p[1] + (sumw[block_size] - sumw[i2])*x_p[2]*x_p[2]; + if (sumq2 > 0 && sumqx*sumqx > best_score*sumq2) { + scale = sumqx/sumq2; best_score = scale*sumqx; + besti1 = i1; besti2 = i2; best_shift = 1; + } + sumqx = (sumx[i1] - sumx[0])*x_m[0] + (sumx[i2] - sumx[i1])*x_m[1] + (sumx[block_size] - sumx[i2])*x_m[2]; + sumq2 = (sumw[i1] - sumw[0])*x_m[0]*x_m[0] + (sumw[i2] - sumw[i1])*x_m[1]*x_m[1] + (sumw[block_size] - sumw[i2])*x_m[2]*x_m[2]; + if (sumq2 > 0 && sumqx*sumqx > best_score*sumq2) { + scale = sumqx/sumq2; best_score = scale*sumqx; + besti1 = i1; besti2 = i2; best_shift = -1; + } + } + } + if (besti1 < 0 || besti2 < 0 || best_shift == 0) { + scales[ib] = 0; + shifts[ib] = 1; + memset(L, 1, block_size); + continue; + } + for (int j = 0; j < besti1; ++j) L[idx[2*j]] = 0; + for (int j = besti1; j < besti2; ++j) L[idx[2*j]] = 1; + for (int j = besti2; j < block_size; ++j) L[idx[2*j]] = 2; + if (scale < 0) { + for (int j = 0; j < block_size; ++j) L[j] = 2 - L[j]; + scale = -scale; best_shift = -best_shift; + } + bool all_on_grid = true; + const float * xx = best_shift == 1 ? x_p : x_m; + for (int k = 0; k < block_size/8; ++k) { + uint16_t u = 0; + for (int j = 0; j < 8; ++j) u |= (L[8*k+j] << 2*j); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + all_on_grid = false; + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq1_find_best_neighbour2(neighbours, kgrid_q2xs, xb + 8*k, weight + 8*k, scale, xx, L + 8*k, NGRID_IQ1S); + GGML_ASSERT(grid_index >= 0); + } + index[k] = grid_index; + } + if (!all_on_grid) { + float sumqx = 0, sumq2 = 0; + for (int k = 0; k < block_size/8; ++k) { + const int8_t * pg = (const int8_t *)(kgrid_q2xs + index[k]); + for (int j = 0; j < 8; ++j) { + float w = weight[8*k + j]; + float q = xx[(pg[j] - 1)/2]; + sumqx += w*q*xb[8*k+j]; + sumq2 += w*q*q; + } + } + if (sumqx > 0 && sumq2 > 0) scale = sumqx/sumq2; + } + uint16_t h = 0; + for (int k = 0; k < block_size/8; ++k) { + y[ibl].qs[(block_size/8)*ib + k] = index[k] & 255; + h |= (index[k] >> 8) << 3*k; + } + y[ibl].qh[ib] = h; + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + shifts[ib] = best_shift; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + continue; + } + + float d = max_scale/15; + y[ibl].d = GGML_FP32_TO_FP16(d*1.125f); // 1.125f is another fudge factor. Don't ask me why it is needed. + float id = 1/d; + for (int ib = 0; ib < QK_K/block_size; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib]-1)); + l = MAX(0, MIN(7, l)); + if (shifts[ib] == -1) l |= 8; + y[ibl].qh[ib] |= (l << 12); + } + } +} + +size_t quantize_iq1_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + float scales[QK_K/IQ1S_BLOCK_SIZE]; + float weight[IQ1S_BLOCK_SIZE]; + int8_t L[IQ1S_BLOCK_SIZE]; + float sumx[IQ1S_BLOCK_SIZE+1]; + float sumw[IQ1S_BLOCK_SIZE+1]; + float pairs[2*IQ1S_BLOCK_SIZE]; + uint16_t index[IQ1S_BLOCK_SIZE/8]; + int8_t shifts[QK_K/IQ1S_BLOCK_SIZE]; + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq1_s_impl(src, qrow, n_per_row, quant_weights, scales, weight, sumx, sumw, pairs, L, index, shifts); + src += n_per_row; + qrow += nblock*sizeof(block_iq1_s); + } + return nrow * nblock * sizeof(block_iq1_s); +} + +static void quantize_row_iq1_m_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights, + float * scales, + float * weight, + float * pairs, + int8_t * L, + uint16_t * index, + int8_t * shifts) { + + const int gindex = iq2_data_index(GGML_TYPE_IQ1_M); + + const uint64_t * kgrid_q2xs = iq2_data[gindex].grid; + const int * kmap_q2xs = iq2_data[gindex].map; + const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours; + + //GGML_ASSERT(quant_weights && "missing quantization weights"); + GGML_ASSERT(kgrid_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kmap_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + block_iq1_m * y = vy; + + const int64_t nbl = n/QK_K; + + const int block_size = IQ1M_BLOCK_SIZE; + + const float x_p[3] = {-1 + IQ1M_DELTA, IQ1M_DELTA, 1 + IQ1M_DELTA}; + const float x_m[3] = {-1 - IQ1M_DELTA, -IQ1M_DELTA, 1 - IQ1M_DELTA}; + const uint8_t masks[4] = {0x00, 0x80, 0x08, 0x88}; + + int * idx = (int *)(pairs + 1); + + float sumqx[4], sumq2[4]; + + iq1m_scale_t s; + const float * xx; + + for (int ibl = 0; ibl < nbl; ++ibl) { + memset(y[ibl].qs, 0, QK_K/8); + memset(y[ibl].qh, 0, QK_K/16); + memset(y[ibl].scales, 0, QK_K/32); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = 2*sumx2/QK_K; + + for (int ib = 0; ib < QK_K/block_size; ++ib) { + const float * xb = xbl + block_size*ib; + if (quant_weights) { + const float * qw = quant_weights + QK_K*ibl + block_size*ib; + for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + } else { + for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i]; + } + float max = fabsf(xb[0]); + for (int i = 1; i < block_size; ++i) max = MAX(max, fabsf(xb[i])); + if (max < GROUP_MAX_EPS_IQ1_M) { + scales[ib] = 0; + shifts[ib] = 0; + memset(L, 1, block_size); + continue; + } + // Here we solve exactly the sum of squared difference (SSD) weighted minimization problem. + // With just 3 allowed quant values (-1, 0, 1), we can search exhaustively for the two + // boundaries that split the weights xb[i] into 3 groups. To do so, we sort the weights + // in ascending order, compute Si = sum[weight[j] xb[j], j = 0...i] and + // Wi = sum[weight[j], j = 0...i], and use these to quckly get get the optimum scale + // for each possible and score for each split. + for (int j = 0; j < block_size; ++j) { + pairs[2*j] = xb[j]; + idx[2*j] = j; + } + qsort(pairs, block_size, 2*sizeof(float), iq1_sort_helper); + float best_score = -FLT_MAX, scale = max; + int besti1 = -1, besti2 = -1, best_k = -1; + // 0: +, + + // 1: +, - + // 2: -, + + // 3: -, - + for (int i1 = 0; i1 <= block_size; ++i1) { + for (int i2 = i1; i2 <= block_size; ++i2) { + memset(sumqx, 0, 4*sizeof(float)); + memset(sumq2, 0, 4*sizeof(float)); + for (int j = 0; j < i1; ++j) { + int i = idx[2*j]; + if (i < block_size/2) { + sumqx[0] += weight[i]*x_p[0]*xb[i]; + sumqx[1] += weight[i]*x_p[0]*xb[i]; + sumqx[2] += weight[i]*x_m[0]*xb[i]; + sumqx[3] += weight[i]*x_m[0]*xb[i]; + sumq2[0] += weight[i]*x_p[0]*x_p[0]; + sumq2[1] += weight[i]*x_p[0]*x_p[0]; + sumq2[2] += weight[i]*x_m[0]*x_m[0]; + sumq2[3] += weight[i]*x_m[0]*x_m[0]; + } else { + sumqx[0] += weight[i]*x_p[0]*xb[i]; + sumqx[2] += weight[i]*x_p[0]*xb[i]; + sumqx[1] += weight[i]*x_m[0]*xb[i]; + sumqx[3] += weight[i]*x_m[0]*xb[i]; + sumq2[0] += weight[i]*x_p[0]*x_p[0]; + sumq2[2] += weight[i]*x_p[0]*x_p[0]; + sumq2[1] += weight[i]*x_m[0]*x_m[0]; + sumq2[3] += weight[i]*x_m[0]*x_m[0]; + } + } + for (int j = i1; j < i2; ++j) { + int i = idx[2*j]; + if (i < block_size/2) { + sumqx[0] += weight[i]*x_p[1]*xb[i]; + sumqx[1] += weight[i]*x_p[1]*xb[i]; + sumqx[2] += weight[i]*x_m[1]*xb[i]; + sumqx[3] += weight[i]*x_m[1]*xb[i]; + sumq2[0] += weight[i]*x_p[1]*x_p[1]; + sumq2[1] += weight[i]*x_p[1]*x_p[1]; + sumq2[2] += weight[i]*x_m[1]*x_m[1]; + sumq2[3] += weight[i]*x_m[1]*x_m[1]; + } else { + sumqx[0] += weight[i]*x_p[1]*xb[i]; + sumqx[2] += weight[i]*x_p[1]*xb[i]; + sumqx[1] += weight[i]*x_m[1]*xb[i]; + sumqx[3] += weight[i]*x_m[1]*xb[i]; + sumq2[0] += weight[i]*x_p[1]*x_p[1]; + sumq2[2] += weight[i]*x_p[1]*x_p[1]; + sumq2[1] += weight[i]*x_m[1]*x_m[1]; + sumq2[3] += weight[i]*x_m[1]*x_m[1]; + } + } + for (int j = i2; j < block_size; ++j) { + int i = idx[2*j]; + if (i < block_size/2) { + sumqx[0] += weight[i]*x_p[2]*xb[i]; + sumqx[1] += weight[i]*x_p[2]*xb[i]; + sumqx[2] += weight[i]*x_m[2]*xb[i]; + sumqx[3] += weight[i]*x_m[2]*xb[i]; + sumq2[0] += weight[i]*x_p[2]*x_p[2]; + sumq2[1] += weight[i]*x_p[2]*x_p[2]; + sumq2[2] += weight[i]*x_m[2]*x_m[2]; + sumq2[3] += weight[i]*x_m[2]*x_m[2]; + } else { + sumqx[0] += weight[i]*x_p[2]*xb[i]; + sumqx[2] += weight[i]*x_p[2]*xb[i]; + sumqx[1] += weight[i]*x_m[2]*xb[i]; + sumqx[3] += weight[i]*x_m[2]*xb[i]; + sumq2[0] += weight[i]*x_p[2]*x_p[2]; + sumq2[2] += weight[i]*x_p[2]*x_p[2]; + sumq2[1] += weight[i]*x_m[2]*x_m[2]; + sumq2[3] += weight[i]*x_m[2]*x_m[2]; + } + } + for (int k = 0; k < 4; ++k) { + if (sumq2[k] > 0 && sumqx[k]*sumqx[k] > best_score*sumq2[k]) { + scale = sumqx[k]/sumq2[k]; best_score = scale*sumqx[k]; + besti1 = i1; besti2 = i2; best_k = k; + } + } + } + } + if (besti1 < 0 || besti2 < 0 || best_k < 0) { + scales[ib] = 0; + shifts[ib] = 0; + memset(L, 1, block_size); + continue; + } + for (int j = 0; j < besti1; ++j) L[idx[2*j]] = 0; + for (int j = besti1; j < besti2; ++j) L[idx[2*j]] = 1; + for (int j = besti2; j < block_size; ++j) L[idx[2*j]] = 2; + if (scale < 0) { + for (int j = 0; j < block_size; ++j) L[j] = 2 - L[j]; + scale = -scale; + best_k = best_k == 0 ? 3 : best_k == 1 ? 2 : best_k == 2 ? 1 : 0; + } + bool all_on_grid = true; + for (int k = 0; k < block_size/8; ++k) { + if (k == 0) xx = best_k < 2 ? x_p : x_m; + else xx = best_k%2 == 0 ? x_p : x_m; + uint16_t u = 0; + for (int j = 0; j < 8; ++j) u |= (L[8*k+j] << 2*j); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + all_on_grid = false; + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq1_find_best_neighbour2(neighbours, kgrid_q2xs, xb + 8*k, weight + 8*k, scale, xx, L + 8*k, NGRID_IQ1S); + GGML_ASSERT(grid_index >= 0); + } + index[k] = grid_index; + } + if (!all_on_grid) { + float sumqx_f = 0, sumq2_f = 0; + for (int k = 0; k < block_size/8; ++k) { + if (k == 0) xx = best_k < 2 ? x_p : x_m; + else xx = best_k%2 == 0 ? x_p : x_m; + const int8_t * pg = (const int8_t *)(kgrid_q2xs + index[k]); + for (int j = 0; j < 8; ++j) { + float w = weight[8*k + j]; + float q = xx[(pg[j] - 1)/2]; + sumqx_f += w*q*xb[8*k+j]; + sumq2_f += w*q*q; + } + } + if (sumqx_f > 0 && sumq2_f > 0) scale = sumqx_f/sumq2_f; + } + y[ibl].qs[2*ib + 0] = index[0] & 255; + y[ibl].qs[2*ib + 1] = index[1] & 255; + y[ibl].qh[ib] = (index[0] >> 8) | ((index[1] >> 8) << 4); + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + shifts[ib] = best_k; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + continue; + } + + uint16_t * sc = (uint16_t *)y[ibl].scales; + float d = max_scale/15; + float id = 1/d; + float sumqx_f = 0, sumq2_f = 0; + for (int ib = 0; ib < QK_K/block_size; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib+0]-1)); + l = MAX(0, MIN(7, l)); + sc[ib/4] |= (l << 3*(ib%4)); + y[ibl].qh[ib] |= masks[shifts[ib]]; + const float * xb = xbl + block_size*ib; + if (quant_weights) { + const float * qw = quant_weights + QK_K*ibl + block_size*ib; + for (int i = 0; i < block_size; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + } else { + for (int i = 0; i < block_size; ++i) weight[i] = xb[i]*xb[i]; + } + for (int k = 0; k < block_size/8; ++k) { + if (k == 0) xx = shifts[ib] < 2 ? x_p : x_m; + else xx = shifts[ib]%2 == 0 ? x_p : x_m; + const int8_t * pg = (const int8_t *)(kgrid_q2xs + y[ibl].qs[2*ib+k] + ((y[ibl].qh[ib] << (8 - 4*k)) & 0x700)); + for (int j = 0; j < 8; ++j) { + float w = weight[8*k + j]; + float q = xx[(pg[j] - 1)/2]*(2*l+1); + sumqx_f += w*q*xb[8*k+j]; + sumq2_f += w*q*q; + } + } + } + if (sumq2_f > 0) d = sumqx_f/sumq2_f; + s.f16 = GGML_FP32_TO_FP16(d*1.1125f); // 1.1125f is another fudge factor. Don't ask me why it is needed. + sc[0] |= ((s.u16 & 0x000f) << 12); + sc[1] |= ((s.u16 & 0x00f0) << 8); + sc[2] |= ((s.u16 & 0x0f00) << 4); + sc[3] |= ((s.u16 & 0xf000) << 0); + } +} + +size_t quantize_iq1_m(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + float scales[QK_K/IQ1M_BLOCK_SIZE]; + float weight[IQ1M_BLOCK_SIZE]; + int8_t L[IQ1M_BLOCK_SIZE]; + float pairs[2*IQ1M_BLOCK_SIZE]; + uint16_t index[IQ1M_BLOCK_SIZE/8]; + int8_t shifts[QK_K/IQ1M_BLOCK_SIZE]; + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq1_m_impl(src, qrow, n_per_row, quant_weights, scales, weight, pairs, L, index, shifts); + src += n_per_row; + qrow += nblock*sizeof(block_iq1_m); + } + return nrow * nblock * sizeof(block_iq1_m); +} + +// ============================ 4-bit non-linear quants + +static void quantize_row_iq4_nl_impl(const int super_block_size, const int block_size, const float * GGML_RESTRICT x, + ggml_fp16_t * dh, uint8_t * q4, uint16_t * scales_h, uint8_t * scales_l, + float * scales, float * weight, uint8_t * L, + const int8_t * values, + const float * quant_weights, + const int ntry) { + + float sigma2 = 0; + for (int j = 0; j < super_block_size; ++j) sigma2 += x[j]*x[j]; + sigma2 *= 2.f/super_block_size; + + memset(q4, 0, super_block_size/2); + dh[0] = GGML_FP32_TO_FP16(0.f); + + float max_scale = 0, amax_scale = 0; + for (int ib = 0; ib < super_block_size/block_size; ++ib) { + const float * xb = x + ib*block_size; + uint8_t * Lb = L + ib*block_size; + if (quant_weights) { + const float * qw = quant_weights + ib*block_size; + for (int j = 0; j < block_size; ++j) weight[j] = qw[j] * sqrtf(sigma2 + xb[j]*xb[j]); + } else { + for (int j = 0; j < block_size; ++j) weight[j] = xb[j]*xb[j]; + } + float amax = 0, max = 0; + for (int j = 0; j < block_size; ++j) { + float ax = fabsf(xb[j]); + if (ax > amax) { + amax = ax; max = xb[j]; + } + } + if (amax < GROUP_MAX_EPS) { + scales[ib] = 0; + continue; + } + float d = ntry > 0 ? -max/values[0] : max/values[0]; + float id = 1/d; + float sumqx = 0, sumq2 = 0; + for (int j = 0; j < block_size; ++j) { + float al = id*xb[j]; + int l = best_index_int8(16, values, al); + Lb[j] = l; + float q = values[l]; + float w = weight[j]; + sumqx += w*q*xb[j]; + sumq2 += w*q*q; + } + d = sumq2 > 0 ? sumqx/sumq2 : 0.f; + float best = d*sumqx; + for (int itry = -ntry; itry <= ntry; ++itry) { + id = (itry + values[0])/max; + sumqx = sumq2 = 0; + for (int j = 0; j < block_size; ++j) { + float al = id*xb[j]; + int l = best_index_int8(16, values, al); + float q = values[l]; + float w = weight[j]; + sumqx += w*q*xb[j]; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + d = sumqx/sumq2; best = d * sumqx; + } + } + scales[ib] = d; + float abs_d = fabsf(d); + if (abs_d > amax_scale) { + amax_scale = abs_d; max_scale = d; + } + } + + if (super_block_size/block_size > 1) { + int nb = super_block_size/block_size; + memset(scales_h, 0, ((nb+7)/8)*sizeof(uint16_t)); + float d = -max_scale/32; + dh[0] = GGML_FP32_TO_FP16(d); + float id = d ? 1/d : 0.f; + for (int ib = 0; ib < super_block_size/block_size; ++ib) { + int l = nearest_int(id*scales[ib]); + l = MAX(-32, MIN(31, l)); + float dl = d * l; + float idl = dl ? 1/dl : 0.f; + uint8_t * Lb = L + ib*block_size; + const float * xb = x + ib*block_size; + for (int j = 0; j < block_size; ++j) { + Lb[j] = best_index_int8(16, values, idl*xb[j]); + } + l += 32; + uint8_t l_l = l & 0xf; + uint8_t l_h = l >> 4; + if (ib%2 == 0) scales_l[ib/2] = l_l; + else scales_l[ib/2] |= (l_l << 4); + scales_h[ib/8] |= (l_h << 2*(ib%8)); + } + } else { + dh[0] = GGML_FP32_TO_FP16(scales[0]); + if (ntry > 0) { + float id = scales[0] ? 1/scales[0] : 0; + for (int j = 0; j < super_block_size; ++j) { + L[j] = best_index_int8(16, values, id*x[j]); + } + } + } + + for (int i = 0; i < super_block_size/32; ++i) { + for (int j = 0; j < 16; ++j) { + q4[16*i + j] = L[32*i + j] | (L[32*i + 16 + j] << 4); + } + } +} + +size_t quantize_iq4_nl(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK4_NL == 0); + int64_t nblock = n_per_row/QK4_NL; + char * qrow = (char *)dst; + uint8_t L[QK4_NL]; + float weight[QK4_NL]; + uint16_t unused_h; + uint8_t * unused_l = NULL; + float scale; + for (int64_t row = 0; row < nrow; ++row) { + block_iq4_nl * iq4 = (block_iq4_nl *)qrow; + for (int ibl = 0; ibl < nblock; ++ibl) { + const float * qw = quant_weights ? quant_weights + QK4_NL*ibl : NULL; + quantize_row_iq4_nl_impl(QK4_NL, 32, src + QK4_NL*ibl, &iq4[ibl].d, iq4[ibl].qs, &unused_h, unused_l, + &scale, weight, L, kvalues_iq4nl, qw, 7); + } + src += n_per_row; + qrow += nblock*sizeof(block_iq4_nl); + } + return nrow * nblock * sizeof(block_iq4_nl); +} + +//void quantize_row_iq4_nl_ref(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) { +void quantize_row_iq4_nl_ref(const float * GGML_RESTRICT x, block_iq4_nl * GGML_RESTRICT y, int64_t k) { + GGML_ASSERT(k%QK4_NL == 0); + int64_t nblock = k/QK4_NL; + uint8_t L[QK4_NL]; + float weight[QK4_NL]; + uint16_t unused_h; + uint8_t * unused_l = NULL; + float scale; + block_iq4_nl * iq4 = y; + for (int ibl = 0; ibl < nblock; ++ibl) { + quantize_row_iq4_nl_impl(QK4_NL, 32, x + QK4_NL*ibl, &iq4[ibl].d, iq4[ibl].qs, &unused_h, unused_l, + &scale, weight, L, kvalues_iq4nl, NULL, -1); + } +} + +size_t quantize_iq4_xs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + uint8_t L[QK_K]; + float weight[32]; + float scales[QK_K/32]; + for (int64_t row = 0; row < nrow; ++row) { + block_iq4_xs * iq4 = (block_iq4_xs *)qrow; + for (int ibl = 0; ibl < nblock; ++ibl) { + const float * qw = quant_weights ? quant_weights + QK_K*ibl : NULL; + quantize_row_iq4_nl_impl(QK_K, 32, src + QK_K*ibl, &iq4[ibl].d, iq4[ibl].qs, &iq4[ibl].scales_h, iq4[ibl].scales_l, + scales, weight, L, kvalues_iq4nl, qw, 7); + } + src += n_per_row; + qrow += nblock*sizeof(block_iq4_xs); + } + return nrow * nblock * sizeof(block_iq4_xs); +} + +void quantize_row_iq4_xs_ref(const float * GGML_RESTRICT x, block_iq4_xs * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + quantize_iq4_xs(x, y, 1, k, NULL); +} + +// =============================== 2.5625 bpw + +static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) { + + const int gindex = iq2_data_index(GGML_TYPE_IQ2_S); + + const uint64_t * kgrid_q2xs = iq2_data[gindex].grid; + const int * kmap_q2xs = iq2_data[gindex].map; + const uint16_t * kneighbors_q2xs = iq2_data[gindex].neighbours; + + GGML_ASSERT(kmap_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kgrid_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(kneighbors_q2xs && "forgot to call ggml_quantize_init()?"); + GGML_ASSERT(n%QK_K == 0); + + const int kMaxQ = 3; + + const int64_t nbl = n/QK_K; + + block_iq2_s * y = vy; + + float scales[QK_K/16]; + float weight[16]; + float xval[16]; + int8_t L[16]; + int8_t Laux[16]; + float waux[16]; + bool is_on_grid[2]; + bool is_on_grid_aux[2]; + uint8_t block_signs[2]; + + for (int ibl = 0; ibl < nbl; ++ibl) { + + memset(&y[ibl], 0, sizeof(block_iq2_s)); + y[ibl].d = GGML_FP32_TO_FP16(0.f); + + float max_scale = 0; + + const float * xbl = x + QK_K*ibl; + float sumx2 = 0; + for (int i = 0; i < QK_K; ++i) sumx2 += xbl[i]*xbl[i]; + float sigma2 = 2*sumx2/QK_K; + + for (int ib = 0; ib < QK_K/16; ++ib) { + const float * xb = xbl + 16*ib; + if (quant_weights) { + const float * qw = quant_weights + QK_K*ibl + 16*ib; + for (int i = 0; i < 16; ++i) weight[i] = qw[i] * sqrtf(sigma2 + xb[i]*xb[i]); + } else { + for (int i = 0; i < 16; ++i) weight[i] = 0.25f*sigma2 + xb[i]*xb[i]; + } + for (int i = 0; i < 16; ++i) waux[i] = sqrtf(weight[i]); + for (int k = 0; k < 2; ++k) { + uint8_t s = 0; + for (int i = 0; i < 8; ++i) { + if (xb[8*k + i] >= 0) xval[8*k + i] = xb[8*k + i]; + else { + xval[8*k + i] = -xb[8*k + i]; s |= (1 << i); + } + } + block_signs[k] = s; + } + float max = xval[0]; + for (int i = 1; i < 16; ++i) max = MAX(max, xval[i]); + memset(L, 0, 16); + if (max < GROUP_MAX_EPS_IQ2_S) { + scales[ib] = 0; + continue; + } + float best = 0; + float scale = max/(2*kMaxQ-1); + is_on_grid[0] = is_on_grid[1] = true; + for (int is = -9; is <= 9; ++is) { + float id = (2*kMaxQ-1+is*0.1f)/max; + float this_scale = 1/id; + for (int k = 0; k < 2; ++k) { + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + Laux[8*k+i] = MAX(0, MIN(kMaxQ-1, l)); + } + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (Laux[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + is_on_grid_aux[k] = true; + if (grid_index < 0) { + is_on_grid_aux[k] = false; + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 16; ++i) { + float w = weight[i]; + float q = 2*Laux[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0 && sumqx*sumqx > best*sumq2) { + scale = sumqx/sumq2; best = scale*sumqx; + for (int i = 0; i < 16; ++i) L[i] = Laux[i]; + for (int k = 0; k < 2; ++k) is_on_grid[k] = is_on_grid_aux[k]; + } + } + int n_not_ongrid = 0; + for (int k = 0; k < 2; ++k) if (!is_on_grid[k]) ++n_not_ongrid; + if (n_not_ongrid > 0 && scale > 0) { + float id = 1/scale; + for (int k = 0; k < 2; ++k) { + if (is_on_grid[k]) continue; + uint16_t u = 0; + for (int i = 0; i < 8; ++i) { + int l = nearest_int(0.5f*(id*xval[8*k+i]-1)); + l = MAX(0, MIN(kMaxQ-1, l)); + u |= (l << 2*i); + L[8*k + i] = l; + } + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; + grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + } + } + float sumqx = 0, sumq2 = 0; + for (int i = 0; i < 16; ++i) { + float w = weight[i]; + float q = 2*L[i] + 1; + sumqx += w*xval[i]*q; + sumq2 += w*q*q; + } + if (sumq2 > 0) scale = sumqx/sumq2; + } + if (scale < 0) { + scale = -scale; + for (int k = 0; k < 2; ++k) block_signs[k] = ~block_signs[k]; + } + for (int k = 0; k < 2; ++k) { + uint16_t u = 0; + for (int i = 0; i < 8; ++i) u |= (L[8*k+i] << 2*i); + int grid_index = kmap_q2xs[u]; + if (grid_index < 0) { + printf("Oops: found point %u not on grid:", u); + for (int i = 0; i < 8; ++i) printf(" %d", L[8*k+i]); + printf("\n"); + GGML_ABORT("fatal error"); + } + const int i8 = 2*ib + k; + y[ibl].qs[i8] = grid_index & 255; + y[ibl].qh[i8/4] |= ((grid_index >> 8) << 2*(i8%4)); + y[ibl].qs[QK_K/8 + i8] = block_signs[k]; + } + GGML_ASSERT(scale >= 0); + scales[ib] = scale; + max_scale = MAX(max_scale, scale); + } + + if (!max_scale) { + continue; + } + + float d = max_scale/31; + y[ibl].d = GGML_FP32_TO_FP16(d * 0.9875f); + float id = 1/d; + for (int ib = 0; ib < QK_K/16; ++ib) { + int l = nearest_int(0.5f*(id*scales[ib]-1)); + l = MAX(0, MIN(15, l)); + if (ib%2 == 0) y[ibl].scales[ib/2] = l; + else y[ibl].scales[ib/2] |= (l << 4); + } + } +} + +size_t quantize_iq2_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrow, int64_t n_per_row, const float * quant_weights) { + GGML_ASSERT(n_per_row%QK_K == 0); + int64_t nblock = n_per_row/QK_K; + char * qrow = (char *)dst; + for (int64_t row = 0; row < nrow; ++row) { + quantize_row_iq2_s_impl(src, qrow, n_per_row, quant_weights); + src += n_per_row; + qrow += nblock*sizeof(block_iq2_s); + } + return nrow * nblock * sizeof(block_iq2_s); +} + +void quantize_row_iq2_s_ref(const float * GGML_RESTRICT x, block_iq2_s * GGML_RESTRICT y, int64_t k) { + assert(k % QK_K == 0); + quantize_iq2_s(x, y, 1, k, NULL); +} + +// =============================== data validation + +static bool validate_float(float f, size_t i) { + if (isinf(f)) { + fprintf(stderr, "ggml_validate_row_data: found inf value at block %zu\n", i); + return false; + } + + if (isnan(f)) { + fprintf(stderr, "ggml_validate_row_data: found nan value at block %zu\n", i); + return false; + } + + return true; +} + +static bool isinf_fp16(ggml_fp16_t f) { + return (f & 0x7c00) == 0x7c00 && (f & 0x03ff) == 0; +} + +static bool isnan_fp16(ggml_fp16_t f) { + return (f & 0x7c00) == 0x7c00 && (f & 0x03ff) != 0; +} + +static bool validate_fp16(ggml_fp16_t f, size_t i) { + if (isinf_fp16(f)) { + fprintf(stderr, "ggml_validate_row_data: found inf value at block %zu\n", i); + return false; + } + + if (isnan_fp16(f)) { + fprintf(stderr, "ggml_validate_row_data: found nan value at block %zu\n", i); + return false; + } + + return true; +} + +static bool validate_e_e8m0(uint8_t e, size_t i) { + if (e == 0xff) { + fprintf(stderr, "ggml_validate_row_data: found invalid e value %d at block %zu\n", e, i); + return false; + } + + return true; +} + +#define VALIDATE_ROW_DATA_D_F16_IMPL(type, data, nb) \ + const type * q = (const type *) (data); \ + for (size_t i = 0; i < (nb); ++i) { \ + if (!validate_fp16(q[i].d, i)) { \ + return false; \ + } \ + } + +#define VALIDATE_ROW_DATA_DM_F16_IMPL(type, data, nb, d, m) \ + const type * q = (const type *) (data); \ + for (size_t i = 0; i < (nb); ++i) { \ + if (!validate_fp16(q[i].d, i) || !validate_fp16(q[i].m, i)) { \ + return false; \ + } \ + } + +#define VALIDATE_ROW_DATA_E_E8M0_IMPL(type, data, nb) \ + const type * q = (const type *) (data); \ + for (size_t i = 0; i < (nb); ++i) { \ + if (!validate_e_e8m0(q[i].e, i)) { \ + return false; \ + } \ + } + +#define VALIDATE_ROW_DATA_DVEC_F16_IMPL(type, data, nb, nr) \ + const type * q = (const type *) (data); \ + for (size_t i = 0; i < (nb); ++i) { \ + for (size_t j = 0; j < (nr); ++j) { \ + if (!validate_fp16(q[i].d[j], i)) { \ + return false; \ + } \ + } \ + } + +bool ggml_validate_row_data(enum ggml_type type, const void * data, size_t nbytes) { + if (type < 0 || type >= GGML_TYPE_COUNT) { + fprintf(stderr, "%s: invalid type %d\n", __func__, type); + return false; + } + + if (nbytes % ggml_type_size(type) != 0) { + fprintf(stderr, "%s: invalid size %zu for type %s (type size = %zu)\n", __func__, nbytes, ggml_type_name(type), ggml_type_size(type)); + return false; + } + + const size_t nb = nbytes/ggml_type_size(type); + + switch (type) { + case GGML_TYPE_BF16: + { + int nans = 0; + int infs = 0; + const unsigned short * f = (const unsigned short *) data; + for (size_t i = 0; i < nb; ++i) { + nans += (f[i] & 0x7fff) > 0x7f80; + infs += (f[i] & 0x7fff) == 0x7f80; + } + if (nans) { + fprintf(stderr, "%s: found %d NaNs in row of %zu BF16 values\n", __func__, nans, nb); + return false; + } + if (infs) { + fprintf(stderr, "%s: found %d infinities in row of %zu BF16 values\n", __func__, infs, nb); + return false; + } + } break; + case GGML_TYPE_F16: + { + const ggml_fp16_t * f = (const ggml_fp16_t *) data; + size_t i = 0; +#if defined(__AVX2__) + for (; i + 15 < nb; i += 16) { + __m256i v = _mm256_loadu_si256((const __m256i *)(f + i)); + __m256i vexp = _mm256_and_si256(v, _mm256_set1_epi16(0x7c00)); + __m256i cmp = _mm256_cmpeq_epi16(vexp, _mm256_set1_epi16(0x7c00)); + int mask = _mm256_movemask_epi8(cmp); + if (mask) { + for (size_t j = 0; j < 16; ++j) { + if (!validate_fp16(f[i + j], i + j)) { + return false; + } + } + GGML_UNREACHABLE(); + } + } +#elif defined(__ARM_NEON) + for (; i + 7 < nb; i += 8) { + uint16x8_t v = vld1q_u16(f + i); + uint16x8_t vexp = vandq_u16(v, vdupq_n_u16(0x7c00)); + uint16x8_t cmp = vceqq_u16(vexp, vdupq_n_u16(0x7c00)); + uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(cmp, 4)), 0); + if (mask) { + for (size_t j = 0; j < 8; ++j) { + if (!validate_fp16(f[i + j], i + j)) { + return false; + } + } + GGML_UNREACHABLE(); + } + } +#endif + for (; i < nb; ++i) { + if (!validate_fp16(f[i], i)) { + return false; + } + } + } break; + case GGML_TYPE_F32: + { + const float * f = (const float *) data; + size_t i = 0; +#if defined(__AVX2__) + for (; i + 7 < nb; i += 8) { + __m256i v = _mm256_loadu_si256((const __m256i *)(f + i)); + __m256i vexp = _mm256_and_si256(v, _mm256_set1_epi32(0x7f800000)); + __m256i cmp = _mm256_cmpeq_epi32(vexp, _mm256_set1_epi32(0x7f800000)); + int mask = _mm256_movemask_epi8(cmp); + if (mask) { + for (size_t j = 0; j < 8; ++j) { + if (!validate_float(f[i + j], i + j)) { + return false; + } + } + GGML_UNREACHABLE(); + } + } +#elif defined(__ARM_NEON) + for (; i + 3 < nb; i += 4) { + uint32x4_t v = vld1q_u32((const uint32_t *)f + i); + uint32x4_t vexp = vandq_u32(v, vdupq_n_u32(0x7f800000)); + uint32x4_t cmp = vceqq_u32(vexp, vdupq_n_u32(0x7f800000)); + uint64_t mask = vget_lane_u64(vreinterpret_u64_u16(vshrn_n_u32(cmp, 8)), 0); + if (mask) { + for (size_t j = 0; j < 4; ++j) { + if (!validate_float(f[i + j], i + j)) { + return false; + } + } + GGML_UNREACHABLE(); + } + } +#endif + for (; i < nb; ++i) { + if (!validate_float(f[i], i)) { + return false; + } + } + } break; + case GGML_TYPE_F64: + { + const double * f = (const double *) data; + for (size_t i = 0; i < nb; ++i) { + if (!validate_float(f[i], i)) { + return false; + } + } + } break; + case GGML_TYPE_Q1_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q1_0, data, nb); + } break; + case GGML_TYPE_Q2_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q2_0, data, nb); + } break; + case GGML_TYPE_Q4_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q4_0, data, nb); + } break; + case GGML_TYPE_Q4_1: + { + VALIDATE_ROW_DATA_DM_F16_IMPL(block_q4_1, data, nb, d, m); + } break; + case GGML_TYPE_Q5_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q5_0, data, nb); + } break; + case GGML_TYPE_Q5_1: + { + VALIDATE_ROW_DATA_DM_F16_IMPL(block_q5_1, data, nb, d, m); + } break; + case GGML_TYPE_Q8_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q8_0, data, nb); + } break; + case GGML_TYPE_MXFP4: + { + VALIDATE_ROW_DATA_E_E8M0_IMPL(block_mxfp4, data, nb); + } break; + case GGML_TYPE_NVFP4: + { + // UE4M3 scales are uint8_t — all byte values are valid + GGML_UNUSED(data); + GGML_UNUSED(nb); + } break; + case GGML_TYPE_Q2_K: + { + VALIDATE_ROW_DATA_DM_F16_IMPL(block_q2_K, data, nb, d, dmin); + } break; + case GGML_TYPE_Q3_K: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q3_K, data, nb); + } break; + case GGML_TYPE_Q4_K: + { + VALIDATE_ROW_DATA_DM_F16_IMPL(block_q4_K, data, nb, d, dmin); + } break; + case GGML_TYPE_Q5_K: + { + VALIDATE_ROW_DATA_DM_F16_IMPL(block_q5_K, data, nb, d, dmin); + } break; + case GGML_TYPE_Q6_K: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_q6_K, data, nb); + } break; + case GGML_TYPE_Q8_K: + { + const block_q8_K * q = (const block_q8_K *) data; + for (size_t i = 0; i < nb; ++i) { + if (!validate_float(q[i].d, i)) { + return false; + } + } + } break; + case GGML_TYPE_TQ1_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_tq1_0, data, nb); + } break; + case GGML_TYPE_TQ2_0: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_tq2_0, data, nb); + } break; + case GGML_TYPE_IQ1_S: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq1_s, data, nb); + } break; + case GGML_TYPE_IQ1_M: + { + const block_iq1_m * q = (const block_iq1_m *) data; + for (size_t i = 0; i < nb; ++i) { + iq1m_scale_t scale; + const uint16_t * sc = (const uint16_t *)q[i].scales; + scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); + if (!validate_fp16(scale.f16, i)) { + return false; + } + } + } break; + case GGML_TYPE_IQ2_XXS: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_xxs, data, nb); + } break; + case GGML_TYPE_IQ2_XS: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_xs, data, nb); + } break; + case GGML_TYPE_IQ2_S: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq2_s, data, nb); + } break; + case GGML_TYPE_IQ3_XXS: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq3_xxs, data, nb); + } break; + + case GGML_TYPE_IQ3_S: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq3_s, data, nb); + } break; + case GGML_TYPE_IQ4_XS: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq4_xs, data, nb); + } break; + case GGML_TYPE_IQ4_NL: + { + VALIDATE_ROW_DATA_D_F16_IMPL(block_iq4_nl, data, nb); + } break; + + case GGML_TYPE_I8: + case GGML_TYPE_I16: + case GGML_TYPE_I32: + case GGML_TYPE_I64: + // nothing to validate + break; + default: + { + fprintf(stderr, "%s: invalid type %d\n", __func__, type); + return false; + } + } + + return true; +} diff --git a/control-plane/third_party/ggml/ggml-quants.h b/control-plane/third_party/ggml/ggml-quants.h new file mode 100644 index 00000000..75188f1a --- /dev/null +++ b/control-plane/third_party/ggml/ggml-quants.h @@ -0,0 +1,115 @@ +#pragma once + +#define GGML_COMMON_DECL_C +#include "ggml-common.h" + +#include "ggml.h" + +// GGML internal header + +#ifdef __cplusplus +extern "C" { +#endif + +// NOTE: these functions are defined as GGML_API because they used by the CPU backend + +// Quantization +GGML_API void quantize_row_q1_0_ref(const float * GGML_RESTRICT x, block_q1_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q2_0_ref(const float * GGML_RESTRICT x, block_q2_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q4_0_ref(const float * GGML_RESTRICT x, block_q4_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q4_1_ref(const float * GGML_RESTRICT x, block_q4_1 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q5_0_ref(const float * GGML_RESTRICT x, block_q5_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q5_1_ref(const float * GGML_RESTRICT x, block_q5_1 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q8_0_ref(const float * GGML_RESTRICT x, block_q8_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q8_1_ref(const float * GGML_RESTRICT x, block_q8_1 * GGML_RESTRICT y, int64_t k); + +GGML_API void quantize_row_mxfp4_ref(const float * GGML_RESTRICT x, block_mxfp4 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_nvfp4_ref(const float * GGML_RESTRICT x, block_nvfp4 * GGML_RESTRICT y, int64_t k); + +GGML_API void quantize_row_q2_K_ref(const float * GGML_RESTRICT x, block_q2_K * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q3_K_ref(const float * GGML_RESTRICT x, block_q3_K * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q4_K_ref(const float * GGML_RESTRICT x, block_q4_K * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q5_K_ref(const float * GGML_RESTRICT x, block_q5_K * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q6_K_ref(const float * GGML_RESTRICT x, block_q6_K * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_q8_K_ref(const float * GGML_RESTRICT x, block_q8_K * GGML_RESTRICT y, int64_t k); + +GGML_API void quantize_row_tq1_0_ref(const float * GGML_RESTRICT x, block_tq1_0 * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_tq2_0_ref(const float * GGML_RESTRICT x, block_tq2_0 * GGML_RESTRICT y, int64_t k); + +GGML_API void quantize_row_iq3_xxs_ref(const float * GGML_RESTRICT x, block_iq3_xxs * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_iq4_nl_ref (const float * GGML_RESTRICT x, block_iq4_nl * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_iq4_xs_ref (const float * GGML_RESTRICT x, block_iq4_xs * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_iq3_s_ref (const float * GGML_RESTRICT x, block_iq3_s * GGML_RESTRICT y, int64_t k); +GGML_API void quantize_row_iq2_s_ref (const float * GGML_RESTRICT x, block_iq2_s * GGML_RESTRICT y, int64_t k); + +// Dequantization +GGML_API void dequantize_row_q1_0(const block_q1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q2_0(const block_q2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q4_0(const block_q4_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q4_1(const block_q4_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q5_0(const block_q5_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q5_1(const block_q5_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q8_0(const block_q8_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +//GGML_API void dequantize_row_q8_1(const block_q8_1 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + +GGML_API void dequantize_row_mxfp4(const block_mxfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_nvfp4(const block_nvfp4 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + +GGML_API void dequantize_row_q2_K(const block_q2_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q3_K(const block_q3_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q4_K(const block_q4_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q5_K(const block_q5_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q6_K(const block_q6_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_q8_K(const block_q8_K * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + +GGML_API void dequantize_row_tq1_0(const block_tq1_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_tq2_0(const block_tq2_0 * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + +GGML_API void dequantize_row_iq2_xxs(const block_iq2_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq2_xs (const block_iq2_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq2_s (const block_iq2_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq3_xxs(const block_iq3_xxs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq1_s (const block_iq1_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq1_m (const block_iq1_m * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq4_nl (const block_iq4_nl * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq4_xs (const block_iq4_xs * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); +GGML_API void dequantize_row_iq3_s (const block_iq3_s * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + +// Quantization utilizing an importance matrix (a.k.a. "Activation aWare Quantization") +GGML_API size_t quantize_iq2_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq2_xs (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq2_s (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq3_xxs(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq1_s (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq1_m (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq4_nl (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq4_xs (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_iq3_s (const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); + +GGML_API size_t quantize_tq1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_tq2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); + +GGML_API size_t quantize_q2_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q3_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q4_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q5_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q6_K(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q1_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q2_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q4_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q4_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q5_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q5_1(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_q8_0(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); + +GGML_API size_t quantize_mxfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); +GGML_API size_t quantize_nvfp4(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst, int64_t nrows, int64_t n_per_row, const float * imatrix); + +GGML_API void iq2xs_init_impl(enum ggml_type type); +GGML_API void iq2xs_free_impl(enum ggml_type type); +GGML_API void iq3xs_init_impl(int grid_size); +GGML_API void iq3xs_free_impl(int grid_size); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/ggml.h b/control-plane/third_party/ggml/ggml.h new file mode 100644 index 00000000..224bdef9 --- /dev/null +++ b/control-plane/third_party/ggml/ggml.h @@ -0,0 +1,3022 @@ +#pragma once + +// +// GGML Tensor Library +// +// This documentation is still a work in progress. +// If you wish some specific topics to be covered, feel free to drop a comment: +// +// https://github.com/ggml-org/whisper.cpp/issues/40 +// +// ## Overview +// +// This library implements: +// +// - a set of tensor operations +// - automatic differentiation +// - basic optimization algorithms +// +// The aim of this library is to provide a minimalistic approach for various machine learning tasks. This includes, +// but is not limited to, the following: +// +// - linear regression +// - support vector machines +// - neural networks +// +// The library allows the user to define a certain function using the available tensor operations. This function +// definition is represented internally via a computation graph. Each tensor operation in the function definition +// corresponds to a node in the graph. Having the computation graph defined, the user can choose to compute the +// function's value and/or its gradient with respect to the input variables. Optionally, the function can be optimized +// using one of the available optimization algorithms. +// +// For example, here we define the function: f(x) = a*x^2 + b +// +// { +// struct ggml_init_params params = { +// .mem_size = 16*1024*1024, +// .mem_buffer = NULL, +// }; +// +// // memory allocation happens here +// struct ggml_context * ctx = ggml_init(params); +// +// struct ggml_tensor * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1); +// +// ggml_set_param(ctx, x); // x is an input variable +// +// struct ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1); +// struct ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1); +// struct ggml_tensor * x2 = ggml_mul(ctx, x, x); +// struct ggml_tensor * f = ggml_add(ctx, ggml_mul(ctx, a, x2), b); +// +// ... +// } +// +// Notice that the function definition above does not involve any actual computation. The computation is performed only +// when the user explicitly requests it. For example, to compute the function's value at x = 2.0: +// +// { +// ... +// +// struct ggml_cgraph * gf = ggml_new_graph(ctx); +// ggml_build_forward_expand(gf, f); +// +// // set the input variable and parameter values +// ggml_set_f32(x, 2.0f); +// ggml_set_f32(a, 3.0f); +// ggml_set_f32(b, 4.0f); +// +// ggml_graph_compute_with_ctx(ctx, &gf, n_threads); +// +// printf("f = %f\n", ggml_get_f32_1d(f, 0)); +// +// ... +// } +// +// The actual computation is performed in the ggml_graph_compute() function. +// +// The ggml_new_tensor_...() functions create new tensors. They are allocated in the memory buffer provided to the +// ggml_init() function. You have to be careful not to exceed the memory buffer size. Therefore, you have to know +// in advance how much memory you need for your computation. Alternatively, you can allocate a large enough memory +// and after defining the computation graph, call the ggml_used_mem() function to find out how much memory was +// actually needed. +// +// The ggml_set_param() function marks a tensor as an input variable. This is used by the automatic +// differentiation and optimization algorithms. +// +// The described approach allows to define the function graph once and then compute its forward or backward graphs +// multiple times. All computations will use the same memory buffer allocated in the ggml_init() function. This way +// the user can avoid the memory allocation overhead at runtime. +// +// The library supports multi-dimensional tensors - up to 4 dimensions. The FP16 and FP32 data types are first class +// citizens, but in theory the library can be extended to support FP8 and integer data types. +// +// Each tensor operation produces a new tensor. Initially the library was envisioned to support only the use of unary +// and binary operations. Most of the available operations fall into one of these two categories. With time, it became +// clear that the library needs to support more complex operations. The way to support these operations is not clear +// yet, but a few examples are demonstrated in the following operations: +// +// - ggml_permute() +// - ggml_conv_1d_1s() +// - ggml_conv_1d_2s() +// +// For each tensor operator, the library implements a forward and backward computation function. The forward function +// computes the output tensor value given the input tensor values. The backward function computes the adjoint of the +// input tensors given the adjoint of the output tensor. For a detailed explanation of what this means, take a +// calculus class, or watch the following video: +// +// What is Automatic Differentiation? +// https://www.youtube.com/watch?v=wG_nF1awSSY +// +// +// ## Tensor data (struct ggml_tensor) +// +// The tensors are stored in memory via the ggml_tensor struct. The structure provides information about the size of +// the tensor, the data type, and the memory buffer where the tensor data is stored. Additionally, it contains +// pointers to the "source" tensors - i.e. the tensors that were used to compute the current tensor. For example: +// +// { +// struct ggml_tensor * c = ggml_add(ctx, a, b); +// +// assert(c->src[0] == a); +// assert(c->src[1] == b); +// } +// +// The multi-dimensional tensors are stored in row-major order. The ggml_tensor struct contains fields for the +// number of elements in each dimension ("ne") as well as the number of bytes ("nb", a.k.a. stride). This allows +// to store tensors that are not contiguous in memory, which is useful for operations such as transposition and +// permutation. All tensor operations have to take the stride into account and not assume that the tensor is +// contiguous in memory. +// +// The data of the tensor is accessed via the "data" pointer. For example: +// +// { +// const int nx = 2; +// const int ny = 3; +// +// struct ggml_tensor * a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nx, ny); +// +// for (int y = 0; y < ny; y++) { +// for (int x = 0; x < nx; x++) { +// *(float *) ((char *) a->data + y*a->nb[1] + x*a->nb[0]) = x + y; +// } +// } +// +// ... +// } +// +// Alternatively, there are helper functions, such as ggml_get_f32_1d() and ggml_set_f32_1d() that can be used. +// +// ## The matrix multiplication operator (ggml_mul_mat) +// +// TODO +// +// +// ## Multi-threading +// +// TODO +// +// +// ## Overview of ggml.c +// +// TODO +// +// +// ## SIMD optimizations +// +// TODO +// +// +// ## Debugging ggml +// +// TODO +// +// + +#ifdef GGML_SHARED +# if defined(_WIN32) && !defined(__MINGW32__) +# ifdef GGML_BUILD +# define GGML_API __declspec(dllexport) extern +# else +# define GGML_API __declspec(dllimport) extern +# endif +# else +# define GGML_API __attribute__ ((visibility ("default"))) extern +# endif +#else +# define GGML_API extern +#endif + +// TODO: support for clang +#ifdef __GNUC__ +# define GGML_DEPRECATED(func, hint) func __attribute__((deprecated(hint))) +#elif defined(_MSC_VER) +# define GGML_DEPRECATED(func, hint) __declspec(deprecated(hint)) func +#else +# define GGML_DEPRECATED(func, hint) func +#endif + +#ifndef __GNUC__ +# define GGML_ATTRIBUTE_FORMAT(...) +#elif defined(__MINGW32__) && !defined(__clang__) +# define GGML_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__))) +#else +# define GGML_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__))) +#endif + +#if defined(_WIN32) && !defined(_WIN32_WINNT) +# define _WIN32_WINNT 0x0A00 +#endif + +#include +#include +#include +#include + +#define GGML_FILE_MAGIC 0x67676d6c // "ggml" +#define GGML_FILE_VERSION 2 + +#define GGML_QNT_VERSION 2 // bump this on quantization format changes +#define GGML_QNT_VERSION_FACTOR 1000 // do not change this + +#define GGML_MAX_DIMS 4 +#define GGML_MAX_PARAMS 2048 +#define GGML_MAX_SRC 10 +#define GGML_MAX_N_THREADS 512 +#define GGML_MAX_OP_PARAMS 64 + +#ifndef GGML_MAX_NAME +# define GGML_MAX_NAME 64 +#endif + +#define GGML_DEFAULT_N_THREADS 4 +#define GGML_DEFAULT_GRAPH_SIZE 2048 + +#if UINTPTR_MAX == 0xFFFFFFFF + #define GGML_MEM_ALIGN 4 +#elif defined(__EMSCRIPTEN__) +// emscripten uses max_align_t == 8, so we need GGML_MEM_ALIGN == 8 for 64-bit wasm. +// (for 32-bit wasm, the first conditional is true and GGML_MEM_ALIGN stays 4.) +// ref: https://github.com/ggml-org/llama.cpp/pull/18628 + #define GGML_MEM_ALIGN 8 +#else + #define GGML_MEM_ALIGN 16 +#endif + +#define GGML_EXIT_SUCCESS 0 +#define GGML_EXIT_ABORTED 1 + +// TODO: convert to enum https://github.com/ggml-org/llama.cpp/pull/16187#discussion_r2388538726 +#define GGML_ROPE_TYPE_NORMAL 0 +#define GGML_ROPE_TYPE_NEOX 2 +#define GGML_ROPE_TYPE_MROPE 8 +#define GGML_ROPE_TYPE_VISION 24 +#define GGML_ROPE_TYPE_IMROPE 40 // binary: 101000 + +#define GGML_MROPE_SECTIONS 4 + +#define GGML_UNUSED(x) (void)(x) +#ifdef __CUDACC__ +template +__host__ __device__ constexpr inline void ggml_unused_vars_impl(Args&&...) noexcept {} +#define GGML_UNUSED_VARS(...) ggml_unused_vars_impl(__VA_ARGS__) +#else +#define GGML_UNUSED_VARS(...) do { (void)sizeof((__VA_ARGS__, 0)); } while(0) +#endif // __CUDACC__ + +#define GGML_PAD(x, n) (((x) + (n) - 1) & ~((n) - 1)) + +#ifndef NDEBUG +# define GGML_UNREACHABLE() do { fprintf(stderr, "statement should be unreachable\n"); abort(); } while(0) +#elif defined(__GNUC__) +# define GGML_UNREACHABLE() __builtin_unreachable() +#elif defined(_MSC_VER) +# define GGML_UNREACHABLE() __assume(0) +#else +# define GGML_UNREACHABLE() ((void) 0) +#endif + +#ifdef __cplusplus +# define GGML_NORETURN [[noreturn]] +#elif defined(_MSC_VER) +# define GGML_NORETURN __declspec(noreturn) +#else +# define GGML_NORETURN _Noreturn +#endif + +#define GGML_ABORT(...) ggml_abort(__FILE__, __LINE__, __VA_ARGS__) +#define GGML_ASSERT(x) if (!(x)) GGML_ABORT("GGML_ASSERT(%s) failed", #x) + +// used to copy the number of elements and stride in bytes of tensors into local variables. +// main purpose is to reduce code duplication and improve readability. +// +// example: +// +// GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne); +// GGML_TENSOR_LOCALS(size_t, nb1, src1, nb); +// +#define GGML_TENSOR_LOCALS_1(type, prefix, pointer, array) \ + const type prefix##0 = (pointer) ? (pointer)->array[0] : 0; \ + GGML_UNUSED(prefix##0); +#define GGML_TENSOR_LOCALS_2(type, prefix, pointer, array) \ + GGML_TENSOR_LOCALS_1 (type, prefix, pointer, array) \ + const type prefix##1 = (pointer) ? (pointer)->array[1] : 0; \ + GGML_UNUSED(prefix##1); +#define GGML_TENSOR_LOCALS_3(type, prefix, pointer, array) \ + GGML_TENSOR_LOCALS_2 (type, prefix, pointer, array) \ + const type prefix##2 = (pointer) ? (pointer)->array[2] : 0; \ + GGML_UNUSED(prefix##2); +#define GGML_TENSOR_LOCALS(type, prefix, pointer, array) \ + GGML_TENSOR_LOCALS_3 (type, prefix, pointer, array) \ + const type prefix##3 = (pointer) ? (pointer)->array[3] : 0; \ + GGML_UNUSED(prefix##3); + +#define GGML_TENSOR_UNARY_OP_LOCALS \ + GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne) \ + GGML_TENSOR_LOCALS(size_t, nb0, src0, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne, dst, ne) \ + GGML_TENSOR_LOCALS(size_t, nb, dst, nb) + +#define GGML_TENSOR_BINARY_OP_LOCALS \ + GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne) \ + GGML_TENSOR_LOCALS(size_t, nb0, src0, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne) \ + GGML_TENSOR_LOCALS(size_t, nb1, src1, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne, dst, ne) \ + GGML_TENSOR_LOCALS(size_t, nb, dst, nb) + +#define GGML_TENSOR_TERNARY_OP_LOCALS \ + GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne) \ + GGML_TENSOR_LOCALS(size_t, nb0, src0, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne) \ + GGML_TENSOR_LOCALS(size_t, nb1, src1, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne2, src2, ne) \ + GGML_TENSOR_LOCALS(size_t, nb2, src2, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne, dst, ne) \ + GGML_TENSOR_LOCALS(size_t, nb, dst, nb) + +#define GGML_TENSOR_BINARY_OP_LOCALS01 \ + GGML_TENSOR_LOCALS(int64_t, ne0, src0, ne) \ + GGML_TENSOR_LOCALS(size_t, nb0, src0, nb) \ + GGML_TENSOR_LOCALS(int64_t, ne1, src1, ne) \ + GGML_TENSOR_LOCALS(size_t, nb1, src1, nb) + +#ifdef __cplusplus +extern "C" { +#endif + + // Function type used in fatal error callbacks + typedef void (*ggml_abort_callback_t)(const char * error_message); + + // Set the abort callback (passing null will restore original abort functionality: printing a message to stdout) + // Returns the old callback for chaining + GGML_API ggml_abort_callback_t ggml_set_abort_callback(ggml_abort_callback_t callback); + + GGML_NORETURN GGML_ATTRIBUTE_FORMAT(3, 4) + GGML_API void ggml_abort(const char * file, int line, const char * fmt, ...); + + enum ggml_status { + GGML_STATUS_ALLOC_FAILED = -2, + GGML_STATUS_FAILED = -1, + GGML_STATUS_SUCCESS = 0, + GGML_STATUS_ABORTED = 1, + }; + + // get ggml_status name string + GGML_API const char * ggml_status_to_string(enum ggml_status status); + + // ieee 754-2008 half-precision float16 + // todo: make this not an integral type + typedef uint16_t ggml_fp16_t; + GGML_API float ggml_fp16_to_fp32(ggml_fp16_t); + GGML_API ggml_fp16_t ggml_fp32_to_fp16(float); + GGML_API void ggml_fp16_to_fp32_row(const ggml_fp16_t *, float *, int64_t); + GGML_API void ggml_fp32_to_fp16_row(const float *, ggml_fp16_t *, int64_t); + + // google brain half-precision bfloat16 + typedef struct { uint16_t bits; } ggml_bf16_t; + GGML_API ggml_bf16_t ggml_fp32_to_bf16(float); + GGML_API float ggml_bf16_to_fp32(ggml_bf16_t); // consider just doing << 16 + GGML_API void ggml_bf16_to_fp32_row(const ggml_bf16_t *, float *, int64_t); + GGML_API void ggml_fp32_to_bf16_row_ref(const float *, ggml_bf16_t *, int64_t); + GGML_API void ggml_fp32_to_bf16_row(const float *, ggml_bf16_t *, int64_t); + + struct ggml_object; + struct ggml_context; + struct ggml_cgraph; + + // NOTE: always add types at the end of the enum to keep backward compatibility + enum ggml_type { + GGML_TYPE_F32 = 0, + GGML_TYPE_F16 = 1, + GGML_TYPE_Q4_0 = 2, + GGML_TYPE_Q4_1 = 3, + // GGML_TYPE_Q4_2 = 4, support has been removed + // GGML_TYPE_Q4_3 = 5, support has been removed + GGML_TYPE_Q5_0 = 6, + GGML_TYPE_Q5_1 = 7, + GGML_TYPE_Q8_0 = 8, + GGML_TYPE_Q8_1 = 9, + GGML_TYPE_Q2_K = 10, + GGML_TYPE_Q3_K = 11, + GGML_TYPE_Q4_K = 12, + GGML_TYPE_Q5_K = 13, + GGML_TYPE_Q6_K = 14, + GGML_TYPE_Q8_K = 15, + GGML_TYPE_IQ2_XXS = 16, + GGML_TYPE_IQ2_XS = 17, + GGML_TYPE_IQ3_XXS = 18, + GGML_TYPE_IQ1_S = 19, + GGML_TYPE_IQ4_NL = 20, + GGML_TYPE_IQ3_S = 21, + GGML_TYPE_IQ2_S = 22, + GGML_TYPE_IQ4_XS = 23, + GGML_TYPE_I8 = 24, + GGML_TYPE_I16 = 25, + GGML_TYPE_I32 = 26, + GGML_TYPE_I64 = 27, + GGML_TYPE_F64 = 28, + GGML_TYPE_IQ1_M = 29, + GGML_TYPE_BF16 = 30, + // GGML_TYPE_Q4_0_4_4 = 31, support has been removed from gguf files + // GGML_TYPE_Q4_0_4_8 = 32, + // GGML_TYPE_Q4_0_8_8 = 33, + GGML_TYPE_TQ1_0 = 34, + GGML_TYPE_TQ2_0 = 35, + // GGML_TYPE_IQ4_NL_4_4 = 36, + // GGML_TYPE_IQ4_NL_4_8 = 37, + // GGML_TYPE_IQ4_NL_8_8 = 38, + GGML_TYPE_MXFP4 = 39, // MXFP4 (1 block) + GGML_TYPE_NVFP4 = 40, // NVFP4 (4 blocks, E4M3 scale) + GGML_TYPE_Q1_0 = 41, + GGML_TYPE_Q2_0 = 42, + GGML_TYPE_COUNT = 43, + }; + + // [TAG_GGML_PREC] + // this enum is used to declare the allowed numerical precision/data-types types that can be used during the compute of an op + // the declared types can be: + // - result accumulation type + // - source tensor data representation type + // - etc. + // the precision parameters are stored as ggml_tensor.op_params to the respective ops + enum ggml_prec { + GGML_PREC_UNDEFINED = 0, + GGML_PREC_DEFAULT = 0, // note: deprecated, use GGML_PREC_UNDEFINED + GGML_PREC_F32 = 10, + GGML_PREC_BF16 = 15, + GGML_PREC_F16 = 20, + GGML_PREC_Q8 = 30, + GGML_PREC_Q4 = 40, + }; + + // op hint + enum ggml_op_hint { + GGML_HINT_NONE = 0, + GGML_HINT_SRC0_IS_HADAMARD = 1, + }; + + // model file types + enum ggml_ftype { + GGML_FTYPE_UNKNOWN = -1, + GGML_FTYPE_ALL_F32 = 0, + GGML_FTYPE_MOSTLY_F16 = 1, // except 1d tensors + GGML_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors + GGML_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors + GGML_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16 + GGML_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors + GGML_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors + GGML_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors + GGML_FTYPE_MOSTLY_Q2_K = 10, // except 1d tensors + GGML_FTYPE_MOSTLY_Q3_K = 11, // except 1d tensors + GGML_FTYPE_MOSTLY_Q4_K = 12, // except 1d tensors + GGML_FTYPE_MOSTLY_Q5_K = 13, // except 1d tensors + GGML_FTYPE_MOSTLY_Q6_K = 14, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ2_XXS = 15, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ2_XS = 16, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ3_XXS = 17, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ1_S = 18, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ4_NL = 19, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ3_S = 20, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ2_S = 21, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ4_XS = 22, // except 1d tensors + GGML_FTYPE_MOSTLY_IQ1_M = 23, // except 1d tensors + GGML_FTYPE_MOSTLY_BF16 = 24, // except 1d tensors + GGML_FTYPE_MOSTLY_MXFP4 = 25, // except 1d tensors + GGML_FTYPE_MOSTLY_NVFP4 = 26, // except 1d tensors + GGML_FTYPE_MOSTLY_Q1_0 = 27, // except 1d tensors + GGML_FTYPE_MOSTLY_Q2_0 = 28, // except 1d tensors + }; + + // available tensor operations: + enum ggml_op { + GGML_OP_NONE = 0, + + GGML_OP_DUP, + GGML_OP_ADD, + GGML_OP_ADD_ID, + GGML_OP_ADD1, + GGML_OP_ACC, + GGML_OP_SUB, + GGML_OP_MUL, + GGML_OP_DIV, + GGML_OP_SQR, + GGML_OP_SQRT, + GGML_OP_LOG, + GGML_OP_SIN, + GGML_OP_COS, + GGML_OP_SUM, + GGML_OP_SUM_ROWS, + GGML_OP_CUMSUM, + GGML_OP_MEAN, + GGML_OP_ARGMAX, + GGML_OP_COUNT_EQUAL, + GGML_OP_REPEAT, + GGML_OP_REPEAT_BACK, + GGML_OP_CONCAT, + GGML_OP_SILU_BACK, + GGML_OP_NORM, // normalize + GGML_OP_RMS_NORM, + GGML_OP_RMS_NORM_BACK, + GGML_OP_GROUP_NORM, + GGML_OP_L2_NORM, + + GGML_OP_MUL_MAT, + GGML_OP_MUL_MAT_ID, + GGML_OP_OUT_PROD, + + GGML_OP_SCALE, + GGML_OP_SET, + GGML_OP_CPY, + GGML_OP_CONT, + GGML_OP_RESHAPE, + GGML_OP_VIEW, + GGML_OP_PERMUTE, + GGML_OP_TRANSPOSE, + GGML_OP_GET_ROWS, + GGML_OP_GET_ROWS_BACK, + GGML_OP_SET_ROWS, + GGML_OP_DIAG, + GGML_OP_DIAG_MASK_INF, + GGML_OP_DIAG_MASK_ZERO, + GGML_OP_SOFT_MAX, + GGML_OP_SOFT_MAX_BACK, + GGML_OP_ROPE, + GGML_OP_ROPE_BACK, + GGML_OP_CLAMP, + GGML_OP_CONV_TRANSPOSE_1D, + GGML_OP_IM2COL, + GGML_OP_IM2COL_BACK, + GGML_OP_IM2COL_3D, + GGML_OP_COL2IM_1D, + GGML_OP_CONV_2D, + GGML_OP_CONV_3D, + GGML_OP_CONV_2D_DW, + GGML_OP_CONV_TRANSPOSE_2D, + GGML_OP_POOL_1D, + GGML_OP_POOL_2D, + GGML_OP_POOL_2D_BACK, + GGML_OP_UPSCALE, + GGML_OP_PAD, + GGML_OP_PAD_REFLECT_1D, + GGML_OP_ROLL, + GGML_OP_ARANGE, + GGML_OP_TIMESTEP_EMBEDDING, + GGML_OP_ARGSORT, + GGML_OP_TOP_K, + GGML_OP_LEAKY_RELU, + GGML_OP_TRI, + GGML_OP_FILL, + + GGML_OP_FLASH_ATTN_EXT, + GGML_OP_FLASH_ATTN_BACK, + GGML_OP_SSM_CONV, + GGML_OP_SSM_SCAN, + GGML_OP_WIN_PART, + GGML_OP_WIN_UNPART, + GGML_OP_GET_REL_POS, + GGML_OP_ADD_REL_POS, + GGML_OP_RWKV_WKV6, + GGML_OP_GATED_LINEAR_ATTN, + GGML_OP_RWKV_WKV7, + GGML_OP_SOLVE_TRI, + GGML_OP_GATED_DELTA_NET, + GGML_OP_LIGHTNING_INDEXER, + GGML_OP_DSV4_HC_COMB, + GGML_OP_DSV4_HC_PRE, + GGML_OP_DSV4_HC_POST, + + GGML_OP_UNARY, + + GGML_OP_MAP_CUSTOM1, + GGML_OP_MAP_CUSTOM2, + GGML_OP_MAP_CUSTOM3, + + GGML_OP_CUSTOM, + + GGML_OP_CROSS_ENTROPY_LOSS, + GGML_OP_CROSS_ENTROPY_LOSS_BACK, + GGML_OP_OPT_STEP_ADAMW, + GGML_OP_OPT_STEP_SGD, + + GGML_OP_GLU, + + GGML_OP_COUNT, + }; + + enum ggml_unary_op { + GGML_UNARY_OP_ABS, + GGML_UNARY_OP_SGN, + GGML_UNARY_OP_NEG, + GGML_UNARY_OP_STEP, + GGML_UNARY_OP_TANH, + GGML_UNARY_OP_ELU, + GGML_UNARY_OP_RELU, + GGML_UNARY_OP_SIGMOID, + GGML_UNARY_OP_GELU, + GGML_UNARY_OP_GELU_QUICK, + GGML_UNARY_OP_SILU, + GGML_UNARY_OP_HARDSWISH, + GGML_UNARY_OP_HARDSIGMOID, + GGML_UNARY_OP_EXP, + GGML_UNARY_OP_EXPM1, + GGML_UNARY_OP_SOFTPLUS, + GGML_UNARY_OP_GELU_ERF, + GGML_UNARY_OP_XIELU, + GGML_UNARY_OP_FLOOR, + GGML_UNARY_OP_CEIL, + GGML_UNARY_OP_ROUND, + GGML_UNARY_OP_TRUNC, + + GGML_UNARY_OP_COUNT, + }; + + enum ggml_glu_op { + GGML_GLU_OP_REGLU, + GGML_GLU_OP_GEGLU, + GGML_GLU_OP_SWIGLU, + GGML_GLU_OP_SWIGLU_OAI, + GGML_GLU_OP_GEGLU_ERF, + GGML_GLU_OP_GEGLU_QUICK, + GGML_GLU_OP_SWIGLU_CLAMP, + + GGML_GLU_OP_COUNT, + }; + + enum ggml_object_type { + GGML_OBJECT_TYPE_TENSOR, + GGML_OBJECT_TYPE_GRAPH, + GGML_OBJECT_TYPE_WORK_BUFFER + }; + + enum ggml_log_level { + GGML_LOG_LEVEL_NONE = 0, + GGML_LOG_LEVEL_DEBUG = 1, + GGML_LOG_LEVEL_INFO = 2, + GGML_LOG_LEVEL_WARN = 3, + GGML_LOG_LEVEL_ERROR = 4, + GGML_LOG_LEVEL_CONT = 5, // continue previous log + }; + + // this tensor... + enum ggml_tensor_flag { + GGML_TENSOR_FLAG_INPUT = 1, // ...is an input for the GGML compute graph + GGML_TENSOR_FLAG_OUTPUT = 2, // ...is an output for the GGML compute graph + GGML_TENSOR_FLAG_PARAM = 4, // ...contains trainable parameters + GGML_TENSOR_FLAG_LOSS = 8, // ...defines loss for numerical optimization (multiple loss tensors add up) + GGML_TENSOR_FLAG_COMPUTE = 16, // ...must be computed + }; + + enum ggml_tri_type { + GGML_TRI_TYPE_UPPER_DIAG = 0, + GGML_TRI_TYPE_UPPER = 1, + GGML_TRI_TYPE_LOWER_DIAG = 2, + GGML_TRI_TYPE_LOWER = 3 + }; + + struct ggml_init_params { + // memory pool + size_t mem_size; // bytes + void * mem_buffer; // if NULL, memory will be allocated internally + bool no_alloc; // don't allocate memory for the tensor data + }; + + // n-dimensional tensor + struct ggml_tensor { + enum ggml_type type; + + struct ggml_backend_buffer * buffer; + + int64_t ne[GGML_MAX_DIMS]; // number of elements + size_t nb[GGML_MAX_DIMS]; // stride in bytes: + // nb[0] = ggml_type_size(type) + // nb[1] = nb[0] * (ne[0] / ggml_blck_size(type)) + padding + // nb[i] = nb[i-1] * ne[i-1] + + // compute data + enum ggml_op op; + + // op params - allocated as int32_t for alignment + int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)]; + + int32_t flags; + + struct ggml_tensor * src[GGML_MAX_SRC]; + + // source tensor and offset for views + struct ggml_tensor * view_src; + size_t view_offs; + + void * data; + + char name[GGML_MAX_NAME]; + + void * extra; // extra things e.g. for ggml-cuda.cu + + char padding[8]; + }; + + static const size_t GGML_TENSOR_SIZE = sizeof(struct ggml_tensor); + + // Abort callback + // If not NULL, called before ggml computation + // If it returns true, the computation is aborted + typedef bool (*ggml_abort_callback)(void * data); + + + // + // GUID + // + + // GUID types + typedef uint8_t ggml_guid[16]; + typedef ggml_guid * ggml_guid_t; + + GGML_API bool ggml_guid_matches(ggml_guid_t guid_a, ggml_guid_t guid_b); + + // misc + + GGML_API const char * ggml_version(void); + GGML_API const char * ggml_commit(void); + + GGML_API void ggml_time_init(void); // call this once at the beginning of the program + GGML_API int64_t ggml_time_ms(void); + GGML_API int64_t ggml_time_us(void); + GGML_API int64_t ggml_cycles(void); + GGML_API int64_t ggml_cycles_per_ms(void); + + // accepts a UTF-8 path, even on Windows + GGML_API FILE * ggml_fopen(const char * fname, const char * mode); + + GGML_API void ggml_print_object (const struct ggml_object * obj); + GGML_API void ggml_print_objects(const struct ggml_context * ctx); + + GGML_API int64_t ggml_nelements (const struct ggml_tensor * tensor); + GGML_API int64_t ggml_nrows (const struct ggml_tensor * tensor); + GGML_API size_t ggml_nbytes (const struct ggml_tensor * tensor); + GGML_API size_t ggml_nbytes_pad(const struct ggml_tensor * tensor); // same as ggml_nbytes() but padded to GGML_MEM_ALIGN + + GGML_API int64_t ggml_blck_size(enum ggml_type type); + GGML_API size_t ggml_type_size(enum ggml_type type); // size in bytes for all elements in a block + GGML_API size_t ggml_row_size (enum ggml_type type, int64_t ne); // size in bytes for all elements in a row + + GGML_DEPRECATED( + GGML_API double ggml_type_sizef(enum ggml_type type), // ggml_type_size()/ggml_blck_size() as float + "use ggml_row_size() instead"); + + GGML_API const char * ggml_type_name(enum ggml_type type); + GGML_API const char * ggml_op_name (enum ggml_op op); + GGML_API const char * ggml_op_symbol(enum ggml_op op); + + GGML_API const char * ggml_unary_op_name(enum ggml_unary_op op); + GGML_API const char * ggml_glu_op_name(enum ggml_glu_op op); + GGML_API const char * ggml_op_desc(const struct ggml_tensor * t); // unary or op name + + GGML_API size_t ggml_element_size(const struct ggml_tensor * tensor); + + GGML_API bool ggml_is_quantized(enum ggml_type type); + + // TODO: temporary until model loading of ggml examples is refactored + GGML_API enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype); + + GGML_API bool ggml_is_transposed(const struct ggml_tensor * tensor); + GGML_API bool ggml_is_permuted (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_empty (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_view (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_scalar (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_vector (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_matrix (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_3d (const struct ggml_tensor * tensor); + GGML_API int ggml_n_dims (const struct ggml_tensor * tensor); // returns 1 for scalars + + // returns whether the tensor elements can be iterated over with a flattened index (no gaps, no permutation) + GGML_API bool ggml_is_contiguous (const struct ggml_tensor * tensor); + GGML_API bool ggml_is_contiguous_0(const struct ggml_tensor * tensor); // same as ggml_is_contiguous() + GGML_API bool ggml_is_contiguous_1(const struct ggml_tensor * tensor); // contiguous for dims >= 1 + GGML_API bool ggml_is_contiguous_2(const struct ggml_tensor * tensor); // contiguous for dims >= 2 + + GGML_API bool ggml_is_contiguous_to_1(const struct ggml_tensor * tensor); // contiguous for dims < 1 + GGML_API bool ggml_is_contiguous_to_2(const struct ggml_tensor * tensor); // contiguous for dims < 2 + GGML_API bool ggml_is_contiguous_to_3(const struct ggml_tensor * tensor); // contiguous for dims < 3 + + // returns whether the tensor elements are allocated as one contiguous block of memory (no gaps, but permutation ok) + GGML_API bool ggml_is_contiguously_allocated(const struct ggml_tensor * tensor); + + // true for tensor that is stored in memory as CxWxHxN and has been permuted to WxHxCxN + GGML_API bool ggml_is_contiguous_channels(const struct ggml_tensor * tensor); + + // true if the elements in dimension 0 are contiguous, or there is just 1 block of elements + GGML_API bool ggml_is_contiguous_rows(const struct ggml_tensor * tensor); + + GGML_API bool ggml_are_same_shape (const struct ggml_tensor * t0, const struct ggml_tensor * t1); + GGML_API bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1); + + GGML_API bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1); + + // use this to compute the memory overhead of a tensor + GGML_API size_t ggml_tensor_overhead(void); + + GGML_API bool ggml_validate_row_data(enum ggml_type type, const void * data, size_t nbytes); + + // main + + GGML_API struct ggml_context * ggml_init (struct ggml_init_params params); + GGML_API void ggml_reset(struct ggml_context * ctx); + GGML_API void ggml_free (struct ggml_context * ctx); + + GGML_API size_t ggml_used_mem(const struct ggml_context * ctx); + + GGML_API bool ggml_get_no_alloc(struct ggml_context * ctx); + GGML_API void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc); + + GGML_API void * ggml_get_mem_buffer (const struct ggml_context * ctx); + GGML_API size_t ggml_get_mem_size (const struct ggml_context * ctx); + GGML_API size_t ggml_get_max_tensor_size(const struct ggml_context * ctx); + + GGML_API struct ggml_tensor * ggml_new_tensor( + struct ggml_context * ctx, + enum ggml_type type, + int n_dims, + const int64_t *ne); + + GGML_API struct ggml_tensor * ggml_new_tensor_1d( + struct ggml_context * ctx, + enum ggml_type type, + int64_t ne0); + + GGML_API struct ggml_tensor * ggml_new_tensor_2d( + struct ggml_context * ctx, + enum ggml_type type, + int64_t ne0, + int64_t ne1); + + GGML_API struct ggml_tensor * ggml_new_tensor_3d( + struct ggml_context * ctx, + enum ggml_type type, + int64_t ne0, + int64_t ne1, + int64_t ne2); + + GGML_API struct ggml_tensor * ggml_new_tensor_4d( + struct ggml_context * ctx, + enum ggml_type type, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3); + + GGML_API void * ggml_new_buffer(struct ggml_context * ctx, size_t nbytes); + + GGML_API struct ggml_tensor * ggml_dup_tensor (struct ggml_context * ctx, const struct ggml_tensor * src); + GGML_API struct ggml_tensor * ggml_view_tensor(struct ggml_context * ctx, struct ggml_tensor * src); + + // Context tensor enumeration and lookup + GGML_API struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx); + GGML_API struct ggml_tensor * ggml_get_next_tensor (const struct ggml_context * ctx, struct ggml_tensor * tensor); + GGML_API struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name); + + // Converts a flat index into coordinates + GGML_API void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3); + + GGML_API enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor); + GGML_API enum ggml_glu_op ggml_get_glu_op(const struct ggml_tensor * tensor); + + GGML_API void * ggml_get_data (const struct ggml_tensor * tensor); + GGML_API float * ggml_get_data_f32(const struct ggml_tensor * tensor); + + GGML_API const char * ggml_get_name (const struct ggml_tensor * tensor); + GGML_API struct ggml_tensor * ggml_set_name ( struct ggml_tensor * tensor, const char * name); + GGML_ATTRIBUTE_FORMAT(2, 3) + GGML_API struct ggml_tensor * ggml_format_name( struct ggml_tensor * tensor, const char * fmt, ...); + + // Tensor flags + GGML_API void ggml_set_input(struct ggml_tensor * tensor); + GGML_API void ggml_set_output(struct ggml_tensor * tensor); + GGML_API void ggml_set_param(struct ggml_tensor * tensor); + GGML_API void ggml_set_loss(struct ggml_tensor * tensor); + + // + // operations on tensors with backpropagation + // + + GGML_API struct ggml_tensor * ggml_dup( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_dup_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_add( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_add_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_add_cast( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + enum ggml_type type); + + // dst[i0, i1, i2] = a[i0, i1, i2] + b[i0, ids[i1, i2]] + GGML_API struct ggml_tensor * ggml_add_id( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * ids); + + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_add1( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b), + "use ggml_add instead"); + + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_add1_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b), + "use ggml_add_inplace instead"); + + // dst = a + // view(dst, nb1, nb2, nb3, offset) += b + // return dst + GGML_API struct ggml_tensor * ggml_acc( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t nb2, + size_t nb3, + size_t offset); + + GGML_API struct ggml_tensor * ggml_acc_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t nb2, + size_t nb3, + size_t offset); + + GGML_API struct ggml_tensor * ggml_sub( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_sub_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_mul( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_mul_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_div( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_div_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_sqr( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sqr_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sqrt( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sqrt_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_log( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_log_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_expm1( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_expm1_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_softplus( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_softplus_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sin( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sin_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_cos( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_cos_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // return scalar + GGML_API struct ggml_tensor * ggml_sum( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // sums along rows, with input shape [a,b,c,d] return shape [1,b,c,d] + GGML_API struct ggml_tensor * ggml_sum_rows( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_cumsum( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // mean along rows + GGML_API struct ggml_tensor * ggml_mean( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // argmax along rows + GGML_API struct ggml_tensor * ggml_argmax( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // count number of equal elements in a and b + GGML_API struct ggml_tensor * ggml_count_equal( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // if a is the same shape as b, and a is not parameter, return a + // otherwise, return a new tensor: repeat(a) to fit in b + GGML_API struct ggml_tensor * ggml_repeat( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // repeat a to the specified shape + GGML_API struct ggml_tensor * ggml_repeat_4d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3); + + // sums repetitions in a into shape of b + GGML_API struct ggml_tensor * ggml_repeat_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); // sum up values that are adjacent in dims > 0 instead of repeated with same stride + + // concat a and b along dim + // used in stable-diffusion + GGML_API struct ggml_tensor * ggml_concat( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int dim); + + GGML_API struct ggml_tensor * ggml_abs( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_abs_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sgn( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sgn_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_neg( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_neg_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_step( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_step_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_tanh( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_tanh_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_elu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_elu_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_relu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_leaky_relu( + struct ggml_context * ctx, + struct ggml_tensor * a, float negative_slope, bool inplace); + + GGML_API struct ggml_tensor * ggml_relu_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sigmoid( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_sigmoid_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_gelu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_gelu_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // GELU using erf (error function) when possible + // some backends may fallback to approximation based on Abramowitz and Stegun formula + GGML_API struct ggml_tensor * ggml_gelu_erf( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_gelu_erf_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_gelu_quick( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_gelu_quick_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_silu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_silu_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // a - dy + // b - x + GGML_API struct ggml_tensor * ggml_silu_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // hardswish(x) = x * relu6(x + 3) / 6 + GGML_API struct ggml_tensor * ggml_hardswish( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // hardsigmoid(x) = relu6(x + 3) / 6 + GGML_API struct ggml_tensor * ggml_hardsigmoid( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_exp( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_exp_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_floor( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_floor_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_ceil( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_ceil_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_round( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_round_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + /** + * Truncates the fractional part of each element in the tensor (towards zero). + * For example: trunc(3.7) = 3.0, trunc(-2.9) = -2.0 + * Similar to std::trunc in C/C++. + */ + + GGML_API struct ggml_tensor * ggml_trunc( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_trunc_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + + + // xIELU activation function + // x = x * (c_a(alpha_n) + c_b(alpha_p, beta) * sigmoid(beta * x)) + eps * (x > 0) + // where c_a = softplus and c_b(a, b) = softplus(a) + b are constraining functions + // that constrain the positive and negative source alpha values respectively + GGML_API struct ggml_tensor * ggml_xielu( + struct ggml_context * ctx, + struct ggml_tensor * a, + float alpha_n, + float alpha_p, + float beta, + float eps); + + // gated linear unit ops + // A: n columns, r rows, + // result is n / 2 columns, r rows, + // expects gate in second half of row, unless swapped is true + GGML_API struct ggml_tensor * ggml_glu( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_glu_op op, + bool swapped); + + GGML_API struct ggml_tensor * ggml_reglu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_reglu_swapped( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu_swapped( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_swiglu( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_swiglu_swapped( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu_erf( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu_erf_swapped( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu_quick( + struct ggml_context * ctx, + struct ggml_tensor * a); + + GGML_API struct ggml_tensor * ggml_geglu_quick_swapped( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // A: n columns, r rows, + // B: n columns, r rows, + GGML_API struct ggml_tensor * ggml_glu_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + enum ggml_glu_op op); + + GGML_API struct ggml_tensor * ggml_reglu_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_geglu_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_swiglu_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_geglu_erf_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_geglu_quick_split( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + GGML_API struct ggml_tensor * ggml_swiglu_oai( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float alpha, + float limit); + + GGML_API struct ggml_tensor * ggml_swiglu_clamp( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float limit); + + // normalize along rows + GGML_API struct ggml_tensor * ggml_norm( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + GGML_API struct ggml_tensor * ggml_norm_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + GGML_API struct ggml_tensor * ggml_rms_norm( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + GGML_API struct ggml_tensor * ggml_rms_norm_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + // group normalize along ne0*ne1*n_groups + // used in stable-diffusion + GGML_API struct ggml_tensor * ggml_group_norm( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_groups, + float eps); + + GGML_API struct ggml_tensor * ggml_group_norm_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_groups, + float eps); + + // l2 normalize along rows + // used in rwkv v7 + GGML_API struct ggml_tensor * ggml_l2_norm( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + GGML_API struct ggml_tensor * ggml_l2_norm_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float eps); + + // a - x + // b - dy + GGML_API struct ggml_tensor * ggml_rms_norm_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float eps); + + // [TAG_GGML_PREC] + // set the minimum required accumulator type for the implementation to use during the compute + // for example: + // - GGML_PREC_F32 - requires accumulation of the results in F32 + // - GGML_PREC_BF16 - can accumulate the results in BF16, F32 + // - GGML_PREC_F16 - can accumulate the results in F16, F32 + // - GGML_PREC_Q8 - not allowed + // - GGML_PREC_Q4 - not allowed + // + // return false on faliure + GGML_API bool ggml_prec_set_acc( + struct ggml_tensor * a, + enum ggml_prec prec); + + // [TAG_GGML_PREC] + // set the smallest rank that the implementation can use to internally convert the src[idx] data to + // ranks in decreasing order: + // - GGML_PREC_F32 - GGML_TYPE_F32 + // - GGML_PREC_BF16 - GGML_TYPE_BF16 + // - GGML_PREC_F16 - GGML_TYPE_F16, + // - GGML_PREC_Q8 - GGML_TYPE_Q8_0, GGML_TYPE_Q8_1, GGML_TYPE_Q8_K, etc. + // - GGML_PREC_Q4 - GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_K, GGML_TYPE_NVFP4, GGML_TYPE_MXFP4, etc. + // + // for example: + // - ggml_prec_set_src(a, GGML_PREC_Q8, 1): + // - allows the implementation to quantize F32, BF16, F16 data of src[1] down to GGML_TYPE_Q8_0 + // - cannot quantize it down to GGML_TYPE_Q4_0 or GGML_TYPE_NVFP4 + // - ggml_prec_set_src(a, GGML_PREC_Q4, 1): + // - allows the implementation to quantize F32, BF16, F16 data of src[1] down to 4-bit datatypes such as GGML_TYPE_Q4_K, GGML_TYPE_NVFP4 etc. + // + // return false on faliure + GGML_API bool ggml_prec_set_src( + struct ggml_tensor * a, + enum ggml_prec prec, + int idx); + + // A: k columns, n rows => [ne03, ne02, n, k] + // B: k columns, m rows (i.e. we transpose it internally) => [ne03 * x, ne02 * y, m, k] + // result is n columns, m rows => [ne03 * x, ne02 * y, m, n] + GGML_API struct ggml_tensor * ggml_mul_mat( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // change the precision of a matrix multiplication + // set to GGML_PREC_F32 for higher precision (useful for phi-2) + GGML_DEPRECATED(GGML_API void ggml_mul_mat_set_prec( + struct ggml_tensor * a, + enum ggml_prec prec), + "use ggml_prec_set_acc() instead"); + + // change the hint of a matrix multiplication + GGML_API void ggml_mul_mat_set_hint( + struct ggml_tensor * a, + enum ggml_op_hint hint); + + // indirect matrix multiplication + GGML_API struct ggml_tensor * ggml_mul_mat_id( + struct ggml_context * ctx, + struct ggml_tensor * as, + struct ggml_tensor * b, + struct ggml_tensor * ids); + + // A: m columns, n rows, + // B: p columns, n rows, + // result is m columns, p rows + GGML_API struct ggml_tensor * ggml_out_prod( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // + // operations on tensors without backpropagation + // + + GGML_API struct ggml_tensor * ggml_scale( + struct ggml_context * ctx, + struct ggml_tensor * a, + float s); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_scale_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float s); + + // x = s * a + b + GGML_API struct ggml_tensor * ggml_scale_bias( + struct ggml_context * ctx, + struct ggml_tensor * a, + float s, + float b); + + GGML_API struct ggml_tensor * ggml_scale_bias_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float s, + float b); + + // b -> view(a,offset,nb1,nb2,3), return modified a + GGML_API struct ggml_tensor * ggml_set( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t nb2, + size_t nb3, + size_t offset); // in bytes + + // b -> view(a,offset,nb1,nb2,3), return view(a) + GGML_API struct ggml_tensor * ggml_set_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t nb2, + size_t nb3, + size_t offset); // in bytes + + GGML_API struct ggml_tensor * ggml_set_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t offset); // in bytes + + GGML_API struct ggml_tensor * ggml_set_1d_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t offset); // in bytes + + // b -> view(a,offset,nb1,nb2,3), return modified a + GGML_API struct ggml_tensor * ggml_set_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t offset); // in bytes + + // b -> view(a,offset,nb1,nb2,3), return view(a) + GGML_API struct ggml_tensor * ggml_set_2d_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + size_t nb1, + size_t offset); // in bytes + + // a -> b, return view(b) + GGML_API struct ggml_tensor * ggml_cpy( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // note: casting from f32 to i32 will discard the fractional part + GGML_API struct ggml_tensor * ggml_cast( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_type type); + + // make contiguous + GGML_API struct ggml_tensor * ggml_cont( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // make contiguous, with new shape + GGML_API struct ggml_tensor * ggml_cont_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0); + + GGML_API struct ggml_tensor * ggml_cont_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1); + + GGML_API struct ggml_tensor * ggml_cont_3d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2); + + GGML_API struct ggml_tensor * ggml_cont_4d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3); + + // return view(a), b specifies the new shape + // TODO: when we start computing gradient, make a copy instead of view + GGML_API struct ggml_tensor * ggml_reshape( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // return view(a) + // TODO: when we start computing gradient, make a copy instead of view + GGML_API struct ggml_tensor * ggml_reshape_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0); + + GGML_API struct ggml_tensor * ggml_reshape_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1); + + // return view(a) + // TODO: when we start computing gradient, make a copy instead of view + GGML_API struct ggml_tensor * ggml_reshape_3d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2); + + GGML_API struct ggml_tensor * ggml_reshape_4d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3); + + // offset in bytes + GGML_API struct ggml_tensor * ggml_view_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + size_t offset); + + GGML_API struct ggml_tensor * ggml_view_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + size_t nb1, // row stride in bytes + size_t offset); + + GGML_API struct ggml_tensor * ggml_view_3d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + size_t nb1, // row stride in bytes + size_t nb2, // slice stride in bytes + size_t offset); + + GGML_API struct ggml_tensor * ggml_view_4d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3, + size_t nb1, // row stride in bytes + size_t nb2, // slice stride in bytes + size_t nb3, + size_t offset); + + GGML_API struct ggml_tensor * ggml_permute( + struct ggml_context * ctx, + struct ggml_tensor * a, + int axis0, + int axis1, + int axis2, + int axis3); + + // alias for ggml_permute(ctx, a, 1, 0, 2, 3) + GGML_API struct ggml_tensor * ggml_transpose( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // supports 4D a: + // a [n_embd, ne1, ne2, ne3] + // b I32 [n_rows, ne2, ne3, 1] + // + // return [n_embd, n_rows, ne2, ne3] + GGML_API struct ggml_tensor * ggml_get_rows( + struct ggml_context * ctx, + struct ggml_tensor * a, // data + struct ggml_tensor * b); // row indices + + GGML_API struct ggml_tensor * ggml_get_rows_back( + struct ggml_context * ctx, + struct ggml_tensor * a, // gradients of ggml_get_rows result + struct ggml_tensor * b, // row indices + struct ggml_tensor * c); // data for ggml_get_rows, only used for its shape + + // a TD [n_embd, ne1, ne2, ne3] + // b TS [n_embd, n_rows, ne02, ne03] | ne02 == ne2, ne03 == ne3 + // c I64 [n_rows, ne11, ne12, 1] | c[i] in [0, ne1) + // + // undefined behavior if destination rows overlap + // + // broadcast: + // ne2 % ne11 == 0 + // ne3 % ne12 == 0 + // + // return view(a) + GGML_API struct ggml_tensor * ggml_set_rows( + struct ggml_context * ctx, + struct ggml_tensor * a, // destination + struct ggml_tensor * b, // source + struct ggml_tensor * c); // row indices + + GGML_API struct ggml_tensor * ggml_diag( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // set elements above the diagonal to -INF + GGML_API struct ggml_tensor * ggml_diag_mask_inf( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_past); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_diag_mask_inf_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_past); + + // set elements above the diagonal to 0 + GGML_API struct ggml_tensor * ggml_diag_mask_zero( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_past); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_diag_mask_zero_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + int n_past); + + GGML_API struct ggml_tensor * ggml_clamp( + struct ggml_context * ctx, + struct ggml_tensor * a, + float min, + float max); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_clamp_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float min, + float max); + + GGML_API struct ggml_tensor * ggml_soft_max( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_soft_max_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a); + + // a [ne0, ne01, ne02, ne03] + // mask [ne0, ne11, ne12, ne13] | ne11 >= ne01, F16 or F32, optional + // + // broadcast: + // ne02 % ne12 == 0 + // ne03 % ne13 == 0 + // + // fused soft_max(a*scale + mask*(ALiBi slope)) + // max_bias = 0.0f for no ALiBi + GGML_API struct ggml_tensor * ggml_soft_max_ext( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * mask, + float scale, + float max_bias); + + GGML_API struct ggml_tensor * ggml_soft_max_ext_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * mask, + float scale, + float max_bias); + + GGML_API void ggml_soft_max_add_sinks( + struct ggml_tensor * a, + struct ggml_tensor * sinks); + + GGML_API struct ggml_tensor * ggml_soft_max_ext_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float scale, + float max_bias); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_soft_max_ext_back_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + float scale, + float max_bias); + + // rotary position embedding + // if (mode & 1) - skip n_past elements (NOT SUPPORTED) + // if (mode & GGML_ROPE_TYPE_NEOX) - GPT-NeoX style + // + // b is an int32 vector with size a->ne[2], it contains the positions + GGML_API struct ggml_tensor * ggml_rope( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int n_dims, + int mode); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_rope_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int n_dims, + int mode); + + // RoPE operations with extended options + // a is the input tensor to apply RoPE to, shape [n_embd, n_head, n_token] + // b is an int32 vector with size n_token + // c is freq factors (e.g. phi3-128k), (optional) + // mode can be GGML_ROPE_TYPE_NORMAL or NEOX; for MROPE and VISION mode, use ggml_rope_multi + // + // pseudo-code for computing theta: + // for i in [0, n_dims/2): + // theta[i] = b[i] * powf(freq_base, -2.0 * i / n_dims); + // theta[i] = theta[i] / c[i]; # if c is provided, divide theta by c + // theta[i] = rope_yarn(theta[i], ...); # note: theta = theta * freq_scale is applied here + // + // other params are used by YaRN RoPE scaling, these default values will disable YaRN: + // freq_scale = 1.0f + // ext_factor = 0.0f + // attn_factor = 1.0f + // beta_fast = 0.0f + // beta_slow = 0.0f + // + // example: + // (marking: c = cos, s = sin, 0 = unrotated) + // given a single head with size = 8 --> [00000000] + // GGML_ROPE_TYPE_NORMAL n_dims = 4 --> [cscs0000] + // GGML_ROPE_TYPE_NORMAL n_dims = 8 --> [cscscscs] + // GGML_ROPE_TYPE_NEOX n_dims = 4 --> [ccss0000] + // GGML_ROPE_TYPE_NEOX n_dims = 8 --> [ccccssss] + GGML_API struct ggml_tensor * ggml_rope_ext( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + int n_dims, + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + // multi-dimensional RoPE, for Qwen-VL and similar vision models + // mode can be either VISION, MROPE, IMROPE, cannot be combined with NORMAL or NEOX + // sections specify how many dimensions to rotate in each section: + // section length is equivalent to number of cos/sin pairs, NOT the number of dims + // (i.e. sum of 4 sections are expected to be n_dims/2) + // last sections can be 0, means ignored + // all other options are identical to ggml_rope_ext + // + // important note: + // - NEOX ordering is automatically applied and cannot be disabled for MROPE and VISION + // if you need normal ordering, there are 2 methods: + // (1) split the tensor manually using ggml_view + // (2) permute the weight upon conversion + // - for VISION, n_dims must be head_size/2 + // + // example M-RoPE: + // given sections = [t=4, y=2, x=2, 0] + // given a single head with size = 18 --> [000000000000000000] + // GGML_ROPE_TYPE_MROPE n_dims = 16 --> [ttttyyxxttttyyxx00] (cos/sin are applied in NEOX ordering) + // GGML_ROPE_TYPE_IMROPE n_dims = 16 --> [ttyxttyxttyxttyx00] (interleaved M-RoPE, still NEOX ordering) + // note: the theta for each dim is computed the same way as ggml_rope_ext, no matter the section + // in other words, idx used for theta: [0123456789... until n_dims/2], not reset for each section + // + // example vision RoPE: + // given sections = [y=4, x=4, 0, 0] (last 2 sections are ignored) + // given a single head with size = 8 --> [00000000] + // GGML_ROPE_TYPE_VISION n_dims = 4 --> [yyyyxxxx] + // other values of n_dims are untested and is undefined behavior + // note: unlike MROPE, the theta for each dim is computed differently for each section + // in other words, idx used for theta: [0123] for y section, then [0123] for x section + GGML_API struct ggml_tensor * ggml_rope_multi( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + int n_dims, + int sections[GGML_MROPE_SECTIONS], + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + // in-place, returns view(a) + GGML_API struct ggml_tensor * ggml_rope_ext_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + int n_dims, + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + GGML_API struct ggml_tensor * ggml_rope_multi_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + int n_dims, + int sections[GGML_MROPE_SECTIONS], + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_rope_custom( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int n_dims, + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow), + "use ggml_rope_ext instead"); + + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_rope_custom_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int n_dims, + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow), + "use ggml_rope_ext_inplace instead"); + + // compute correction dims for YaRN RoPE scaling + GGML_API void ggml_rope_yarn_corr_dims( + int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]); + + // rotary position embedding backward, i.e compute dx from dy + // a - dy + GGML_API struct ggml_tensor * ggml_rope_ext_back( + struct ggml_context * ctx, + struct ggml_tensor * a, // gradients of ggml_rope result + struct ggml_tensor * b, // positions + struct ggml_tensor * c, // freq factors + int n_dims, + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + GGML_API struct ggml_tensor * ggml_rope_multi_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + int n_dims, + int sections[4], + int mode, + int n_ctx_orig, + float freq_base, + float freq_scale, + float ext_factor, + float attn_factor, + float beta_fast, + float beta_slow); + + // set the offset dims for RoPE + // a must be GGML_OP_ROPE or GGML_OP_ROPE_BACK + // vision RoPE is not supported + // example: (marking: x = rotated, 0 = unrotated) + // n_embd = 10, n_dims = 4, offset = 2 --> [00xxxx0000] + GGML_API struct ggml_tensor * ggml_rope_set_offset( + struct ggml_tensor * a, + int n_offs); + + // im2col + // converts data into a format that effectively results in a convolution when combined with matrix multiplication + GGML_API struct ggml_tensor * ggml_im2col( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride dimension 0 + int s1, // stride dimension 1 + int p0, // padding dimension 0 + int p1, // padding dimension 1 + int d0, // dilation dimension 0 + int d1, // dilation dimension 1 + bool is_2D, + enum ggml_type dst_type); + + GGML_API struct ggml_tensor * ggml_im2col_back( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // gradient of im2col output + int64_t * ne, // shape of im2col input + int s0, // stride dimension 0 + int s1, // stride dimension 1 + int p0, // padding dimension 0 + int p1, // padding dimension 1 + int d0, // dilation dimension 0 + int d1, // dilation dimension 1 + bool is_2D); + + // col2im_1d: scatter-add GEMM columns back to 1D signal + // a: [K*OC, T_in] (columns from matmul, K = a->ne[0]/OC) + // result: [T_out, OC] where T_out = (T_in - 1)*s0 + K - 2*p0 + GGML_API struct ggml_tensor * ggml_col2im_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, // columns [K*OC, T_in] + int s0, // stride + int oc, // output channels + int p0); // padding to crop from both sides + + GGML_API struct ggml_tensor * ggml_conv_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride + int p0, // padding + int d0); // dilation + + // conv_1d with padding = half + // alias for ggml_conv_1d(a, b, s, a->ne[0]/2, d) + GGML_API struct ggml_tensor* ggml_conv_1d_ph( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s, // stride + int d); // dilation + + // depthwise + // TODO: this is very likely wrong for some cases! - needs more testing + GGML_API struct ggml_tensor * ggml_conv_1d_dw( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride + int p0, // padding + int d0); // dilation + + GGML_API struct ggml_tensor * ggml_conv_1d_dw_ph( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride + int d0); // dilation + + GGML_API struct ggml_tensor * ggml_conv_transpose_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride + int p0, // padding + int d0); // dilation + + GGML_API struct ggml_tensor * ggml_conv_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride dimension 0 + int s1, // stride dimension 1 + int p0, // padding dimension 0 + int p1, // padding dimension 1 + int d0, // dilation dimension 0 + int d1); // dilation dimension 1 + + GGML_API struct ggml_tensor * ggml_im2col_3d( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int64_t IC, + int s0, // stride width + int s1, // stride height + int s2, // stride depth + int p0, // padding width + int p1, // padding height + int p2, // padding depth + int d0, // dilation width + int d1, // dilation height + int d2, // dilation depth + enum ggml_type dst_type); + + // a: [OC*IC, KD, KH, KW] + // b: [N*IC, ID, IH, IW] + // result: [N*OC, OD, OH, OW] + GGML_API struct ggml_tensor * ggml_conv_3d( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int64_t IC, + int s0, // stride width + int s1, // stride height + int s2, // stride depth + int p0, // padding width + int p1, // padding height + int p2, // padding depth + int d0, // dilation width + int d1, // dilation height + int d2 // dilation depth + ); + + // kernel size is a->ne[0] x a->ne[1] + // stride is equal to kernel size + // padding is zero + // example: + // a: 16 16 3 768 + // b: 1024 1024 3 1 + // res: 64 64 768 1 + // used in sam + GGML_API struct ggml_tensor * ggml_conv_2d_sk_p0( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // kernel size is a->ne[0] x a->ne[1] + // stride is 1 + // padding is half + // example: + // a: 3 3 256 256 + // b: 64 64 256 1 + // res: 64 64 256 1 + // used in sam + GGML_API struct ggml_tensor * ggml_conv_2d_s1_ph( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + + // depthwise (via im2col and mul_mat) + GGML_API struct ggml_tensor * ggml_conv_2d_dw( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel + struct ggml_tensor * b, // data + int s0, // stride dimension 0 + int s1, // stride dimension 1 + int p0, // padding dimension 0 + int p1, // padding dimension 1 + int d0, // dilation dimension 0 + int d1); // dilation dimension 1 + + // Depthwise 2D convolution + // may be faster than ggml_conv_2d_dw, but not available in all backends + // a: KW KH 1 C convolution kernel + // b: W H C N input data + // res: W_out H_out C N + GGML_API struct ggml_tensor * ggml_conv_2d_dw_direct( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int stride0, + int stride1, + int pad0, + int pad1, + int dilation0, + int dilation1); + + GGML_API struct ggml_tensor * ggml_conv_transpose_2d_p0( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + int stride); + + GGML_API struct ggml_tensor * ggml_conv_2d_direct( + struct ggml_context * ctx, + struct ggml_tensor * a, // convolution kernel [KW, KH, IC, OC] + struct ggml_tensor * b, // input data [W, H, C, N] + int s0, // stride dimension 0 + int s1, // stride dimension 1 + int p0, // padding dimension 0 + int p1, // padding dimension 1 + int d0, // dilation dimension 0 + int d1); // dilation dimension 1 + + GGML_API struct ggml_tensor * ggml_conv_3d_direct( + struct ggml_context * ctx, + struct ggml_tensor * a, // kernel [KW, KH, KD, IC * OC] + struct ggml_tensor * b, // input [W, H, D, C * N] + int s0, // stride + int s1, + int s2, + int p0, // padding + int p1, + int p2, + int d0, // dilation + int d1, + int d2, + int n_channels, + int n_batch, + int n_channels_out); + + enum ggml_op_pool { + GGML_OP_POOL_MAX, + GGML_OP_POOL_AVG, + GGML_OP_POOL_COUNT, + }; + + GGML_API struct ggml_tensor * ggml_pool_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_op_pool op, + int k0, // kernel size + int s0, // stride + int p0); // padding + + // the result will have 2*p0 padding for the first dimension + // and 2*p1 padding for the second dimension + GGML_API struct ggml_tensor * ggml_pool_2d( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_op_pool op, + int k0, + int k1, + int s0, + int s1, + float p0, + float p1); + + GGML_API struct ggml_tensor * ggml_pool_2d_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * af, // "a"/input used in forward pass + enum ggml_op_pool op, + int k0, + int k1, + int s0, + int s1, + float p0, + float p1); + + enum ggml_scale_mode { + GGML_SCALE_MODE_NEAREST = 0, + GGML_SCALE_MODE_BILINEAR = 1, + GGML_SCALE_MODE_BICUBIC = 2, + + GGML_SCALE_MODE_COUNT + }; + + enum ggml_scale_flag { + GGML_SCALE_FLAG_ALIGN_CORNERS = (1 << 8), + GGML_SCALE_FLAG_ANTIALIAS = (1 << 9), + }; + + // interpolate + // multiplies ne0 and ne1 by scale factor + GGML_API struct ggml_tensor * ggml_upscale( + struct ggml_context * ctx, + struct ggml_tensor * a, + int scale_factor, + enum ggml_scale_mode mode); + + // interpolate + // interpolate scale to specified dimensions + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_upscale_ext( + struct ggml_context * ctx, + struct ggml_tensor * a, + int ne0, + int ne1, + int ne2, + int ne3, + enum ggml_scale_mode mode), + "use ggml_interpolate instead"); + + // Up- or downsamples the input to the specified size. + // 2D scale modes (eg. bilinear) are applied to the first two dimensions. + GGML_API struct ggml_tensor * ggml_interpolate( + struct ggml_context * ctx, + struct ggml_tensor * a, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3, + uint32_t mode); // ggml_scale_mode [ | ggml_scale_flag...] + + // pad each dimension with zeros: [x, ..., x] -> [x, ..., x, 0, ..., 0] + GGML_API struct ggml_tensor * ggml_pad( + struct ggml_context * ctx, + struct ggml_tensor * a, + int p0, + int p1, + int p2, + int p3); + + // pad each dimension with values on the other side of the torus (looping around) + GGML_API struct ggml_tensor * ggml_pad_circular( + struct ggml_context * ctx, + struct ggml_tensor * a, + int p0, + int p1, + int p2, + int p3); + + GGML_API struct ggml_tensor * ggml_pad_ext( + struct ggml_context * ctx, + struct ggml_tensor * a, + int lp0, + int rp0, + int lp1, + int rp1, + int lp2, + int rp2, + int lp3, + int rp3 + ); + + // pad each dimension with values on the other side of the torus (looping around) + GGML_API struct ggml_tensor * ggml_pad_ext_circular( + struct ggml_context * ctx, + struct ggml_tensor * a, + int lp0, + int rp0, + int lp1, + int rp1, + int lp2, + int rp2, + int lp3, + int rp3); + + // pad each dimension with reflection: [a, b, c, d] -> [b, a, b, c, d, c] + GGML_API struct ggml_tensor * ggml_pad_reflect_1d( + struct ggml_context * ctx, + struct ggml_tensor * a, + int p0, + int p1); + + // Move tensor elements by an offset given for each dimension. Elements that + // are shifted beyond the last position are wrapped around to the beginning. + GGML_API struct ggml_tensor * ggml_roll( + struct ggml_context * ctx, + struct ggml_tensor * a, + int shift0, + int shift1, + int shift2, + int shift3); + + // Convert matrix into a triangular one (upper, strict upper, lower or strict lower) by writing + // zeroes everywhere outside the masked area + GGML_API struct ggml_tensor * ggml_tri( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_tri_type type); + + // Fill tensor a with constant c + GGML_API struct ggml_tensor * ggml_fill( + struct ggml_context * ctx, + struct ggml_tensor * a, + float c); + + GGML_API struct ggml_tensor * ggml_fill_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + float c); + + // Ref: https://github.com/CompVis/stable-diffusion/blob/main/ldm/modules/diffusionmodules/util.py#L151 + // timesteps: [N,] + // return: [N, dim] + GGML_API struct ggml_tensor * ggml_timestep_embedding( + struct ggml_context * ctx, + struct ggml_tensor * timesteps, + int dim, + int max_period); + + // sort rows + enum ggml_sort_order { + GGML_SORT_ORDER_ASC, + GGML_SORT_ORDER_DESC, + }; + + GGML_API struct ggml_tensor * ggml_argsort( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_sort_order order); + + // similar to ggml_top_k but implemented as `argsort` + `view` + GGML_API struct ggml_tensor * ggml_argsort_top_k( + struct ggml_context * ctx, + struct ggml_tensor * a, + int k); + + // top k elements per row + // note: the resulting top k indices are in no particular order + GGML_API struct ggml_tensor * ggml_top_k( + struct ggml_context * ctx, + struct ggml_tensor * a, + int k); + + GGML_API struct ggml_tensor * ggml_arange( + struct ggml_context * ctx, + float start, + float stop, + float step); + + // q: [n_embd_k, n_batch, n_head, ne3 ] + // k: [n_embd_k, n_kv, n_head_kv, ne3 ] + // v: [n_embd_v, n_kv, n_head_kv, ne3 ] !! not transposed !! + // mask: [n_kv, n_batch, ne32, ne33] + // res: [n_embd_v, n_head, n_batch, ne3 ] !! permuted !! + // + // broadcast: + // n_head % n_head_kv == 0 + // n_head % ne32 == 0 + // ne3 % ne33 == 0 + // + GGML_API struct ggml_tensor * ggml_flash_attn_ext( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * mask, + float scale, + float max_bias, + float logit_softcap); + + GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( + struct ggml_tensor * a, + enum ggml_prec prec), + "use ggml_prec_set_acc() instead"); + + GGML_API enum ggml_prec ggml_flash_attn_ext_get_prec( + const struct ggml_tensor * a); + + // Use finite mask entries as a sparse K/V set. Set 0 to disable. + // n_kv_max must bound the number of finite entries in every mask row. + GGML_API void ggml_flash_attn_ext_set_n_kv_max( + struct ggml_tensor * a, + int32_t n_kv_max); + + GGML_API void ggml_flash_attn_ext_add_sinks( + struct ggml_tensor * a, + struct ggml_tensor * sinks); + + // TODO: needs to be adapted to ggml_flash_attn_ext + GGML_API struct ggml_tensor * ggml_flash_attn_back( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * d, + bool masked); + + GGML_API struct ggml_tensor * ggml_ssm_conv( + struct ggml_context * ctx, + struct ggml_tensor * sx, + struct ggml_tensor * c); + + GGML_API struct ggml_tensor * ggml_ssm_scan( + struct ggml_context * ctx, + struct ggml_tensor * s, + struct ggml_tensor * x, + struct ggml_tensor * dt, + struct ggml_tensor * A, + struct ggml_tensor * B, + struct ggml_tensor * C, + struct ggml_tensor * ids, + int64_t K); + + // partition into non-overlapping windows with padding if needed + // example: + // a: 768 64 64 1 + // w: 14 + // res: 768 14 14 25 + // used in sam + GGML_API struct ggml_tensor * ggml_win_part( + struct ggml_context * ctx, + struct ggml_tensor * a, + int w); + + // reverse of ggml_win_part + // used in sam + GGML_API struct ggml_tensor * ggml_win_unpart( + struct ggml_context * ctx, + struct ggml_tensor * a, + int w0, + int h0, + int w); + + GGML_API struct ggml_tensor * ggml_unary( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_unary_op op); + + GGML_API struct ggml_tensor * ggml_unary_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_unary_op op); + + // used in sam + GGML_API struct ggml_tensor * ggml_get_rel_pos( + struct ggml_context * ctx, + struct ggml_tensor * a, + int qh, + int kh); + + // used in sam + GGML_API struct ggml_tensor * ggml_add_rel_pos( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * pw, + struct ggml_tensor * ph); + + GGML_API struct ggml_tensor * ggml_add_rel_pos_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * pw, + struct ggml_tensor * ph); + + GGML_API struct ggml_tensor * ggml_rwkv_wkv6( + struct ggml_context * ctx, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * r, + struct ggml_tensor * tf, + struct ggml_tensor * td, + struct ggml_tensor * state); + + GGML_API struct ggml_tensor * ggml_gated_linear_attn( + struct ggml_context * ctx, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * q, + struct ggml_tensor * g, + struct ggml_tensor * state, + float scale); + + GGML_API struct ggml_tensor * ggml_rwkv_wkv7( + struct ggml_context * ctx, + struct ggml_tensor * r, + struct ggml_tensor * w, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * state); + + /* Solves a specific equation of the form Ax=B, where A is a triangular matrix + * without zeroes on the diagonal (i.e. invertible). + * B can have any number of columns, but must have the same number of rows as A + * If A is [n, n] and B is [n, m], then the result will be [n, m] as well + * Has O(n^3) complexity (unlike most matrix ops out there), so use on cases + * where n > 100 sparingly, pre-chunk if necessary. + * + * If left = false, solves xA=B instead + * If lower = false, assumes upper triangular instead + * If uni = true, assumes diagonal of A to be all ones (will override actual values) + * + * TODO: currently only lower, right, non-unitriangular variant is implemented + */ + GGML_API struct ggml_tensor * ggml_solve_tri( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + bool left, + bool lower, + bool uni); + + // TODO: add ggml_gated_delta_net_set_bcast() to be able to configure Q, K broadcast type: tiled vs interleaved [TAG_GGML_GDN_BCAST] + // ref: https://github.com/ggml-org/llama.cpp/pull/19468#discussion_r2786394306 + // + // tensor shapes (S_k == S_v, H_v % H_k == 0): + // q, k : [S_k, H_k, n_tokens, n_seqs] + // v : [S_v, H_v, n_tokens, n_seqs] + // g : [1, H_v, n_tokens, n_seqs] (scalar gate) or [S_v, H_v, n_tokens, n_seqs] (KDA) + // beta : [1, H_v, n_tokens, n_seqs] + // state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0 + // + // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state + // snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1 + // keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written. + GGML_API struct ggml_tensor * ggml_gated_delta_net( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + int64_t K); + + // DSA lightning indexer + // + // q: [n_embd_idx, n_head_idx, n_batch, ne3 ] + // k: [n_embd_idx, 1, n_kv, ne3 ] + // weights: [n_head_idx, n_batch, 1, ne3 ] !! prescaled !! + // mask: [n_kv, n_batch, 1, ne33] !! f16 !! + // res: [n_kv, n_batch, 1, ne3 ] + // + // broadcast: + // ne3 % ne33 == 0 + // + GGML_API struct ggml_tensor * ggml_lightning_indexer( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * weights, + struct ggml_tensor * mask); + + // DeepSeek V4 hyper-connections (ref. https://arxiv.org/pdf/2512.24880) + // In short these operations are replacements for the original residual connection (x = transformer(x) + x) + // using a richer representation through streams. + // + // hc_comb: mixes [(2 + hc)*hc, n_tokens], scale [3], base [(2 + hc)*hc] + // -> [dst_hc, src_hc, n_tokens] + // logits[dst, src, t] = mixes[2*hc + dst + hc*src, t]*scale[2] + // + base[2*hc + dst + hc*src] + // Softmax over dst, add eps, normalize over src, then repeat normalization + // over dst followed by src for iterations 1 through n_iter - 1. + GGML_API struct ggml_tensor * ggml_dsv4_hc_comb( + struct ggml_context * ctx, + struct ggml_tensor * mixes, + struct ggml_tensor * scale, + struct ggml_tensor * base, + float eps, + int32_t n_iter); + + // hc_pre: x [n_embd, hc, n_tokens], weights [hc, n_tokens] -> [n_embd, n_tokens] + // result[i, t] = sum_h x[i, h, t]*weights[h, t] + // + GGML_API struct ggml_tensor * ggml_dsv4_hc_pre( + struct ggml_context * ctx, + struct ggml_tensor * x, + struct ggml_tensor * weights); + + // hc_pre with a per-element gate (Qwen3.8-Flash-Next): gate [n_embd, hc, n_tokens] + // result[i, t] = scale*sum_h x[i, h, t]*sigmoid(gate[i, h, t]) + // + GGML_API struct ggml_tensor * ggml_dsv4_hc_pre_gated( + struct ggml_context * ctx, + struct ggml_tensor * x, + struct ggml_tensor * gate, + float scale); + + // hc_post: x [n_embd, n_tokens], residual [n_embd, hc, n_tokens], + // post [hc, n_tokens], comb [dst_hc, src_hc, n_tokens] + // -> [n_embd, hc, n_tokens] + // result[i, dst, t] = x[i, t]*post[dst, t] + // + sum_src residual[i, src, t]*comb[dst, src, t] + // comb == NULL uses the identity: result[i, dst, t] = x[i, t]*post[dst, t] + residual[i, dst, t] + // + GGML_API struct ggml_tensor * ggml_dsv4_hc_post( + struct ggml_context * ctx, + struct ggml_tensor * x, + struct ggml_tensor * residual, + struct ggml_tensor * post, + struct ggml_tensor * comb); + + // custom operators + + typedef void (*ggml_custom1_op_t)(struct ggml_tensor * dst , const struct ggml_tensor * a, int ith, int nth, void * userdata); + typedef void (*ggml_custom2_op_t)(struct ggml_tensor * dst , const struct ggml_tensor * a, const struct ggml_tensor * b, int ith, int nth, void * userdata); + typedef void (*ggml_custom3_op_t)(struct ggml_tensor * dst , const struct ggml_tensor * a, const struct ggml_tensor * b, const struct ggml_tensor * c, int ith, int nth, void * userdata); + +#define GGML_N_TASKS_MAX (-1) + // n_tasks == GGML_N_TASKS_MAX means to use max number of tasks + + GGML_API struct ggml_tensor * ggml_map_custom1( + struct ggml_context * ctx, + struct ggml_tensor * a, + ggml_custom1_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_map_custom1_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + ggml_custom1_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_map_custom2( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + ggml_custom2_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_map_custom2_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + ggml_custom2_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_map_custom3( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + ggml_custom3_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_map_custom3_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + ggml_custom3_op_t fun, + int n_tasks, + void * userdata); + + typedef void (*ggml_custom_op_t)(struct ggml_tensor * dst , int ith, int nth, void * userdata); + + GGML_API struct ggml_tensor * ggml_custom_4d( + struct ggml_context * ctx, + enum ggml_type type, + int64_t ne0, + int64_t ne1, + int64_t ne2, + int64_t ne3, + struct ggml_tensor ** args, + int n_args, + ggml_custom_op_t fun, + int n_tasks, + void * userdata); + + GGML_API struct ggml_tensor * ggml_custom_inplace( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor ** args, + int n_args, + ggml_custom_op_t fun, + int n_tasks, + void * userdata); + + // loss function + + GGML_API struct ggml_tensor * ggml_cross_entropy_loss( + struct ggml_context * ctx, + struct ggml_tensor * a, // logits + struct ggml_tensor * b); // labels + + GGML_API struct ggml_tensor * ggml_cross_entropy_loss_back( + struct ggml_context * ctx, + struct ggml_tensor * a, // logits + struct ggml_tensor * b, // labels + struct ggml_tensor * c); // gradients of cross_entropy_loss result + + // AdamW optimizer step + // Paper: https://arxiv.org/pdf/1711.05101v3.pdf + // PyTorch: https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html + GGML_API struct ggml_tensor * ggml_opt_step_adamw( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * grad, + struct ggml_tensor * m, + struct ggml_tensor * v, + struct ggml_tensor * adamw_params); // parameters such as the learning rate + + // stochastic gradient descent step (with weight decay) + GGML_API struct ggml_tensor * ggml_opt_step_sgd( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * grad, + struct ggml_tensor * sgd_params); // alpha, weight decay + + // build forward multiple tensors and select one of them for computing + // this is useful for creating graphs that have constant topology but compute different things based on the input + // ref: https://github.com/ggml-org/llama.cpp/pull/18550 + // + // nodes: + // | - build forward into the graph but do not compute + // c - build forward into the graph and compute + // + // | | ... c ... | + // | | ... c ... | + // | | ... c ... | + // [0 1 ... idx ... n-1] <-- ggml_build_forward_select(..., n, idx) + // c + // c + // + // example: + // struct ggml_tensor * curs[3]; + // + // curs[0] = compute0(...); + // curs[1] = compute1(...); + // curs[2] = compute2(...); + // + // int idx = select_branch(some_input); + // + // struct ggml_tensor * out = ggml_build_forward_select(cgraph, curs, 3, idx); + // + GGML_API struct ggml_tensor * ggml_build_forward_select( + struct ggml_cgraph * cgraph, + struct ggml_tensor ** tensors, + int n_tensors, + int idx); + + GGML_API void ggml_build_forward_expand( + struct ggml_cgraph * cgraph, + struct ggml_tensor * tensor); + + // add the tensor and its parents to the graph without marking them for compute + // the flag is set later, when the tensor is reached from a node that computes + GGML_API void ggml_build_forward_order( + struct ggml_cgraph * cgraph, + struct ggml_tensor * tensor); + + GGML_API void ggml_build_backward_expand( + struct ggml_context * ctx, // context for gradient computation + struct ggml_cgraph * cgraph, + struct ggml_tensor ** grad_accs); + + // graph allocation in a context + GGML_API struct ggml_cgraph * ggml_new_graph (struct ggml_context * ctx); // size = GGML_DEFAULT_GRAPH_SIZE, grads = false + GGML_API struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads); + GGML_API struct ggml_cgraph * ggml_graph_dup (struct ggml_context * ctx, struct ggml_cgraph * cgraph, bool force_grads); + GGML_API void ggml_graph_cpy (struct ggml_cgraph * src, struct ggml_cgraph * dst); + GGML_API void ggml_graph_reset (struct ggml_cgraph * cgraph); // set regular grads + optimizer momenta to 0, set loss grad to 1 + GGML_API void ggml_graph_clear (struct ggml_cgraph * cgraph); + + GGML_API int ggml_graph_size (struct ggml_cgraph * cgraph); + GGML_API struct ggml_tensor * ggml_graph_node (struct ggml_cgraph * cgraph, int i); // if i < 0, returns nodes[n_nodes + i] + GGML_API struct ggml_tensor ** ggml_graph_nodes (struct ggml_cgraph * cgraph); + GGML_API int ggml_graph_n_nodes(struct ggml_cgraph * cgraph); + + GGML_API void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor); + + GGML_API size_t ggml_graph_overhead(void); + GGML_API size_t ggml_graph_overhead_custom(size_t size, bool grads); + + GGML_API struct ggml_tensor * ggml_graph_get_tensor (const struct ggml_cgraph * cgraph, const char * name); + GGML_API struct ggml_tensor * ggml_graph_get_grad (const struct ggml_cgraph * cgraph, const struct ggml_tensor * node); + GGML_API struct ggml_tensor * ggml_graph_get_grad_acc(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node); + + // print info and performance information for the graph + GGML_API void ggml_graph_print(const struct ggml_cgraph * cgraph); + + // dump the graph into a file using the dot format + GGML_API void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * cgraph, const char * filename); + + // TODO these functions were sandwiched in the old optimization interface, is there a better place for them? + typedef void (*ggml_log_callback)(enum ggml_log_level level, const char * text, void * user_data); + + // Set callback for all future logging events. + // If this is not called, or NULL is supplied, everything is output on stderr. + GGML_API void ggml_log_get(ggml_log_callback * log_callback, void ** user_data); + GGML_API void ggml_log_set(ggml_log_callback log_callback, void * user_data); + + GGML_API struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor); + + // + // quantization + // + + // - ggml_quantize_init can be called multiple times with the same type + // it will only initialize the quantization tables for the first call or after ggml_quantize_free + // automatically called by ggml_quantize_chunk for convenience + // + // - ggml_quantize_free will free any memory allocated by ggml_quantize_init + // call this at the end of the program to avoid memory leaks + // + // note: these are thread-safe + // + GGML_API void ggml_quantize_init(enum ggml_type type); + GGML_API void ggml_quantize_free(void); + + // some quantization type cannot be used without an importance matrix + GGML_API bool ggml_quantize_requires_imatrix(enum ggml_type type); + + // calls ggml_quantize_init internally (i.e. can allocate memory) + GGML_API size_t ggml_quantize_chunk( + enum ggml_type type, + const float * src, + void * dst, + int64_t start, + int64_t nrows, + int64_t n_per_row, + const float * imatrix); + +#ifdef __cplusplus + // restrict not standard in C++ +# if defined(__GNUC__) +# define GGML_RESTRICT __restrict__ +# elif defined(__clang__) +# define GGML_RESTRICT __restrict +# elif defined(_MSC_VER) +# define GGML_RESTRICT __restrict +# else +# define GGML_RESTRICT +# endif +#else +# if defined (_MSC_VER) && (__STDC_VERSION__ < 201112L) +# define GGML_RESTRICT __restrict +# else +# define GGML_RESTRICT restrict +# endif +#endif + typedef void (*ggml_to_float_t) (const void * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k); + typedef void (*ggml_from_float_t)(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k); + + struct ggml_type_traits { + const char * type_name; + int64_t blck_size; + int64_t blck_size_interleave; // interleave elements in blocks + size_t type_size; + bool is_quantized; + ggml_to_float_t to_float; + ggml_from_float_t from_float_ref; + }; + + GGML_API const struct ggml_type_traits * ggml_get_type_traits(enum ggml_type type); + + // ggml threadpool + // TODO: currently, only a few functions are in the base ggml API, while the rest are in the CPU backend + // the goal should be to create an API that other backends can use move everything to the ggml base + + // scheduling priorities + enum ggml_sched_priority { + GGML_SCHED_PRIO_LOW = -1, + GGML_SCHED_PRIO_NORMAL, + GGML_SCHED_PRIO_MEDIUM, + GGML_SCHED_PRIO_HIGH, + GGML_SCHED_PRIO_REALTIME + }; + + // threadpool params + // Use ggml_threadpool_params_default() or ggml_threadpool_params_init() to populate the defaults + struct ggml_threadpool_params { + bool cpumask[GGML_MAX_N_THREADS]; // mask of cpu cores (all-zeros means use default affinity settings) + int n_threads; // number of threads + enum ggml_sched_priority prio; // thread priority + uint32_t poll; // polling level (0 - no polling, 100 - aggressive polling) + bool strict_cpu; // strict cpu placement + bool paused; // start in paused state + }; + + struct ggml_threadpool; // forward declaration, see ggml.c + + typedef struct ggml_threadpool * ggml_threadpool_t; + + GGML_API struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads); + GGML_API void ggml_threadpool_params_init (struct ggml_threadpool_params * p, int n_threads); + GGML_API bool ggml_threadpool_params_match (const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1); + +#ifdef __cplusplus +} +#endif diff --git a/control-plane/third_party/ggml/gguf.h b/control-plane/third_party/ggml/gguf.h new file mode 100644 index 00000000..b3a1e123 --- /dev/null +++ b/control-plane/third_party/ggml/gguf.h @@ -0,0 +1,211 @@ +// This file contains functionality related to "GGUF" files, the binary file format used by ggml. +// GGUF files have the following structure: +// +// 1. File magic "GGUF" (4 bytes). +// 2. File version (uint32_t). +// 3. Number of ggml tensors in file (int64_t). +// 4. Number of key-value-pairs in file (int64_t). +// 5. For each KV pair: +// 1. The key (string). +// 2. The value type (gguf_type). +// 3a. If the value type is GGUF_TYPE_ARRAY: +// 1. The type of the array (gguf_type). +// 2. The number of elements in the array (uint64_t). +// 3. The binary representation of each element in the array. +// 3b. Otherwise: +// 1. The binary representation of the value. +// 6. For each ggml tensor: +// 1. The tensor name (string). +// 2. The number of dimensions of the tensor (uint32_t). +// 3. For each dimension: +// 1. The size of the tensor in the dimension (int64_t). +// 4. The tensor data type (ggml_type). +// 5. The tensor data offset in the tensor data binary blob (uint64_t). +// 7. The tensor data binary blob (optional, aligned). +// +// Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator. +// All enums are stored as int32_t. +// All bool values are stored as int8_t. +// If the special key "general.alignment" (uint32_t) is defined it is used for alignment, +// otherwise GGUF_DEFAULT_ALIGNMENT is used. +// +// Module maintainer: Johannes Gäßler (@JohannesGaessler, johannesg@5d6.de) + +#pragma once + +#include "ggml.h" + +#include +#include + +#define GGUF_MAGIC "GGUF" +#define GGUF_VERSION 3 + +#define GGUF_KEY_GENERAL_ALIGNMENT "general.alignment" + +#define GGUF_DEFAULT_ALIGNMENT 32 + +#ifdef __cplusplus +extern "C" { +#endif + + // types that can be stored as GGUF KV data + enum gguf_type { + GGUF_TYPE_UINT8 = 0, + GGUF_TYPE_INT8 = 1, + GGUF_TYPE_UINT16 = 2, + GGUF_TYPE_INT16 = 3, + GGUF_TYPE_UINT32 = 4, + GGUF_TYPE_INT32 = 5, + GGUF_TYPE_FLOAT32 = 6, + GGUF_TYPE_BOOL = 7, + GGUF_TYPE_STRING = 8, + GGUF_TYPE_ARRAY = 9, + GGUF_TYPE_UINT64 = 10, + GGUF_TYPE_INT64 = 11, + GGUF_TYPE_FLOAT64 = 12, + GGUF_TYPE_COUNT, // marks the end of the enum + }; + + struct gguf_context; + + struct gguf_init_params { + bool no_alloc; + + // if not NULL, create a ggml_context and allocate the tensor data in it + struct ggml_context ** ctx; + }; + + // callback to simulate or wrap a FILE pointer - read up to `len` bytes at `offset` into `output` and return the number of bytes read + typedef size_t (*gguf_reader_callback_t)(void * userdata, void * output, uint64_t offset, size_t len); + + GGML_API struct gguf_context * gguf_init_empty(void); + GGML_API struct gguf_context * gguf_init_from_file_ptr(FILE * file, struct gguf_init_params params); + GGML_API struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params); + GGML_API struct gguf_context * gguf_init_from_buffer(const void * data, size_t size, struct gguf_init_params params); + + // max_chunk_read is the maximum number of bytes that the GGUF code will read at once from the callback, a value of 0 means no limit + GGML_API struct gguf_context * gguf_init_from_callback(gguf_reader_callback_t callback, void * userdata, size_t max_chunk_read, uint64_t max_expected_size, struct gguf_init_params params); + + GGML_API void gguf_free(struct gguf_context * ctx); + + GGML_API const char * gguf_type_name(enum gguf_type type); + + GGML_API uint32_t gguf_get_version (const struct gguf_context * ctx); + GGML_API size_t gguf_get_alignment (const struct gguf_context * ctx); + GGML_API size_t gguf_get_data_offset(const struct gguf_context * ctx); // padded to gguf_get_alignment if and only if the gguf_context contains at least one tensor + + GGML_API int64_t gguf_get_n_kv(const struct gguf_context * ctx); + GGML_API int64_t gguf_find_key(const struct gguf_context * ctx, const char * key); // returns -1 if key is not found + GGML_API const char * gguf_get_key (const struct gguf_context * ctx, int64_t key_id); + + GGML_API enum gguf_type gguf_get_kv_type (const struct gguf_context * ctx, int64_t key_id); + GGML_API enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id); + + // will abort if the wrong type is used for the key + GGML_API uint8_t gguf_get_val_u8 (const struct gguf_context * ctx, int64_t key_id); + GGML_API int8_t gguf_get_val_i8 (const struct gguf_context * ctx, int64_t key_id); + GGML_API uint16_t gguf_get_val_u16 (const struct gguf_context * ctx, int64_t key_id); + GGML_API int16_t gguf_get_val_i16 (const struct gguf_context * ctx, int64_t key_id); + GGML_API uint32_t gguf_get_val_u32 (const struct gguf_context * ctx, int64_t key_id); + GGML_API int32_t gguf_get_val_i32 (const struct gguf_context * ctx, int64_t key_id); + GGML_API float gguf_get_val_f32 (const struct gguf_context * ctx, int64_t key_id); + GGML_API uint64_t gguf_get_val_u64 (const struct gguf_context * ctx, int64_t key_id); + GGML_API int64_t gguf_get_val_i64 (const struct gguf_context * ctx, int64_t key_id); + GGML_API double gguf_get_val_f64 (const struct gguf_context * ctx, int64_t key_id); + GGML_API bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id); + GGML_API const char * gguf_get_val_str (const struct gguf_context * ctx, int64_t key_id); + GGML_API const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id); + GGML_API size_t gguf_get_arr_n (const struct gguf_context * ctx, int64_t key_id); + + // get raw pointer to the first element of the array with the given key_id + // for bool arrays, note that they are always stored as int8 on all platforms (usually this makes no difference) + GGML_API const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id); + + // get ith C string from array with given key_id + GGML_API const char * gguf_get_arr_str (const struct gguf_context * ctx, int64_t key_id, size_t i); + + GGML_API int64_t gguf_get_n_tensors (const struct gguf_context * ctx); + GGML_API int64_t gguf_find_tensor (const struct gguf_context * ctx, const char * name); // returns -1 if the tensor is not found + GGML_API size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id); + GGML_API const char * gguf_get_tensor_name (const struct gguf_context * ctx, int64_t tensor_id); + GGML_API const int64_t * gguf_get_tensor_ne (const struct gguf_context * ctx, int64_t tensor_id); // returns ne, an array of GGML_MAX_DIMS elements; ne[dim] is 1 for dim >= n_dims + GGML_API enum ggml_type gguf_get_tensor_type (const struct gguf_context * ctx, int64_t tensor_id); + GGML_API size_t gguf_get_tensor_size (const struct gguf_context * ctx, int64_t tensor_id); + + // removes key if it exists, returns id that the key had prior to removal (-1 if it didn't exist) + GGML_API int64_t gguf_remove_key(struct gguf_context * ctx, const char * key); + + // overrides an existing KV pair or adds a new one, the new KV pair is always at the back + GGML_API void gguf_set_val_u8 (struct gguf_context * ctx, const char * key, uint8_t val); + GGML_API void gguf_set_val_i8 (struct gguf_context * ctx, const char * key, int8_t val); + GGML_API void gguf_set_val_u16 (struct gguf_context * ctx, const char * key, uint16_t val); + GGML_API void gguf_set_val_i16 (struct gguf_context * ctx, const char * key, int16_t val); + GGML_API void gguf_set_val_u32 (struct gguf_context * ctx, const char * key, uint32_t val); + GGML_API void gguf_set_val_i32 (struct gguf_context * ctx, const char * key, int32_t val); + GGML_API void gguf_set_val_f32 (struct gguf_context * ctx, const char * key, float val); + GGML_API void gguf_set_val_u64 (struct gguf_context * ctx, const char * key, uint64_t val); + GGML_API void gguf_set_val_i64 (struct gguf_context * ctx, const char * key, int64_t val); + GGML_API void gguf_set_val_f64 (struct gguf_context * ctx, const char * key, double val); + GGML_API void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val); + GGML_API void gguf_set_val_str (struct gguf_context * ctx, const char * key, const char * val); + + // creates a new array with n elements of the given type and copies the corresponding number of bytes from data + GGML_API void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n); + + // creates a new array with n strings and copies the corresponding strings from data + GGML_API void gguf_set_arr_str (struct gguf_context * ctx, const char * key, const char ** data, size_t n); + + // set or add KV pairs from another context + GGML_API void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src); + + // add tensor to GGUF context, tensor name must be unique + GGML_API void gguf_add_tensor(struct gguf_context * ctx, const struct ggml_tensor * tensor); + + // after changing a tensor's type, the offsets of all tensors with higher indices are immediately recalculated + // in such a way that the tensor data remains as one contiguous block (except for padding) + GGML_API void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type); + + // assumes that at least gguf_get_tensor_size bytes can be read from data + GGML_API void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data); + + // writing gguf files can be done in 3 ways: + // + // - write the entire gguf_context to a binary file in a single pass: + // + // gguf_write_to_file(ctx, fname, /*only_meta =*/ false); + // + // - write only the meta data to a file, then re-open the file and append the tensor data: + // + // gguf_write_to_file(ctx, fname, /*only_meta =*/ true); + // FILE * f = fopen(fname, "ab"); + // fwrite(f, ...); // write tensor data + // fclose(f); + // + // - first prepare a file with a placeholder for the meta data, write the tensor data, then write the meta data: + // + // FILE * f = fopen(fname, "wb"); + // const size_t size_meta = gguf_get_meta_size(ctx); + // fseek(f, size_meta, SEEK_SET); + // fwrite(f, ...); // write tensor data + // void * data = malloc(size_meta); + // gguf_get_meta_data(ctx, data); + // rewind(f); + // fwrite(data, 1, data, f); + // free(data); + // fclose(f); + // + + // write the entire context to a binary file + GGML_API bool gguf_write_to_file_ptr(const struct gguf_context * ctx, FILE * file, bool only_meta); + GGML_API bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta); + + // get the size in bytes of the meta data (header, kv pairs, tensor info) including padding + GGML_API size_t gguf_get_meta_size(const struct gguf_context * ctx); + + // writes the meta data to pointer "data" + GGML_API void gguf_get_meta_data(const struct gguf_context * ctx, void * data); + +#ifdef __cplusplus +} +#endif diff --git a/deploy/Dockerfile.runtime b/deploy/Dockerfile.runtime new file mode 100644 index 00000000..ff6af8b1 --- /dev/null +++ b/deploy/Dockerfile.runtime @@ -0,0 +1,15 @@ +# Built only from the private, validated context produced by build-runtime-image.py. +ARG BASE +FROM ${BASE} +ARG BUILD_ID +ARG PACKAGE_KIND +LABEL io.strata.build-id=${BUILD_ID} io.strata.package-kind=${PACKAGE_KIND} +COPY --chmod=0555 strata-next-linux-x86_64-musl /usr/local/bin/strata-next +COPY --chmod=0444 PROVENANCE.json SHA256SUMS /usr/share/strata/ +ENV NVIDIA_VISIBLE_DEVICES=void NVIDIA_DRIVER_CAPABILITIES=compute,utility STRATA_BIND=0.0.0.0:8081 +USER 65532:65532 +WORKDIR /tmp +EXPOSE 8081 +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/local/bin/strata-next"] +CMD ["serve"] diff --git a/deploy/Dockerfile.static-cli b/deploy/Dockerfile.static-cli new file mode 100644 index 00000000..066dde61 --- /dev/null +++ b/deploy/Dockerfile.static-cli @@ -0,0 +1,20 @@ +FROM rust:1.99-bookworm AS build + +ARG RUST_TARGET=x86_64-unknown-linux-musl +RUN apt-get update \ + && apt-get install -y --no-install-recommends musl-tools cmake \ + && rm -rf /var/lib/apt/lists/* +RUN rustup target add "${RUST_TARGET}" + +WORKDIR /src +COPY rust-toolchain.toml ./ +COPY manifests/ ./manifests/ +COPY control-plane/ ./control-plane/ +COPY engine/strata/LICENSE ./engine/strata/LICENSE +RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \ + --target "${RUST_TARGET}" --bin strata-next + +FROM scratch +ARG RUST_TARGET=x86_64-unknown-linux-musl +COPY --from=build /src/control-plane/target/${RUST_TARGET}/release/strata-next /strata-next +ENTRYPOINT ["/strata-next"] diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 00000000..1010ce20 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,1132 @@ +# Deployment + +Linux CI builds a statically linked musl CLI/control-plane preview and publishes it as a prerelease artifact on version tags. This is not yet a complete GPU runtime: the C++/CUDA engine is not linked into that executable. The host must have a compatible NVIDIA driver already installed (CUDA 13.0 GA baseline: 580.65.06 or newer). The `strata-next doctor` command checks the installed version. Model weights belong on an external volume. A complete GPU deployment image has not been built yet. + +For a local static CLI image smoke test, build `deploy/Dockerfile.static-cli` with a Linux/musl target. The final image is `scratch` plus the CLI binary. It is a packaging test, not the deployment image for inference. + +## Worker recovery + +Configure top-level JSON `max_in_flight_requests` or environment +`STRATA_MAX_IN_FLIGHT_REQUESTS` to bound admitted HTTP inference requests +(1–256; default 17). Environment overrides the file. At capacity, new Responses +POSTs receive 429 `runtime_overloaded` and `Retry-After: 1` before parsing; +drain still returns 503. This covers queued requests and streaming bodies, +not GPU concurrency. `/admin/lifecycle` exposes the limit and available request +slots; `check-config` validates and reports the limit. See +[admission lifecycle](../docs/api-contract.md#admission-lifecycle) for scope. + +The Rust supervisor defaults to three lifetime restarts after a post-READY +worker failure, with 2/4/8-second backoff. Configure `engine.max_restarts` or +`STRATA_MAX_WORKER_RESTARTS` from 0 to 3; zero disables recovery. Failed and +queued generations are not replayed. Readiness stays false until the new +worker handshake completes. A startup failure or an exhausted budget leaves +the service unhealthy for inference until an operator restarts it; `/health` +remains available. See [the API contract](../docs/api-contract.md). + +Top-level `queue_timeout_s` (or `STRATA_QUEUE_TIMEOUT_S`, 1–86400 seconds) optionally +bounds waiting for a worker to claim an inference command. It is disabled by +default; environment overrides the config file. The clock starts after request +validation, prompt rendering and tokenization, and includes command-channel +admission and waiting behind active work. `check-config` reports seconds or null. +Responses, Chat and Messages use the same queue. An expired unclaimed request +returns HTTP 504 with a JSON error before any SSE headers; Responses/Chat use +`queue_timeout`, while Messages retains its own error envelope. + +Worker claim and expiry have one atomic winner. Expired commands are skipped +without sending `GEN`; there is no retry or replay. Once claimed, only the +existing active-generation deadline applies, so a long prefill is not cut short +by the queue setting. A canceled queued command retains its generation activity +guard until the worker dequeues it or the queue closes, allowing drain to account +for outstanding cleanup. Queue time does not include upload or tokenization and +is not a total request deadline. Default behavior is unchanged. Tests cover an +isolated CPU worker and exact output A, not real-model performance. + +An optional `engine.generation_timeout_s` (or `STRATA_GENERATION_TIMEOUT_S`) +sets an absolute active-command deadline, 1–86400 seconds. It is **disabled +when omitted**. Select a budget that accommodates the model's longest prefill +and output. The clock starts when the worker takes the command; HTTP parsing, +tokenization and queue wait are excluded. Engine stdin writes, reading tokens +and waiting on the streaming channel are included. Native `check-config` +reports this value, or null when disabled/unconfigured. + +On expiry the supervisor revokes readiness and kills/reaps that worker rather +than attempting to reuse its unfinished protocol stream. The failed command +and queued work are never replayed. The existing finite restart budget applies; +model loading and caches must be rebuilt after restart. With zero restarts the +worker remains failed. Connected clients receive the terminal failure described +in [the API contract](../docs/api-contract.md#active-generation-deadline). + +## Native Linux service lifecycle + +For an authenticated deployment, initialize its credential using the executable: + +```sh +mkdir -m 700 /absolute/private/config +/absolute/path/strata-next api-key init --file /absolute/private/config/api.key +``` + +Set `api_key_file` in the serving config (or `STRATA_API_KEY_FILE`) to this path; +pass it to `wait-ready --key-file` and configure the client to use its contents. +`api-key init` uses the Linux OS random source and atomically publishes a 0600 +file in an existing owned private directory. It returns only `created`/`reused`. +Repeated or concurrent initialization preserves the existing valid private key. +Invalid, permissive, symlink or nonregular targets are refused without replacement +or permission changes. This command does not rotate credentials or alter a running +service; retain the key outside Git and container images. + +The native executable can install and operate its per-user service directly: + +```sh +/absolute/path/strata-next service-install \ + --config /absolute/path/config.json --working-dir /absolute/path/workdir \ + --unit strata-next-prod.service --start +/absolute/path/strata-next service-control status \ + --config /absolute/path/config.json --working-dir /absolute/path/workdir \ + --unit strata-next-prod.service +``` + +`service-control` accepts `status`, `start`, `stop`, `restart`, `enable`, `disable`, +`start-ready`, `restart-ready`, `drain-stop` or `resume`. Supply the same +executable, config, working directory, optional `--env-file` and unit name used +at installation. The CLI verifies the existing private unit's exact generated +content and the user manager's fragment path/no drop-ins before operating on it. +A stale manager definition (`NeedDaemonReload`) is refused until explicitly reconciled. +Missing or conflicting units are refused. `status` only queries the manager; +control never installs or replaces a unit. Activation actions reload user-manager +unit definitions; status/start/stop/restart do not. Start/stop are +idempotent manager requests; restart explicitly stops and starts the service. +The JSON result includes `manager.active_state`, `manager.sub_state`, +`manager.main_pid`, `manager.unit_file_state` and `model_readiness: "not_checked"`. Use native `wait-ready` +for actual model readiness. No journal or environment contents are returned. + +For a managed start that also verifies model readiness, use: + +```sh +/absolute/path/strata-next service-control start-ready \ + --config /absolute/path/config.json --working-dir /absolute/path/workdir \ + --unit strata-next-prod.service \ + --ready-url http://127.0.0.1:18082 --ready-model MODEL_ID \ + --ready-key-file /absolute/path/api.key --ready-timeout-s 120 +``` + +`restart-ready` explicitly restarts first; `start-ready` reuses an already running +service. Both require a literal loopback HTTP origin and model ID. The key file is +optional for an unauthenticated profile. Options and private key validity are +checked before any manager command. After the manager action, the bounded HTTP +wait checks service/model/worker readiness and `server_pid` against the managed +MainPID. Before returning `model_readiness: "ready"`, it rechecks the exact unit, +loaded definition, active state and unchanged MainPID. `/status` and `/ready` +include `server_pid`; standalone `wait-ready` still accepts endpoints without it. + +This process correlation requires the same local PID namespace. A PID is neither +authentication nor a durable process epoch, and readiness is a point-in-time +observation. The readiness timeout (1–3600 seconds, default 300) starts after the +manager action; manager query/action limits still apply separately. On a wait or +identity failure, the CLI returns an error and leaves the service for explicit +reconciliation. It does not repeat the action, stop an unrelated endpoint or +perform automatic rollback. Hosted checks use an isolated synthetic worker, +including cold/repeated start, restart, exact output A, mismatched PID and timeout. + +To stop after current work finishes, use `service-control drain-stop` with the +same unit identity and `--ready-*` arguments. It validates the managed process, +closes new inference admission, and waits for its admitted HTTP requests and +queued/active worker jobs to finish. Only a same-process `drained: true` snapshot +with zero activity, followed by fresh unit/manager checks, permits one systemd +stop request. Plain `stop` and `restart` retain their existing bounded shutdown +behavior; draining is explicit. + +If the admission deadline expires or the HTTP outcome is unknown, no manager +stop is requested. The runtime may remain draining. Inspect its state, then use +`service-control resume` with the same arguments to reopen that process without +restarting it, or explicitly retry `drain-stop` to wait longer. These commands +never automatically replay an HTTP mutation or force stop after drain failure. +The HTTP budget includes the initial identity read, single mutation and polls; +manager timeouts are separate. Serialize administrative operations: an external +operator can change admission or systemd state after the final observation. + +`/admin/lifecycle`, `/admin/drain` and `/admin/resume` return service/model/PID +identity. Drain and resume accept optional `x-strata-expected-pid`; an invalid or +duplicate header returns 400 and a different PID returns 409 before changing +admission. Native managed controls send this precondition. Existing authenticated +HTTP clients without it remain compatible. As with readiness, PID correlation +requires the same local namespace and does not replace authentication or an epoch. + +### Switch between installed native profiles + +`service-switch` composes target preparation, graceful drain and verified startup +with rollback when target startup fails. Both profiles must already be installed +using this exact executable and `service-install`; the previous service must be +running and ready, and the target inactive. Use distinct units and immutable, +versioned config/model paths. This initial path supports native Strata service +profiles without environment-file overlays, sharing one literal loopback origin. +It does not import the qwen-codex-ctl catalog or add other inference backends. + +Save a private (mode 600), owned catalog, for example: + +```json +{ + "schema_version": 1, + "provision_timeout_s": 3600, + "profiles": { + "alpha": { + "unit": "strata-next-alpha.service", + "config": "/home/operator/strata/alpha/config.json", + "working_dir": "/home/operator/strata/alpha", + "url": "http://127.0.0.1:18082", + "model": "alpha", + "key_file": "/home/operator/strata/api.key", + "timeout_s": 300 + }, + "beta": { + "unit": "strata-next-beta.service", + "config": "/home/operator/strata/beta/config.json", + "working_dir": "/home/operator/strata/beta", + "url": "http://127.0.0.1:18082", + "model": "beta", + "key_file": "/home/operator/strata/api.key", + "timeout_s": 300 + } + } +} +``` + +```sh +strata-next service-switch --catalog /home/operator/strata/catalog.json \ + --from alpha --to beta --state-dir /home/operator/strata/switch-state +``` + +The catalog is bounded to 64 KiB/16 profiles; readiness budgets are 1–3600 seconds +and the preparation budget is 1–86400 seconds. Target preparation invokes this +same executable's `provision --config`, with inherited `STRATA_*` overrides +removed, before draining the previous service. Service-manager environment +should likewise contain no conflicting overrides. Config digests are checked +around preparation and before startup. Successful preparation is not proof of +GPU/model readiness; startup still has to pass the managed readiness check. + +The state directory is created privately (parent must exist), with an OS lock +and durable `transaction.json` phase record. Use one state directory for all +switches of this deployment and serialize external administrative changes. A +preparation failure preserves the running profile. A failed target startup is +followed by verified target stop and previous-profile startup/readiness; this +returns a nonzero exit with `rolled_back` and retains the result in the journal. +If target stop or previous restoration cannot be confirmed, the command stops +with reconciliation required. No unknown lifecycle action is silently replayed. + +An unfinished/unknown journal prevents another switch. After interruption, +inspect both units with `service-control status` and their native lifecycle +endpoints. Explicitly keep the selected service, or stop the target and restore +the previous one using the existing native controls; resume admission if needed. +For known interrupted phases, use the SHA-bound `service-switch reconcile` command +below to verify and record that state before a new explicit selection. Unknown +or corrupt records remain blocked for manual investigation. +This version does not automatically recover across command/process crashes. +PID checks require the same namespace; all artifact paths must remain immutable +through the transaction. Tests qualify actual isolated Linux services with CPU +fixtures, not live GPU rollback or full model/backend catalog parity. + +To opt in to startup in future user-manager sessions, add `--enable` to +`service-install`. It is independent of `--start`: enabling alone does not start +or restart the runtime. For an installed unit use `service-control enable` or +`service-control disable` with the same identity arguments as `status` above. +These actions use `systemctl --user enable/disable` with its normal user-manager +configuration reload, without `--now` or `--force`. Reload is needed to reconcile +activation state; it does not restart the process. The exact loaded unit identity +is checked again after activation. Repeated enable/disable is supported. +The default-target activation directory must be owned and not group/other +writable, and any existing activation link must point to this exact unit. +Conflicts are refused for explicit reconciliation. No activation option is +enabled by default, and disabling does not delete the unit or model artifacts. + +Enabling a user service means startup when that user's systemd manager starts, +usually at login. Startup without login requires host-admin configured lingering +or an equivalent manager lifecycle. The CLI never invokes `loginctl`, changes +lingering, installs a system-wide unit or requests privileges. An enabled unit +does not establish model readiness; use `wait-ready` after startup. Hosted tests +verify actual isolated manager activation links and PID preservation, not a +physical reboot or clean-node GPU inference. + +Each manager query is limited to 30 seconds/16 KiB, and lifecycle actions to +60 seconds (the generated unit has a 45-second stop deadline). If a client times +out, its process is killed/reaped; the manager job may still be pending. Inspect +status before retrying. A moved executable or changed unit/config identity +requires explicit reconciliation; control does not guess which service to use. + +For manual installation or unit inspection, `strata-next service-unit` renders a **systemd user unit** to stdout. It does +not install, start, enable or replace a service. Provision the native executable, +engine, tokenizer and private JSON configuration first; all supplied paths must +be absolute and exist. Systemd disallows quotes and backslashes in the executable +path; the renderer rejects these with a relocation instruction. For example, +on the Linux host: + +```sh +umask 077 +mkdir -p "$HOME/.config/systemd/user" +/absolute/path/strata-next service-unit \ + --config /absolute/path/config.json \ + --working-dir /absolute/path/engine-workdir \ + --env-file /absolute/path/runtime.env > "$HOME/strata-next.service" +systemd-analyze --user verify "$HOME/strata-next.service" +# Review the generated unit before installing. Do not overwrite a live unit. +systemctl --user link "$HOME/strata-next.service" +systemctl --user start strata-next.service +systemctl --user status strata-next.service +journalctl --user -u strata-next.service -n 100 +``` + +Omit `--env-file` if unnecessary. The file uses systemd EnvironmentFile syntax, +not shell commands; it can set `LD_LIBRARY_PATH` and engine tuning variables. +Its path cannot contain glob characters (`*`, `?`, `[`), backslashes or trailing +whitespace, because systemd interprets that directive as a filename pattern. +`serve --config FILE` selects the explicit config even if `STRATA_CONFIG` is +also set; other documented environment overrides still apply. Keep the API +bound to loopback and use SSH forwarding; optional bearer authentication does +not provide transport encryption. Set `STRATA_API_KEY_FILE` to a private key +file to enable the [native auth gate](../docs/api-contract.md#optional-bearer-authentication). + +Systemd process startup is not model readiness: check the configured `/ready` +endpoint before connecting the console harness. `Restart=no` preserves the +supervisor's finite worker restart policy. SIGTERM goes to the supervisor; +remaining processes in its cgroup are killed after the 45-second stop deadline. +No model or logs are copied into a release by rendering the unit. Journald +retention is managed by the host; model and capture paths should remain private. + +To stop and remove an explicitly installed service: + +```sh +systemctl --user stop strata-next.service +systemctl --user disable strata-next.service +systemctl --user daemon-reload +``` + +Without the explicit `--enable`/`enable` option, the service is not enabled at +login/boot by these instructions. A running user +manager is required. The existing trial endpoint remains externally launched; +these instructions do not migrate it. Use the existing `connect strata-native` +command once a provisioned service is ready. + +### Console controller + +Install the opt-in controller commands on the laptop after the native Responses +launcher integration (the installer preserves the selected connection): + +```sh +python3 scripts/install-qwen-native.py +python3 scripts/install-qwen-native-service.py +qwen-codex-ctl native-service status --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service start --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service logs --host rnr5090 --unit strata-next.service +qwen-codex-ctl native-service stop --host rnr5090 --unit strata-next.service +``` + +These operate on an **already provisioned** systemd user unit through SSH; +they never install, enable, migrate or switch a model. The host defaults to the +launcher's configured SSH alias, and the unit to `strata-next.service`. Optional +unit names must follow `strata-next-NAME.service`. Start/stop are idempotent; +SSH calls time out after 90 seconds. Logs show the selected unit's last 100 +entries. No service credentials are copied or stored by this helper. + +The JSON status describes the **process**; `model_readiness: not_checked` is +explicit. Model initialization can continue after process startup. The separate +`qwen-codex-ctl connect strata-native --url http://127.0.0.1:18084 --no-auth` + +### Select an existing native deployment in the launcher menu + +After native Responses integration, run `python3 scripts/install-qwen-native-menu.py` +on the client to install or upgrade the native picker. This preserves the selected +connection and backs up the launcher. To make `qwen-codex-ctl start strata-native` +attach to a specific ready deployment, create a private `native-picker.json` in +the launcher profile directory (normally `~/.codex-qwen-interactive`, or the +explicit `QWEN_CODEX_PROFILE` directory): + +```json +{ + "schema_version": 1, + "mode": "attach", + "url": "http://127.0.0.1:18084", + "model": "my-native-model", + "key_file": "/absolute/private/path/api.key" +} +``` + +Set permissions to `0600`; the file must be owned by the current user and cannot +be a symlink. `key_file` may be `null` for a deliberately unauthenticated loopback +endpoint. The endpoint/tunnel must already exist. Attachment checks readiness, +the exact model ID, and the supported one-slot 256K layout before updating the +connection. It does not start or switch remote services, create tunnels, or change +the model's compression mode. Errors fail without invoking the legacy controller. +If the file is absent, the prior managed native menu behavior remains in effect. +checks inference readiness through the existing SSH tunnel before switching +the console connection. Tunnel setup remains separate. The existing plain +`start/stop` commands retain their previous behavior; use `native-service` +explicitly for a managed native unit. The currently running external trial +has no such unit, so these commands safely report it as not provisioned. + +### Native API commands in the console controller + +Install the API helper after the native launcher integration: + +```sh +python3 scripts/install-qwen-native-api.py +qwen-codex-ctl native-api status +qwen-codex-ctl native-api wait-ready --wait 60 +qwen-codex-ctl native-api metrics +qwen-codex-ctl native-api lifecycle +qwen-codex-ctl native-api drain --wait 60 +# Explicitly reopen admission when maintenance is abandoned or complete: +qwen-codex-ctl native-api resume +``` + +These use the selected `strata-native` connection and its private key file. +An explicit URL requires an explicit authentication choice and does not change +the selected connection: + +```sh +qwen-codex-ctl native-api status --url http://127.0.0.1:18084 --no-auth +qwen-codex-ctl native-api metrics --url http://127.0.0.1:18084 --key-file /private/path/api.key +``` + +The helper verifies native `/status` identity before any admission mutation. +It uses direct loopback HTTP, ignoring proxy environment variables, refuses +redirects, and bounds each JSON response to 64 KiB. Socket operations time out +after eight seconds; this is not a hard total deadline for a server that keeps +sending partial bytes. Credentials are never command-line token arguments. + +`drain --wait SECONDS` polls lifecycle for up to the requested interval (0–3600 +seconds, subject to in-flight HTTP I/O). Without a positive wait it returns the +initial snapshot. Timeout, interruption or a concurrent resume produces an +error; the client never automatically stops or resumes the runtime. Inspect +lifecycle after any uncertain mutation result. Serialize operator actions. +No service, SSH tunnel or model is created or switched by these commands. + +`wait-ready --wait SECONDS` waits for native model readiness using read-only +`GET /status` calls, including when the process is still loading its model or +recovering its worker. It retries connection failures and polls every 250 ms. +The positive wait budget (up to 3600 seconds) starts before the first request; +each socket timeout is capped by the remaining budget and eight seconds. +As with the other commands, this is not a hard total deadline against a server +that keeps sending partial bytes. A response arriving after the budget does not +count as success. With no positive wait, it performs one check and fails if +the model is not ready. + +Authentication/HTTP/JSON errors, wrong endpoint identity, inconsistent status, +and failed/stopping/unconfigured workers fail immediately. The command never +starts a service, sends inference, restarts a failed worker or changes the +selected connection. Ready means available at that instant; it does not mean +idle, model quality verified, or sustained stability. + +The retained GPU trial supports `native-api status` and `native-api wait-ready`; metrics and admission +controls require the newer feature preview and return HTTP 404 on that older +trial. The helper does not upgrade a runtime automatically. Client Python is +part of the existing laptop harness; native production serving remains Rust. + +Verification without GPU inference: + +```sh +python3 scripts/smoke-service-unit.py /absolute/path/strata-next --lifecycle +``` + +This creates and removes an isolated CPU-only service on an unused loopback +port. It checks real systemd path parsing (spaces, quotes, backslashes, `$` and +`%`), config precedence, environment loading, health, false readiness without a +worker and process removal. Without `--lifecycle`, only unit syntax and rejected +path checks run, as wired into Linux CI. Hosted CI execution remains pending. + +## Drain before maintenance + +The feature preview exposes process-local admission controls (protected by the +configured API key, if enabled): + +```sh +curl -fsS -X POST http://127.0.0.1:18082/admin/drain +curl -fsS http://127.0.0.1:18082/admin/lifecycle +# Wait for drained: true, then perform an intentional stop using your service manager. +# To abandon maintenance and accept new work again: +curl -fsS -X POST http://127.0.0.1:18082/admin/resume +``` + +Use the configured endpoint port and bearer header when enabled. These calls +only change admission; they do not stop, restart, migrate or switch the engine. +They are not installed on the preserved GPU user trial yet. + +Drain is idempotent. It rejects new Responses admissions with HTTP 503 +`runtime_draining` and makes `/ready` return 503 (`/status.ready` is false). +Previously admitted JSON/SSE requests, including requests waiting for the +command queue, continue normally. Health, metrics and admin endpoints remain +available. Resume is idempotent and restores admission, subject to ordinary +worker readiness. + +`GET /admin/lifecycle` reports `draining`, `requests_in_flight`, +`generation_jobs`, `worker` and `drained`. Request tracking starts before body +parsing and lasts until the response body is consumed or dropped. Generation +tracking includes queue waits, queued commands, execution and worker protocol +cleanup. Client disconnect does not declare a generation drained while STOP +is still being processed. Frames and trailers pass through unchanged. + +`drained: true` requires drain mode, zero tracked requests and commands, no +active generation, and a ready or unconfigured worker. Startup, restart, +stopping or failed worker states report false. A stalled client or worker can +hold drain indefinitely; the existing STOP timeout and finite restart policy +still apply. No deadline triggers a forced stop. Investigate a stuck drain or +explicitly choose to stop, accepting interruption, using the service manager. + +Optional signal grace: set top-level `shutdown_grace_s` in the native JSON config +or `STRATA_SHUTDOWN_GRACE_S` in its environment (integer 0–20 seconds, default 0). +`strata-next check-config` reports the effective setting. A positive value lets +admitted requests finish after SIGTERM/SIGINT, until the grace expires. During +that interval lifecycle reports `shutting_down: true`, readiness is false, new +inference is rejected, and resume cannot reopen admission. Worker shutdown +starts when admitted HTTP/worker activity clears or the grace expires. + +The rendered unit's 45-second stop budget still applies. Grace is only the +initial drain phase; worker and HTTP cleanup follow it. Use the explicit drain +procedure above for longer maintenance windows. Existing deployments keep +immediate interruption until this setting and a supporting binary are installed. + +Serialize maintenance operations: another operator can resume admission after +a status snapshot. The state is not a deployment lock or evidence that a client +received/processed all bytes. It resets to accepting after a control-plane +restart. CPU protocol tests cover the controls; managed GPU maintenance and +long-running user workloads require separate qualification. + +## Optional embedded engine preview + +A private build can carry a pinned Linux engine executable inside `strata-next`: + +```sh +export STRATA_EMBED_ENGINE_PATH=/absolute/path/to/verified/strata +export STRATA_EMBED_ENGINE_SHA256=THE_64_HEX_DIGIT_ENGINE_SHA256 +export STRATA_EMBED_ENGINE_REVISION=THE_FULL_40_HEX_DIGIT_SOURCE_COMMIT +cargo build --manifest-path control-plane/Cargo.toml --locked --release \ + --target x86_64-unknown-linux-musl +``` + +Use an actual engine digest and its declared source revision. The build requires +all three variables together, verifies the digest, limits the payload to 1 GiB with a 64 KiB copy/hash buffer +and checks an ELF64 little-endian executable header matching the target CPU. +This is not a complete ELF dependency audit or proof that the declared revision +produced that binary; retain the build/provenance record alongside the digest. +Normal builds without these variables remain control-plane-only builds. The +copy/hash stage uses a fixed buffer; Rust compilation/linking still process the +full payload and require memory and disk space proportional to its size. + +`strata-next engine-info` reports payload identity without executing it. +`strata-next engine-help` materializes the embedded worker and runs its `--help` +with no GPU visible; this checks loading and help output, not model readiness. +`strata-next --engine-license` prints the imported Strata MIT license. The +upstream record in `docs/upstream.md` remains authoritative and unchanged. +Select the embedded worker explicitly in the usual configuration: + +```json +{ + "bind": "127.0.0.1:18082", + "model": "your-model-id", + "engine": { + "executable": "@embedded", + "args": ["--pack", "/absolute/path/to/pack"], + "tokenizer_dir": "/absolute/path/to/tokenizer" + } +} +``` + +Keep the actual engine arguments from the qualified model profile. An external +executable path continues to work even in a payload build. Missing payload or +unsupported platforms fail before the HTTP listener opens when `@embedded` is +selected. The Linux supervisor copies the embedded bytes into an anonymous +executable `memfd`, seals content and size changes, and retains its descriptor +through worker restarts. The descriptor is released after worker shutdown; +there is no persistent extraction directory. This consumes RAM proportional to +engine size in addition to the executable's mapped pages. `/proc` access and +an OS policy allowing executable memfds are required; the runtime does not +change kernel policy. See the [Linux memfd documentation](https://man7.org/linux/man-pages/man2/memfd_create.2.html) +and [executable memfd policy](https://docs.kernel.org/userspace-api/mfd_noexec.html). + +**One packaged executable does not yet mean a fully static GPU runtime.** The +current qualified engine still needs host `libcudart.so.13`, `libcublas.so.13`, +C++/C runtime libraries and the NVIDIA driver. These are not embedded, and the +engine's existing library search paths remain unchanged. Model/tokenizer assets +also remain external. Do not deploy this preview to a clean host assuming a +driver alone suffices, or replace a running user trial to test packaging. +The synthetic CPU packaging check exercises supervisor behavior without GPU +qualification. A production single-file package still needs library/linking, +clean-node, real-model and license/distribution gates. + +## Validate configuration before switching a service + +```sh +strata-next check-config --config /absolute/path/to/native.json +``` + +This native command reads the same configuration, environment overrides, key file +and tokenizer assets as `serve`. It checks that an external engine resolves to +an accessible executable file (including `PATH` lookup), or that the selected +embedded engine is present in a Linux build. Bare executable names require `PATH`; +an explicit executable path avoids lookup ambiguity. Run it with the same user, +working directory and environment as the intended service. + +The existing laptop controller can run this check over SSH after installing its +updated helper: + +```sh +python3 scripts/install-qwen-native-service.py +qwen-codex-ctl native-service check-config --host rnr5090 \ + --binary /absolute/path/to/candidate/strata-next \ + --config /absolute/path/to/native.json \ + --working-dir /absolute/path/to/engine-workdir +``` + +All three paths refer to the remote host. This uses the SSH login environment; +it does not source a systemd environment file, upload files, install a unit or +change the selected connection. The candidate must already support `check-config`. +The client filters the returned JSON and suppresses raw remote errors. SSH stdout +is capped at 64 KiB with a 30-second local deadline; on failure the local SSH +process is terminated, which is not a guarantee that a remote process has exited. +Only invoke an explicitly chosen, trusted candidate executable. + +Success prints JSON with `configuration_valid`, `engine`, `tokenizer_validated`, +`authentication_enabled` and `inference_configured`. The last field means both +engine and tokenizer are configured. A control-plane-only config can also pass. +Keys, engine arguments and raw file contents are not printed; failures identify +the config/key, executable or tokenizer stage and return nonzero. + +The check does not execute the worker, extract the embedded payload, bind the +configured port, contact a running server or inspect model weights. Files and +permissions may change after it runs. `readiness_checked` is always false: +shared libraries, driver compatibility, model loading, available ports and real +generation still require deployment qualification. An already occupied port is +allowed so the candidate can be checked while the current service keeps running. + +## Linux engine with static CUDA toolkit libraries + +`STRATA_CUDA_STATIC=ON` is an optional Linux/GNU C++ build profile. It selects +CMake's static CUDA runtime and cuBLAS targets and statically links the engine's +GNU C++ runtime. The default CUDA profile continues to use shared toolkit +libraries. HIP and non-Linux/GNU configurations reject this option. + +On a Linux builder with the toolkit and CMake already installed: + +```sh +export CUDACXX=/absolute/path/to/cuda/bin/nvcc +export CUDAToolkit_ROOT=/absolute/path/to/cuda +# Optional existing pinned llama.cpp checkout; otherwise CMake fetches its pinned source: +export STRATA_GGML_DIR=/absolute/path/to/llama.cpp +BUILD_JOBS=2 scripts/build-static-cuda.sh +``` + +The script builds only `strata`, using SM 120 and portable AVX2 GGML defaults; +`CUDA_ARCHITECTURES` and `STRATA_BUILD_DIR` can override the build target/path. +It audits ELF dependencies and runs only `--help` with no GPU visible. It does +not install anything, serve a model, change a service, or run a speed test. +CMake's imported targets provide the static dependency closure; see the +[FindCUDAToolkit reference](https://cmake.org/cmake/help/latest/module/FindCUDAToolkit.html). + +The measured CUDA 13.2 build has only `libm.so.6`, `libc.so.6` and the host loader +in DT_NEEDED, with no RPATH/RUNPATH. It is **593,942,184 bytes**. This host's GNU +build requires **glibc 2.43**; build against an older supported glibc baseline +before targeting older distributions. The audit reports this symbol-version +minimum. NVIDIA's installed driver remains required. ELF direct dependencies +do not establish whether runtime-selected CUDA paths use additional `dlopen` +components; real-model and clean-host qualification are still necessary. + +This private candidate has not replaced the user's running engine. The bounded +large-payload path can now include it in one executable under the 1 GiB cap. +The combined static-CUDA preview is **611,277,088 bytes**. On Linux it passed +embedded identity verification and `engine-help` with `LD_LIBRARY_PATH` unset +and no GPU visible. The outer musl executable has no ELF interpreter or +DT_NEEDED entries; the embedded engine retains the glibc/driver requirements +above. The earlier 63 MB combined preview remains a separate fallback containing +the dynamic engine. See the [packaging report](../docs/experiments/2026-10-04-large-embedded-package.md). +No quality, numerical parity, speedup or production-ready claim follows from +linking successfully. Keep the default profile until the model gates pass. + +The optional `static_cuda_package` workflow-dispatch job performs the build and +ELF audit on the private CUDA runner without inference. It publishes no package +and cleans its private build directory. The runner must have the required +compiler/toolkit in its environment; hosted execution has not yet occurred. + +## Fetch pinned assets as part of native startup + +`serve --config /absolute/runtime.json` can now acquire prebuilt model-pack and +Qwen tokenizer files before it opens its HTTP listener or starts the worker. +Declare an optional `assets` array alongside the existing engine configuration: + +```json +{ + "assets": [ + { + "manifest": "/home/user/strata/pack-v1.manifest.json", + "directory": "/home/user/strata/assets/pack-v1" + }, + { + "manifest": "/home/user/strata/tokenizer-v1.manifest.json", + "directory": "/home/user/strata/assets/tokenizer-v1" + } + ], + "engine": { + "executable": "@embedded", + "args": ["--pack", "/home/user/strata/assets/pack-v1"], + "tokenizer_dir": "/home/user/strata/assets/tokenizer-v1" + } +} +``` + +Each local manifest uses the same schema as `model fetch`: `schema_version: 1` +and a nonempty `files` array with `name`, HTTPS `url`, positive `size` and +`sha256` for each file. Names are flat, unique filenames. Use manifests for +artifacts already prepared for the chosen worker; fetching GGUF shards alone +is not a Strata pack conversion. Models and private manifests stay outside Git. +The example requires a Linux executable built with an embedded engine. + +To acquire/verify the assets separately without starting the service: + +```sh +strata-next provision --config /absolute/runtime.json +``` + +Paths must be absolute, without `..`; bundle destinations cannot overlap. +All manifests are parsed before acquisition. Each bundle is downloaded into a +private sibling `.NAME.strata-stage`, verified in full, and then published by +a directory rename. Existing bundles are verified even when offline; a digest +mismatch fails without overwriting them. Use a new versioned destination for +upgrades, and retain the previous config/destination for rollback. No global +current-model pointer or running service is changed by provisioning. + +A per-destination `.NAME.strata-lock` coordinates native preparers. A competing +preparer fails promptly; process death releases the OS lock. The small lock +file remains to avoid an inode race. Failed/interrupted stages remain for +resume; after stopping all preparers they may be removed to discard incomplete +downloads. Extra files from a different manifest fail verification. Atomicity +is per bundle: if a later bundle fails, earlier verified bundles remain, but +`serve` never launches the worker. Use user-owned local storage for locks and +staging. This is not a defense against another process with the same user's +write access altering files after verification. + +`check-config` stays read-only and reports the bundle count and +`assets_verified: false`; it does not download or hash model files. It still +requires configured tokenizer assets to exist. Run `provision` first when +using that preflight on a fresh installation. + +This implements acquisition of prepared assets, not automatic GGUF-to-pack +conversion or full KAR model preparation. The complete-package Linux/GPU +clean-node acceptance gate remains separate. The CPU smoke uses synthetic +pack bytes and tokenizer files; it proves publication and startup ordering, +not model inference or performance. + +## Prepare a native serving pack from GGUF + +The native CLI can now build a Qwen `qwen4exp` serving pack from locally present, +manifest-pinned GGUF shards: + +```sh +strata-next model prepare-native-pack /absolute/shards.json \ + --source-dir /absolute/models --output /absolute/packs/model-v1 +``` + +The command verifies source sizes and SHA-256, split shard identity/counts, +unique tensors, expert router counts and gate/up/down geometry. It emits +`dense.bin`, `index.txt`, `native_experts.txt`, `conversions.json`, +`source.json` and `tokenizer/` through a private staging directory, then renames +the completed directory into place. Existing output is refused; retain the +old version and configuration for rollback. Failed ordinary preparation +removes its own stage; after a killed process an unused +`.NAME.native-pack-PID.tmp` may be removed before retrying. No existing pack is +replaced and no worker is started. + +Use the result with the existing engine's `--native FIRST_SHARD.gguf` option +and `--pack` output directory, plus the pack's `tokenizer/` for native Responses. +The quantized expert weights, native dense projections and large PLE table +remain in the original GGUF shards: **retain those shards**. This command does +not create `experts.bin`, add KAR compression or reduce the model's quantization. +Source shard filenames must form the engine's usual split-file family. + +Preparation currently accepts matching float types, exact F32-to-BF16, +F16/BF16-to-F32 widening, and exact F32-to-F16 through the loader's index kind3. +It rejects conversions that would round weights; there is no `--compat-bf16` +option. Unsupported architectures, missing expert roles, incompatible shapes, +quantized projections requiring conversion, and non-finite converted values +fail without publishing a pack. `conversions.json` records the exact changes +and source tensor hashes; `source.json` records the verified shard identities. + +`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. 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. + +## Fetch, prepare and serve a native GGUF model + +An optional `native_model` section connects source acquisition and exact pack +preparation to `provision --config` and `serve --config`: + +```json +{ + "bind": "127.0.0.1:8081", + "model": "qwen-flash-native", + "gpu_requirement": "cuda-13.0-linux", + "engine_probe": true, + "native_model": { + "manifest": "/srv/strata/manifests/source-v1.json", + "source_dir": "/srv/strata/models/source-v1", + "output": "/srv/strata/models/pack-v1" + }, + "engine": { + "executable": "@embedded", + "args": ["--max-context", "262144"] + } +} +``` + +Use a binary that actually embeds the Linux engine, or an explicit engine path. +The existing engine still needs a compatible GPU/driver and appropriate memory +settings. This configuration does not select new hardware or compression policy. + +Startup obtains and verifies source shards, builds the exact native pack, then +adds `--pack OUTPUT --native FIRST_SHARD` and selects `OUTPUT/tokenizer` before +opening HTTP or launching the worker. Do not also supply those engine arguments +or a tokenizer override. `check-config` remains read-only and reports an absent +managed tokenizer as pending; it does not claim model integrity or readiness. + +The pack now includes `receipt.json`, with source identities and SHA-256/size for +all generated files. Offline reuse verifies both source shards and the complete +pack, rejecting damaged files, symlinks and unexpected entries. The receipt is an +integrity record in user-owned storage, not a publisher signature or protection +against a local actor who can replace both receipt and files. Earlier packs +without a receipt must be regenerated into a new versioned directory. + +Use distinct versioned source/output directories when changing models. A failed +new preparation leaves earlier versions intact; reverting to the earlier config +reuses that version after verification. This does not hot-switch an already +running service or automatically restart a previous service after a worker +startup failure. A per-output OS lock prevents concurrent managed preparation. +Source GGUF files remain required for native quantized weights and PLE lookup. + +Asset bundles, native packs and extracted tokenizers use an atomic no-replace +directory rename on Linux and macOS. Any destination created during preparation, +including an empty directory, is preserved and causes publication to fail. A +filesystem without the exclusive rename primitive returns an error; there is no +fallback that can replace a destination. Existing resumable asset stages and +temporary pack cleanup retain their respective behavior. + +MTP is a separate pack selected by the engine's `--mtp PATH` option. The native +preparer does not produce MTP, vision or calibration assets. Acquire any required +auxiliary pack with a separate pinned `assets` bundle and pass its explicit path; +keep its directory disjoint from managed sources/output. The baseline can run +without optional MTP. Full-model and clean-node GPU qualification remain open. + +For the current specialised engine, add +`"runtime_profile": "qwen4exp-flash-next"` inside `native_model`. After source +SHA verification and shard discovery, `provision`/`serve` check the first GGUF +shard **before pack preparation or output mutation**, including offline reuse. +The profile requires `qwen4exp` metadata with 48 blocks, hidden width 2560, +24 attention heads and 2 KV heads. Expert counts must be positive 32-bit signed +values and selected experts cannot exceed total experts; pruned counts remain +allowed with or without MTP. The engine uses an independent canonical draft +geometry for MTP, so its 512 experts need not match a pruned target. Missing, mistyped or incompatible fields identify the failing key. +Unknown profile names fail config validation; `check-config` reports the selected +`native_runtime_profile` and `native_runtime_profile_checked: false` without +reading model files or downloading anything. + +Omitting the profile preserves generic exact preparation. The profile checks +metadata compatibility only: tensor layout/values, checkpoint pairing, memory +fit and actual GPU/model/MTP qualification remain separate checks. It does not +change generated bytes or enable compression. Rejected versioned sources remain +available for diagnosis, and existing prepared versions remain unchanged. + +For the current Qwen3.8 Flash Next **Q2 MTP runtime layout**, set `mtp_pack` to +exactly one directory listed in `assets`: + +```json +{ + "assets": [{"manifest": "/models/mtp-assets.json", "directory": "/models/mtp-v1"}], + "mtp_pack": "/models/mtp-v1" +} +``` + +Merge these fields into an engine configuration. The pinned bundle must contain +`dense.txt`, `dense.bin`, and `experts.bin`. Existing bundle SHA/size verification +runs first. Then a bounded native structural check runs before `native_model` +source acquisition or preparation, listener creation and worker startup. The +control plane appends `--mtp /models/mtp-v1`; remove any manual `--mtp` or +`--mtp=...` from engine arguments when using this option. Existing configurations +without `mtp_pack` retain their behavior. + +The check validates an ASCII index of at most 64 KiB / 128 tensors, required +current-engine tensor names/dtypes and exact rows/columns, exact dtype byte counts, +256-byte alignment, non-overlapping in-file ranges and exact dense file extent. +The Q2 expert blob must have exactly 707788800 bytes (512 × 1382400). Files must +be readable regular files, not symlinks; read-only host volumes can use another +owner UID, as with existing pinned assets. Keep paths immutable during serving. +`check-config` reports `pinned_structural_check_pending` without fetching or +reading the pack; `provision` reports `mtp_pack_structurally_validated: true` +only after verification. Missing or malformed packs fail before fetching the +base model, preserving existing versioned directories. + +Required tensor geometry is pinned to the current Flash Next MTP consumer +(2560 hidden width, four hyper-connection streams, 24 query heads of width 256, +two KV heads, 640 expert width). The optional three indexer tensors must also +match their pinned geometry when present. Dimensions are checked independently +of byte count: a rectangular matrix with swapped dimensions is rejected even +when its byte length and offsets remain consistent. Sparse CPU fixtures take +their shapes from the upstream checkpoint manifest and compare against this +preflight; a transposed Q projection is rejected before base acquisition. + +This is a structural and MTP geometry check, **not proof of compatible base-model geometry, weight values, +source-model pairing, Gemma norm conversion, quality, VRAM capacity or GPU +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/strata-next` (synthetic sparse layout). + + +`scripts/smoke-native-bootstrap.py` verifies real HTTP acquisition, exact pack +preparation and offline reuse with a synthetic worker, including corruption, +locking, conflicting config and previous-version preservation. It is a CPU +startup-order test, not an inference or model-quality result. + +### Explicit GPU profile requirement + +Set top-level `"gpu_requirement": "cuda-13.0-linux"` on CUDA 13.0 Linux +profiles. `provision` and `serve` check the host before fetching assets, +preparing a model, materializing an embedded engine, starting a worker, or +opening the HTTP listener. Unsupported OS, missing/unreadable driver, and a +version below this profile's conservative **580.65.06** floor fail with an +actionable error. The floor follows the Linux CUDA 13.0 GA toolkit driver in +[NVIDIA's release table](https://docs.nvidia.com/cuda/archive/13.0.0/cuda-toolkit-release-notes/index.html). +This is an explicit deployment policy, not a universal CUDA compatibility limit. + +The check reads the kernel driver version, falling back to `nvidia-smi` when +unavailable. That subprocess has a five-second timeout and 8 KiB output limit; +it is killed and reaped on failure. Versions are compared numerically. No CUDA +context or inference request is created. `check-config` only reports the +requirement with `gpu_requirement_checked: false`; it never runs this probe. +Omitting the requirement preserves CPU/manual worker behavior. A requirement +without a worker, or an unknown requirement, is rejected. + +A successful check does **not** qualify GPU architecture, free VRAM, model +quality, engine shared-library dependencies, MTP support, or a clean-node +real-model launch. Those remain separate release gates. Keep model/auxiliary +bundles pinned and use distinct versioned output directories as described above. + +### Optional declared VRAM budget + +For a previously sized single-GPU profile, add top-level +`"cuda_memory": {"required_mib": 24000, "reserve_mib": 1024}` together with +`"gpu_requirement": "cuda-13.0-linux"`. These example numbers are placeholders; +use a budget qualified for the model, context, KV and optional MTP configuration. +The control plane queries GPU UUID, total/free MiB and MIG mode through a bounded +5-second, 8-KiB `nvidia-smi` call before model acquisition. It selects the eligible +GPU with the most free memory covering the declared budget plus reserve; UUID +breaks ties deterministically. MIG-enabled physical GPUs are excluded. + +The worker receives only the selected full UUID in `CUDA_VISIBLE_DEVICES`; the +parent environment is unchanged. Existing visibility is respected: use an unset +variable or a comma-separated list of full GPU UUIDs; empty means no GPU. +Ordinal, abbreviated and MIG identifiers fail explicitly instead of being +reinterpreted. See NVIDIA's [UUID visibility contract](https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/environment-variables.html) +and [inventory query documentation](https://docs.nvidia.com/deploy/nvidia-smi/index.html). +Inventory is limited to devices exposed by the host/container runtime. + +The same selected GPU is checked again before each worker spawn (including +restarts). If capacity is lost or the device disappears, the worker fails before +spawn and readiness stays false. It does not silently migrate to another device. +`check-config` only validates and reports `cuda_memory_checked: false`. +Omitting this policy preserves the manual/CPU launch behavior. + +This is point-in-time admission against a **declared** budget, not automatic model +memory sizing, an allocation reservation, CUDA kernel compatibility or an OOM +guarantee. Other processes can consume memory after the check. Query time is +bounded separately from the worker's READY timeout. No context, cache, sampling +or quantization setting is changed. Isolated CPU tests verify selection, child +environment, failed recheck, restart and timeout; actual GPU/model qualification +remains a separate gate. + +### Early engine loader probe + +Set top-level `"engine_probe": true` to run the selected engine's `--help` +before model/auxiliary downloads and preparation. It works with an explicit +external executable or `@embedded`. `provision` can perform this check without +starting a serving worker; `serve` performs it before opening its listener. +Missing executables, wrong executable format, a missing loader/eager shared +library, nonzero exit, or a ten-second timeout fail before acquisition. The +timeout kills and reaps the direct child. Existing profiles default to no probe. + +The probe passes **only** `--help`, with `CUDA_VISIBLE_DEVICES` empty and stdin, +stdout and stderr discarded. Configured model arguments are not passed. It +executes an operator-trusted binary: only enable it for an engine whose help is +side-effect-free. The pinned Strata entry point exits from help before model or +CUDA initialization. This is not a sandbox for arbitrary executables. + +`check-config` never executes help; it reports `engine_probe_configured` and +`engine_probe_checked: false`. A successful help exit checks only that loader +path, not lazy-loaded libraries, CUDA kernels, VRAM, MTP or real-model quality. +A loader failure reports the stage and exit status without echoing child output; +use the engine's explicit `--help` (`strata-next engine-help` for embedded payloads) +for detailed local loader diagnostics. Full clean-node inference remains a +separate qualification step. + +### Assemble a complete private Linux package + +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: + +```sh +scripts/build-static-cuda.sh +engine="$PWD/artifacts/build-static-cuda/strata" +python3 scripts/build-linux-package.py \ + --engine "$engine" --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" \ + --revision "$(git rev-parse HEAD)" \ + --cargo-target-dir "$PWD/artifacts/combined-build" \ + --output "$PWD/artifacts/combined-v1" +``` + +Commit source changes before packaging. The revision must match the clean +checkout; the engine digest must match the exact frozen bytes embedded by the +existing Rust build. Use a dedicated Cargo directory without concurrent external +Cargo commands. The builder serializes its own calls and never replaces an +existing output directory. Failed assembly removes its private stage and leaves +older packages intact. Linux `renameat2(RENAME_NOREPLACE)` atomically publishes the +new directory; unsupported hosts fail instead of using an overwrite fallback. + +The result contains the combined executable, `PROVENANCE.json`, and `SHA256SUMS`. +It verifies static outer ELF, embedded identity and bounded GPU-hidden engine +help before publication. The provenance records the inner engine's direct +shared-library and minimum glibc requirements. The engine source revision is +operator/CI-declared provenance, not a binary-to-source attestation, and this +pipeline does not promise bit-identical compiler output. Python is used only on +the build host; the resulting runtime does not require it. + +The manual `static_cuda_package` workflow builds the engine then assembles and +uploads the combined preview to the **private repository**, with seven-day +artifact retention. It cleans owned build directories after the upload attempt; the final package +copy is removed only after a successful upload. A failed upload leaves that +private final package available for recovery. +The normal hosted job uses `--cpu-fixture` to exercise the same assembly path and +then tests exact serving output/restart against the external fixture. CPU +artifacts are explicitly marked and are not CUDA releases. No model weights, +requests or credentials enter either package. + +A successful package build does not pass the clean-node real-model gate: the +inner engine still requires the recorded host glibc and NVIDIA driver, and lazy +CUDA dependencies, kernels, model/MTP compatibility and quality need separate +qualification. Existing active endpoints are not modified by this build tool. + +## Combined runtime OCI preview (STRA-67) + +Build a private image from a trusted STRA-65 combined package (exactly the +executable, `PROVENANCE.json`, and `SHA256SUMS`): + +```sh +python3 scripts/build-runtime-image.py --package /private/package \ + --receipt-sha256 > /private/image.json +``` + +The builder freezes and verifies the three files before Docker receives a minimal +context. An official Ubuntu 26.04 **linux/amd64 manifest digest** is the default +base; its actual `getconf GNU_LIBC_VERSION` reports 2.43 in the isolated validation. +`--base repository@sha256:DIGEST` permits another explicitly pinned glibc image. +A base below the engine's recorded minimum glibc is rejected before image build. +Embedded identity and GPU-hidden `engine-help` are checked inside the resulting +non-root, read-only image. The image ID is returned only after these checks; +failed probes remove the uniquely labelled build image. No public registry push +occurs. Python and Docker are build tools, not serving dependencies. + +Run the image ID with NVIDIA Container Toolkit and a compatible installed host +driver. The caller supplies private configuration, source/model data, and a +writable state directory owned by UID 65532. Example paths inside the configuration +must match these mount destinations: + +```sh +docker run --rm --gpus all --read-only --cap-drop ALL \ + --security-opt no-new-privileges --tmpfs /tmp:rw,nosuid,nodev,size=256m \ + -e NVIDIA_VISIBLE_DEVICES=all -p 127.0.0.1:8081:8081 \ + --mount type=bind,src=/private/config,dst=/config,readonly \ + --mount type=bind,src=/private/models,dst=/models,readonly \ + --mount type=bind,src=/private/state,dst=/state \ + sha256:IMAGE_ID serve --config /config/runtime.json +``` + +The runtime uses its native `@embedded` engine and existing asset/native-model +configuration. Set the profile's explicit GPU requirement and `engine_probe`; +keep the key file private and readable by the container UID. Network access is +needed for configured acquisition; use verified offline assets to avoid it. +Do not mount the Docker socket or include models, keys, logs or configuration in +the build context. The default image exposes no GPU unless requested explicitly. + +The hosted CPU path uses `--cpu-fixture` and verifies actual Responses output `A`, +worker crash/restart and graceful shutdown in the image, with zero tolerance. +The manual private CUDA job now saves the image and provenance alongside the +combined package. Neither CPU success nor hidden-GPU help qualifies CUDA kernels, +lazy driver dependencies, real model/MTP compatibility, quality or clean-node GPU +serving. That full gate remains pending; the active user trial is not migrated. + +Switch preparation uses `provision --config FILE --defer-memory-check`: it verifies +assets and the declared driver requirement while the previous runtime occupies +VRAM. Its JSON explicitly reports `memory_admission: deferred_until_serve`. +This command never starts a worker. Ordinary `provision` and every `serve` still +perform the full declared memory admission; a target rejected at startup triggers +the switch rollback procedure. + +### Select a native profile without knowing the current one + +Omit `--from` to select the target from the same installed native catalog: + +```sh +strata-next service-switch --catalog /home/operator/strata/catalog.json \ + --to next --state-dir /home/operator/strata/switch-state +``` + +Under the shared transaction lock, the command checks every catalog unit. With +none running it prepares and starts the target; with the target already running +it verifies readiness and reuses the same process; with one other running it +uses the existing drain/switch/rollback path. Multiple active, failed, +transitional or unknown units cause an error before lifecycle changes. Every +catalog entry must be installed, have distinct unit/config paths and share the +same loopback origin. External service administration must remain serialized. + +A failed cold start stops only the verified target and records `cold_failed`, +allowing a later explicit selection. An interrupted or unconfirmed operation +still requires reconciliation. This does not discover unmanaged runtimes or +import other inference backends. + +### Install and wait for model readiness in one command + +```sh +strata-next service-install --config /home/operator/strata/runtime.json \ + --working-dir /home/operator/strata --unit strata-next-main.service \ + --start-ready --ready-url http://127.0.0.1:8080 --ready-model MODEL_ID \ + --ready-key-file /home/operator/strata/api.key --ready-timeout-s 600 +``` + +`--start-ready` verifies credentials before publishing the unit, installs or +reuses the exact unit, and waits for authenticated model readiness tied to its +systemd PID. Repeating it reuses a running service without restarting it. +`--enable` remains independently opt-in. The existing `--start` checks only the +manager operation; it cannot be combined with `--start-ready`. + +A readiness timeout or identity error returns failure and retains the unit and +service for explicit inspection through `service-control status`. It does not +silently stop, restart or replay the action. Readiness options require +`--start-ready`. Actual model loading still uses the configured serving pipeline; +this CLI option does not qualify a GPU/model combination by itself. + +### Reconcile an interrupted profile selection + +After inspecting `service-control status` for the catalog units, acknowledge the +exact private transaction record and verify the current state without replaying +any lifecycle command: + +```sh +sha256sum /home/operator/strata/switch-state/transaction.json +strata-next service-switch reconcile --catalog /home/operator/strata/catalog.json \ + --state-dir /home/operator/strata/switch-state --expected-journal-sha SHA256_FROM_ABOVE +``` + +Reconciliation requires the original catalog and recorded config digests, a +known interrupted phase, and either all units inactive or exactly one ready +native process. It rejects ambiguous, failed or transitional states. The result +records the prior journal digest/phase and current profile/PID; it does not +start, stop, drain, resume or prepare a model. A later explicit selection can +then proceed. Wrong acknowledgments or changed configurations leave the journal +unchanged. Keep external administration serialized with these operations. diff --git a/deploy/cuda-toolkit.lock.json b/deploy/cuda-toolkit.lock.json new file mode 100644 index 00000000..1fad2cc8 --- /dev/null +++ b/deploy/cuda-toolkit.lock.json @@ -0,0 +1,63 @@ +{ + "release": "13.0.1", + "manifest_url": "https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json", + "manifest_sha256": "9c494bc13b34e8fbcad083a6486d185b0906068b821722502edf9d0e3bd14096", + "components": [ + { + "component": "cuda_nvcc", + "version": "13.0.88", + "relative_path": "cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-13.0.88-archive.tar.xz", + "sha256": "48e35be3cfbf4b4fbc16828eaec8a7048ee789403049dc409f7b643d6259cf7a", + "md5": "e3e925c644055b9306aec9c9b84d1975", + "size": "26657716" + }, + { + "component": "cuda_crt", + "version": "13.0.88", + "relative_path": "cuda_crt/linux-x86_64/cuda_crt-linux-x86_64-13.0.88-archive.tar.xz", + "sha256": "5a3279a049ffc1cdb951c44cb95206acfdde9e9ae5e87825fc18d7e4a6878bb0", + "md5": "f90b38d702a29668d97e8f94a399ea31", + "size": "79800" + }, + { + "component": "cuda_cudart", + "version": "13.0.88", + "relative_path": "cuda_cudart/linux-x86_64/cuda_cudart-linux-x86_64-13.0.88-archive.tar.xz", + "sha256": "bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658", + "md5": "4ec0cce22fdbeeacb4bb406a800e27bc", + "size": "1491604" + }, + { + "component": "cuda_cccl", + "version": "13.0.85", + "relative_path": "cuda_cccl/linux-x86_64/cuda_cccl-linux-x86_64-13.0.85-archive.tar.xz", + "sha256": "ed845eae8c1767706b6ee91e40c608a03f6f633551a849b63f7346d32d73ee60", + "md5": "c0dd26e0c41dc35bd73435a4799c7508", + "size": "991284" + }, + { + "component": "cuda_culibos", + "version": "13.0.85", + "relative_path": "cuda_culibos/linux-x86_64/cuda_culibos-linux-x86_64-13.0.85-archive.tar.xz", + "sha256": "98fca11f9ab89be61385a67eee686c1ebf76fad9c7269d0cf9090edfcdb8a8ac", + "md5": "4b61b30864c47e1292f6d132653140d1", + "size": "21412" + }, + { + "component": "libnvvm", + "version": "13.0.88", + "relative_path": "libnvvm/linux-x86_64/libnvvm-linux-x86_64-13.0.88-archive.tar.xz", + "sha256": "17ef1665b63670887eeba7d908da5669fa8c66bb73b5b4c1367f49929c086353", + "md5": "816927093ffbdc10fddd751f045396b1", + "size": "43645408" + }, + { + "component": "libcublas", + "version": "13.0.2.14", + "relative_path": "libcublas/linux-x86_64/libcublas-linux-x86_64-13.0.2.14-archive.tar.xz", + "sha256": "158c1d7e862282d5218ed82f173ba14679c0f8afa1fe8cb4a3a34a4c0a9a5ff9", + "md5": "f17607125167fbb269fdb40b6991b543", + "size": "800056524" + } + ] +} diff --git a/desktop-core/Cargo.lock b/desktop-core/Cargo.lock new file mode 100644 index 00000000..561d4de7 --- /dev/null +++ b/desktop-core/Cargo.lock @@ -0,0 +1,1830 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042" +dependencies = [ + "heck", + "itertools", + "log", + "multimap", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "pulldown-cmark", + "pulldown-cmark-to-cmark", + "regex", + "syn 2.0.119", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-types" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a" +dependencies = [ + "prost", +] + +[[package]] +name = "protoc-bin-vendored" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" + +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + +[[package]] +name = "pulldown-cmark-to-cmark" +version = "22.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84bbb29c624230c4bd1047bbdb2aa47e41c860e9665ce62ba9504eebe91bf867" +dependencies = [ + "pulldown-cmark", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strata-desktop-core" +version = "0.1.0" +dependencies = [ + "async-stream", + "axum", + "futures-util", + "prost", + "protoc-bin-vendored", + "reqwest", + "serde", + "serde_json", + "sha2", + "subtle", + "sysinfo", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tonic-prost-build", + "tower", + "uuid", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "sysinfo" +version = "0.39.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tonic" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +dependencies = [ + "async-trait", + "axum", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2", + "sync_wrapper", + "tokio", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tonic-prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +dependencies = [ + "bytes", + "prost", + "tonic", +] + +[[package]] +name = "tonic-prost-build" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "prost-types", + "quote", + "syn 2.0.119", + "tempfile", + "tonic-build", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "indexmap", + "pin-project-lite", + "slab", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/desktop-core/Cargo.toml b/desktop-core/Cargo.toml new file mode 100644 index 00000000..a7a24bd7 --- /dev/null +++ b/desktop-core/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "strata-desktop-core" +version = "0.1.0" +edition = "2024" +rust-version = "1.99" + +[[bin]] +name = "strata-desktop" +path = "src/main.rs" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sysinfo = { version = "0.39.6", default-features = false, features = ["system"] } +tokio = { version = "1", features = ["rt", "macros", "process", "io-util", "time", "sync", "net", "signal", "fs"] } +axum = "0.8" +reqwest = { version = "0.13.5", default-features = false, features = ["stream"] } +futures-util = "0.3" +subtle = "2.6.1" +tonic = "0.14.6" +tonic-prost = "0.14.6" +prost = "0.14" +tokio-stream = { version = "0.1", features = ["net", "sync"] } +async-stream = "0.3" +tower = { version = "0.5", features = ["util"] } +uuid = { version = "1", features = ["v4"] } + +sha2 = "0.11" + +[build-dependencies] +tonic-prost-build = "0.14.6" +protoc-bin-vendored = "3" diff --git a/desktop-core/GRPC.md b/desktop-core/GRPC.md new file mode 100644 index 00000000..a29c7e81 --- /dev/null +++ b/desktop-core/GRPC.md @@ -0,0 +1,286 @@ +# Shared node protocol (STRA-58/59) + +Requirements for the first executable slice, 2026-10-04: + +- `strata.node.v1.Node` is the same authenticated gRPC API for local loopback and + SSH-forwarded remote loopback. No public bind; no unauthenticated localhost. +- Handshake requires protocol version 1 and returns an agent epoch, state cursor + and advertised capabilities. Unsupported features are absent from capabilities. +- Hardware and memory planning use bounded JSON v1 payloads inside typed protobuf + envelopes, preserving the existing inventory/planner contract. +- Snapshot subscriptions are replaceable state, not an audit log. Every connection + gets a consistent full snapshot; subsequent snapshots carry epoch/sequence. + Slow observers coalesce state; clients replace state and do not replay inference. +- Responses RPC sends HTTP status/content type followed by byte-preserving body + chunks and an explicit end marker. A transport failure is never successful EOF. + The existing gateway owns model routing, admission and protocol validation. + Inference has no automatic retry. Dropping a stream uses the gateway's existing + cancellation/quarantine rule; it is not an engine cancellation acknowledgement. +- Bound request messages to 2 MiB plus envelope, output chunks to 64 KiB, subscriptions + to 16 and live Responses RPCs to 64. Hardware refresh is serialized and explicit; planning reuses a snapshot for at most five seconds. + No prompts, response bodies, tokens or credentials enter diagnostics/state events. +- Desktop C# and Rust clients are generated from one `.proto`. Standalone node + may outlive UI; the owned desktop preview child is inventory/planning only and + is shut down when that app exits. It cannot own active inference. +- Real HTTP/2 tests must reject wrong credentials/version/public bind; exercise + state reconnect, streaming tool bytes, resource release and concurrent control. + +Not yet acceptance-complete: persistent model install/start/stop jobs, durable +operation IDs, process restart reconciliation, automatic SSH provisioning, full +inference resume, and real-model cross-platform backend qualification. These +remain explicit STRA-58/59 and backend milestones, not advertised capabilities. + +The local `node-proxy` command exposes authenticated Responses HTTP/SSE to the +harness and forwards only through the shared gRPC channel to a configured node. +It preserves status/content-type/retry-after and body bytes; requires headers, +then data, then exactly one end marker and successful gRPC completion. An error +or truncated stream fails the HTTP body. No redirects, proxies or automatic +inference retry. Both bind and node destination must be literal loopback IPs. + +## Run (development) + +Build with `cargo build --locked --manifest-path desktop-core/Cargo.toml`. +Protobuf generation uses a build-only vendored protoc; deployed binaries do not +require protoc, Python or .NET. Use a fresh secret of at least 32 printable ASCII +bytes supplied through an environment variable from your credential store. + +```sh +strata-desktop node --listen 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN +# Explicitly attach only already managed, ready and exclusively assigned workers: +strata-desktop node --listen 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN --pool /absolute/private/pool.json +# Harness-facing endpoint on the app host; --node may be an SSH-forwarded port: +strata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN +``` + +The first two commands are alternatives. Pool schema is described in `POOL.md`; +node and its embedded gateway use the node credential. Backend credentials remain +separate per-deployment environment references. The node only prints its public +loopback endpoint descriptor, never the credential. Standalone nodes keep running +when UI disconnects. `--stdio-lifetime` is reserved for the desktop-owned +inventory-only child and cannot be combined with `--pool`. + +`node-proxy` requires the node Responses capability; an inventory-only node +correctly fails that handshake. The initial proxy uses the node credential for +its local harness endpoint too. Per-client authorization is a future extension. +`active_responses` counts transport requests including queue waits, not GPU slots; +a disconnected stream may leave a backend quarantined until verified recovery. +Snapshot events cover these transport counters, not a durable job history. + +## Verification + +Real loopback HTTP/2 tests include auth/version/limits, independent control during +streaming, new epoch snapshots, byte-identical tool-call SSE, incomplete terminal +failure and quarantine, client disconnect, and HTTP→gRPC→HTTP adapter path. +C# headless app self-check runs the actual Rust executable and generated client. +No real model requests are sent by these tests. Durable lifecycle and remote install remain unqualified and unadvertised. +The transport reconnect implementation is described below. + +Verified on 2026-10-04, macOS Apple Silicon: all 33 Rust tests passed; strict +Clippy and RustSec audit passed. .NET locked restore/build and C# self-check +passed. Two separate C# app connections to one external test node completed; +app exit left that node alive. Wrong credentials were rejected. Test node was +removed afterward. NuGet reported no known vulnerable direct/transitive packages. +Hosted CI, Windows/Linux native execution and real-model transport are not yet +verified. Active user RTX5090 runtime was untouched. + +## Recovery requirements (STRA-59) + +Each node has an independent owned connection monitor. States: connecting, +ready, disconnected, auth_error, protocol_error. `ready` means a fresh node +connection, not proof of model readiness. New proxy admission requires a snapshot +heard within 15 seconds and the advertised Responses capability. A 5-second +heartbeat, with a 5-second RPC deadline, detects an idle broken connection. +Reconnect uses capped 200ms→10s exponential backoff with jitter. Invalid auth or +protocol/sequence state stops retries until configuration changes. State events +replace snapshots; epoch changes reset the cursor, same-epoch regressions fail. +Observer loss never releases backend slots or reissues an inference request. + +The proxy exposes authenticated `/node/status` with connection state and numeric +snapshot only. In-flight failures retain their explicit interruption behavior. +The desktop displays connection status separately from hardware/model status, +observes snapshot changes and reconnects independently of UI actions. Dropping +its observation cancels that monitor, not the external agent. Restarting the +owned inventory-only child is allowed; restarting external workers is not. + +Acceptance: same-port agent crash/restart recovers with a fresh epoch, offline +requests are rejected before inference dispatch, wrong credentials do not spin, +one failed node does not block another, monitor drop ends its tasks/subscription, +and existing streaming/tool integrity tests remain passing. + +Recovery implementation verified 2026-10-04: Rust `Connection` and the desktop +observer automatically reconnect with bounded backoff/jitter and heartbeat. +The proxy's authenticated `/node/status` reports freshness, epoch, sequence, +transport request count and capabilities, never request bodies. It refuses new +work when the node state is stale/disconnected. Inference calls are never +application-retried. Subscription snapshots replace state, not durable job logs. + +36 Rust tests passed, including actual child process kill/restart on the same +port, independent nodes, terminal auth errors, offline startup and releasing +20 successive observer subscriptions. C# recovered from an actual isolated node +restart; the repeatable CI fault test is `python desktop/tests/reconnect.py`. +Python is only a test orchestrator and is not part of serving or deployment. + +Remaining switch gates: managed model/process lifecycle, durable operation +reconciliation, verifying backend readiness after node restart (node connectivity +alone is insufficient), real-model harness test, platform qualification and +managed SSH tunnel recreation. An existing tunnel can recover and the gRPC +client reconnects, but this slice does not create/restart SSH processes. + +## Managed worker profile (STRA-58) + +Implemented CLI/gRPC slice: one trusted, operator-installed profile per node. It binds +an absolute executable and bounded argv to a model identifier and loopback HTTP +endpoint. gRPC exposes typed Start/Stop/Status with an operation UUID; no RPC can +supply executable, shell text or arbitrary arguments. Spawn a direct child with +restricted inherited environment, null logs, and no node credential inheritance. + +Admission starts CLOSED. Start refuses an occupied endpoint, launches only its +configured process, polls bounded `/health` and requires status=ok, loaded=true, +model=expected while the child remains alive before opening admission. Child exit +closes admission. Stop closes admission first, waits for admitted work to drain, +and kills/reaps only its owned child. Drain timeout leaves admission closed and +reports failure; no implicit force termination of active inference. + +An actor owns operations independently of RPC lifetime. Up to 256 operation IDs +are retained for this process epoch, matching duplicate returns prior status, +conflicting payload is rejected, and at capacity new IDs are refused (no unsafe +eviction). This is process-local idempotency; durable restart reconciliation is +not claimed. Agent restart starts closed and never adopts/kills an existing PID. +An orphan still holding the endpoint causes Start to fail explicitly. Profile +installation and orphan recovery remain separate provisioning/lifecycle gates. +Tests launch synthetic local fixture processes only, without real model requests. + + +The profile is a JSON file on the node, installed by its operator: +```json +{ + "schema_version": 1, + "id": "my-model", + "model": "backend-model-identifier", + "executable": "/absolute/path/to/worker", + "args": ["--serve", "--port", "18090"], + "endpoint": "127.0.0.1:18090", + "startup_timeout_ms": 120000, + "capabilities": ["responses"] +} +``` +The executable must remain in the foreground and expose HTTP Responses and +the health contract described above. Configure its real supported arguments; +the example is not a generic adapter for arbitrary engines. The profile ID is +the public gateway model ID; the model field is sent to the backend and checked +against health. Capabilities default to responses only; declare tools, reasoning, +structured_output, image/audio/file only after adapter verification. One slot is +reserved for the exclusive managed worker; the initial resource budget is a slot +sentinel, not an estimate of memory or automatic hardware admission. + +```sh +strata-desktop node --listen 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN --worker-profile PROFILE.json +strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN status +strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN start OPERATION_UUID +strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN operation OPERATION_UUID +strata-desktop worker --node 127.0.0.1:18766 --token-env STRATA_NODE_TOKEN stop ANOTHER_UUID +``` +Supply a private credential through the environment; start/stop return accepted, +not completed. Poll operation with the same UUID; never infer success from +acceptance. CLI stop uses a 30-second drain grace. A lost connection can query +the same ID in the same node epoch; unknown ID after node restart requires +explicit reconciliation, not automatic resubmission. Node capability is +worker.lifecycle.v1. Existing inventory-only UI children cannot own models; +managed nodes stay independent of UI lifetime. Profile installation remains pending; the desktop now exposes lifecycle buttons +for an explicitly configured persistent node. + +The child receives STRATA_WORKER_ENDPOINT and STRATA_WORKER_MODEL alongside a +restricted platform environment. Backend stdout/stderr are discarded. An owned +process exit is observed within the 200 ms polling interval; runtime liveness +beyond process exit is not yet supervised after startup. Starting a replacement +clears previous_response_id ownership, preventing affinity to a lost conversation. +No inference request is retried by lifecycle. + +Validation on macOS: real Rust fixture children, real gRPC and CLI subprocesses; +start/stop/auth/dedup/conflict, exact response bytes (zero tolerance), restart +affinity rejection, wrong model/occupied endpoint fail-closed, child crash and +explicit restart, drain timeout preserves active request. The ignored fixture +entry is invoked as a subprocess by the tests, not an omitted quality check. +These are synthetic protocol/process tests, not model quality or speed results. + +### Desktop lifecycle controls +A configured persistent node exposes model phase and explicit Start/Stop buttons. +The inventory-only app-owned node cannot launch models. UI submits one UUID once, +polls its outcome after reconnect, and never retries a mutation after uncertain +delivery. Expected node epoch fences mutations; a changed epoch or missing +operation requires explicit operator reconciliation. UI closure cancels only +client observation, never stops the external worker. No automatic Start on app +launch, no SSH provisioning or user runtime adoption in this slice. + + +The UI controller keeps one outstanding operation ID for the lifetime of that +window. Start/Stop are disabled when state is unavailable, the worker is +transitioning, or an operation remains unresolved. Each explicit command first +reads fresh worker state. Acknowledgement loss triggers status queries only; +the command is not resubmitted. Expected epoch is sent by both current CLI and +desktop; the node rejects mismatching nonempty epochs before enqueueing. +Empty epoch remains accepted for earlier v1 clients. This is additive protobuf +compatibility, not durable cross-restart idempotency. + +The UI polls managed status every second with bounded RPC deadlines, separately +from the connection observer. A changed node epoch or missing operation retains +the UUID and blocks new UI commands with a reconciliation message. Pending state +is currently in memory: closing/reopening the app reads authoritative worker state +but does not recover the previous UI operation journal. Auto-download/provision, +profile selection and durable reconciliation are still outstanding. + +Verification: `python desktop/tests/lifecycle.py` exercises the same desktop +controller and generated C# client against an actual isolated Rust node and +synthetic backend process. It injects lost acknowledgement after real commands, +confirms polling reaches completion with exactly one submit, closes/reconnects +the client without stopping the worker, checks exact synthetic Responses bytes, +and stops the owned worker. A deterministic replacement-epoch fixture verifies +that uncertain commands remain blocked. Rust gRPC tests additionally verify +rejection of a stale epoch with the worker still stopped. No active remote node +or user inference is involved. Python is only the offline test fixture/runner. + +### Durable node journal +Optional operator-supplied --journal PATH uses an exclusively locked private, +bounded append-only file and binds history to a SHA-256 fingerprint of the +installed profile (not stored command paths/arguments). Persist+sync accepted +before returning acknowledgement; persist running before side effects and final +outcome after execution. Reopening preserves terminal outcomes; accepted/running +operations become indeterminate, never replayed. Unresolved recovery or journal +I/O failure closes admission and blocks new commands for operator reconciliation. +No automatic PID adoption, no promise of exactly-once external effects after a +crash. Corrupt/torn records reject startup without truncating evidence. + + +Usage: append `--journal /absolute/private-directory/operations.jsonl` after +`--worker-profile PROFILE.json`. The parent directory must already exist. +Unix permissions are checked (directory 0700, regular single-link file 0600); +on Windows use an operator-owned directory with a private ACL. Windows ACL and +power-loss durability qualification are not yet complete. The node holds a +nonblocking exclusive OS file lock for its lifetime. The journal is limited to +4 MiB and 256 UUIDs; there is no automatic eviction/rotation. This limit is +intentional until archival/reconciliation can retain deduplication guarantees. + +The journal contains profile fingerprint, UUID, action, drain grace, expected +epoch, status and fixed reason codes. It stores no argv, paths, prompts, weights, +credentials or backend logs. SHA-256 uses the same sha2 0.11 line as the existing +control plane. The semantic duplicate check compares action and grace; transport +epoch may differ on an explicit same-ID retry. Epoch fencing still happens first, +and a stale epoch never executes a command. + +With a journal the node advertises `worker.journal.v1`. Desktop may look up an +outstanding command in a replacement epoch that advertises durable history. +Terminal outcomes reconcile without resubmission. Missing/indeterminate history +blocks new UI actions; node recovery uncertainty also rejects new mutations. +The persisted result is historical and does not assert a model is still running: +current worker state/admission is closed after restart. No old PID is adopted. +Operators must reconcile orphan processes and uncertain side effects; automated +recovery resolution and durable desktop-window journal remain pending. Do not +delete/rotate the journal to bypass an unresolved operation. + +Validation: five journal tests cover retained final outcomes, interrupted command +conversion/no replay, exclusive lock, profile fingerprint mismatch, torn/invalid +history, size bounds, failed append preserving evidence and blocked mutation. +The desktop lifecycle test also kills/restarts an actual isolated node, queries +the prior completed command, and retries that UUID to confirm history is returned. +Synthetic Responses remain byte-exact. Mac-only evidence; no real-model, Windows/ +Linux runtime, performance or sudden-power-loss claim. diff --git a/desktop-core/INSTALL.md b/desktop-core/INSTALL.md new file mode 100644 index 00000000..ed3b8645 --- /dev/null +++ b/desktop-core/INSTALL.md @@ -0,0 +1,62 @@ +# Private SSH installation (STRA-52) + +`remote-install CONFIG.json` transfers a trusted operator-pinned local Rust helper +and a worker profile into `$HOME/.strata-next/installations/SLOT` over authenticated +OpenSSH. The profile names a backend already installed on the target. No backend, +model, driver or service is implicitly downloaded or started. + +Config v1: `target` contains `ssh` (the existing SshProfile), `slot` (1–64 ASCII +letters/digits/hyphen/underscore), `os` (`linux`/`macos`), `arch` +(`x86_64`/`aarch64`); `runtime` and `worker_profile` are absolute local file paths; +`runtime_sha256` is a trusted lowercase SHA-256 pin. Runtime limit is 256 MiB, +profile limit 1 MiB. Runtime and profile together identify an immutable release. + +The fixed remote installer verifies OS/ISA, private owned directories, available +disk, lengths and both hashes before executing the helper's `validate-worker` +command. That command validates configuration without launching the worker. +Validation of model assets/driver compatibility remains a separate launch gate. +A slot lock serializes installation/activation. Staging and marker replacement +are on the destination filesystem; failed validation leaves `current` unchanged. +Repeated installation verifies the retained release again. Successful output +includes release/runtime/profile hashes for a subsequent explicit rollback. + +`remote-activate CONFIG.json` accepts the same `target` plus `runtime_sha256` and +`profile_sha256` from an earlier successful install. It revalidates that retained +release before atomically changing the regular `current` marker. Neither command +restarts an existing runtime. A lost acknowledgement has an unknown outcome; +repeating install/activate with the same hashes is idempotent. Releases are retained. + +SSH host keys must already be trusted. No password/key contents enter JSON, and +remote diagnostics never include profile contents or backend argv. No sudo or +Python is used by installation. SHA pins require a trusted source; they are not +a substitute for release signatures. Local Windows clients can use OpenSSH; +remote targets currently require Linux/macOS POSIX tools. Signed distribution, +remote Windows installation, model acquisition, persistent node bootstrap and +UI installation are not delivered by these commands. A killed remote installer +can leave a private lock/staging directory; it fails closed until inspected. +Atomic visibility does not claim power-loss durability on all filesystems. + +## CLI flow + +Start with `examples/remote-install.json`; replace the zero digest with the +trusted artifact SHA-256 and point to the local artifact/profile files. The JSON +profile's `executable` and model paths refer to the remote host. SSH aliases from +the user's existing SSH config are supported, as in `remote-inspect`. + +``` +strata-desktop remote-inspect SSH_PROFILE.json +strata-desktop remote-install INSTALL.json +strata-desktop remote-activate ACTIVATION.json +``` + +For activation, retain only `schema_version`, `target`, `runtime_sha256`, and +`profile_sha256` (the latter two from the install receipt). Activation can select +any previously installed matching bundle, including the previous version. +The selected helper/profile live under +`$HOME/.strata-next/installations/SLOT/releases/RELEASE/`. `current` contains +RELEASE. Installation receipts must be retained outside Git. + +The real SSH integration uses private fixture keys and a random test slot, tests +idempotence, profile change, rollback, wrong platform/digest/profile, truncated +uploads, locked slots, corrupt releases and unsafe markers; it asserts that the +backend was never started. No existing runtime, tunnel or SSH config is changed. diff --git a/desktop-core/POOL.md b/desktop-core/POOL.md new file mode 100644 index 00000000..3e82ff60 --- /dev/null +++ b/desktop-core/POOL.md @@ -0,0 +1,81 @@ +# Experimental pool gateway + +Implemented in STRA-56. One loopback Responses endpoint can queue requests and +forward them to several already running local workers or loopback SSH tunnels. +This does **not** install runtimes, create tunnels, load models or integrate a +pool editor into the desktop UI yet. Production serving is Rust, without Python. + +## Run + +Copy `examples/pool.json` to a private location and replace all model IDs, +endpoints, capabilities and memory budgets with verified values. The included +three endpoints and 1 GiB allocations are examples, not a tested model recipe. +Supply credentials through the named environment variables (minimum 16 bytes). +Use a separate gateway token; upstream credentials are never forwarded from a +client header. An upstream token reference may be null for a trusted unauthenticated +loopback worker. Never commit real configurations or credentials. + +```sh +cargo build --locked --manifest-path desktop-core/Cargo.toml +desktop-core/target/debug/strata-desktop gateway /absolute/private/pool.json +``` + +Configure the harness base URL as `http://127.0.0.1:18765/v1`, its bearer token as +the gateway token, and its model as a deployment ID or an explicitly configured +alias such as `coding-pool`. The gateway exposes authenticated `/v1/models`, +`/v1/responses` and `/pool/status`. Exact deployment IDs never substitute models. +An alias explicitly permits any of its members; choose equivalent models or +accept the heterogeneous selection policy intentionally. Backend model IDs are +sent upstream and retained in responses; `x-strata-deployment` identifies routing. + +## Admission and streams + +- Default example queue: 8 waiting requests; gateway maximum: 64. Request bodies + are limited to 2 MiB, buffered non-stream responses to 8 MiB, terminal SSE + inspection to 1 MiB per line/event. Streaming content is relayed unchanged. +- Requests wait on the same HTTP connection; this is not a durable 202 job API. + Align harness timeouts with queue plus inference time. Full queue returns 429 + with Retry-After; expired queue returns 504. Accepted work does not survive a + gateway restart. +- Oldest eligible request gets a free slot; unrelated blocked requests do not + block other workers. Per-worker and shared resource-group admission is atomic. + Group budgets are incremental memory AFTER resident weights and safety reserve; + request_bytes must upper-bound allocations for the worker's allowed context. + The backend must enforce those limits. Aliases to one GPU must share a group. +- Capability filters cover Responses, tools, reasoning, structured output, + image/audio/file input. These are explicit administrator declarations, not + automatic quality or compatibility validation. Native backend validation remains. +- A lease lasts through response completion, not merely HTTP headers. Waiting + cancellation removes the queue entry. Stream cancellation/timeout or missing + terminal event quarantines that deployment: cancellation alone cannot prove + the upstream worker stopped computing. Other deployments continue. +- Recovery is intentionally manual in this preview: verify the upstream worker + is idle and healthy before restarting the gateway. Automatic verified recovery + and upstream cancellation acknowledgement belong to managed lifecycle work. +- No inference request is retried. Per-request SSE bytes/tool-call arguments are + preserved. An interrupted stream ends as a transport error, never a fabricated + successful response. Never infer model quality from successful transport tests. +- previous_response_id routes to its known original worker. Ownership is bounded + to the latest 4096 response IDs in gateway memory; unknown/evicted IDs return + 409. Worker state must still exist. Durable ownership, conversation resources, + background mode and transparent migration are not supported. Input must contain + full history when starting a new independent session. + +## Security and deployment boundary + +Bind and upstream addresses must be literal loopback IPs. Remote links go through +an independently managed SSH tunnel. Redirects and ambient HTTP proxies are +disabled. Credentials come from environment references, raw payloads are not +logged. This version assumes configured workers are ready at startup and their +slots are exclusively managed by this gateway; attaching a busy shared worker is +not supported. Existing user test sessions must not be attached automatically. + +## Evidence + +`cargo test --locked --manifest-path desktop-core/Cargo.toml` exercises a real +loopback HTTP gateway with three synthetic workers: concurrent execution, +fourth-request queuing, routing/affinity, saturation/timeout, authentication, +capability rejection, fragmented SSE byte equality and disconnect isolation. +Pool tests additionally cover FIFO eligibility, shared memory budgets and 100 +dispatch/cancel races. These are functional tests, not real-model benchmarks. +The real local + two SSH harness run and desktop integration remain open. diff --git a/desktop-core/REMOTE.md b/desktop-core/REMOTE.md new file mode 100644 index 00000000..4735e2bd --- /dev/null +++ b/desktop-core/REMOTE.md @@ -0,0 +1,122 @@ +# SSH preflight + +`strata-desktop remote-inspect /absolute/private/ssh-profile.json` reads server +resources using system OpenSSH. Copy `examples/ssh-profile.json` and supply a host +or trusted SSH config alias. Null user/port/identity fields defer to OpenSSH's +configuration/agent. Identity paths must be absolute; keys are referenced, never +embedded. There is no password field. Keep real profiles outside Git. + +This command sends a fixed read-only POSIX shell script over SSH stdin. It reads +Linux OS/architecture, CPU/count/features, RAM, NVIDIA memory/driver and available +disk space on the SSH user's current/home filesystem. Recheck the actual model +destination filesystem during provisioning. Non-NVIDIA GPU/NPU and engine +capabilities remain unknown, not inferred from the client hardware. No Python, +model request, process restart, package installation or persistent agent occurs. + +Known-host verification is strict; establish and verify trust in the usual SSH +flow first. Agent forwarding, configured forwards and LocalCommand are disabled. +Batch mode avoids password prompts; the existing SSH configuration (including +ProxyJump/ProxyCommand when configured by the user) remains a trusted dependency. +The probe has a 15-second total deadline and 128 KiB stdout/stderr limits. +Unexpected banners, malformed data and unsupported remote OS/CPU return explicit +errors. Raw SSH stderr and key paths are not included in the returned inventory. + +Tests cover injected options/shell syntax, forbidden secret fields, memory and +unknown GPU parsing, output bounds, stdin EOF, timeout and host-key rejection. +On 2026-10-04 the command also read the authorized existing Linux RTX5090 host +successfully without changing its active serving session. This proves preflight, +not remote provisioning or persistent lifecycle. + +STRA-58 now provides a shared local/SSH gRPC node transport; see `GRPC.md`. +STRA-52 provisioning remains pending. gRPC reconnect and optional durable node +operation history are implemented; complete recovery/reconciliation is still pending. SSH remains bootstrap and secure transport. +The preflight command does not install or launch this node. + +## Managed SSH transport (STRA-53) + +The local Rust listener owns one OpenSSH stdio-forward process per accepted TCP +connection: `ssh -W 127.0.0.1:REMOTE_PORT`. It always binds loopback, clears +configured forwards, disables shared ControlMaster/ControlPersist, and sends no +remote shell command. Thus an existing user tunnel/runtime is never replaced. +The same gRPC client can reconnect through the surviving local listener and obtain +a fresh SSH process. SSH keepalives detect lost transport; the existing gRPC +heartbeat/backoff governs node readiness. A listening port alone is not readiness. + +Bound connection count and spawn rate, copy bytes with backpressure, cancel/reap +only owned SSH children on disconnect/shutdown. Fail an occupied local port +without changing its owner. CLI first: private JSON profile with SSH fields, +local listen address and remote node port. Output descriptor has no credential. +No runtime install or model start in this transport operation. All feature tests +use isolated endpoints; active rnr5090 serving/tunnel remain unchanged. + +### Usage and verified behavior + +Copy `examples/ssh-tunnel.json` to a private location and configure the SSH +destination and the **remote gRPC node port**, not the model's HTTP port: +```sh +strata-desktop ssh-tunnel /absolute/private/ssh-tunnel.json +``` +The foreground command prints a loopback endpoint descriptor. Leave it running +and set `STRATA_NODE_ENDPOINT` to that address for the desktop, with the node's +existing private `STRATA_NODE_TOKEN`. The existing `node-proxy --node ADDRESS` +can expose that remote node to the harness through the same authenticated HTTP +Responses interface. Ctrl+C closes only this listener and its SSH children; +the remote node/model remains running. If the configured local port is occupied, +startup fails without touching that listener. Port 0 allows OS-assigned ports. + +The configured maximum is 1–16 simultaneous TCP connections; starts are spaced +at least 250 ms apart. Each gRPC HTTP/2 connection multiplexes its RPC streams +over one SSH connection. SSH keepalives are 10 seconds with three missed replies; +gRPC liveness and reconnect/backoff remain separate. Remote destination is always +127.0.0.1. No remote shell command or background shared SSH master is created. +Counters distinguish accepted/active/completed/failed/rejected transport +connections; they are not model requests, readiness, or performance measurements. +SSH stderr is discarded; use the existing read-only preflight command to diagnose +trust/authentication failures rather than exposing remote logs in the UI. + +Validation on macOS: four Rust tests cover safe arguments, public-bind/occupied +port rejection, byte-exact 300,000-byte binary duplex transfer including client +half-close, repeated connection creation, concurrency rejection, failed child, +and shutdown cleanup. `python desktop/tests/ssh_tunnel.py` creates a real isolated +localhost sshd with temporary host/user keys and a dedicated known_hosts file; +no ~/.ssh or system service changes. Two real C# clients completed gRPC +handshake/hardware/plan/snapshot through the tunnel. The test then killed only an +SSH child whose parent matched its own tunnel process and observed the C# client +reconnect to the unchanged node epoch. Graceful tunnel shutdown left the remote +fixture node running. All fixture processes, keys and files were removed. + +This integration is in the macOS CI definition; hosted Actions are unrun. +Windows/Linux real SSH and suspend/resume qualification remain pending. +Model installation, persistent node bootstrap and saved connection profiles remain +next features. The desktop now provides a pre-session Local/SSH connection form. The active user's remote runtime/tunnel was not changed. + +Digest-pinned per-user installation and activation: [INSTALL.md](INSTALL.md). + +## Desktop connection chooser (STRA-53) + +Without an explicit `STRATA_NODE_ENDPOINT`, desktop startup offers this computer +or an existing SSH node. The form accepts SSH alias/host, optional user and key +file reference, SSH port, remote loopback node port, and a masked node credential. +The credential stays in memory; it is not included in CLI arguments, tunnel +configuration or temporary files. Saving to an OS credential vault is future work. + +The app sends a bounded single-line JSON config to +`ssh-tunnel --stdio-lifetime`, which owns an ephemeral loopback listener. Closing +its stdin closes/reaps that listener and its own SSH children. Desktop first +completes the authenticated gRPC handshake before opening the management window. +Failed authentication returns to the form for correction. No local/remote +rebinding is allowed after a management client exists, preserving lifecycle UUID +ownership. Close and reopen desktop to choose another node; closing does not +stop an external model. Existing explicit environment endpoints still work. + +The Local option currently starts an inventory/planning node, without an inference +backend. Remote requires an already started compatible node with a trusted SSH +host key. Neither the chooser nor a successful handshake claims model readiness. +The management window reports worker readiness separately. + +Real isolated localhost SSH integration exercises the same C# connection path: +wrong-token rejection, successful retry, hardware/plan/events, rejected active +rebind, owned tunnel cleanup while remote node survives, and selection of a new +local node after closing. Native macOS UI was checked for validation feedback +and transition to the local hardware/worker management window. Windows/Linux +UI and sleep/resume qualification remain pending; hosted CI has not run. diff --git a/desktop-core/build.rs b/desktop-core/build.rs new file mode 100644 index 00000000..93cb8f8d --- /dev/null +++ b/desktop-core/build.rs @@ -0,0 +1,11 @@ +fn main() -> Result<(), Box> { + let mut config = tonic_prost_build::Config::new(); + config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); + tonic_prost_build::configure().compile_with_config( + config, + &["proto/node.proto"], + &["proto"], + )?; + println!("cargo:rerun-if-changed=proto/node.proto"); + Ok(()) +} diff --git a/desktop-core/examples/pool.json b/desktop-core/examples/pool.json new file mode 100644 index 00000000..0898377f --- /dev/null +++ b/desktop-core/examples/pool.json @@ -0,0 +1,19 @@ +{ + "schema_version": 1, + "listen": "127.0.0.1:18765", + "token_env": "STRATA_POOL_TOKEN", + "queue_limit": 8, + "queue_timeout_ms": 120000, + "request_timeout_ms": 900000, + "groups": [ + {"id": "local", "slots": 1, "available_bytes": 1073741824}, + {"id": "server-a", "slots": 1, "available_bytes": 1073741824}, + {"id": "server-b", "slots": 1, "available_bytes": 1073741824} + ], + "deployments": [ + {"id": "local-model", "model": "replace-with-local-model-id", "endpoint": "http://127.0.0.1:19001", "token_env": "STRATA_LOCAL_TOKEN", "group": "local", "slots": 1, "request_bytes": 1073741824, "capabilities": ["responses", "tools"]}, + {"id": "remote-a", "model": "replace-with-server-a-model-id", "endpoint": "http://127.0.0.1:19002", "token_env": "STRATA_REMOTE_A_TOKEN", "group": "server-a", "slots": 1, "request_bytes": 1073741824, "capabilities": ["responses", "tools"]}, + {"id": "remote-b", "model": "replace-with-server-b-model-id", "endpoint": "http://127.0.0.1:19003", "token_env": "STRATA_REMOTE_B_TOKEN", "group": "server-b", "slots": 1, "request_bytes": 1073741824, "capabilities": ["responses", "tools"]} + ], + "aliases": {"coding-pool": ["local-model", "remote-a", "remote-b"]} +} diff --git a/desktop-core/examples/remote-install.json b/desktop-core/examples/remote-install.json new file mode 100644 index 00000000..c8290e6f --- /dev/null +++ b/desktop-core/examples/remote-install.json @@ -0,0 +1,19 @@ +{ + "schema_version": 1, + "target": { + "ssh": { + "schema_version": 1, + "id": "private-linux", + "host": "my-inference-host", + "user": null, + "port": null, + "identity_file": null + }, + "slot": "default", + "os": "linux", + "arch": "x86_64" + }, + "runtime": "/absolute/path/to/linux/strata-desktop", + "runtime_sha256": "0000000000000000000000000000000000000000000000000000000000000000", + "worker_profile": "/absolute/path/to/remote-worker.json" +} diff --git a/desktop-core/examples/requirements.json b/desktop-core/examples/requirements.json new file mode 100644 index 00000000..8ca57cb4 --- /dev/null +++ b/desktop-core/examples/requirements.json @@ -0,0 +1,15 @@ +{ + "schema_version": 1, + "model": "Example only: synthetic 10 GiB runtime weights", + "context_tokens": 8192, + "concurrent_requests": 1, + "weights_bytes": 10737418240, + "kv_bytes_per_token_per_request": 131072, + "workspace_bytes": 1073741824, + "load_scratch_bytes": 1073741824, + "host_overhead_bytes": 1073741824, + "host_reserve_bytes": 2147483648, + "device_reserve_bytes": 1073741824, + "retains_host_weights": false, + "allow_weight_offload": true +} diff --git a/desktop-core/examples/ssh-profile.json b/desktop-core/examples/ssh-profile.json new file mode 100644 index 00000000..60d1353b --- /dev/null +++ b/desktop-core/examples/ssh-profile.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "id": "server-a", + "host": "your-ssh-config-alias", + "user": null, + "port": null, + "identity_file": null +} diff --git a/desktop-core/examples/ssh-tunnel.json b/desktop-core/examples/ssh-tunnel.json new file mode 100644 index 00000000..bb00fb7c --- /dev/null +++ b/desktop-core/examples/ssh-tunnel.json @@ -0,0 +1,14 @@ +{ + "schema_version": 1, + "ssh": { + "schema_version": 1, + "id": "server-a", + "host": "your-ssh-config-alias", + "user": null, + "port": null, + "identity_file": null + }, + "listen": "127.0.0.1:18767", + "remote_port": 18766, + "max_connections": 4 +} diff --git a/desktop-core/proto/node.proto b/desktop-core/proto/node.proto new file mode 100644 index 00000000..0bdddcc7 --- /dev/null +++ b/desktop-core/proto/node.proto @@ -0,0 +1,56 @@ +syntax = "proto3"; +package strata.node.v1; +option csharp_namespace = "Strata.Node.V1"; +service Node { + rpc WorkerStatus(Empty) returns (WorkerState); + rpc ControlWorker(WorkerCommand) returns (WorkerOperation); + rpc OperationStatus(OperationQuery) returns (WorkerOperation); + rpc Handshake(Hello) returns (Snapshot); + rpc Hardware(Empty) returns (JsonDocument); + rpc Plan(JsonDocument) returns (JsonDocument); + rpc Watch(Cursor) returns (stream Snapshot); + rpc Models(Empty) returns (JsonDocument); + rpc Respond(ResponseRequest) returns (stream ResponseFrame); +} +message Empty {} +message Hello { uint32 protocol_version = 1; } +message Cursor { string agent_epoch = 1; uint64 sequence = 2; } +message Snapshot { + uint32 protocol_version = 1; + string agent_epoch = 2; + uint64 sequence = 3; + repeated string capabilities = 4; + uint32 active_responses = 5; + bool full_snapshot = 6; +} +message JsonDocument { bytes json = 1; } +message ResponseRequest { bytes json = 1; } +message ResponseHeaders { uint32 status = 1; string content_type = 2; string retry_after = 3; } +message ResponseFrame { + oneof payload { + ResponseHeaders headers = 1; + bytes data = 2; + Empty end = 3; + } +} + +message WorkerState { + string profile_id = 1; + string model = 2; + string phase = 3; + uint32 pid = 4; + string reason = 5; +} +message WorkerCommand { + string operation_id = 1; + enum Action { UNSPECIFIED = 0; START = 1; STOP = 2; } + Action action = 2; + uint32 drain_timeout_ms = 3; + string expected_epoch = 4; +} +message OperationQuery { string operation_id = 1; } +message WorkerOperation { + string operation_id = 1; + string status = 2; + string reason = 3; +} diff --git a/desktop-core/src/gateway.rs b/desktop-core/src/gateway.rs new file mode 100644 index 00000000..742c54f7 --- /dev/null +++ b/desktop-core/src/gateway.rs @@ -0,0 +1,559 @@ +//! Experimental loopback gateway. Endpoints must already be managed and ready. +use crate::pool::{AdmissionError, Lease, Pool, ResourceGroup, Worker}; +use axum::{ + Json, Router, + body::{Body, Bytes}, + extract::{DefaultBodyLimit, State}, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use futures_util::StreamExt; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, HashSet, VecDeque}, + net::{IpAddr, SocketAddr}, + sync::{Arc, Mutex}, + time::Duration, +}; +use subtle::ConstantTimeEq; + +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub schema_version: u32, + pub listen: SocketAddr, + pub token_env: String, + pub queue_limit: usize, + pub queue_timeout_ms: u64, + pub request_timeout_ms: u64, + pub groups: Vec, + pub deployments: Vec, + /// Explicitly permitted members; distinct models never share an implicit alias. + pub aliases: BTreeMap>, +} +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Group { + pub id: String, + pub slots: usize, + pub available_bytes: u64, +} +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Deployment { + pub id: String, + pub model: String, + pub endpoint: String, + pub token_env: Option, + pub group: String, + pub slots: usize, + pub request_bytes: u64, + pub capabilities: Vec, +} +#[derive(Clone)] +pub struct Gateway(Arc); +struct Inner { + config: Config, + pool: Pool, + token: String, + upstream_tokens: Vec>, + client: reqwest::Client, + // Bounded process-local ownership, never response text or prompts. + owners: Mutex>, +} +fn secret(name: &str) -> Result { + if name.is_empty() || !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') { + return Err("invalid credential environment name".into()); + } + let value = std::env::var(name).map_err(|_| "credential environment variable is missing")?; + if value.len() < 16 || value.len() > 4096 || value.bytes().any(|c| c.is_ascii_control()) { + return Err("credential must contain 16..4096 non-control bytes".into()); + } + Ok(value) +} +impl Gateway { + pub fn new(config: Config) -> Result { + let token = secret(&config.token_env)?; + Self::with_token(config, token) + } + /// Explicit token injection is useful for an embedding host and isolated tests. + pub fn with_token(config: Config, token: String) -> Result { + if config.schema_version != 1 + || !config.listen.ip().is_loopback() + || token.len() < 16 + || config.queue_timeout_ms == 0 + || config.queue_timeout_ms > 3_600_000 + || config.request_timeout_ms == 0 + || config.request_timeout_ms > 86_400_000 + || config.queue_limit > 64 + || config.aliases.len() > 256 + { + return Err("invalid gateway limits or non-loopback bind".into()); + } + let mut endpoints = HashSet::new(); + for d in &config.deployments { + let u = reqwest::Url::parse(&d.endpoint).map_err(|_| "invalid endpoint")?; + let ip = u + .host_str() + .unwrap_or("") + .trim_matches(['[', ']']) + .parse::() + .map_err(|_| "endpoint must use a loopback IP")?; + if !ip.is_loopback() + || u.scheme() != "http" + || u.path() != "/" + || u.query().is_some() + || u.fragment().is_some() + || !u.username().is_empty() + || u.password().is_some() + || !endpoints.insert(u.to_string()) + || d.model.is_empty() + || d.id.len() > 128 + { + return Err("invalid, duplicate or non-loopback endpoint".into()); + } + } + let ids: HashSet<_> = config.deployments.iter().map(|d| d.id.as_str()).collect(); + for (alias, members) in &config.aliases { + if alias.is_empty() + || ids.contains(alias.as_str()) + || members.is_empty() + || members.len() > 256 + || members.iter().any(|m| !ids.contains(m.as_str())) + { + return Err("invalid pool alias".into()); + } + } + let pool = Pool::new( + config + .deployments + .iter() + .map(|d| Worker { + id: d.id.clone(), + group: d.group.clone(), + slots: d.slots, + request_bytes: d.request_bytes, + }) + .collect(), + config + .groups + .iter() + .map(|g| ResourceGroup { + id: g.id.clone(), + slots: g.slots, + available_bytes: g.available_bytes, + }) + .collect(), + config.queue_limit, + ) + .map_err(|_| "invalid resource capacity")?; + let upstream_tokens = config + .deployments + .iter() + .map(|d| d.token_env.as_deref().map(secret).transpose()) + .collect::>()?; + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .build() + .map_err(|_| "HTTP client initialization failed")?; + Ok(Self(Arc::new(Inner { + config, + pool, + token, + upstream_tokens, + client, + owners: Mutex::new(VecDeque::new()), + }))) + } + pub(crate) fn matches_credential(&self, token: &str) -> bool { + bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes())) + } + pub(crate) fn clear_response_owners(&self) { + self.0.owners.lock().unwrap().clear(); + } + pub(crate) fn set_managed_ready(&self, ready: bool) { + for i in 0..self.0.config.deployments.len() { + let _ = self.0.pool.set_ready(i, ready); + } + } + pub(crate) fn idle(&self) -> bool { + let s = self.0.pool.snapshot(); + s.active == 0 && s.queued == 0 + } + pub fn router(&self) -> Router { + Router::new() + .route("/v1/models", get(models)) + .route("/v1/responses", post(responses)) + .route("/pool/status", get(status)) + .layer(DefaultBodyLimit::max(2 * 1024 * 1024)) + .with_state(self.clone()) + } + fn authorized(&self, h: &HeaderMap) -> bool { + h.get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ")) + .is_some_and(|s| bool::from(s.as_bytes().ct_eq(self.0.token.as_bytes()))) + } + fn remember(&self, id: String, worker: usize) { + if id.is_empty() || id.len() > 256 { + return; + } + let mut owners = self.0.owners.lock().unwrap(); + // A collision is ambiguous; sentinel ownership rejects further continuations. + let owner = owners + .iter() + .find(|(key, _)| key == &id) + .map(|(_, w)| if *w == worker { worker } else { usize::MAX }) + .unwrap_or(worker); + owners.retain(|(key, _)| key != &id); + owners.push_back((id, owner)); + if owners.len() > 4096 { + owners.pop_front(); + } + } +} +fn error(code: StatusCode, kind: &str) -> Response { + let mut response = (code, Json(json!({"error":{"type":kind,"message":kind}}))).into_response(); + if code == StatusCode::TOO_MANY_REQUESTS { + response + .headers_mut() + .insert("retry-after", "1".parse().unwrap()); + } + response +} +async fn models(State(g): State, h: HeaderMap) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let ids = + g.0.config + .deployments + .iter() + .map(|d| d.id.clone()) + .chain(g.0.config.aliases.keys().cloned()); + Json(json!({"object":"list","data":ids.map(|id|json!({"id":id,"object":"model","owned_by":"configured-pool"})).collect::>()})).into_response() +} +async fn status(State(g): State, h: HeaderMap) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + Json(json!({"schema_version":1,"pool":g.0.pool.snapshot()})).into_response() +} +fn required_caps(v: &Value, out: &mut HashSet<&'static str>) { + match v { + Value::Array(a) => { + for v in a { + required_caps(v, out) + } + } + Value::Object(m) => { + match m.get("type").and_then(Value::as_str) { + Some("input_image") => { + out.insert("image"); + } + Some("input_audio") => { + out.insert("audio"); + } + Some("input_file") => { + out.insert("file"); + } + _ => {} + } + for v in m.values() { + required_caps(v, out); + } + } + _ => {} + } +} +struct InFlight { + g: Gateway, + worker: usize, + lease: Option, + complete: bool, +} +impl Drop for InFlight { + fn drop(&mut self) { + // Client disconnect does not prove upstream stopped computing. Quarantine before releasing. + if !self.complete { + let _ = self.g.0.pool.set_ready(self.worker, false); + } + self.lease.take(); + } +} +#[derive(Default)] +struct Terminal { + line: Vec, + data: Vec, + overflow: bool, + complete: bool, + response_id: Option, +} +impl Terminal { + fn feed(&mut self, bytes: &[u8]) { + for b in bytes { + if *b == b'\n' { + let line = self.line.strip_suffix(b"\r").unwrap_or(&self.line); + if line.is_empty() { + if !self.overflow + && let Ok(v) = serde_json::from_slice::(&self.data) + && matches!( + v.get("type").and_then(Value::as_str), + Some("response.completed" | "response.failed" | "response.incomplete") + ) + { + self.complete = true; + self.response_id = v + .pointer("/response/id") + .and_then(Value::as_str) + .map(str::to_owned); + } + self.data.clear(); + self.overflow = false; + } else if !self.overflow + && let Some(data) = line.strip_prefix(b"data:") + { + if self.data.len() + data.len() + 1 > 1024 * 1024 { + self.overflow = true; + } else { + self.data.extend_from_slice(data); + self.data.push(b'\n'); + } + } + self.line.clear(); + } else if self.line.len() < 1024 * 1024 { + self.line.push(*b); + } else { + self.overflow = true; + } + } + } +} +async fn responses(State(g): State, h: HeaderMap, body: Bytes) -> Response { + if !g.authorized(&h) { + return error(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let mut v: Value = match serde_json::from_slice(&body) { + Ok(Value::Object(v)) => Value::Object(v), + _ => return error(StatusCode::BAD_REQUEST, "invalid_json"), + }; + if v.get("conversation").is_some_and(|v| !v.is_null()) + || v.get("background") == Some(&Value::Bool(true)) + { + return error(StatusCode::BAD_REQUEST, "unsupported_stateful_mode"); + } + let Some(model) = v.get("model").and_then(Value::as_str) else { + return error(StatusCode::BAD_REQUEST, "model_required"); + }; + let mut eligible: Vec<_> = + g.0.config + .deployments + .iter() + .enumerate() + .filter(|(_, d)| { + d.id == model + || g.0 + .config + .aliases + .get(model) + .is_some_and(|m| m.contains(&d.id)) + }) + .map(|(i, _)| i) + .collect(); + if eligible.is_empty() { + return error(StatusCode::NOT_FOUND, "unknown_model"); + } + let mut caps = HashSet::from(["responses"]); + required_caps(v.get("input").unwrap_or(&Value::Null), &mut caps); + if v.get("tools") + .is_some_and(|v| v.as_array().is_none_or(|a| !a.is_empty())) + { + caps.insert("tools"); + } + if v.get("reasoning").is_some_and(|v| !v.is_null()) { + caps.insert("reasoning"); + } + if v.pointer("/text/format/type") + .and_then(Value::as_str) + .is_some_and(|s| s != "text") + { + caps.insert("structured_output"); + } + eligible.retain(|i| { + caps.iter().all(|c| { + g.0.config.deployments[*i] + .capabilities + .iter() + .any(|x| x == c) + }) + }); + if let Some(previous) = v.get("previous_response_id").filter(|v| !v.is_null()) { + let owner = previous.as_str().and_then(|id| { + g.0.owners + .lock() + .unwrap() + .iter() + .find(|(key, _)| key == id) + .map(|(_, w)| *w) + }); + let Some(owner) = owner else { + return error(StatusCode::CONFLICT, "unknown_response_owner"); + }; + eligible.retain(|i| *i == owner); + } + if eligible.is_empty() { + return error(StatusCode::CONFLICT, "no_compatible_deployment"); + } + let lease = match g + .0 + .pool + .acquire(eligible, Duration::from_millis(g.0.config.queue_timeout_ms)) + .await + { + Ok(l) => l, + Err(AdmissionError::Full) => return error(StatusCode::TOO_MANY_REQUESTS, "queue_full"), + Err(AdmissionError::Expired) => return error(StatusCode::GATEWAY_TIMEOUT, "queue_timeout"), + Err(_) => return error(StatusCode::SERVICE_UNAVAILABLE, "admission_failed"), + }; + let worker = lease.worker(); + let mut guard = InFlight { + g: g.clone(), + worker, + lease: Some(lease), + complete: false, + }; + let d = &g.0.config.deployments[worker]; + v["model"] = Value::String(d.model.clone()); + let streaming = v.get("stream") == Some(&Value::Bool(true)); + let deadline = + tokio::time::Instant::now() + Duration::from_millis(g.0.config.request_timeout_ms); + let mut request = + g.0.client + .post(format!("{}/v1/responses", d.endpoint.trim_end_matches('/'))) + .header("content-type", "application/json") + .body(serde_json::to_vec(&v).unwrap()); + if let Some(token) = &g.0.upstream_tokens[worker] { + request = request.bearer_auth(token); + } + let response = match tokio::time::timeout_at(deadline, request.send()).await { + Ok(Ok(r)) => r, + _ => return error(StatusCode::BAD_GATEWAY, "upstream_unavailable"), + }; + let code = response.status(); + let is_sse = response + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|s| s.starts_with("text/event-stream")); + if code.is_success() && streaming && !is_sse { + return error(StatusCode::BAD_GATEWAY, "upstream_stream_type"); + } + let content_type = if is_sse { + "text/event-stream" + } else { + "application/json" + }; + let mut result = if streaming && code.is_success() { + let stream = response.bytes_stream(); + let stream = futures_util::stream::unfold( + (Box::pin(stream), guard, Terminal::default(), false), + move |(mut source, mut guard, mut terminal, done)| async move { + if done { + return None; + } + match tokio::time::timeout_at(deadline, source.next()).await { + Ok(Some(Ok(bytes))) => { + terminal.feed(&bytes); + if let Some(id) = terminal.response_id.take() { + guard.g.remember(id, guard.worker); + } + Some(( + Ok::<_, std::io::Error>(bytes), + (source, guard, terminal, false), + )) + } + Ok(None) => { + guard.complete = terminal.complete; + if terminal.complete { + if let Some(id) = terminal.response_id.take() { + guard.g.remember(id, guard.worker); + } + None + } else { + Some(( + Err(std::io::Error::other("upstream missing terminal event")), + (source, guard, terminal, true), + )) + } + } + _ => Some(( + Err(std::io::Error::other("upstream stream interrupted")), + (source, guard, terminal, true), + )), + } + }, + ); + (code, Body::from_stream(stream)).into_response() + } else { + let mut data = Vec::new(); + let mut stream = response.bytes_stream(); + loop { + match tokio::time::timeout_at(deadline, stream.next()).await { + Ok(Some(Ok(bytes))) if data.len() + bytes.len() <= 8 * 1024 * 1024 => { + data.extend_from_slice(&bytes) + } + Ok(None) => break, + _ => return error(StatusCode::BAD_GATEWAY, "upstream_body_failed"), + } + } + if code.is_success() { + let parsed = serde_json::from_slice::(&data).ok(); + if !matches!( + parsed + .as_ref() + .and_then(|v| v.get("status")) + .and_then(Value::as_str), + Some("completed" | "failed" | "incomplete") + ) { + return error(StatusCode::BAD_GATEWAY, "upstream_missing_terminal_status"); + } + if let Some(id) = parsed + .as_ref() + .and_then(|v| v.get("id")) + .and_then(Value::as_str) + { + g.remember(id.into(), worker); + } + } + guard.complete = true; + (code, Body::from(data)).into_response() + }; + result + .headers_mut() + .insert("content-type", content_type.parse().unwrap()); + result + .headers_mut() + .insert("cache-control", "no-store".parse().unwrap()); + // IDs are validated as HTTP values instead of panicking on administrator input. + if let Ok(id) = d.id.parse() { + result.headers_mut().insert("x-strata-deployment", id); + } + result +} + +pub async fn serve(config: Config) -> Result<(), Box> { + let address = config.listen; + let g = Gateway::new(config)?; + let listener = tokio::net::TcpListener::bind(address).await?; + eprintln!("Strata pool listening on {}", listener.local_addr()?); + axum::serve(listener, g.router()) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + Ok(()) +} diff --git a/desktop-core/src/hardware.rs b/desktop-core/src/hardware.rs new file mode 100644 index 00000000..b1363d92 --- /dev/null +++ b/desktop-core/src/hardware.rs @@ -0,0 +1,289 @@ +use serde::{Deserialize, Serialize}; +use std::{ + process::Stdio, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::{io::AsyncReadExt, process::Command}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Memory { + pub total_bytes: Option, + pub available_bytes: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum MemoryKind { + Dedicated, + Shared, + Unknown, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Accelerator { + pub id: String, + pub name: String, + pub vendor: String, + pub memory_kind: MemoryKind, + /// For shared GPUs this is an independent device allocation limit, not RAM. + pub memory: Memory, + pub driver: Option, + pub source: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Hardware { + pub schema_version: u32, + pub sampled_at_unix_ms: u64, + pub os: String, + pub architecture: String, + pub cpu_name: String, + pub logical_cpus: usize, + pub cpu_features: Vec, + pub memory: Memory, + pub accelerators: Vec, + pub warnings: Vec, +} + +pub async fn inventory() -> Hardware { + let mut system = sysinfo::System::new(); + system.refresh_memory(); + system.refresh_cpu_all(); + let total = system.total_memory(); + let mut h = Hardware { + schema_version: 1, + sampled_at_unix_ms: SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|t| t.as_millis() as u64) + .unwrap_or(0), + os: std::env::consts::OS.into(), + architecture: std::env::consts::ARCH.into(), + cpu_name: system + .cpus() + .first() + .map(|c| c.brand().to_owned()) + .unwrap_or_default(), + logical_cpus: system.cpus().len(), + cpu_features: cpu_features(), + memory: Memory { + total_bytes: (total > 0).then_some(total), + available_bytes: (total > 0).then_some(system.available_memory().min(total)), + }, + accelerators: vec![], + warnings: vec![ + "NPU and inference provider availability are not probed in this version.".into(), + ], + }; + if cfg!(target_os = "macos") { + match probe( + "/usr/sbin/system_profiler", + &["SPDisplaysDataType", "-json"], + Duration::from_secs(5), + ) + .await + { + Ok(data) => match parse_macos(&data, cfg!(target_arch = "aarch64")) { + Ok(gpus) => h.accelerators = gpus, + Err(e) => h.warnings.push(e), + }, + Err(e) => h.warnings.push(format!("Apple display inventory: {e}")), + } + } else { + match probe( + "nvidia-smi", + &[ + "--query-gpu=name,memory.total,memory.free,driver_version", + "--format=csv,noheader,nounits", + ], + Duration::from_secs(3), + ) + .await + { + Ok(data) => match parse_nvidia(&data) { + Ok(gpus) => h.accelerators = gpus, + Err(e) => h.warnings.push(e), + }, + Err(e) => h + .warnings + .push(format!("NVIDIA inventory unavailable: {e}")), + } + h.warnings.push( + "Non-NVIDIA GPU inventory is not implemented; an empty list does not mean no GPU." + .into(), + ); + } + h +} + +fn cpu_features() -> Vec { + let mut result = Vec::new(); + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if std::is_x86_feature_detected!("avx2") { + result.push("avx2".into()); + } + if std::is_x86_feature_detected!("avx512f") { + result.push("avx512f".into()); + } + if std::is_x86_feature_detected!("fma") { + result.push("fma".into()); + } + } + #[cfg(target_arch = "aarch64")] + { + if std::arch::is_aarch64_feature_detected!("neon") { + result.push("neon".into()); + } + if std::arch::is_aarch64_feature_detected!("dotprod") { + result.push("dotprod".into()); + } + } + result +} + +/// Fixed program/arguments from inventory only; no shell, prompts or process list. +async fn probe(program: &str, args: &[&str], limit: Duration) -> Result { + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "probe could not start".to_string())?; + let stdout = child.stdout.take().ok_or("missing probe output")?; + let mut data = Vec::new(); + let read = async { + stdout + .take(65537) + .read_to_end(&mut data) + .await + .map_err(|_| "probe read failed")?; + if data.len() > 65536 { + return Err("probe output too large"); + } + let status = child.wait().await.map_err(|_| "probe wait failed")?; + if !status.success() { + return Err("probe exited unsuccessfully"); + } + Ok(()) + }; + match tokio::time::timeout(limit, read).await { + Ok(Ok(())) => String::from_utf8(data).map_err(|_| "probe output is not UTF-8".into()), + outcome => { + let _ = child.kill().await; + Err(match outcome { + Ok(Err(e)) => e, + _ => "probe timed out", + } + .into()) + } + } +} + +pub(crate) fn parse_nvidia(data: &str) -> Result, String> { + data.lines() + .filter(|l| !l.trim().is_empty()) + .enumerate() + .map(|(i, line)| { + let parts: Vec<_> = line.split(',').map(str::trim).collect(); + if parts.len() != 4 { + return Err("invalid NVIDIA inventory row".into()); + } + let mib = |s: &str| { + s.parse::() + .ok() + .and_then(|n| n.checked_mul(1024 * 1024)) + }; + let total = mib(parts[1]); + let free = mib(parts[2]); + if let (Some(t), Some(f)) = (total, free) + && f > t + { + return Err("inconsistent NVIDIA memory".into()); + } + Ok(Accelerator { + id: format!("nvidia-{i}"), + name: parts[0].into(), + vendor: "NVIDIA".into(), + memory_kind: MemoryKind::Dedicated, + memory: Memory { + total_bytes: total, + available_bytes: free, + }, + driver: (!parts[3].is_empty()).then(|| parts[3].into()), + source: "nvidia-smi".into(), + }) + }) + .collect() +} + +fn parse_macos(data: &str, apple_silicon: bool) -> Result, String> { + let value: serde_json::Value = + serde_json::from_str(data).map_err(|_| "invalid display JSON")?; + let rows = value + .get("SPDisplaysDataType") + .and_then(|v| v.as_array()) + .ok_or("missing display inventory")?; + Ok(rows + .iter() + .enumerate() + .filter_map(|(i, r)| { + let name = r.get("sppci_model").or_else(|| r.get("_name"))?.as_str()?; + Some(Accelerator { + id: format!("display-{i}"), + name: name.into(), + vendor: if apple_silicon { "Apple" } else { "unknown" }.into(), + memory_kind: if apple_silicon { + MemoryKind::Shared + } else { + MemoryKind::Unknown + }, + memory: Memory { + total_bytes: None, + available_bytes: None, + }, + driver: None, + source: "system_profiler".into(), + }) + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn nvidia_unknown_is_not_zero_and_mib_is_binary() { + let g = parse_nvidia("RTX test, 8192, 7168, 580.65.06\nGPU test, [N/A], [N/A], unknown") + .unwrap(); + assert_eq!(g[0].memory.total_bytes, Some(8 * 1024 * 1024 * 1024)); + assert_eq!(g[1].memory.available_bytes, None); + assert!(parse_nvidia("GPU, 1, 2, v").is_err()); + } + #[test] + fn shared_gpu_does_not_invent_a_second_ram_pool() { + let g = parse_macos( + r#"{"SPDisplaysDataType":[{"sppci_model":"Apple test"}]}"#, + true, + ) + .unwrap(); + assert_eq!(g[0].memory_kind, MemoryKind::Shared); + assert_eq!(g[0].memory.available_bytes, None); + } + #[cfg(unix)] + #[tokio::test] + async fn command_timeout_is_bounded() { + let start = std::time::Instant::now(); + assert_eq!( + probe("/bin/sleep", &["5"], Duration::from_millis(20)) + .await + .unwrap_err(), + "probe timed out" + ); + assert!(start.elapsed() < Duration::from_secs(2)); + } +} diff --git a/desktop-core/src/lib.rs b/desktop-core/src/lib.rs new file mode 100644 index 00000000..ec56fc38 --- /dev/null +++ b/desktop-core/src/lib.rs @@ -0,0 +1,16 @@ +//! Portable desktop contracts. Inventory is not an inference capability claim. +pub mod gateway; +pub mod hardware; +pub mod managed_worker; +pub mod node; +pub mod node_connection; +pub mod node_proxy; +pub mod planner; +pub mod pool; +pub mod remote; + +mod operation_journal; + +pub mod ssh_tunnel; + +pub mod remote_install; diff --git a/desktop-core/src/main.rs b/desktop-core/src/main.rs new file mode 100644 index 00000000..27c83933 --- /dev/null +++ b/desktop-core/src/main.rs @@ -0,0 +1,277 @@ +use std::{env, fs::File, io::Read}; +use strata_desktop_core::{gateway, hardware, node, planner, remote}; + +fn read_json(path: &str) -> Result> { + let mut data = Vec::new(); + File::open(path)? + .take(1024 * 1024 + 1) + .read_to_end(&mut data)?; + if data.len() > 1024 * 1024 { + return Err("input JSON exceeds 1 MiB".into()); + } + Ok(serde_json::from_slice(&data)?) +} + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + let args: Vec<_> = env::args().skip(1).collect(); + if let [cmd, l, listen, n, address, t, token_env] = args.as_slice() + && cmd == "node-proxy" + && l == "--listen" + && n == "--node" + && t == "--token-env" + { + let listen: std::net::SocketAddr = listen.parse()?; + if !listen.ip().is_loopback() { + return Err("proxy must bind loopback".into()); + } + let token = std::env::var(token_env).map_err(|_| "missing node credential")?; + let proxy = + strata_desktop_core::node_proxy::Proxy::connect(address.parse()?, token).await?; + let listener = tokio::net::TcpListener::bind(listen).await?; + axum::serve(listener, proxy.router()) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + return Ok(()); + } + if let [cmd, file] = args.as_slice() + && cmd == "ssh-tunnel" + { + let stdio_lifetime = file == "--stdio-lifetime"; + let config = if stdio_lifetime { + use std::io::BufRead; + let mut line = Vec::new(); + std::io::stdin() + .lock() + .take(1024 * 1024 + 1) + .read_until(b'\n', &mut line)?; + if line.len() > 1024 * 1024 || line.last() != Some(&b'\n') { + return Err("invalid tunnel bootstrap size or framing".into()); + } + serde_json::from_slice(&line)? + } else { + read_json(file)? + }; + let tunnel = strata_desktop_core::ssh_tunnel::Tunnel::bind(&config).await?; + let (closed_tx, closed_rx) = tokio::sync::oneshot::channel(); + if stdio_lifetime { + std::thread::spawn(move || { + let mut byte = [0]; + while std::io::stdin().read(&mut byte).is_ok_and(|n| n > 0) {} + let _ = closed_tx.send(()); + }); + } + println!( + "{}", + serde_json::json!({"schema_version":1,"endpoint":format!("http://{}",tunnel.address()),"transport":"ssh","readiness":"requires_authenticated_node_handshake"}) + ); + use std::io::Write; + std::io::stdout().flush()?; + return tunnel + .serve(async move { + if stdio_lifetime { + tokio::select! { _ = closed_rx => {}, _ = tokio::signal::ctrl_c() => {} } + } else { + let _ = tokio::signal::ctrl_c().await; + } + }) + .await + .map_err(Into::into); + } + if args.first().is_some_and(|s| s == "worker") { + return worker(&args[1..]).await; + } + if args.first().is_some_and(|s| s == "node") { + return serve_node(&args[1..]).await; + } + let value = match args.as_slice() { + [cmd, file] if cmd == "remote-install" => serde_json::to_value( + strata_desktop_core::remote_install::install(read_json(file)?).await?, + )?, + [cmd, file] if cmd == "remote-activate" => serde_json::to_value( + strata_desktop_core::remote_install::activate(read_json(file)?).await?, + )?, + [cmd, file] if cmd == "validate-worker" => { + let profile: strata_desktop_core::managed_worker::Profile = read_json(file)?; + profile.validate()?; + return Ok(()); + } + [cmd, file] if cmd == "remote-inspect" => { + serde_json::to_value(remote::inspect(&read_json(file)?).await?)? + } + [cmd, file] if cmd == "gateway" => { + gateway::serve(read_json(file)?).await?; + return Ok(()); + } + [cmd] if cmd == "hardware" => serde_json::to_value(hardware::inventory().await)?, + [cmd, file] if cmd == "plan" => { + let r = read_json(file)?; + serde_json::to_value(planner::plan(&hardware::inventory().await, &r)?)? + } + [cmd, file, flag, snapshot] if cmd == "plan" && flag == "--hardware" => { + serde_json::to_value(planner::plan(&read_json(snapshot)?, &read_json(file)?)?)? + } + [cmd] if cmd == "--help" || cmd == "help" => { + println!( + "strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop remote-inspect SSH_PROFILE.json\nstrata-desktop ssh-tunnel TUNNEL_PROFILE.json\nstrata-desktop remote-install INSTALL.json\nstrata-desktop remote-activate ACTIVATION.json\nstrata-desktop validate-worker WORKER.json\nstrata-desktop gateway POOL.json\nstrata-desktop node --listen 127.0.0.1:0 --token-env ENV [--pool POOL.json | --worker-profile FILE [--journal PRIVATE_PATH] | --stdio-lifetime]\nstrata-desktop node-proxy --listen 127.0.0.1:18765 --node 127.0.0.1:18766 --token-env ENV\nstrata-desktop worker --node 127.0.0.1:18766 --token-env ENV status|start UUID|stop UUID|operation UUID\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models." + ); + return Ok(()); + } + _ => { + return Err( + "usage: strata-desktop --help (hardware, plan, remote-inspect, gateway)".into(), + ); + } + }; + println!("{}", serde_json::to_string_pretty(&value)?); + Ok(()) +} + +async fn serve_node(args: &[String]) -> Result<(), Box> { + use std::io::Write; + let (address, token_env, mode) = match args { + [a, address, t, token_env, rest @ ..] if a == "--listen" && t == "--token-env" => { + (address, token_env, rest) + } + _ => return Err( + "usage: node --listen LOOPBACK:PORT --token-env ENV [--pool FILE | --worker-profile FILE [--journal PRIVATE_PATH] | --stdio-lifetime]" + .into(), + ), + }; + let address: std::net::SocketAddr = address.parse()?; + if !address.ip().is_loopback() { + return Err("node must bind loopback".into()); + } + if token_env.is_empty() + || !token_env + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_') + { + return Err("invalid credential variable name".into()); + } + let token = std::env::var(token_env).map_err(|_| "missing node credential")?; + let mut profile = None; + let mut journal = None; + let (gateway, stdio_lifetime) = match mode { + [p, file, j, path] if p == "--worker-profile" && j == "--journal" => { + profile = Some(read_json(file)?); + journal = Some(std::path::Path::new(path)); + (None, false) + } + [p, file] if p == "--worker-profile" => { + profile = Some(read_json(file)?); + (None, false) + } + [] => (None, false), + [s] if s == "--stdio-lifetime" => (None, true), + [p, file] if p == "--pool" => ( + Some(gateway::Gateway::with_token( + read_json(file)?, + token.clone(), + )?), + false, + ), + _ => return Err("invalid node mode; stdio lifetime cannot own inference".into()), + }; + let agent = if let Some(profile) = profile { + node::Agent::managed_journal(token, profile, journal)? + } else { + node::Agent::new(token, gateway)? + }; + let listener = tokio::net::TcpListener::bind(address).await?; + println!( + "{}", + serde_json::json!({"schema_version":1,"endpoint":format!("http://{}",listener.local_addr()?)}) + ); + std::io::stdout().flush()?; + let (closed_tx, closed_rx) = tokio::sync::oneshot::channel(); + if stdio_lifetime { + std::thread::spawn(move || { + let mut b = [0; 1]; + while std::io::stdin().read(&mut b).is_ok_and(|n| n > 0) {} + let _ = closed_tx.send(()); + }); + } + agent + .serve(listener, async move { + if stdio_lifetime { + let _ = closed_rx.await; + } else { + let _ = tokio::signal::ctrl_c().await; + } + }) + .await +} + +async fn worker(args: &[String]) -> Result<(), Box> { + use node::proto::*; + let [n, address, t, env, action, rest @ ..] = args else { + return Err("worker --node LOOPBACK:PORT --token-env ENV status|start UUID|stop UUID|operation UUID".into()); + }; + if n != "--node" || t != "--token-env" { + return Err("invalid worker options".into()); + } + let token = std::env::var(env).map_err(|_| "missing node credential")?; + let mut client = node::connect(address.parse()?).await?; + let value = match (action.as_str(), rest) { + ("status", []) => { + let s = client + .worker_status(worker_request(Empty {}, &token)?) + .await? + .into_inner(); + serde_json::json!({"profile_id":s.profile_id,"model":s.model,"phase":s.phase,"pid":s.pid,"reason":s.reason}) + } + ("start" | "stop", [id]) => { + let epoch = client + .handshake(worker_request( + Hello { + protocol_version: 1, + }, + &token, + )?) + .await? + .into_inner() + .agent_epoch; + let s = client + .control_worker(worker_request( + WorkerCommand { + operation_id: id.clone(), + expected_epoch: epoch, + action: if action == "start" { 1 } else { 2 }, + drain_timeout_ms: if action == "stop" { 30000 } else { 0 }, + }, + &token, + )?) + .await? + .into_inner(); + serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason}) + } + ("operation", [id]) => { + let s = client + .operation_status(worker_request( + OperationQuery { + operation_id: id.clone(), + }, + &token, + )?) + .await? + .into_inner(); + serde_json::json!({"operation_id":s.operation_id,"status":s.status,"reason":s.reason}) + } + _ => { + return Err( + "invalid worker action; supply a stable operation UUID for commands".into(), + ); + } + }; + println!("{}", serde_json::to_string(&value)?); + Ok(()) +} + +fn worker_request(message: T, token: &str) -> Result, tonic::Status> { + let mut request = node::authorized(message, token)?; + request.set_timeout(std::time::Duration::from_secs(5)); + Ok(request) +} diff --git a/desktop-core/src/managed_worker.rs b/desktop-core/src/managed_worker.rs new file mode 100644 index 00000000..203b79e3 --- /dev/null +++ b/desktop-core/src/managed_worker.rs @@ -0,0 +1,476 @@ +//! One trusted local profile. RPC supplies actions, never commands or paths. +use crate::operation_journal::{Entries, Journal}; +use crate::{ + gateway::{self, Gateway}, + node::proto::{WorkerCommand, WorkerOperation, WorkerState}, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + net::{IpAddr, SocketAddr}, + path::PathBuf, + process::Stdio, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + process::{Child, Command}, + sync::{mpsc, watch}, + task::JoinHandle, +}; +use tonic::Status; +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Profile { + pub schema_version: u32, + pub id: String, + pub model: String, + pub executable: PathBuf, + pub args: Vec, + pub endpoint: SocketAddr, + pub startup_timeout_ms: u64, + /// Verified adapter capabilities, never inferred from the model name. + #[serde(default = "default_capabilities")] + pub capabilities: Vec, +} +fn default_capabilities() -> Vec { + vec!["responses".into()] +} +impl Profile { + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != 1 + || self.id.is_empty() + || self.id.len() > 128 + || !self + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + || self.capabilities.is_empty() + || self.capabilities.len() > 16 + || !self.capabilities.iter().any(|c| c == "responses") + || self.capabilities.iter().any(|c| { + ![ + "responses", + "tools", + "reasoning", + "structured_output", + "image", + "audio", + "file", + ] + .contains(&c.as_str()) + }) + || self.model.is_empty() + || self.model.len() > 256 + || self.model.chars().any(char::is_control) + || !self.executable.is_absolute() + || !self.executable.is_file() + || self.args.len() > 256 + || self.args.iter().any(|a| a.len() > 4096 || a.contains('\0')) + || self.args.iter().map(String::len).sum::() > 32768 + || !self.endpoint.ip().is_loopback() + || self.endpoint.port() < 1024 + || !(100..=3600000).contains(&self.startup_timeout_ms) + { + return Err("invalid managed worker profile".into()); + } + Ok(()) + } + pub fn gateway(&self, token: String) -> Result { + self.validate()?; + let gateway = Gateway::with_token( + gateway::Config { + schema_version: 1, + listen: SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 0), + token_env: "UNUSED".into(), + queue_limit: 16, + queue_timeout_ms: 1000, + request_timeout_ms: 3600000, + groups: vec![gateway::Group { + id: self.id.clone(), + slots: 1, + available_bytes: 1, + }], + deployments: vec![gateway::Deployment { + id: self.id.clone(), + model: self.model.clone(), + endpoint: format!("http://{}", self.endpoint), + token_env: None, + group: self.id.clone(), + slots: 1, + request_bytes: 1, + capabilities: self.capabilities.clone(), + }], + aliases: BTreeMap::new(), + }, + token, + )?; + gateway.set_managed_ready(false); + Ok(gateway) + } +} +#[derive(Clone)] +pub struct Manager(Arc); +struct Owner { + tx: mpsc::Sender, + records: Records, + state: watch::Receiver, + task: JoinHandle<()>, + gateway: Gateway, +} +impl Drop for Owner { + fn drop(&mut self) { + self.task.abort(); + } +} +impl Manager { + pub fn new(profile: Profile, gateway: Gateway) -> Result { + Self::with_journal(profile, gateway, None) + } + pub fn with_journal( + profile: Profile, + gateway: Gateway, + path: Option<&std::path::Path>, + ) -> Result { + profile.validate()?; + gateway.set_managed_ready(false); + let (journal, entries) = if let Some(path) = path { + let (j, e) = Journal::open(path, &profile)?; + (Some(j), e) + } else { + (None, Entries::new()) + }; + let blocked = entries.values().any(|(_, r)| r.status == "indeterminate"); + let (state_tx, state) = watch::channel(WorkerState { + profile_id: profile.id.clone(), + model: profile.model.clone(), + phase: "stopped".into(), + pid: 0, + reason: String::new(), + }); + let records = Arc::new(Mutex::new(History { + entries, + journal, + blocked, + })); + let (tx, rx) = mpsc::channel(8); + let task = tokio::spawn(run(profile, gateway.clone(), state_tx, records.clone(), rx)); + Ok(Self(Arc::new(Owner { + tx, + records, + state, + task, + gateway, + }))) + } + pub fn durable(&self) -> bool { + self.0.records.lock().unwrap().journal.is_some() + } + pub fn state(&self) -> WorkerState { + let mut state = self.0.state.borrow().clone(); + if self.0.records.lock().unwrap().blocked { + state.phase = "failed".into(); + state.reason = "reconciliation_required".into(); + } + state + } + pub fn operation(&self, id: &str) -> Result { + self.0 + .records + .lock() + .unwrap() + .entries + .get( + &uuid::Uuid::parse_str(id) + .map_err(|_| Status::invalid_argument("operation UUID required"))? + .to_string(), + ) + .map(|(_, r)| r.clone()) + .ok_or_else(|| Status::not_found("unknown operation for this epoch")) + } + pub fn submit(&self, mut c: WorkerCommand) -> Result { + c.operation_id = uuid::Uuid::parse_str(&c.operation_id) + .map_err(|_| Status::invalid_argument("operation UUID required"))? + .to_string(); + if !(1..=2).contains(&c.action) + || c.drain_timeout_ms > 30000 + || (c.action == 1 && c.drain_timeout_ms != 0) + || c.expected_epoch.len() > 128 + { + return Err(Status::invalid_argument( + "invalid worker action or drain timeout", + )); + } + let mut records = self.0.records.lock().unwrap(); + if let Some((old, result)) = records.entries.get(&c.operation_id) { + return if old.action == c.action && old.drain_timeout_ms == c.drain_timeout_ms { + Ok(result.clone()) + } else { + Err(Status::already_exists( + "operation ID has different parameters", + )) + }; + } + if records.blocked { + return Err(Status::failed_precondition( + "journal reconciliation required", + )); + } + if records.entries.len() >= 256 { + return Err(Status::resource_exhausted( + "operation history full; reconcile before new epoch", + )); + } + let permit = self + .0 + .tx + .try_reserve() + .map_err(|_| Status::resource_exhausted("worker command queue full"))?; + let result = WorkerOperation { + operation_id: c.operation_id.clone(), + status: "accepted".into(), + reason: String::new(), + }; + if records.persist(&c, &result).is_err() { + self.0.gateway.set_managed_ready(false); + return Err(Status::internal("journal unavailable; reconcile operation")); + } + records + .entries + .insert(c.operation_id.clone(), (c.clone(), result.clone())); + permit.send(c); + Ok(result) + } +} +fn state(tx: &watch::Sender, phase: &str, pid: u32, reason: &str) { + tx.send_modify(|s| { + s.phase = phase.into(); + s.pid = pid; + s.reason = reason.into(); + }); +} +async fn healthy(client: &reqwest::Client, profile: &Profile) -> bool { + let Ok(response) = client + .get(format!("http://{}/health", profile.endpoint)) + .send() + .await + else { + return false; + }; + if !response.status().is_success() { + return false; + } + let mut response = response; + let mut data = vec![]; + loop { + match response.chunk().await { + Ok(Some(b)) if data.len() + b.len() <= 65536 => data.extend(b), + Ok(None) => break, + _ => return false, + } + } + let Ok(value) = serde_json::from_slice::(&data) else { + return false; + }; + value["status"] == "ok" && value["loaded"] == true && value["model"] == profile.model +} +async fn terminate(child: &mut Option) -> Result<(), &'static str> { + if let Some(c) = child { + c.start_kill().map_err(|_| "stop_failed")?; + tokio::time::timeout(Duration::from_secs(5), c.wait()) + .await + .map_err(|_| "stop_timeout")? + .map_err(|_| "wait_failed")?; + } + *child = None; + Ok(()) +} +async fn start( + profile: &Profile, + gateway: &Gateway, + tx: &watch::Sender, + child: &mut Option, + client: &reqwest::Client, +) -> Result<(), &'static str> { + if let Some(c) = child.as_mut() + && c.try_wait().map_err(|_| "wait_failed")?.is_some() + { + *child = None; + } + if child.is_some() { + return if tx.borrow().phase == "ready" { + Ok(()) + } else { + Err("stop_existing_owned_worker_first") + }; + } + gateway.set_managed_ready(false); + // Binding a temporary listener proves the endpoint was free before spawn. + let listener = tokio::net::TcpListener::bind(profile.endpoint) + .await + .map_err(|_| "endpoint_occupied")?; + drop(listener); + gateway.clear_response_owners(); + state(tx, "starting", 0, ""); + let mut command = Command::new(&profile.executable); + command.args(&profile.args).env_clear(); + for key in [ + "PATH", + "HOME", + "USER", + "TMPDIR", + "TEMP", + "TMP", + "SystemRoot", + "WINDIR", + "LD_LIBRARY_PATH", + "DYLD_LIBRARY_PATH", + "CUDA_VISIBLE_DEVICES", + ] { + if let Some(value) = std::env::var_os(key) { + // Even a nonstandard token variable must not leak through the allowlist. + if !gateway.matches_credential(&value.to_string_lossy()) { + command.env(key, value); + } + } + } + command + .env("STRATA_WORKER_ENDPOINT", profile.endpoint.to_string()) + .env("STRATA_WORKER_MODEL", &profile.model); + let process = command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "spawn_failed")?; + let pid = process.id().unwrap_or(0); + *child = Some(process); + state(tx, "starting", pid, ""); + let deadline = tokio::time::Instant::now() + Duration::from_millis(profile.startup_timeout_ms); + while tokio::time::Instant::now() < deadline { + if child + .as_mut() + .unwrap() + .try_wait() + .map_err(|_| "wait_failed")? + .is_some() + { + *child = None; + return Err("worker_exited"); + } + if healthy(client, profile).await + && child + .as_mut() + .unwrap() + .try_wait() + .map_err(|_| "wait_failed")? + .is_none() + { + gateway.set_managed_ready(true); + state(tx, "ready", pid, ""); + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + terminate(child).await?; + Err("startup_timeout") +} +async fn stop( + gateway: &Gateway, + tx: &watch::Sender, + child: &mut Option, + grace: u32, +) -> Result<(), &'static str> { + gateway.set_managed_ready(false); + state( + tx, + "draining", + child.as_ref().and_then(Child::id).unwrap_or(0), + "", + ); + let deadline = tokio::time::Instant::now() + Duration::from_millis(grace as u64); + while !gateway.idle() { + if tokio::time::Instant::now() >= deadline { + return Err("drain_timeout"); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + terminate(child).await?; + state(tx, "stopped", 0, ""); + Ok(()) +} +struct History { + entries: Entries, + journal: Option, + blocked: bool, +} +impl History { + fn persist(&mut self, c: &WorkerCommand, r: &WorkerOperation) -> Result<(), ()> { + if self.blocked { + return Err(()); + } + if let Some(j) = self.journal.as_mut() + && j.append(c, r).is_err() + { + self.blocked = true; + return Err(()); + } + Ok(()) + } + fn update(&mut self, c: &WorkerCommand, status: &str, reason: &str) -> Result<(), ()> { + let r = WorkerOperation { + operation_id: c.operation_id.clone(), + status: status.into(), + reason: reason.into(), + }; + if self.persist(c, &r).is_err() { + if let Some((_, old)) = self.entries.get_mut(&c.operation_id) { + old.status = "indeterminate".into(); + old.reason = "journal_unavailable".into(); + } + return Err(()); + } + self.entries.insert(c.operation_id.clone(), (c.clone(), r)); + Ok(()) + } +} +type Records = Arc>; +async fn run( + profile: Profile, + gateway: Gateway, + tx: watch::Sender, + records: Records, + mut rx: mpsc::Receiver, +) { + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_millis(500)) + .build() + .expect("HTTP client"); + let mut child: Option = None; + let mut tick = tokio::time::interval(Duration::from_millis(200)); + loop { + tokio::select! { + command=rx.recv()=>{ + let Some(command)=command else{break}; + if records.lock().unwrap().update(&command,"running","").is_err(){gateway.set_managed_ready(false);continue} + let result=if command.action==1 {start(&profile,&gateway,&tx,&mut child,&client).await}else{stop(&gateway,&tx,&mut child,command.drain_timeout_ms).await}; + if let Err(reason)=result {gateway.set_managed_ready(false);state(&tx,"failed",child.as_ref().and_then(Child::id).unwrap_or(0),reason);} + if records.lock().unwrap().update(&command,if result.is_ok(){"succeeded"}else{"failed"},result.err().unwrap_or("")).is_err(){gateway.set_managed_ready(false);} + }, + _=tick.tick()=>{ + if let Some(c)=child.as_mut() { + match c.try_wait() { + Ok(Some(_))=>{child=None;gateway.set_managed_ready(false);state(&tx,"failed",0,"worker_exited");}, + Err(_)=>{gateway.set_managed_ready(false);state(&tx,"failed",c.id().unwrap_or(0),"wait_failed");}, + Ok(None)=>{} + } + } + } + } + } + gateway.set_managed_ready(false); + let _ = terminate(&mut child).await; +} diff --git a/desktop-core/src/node.rs b/desktop-core/src/node.rs new file mode 100644 index 00000000..d9146338 --- /dev/null +++ b/desktop-core/src/node.rs @@ -0,0 +1,378 @@ +//! Shared local/SSH node boundary. Never retries an inference request. +use crate::{gateway::Gateway, hardware, planner}; +use axum::{Router, body::Body, http}; +use futures_util::{Stream, StreamExt}; +use std::{net::SocketAddr, pin::Pin, sync::Arc, time::Duration}; +use subtle::ConstantTimeEq; +use tokio::sync::{Mutex, Semaphore, watch}; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::{ + Request, Response, Status, + transport::{Channel, Endpoint, Server}, +}; +use tower::ServiceExt; + +pub mod proto { + tonic::include_proto!("strata.node.v1"); +} +use proto::{ + node_server::{Node, NodeServer}, + *, +}; +pub const MAX_MESSAGE: usize = 2 * 1024 * 1024 + 1024; +type RpcStream = Pin> + Send>>; + +#[derive(Clone)] +pub struct Agent(Arc); +struct Inner { + token: String, + router: Option, + manager: Option, + state: watch::Sender, + observers: Arc, + responses: Arc, + hardware: Mutex>, +} +impl Agent { + pub fn managed(token: String, profile: crate::managed_worker::Profile) -> Result { + Self::managed_journal(token, profile, None) + } + pub fn managed_journal( + token: String, + profile: crate::managed_worker::Profile, + path: Option<&std::path::Path>, + ) -> Result { + let gateway = profile.gateway(token.clone())?; + let manager = crate::managed_worker::Manager::with_journal(profile, gateway.clone(), path)?; + Self::build(token, Some(gateway), Some(manager)) + } + pub fn new(token: String, gateway: Option) -> Result { + Self::build(token, gateway, None) + } + fn build( + token: String, + gateway: Option, + manager: Option, + ) -> Result { + if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) { + return Err("node credential must be 32..4096 printable ASCII bytes".into()); + } + if gateway + .as_ref() + .is_some_and(|g| !g.matches_credential(&token)) + { + return Err("gateway and node credentials must match".into()); + } + let mut capabilities = vec!["hardware.v1".into(), "plan.v1".into(), "snapshot.v1".into()]; + if gateway.is_some() { + capabilities.push("responses.gateway.v1".into()); + } + if manager.as_ref().is_some_and(|m| m.durable()) { + capabilities.push("worker.journal.v1".into()); + } + if manager.is_some() { + capabilities.push("worker.lifecycle.v1".into()); + } + let (state, _) = watch::channel(Snapshot { + protocol_version: 1, + agent_epoch: uuid::Uuid::new_v4().to_string(), + sequence: 1, + capabilities, + active_responses: 0, + full_snapshot: true, + }); + Ok(Self(Arc::new(Inner { + token, + manager, + router: gateway.map(|g| g.router()), + state, + observers: Arc::new(Semaphore::new(16)), + responses: Arc::new(Semaphore::new(64)), + hardware: Mutex::new(None), + }))) + } + fn auth(&self, r: &Request) -> Result<(), Status> { + let token = r + .metadata() + .get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or(""); + if bool::from(token.as_bytes().ct_eq(self.0.token.as_bytes())) { + Ok(()) + } else { + Err(Status::unauthenticated("node credential required")) + } + } + async fn inventory(&self, refresh: bool) -> Result { + let mut cached = self + .0 + .hardware + .try_lock() + .map_err(|_| Status::resource_exhausted("inventory already in progress"))?; + if refresh + || cached + .as_ref() + .is_none_or(|(at, _)| at.elapsed() > Duration::from_secs(5)) + { + *cached = Some((std::time::Instant::now(), hardware::inventory().await)); + } + Ok(cached.as_ref().expect("inventory populated").1.clone()) + } + fn snapshot(&self) -> Snapshot { + self.0.state.borrow().clone() + } + fn count(&self, entering: bool) { + self.0.state.send_modify(|s| { + s.sequence += 1; + if entering { + s.active_responses += 1 + } else { + s.active_responses -= 1 + } + }); + } + async fn dispatch( + &self, + path: &str, + body: Vec, + ) -> Result { + let router = self + .0 + .router + .clone() + .ok_or_else(|| Status::failed_precondition("no inference gateway configured"))?; + let req = http::Request::builder() + .method(if path == "/v1/models" { "GET" } else { "POST" }) + .uri(path) + .header("authorization", format!("Bearer {}", self.0.token)) + .header("content-type", "application/json") + .body(Body::from(body)) + .map_err(|_| Status::internal("request construction failed"))?; + Ok(router + .oneshot(req) + .await + .expect("Router errors are Infallible")) + } + pub async fn serve( + self, + listener: tokio::net::TcpListener, + shutdown: impl Future + Send + 'static, + ) -> Result<(), Box> { + if !listener.local_addr()?.ip().is_loopback() { + return Err("node must bind loopback".into()); + } + Server::builder() + .max_concurrent_streams(128) + .add_service( + NodeServer::new(self) + .max_decoding_message_size(MAX_MESSAGE) + .max_encoding_message_size(MAX_MESSAGE), + ) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), shutdown) + .await?; + Ok(()) + } +} +struct Active(Agent); +impl Drop for Active { + fn drop(&mut self) { + self.0.count(false) + } +} +#[tonic::async_trait] +impl Node for Agent { + async fn worker_status(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + Ok(Response::new( + self.0 + .manager + .as_ref() + .ok_or_else(|| Status::failed_precondition("no managed profile"))? + .state(), + )) + } + async fn control_worker( + &self, + r: Request, + ) -> Result, Status> { + self.auth(&r)?; + if !r.get_ref().expected_epoch.is_empty() + && r.get_ref().expected_epoch != self.snapshot().agent_epoch + { + return Err(Status::failed_precondition("node epoch changed")); + } + self.0 + .manager + .as_ref() + .ok_or_else(|| Status::failed_precondition("no managed profile"))? + .submit(r.into_inner()) + .map(Response::new) + } + async fn operation_status( + &self, + r: Request, + ) -> Result, Status> { + self.auth(&r)?; + self.0 + .manager + .as_ref() + .ok_or_else(|| Status::failed_precondition("no managed profile"))? + .operation(&r.get_ref().operation_id) + .map(Response::new) + } + + async fn handshake(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + if r.get_ref().protocol_version != 1 { + return Err(Status::failed_precondition("unsupported protocol version")); + } + Ok(Response::new(self.snapshot())) + } + async fn hardware(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + let h = self.inventory(true).await?; + document(&h).map(Response::new) + } + async fn plan(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + if r.get_ref().json.len() > 1024 * 1024 { + return Err(Status::resource_exhausted("plan exceeds 1 MiB")); + } + let requirements = serde_json::from_slice(&r.get_ref().json) + .map_err(|_| Status::invalid_argument("invalid requirements"))?; + let h = self.inventory(false).await?; + let plan = planner::plan(&h, &requirements) + .map_err(|_| Status::invalid_argument("invalid memory requirements"))?; + document(&plan).map(Response::new) + } + type WatchStream = RpcStream; + async fn watch(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + if r.get_ref().agent_epoch.len() > 128 { + return Err(Status::invalid_argument("invalid cursor")); + } + let permit = self + .0 + .observers + .clone() + .try_acquire_owned() + .map_err(|_| Status::resource_exhausted("observer limit"))?; + let mut receiver = self.0.state.subscribe(); + // Full snapshot is authoritative even for future cursors or a replaced epoch. + let stream = async_stream::try_stream! { + let _permit = permit; + loop { + let snapshot = receiver.borrow_and_update().clone(); + yield snapshot; + if receiver.changed().await.is_err() {break} + } + }; + Ok(Response::new(Box::pin(stream))) + } + async fn models(&self, r: Request) -> Result, Status> { + self.auth(&r)?; + let response = self.dispatch("/v1/models", vec![]).await?; + if !response.status().is_success() { + return Err(Status::internal("gateway model listing failed")); + } + let json = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .map_err(|_| Status::resource_exhausted("model listing limit"))? + .to_vec(); + Ok(Response::new(JsonDocument { json })) + } + type RespondStream = RpcStream; + async fn respond( + &self, + r: Request, + ) -> Result, Status> { + self.auth(&r)?; + if self + .0 + .manager + .as_ref() + .is_some_and(|m| m.state().phase != "ready") + { + return Err(Status::unavailable("managed worker is not ready")); + } + if r.get_ref().json.len() > 2 * 1024 * 1024 { + return Err(Status::resource_exhausted("request exceeds 2 MiB")); + } + if self.0.router.is_none() { + return Err(Status::failed_precondition( + "no inference gateway configured", + )); + } + let permit = self + .0 + .responses + .clone() + .try_acquire_owned() + .map_err(|_| Status::resource_exhausted("response limit"))?; + self.count(true); + let active = Active(self.clone()); + let response = self.dispatch("/v1/responses", r.into_inner().json).await?; + let header = ResponseHeaders { + status: response.status().as_u16() as u32, + content_type: response + .headers() + .get("content-type") + .and_then(|s| s.to_str().ok()) + .unwrap_or("") + .into(), + retry_after: response + .headers() + .get("retry-after") + .and_then(|s| s.to_str().ok()) + .unwrap_or("") + .into(), + }; + let mut body = response.into_body().into_data_stream(); + let stream = async_stream::try_stream! { + let (_permit,_active) = (permit,active); + yield ResponseFrame{payload:Some(response_frame::Payload::Headers(header))}; + while let Some(data) = body.next().await { + let data = data.map_err(|_|Status::aborted("response interrupted; do not replay"))?; + for chunk in data.chunks(64*1024) { + yield ResponseFrame{payload:Some(response_frame::Payload::Data(chunk.to_vec()))}; + } + } + yield ResponseFrame{payload:Some(response_frame::Payload::End(Empty{}))}; + }; + Ok(Response::new(Box::pin(stream))) + } +} +fn document(value: &impl serde::Serialize) -> Result { + let json = serde_json::to_vec(value).map_err(|_| Status::internal("serialization failed"))?; + if json.len() > MAX_MESSAGE - 1024 { + return Err(Status::resource_exhausted("document limit")); + } + Ok(JsonDocument { json }) +} + +/// Same client for local listener or an SSH-forwarded local port. No inference retries. +pub async fn connect( + address: SocketAddr, +) -> Result, Box> { + if !address.ip().is_loopback() { + return Err("node connection must use loopback or SSH tunnel".into()); + } + let channel = Endpoint::from_shared(format!("http://{address}"))? + .connect_timeout(Duration::from_secs(5)) + .connect() + .await?; + Ok(proto::node_client::NodeClient::new(channel) + .max_decoding_message_size(MAX_MESSAGE) + .max_encoding_message_size(MAX_MESSAGE)) +} +pub fn authorized(message: T, token: &str) -> Result, Status> { + let mut r = Request::new(message); + r.metadata_mut().insert( + "authorization", + format!("Bearer {token}") + .parse() + .map_err(|_| Status::invalid_argument("invalid credential"))?, + ); + Ok(r) +} diff --git a/desktop-core/src/node_connection.rs b/desktop-core/src/node_connection.rs new file mode 100644 index 00000000..8440f475 --- /dev/null +++ b/desktop-core/src/node_connection.rs @@ -0,0 +1,288 @@ +//! Independently owned node observer. Reconnects state, never inference. +use crate::node::{ + self, + proto::{self, node_client::NodeClient}, +}; +use serde::Serialize; +use std::{ + net::SocketAddr, + sync::Arc, + time::{Duration, Instant}, +}; +use tokio::{sync::watch, task::JoinHandle}; +use tonic::{Code, Status, transport::Channel}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Connecting, + Ready, + Disconnected, + AuthError, + ProtocolError, +} +#[derive(Clone)] +struct State { + phase: Phase, + snapshot: Option, + heard: Option, + client: Option>, +} +#[derive(Clone, Debug, Serialize)] +pub struct StatusView { + pub phase: Phase, + pub fresh: bool, + pub agent_epoch: Option, + pub sequence: Option, + pub active_responses: Option, + pub capabilities: Vec, +} +struct Owner { + state: watch::Receiver, + task: JoinHandle<()>, + freshness: Duration, +} +impl Drop for Owner { + fn drop(&mut self) { + self.task.abort() + } +} +#[derive(Clone)] +pub struct Connection(Arc); +#[derive(Clone, Copy)] +pub struct Timing { + pub heartbeat: Duration, + pub deadline: Duration, + pub freshness: Duration, + pub retry_min: Duration, + pub retry_max: Duration, +} +impl Default for Timing { + fn default() -> Self { + Self { + heartbeat: Duration::from_secs(5), + deadline: Duration::from_secs(5), + freshness: Duration::from_secs(15), + retry_min: Duration::from_millis(200), + retry_max: Duration::from_secs(10), + } + } +} +impl Connection { + pub fn start(address: SocketAddr, token: String) -> Result { + Self::with_timing(address, token, Timing::default()) + } + pub fn with_timing(address: SocketAddr, token: String, timing: Timing) -> Result { + if !address.ip().is_loopback() + || token.len() < 32 + || token.len() > 4096 + || !token.bytes().all(|b| b.is_ascii_graphic()) + { + return Err("invalid node address or credential".into()); + } + if timing.heartbeat.is_zero() + || timing.deadline.is_zero() + || timing.retry_min.is_zero() + || timing.retry_max < timing.retry_min + || timing.freshness < timing.heartbeat + timing.deadline + { + return Err("invalid observer timing".into()); + } + let (tx, state) = watch::channel(State { + phase: Phase::Connecting, + snapshot: None, + heard: None, + client: None, + }); + let task = tokio::spawn(observe(address, token, timing, tx)); + Ok(Self(Arc::new(Owner { + state, + task, + freshness: timing.freshness, + }))) + } + pub fn status(&self) -> StatusView { + let s = self.0.state.borrow(); + let snapshot = s.snapshot.as_ref(); + let fresh = + s.phase == Phase::Ready && s.heard.is_some_and(|h| h.elapsed() < self.0.freshness); + StatusView { + phase: if s.phase == Phase::Ready && !fresh { + Phase::Disconnected + } else { + s.phase + }, + fresh, + agent_epoch: snapshot.map(|s| s.agent_epoch.clone()), + sequence: snapshot.map(|s| s.sequence), + active_responses: snapshot.map(|s| s.active_responses), + capabilities: snapshot.map(|s| s.capabilities.clone()).unwrap_or_default(), + } + } + pub fn client(&self, capability: &str) -> Result, Status> { + let s = self.0.state.borrow(); + if s.phase != Phase::Ready || !s.heard.is_some_and(|h| h.elapsed() < self.0.freshness) { + return Err(Status::unavailable("node state is not fresh")); + } + if !s + .snapshot + .as_ref() + .is_some_and(|s| s.capabilities.iter().any(|c| c == capability)) + { + return Err(Status::failed_precondition("node capability unavailable")); + } + s.client + .clone() + .ok_or_else(|| Status::unavailable("node disconnected")) + } + pub async fn wait_ready(&self, timeout: Duration) -> Result<(), Status> { + let mut state = self.0.state.clone(); + tokio::time::timeout(timeout, async { + loop { + match state.borrow().phase { + Phase::Ready => return Ok(()), + Phase::AuthError => { + return Err(Status::unauthenticated("node authentication failed")); + } + Phase::ProtocolError => { + return Err(Status::failed_precondition("node protocol incompatible")); + } + _ => {} + } + state + .changed() + .await + .map_err(|_| Status::unavailable("node observer stopped"))?; + } + }) + .await + .map_err(|_| Status::deadline_exceeded("node connect timeout"))? + } +} +fn terminal(code: Code) -> Option { + match code { + Code::Unauthenticated | Code::PermissionDenied => Some(Phase::AuthError), + Code::FailedPrecondition | Code::Unimplemented | Code::InvalidArgument => { + Some(Phase::ProtocolError) + } + _ => None, + } +} +fn validate(s: &proto::Snapshot, old: Option<&proto::Snapshot>) -> Result<(), Status> { + if s.protocol_version != 1 + || s.agent_epoch.is_empty() + || s.agent_epoch.len() > 128 + || s.sequence == 0 + || !s.full_snapshot + || s.capabilities.len() > 64 + || s.capabilities.iter().any(|s| s.len() > 128) + { + return Err(Status::failed_precondition("invalid node snapshot")); + } + if old.is_some_and(|o| o.agent_epoch == s.agent_epoch && o.sequence > s.sequence) { + return Err(Status::failed_precondition("node sequence regressed")); + } + Ok(()) +} +async fn hello( + client: &mut NodeClient, + token: &str, + timing: Timing, +) -> Result { + let mut r = node::authorized( + proto::Hello { + protocol_version: 1, + }, + token, + )?; + r.set_timeout(timing.deadline); + tokio::time::timeout(timing.deadline, client.handshake(r)) + .await + .map_err(|_| Status::deadline_exceeded("node heartbeat deadline"))? + .map(|s| s.into_inner()) +} +async fn session( + address: SocketAddr, + token: &str, + timing: Timing, + tx: &watch::Sender, +) -> Result<(), Status> { + let mut client = tokio::time::timeout(timing.deadline, node::connect(address)) + .await + .map_err(|_| Status::unavailable("node connect timeout"))? + .map_err(|_| Status::unavailable("node unavailable"))?; + let first = hello(&mut client, token, timing).await?; + let previous = tx.borrow().snapshot.clone(); + validate(&first, previous.as_ref())?; + let cursor = proto::Cursor { + agent_epoch: first.agent_epoch.clone(), + sequence: first.sequence, + }; + let r = node::authorized(cursor, token)?; + let mut stream = tokio::time::timeout(timing.deadline, client.watch(r)) + .await + .map_err(|_| Status::deadline_exceeded("node subscription timeout"))?? + .into_inner(); + // Do not open admission until the subscription itself supplies a full snapshot. + let mut current = tokio::time::timeout(timing.deadline, stream.message()) + .await + .map_err(|_| Status::deadline_exceeded("node snapshot timeout"))?? + .ok_or_else(|| Status::unavailable("node subscription closed"))?; + validate(¤t, Some(&first))?; + tx.send_replace(State { + phase: Phase::Ready, + snapshot: Some(current.clone()), + heard: Some(Instant::now()), + client: Some(client.clone()), + }); + let mut heartbeat = tokio::time::interval(timing.heartbeat); + heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + heartbeat.tick().await; + loop { + let (next, from_watch) = tokio::select! { + event=stream.message()=> (event?.ok_or_else(||Status::unavailable("node subscription closed"))?,true), + _=heartbeat.tick()=> (hello(&mut client,token,timing).await?,false), + }; + // A handshake can overtake a buffered watch event. Ignore old buffered state; + // the independent handshake must itself never go backwards in an epoch. + if from_watch && next.agent_epoch == current.agent_epoch && next.sequence < current.sequence + { + continue; + } + validate(&next, Some(¤t))?; + if next.agent_epoch != current.agent_epoch { + return Err(Status::unavailable("node epoch changed; resubscribe")); + } + current = next; + tx.send_replace(State { + phase: Phase::Ready, + snapshot: Some(current.clone()), + heard: Some(Instant::now()), + client: Some(client.clone()), + }); + } +} +async fn observe(address: SocketAddr, token: String, timing: Timing, tx: watch::Sender) { + let mut retry = timing.retry_min; + loop { + let started = Instant::now(); + let error = session(address, &token, timing, &tx) + .await + .expect_err("subscriptions end with status"); + let phase = terminal(error.code()).unwrap_or(Phase::Disconnected); + tx.send_modify(|s| { + s.phase = phase; + s.client = None; + s.heard = None; + }); + if matches!(phase, Phase::AuthError | Phase::ProtocolError) { + return; + } + if started.elapsed() >= timing.heartbeat { + retry = timing.retry_min; + } + let jitter = Duration::from_millis((uuid::Uuid::new_v4().as_u128() % 101) as u64); + tokio::time::sleep((retry + jitter).min(timing.retry_max)).await; + retry = (retry * 2).min(timing.retry_max); + } +} diff --git a/desktop-core/src/node_proxy.rs b/desktop-core/src/node_proxy.rs new file mode 100644 index 00000000..3df14dd5 --- /dev/null +++ b/desktop-core/src/node_proxy.rs @@ -0,0 +1,143 @@ +//! Harness-facing adapter to the common node gRPC protocol. +use crate::node::{ + self, + proto::{self, response_frame::Payload}, +}; +use crate::node_connection::Connection; +use axum::{ + Router, + body::{Body, Bytes}, + extract::{DefaultBodyLimit, State}, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, + routing::{get, post}, +}; +use std::{net::SocketAddr, time::Duration}; +use subtle::ConstantTimeEq; +#[derive(Clone)] +pub struct Proxy { + connection: Connection, + token: String, +} +impl Proxy { + pub async fn connect( + address: SocketAddr, + token: String, + ) -> Result> { + if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) { + return Err("invalid node credential".into()); + } + let connection = Connection::start(address, token.clone())?; + connection.wait_ready(Duration::from_secs(6)).await?; + connection.client("responses.gateway.v1")?; + Ok(Self { connection, token }) + } + pub fn router(self) -> Router { + Router::new() + .route("/v1/models", get(models)) + .route("/node/status", get(connection_status)) + .route("/v1/responses", post(respond)) + .layer(DefaultBodyLimit::max(2 * 1024 * 1024)) + .with_state(self) + } + fn auth(&self, h: &HeaderMap) -> bool { + h.get("authorization") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .is_some_and(|v| bool::from(v.as_bytes().ct_eq(self.token.as_bytes()))) + } +} +fn failure(status: StatusCode, kind: &str) -> Response { + ( + status, + axum::Json(serde_json::json!({"error":{"type":kind,"message":kind}})), + ) + .into_response() +} +async fn models(State(p): State, h: HeaderMap) -> Response { + if !p.auth(&h) { + return failure(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let Ok(mut client) = p.connection.client("responses.gateway.v1") else { + return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready"); + }; + let mut r = node::authorized(proto::Empty {}, &p.token).expect("validated credential"); + r.set_timeout(Duration::from_secs(5)); + match client.models(r).await { + Ok(v) => ([("content-type", "application/json")], v.into_inner().json).into_response(), + Err(_) => failure(StatusCode::BAD_GATEWAY, "node_unavailable"), + } +} +async fn respond(State(p): State, h: HeaderMap, body: Bytes) -> Response { + if !p.auth(&h) { + return failure(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let Ok(mut client) = p.connection.client("responses.gateway.v1") else { + return failure(StatusCode::SERVICE_UNAVAILABLE, "node_not_ready"); + }; + let mut request = node::authorized( + proto::ResponseRequest { + json: body.to_vec(), + }, + &p.token, + ) + .expect("validated credential"); + request.set_timeout(Duration::from_secs(86400)); + let mut stream = match client.respond(request).await { + Ok(r) => r.into_inner(), + Err(e) => { + return failure( + if e.code() == tonic::Code::ResourceExhausted { + StatusCode::TOO_MANY_REQUESTS + } else { + StatusCode::BAD_GATEWAY + }, + "node_request_failed", + ); + } + }; + let headers = match stream.message().await { + Ok(Some(proto::ResponseFrame { + payload: Some(Payload::Headers(h)), + })) => h, + _ => return failure(StatusCode::BAD_GATEWAY, "missing_node_headers"), + }; + let Ok(code) = u16::try_from(headers.status) + .ok() + .and_then(|s| StatusCode::from_u16(s).ok()) + .ok_or(()) + else { + return failure(StatusCode::BAD_GATEWAY, "invalid_node_status"); + }; + let body = async_stream::try_stream! { + let mut ended=false; + while let Some(frame)=stream.message().await.map_err(|_|std::io::Error::other("node stream interrupted; do not replay"))? { + match frame.payload { + Some(Payload::Data(bytes)) if !ended=>{yield Bytes::from(bytes);}, + Some(Payload::End(_)) if !ended=>ended=true, + _=>Err(std::io::Error::other("invalid node frame order"))?, + } + } + if !ended {Err(std::io::Error::other("missing node end marker"))?;} + }; + let mut response = Response::builder().status(code); + if !headers.content_type.is_empty() { + response = response.header("content-type", headers.content_type); + } + if !headers.retry_after.is_empty() { + response = response.header("retry-after", headers.retry_after); + } + response + .body(Body::from_stream(Box::pin(body) + as std::pin::Pin< + Box> + Send>, + >)) + .unwrap_or_else(|_| failure(StatusCode::BAD_GATEWAY, "invalid_node_headers")) +} + +async fn connection_status(State(p): State, h: HeaderMap) -> Response { + if !p.auth(&h) { + return failure(StatusCode::UNAUTHORIZED, "unauthorized"); + } + axum::Json(p.connection.status()).into_response() +} diff --git a/desktop-core/src/operation_journal.rs b/desktop-core/src/operation_journal.rs new file mode 100644 index 00000000..c0e5cb59 --- /dev/null +++ b/desktop-core/src/operation_journal.rs @@ -0,0 +1,348 @@ +//! Bounded operator-owned journal. Never replay a command after restart. +use crate::{ + managed_worker::Profile, + node::proto::{WorkerCommand, WorkerOperation}, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashMap, + fs::{File, OpenOptions}, + io::{Read, Write}, + path::Path, +}; + +const MAX_BYTES: u64 = 4 * 1024 * 1024; +pub(crate) type Entries = HashMap; +pub(crate) struct Journal { + file: File, + bytes: u64, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Header { + version: u32, + profile_sha256: String, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Entry { + id: String, + action: i32, + grace: u32, + epoch: String, + status: String, + reason: String, +} +impl Journal { + pub fn open(path: &Path, profile: &Profile) -> Result<(Self, Entries), String> { + if !path.is_absolute() { + return Err("journal path must be absolute".into()); + } + let parent = path.parent().ok_or("journal parent required")?; + let parent_meta = + std::fs::symlink_metadata(parent).map_err(|_| "journal parent must exist")?; + if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() { + return Err("journal parent must be a real private directory".into()); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if parent_meta.permissions().mode() & 0o077 != 0 { + return Err("journal directory must have mode 0700".into()); + } + } + if let Ok(m) = std::fs::symlink_metadata(path) + && (!m.is_file() || m.file_type().is_symlink()) + { + return Err("journal must be a regular file".into()); + } + let mut options = OpenOptions::new(); + options.create(true).read(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(path).map_err(|_| "cannot open journal")?; + file.try_lock() + .map_err(|_| "journal already owned or locking unavailable")?; + let meta = file.metadata().map_err(|_| "cannot inspect journal")?; + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + if meta.permissions().mode() & 0o077 != 0 || meta.nlink() != 1 { + return Err("journal must be private and not hardlinked".into()); + } + } + if meta.len() > MAX_BYTES { + return Err("journal size limit".into()); + } + let digest = Sha256::digest(serde_json::to_vec(profile).map_err(|_| "invalid profile")?) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let mut text = String::new(); + file.read_to_string(&mut text) + .map_err(|_| "unreadable journal")?; + let mut journal = Self { + file, + bytes: meta.len(), + }; + if text.is_empty() { + journal.line(&Header { + version: 1, + profile_sha256: digest, + })?; + #[cfg(unix)] + File::open(parent) + .and_then(|f| f.sync_all()) + .map_err(|_| "journal directory sync failed")?; + return Ok((journal, HashMap::new())); + } + if !text.ends_with('\n') { + return Err("incomplete journal; preserve for reconciliation".into()); + } + let mut lines = text.lines(); + let header: Header = serde_json::from_str(lines.next().ok_or("missing journal header")?) + .map_err(|_| "invalid journal header")?; + if header.version != 1 || header.profile_sha256 != digest { + return Err("journal profile/version mismatch".into()); + } + let mut records: Entries = HashMap::new(); + for line in lines { + let e: Entry = serde_json::from_str(line).map_err(|_| "invalid journal record")?; + if uuid::Uuid::parse_str(&e.id).is_err() + || e.epoch.len() > 128 + || e.reason.len() > 256 + || !(1..=2).contains(&e.action) + || e.grace > 30000 + || (e.action == 1 && e.grace != 0) + || ![ + "accepted", + "running", + "succeeded", + "failed", + "indeterminate", + ] + .contains(&e.status.as_str()) + { + return Err("invalid journal command".into()); + } + let c = WorkerCommand { + operation_id: e.id.clone(), + action: e.action, + drain_timeout_ms: e.grace, + expected_epoch: e.epoch, + }; + let r = WorkerOperation { + operation_id: e.id.clone(), + status: e.status, + reason: e.reason, + }; + if let Some((old, previous)) = records.get(&e.id) { + if old != &c + || !matches!( + (previous.status.as_str(), r.status.as_str()), + ("accepted", "running" | "indeterminate") + | ("running", "succeeded" | "failed" | "indeterminate") + ) + { + return Err("invalid journal transition".into()); + } + } else if r.status != "accepted" || records.len() >= 256 { + return Err("invalid journal history".into()); + } + records.insert(e.id, (c, r)); + } + for (c, r) in records.values_mut() { + if r.status == "accepted" || r.status == "running" { + r.status = "indeterminate".into(); + r.reason = "node_restarted".into(); + journal.append(c, r)?; + } + } + Ok((journal, records)) + } + fn line(&mut self, value: &impl Serialize) -> Result<(), String> { + let mut bytes = serde_json::to_vec(value).map_err(|_| "journal encoding failed")?; + bytes.push(b'\n'); + if self.bytes + bytes.len() as u64 > MAX_BYTES { + return Err("journal size limit".into()); + } + self.file + .write_all(&bytes) + .and_then(|_| self.file.sync_all()) + .map_err(|_| "journal sync failed")?; + self.bytes += bytes.len() as u64; + Ok(()) + } + pub fn append(&mut self, c: &WorkerCommand, r: &WorkerOperation) -> Result<(), String> { + self.line(&Entry { + id: c.operation_id.clone(), + action: c.action, + grace: c.drain_timeout_ms, + epoch: c.expected_epoch.clone(), + status: r.status.clone(), + reason: r.reason.clone(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + struct Temp(std::path::PathBuf); + impl Temp { + fn new() -> Self { + let p = std::env::temp_dir().join(format!("strata-journal-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&p).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + Self(p) + } + fn file(&self) -> std::path::PathBuf { + self.0.join("operations.jsonl") + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + fn profile() -> Profile { + Profile { + schema_version: 1, + id: "fixture".into(), + model: "synthetic".into(), + executable: std::env::current_exe().unwrap(), + args: vec![], + endpoint: "127.0.0.1:18999".parse().unwrap(), + startup_timeout_ms: 1000, + capabilities: vec!["responses".into()], + } + } + fn command() -> WorkerCommand { + WorkerCommand { + operation_id: uuid::Uuid::new_v4().to_string(), + action: 2, + drain_timeout_ms: 0, + expected_epoch: "original".into(), + } + } + fn result(c: &WorkerCommand, status: &str) -> WorkerOperation { + WorkerOperation { + operation_id: c.operation_id.clone(), + status: status.into(), + reason: String::new(), + } + } + #[test] + fn terminal_history_survives_and_incomplete_is_not_replayed() { + let t = Temp::new(); + let p = profile(); + let (mut j, _) = Journal::open(&t.file(), &p).unwrap(); + let completed = command(); + for s in ["accepted", "running", "succeeded"] { + j.append(&completed, &result(&completed, s)).unwrap(); + } + let interrupted = command(); + j.append(&interrupted, &result(&interrupted, "accepted")) + .unwrap(); + drop(j); + let (j, records) = Journal::open(&t.file(), &p).unwrap(); + assert_eq!(records[&completed.operation_id].1.status, "succeeded"); + assert_eq!(records[&interrupted.operation_id].1.status, "indeterminate"); + drop(j); + let (_, again) = Journal::open(&t.file(), &p).unwrap(); + assert_eq!(again[&interrupted.operation_id].1.reason, "node_restarted"); + } + #[test] + fn exclusive_lock_profile_fingerprint_and_torn_tail_fail_closed() { + let t = Temp::new(); + let p = profile(); + let (j, _) = Journal::open(&t.file(), &p).unwrap(); + assert!(Journal::open(&t.file(), &p).is_err()); + drop(j); + let mut other = p.clone(); + other.args.push("changed".into()); + assert!(Journal::open(&t.file(), &other).is_err()); + OpenOptions::new() + .append(true) + .open(t.file()) + .unwrap() + .write_all(b"{torn") + .unwrap(); + assert!(Journal::open(&t.file(), &p).is_err()); + assert!( + std::fs::read_to_string(t.file()) + .unwrap() + .ends_with("{torn") + ); + } + #[test] + fn impossible_history_and_limit_rejected() { + let t = Temp::new(); + let p = profile(); + let (mut j, _) = Journal::open(&t.file(), &p).unwrap(); + let c = command(); + j.append(&c, &result(&c, "succeeded")).unwrap(); + drop(j); + assert!(Journal::open(&t.file(), &p).is_err()); + let file = t.0.join("oversized"); + let f = File::create(&file).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + f.set_permissions(std::fs::Permissions::from_mode(0o600)) + .unwrap(); + } + f.set_len(MAX_BYTES + 1).unwrap(); + drop(f); + assert_eq!( + Journal::open(&file, &p).err().unwrap(), + "journal size limit" + ); + } + #[test] + fn append_failure_preserves_existing_evidence() { + let t = Temp::new(); + let p = profile(); + let (mut j, _) = Journal::open(&t.file(), &p).unwrap(); + let before = std::fs::read(t.file()).unwrap(); + j.bytes = MAX_BYTES; + let c = command(); + assert!(j.append(&c, &result(&c, "accepted")).is_err()); + drop(j); + assert_eq!(std::fs::read(t.file()).unwrap(), before); + assert!(Journal::open(&t.file(), &p).unwrap().1.is_empty()); + } + #[tokio::test] + async fn recovered_uncertainty_blocks_new_mutation_and_preserves_lookup() { + let t = Temp::new(); + let p = profile(); + let (mut j, _) = Journal::open(&t.file(), &p).unwrap(); + let c = command(); + j.append(&c, &result(&c, "accepted")).unwrap(); + drop(j); + let g = p + .gateway("synthetic-journal-token-32-bytes-value".into()) + .unwrap(); + let manager = crate::managed_worker::Manager::with_journal(p, g, Some(&t.file())).unwrap(); + assert_eq!( + manager.operation(&c.operation_id).unwrap().status, + "indeterminate" + ); + assert_eq!(manager.state().reason, "reconciliation_required"); + assert_eq!( + manager.submit(command()).unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + assert_eq!(manager.submit(c).unwrap().status, "indeterminate"); + drop(manager); + tokio::task::yield_now().await; + } +} diff --git a/desktop-core/src/planner.rs b/desktop-core/src/planner.rs new file mode 100644 index 00000000..eec78229 --- /dev/null +++ b/desktop-core/src/planner.rs @@ -0,0 +1,212 @@ +use crate::hardware::{Hardware, MemoryKind}; +use serde::{Deserialize, Serialize}; + +/// Runtime allocations supplied by a model/backend adapter, NOT archive size. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Requirements { + pub schema_version: u32, + pub model: String, + pub context_tokens: u64, + pub concurrent_requests: u32, + pub weights_bytes: u64, + pub kv_bytes_per_token_per_request: u64, + pub workspace_bytes: u64, + pub load_scratch_bytes: u64, + pub host_overhead_bytes: u64, + pub host_reserve_bytes: u64, + pub device_reserve_bytes: u64, + /// Explicitly model a worker that retains a complete host weight copy. + pub retains_host_weights: bool, + /// Only true when the selected backend supports this weight split. + pub allow_weight_offload: bool, +} + +#[derive(Debug, Serialize)] +pub struct Candidate { + pub device: String, + pub placement: String, + pub device_weight_percent: u32, + pub host_peak_bytes: u64, + pub device_peak_bytes: u64, + pub host_budget_bytes: Option, + pub device_budget_bytes: Option, + pub fit: String, + pub reasons: Vec, +} + +#[derive(Debug, Serialize)] +pub struct Plan { + pub schema_version: u32, + pub model: String, + pub context_tokens: u64, + pub concurrent_requests: u32, + pub evidence: &'static str, + pub execution_compatibility: &'static str, + pub warnings: Vec, + pub candidates: Vec, +} + +fn sum(values: &[u64]) -> Result { + values.iter().try_fold(0u64, |s, n| { + s.checked_add(*n).ok_or("memory size overflow".into()) + }) +} + +pub fn plan(h: &Hardware, r: &Requirements) -> Result { + if h.schema_version != 1 || r.schema_version != 1 { + return Err("unsupported schema version".into()); + } + if r.model.trim().is_empty() + || r.weights_bytes == 0 + || r.context_tokens == 0 + || r.concurrent_requests == 0 + { + return Err("model, weights, context and concurrency must be nonzero".into()); + } + for m in std::iter::once(&h.memory).chain(h.accelerators.iter().map(|g| &g.memory)) { + if let (Some(t), Some(a)) = (m.total_bytes, m.available_bytes) + && a > t + { + return Err("available memory exceeds total".into()); + } + } + let kv = r + .kv_bytes_per_token_per_request + .checked_mul(r.context_tokens) + .and_then(|v| v.checked_mul(u64::from(r.concurrent_requests))) + .ok_or("KV size overflow")?; + let runtime = sum(&[kv, r.workspace_bytes, r.load_scratch_bytes])?; + let host_budget = h + .memory + .available_bytes + .map(|n| n.saturating_sub(r.host_reserve_bytes)); + let cpu_peak = sum(&[r.weights_bytes, runtime, r.host_overhead_bytes])?; + let mut candidates = vec![candidate( + "cpu", + "host", + 0, + cpu_peak, + 0, + host_budget, + None, + false, + )]; + for g in &h.accelerators { + let device_budget = g + .memory + .available_bytes + .map(|n| n.saturating_sub(r.device_reserve_bytes)); + if g.memory_kind != MemoryKind::Dedicated { + // Shared weights/runtime are counted ONCE in host_peak; also enforce device ceiling. + let shared_peak = sum(&[ + cpu_peak, + if r.retains_host_weights { + r.weights_bytes + } else { + 0 + }, + ])?; + let mut c = candidate( + &g.id, + "shared", + 100, + shared_peak, + sum(&[r.weights_bytes, runtime])?, + host_budget, + device_budget, + true, + ); + if g.memory_kind == MemoryKind::Unknown { + c.fit = "unknown".into(); + c.reasons.push("memory topology unknown".into()); + } + candidates.push(c); + continue; + } + let splits: &[u32] = if r.allow_weight_offload { + &[100, 75, 50, 25] + } else { + &[100] + }; + for &percent in splits { + let device_weights = + ((u128::from(r.weights_bytes) * u128::from(percent)).div_ceil(100)) as u64; + let host_weights = if r.retains_host_weights { + r.weights_bytes + } else { + r.weights_bytes - device_weights + }; + // Conservative: reserve scratch on host too for upload/decode staging. + let host_peak = sum(&[host_weights, r.host_overhead_bytes, r.load_scratch_bytes])?; + let device_peak = sum(&[device_weights, runtime])?; + candidates.push(candidate( + &g.id, + if percent == 100 { "device" } else { "offload" }, + percent, + host_peak, + device_peak, + host_budget, + device_budget, + true, + )); + } + } + Ok(Plan {schema_version:1, model:r.model.clone(),context_tokens:r.context_tokens, + concurrent_requests:r.concurrent_requests,evidence:"estimated",execution_compatibility:"not_validated", + warnings: vec!["Memory fit does not establish model/backend compatibility, quality or speed.".into(), + "Requirements must describe runtime allocations; compressed file size is insufficient. Recheck available memory before load.".into()], candidates}) +} + +#[allow(clippy::too_many_arguments)] +fn candidate( + device: &str, + placement: &str, + percent: u32, + host_peak: u64, + device_peak: u64, + host_budget: Option, + device_budget: Option, + needs_device: bool, +) -> Candidate { + let mut reasons = Vec::new(); + let mut unknown = false; + let mut insufficient = false; + for (label, needed, budget) in [ + ("host", host_peak, host_budget), + ("device", device_peak, device_budget), + ] { + if label == "device" && !needs_device { + continue; + } + match budget { + None => { + unknown = true; + reasons.push(format!("{label} available budget unknown")); + } + Some(n) if needed > n => { + insufficient = true; + reasons.push(format!("{label} needs {} more bytes", needed - n)); + } + _ => {} + } + } + Candidate { + device: device.into(), + placement: placement.into(), + device_weight_percent: percent, + host_peak_bytes: host_peak, + device_peak_bytes: device_peak, + host_budget_bytes: host_budget, + device_budget_bytes: device_budget, + fit: if insufficient { + "insufficient" + } else if unknown { + "unknown" + } else { + "fits_estimate" + } + .into(), + reasons, + } +} diff --git a/desktop-core/src/pool.rs b/desktop-core/src/pool.rs new file mode 100644 index 00000000..c1a7ffb4 --- /dev/null +++ b/desktop-core/src/pool.rs @@ -0,0 +1,240 @@ +//! In-memory admission only: a lease covers the entire upstream request/stream. +use serde::Serialize; +use std::{ + collections::{HashMap, VecDeque}, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{sync::oneshot, time::Instant}; + +#[derive(Clone, Debug)] +pub struct Worker { + pub id: String, + pub group: String, + pub slots: usize, + /// Adapter-supplied upper bound on incremental memory per active request. + pub request_bytes: u64, +} +#[derive(Clone, Debug)] +pub struct ResourceGroup { + pub id: String, + pub slots: usize, + /// Available budget AFTER resident model weights and safety reserve. + pub available_bytes: u64, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdmissionError { + Invalid, + Full, + Expired, + Closed, +} +#[derive(Clone)] +pub struct Pool(Arc>); +struct State { + workers: Vec, + groups: HashMap, + ready: Vec, + pending: VecDeque, + active: HashMap, + next_id: u64, + queue_limit: usize, +} +struct Pending { + id: u64, + eligible: Vec, + deadline: Instant, + tx: oneshot::Sender>, +} +/// Dropping an acquisition future OR its successful lease releases its reservation. +pub struct Lease { + pool: Pool, + id: u64, + worker: usize, +} +impl Lease { + pub fn worker(&self) -> usize { + self.worker + } +} +impl Drop for Lease { + fn drop(&mut self) { + let mut s = self.pool.0.lock().unwrap(); + s.pending.retain(|p| p.id != self.id); + s.active.remove(&self.id); + s.dispatch(); + } +} +#[derive(Debug, Serialize)] +pub struct Snapshot { + pub queued: usize, + pub active: usize, + pub workers: Vec, +} +#[derive(Debug, Serialize)] +pub struct WorkerStatus { + pub id: String, + pub ready: bool, + pub active: usize, + pub slots: usize, +} + +impl Pool { + pub fn new( + workers: Vec, + groups: Vec, + queue_limit: usize, + ) -> Result { + if workers.is_empty() + || workers.len() > 256 + || groups.is_empty() + || queue_limit == 0 + || queue_limit > 4096 + { + return Err(AdmissionError::Invalid); + } + let count = groups.len(); + let groups: HashMap<_, _> = groups.into_iter().map(|g| (g.id.clone(), g)).collect(); + if groups.len() != count + || groups + .values() + .any(|g| g.id.is_empty() || g.slots == 0 || g.slots > 4096) + { + return Err(AdmissionError::Invalid); + } + let mut ids = std::collections::HashSet::new(); + for w in &workers { + if w.id.is_empty() + || !ids.insert(&w.id) + || w.slots == 0 + || w.slots > 4096 + || !groups + .get(&w.group) + .is_some_and(|g| w.request_bytes <= g.available_bytes) + { + return Err(AdmissionError::Invalid); + } + } + Ok(Self(Arc::new(Mutex::new(State { + ready: vec![true; workers.len()], + workers, + groups, + pending: VecDeque::new(), + active: HashMap::new(), + next_id: 0, + queue_limit, + })))) + } + + pub async fn acquire( + &self, + eligible: Vec, + wait: Duration, + ) -> Result { + let deadline = Instant::now() + .checked_add(wait) + .ok_or(AdmissionError::Invalid)?; + let (tx, rx) = oneshot::channel(); + let mut lease = { + let mut s = self.0.lock().unwrap(); + if eligible.is_empty() || eligible.iter().any(|i| *i >= s.workers.len()) { + return Err(AdmissionError::Invalid); + } + s.dispatch(); + if s.pending.len() >= s.queue_limit { + return Err(AdmissionError::Full); + } + let id = s.next_id.checked_add(1).ok_or(AdmissionError::Closed)?; + s.next_id = id; + s.pending.push_back(Pending { + id, + eligible, + deadline, + tx, + }); + s.dispatch(); + Lease { + pool: self.clone(), + id, + worker: 0, + } + }; + // The guard exists before the first await, including the dispatch/cancel race. + let worker = tokio::time::timeout_at(deadline, rx) + .await + .map_err(|_| AdmissionError::Expired)? + .map_err(|_| AdmissionError::Closed)??; + lease.worker = worker; + Ok(lease) + } + + pub fn set_ready(&self, worker: usize, ready: bool) -> Result<(), AdmissionError> { + let mut s = self.0.lock().unwrap(); + *s.ready.get_mut(worker).ok_or(AdmissionError::Invalid)? = ready; + s.dispatch(); + Ok(()) + } + pub fn snapshot(&self) -> Snapshot { + let s = self.0.lock().unwrap(); + Snapshot { + queued: s.pending.len(), + active: s.active.len(), + workers: s + .workers + .iter() + .enumerate() + .map(|(i, w)| WorkerStatus { + id: w.id.clone(), + ready: s.ready[i], + slots: w.slots, + active: s.active.values().filter(|v| **v == i).count(), + }) + .collect(), + } + } +} +impl State { + fn available(&self, i: usize) -> bool { + let w = &self.workers[i]; + if !self.ready[i] || self.active.values().filter(|v| **v == i).count() >= w.slots { + return false; + } + let group = &self.groups[&w.group]; + let active: Vec<_> = self + .active + .values() + .map(|j| &self.workers[*j]) + .filter(|v| v.group == w.group) + .collect(); + let bytes: u128 = active.iter().map(|v| u128::from(v.request_bytes)).sum(); + active.len() < group.slots + && bytes + u128::from(w.request_bytes) <= u128::from(group.available_bytes) + } + fn dispatch(&mut self) { + let mut i = 0; + while i < self.pending.len() { + let p = &self.pending[i]; + if p.tx.is_closed() || p.deadline <= Instant::now() { + let p = self.pending.remove(i).unwrap(); + let _ = p.tx.send(Err(AdmissionError::Expired)); + continue; + } + // Oldest eligible request first; unrelated blocked requests do not stall free workers. + let worker = p + .eligible + .iter() + .copied() + .filter(|j| self.available(*j)) + .min_by_key(|j| self.active.values().filter(|v| **v == *j).count()); + if let Some(worker) = worker { + let p = self.pending.remove(i).unwrap(); + self.active.insert(p.id, worker); + if p.tx.send(Ok(worker)).is_err() { + self.active.remove(&p.id); + } + } else { + i += 1; + } + } + } +} diff --git a/desktop-core/src/remote.rs b/desktop-core/src/remote.rs new file mode 100644 index 00000000..76e10e73 --- /dev/null +++ b/desktop-core/src/remote.rs @@ -0,0 +1,393 @@ +//! OpenSSH transport preflight. Does not install or start anything on the host. +use crate::hardware::{Hardware, Memory, parse_nvidia}; +use serde::{Deserialize, Serialize}; +use std::{ + path::Path, + process::Stdio, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, + process::Command, +}; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SshProfile { + pub schema_version: u32, + pub id: String, + pub host: String, + pub user: Option, + pub port: Option, + /// Reference only. Private key contents never enter the profile or protocol. + pub identity_file: Option, +} +#[derive(Debug, Serialize)] +pub struct RemoteInventory { + pub schema_version: u32, + pub node_id: String, + pub transport: &'static str, + pub hardware: Hardware, + /// SSH user's current/home filesystem; recheck actual model destination before install. + pub home_disk_available_bytes: Option, +} +impl SshProfile { + pub fn arguments(&self) -> Result, String> { + let ident = |s: &str| { + !s.is_empty() + && s.len() <= 128 + && s.as_bytes()[0].is_ascii_alphanumeric() + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) + }; + if self.schema_version != 1 + || !ident(&self.id) + || self.host.is_empty() + || self.host.len() > 253 + || !self.host.as_bytes()[0].is_ascii_alphanumeric() + || !self + .host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-:".contains(&b)) + || self.user.as_ref().is_some_and(|s| !ident(s)) + || self.port == Some(0) + { + return Err("invalid SSH profile".into()); + } + let mut args = vec![ + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ForwardAgent=no", + "-o", + "ClearAllForwardings=yes", + "-o", + "PermitLocalCommand=no", + "-o", + "ConnectTimeout=8", + ] + .into_iter() + .map(str::to_owned) + .collect::>(); + if let Some(port) = self.port { + args.extend(["-p".into(), port.to_string()]); + } + if let Some(user) = &self.user { + args.extend(["-l".into(), user.clone()]); + } + if let Some(path) = &self.identity_file { + if !Path::new(path).is_absolute() + || path.len() > 4096 + || path.chars().any(char::is_control) + { + return Err("SSH identity must be an absolute key-file reference".into()); + } + args.extend(["-i".into(), path.clone()]); + } + args.extend(["--".into(), self.host.clone(), "sh".into(), "-s".into()]); + Ok(args) + } +} +// Static stdin only: no profile values interpolated into this remote shell program. +const PROBE: &str = r#"export LC_ALL=C +printf 'os\t'; uname -s +if [ "$(uname -s)" != Linux ]; then exit 0; fi +printf 'arch\t'; uname -m +printf 'cpus\t'; getconf _NPROCESSORS_ONLN +awk -F: '/^model name/ {sub(/^[ \t]+/, "", $2); print "cpu\t" $2; exit}' /proc/cpuinfo +awk -F: '/^(flags|Features)[ \t]*:/ {print "features\t" $2; exit}' /proc/cpuinfo +awk '/^MemTotal:/ {print "total_kib\t" $2} /^MemAvailable:/ {print "available_kib\t" $2}' /proc/meminfo +df -Pk . 2>/dev/null | awk 'NR==2 {print "disk_available_kib\t" $4}' +if command -v nvidia-smi >/dev/null 2>&1; then + nvidia-smi --query-gpu=name,memory.total,memory.free,driver_version --format=csv,noheader,nounits 2>/dev/null | sed 's/^/gpu\t/' +fi +printf 'end\tok\n' +"#; +async fn bounded(reader: impl AsyncRead + Unpin) -> Result, String> { + let mut data = Vec::new(); + reader + .take(128 * 1024 + 1) + .read_to_end(&mut data) + .await + .map_err(|_| "SSH read failed")?; + if data.len() > 128 * 1024 { + return Err("SSH output limit exceeded".into()); + } + Ok(data) +} +pub async fn inspect(profile: &SshProfile) -> Result { + inspect_with_program(profile, "ssh", Duration::from_secs(15)).await +} +async fn inspect_with_program( + profile: &SshProfile, + program: &str, + limit: Duration, +) -> Result { + let args = profile.arguments()?; + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "OpenSSH is unavailable")?; + let mut input = child.stdin.take().ok_or("SSH stdin missing")?; + let output = child.stdout.take().ok_or("SSH stdout missing")?; + let error = child.stderr.take().ok_or("SSH stderr missing")?; + let run = async { + let write = async move { + input + .write_all(PROBE.as_bytes()) + .await + .map_err(|_| "SSH input failed".to_string())?; + drop(input); // Close the pipe: remote `sh -s` must receive EOF. + Ok::<(), String>(()) + }; + let (_, output, error) = tokio::try_join!(write, bounded(output), bounded(error))?; + let status = child.wait().await.map_err(|_| "SSH wait failed")?; + if !status.success() { + let error = String::from_utf8_lossy(&error); + return Err(if error.contains("Host key verification failed") + || error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED") + { + "SSH host identity is not trusted or has changed" + } else if error.contains("Permission denied") { + "SSH authentication failed" + } else { + "SSH preflight failed; verify connection and host configuration" + } + .to_string()); + } + parse( + profile, + &String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?, + ) + }; + match tokio::time::timeout(limit, run).await { + Ok(Ok(result)) => Ok(result), + failure => { + let _ = child.kill().await; + match failure { + Ok(Err(e)) => Err(e), + _ => Err("SSH preflight timed out".into()), + } + } + } +} +fn parse(profile: &SshProfile, data: &str) -> Result { + let mut fields = std::collections::HashMap::new(); + let mut gpus = Vec::new(); + for line in data.lines() { + let Some((key, value)) = line.split_once('\t') else { + return Err("unexpected SSH probe output".into()); + }; + if key == "gpu" { + gpus.push(value); + } else if fields.insert(key, value).is_some() { + return Err("duplicate SSH probe field".into()); + } + } + if fields.get("os") != Some(&"Linux") { + return Err("remote worker preflight currently supports Linux only".into()); + } + if fields.get("end") != Some(&"ok") { + return Err("incomplete SSH probe".into()); + } + let kib = |key: &str| { + fields + .get(key) + .and_then(|s| s.parse::().ok()) + .and_then(|n| n.checked_mul(1024)) + }; + let memory = Memory { + total_bytes: kib("total_kib"), + available_bytes: kib("available_kib"), + }; + if memory.total_bytes.is_none_or(|n| n == 0) + || matches!((memory.total_bytes,memory.available_bytes),(Some(t),Some(a)) if a>t) + { + return Err("invalid remote RAM inventory".into()); + } + let architecture = match fields.get("arch").copied() { + Some("x86_64") => "x86_64", + Some("aarch64" | "arm64") => "aarch64", + _ => return Err("unsupported remote CPU architecture".into()), + }; + let cpus = fields + .get("cpus") + .and_then(|s| s.parse::().ok()) + .filter(|n| *n > 0) + .ok_or("invalid remote CPU count")?; + let flags = fields + .get("features") + .copied() + .unwrap_or("") + .split_whitespace() + .collect::>(); + let cpu_features = [ + ("avx2", "avx2"), + ("avx512f", "avx512f"), + ("fma", "fma"), + ("asimd", "neon"), + ("asimddp", "dotprod"), + ] + .into_iter() + .filter(|(flag, _)| flags.contains(flag)) + .map(|(_, name)| name.to_owned()) + .collect(); + let mut warnings = + vec!["NPU and inference-provider support require a separate capability check.".into()]; + let accelerators = match parse_nvidia(&gpus.join("\n")) { + Ok(g) => g, + Err(e) => { + warnings.push(e); + vec![] + } + }; + if accelerators.is_empty() { + warnings.push("No NVIDIA inventory; other accelerators are not probed yet.".into()); + } + Ok(RemoteInventory { + schema_version: 1, + node_id: profile.id.clone(), + transport: "ssh", + home_disk_available_bytes: kib("disk_available_kib"), + hardware: Hardware { + schema_version: 1, + sampled_at_unix_ms: SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|t| t.as_millis() as u64) + .unwrap_or(0), + os: "linux".into(), + architecture: architecture.into(), + cpu_name: fields.get("cpu").copied().unwrap_or("unknown").into(), + logical_cpus: cpus, + cpu_features, + memory, + accelerators, + warnings, + }, + }) +} +#[cfg(test)] +mod tests { + use super::*; + fn profile() -> SshProfile { + SshProfile { + schema_version: 1, + id: "server-a".into(), + host: "gpu-server".into(), + user: None, + port: None, + identity_file: None, + } + } + #[test] + fn hostile_options_and_secrets_are_not_configuration() { + for host in [ + "-oProxyCommand=evil", + "user@host", + "host;touch x", + "host\ncommand", + "$(id)", + ] { + let mut p = profile(); + p.host = host.into(); + assert!(p.arguments().is_err()); + } + let mut p = profile(); + p.user = Some("-root".into()); + assert!(p.arguments().is_err()); + p = profile(); + p.identity_file = Some("relative-key".into()); + assert!(p.arguments().is_err()); + assert!( + serde_json::from_str::( + r#"{"schema_version":1,"id":"a","host":"h","password":"secret"}"# + ) + .is_err() + ); + let args = profile().arguments().unwrap(); + assert!(args.contains(&"StrictHostKeyChecking=yes".into())); + assert!(args.contains(&"ForwardAgent=no".into())); + } + #[test] + fn parses_server_memory_and_unknown_accelerators() { + let data = "os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\ntotal_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n"; + let r = parse(&profile(), data).unwrap(); + assert_eq!( + r.hardware.memory.available_bytes, + Some(16 * 1024 * 1024 * 1024) + ); + assert!(r.hardware.accelerators.is_empty()); + assert_eq!(r.home_disk_available_bytes, Some(1024 * 1024)); + assert!(parse(&profile(), &data.replace("Linux", "Darwin")).is_err()); + assert!(parse(&profile(), &data.replace("end\tok\n", "")).is_err()); + assert!( + parse( + &profile(), + &data.replace("16777216", "9999999999999999999999") + ) + .unwrap() + .hardware + .memory + .available_bytes + .is_none() + ); + } + #[tokio::test] + async fn probe_output_is_bounded() { + assert!(bounded(&vec![b'x'; 128 * 1024 + 1][..]).await.is_err()); + } + + #[cfg(unix)] + #[tokio::test] + async fn ssh_stdin_closes_and_hung_probe_times_out() { + use std::{io::Write, os::unix::fs::PermissionsExt}; + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let path = + Temp(std::env::temp_dir().join(format!("strata-ssh-test-{}", std::process::id()))); + let script = "#!/bin/sh\ncat >/dev/null\nprintf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n"; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path.0) + .unwrap(); + file.write_all(script.as_bytes()).unwrap(); + drop(file); + std::fs::set_permissions(&path.0, std::fs::Permissions::from_mode(0o700)).unwrap(); + let p = path.0.to_str().unwrap(); + assert!( + inspect_with_program(&profile(), p, Duration::from_secs(2)) + .await + .is_ok() + ); + std::fs::write(&path.0, "#!/bin/sh\nexec sleep 5\n").unwrap(); + assert_eq!( + inspect_with_program(&profile(), p, Duration::from_millis(20)) + .await + .unwrap_err(), + "SSH preflight timed out" + ); + std::fs::write( + &path.0, + "#!/bin/sh\ncat >/dev/null\necho 'Host key verification failed' >&2\nexit 255\n", + ) + .unwrap(); + assert_eq!( + inspect_with_program(&profile(), p, Duration::from_secs(2)) + .await + .unwrap_err(), + "SSH host identity is not trusted or has changed" + ); + } +} diff --git a/desktop-core/src/remote_install.rs b/desktop-core/src/remote_install.rs new file mode 100644 index 00000000..f2ad1cfe --- /dev/null +++ b/desktop-core/src/remote_install.rs @@ -0,0 +1,369 @@ +//! Digest-pinned, per-user installation. Does not launch or replace serving models. +use crate::{managed_worker::Profile, remote::SshProfile}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::File, + io::{Read, Seek, SeekFrom}, + path::{Path, PathBuf}, + process::Stdio, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + process::Command, +}; + +const SCRIPT: &str = include_str!("remote_install.sh"); +const MAX_BINARY: u64 = 256 * 1024 * 1024; +const MAX_PROFILE: u64 = 1024 * 1024; +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Target { + pub ssh: SshProfile, + pub slot: String, + pub os: String, + pub arch: String, +} +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Install { + pub schema_version: u32, + pub target: Target, + pub runtime: PathBuf, + pub runtime_sha256: String, + pub worker_profile: PathBuf, +} +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Activate { + pub schema_version: u32, + pub target: Target, + pub runtime_sha256: String, + pub profile_sha256: String, +} +#[derive(Serialize)] +pub struct Receipt { + pub schema_version: u32, + pub slot: String, + pub release: String, + pub runtime_sha256: String, + pub profile_sha256: String, + pub outcome: String, + pub serving_changed: bool, +} +fn to_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} +fn hex_hash(bytes: &[u8]) -> String { + to_hex(&Sha256::digest(bytes)) +} +fn valid_hash(s: &str) -> bool { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +impl Target { + fn platform(&self) -> Result<(&'static str, &'static str), String> { + if self.slot.is_empty() + || self.slot.len() > 64 + || !self + .slot + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) + { + return Err("invalid installation slot".into()); + } + let os = match self.os.as_str() { + "linux" => "Linux", + "macos" => "Darwin", + _ => return Err("unsupported remote installation OS".into()), + }; + let arch = match (os, self.arch.as_str()) { + (_, "x86_64") => "x86_64", + ("Linux", "aarch64") => "aarch64", + ("Darwin", "aarch64") => "arm64", + _ => return Err("unsupported installation architecture".into()), + }; + Ok((os, arch)) + } +} +fn regular(path: &Path, limit: u64) -> Result { + if !path.is_absolute() { + return Err("installation files must use absolute paths".into()); + } + let file = File::open(path).map_err(|_| "cannot open installation file")?; + let meta = file + .metadata() + .map_err(|_| "cannot inspect installation file")?; + if !meta.is_file() || meta.len() == 0 || meta.len() > limit { + return Err("installation file size/type is invalid".into()); + } + Ok(file) +} +struct Prepared { + binary: File, + size: u64, + profile: Vec, +} +fn prepare(config: &Install) -> Result { + let mut binary = regular(&config.runtime, MAX_BINARY)?; + let size = binary + .metadata() + .map_err(|_| "cannot inspect runtime")? + .len(); + let mut digest = Sha256::new(); + let mut buf = [0u8; 65536]; + let mut count = 0; + loop { + let n = binary.read(&mut buf).map_err(|_| "cannot read runtime")?; + if n == 0 { + break; + } + count += n as u64; + if count > MAX_BINARY { + return Err("runtime grew beyond size limit".into()); + } + digest.update(&buf[..n]); + } + if count != size || to_hex(&digest.finalize()) != config.runtime_sha256 { + return Err("runtime SHA-256 mismatch".into()); + } + binary + .seek(SeekFrom::Start(0)) + .map_err(|_| "cannot rewind runtime")?; + let mut profile = Vec::new(); + regular(&config.worker_profile, MAX_PROFILE)? + .take(MAX_PROFILE + 1) + .read_to_end(&mut profile) + .map_err(|_| "cannot read worker profile")?; + if profile.len() as u64 > MAX_PROFILE { + return Err("worker profile too large".into()); + } + // Paths belong to the target OS: validate semantic/path constraints there. + serde_json::from_slice::(&profile).map_err(|_| "invalid worker profile JSON")?; + Ok(Prepared { + binary, + size, + profile, + }) +} +pub async fn install(config: Install) -> Result { + validate( + &config.target, + config.schema_version, + &config.runtime_sha256, + None, + )?; + let input = config.clone(); + let prepared = tokio::task::spawn_blocking(move || prepare(&input)) + .await + .map_err(|_| "artifact validation interrupted")??; + let profile_hash = hex_hash(&prepared.profile); + execute( + &config.target, + &config.runtime_sha256, + &profile_hash, + Some(prepared), + ) + .await +} +pub async fn activate(config: Activate) -> Result { + validate( + &config.target, + config.schema_version, + &config.runtime_sha256, + Some(&config.profile_sha256), + )?; + execute( + &config.target, + &config.runtime_sha256, + &config.profile_sha256, + None, + ) + .await +} +fn validate( + target: &Target, + version: u32, + binary: &str, + profile: Option<&str>, +) -> Result<(), String> { + target.platform()?; + target.ssh.arguments()?; + if version != 1 || !valid_hash(binary) || profile.is_some_and(|p| !valid_hash(p)) { + return Err("invalid installation schema or SHA-256 pin".into()); + } + Ok(()) +} +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} +async fn execute( + target: &Target, + binary_hash: &str, + profile_hash: &str, + prepared: Option, +) -> Result { + let (os, arch) = target.platform()?; + let release = hex_hash(format!("v1:{os}:{arch}:{binary_hash}:{profile_hash}").as_bytes()); + let action = if prepared.is_some() { + "install" + } else { + "activate" + }; + let (size, profile_size) = prepared + .as_ref() + .map(|p| (p.size, p.profile.len())) + .unwrap_or_default(); + let remote_command = format!( + "sh -c {} strata-install {action} {} {os} {arch} {binary_hash} {profile_hash} {release} {size} {profile_size}", + quote(SCRIPT), + target.slot + ); + let mut args = target.ssh.arguments()?; + args.truncate(args.len() - 4); + for option in [ + "ControlMaster=no", + "ControlPath=none", + "ControlPersist=no", + "ForwardX11=no", + "ServerAliveInterval=10", + "ServerAliveCountMax=3", + ] { + args.extend(["-o".into(), option.into()]); + } + args.extend(["--".into(), target.ssh.host.clone(), remote_command]); + let mut child = Command::new("ssh") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "cannot start SSH installer")?; + let mut stdin = child.stdin.take().ok_or("missing SSH stdin")?; + let stdout = child.stdout.take().ok_or("missing SSH stdout")?; + let result = tokio::time::timeout(Duration::from_secs(180), async { + let upload = async move { + if let Some(p) = prepared { + let mut file = tokio::fs::File::from_std(p.binary).take(p.size); + let copied = tokio::io::copy(&mut file, &mut stdin).await?; + if copied != p.size { + return Err(std::io::Error::other("runtime truncated during transfer")); + } + stdin.write_all(&p.profile).await?; + } + stdin.shutdown().await + }; + let receive = async move { + let mut data = Vec::new(); + stdout.take(8193).read_to_end(&mut data).await?; + if data.len() > 8192 { + return Err(std::io::Error::other("installer output too large")); + } + Ok(data) + }; + tokio::join!(upload, receive, child.wait()) + }) + .await; + let (bytes, status) = match result { + Ok((uploaded, Ok(bytes), Ok(status))) if uploaded.is_ok() || !status.success() => { + (bytes, status) + } + _ => { + let _ = child.kill().await; + let _ = child.wait().await; + return Err("SSH installation interrupted; activation outcome unknown, retry with the same pins".into()); + } + }; + if !status.success() { + for code in [ + "target_os", + "target_arch", + "directory_symlink", + "directory_create", + "directory_type", + "directory_permissions", + "runtime_type", + "profile_type", + "runtime_digest", + "profile_digest", + "profile_validation", + "slot_locked", + "marker_symlink", + "marker_type", + "stale_marker", + "disk_probe", + "disk_capacity", + "upload_size", + "runtime_size", + "profile_size", + "release_missing", + ] { + if bytes == format!("error:{code}\n").as_bytes() { + return Err(format!("remote installation rejected: {code}")); + } + } + } + let outcome = match (status.success(), bytes.as_slice()) { + (true, b"ok:installed\n") => "installed", + (true, b"ok:reused\n") => "reused", + (true, b"ok:activated\n") => "activated", + _ => return Err("remote installation failed; inspect target permissions, capacity, platform and worker profile; activation may require reconciliation".into()), + }; + Ok(Receipt { + schema_version: 1, + slot: target.slot.clone(), + release, + runtime_sha256: binary_hash.into(), + profile_sha256: profile_hash.into(), + outcome: outcome.into(), + serving_changed: false, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + fn target() -> Target { + Target { + ssh: SshProfile { + schema_version: 1, + id: "fixture".into(), + host: "localhost".into(), + user: None, + port: None, + identity_file: None, + }, + slot: "test".into(), + os: "macos".into(), + arch: "aarch64".into(), + } + } + #[test] + fn reject_untrusted_arguments_before_ssh() { + let mut t = target(); + assert!(validate(&t, 1, &"a".repeat(64), None).is_ok()); + for slot in ["../other", "a b", "$(id)", "", "a;id"] { + t.slot = slot.into(); + assert!(t.platform().is_err()); + } + t = target(); + t.os = "windows".into(); + assert!(t.platform().is_err()); + assert!(!valid_hash(&"A".repeat(64))); + assert!(validate(&target(), 2, &"a".repeat(64), None).is_err()); + assert!(validate(&target(), 1, &"a".repeat(64), Some("x")).is_err()); + } + #[test] + fn reject_bad_artifact_pin_and_unbounded_input() { + assert!(regular(Path::new("relative"), MAX_BINARY).is_err()); + assert!(!valid_hash("deadbeef")); + assert_eq!( + hex_hash(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!(quote("a'b"), "'a'\\''b'"); + } +} diff --git a/desktop-core/src/remote_install.sh b/desktop-core/src/remote_install.sh new file mode 100644 index 00000000..1599f8ec --- /dev/null +++ b/desktop-core/src/remote_install.sh @@ -0,0 +1,94 @@ +# Fixed program; all positional arguments are constrained by the Rust client. +set -eu +umask 077 +fail() { printf 'error:%s\n' "$1"; exit 1; } +strata_action=$1 +strata_slot=$2 +strata_os=$3 +strata_arch=$4 +strata_binary_hash=$5 +strata_profile_hash=$6 +strata_release=$7 +strata_binary_size=$8 +strata_profile_size=$9 +[ "$(uname -s)" = "$strata_os" ] || fail target_os +[ "$(uname -m)" = "$strata_arch" ] || fail target_arch +strata_uid=$(id -u) +private_dir() { + [ ! -L "$1" ] || fail directory_symlink + if [ ! -e "$1" ]; then mkdir "$1" || fail directory_create; fi + [ -d "$1" ] || fail directory_type + if [ "$strata_os" = Darwin ]; then + strata_stat=$(stat -f '%u:%Lp' "$1") + else + strata_stat=$(stat -c '%u:%a' "$1") + fi + [ "$strata_stat" = "$strata_uid:700" ] || fail directory_permissions +} +digest() { + if [ "$strata_os" = Darwin ]; then shasum -a 256 "$1" | awk '{print $1}'; + else sha256sum "$1" | awk '{print $1}'; fi +} +verify() { + private_dir "$1" + [ -f "$1/strata-desktop" ] && [ ! -L "$1/strata-desktop" ] || fail runtime_type + [ -f "$1/worker.json" ] && [ ! -L "$1/worker.json" ] || fail profile_type + [ "$(digest "$1/strata-desktop")" = "$strata_binary_hash" ] || fail runtime_digest + [ "$(digest "$1/worker.json")" = "$strata_profile_hash" ] || fail profile_digest + "$1/strata-desktop" validate-worker "$1/worker.json" /dev/null 2>&1 || fail profile_validation +} +private_dir "$HOME/.strata-next" +private_dir "$HOME/.strata-next/installations" +strata_root="$HOME/.strata-next/installations/$strata_slot" +private_dir "$strata_root" +private_dir "$strata_root/releases" +mkdir "$strata_root/.lock" 2>/dev/null || fail slot_locked +strata_stage= +strata_marker_owned= +cleanup() { + if [ -n "$strata_stage" ]; then rm -rf "$strata_stage"; fi + if [ -n "$strata_marker_owned" ]; then rm -f "$strata_root/.current-next"; fi + rmdir "$strata_root/.lock" +} +trap cleanup EXIT +trap 'exit 1' HUP INT TERM +[ ! -L "$strata_root/current" ] || fail marker_symlink +[ ! -e "$strata_root/current" ] || [ -f "$strata_root/current" ] || fail marker_type +[ ! -e "$strata_root/.current-next" ] && [ ! -L "$strata_root/.current-next" ] || fail stale_marker +strata_dest="$strata_root/releases/$strata_release" +strata_result=activated +if [ "$strata_action" = install ]; then + strata_free=$(df -Pk "$strata_root" | awk 'END {print $4}') + case "$strata_free" in ''|*[!0-9]*) fail disk_probe;; esac + strata_needed=$(( (2 * (strata_binary_size + strata_profile_size) + 1023) / 1024 + 1024 )) + [ "$strata_free" -ge "$strata_needed" ] || fail disk_capacity + strata_stage=$(mktemp -d "$strata_root/.stage.XXXXXXXX") + # BSD head can read ahead on a pipe. Spool one bounded frame, then split + # regular files so no profile bytes are lost between reader processes. + strata_total=$((strata_binary_size + strata_profile_size)) + head -c "$strata_total" > "$strata_stage/payload" + [ "$(wc -c < "$strata_stage/payload" | tr -d ' ')" = "$strata_total" ] || fail upload_size + head -c "$strata_binary_size" "$strata_stage/payload" > "$strata_stage/strata-desktop" + tail -c "$strata_profile_size" "$strata_stage/payload" > "$strata_stage/worker.json" + rm "$strata_stage/payload" + [ "$(wc -c < "$strata_stage/strata-desktop" | tr -d ' ')" = "$strata_binary_size" ] || fail runtime_size + [ "$(wc -c < "$strata_stage/worker.json" | tr -d ' ')" = "$strata_profile_size" ] || fail profile_size + chmod 700 "$strata_stage/strata-desktop" + verify "$strata_stage" + if [ -e "$strata_dest" ] || [ -L "$strata_dest" ]; then + verify "$strata_dest" + strata_result=reused + else + mv "$strata_stage" "$strata_dest" + strata_stage= + strata_result=installed + fi +else + [ -d "$strata_dest" ] || fail release_missing + verify "$strata_dest" +fi +# No process operation: this only selects a release for a future managed launch. +strata_marker_owned=yes +printf '%s\n' "$strata_release" > "$strata_root/.current-next" +mv -f "$strata_root/.current-next" "$strata_root/current" +printf 'ok:%s\n' "$strata_result" diff --git a/desktop-core/src/ssh_tunnel.rs b/desktop-core/src/ssh_tunnel.rs new file mode 100644 index 00000000..7bb5ebf7 --- /dev/null +++ b/desktop-core/src/ssh_tunnel.rs @@ -0,0 +1,372 @@ +//! Owned local listener + isolated OpenSSH stdio forwards. No remote commands. +use crate::remote::SshProfile; +use serde::{Deserialize, Serialize}; +use std::{ + net::SocketAddr, + process::Stdio, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, + time::Duration, +}; +use tokio::{ + io::AsyncWriteExt, + net::{TcpListener, TcpStream}, + process::Command, + sync::{Semaphore, watch}, + task::JoinSet, +}; +#[derive(Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub schema_version: u32, + pub ssh: SshProfile, + pub listen: SocketAddr, + pub remote_port: u16, + pub max_connections: usize, +} +impl Config { + pub fn arguments(&self) -> Result, String> { + if self.schema_version != 1 + || !self.listen.ip().is_loopback() + || self.remote_port == 0 + || !(1..=16).contains(&self.max_connections) + { + return Err("invalid SSH tunnel profile".into()); + } + let mut args = self.ssh.arguments()?; + args.truncate(args.len() - 4); // remove -- host sh -s; no remote shell command + args.extend( + [ + "-o", + "ControlMaster=no", + "-o", + "ControlPath=none", + "-o", + "ControlPersist=no", + "-o", + "ForwardX11=no", + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ServerAliveInterval=10", + "-o", + "ServerAliveCountMax=3", + "-W", + ] + .into_iter() + .map(str::to_owned), + ); + args.extend([ + format!("127.0.0.1:{}", self.remote_port), + "--".into(), + self.ssh.host.clone(), + ]); + Ok(args) + } +} +#[derive(Clone, Default)] +pub struct Counters { + accepted: Arc, + active: Arc, + completed: Arc, + failed: Arc, + rejected: Arc, +} +#[derive(Serialize)] +pub struct Snapshot { + pub accepted: u64, + pub active: u64, + pub completed: u64, + pub failed: u64, + pub rejected: u64, +} +impl Counters { + pub fn snapshot(&self) -> Snapshot { + Snapshot { + accepted: self.accepted.load(Ordering::Relaxed), + active: self.active.load(Ordering::Relaxed), + completed: self.completed.load(Ordering::Relaxed), + failed: self.failed.load(Ordering::Relaxed), + rejected: self.rejected.load(Ordering::Relaxed), + } + } +} +struct Active(Counters); +impl Drop for Active { + fn drop(&mut self) { + self.0.active.fetch_sub(1, Ordering::Relaxed); + } +} +pub struct Tunnel { + listener: TcpListener, + args: Vec, + limit: usize, + counters: Counters, +} +impl Tunnel { + pub async fn bind(config: &Config) -> Result { + let args = config.arguments()?; + let listener = TcpListener::bind(config.listen) + .await + .map_err(|_| "SSH tunnel local port unavailable")?; + Ok(Self { + listener, + args, + limit: config.max_connections, + counters: Counters::default(), + }) + } + pub fn address(&self) -> SocketAddr { + self.listener.local_addr().expect("bound listener") + } + pub fn counters(&self) -> Counters { + self.counters.clone() + } + pub async fn serve(self, shutdown: impl Future + Send) -> Result<(), String> { + self.run("ssh", shutdown).await + } + async fn run( + self, + program: &str, + shutdown: impl Future + Send, + ) -> Result<(), String> { + let permits = Arc::new(Semaphore::new(self.limit)); + let mut tasks = JoinSet::new(); + let (cancel_tx, cancel) = watch::channel(false); + tokio::pin!(shutdown); + let mut next_start = tokio::time::Instant::now(); + loop { + tokio::select! { + _=&mut shutdown=>break, + Some(_)=tasks.join_next(),if !tasks.is_empty()=>{}, + accepted=self.listener.accept()=>{ + let (stream,_)=accepted.map_err(|_|"tunnel accept failed")?; + let Ok(permit)=permits.clone().try_acquire_owned() else{self.counters.rejected.fetch_add(1,Ordering::Relaxed);drop(stream);continue}; + self.counters.accepted.fetch_add(1,Ordering::Relaxed);self.counters.active.fetch_add(1,Ordering::Relaxed); + let args=self.args.clone();let program=program.to_string();let counters=self.counters.clone();let cancel=cancel.clone(); + let start=std::cmp::max(next_start,tokio::time::Instant::now());next_start=start+Duration::from_millis(250); + tasks.spawn(async move{ + let _permit=permit;let _active=Active(counters.clone()); + let result=forward(stream,&program,&args,cancel,start).await; + if result.is_ok(){counters.completed.fetch_add(1,Ordering::Relaxed);}else{counters.failed.fetch_add(1,Ordering::Relaxed);} + }); + } + } + } + cancel_tx.send_replace(true); + while tasks.join_next().await.is_some() {} + Ok(()) + } +} +async fn forward( + mut stream: TcpStream, + program: &str, + args: &[String], + mut cancel: watch::Receiver, + start: tokio::time::Instant, +) -> Result<(), ()> { + tokio::select! {_=tokio::time::sleep_until(start)=>{},_=cancel.changed()=>return Ok(())} + if *cancel.borrow() { + return Ok(()); + } + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| ())?; + let mut input = child.stdin.take().ok_or(())?; + let mut output = child.stdout.take().ok_or(())?; + // Both directions are bounded by copy's fixed buffer and pipe/socket backpressure. + // EOF ends this SSH connection; no request replay or cross-connection byte reuse. + let result = { + let (mut read, mut write) = stream.split(); + let up = async move { + let result = tokio::io::copy(&mut read, &mut input).await; + let _ = input.shutdown().await; + drop(input); + result.map(|_| ()).map_err(|_| ()) + }; + let down = async { + let result = tokio::io::copy(&mut output, &mut write).await; + let _ = write.shutdown().await; + result.map(|_| ()).map_err(|_| ()) + }; + tokio::pin!(up, down); + tokio::select! { + r=&mut down=>r, + r=&mut up=>if r.is_err(){r}else{tokio::select!{r=&mut down=>r,_=cancel.changed()=>Ok(())}}, + _=cancel.changed()=>Ok(()), + } + }; + drop(output); + let status = match tokio::time::timeout(Duration::from_millis(100), child.wait()).await { + Ok(Ok(s)) => Some(s), + _ => { + let _ = child.start_kill(); + let _ = child.wait().await; + None + } + }; + let _ = stream.shutdown().await; + if status.is_some_and(|s| !s.success()) { + Err(()) + } else { + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::AsyncReadExt; + fn config() -> Config { + Config { + schema_version: 1, + ssh: SshProfile { + schema_version: 1, + id: "test".into(), + host: "example.test".into(), + user: None, + port: None, + identity_file: None, + }, + listen: "127.0.0.1:0".parse().unwrap(), + remote_port: 18766, + max_connections: 2, + } + } + #[test] + fn safe_stdio_forward_arguments_and_validation() { + let c = config(); + let a = c.arguments().unwrap(); + for v in [ + "StrictHostKeyChecking=yes", + "ClearAllForwardings=yes", + "ControlMaster=no", + "ControlPath=none", + "ControlPersist=no", + "ForwardAgent=no", + "PermitLocalCommand=no", + "-W", + "127.0.0.1:18766", + ] { + assert!(a.iter().any(|x| x == v), "{v}"); + } + assert_eq!(&a[a.len() - 2..], ["--", "example.test"]); + assert!(!a.iter().any(|x| x == "sh" || x == "-s" || x == "-L")); + let mut bad = c.clone(); + bad.listen = "0.0.0.0:1234".parse().unwrap(); + assert!(bad.arguments().is_err()); + bad = c.clone(); + bad.remote_port = 0; + assert!(bad.arguments().is_err()); + bad = c; + bad.ssh.host = "-oProxyCommand=bad".into(); + assert!(bad.arguments().is_err()); + } + #[tokio::test] + async fn occupied_port_is_not_replaced() { + let held = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut c = config(); + c.listen = held.local_addr().unwrap(); + assert!(Tunnel::bind(&c).await.is_err()); + assert!(TcpStream::connect(c.listen).await.is_ok()); + } + // A direct subprocess exercises backpressure, binary data, half-close, lifetime, + // connection admission and recreation independently of an SSH daemon. + #[cfg(unix)] + #[tokio::test] + async fn bytes_half_close_reconnect_and_owned_shutdown() { + let t = Tunnel::bind(&config()).await.unwrap(); + let addr = t.address(); + let stats = t.counters(); + let (stop, rx) = tokio::sync::oneshot::channel(); + // cat is a byte transport fixture; remove SSH arguments only inside this test. + let t = Tunnel { args: vec![], ..t }; + let task = tokio::spawn(t.run("/bin/cat", async { + let _ = rx.await; + })); + for _ in 0..2 { + let mut stream = TcpStream::connect(addr).await.unwrap(); + let data: Vec = (0..300_000).map(|i| (i % 251) as u8).collect(); + let (mut r, mut w) = stream.split(); + let writer = async { + w.write_all(&data).await.unwrap(); + w.shutdown().await.unwrap(); + }; + let reader = async { + let mut out = vec![]; + r.read_to_end(&mut out).await.unwrap(); + out + }; + let (_, out) = tokio::time::timeout(Duration::from_secs(4), async { + tokio::join!(writer, reader) + }) + .await + .unwrap(); + assert_eq!(out, data); + } + let mut a = TcpStream::connect(addr).await.unwrap(); + a.write_all(b"a").await.unwrap(); + let mut b = [0]; + a.read_exact(&mut b).await.unwrap(); + stop.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(2), task) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(stats.snapshot().active, 0); + assert_eq!(stats.snapshot().accepted, 3); + assert_eq!(a.read(&mut b).await.unwrap(), 0); + assert!(TcpListener::bind(addr).await.is_ok()); + } + #[cfg(unix)] + #[tokio::test] + async fn failure_isolated_and_connection_limit_enforced() { + let mut c = config(); + c.max_connections = 1; + let t = Tunnel::bind(&c).await.unwrap(); + let addr = t.address(); + let stats = t.counters(); + let (stop, rx) = tokio::sync::oneshot::channel(); + let t = Tunnel { args: vec![], ..t }; + let task = tokio::spawn(t.run("/bin/cat", async { + let _ = rx.await; + })); + let mut first = TcpStream::connect(addr).await.unwrap(); + first.write_all(b"x").await.unwrap(); + let mut b = [0]; + first.read_exact(&mut b).await.unwrap(); + let mut second = TcpStream::connect(addr).await.unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), second.read(&mut b)) + .await + .unwrap() + .unwrap(), + 0 + ); + assert_eq!(stats.snapshot().rejected, 1); + stop.send(()).unwrap(); + task.await.unwrap().unwrap(); + let t = Tunnel::bind(&c).await.unwrap(); + let addr = t.address(); + let stats = t.counters(); + let (stop, rx) = tokio::sync::oneshot::channel(); + let t = Tunnel { args: vec![], ..t }; + let task = tokio::spawn(t.run("/usr/bin/false", async { + let _ = rx.await; + })); + let mut client = TcpStream::connect(addr).await.unwrap(); + assert_eq!(client.read(&mut b).await.unwrap(), 0); + tokio::time::sleep(Duration::from_millis(150)).await; + assert_eq!(stats.snapshot().failed, 1); + stop.send(()).unwrap(); + task.await.unwrap().unwrap(); + } +} diff --git a/desktop-core/tests/gateway.rs b/desktop-core/tests/gateway.rs new file mode 100644 index 00000000..10e716fd --- /dev/null +++ b/desktop-core/tests/gateway.rs @@ -0,0 +1,403 @@ +use axum::{ + Json, Router, + body::{Body, Bytes}, + extract::State, + routing::post, +}; +use futures_util::StreamExt; +use serde_json::{Value, json}; +use std::{ + collections::BTreeMap, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; +use strata_desktop_core::gateway::{Config, Deployment, Gateway, Group}; +use tokio::{ + sync::{Notify, Semaphore}, + task::JoinHandle, +}; +const TOKEN: &str = "synthetic-test-token-no-secret"; +struct Server { + url: String, + task: JoinHandle<()>, +} +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn server(router: Router) -> Server { + let socket = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", socket.local_addr().unwrap()); + let task = tokio::spawn(async move { + axum::serve(socket, router).await.unwrap(); + }); + Server { url, task } +} +fn config(nodes: &[&Server]) -> Config { + Config { + schema_version: 1, + listen: "127.0.0.1:0".parse().unwrap(), + token_env: "UNUSED".into(), + queue_limit: 2, + queue_timeout_ms: 1000, + request_timeout_ms: 3000, + groups: nodes + .iter() + .enumerate() + .map(|(i, _)| Group { + id: format!("g{i}"), + slots: 1, + available_bytes: 100, + }) + .collect(), + deployments: nodes + .iter() + .enumerate() + .map(|(i, n)| Deployment { + id: format!("d{i}"), + model: format!("m{i}"), + endpoint: n.url.clone(), + token_env: None, + group: format!("g{i}"), + slots: 1, + request_bytes: 100, + capabilities: vec!["responses".into(), "tools".into()], + }) + .collect(), + aliases: BTreeMap::from([( + "pool".into(), + (0..nodes.len()).map(|i| format!("d{i}")).collect(), + )]), + } +} +fn request(client: &reqwest::Client, g: &Server, value: Value) -> reqwest::RequestBuilder { + client + .post(format!("{}/v1/responses", g.url)) + .bearer_auth(TOKEN) + .header("content-type", "application/json") + .body(value.to_string()) +} +async fn status(client: &reqwest::Client, g: &Server) -> Value { + let text = client + .get(format!("{}/pool/status", g.url)) + .bearer_auth(TOKEN) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + serde_json::from_str(&text).unwrap() +} +struct Counting { + started: AtomicUsize, + notify: Notify, + release: Semaphore, +} +async fn held(State(c): State>, Json(v): Json) -> Json { + let id = c.started.fetch_add(1, Ordering::SeqCst); + c.notify.notify_one(); + c.release.acquire().await.unwrap().forget(); + Json( + json!({"id":format!("response-{id}"),"status":"completed","model":v["model"],"output":v["input"]}), + ) +} +async fn wait_started(c: &Counting, n: usize) { + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let notified = c.notify.notified(); + if c.started.load(Ordering::SeqCst) >= n { + return; + } + notified.await; + } + }) + .await + .unwrap(); +} +#[tokio::test] +async fn three_http_requests_overlap_fourth_queues_and_affinity_is_preserved() { + let c = Arc::new(Counting { + started: AtomicUsize::new(0), + notify: Notify::new(), + release: Semaphore::new(0), + }); + let a = server( + Router::new() + .route("/v1/responses", post(held)) + .with_state(c.clone()), + ) + .await; + let b = server( + Router::new() + .route("/v1/responses", post(held)) + .with_state(c.clone()), + ) + .await; + let d = server( + Router::new() + .route("/v1/responses", post(held)) + .with_state(c.clone()), + ) + .await; + let gateway = Gateway::with_token(config(&[&a, &b, &d]), TOKEN.into()).unwrap(); + let g = server(gateway.router()).await; + let client = reqwest::Client::new(); + let mut jobs = Vec::new(); + for i in 0..3 { + let r = request( + &client, + &g, + json!({"model":"pool","input":format!("job-{i}")}), + ); + jobs.push(tokio::spawn(async move { + r.send().await.unwrap().text().await.unwrap() + })); + } + wait_started(&c, 3).await; + assert_eq!(status(&client, &g).await["pool"]["active"], 3); + let r = request(&client, &g, json!({"model":"pool","input":"fourth"})); + let fourth = tokio::spawn(async move { r.send().await.unwrap().text().await.unwrap() }); + tokio::time::timeout(Duration::from_secs(1), async { + while status(&client, &g).await["pool"]["queued"] != 1 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(c.started.load(Ordering::SeqCst), 3); + c.release.add_permits(4); + let mut models = std::collections::HashSet::new(); + let mut first = None; + for (i, j) in jobs.into_iter().enumerate() { + let v: Value = serde_json::from_str(&j.await.unwrap()).unwrap(); + assert_eq!(v["output"], format!("job-{i}")); + models.insert(v["model"].as_str().unwrap().to_owned()); + first = Some(v); + } + assert_eq!(models.len(), 3); + assert!(fourth.await.unwrap().contains("fourth")); + let old = first.unwrap(); + c.release.add_permits(1); + let next = request( + &client, + &g, + json!({"model":"pool","input":"continuation","previous_response_id":old["id"]}), + ) + .send() + .await + .unwrap(); + let next: Value = serde_json::from_str(&next.text().await.unwrap()).unwrap(); + assert_eq!(next["model"], old["model"]); + let denied = request( + &client, + &g, + json!({"model":"pool","previous_response_id":"unknown","input":"x"}), + ) + .send() + .await + .unwrap(); + assert_eq!(denied.status(), 409); +} + +#[tokio::test] +async fn fragmented_sse_tool_arguments_are_byte_identical() { + let wire = "event: response.output_item.done\ndata: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"function_call\",\"call_id\":\"c1\",\"name\":\"test\",\"arguments\":\"{\\\"a\\\":1}\"}}\n\nevent: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"stream-1\",\"status\":\"completed\"}}\n\n"; + let a = server(Router::new().route( + "/v1/responses", + post(move |Json(v): Json| async move { + assert_eq!(v["model"], "m0"); + assert_eq!(v["tools"][0]["name"], "test"); + let chunks: Vec<_> = wire + .as_bytes() + .chunks(3) + .map(Bytes::copy_from_slice) + .map(Ok::<_, std::io::Error>) + .collect(); + ( + [("content-type", "text/event-stream")], + Body::from_stream(futures_util::stream::iter(chunks)), + ) + }), + )) + .await; + let g = server( + Gateway::with_token(config(&[&a]), TOKEN.into()) + .unwrap() + .router(), + ) + .await; + let client = reqwest::Client::new(); + let r=request(&client,&g,json!({"model":"pool","stream":true,"input":"x","tools":[{"type":"function","name":"test","parameters":{"type":"object"}}]})).send().await.unwrap(); + assert_eq!(r.headers()["x-strata-deployment"], "d0"); + assert_eq!(r.text().await.unwrap(), wire); + let s = status(&client, &g).await; + assert_eq!(s["pool"]["active"], 0); + assert_eq!(s["pool"]["workers"][0]["ready"], true); +} +#[tokio::test] +async fn auth_capabilities_and_queue_saturation_fail_explicitly() { + let c = Arc::new(Counting { + started: AtomicUsize::new(0), + notify: Notify::new(), + release: Semaphore::new(0), + }); + let a = server( + Router::new() + .route("/v1/responses", post(held)) + .with_state(c.clone()), + ) + .await; + let mut cfg = config(&[&a]); + cfg.queue_limit = 1; + cfg.queue_timeout_ms = 100; + let g = server(Gateway::with_token(cfg, TOKEN.into()).unwrap().router()).await; + let client = reqwest::Client::new(); + assert_eq!( + client + .get(format!("{}/v1/models", g.url)) + .send() + .await + .unwrap() + .status(), + 401 + ); + assert_eq!( + request( + &client, + &g, + json!({"model":"pool","input":[{"type":"input_image","image_url":"x"}]}) + ) + .send() + .await + .unwrap() + .status(), + 409 + ); + let r = request(&client, &g, json!({"model":"d0","input":"hold"})); + let hold = tokio::spawn(async move { r.send().await.unwrap() }); + wait_started(&c, 1).await; + let r = request(&client, &g, json!({"model":"d0","input":"wait"})); + let wait = tokio::spawn(async move { r.send().await.unwrap() }); + tokio::time::timeout(Duration::from_secs(1), async { + while status(&client, &g).await["pool"]["queued"] != 1 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!( + request(&client, &g, json!({"model":"d0","input":"overflow"})) + .send() + .await + .unwrap() + .status(), + 429 + ); + assert_eq!(wait.await.unwrap().status(), 504); + c.release.add_permits(1); + assert_eq!(hold.await.unwrap().status(), 200); +} +#[tokio::test] +async fn interrupted_upstream_is_quarantined_without_stalling_other_nodes() { + let a = server(Router::new().route( + "/v1/responses", + post(|| async { + ( + [("content-type", "text/event-stream")], + "data: {\"type\":\"response.created\"}\n\n", + ) + }), + )) + .await; + let b = server(Router::new().route( + "/v1/responses", + post(|| async { Json(json!({"id":"healthy","status":"completed"})) }), + )) + .await; + let g = server( + Gateway::with_token(config(&[&a, &b]), TOKEN.into()) + .unwrap() + .router(), + ) + .await; + let client = reqwest::Client::new(); + let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"})) + .send() + .await; + if let Ok(r) = r { + assert!(r.text().await.is_err()); + } + let s = status(&client, &g).await; + assert_eq!(s["pool"]["workers"][0]["ready"], false); + assert_eq!(s["pool"]["active"], 0); + assert_eq!( + request(&client, &g, json!({"model":"pool","input":"healthy"})) + .send() + .await + .unwrap() + .status(), + 200 + ); +} +#[tokio::test] +async fn rejects_public_endpoint_bind_and_duplicate_endpoints() { + let fixture = server(Router::new()).await; + let mut c = config(&[&fixture]); + c.listen = "0.0.0.0:1234".parse().unwrap(); + assert!(Gateway::with_token(c, TOKEN.into()).is_err()); + let mut c = config(&[&fixture]); + c.deployments[0].endpoint = "http://192.0.2.1:80".into(); + assert!(Gateway::with_token(c, TOKEN.into()).is_err()); + let c = config(&[&fixture, &fixture]); + assert!(Gateway::with_token(c, TOKEN.into()).is_err()); +} + +#[tokio::test] +async fn client_disconnect_quarantines_worker_until_verified_recovery() { + let a = server(Router::new().route( + "/v1/responses", + post(|| async { + let initial = futures_util::stream::once(async { + Ok::<_, std::io::Error>(Bytes::from_static( + b"data: {\"type\":\"response.created\"}\n\n", + )) + }); + ( + [("content-type", "text/event-stream")], + Body::from_stream(initial.chain(futures_util::stream::pending())), + ) + }), + )) + .await; + let g = server( + Gateway::with_token(config(&[&a]), TOKEN.into()) + .unwrap() + .router(), + ) + .await; + let client = reqwest::Client::new(); + let r = request(&client, &g, json!({"model":"d0","stream":true,"input":"x"})) + .send() + .await + .unwrap(); + let mut stream = r.bytes_stream(); + assert!(stream.next().await.unwrap().is_ok()); + drop(stream); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let s = status(&client, &g).await; + if s["pool"]["workers"][0]["ready"] == false { + assert_eq!(s["pool"]["active"], 0); + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} diff --git a/desktop-core/tests/managed_worker.rs b/desktop-core/tests/managed_worker.rs new file mode 100644 index 00000000..5cf91a22 --- /dev/null +++ b/desktop-core/tests/managed_worker.rs @@ -0,0 +1,500 @@ +use std::{net::SocketAddr, time::Duration}; +use strata_desktop_core::{ + managed_worker::{Manager, Profile}, + node::{self, proto::*}, +}; +use tokio::net::TcpListener; +const TOKEN: &str = "synthetic-lifecycle-test-token-32bytes"; +const OUTPUT: &str = + r#"{"id":"resp_fixture","object":"response","status":"completed","output":[]}"#; + +// Same Rust test executable becomes a real isolated backend child. No Python, +// GPU, model download, request capture or running user endpoint is involved. +#[test] +#[ignore] +fn fixture() { + let Ok(endpoint) = std::env::var("STRATA_WORKER_ENDPOINT") else { + return; + }; + assert!(std::env::var("STRATA_NODE_TOKEN").is_err()); + let model = std::env::var("STRATA_WORKER_MODEL").unwrap(); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async move { + let health_model = if model == "wrong" { + "unexpected".to_string() + } else { + model.clone() + }; + let router = axum::Router::new() + .route( + "/health", + axum::routing::get(move || { + let model = health_model.clone(); + async move { + axum::Json( + serde_json::json!({"status":"ok","loaded":true,"model":model}), + ) + } + }), + ) + .route( + "/v1/responses", + axum::routing::post(move || { + let slow = model == "slow"; + async move { + if slow { + tokio::time::sleep(Duration::from_millis(600)).await; + } + ( + [(axum::http::header::CONTENT_TYPE, "application/json")], + OUTPUT, + ) + } + }), + ) + .route( + "/exit", + axum::routing::get(|| async { + std::process::exit(7); + #[allow(unreachable_code)] + "exited" + }), + ); + axum::serve(TcpListener::bind(endpoint).await.unwrap(), router) + .await + .unwrap(); + }); +} +async fn profile(model: &str) -> Profile { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = l.local_addr().unwrap(); + drop(l); + Profile { + schema_version: 1, + id: "fixture".into(), + model: model.into(), + executable: std::env::current_exe().unwrap(), + args: vec![ + "--exact".into(), + "fixture".into(), + "--ignored".into(), + "--nocapture".into(), + ], + endpoint, + startup_timeout_ms: 1500, + capabilities: vec!["responses".into()], + } +} +fn command(action: i32, grace: u32) -> WorkerCommand { + WorkerCommand { + operation_id: uuid::Uuid::new_v4().to_string(), + action, + drain_timeout_ms: grace, + expected_epoch: String::new(), + } +} +async fn finish(m: &Manager, c: WorkerCommand) -> WorkerOperation { + let id = c.operation_id.clone(); + m.submit(c).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let s = m.operation(&id).unwrap(); + if s.status == "succeeded" || s.status == "failed" { + break s; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap() +} +struct Server { + address: SocketAddr, + task: tokio::task::JoinHandle<()>, +} +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn serve(p: Profile) -> Server { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = l.local_addr().unwrap(); + let agent = node::Agent::managed(TOKEN.into(), p).unwrap(); + Server { + address, + task: tokio::spawn(async move { + agent.serve(l, std::future::pending()).await.unwrap(); + }), + } +} +fn req(v: T) -> tonic::Request { + node::authorized(v, TOKEN).unwrap() +} +async fn remote_finish( + c: &mut node_client::NodeClient, + op: WorkerCommand, +) -> WorkerOperation { + let id = op.operation_id.clone(); + c.control_worker(req(op)).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let op = c + .operation_status(req(OperationQuery { + operation_id: id.clone(), + })) + .await + .unwrap() + .into_inner(); + if op.status == "succeeded" || op.status == "failed" { + break op; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap() +} +#[tokio::test] +async fn grpc_owned_start_stop_and_exact_response() { + let server = serve(profile("test").await).await; + let mut c = node::connect(server.address).await.unwrap(); + assert_eq!( + c.worker_status(Empty {}).await.unwrap_err().code(), + tonic::Code::Unauthenticated + ); + assert_eq!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .phase, + "stopped" + ); + let input = ResponseRequest { + json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(), + }; + assert_eq!( + c.respond(req(input.clone())).await.unwrap_err().code(), + tonic::Code::Unavailable + ); + let mut stale = command(1, 0); + stale.expected_epoch = "old-epoch".into(); + assert_eq!( + c.control_worker(req(stale)).await.unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + assert_eq!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .phase, + "stopped" + ); + let op = command(1, 0); + assert_eq!(remote_finish(&mut c, op.clone()).await.status, "succeeded"); + let state = c.worker_status(req(Empty {})).await.unwrap().into_inner(); + assert_eq!(state.phase, "ready"); + assert_ne!(state.pid, 0); + // Same operation ID survives transport disconnect without spawning twice. + drop(c); + let mut c = node::connect(server.address).await.unwrap(); + assert_eq!( + c.control_worker(req(op.clone())) + .await + .unwrap() + .into_inner() + .status, + "succeeded" + ); + assert_eq!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .pid, + state.pid + ); + let mut conflict = op; + conflict.action = 2; + assert_eq!( + c.control_worker(req(conflict)).await.unwrap_err().code(), + tonic::Code::AlreadyExists + ); + let mut frames = c.respond(req(input.clone())).await.unwrap().into_inner(); + let mut data = vec![]; + let mut end = false; + while let Some(frame) = frames.message().await.unwrap() { + match frame.payload.unwrap() { + response_frame::Payload::Data(b) => data.extend(b), + response_frame::Payload::End(_) => end = true, + response_frame::Payload::Headers(h) => assert_eq!(h.status, 200), + } + } + assert_eq!(data, OUTPUT.as_bytes()); + assert!(end); + assert_eq!( + remote_finish(&mut c, command(2, 1000)).await.status, + "succeeded" + ); + assert_eq!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .phase, + "stopped" + ); + assert_eq!( + c.respond(req(input)).await.unwrap_err().code(), + tonic::Code::Unavailable + ); + assert_eq!( + remote_finish(&mut c, command(1, 0)).await.status, + "succeeded" + ); + let mut old = c + .respond(req(ResponseRequest { + json: + br#"{"model":"fixture","input":"synthetic","previous_response_id":"resp_fixture"}"# + .to_vec(), + })) + .await + .unwrap() + .into_inner(); + assert!(matches!( + old.message().await.unwrap().unwrap().payload, + Some(response_frame::Payload::Headers(ResponseHeaders { + status: 409, + .. + })) + )); + drop(old); + assert_eq!( + remote_finish(&mut c, command(2, 1000)).await.status, + "succeeded" + ); +} +#[tokio::test] +async fn wrong_health_and_occupied_endpoint_fail_closed() { + let mut p = profile("wrong").await; + p.startup_timeout_ms = 300; + let g = p.gateway(TOKEN.into()).unwrap(); + let m = Manager::new(p, g).unwrap(); + assert_eq!(finish(&m, command(1, 0)).await.reason, "startup_timeout"); + assert_eq!(m.state().pid, 0); + let p = profile("test").await; + let held = TcpListener::bind(p.endpoint).await.unwrap(); + let m = Manager::new(p.clone(), p.gateway(TOKEN.into()).unwrap()).unwrap(); + assert_eq!(finish(&m, command(1, 0)).await.reason, "endpoint_occupied"); + assert_eq!(m.state().pid, 0); + assert!( + tokio::net::TcpStream::connect(held.local_addr().unwrap()) + .await + .is_ok() + ); +} +#[tokio::test] +async fn unexpected_child_exit_closes_admission_and_can_restart() { + let p = profile("test").await; + let m = Manager::new(p.clone(), p.gateway(TOKEN.into()).unwrap()).unwrap(); + assert_eq!(finish(&m, command(1, 0)).await.status, "succeeded"); + let _ = reqwest::get(format!("http://{}/exit", p.endpoint)).await; + tokio::time::timeout(Duration::from_secs(2), async { + while m.state().phase != "failed" { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .unwrap(); + assert_eq!(m.state().reason, "worker_exited"); + assert_eq!(finish(&m, command(1, 0)).await.status, "succeeded"); + assert_eq!(finish(&m, command(2, 0)).await.status, "succeeded"); +} +#[tokio::test] +async fn stop_timeout_does_not_kill_active_request() { + let server = serve(profile("slow").await).await; + let mut c = node::connect(server.address).await.unwrap(); + assert_eq!( + remote_finish(&mut c, command(1, 0)).await.status, + "succeeded" + ); + let mut response_client = c.clone(); + let request = tokio::spawn(async move { + let mut stream = response_client + .respond(req(ResponseRequest { + json: br#"{"model":"fixture","input":"synthetic","stream":false}"#.to_vec(), + })) + .await + .unwrap() + .into_inner(); + let mut data = vec![]; + while let Some(f) = stream.message().await.unwrap() { + if let Some(response_frame::Payload::Data(b)) = f.payload { + data.extend(b) + } + } + data + }); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + if c.handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner() + .active_responses + == 1 + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + // Give the request time to acquire its lease before draining. + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!( + remote_finish(&mut c, command(2, 0)).await.reason, + "drain_timeout" + ); + assert_ne!( + c.worker_status(req(Empty {})) + .await + .unwrap() + .into_inner() + .pid, + 0 + ); + assert_eq!(request.await.unwrap(), OUTPUT.as_bytes()); + assert_eq!( + remote_finish(&mut c, command(2, 1000)).await.status, + "succeeded" + ); +} + +#[tokio::test] +async fn cli_profile_start_status_stop_and_node_drop_cleanup() { + use tokio::io::{AsyncBufReadExt, BufReader}; + let p = profile("test").await; + let path = std::env::temp_dir().join(format!("strata-profile-{}.json", uuid::Uuid::new_v4())); + struct FileGuard(std::path::PathBuf); + impl Drop for FileGuard { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let _file = FileGuard(path.clone()); + std::fs::write( + &path, + serde_json::to_vec(&serde_json::json!({ + "schema_version":1,"id":p.id,"model":p.model,"executable":p.executable,"args":p.args, + "endpoint":p.endpoint,"startup_timeout_ms":p.startup_timeout_ms + })) + .unwrap(), + ) + .unwrap(); + let mut node = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop")) + .args([ + "node", + "--listen", + "127.0.0.1:0", + "--token-env", + "STRATA_NODE_TOKEN", + "--worker-profile", + ]) + .arg(&path) + .env("STRATA_NODE_TOKEN", TOKEN) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut lines = BufReader::new(node.stdout.take().unwrap()).lines(); + let line = tokio::time::timeout(Duration::from_secs(5), lines.next_line()) + .await + .unwrap() + .unwrap() + .unwrap(); + let address = serde_json::from_str::(&line).unwrap()["endpoint"] + .as_str() + .unwrap() + .trim_start_matches("http://") + .to_string(); + async fn cli(address: &str, action: &[&str]) -> serde_json::Value { + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_strata-desktop")); + command + .args([ + "worker", + "--node", + address, + "--token-env", + "STRATA_NODE_TOKEN", + ]) + .args(action) + .env("STRATA_NODE_TOKEN", TOKEN) + .kill_on_drop(true); + let output = tokio::time::timeout(Duration::from_secs(5), command.output()) + .await + .unwrap() + .unwrap(); + assert!(output.status.success(), "CLI action failed"); + serde_json::from_slice(&output.stdout).unwrap() + } + assert_eq!(cli(&address, &["status"]).await["phase"], "stopped"); + let id = uuid::Uuid::new_v4().to_string(); + assert_eq!(cli(&address, &["start", &id]).await["operation_id"], id); + let mut c = node::connect(address.parse().unwrap()).await.unwrap(); + let epoch = c + .handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner() + .agent_epoch; + assert_eq!( + remote_finish( + &mut c, + WorkerCommand { + operation_id: id.clone(), + action: 1, + drain_timeout_ms: 0, + expected_epoch: epoch.clone(), + } + ) + .await + .status, + "succeeded" + ); + assert_eq!( + cli(&address, &["operation", &id]).await["status"], + "succeeded" + ); + assert_eq!(cli(&address, &["status"]).await["phase"], "ready"); + let id = uuid::Uuid::new_v4().to_string(); + cli(&address, &["stop", &id]).await; + assert_eq!( + remote_finish( + &mut c, + WorkerCommand { + operation_id: id, + action: 2, + drain_timeout_ms: 30000, + expected_epoch: epoch.clone(), + } + ) + .await + .status, + "succeeded" + ); + node.kill().await.unwrap(); + node.wait().await.unwrap(); + assert!(TcpListener::bind(p.endpoint).await.is_ok()); +} diff --git a/desktop-core/tests/node_contract.rs b/desktop-core/tests/node_contract.rs new file mode 100644 index 00000000..cf97a315 --- /dev/null +++ b/desktop-core/tests/node_contract.rs @@ -0,0 +1,382 @@ +use axum::{Router, body::Body, routing::post}; +use std::{collections::BTreeMap, time::Duration}; +use strata_desktop_core::{ + gateway, + node::{self, proto::*}, +}; +use tokio::net::TcpListener; +use tonic::Code; +const TOKEN: &str = "synthetic-test-credential-32-bytes-only"; +struct Server { + address: std::net::SocketAddr, + task: tokio::task::JoinHandle<()>, +} +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} +async fn server(gateway: Option) -> Server { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let agent = node::Agent::new(TOKEN.into(), gateway).unwrap(); + let task = + tokio::spawn(async move { agent.serve(listener, std::future::pending()).await.unwrap() }); + Server { address, task } +} +fn req(message: T) -> tonic::Request { + node::authorized(message, TOKEN).unwrap() +} +async fn fake(body: &'static str, delay: bool) -> (Server, gateway::Gateway) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let router=Router::new().route("/v1/responses",post(move ||async move { + let stream=async_stream::stream! { + if delay {tokio::time::sleep(Duration::from_millis(150)).await;} + for bytes in body.as_bytes().chunks(3) { yield Ok::<_,std::io::Error>(bytes.to_vec()); } + }; + axum::response::Response::builder().header("content-type","text/event-stream").body(Body::from_stream(stream)).unwrap() + })); + let task = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let g = gateway::Gateway::with_token( + gateway::Config { + schema_version: 1, + listen: "127.0.0.1:0".parse().unwrap(), + token_env: "UNUSED".into(), + queue_limit: 4, + queue_timeout_ms: 1000, + request_timeout_ms: 3000, + groups: vec![gateway::Group { + id: "local".into(), + slots: 1, + available_bytes: 100, + }], + deployments: vec![gateway::Deployment { + id: "test".into(), + model: "test".into(), + endpoint: format!("http://{address}"), + token_env: None, + group: "local".into(), + slots: 1, + request_bytes: 1, + capabilities: vec!["responses".into(), "tools".into()], + }], + aliases: BTreeMap::new(), + }, + TOKEN.into(), + ) + .unwrap(); + (Server { address, task }, g) +} +#[tokio::test] +async fn auth_version_capabilities_bounds_and_loopback() { + let server = server(None).await; + let mut client = node::connect(server.address).await.unwrap(); + assert_eq!( + client + .handshake(Hello { + protocol_version: 1 + }) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); + assert_eq!( + client + .handshake(req(Hello { + protocol_version: 2 + })) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + let snapshot = client + .handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner(); + assert!( + !snapshot + .capabilities + .iter() + .any(|s| s.contains("responses")) + ); + assert_eq!( + client.hardware(Empty {}).await.unwrap_err().code(), + Code::Unauthenticated + ); + assert_eq!( + client + .plan(JsonDocument { json: vec![] }) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); + assert_eq!( + client.models(Empty {}).await.unwrap_err().code(), + Code::Unauthenticated + ); + assert_eq!( + client + .respond(ResponseRequest { json: vec![] }) + .await + .unwrap_err() + .code(), + Code::Unauthenticated + ); + assert_eq!( + client.watch(Cursor::default()).await.unwrap_err().code(), + Code::Unauthenticated + ); + assert_eq!( + client + .plan(req(JsonDocument { + json: vec![b' '; 1024 * 1024 + 1] + })) + .await + .unwrap_err() + .code(), + Code::ResourceExhausted + ); + assert!( + node::connect("192.0.2.1:1234".parse().unwrap()) + .await + .is_err() + ); + let listener = TcpListener::bind("0.0.0.0:0").await.unwrap(); + assert!( + node::Agent::new(TOKEN.into(), None) + .unwrap() + .serve(listener, async {}) + .await + .is_err() + ); +} +#[tokio::test] +async fn watch_reconnect_limits_and_new_epoch_snapshot() { + let a = server(None).await; + let mut client = node::connect(a.address).await.unwrap(); + let mut subscriptions = vec![]; + for _ in 0..16 { + let mut stream = client + .watch(req(Cursor { + agent_epoch: "old".into(), + sequence: u64::MAX, + })) + .await + .unwrap() + .into_inner(); + let state = stream.message().await.unwrap().unwrap(); + assert!(state.full_snapshot); + assert_ne!(state.agent_epoch, "old"); + assert_eq!(state.sequence, 1); + subscriptions.push(stream); + } + assert_eq!( + client + .watch(req(Cursor::default())) + .await + .unwrap_err() + .code(), + Code::ResourceExhausted + ); + let epoch = client + .handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner() + .agent_epoch; + drop(subscriptions); + let b = server(None).await; + let mut other = node::connect(b.address).await.unwrap(); + let mut stream = other + .watch(req(Cursor { + agent_epoch: epoch.clone(), + sequence: 1, + })) + .await + .unwrap() + .into_inner(); + assert_ne!(stream.message().await.unwrap().unwrap().agent_epoch, epoch); +} +const SSE: &str = "data: {\"type\":\"response.function_call_arguments.delta\",\"delta\":\"{\\\"x\\\":1}\"}\n\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_test\"}}\n\n"; +#[tokio::test] +async fn responses_preserve_bytes_terminal_and_control_during_generation() { + let (_fake, g) = fake(SSE, true).await; + let server = server(Some(g)).await; + let mut client = node::connect(server.address).await.unwrap(); + let mut watch = client + .watch(req(Cursor::default())) + .await + .unwrap() + .into_inner(); + let first = watch.message().await.unwrap().unwrap(); + let mut stream = client + .respond(req(ResponseRequest { + json: br#"{"model":"test","stream":true,"input":"synthetic"}"#.to_vec(), + })) + .await + .unwrap() + .into_inner(); + let active = watch.message().await.unwrap().unwrap(); + assert_eq!(active.active_responses, 1); + assert!(active.sequence > first.sequence); + let snapshot = tokio::time::timeout( + Duration::from_secs(1), + client.handshake(req(Hello { + protocol_version: 1, + })), + ) + .await + .unwrap() + .unwrap() + .into_inner(); + assert_eq!(snapshot.active_responses, 1); + let mut bytes = vec![]; + let mut end = false; + let mut headers = false; + while let Some(frame) = stream.message().await.unwrap() { + match frame.payload.unwrap() { + response_frame::Payload::Headers(h) => { + assert!(!headers); + assert_eq!(h.status, 200); + headers = true + } + response_frame::Payload::Data(b) => { + assert!(headers && !end); + bytes.extend(b) + } + response_frame::Payload::End(_) => { + assert!(!end); + end = true + } + } + } + assert!(end); + assert_eq!(bytes, SSE.as_bytes()); + let complete = watch.message().await.unwrap().unwrap(); + assert_eq!(complete.active_responses, 0); + let reconnect = client + .watch(req(Cursor { + agent_epoch: complete.agent_epoch.clone(), + sequence: 1, + })) + .await + .unwrap() + .into_inner() + .message() + .await + .unwrap() + .unwrap(); + assert_eq!(reconnect.sequence, complete.sequence); + assert!(reconnect.full_snapshot); +} +#[tokio::test] +async fn interrupted_upstream_is_error_not_end_and_quarantines() { + let (_fake, g) = fake("data: {\"type\":\"response.created\"}\n\n", false).await; + let server = server(Some(g)).await; + let mut client = node::connect(server.address).await.unwrap(); + let input = || { + req(ResponseRequest { + json: br#"{"model":"test","stream":true}"#.to_vec(), + }) + }; + let mut s = client.respond(input()).await.unwrap().into_inner(); + loop { + match s.message().await { + Err(e) => { + assert_eq!(e.code(), Code::Aborted); + break; + } + Ok(Some(f)) => assert!(!matches!(f.payload, Some(response_frame::Payload::End(_)))), + Ok(None) => panic!("missing interruption error"), + } + } + let mut second = client.respond(input()).await.unwrap().into_inner(); + let header = second.message().await.unwrap().unwrap(); + assert!(matches!(header.payload,Some(response_frame::Payload::Headers(h)) if h.status==504)); +} + +#[tokio::test] +async fn harness_http_to_grpc_to_worker_preserves_stream_and_auth() { + let (_fake, g) = fake(SSE, false).await; + let node = server(Some(g)).await; + let proxy = strata_desktop_core::node_proxy::Proxy::connect(node.address, TOKEN.into()) + .await + .unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { axum::serve(listener, proxy.router()).await.unwrap() }); + let _proxy = Server { address, task }; + let client = reqwest::Client::new(); + let url = format!("http://{address}/v1/responses"); + assert_eq!( + client.post(&url).body("{}").send().await.unwrap().status(), + 401 + ); + let response = client + .post(&url) + .bearer_auth(TOKEN) + .body(r#"{"model":"test","stream":true}"#) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.text().await.unwrap(), SSE); + let models = client + .get(format!("http://{address}/v1/models")) + .bearer_auth(TOKEN) + .send() + .await + .unwrap(); + assert_eq!(models.status(), 200); + assert!(models.text().await.unwrap().contains("test")); +} + +#[tokio::test] +async fn disconnect_releases_transport_count_but_does_not_reuse_unconfirmed_worker() { + let (_fake, g) = fake(SSE, true).await; + let node = server(Some(g)).await; + let mut client = node::connect(node.address).await.unwrap(); + let input = || { + req(ResponseRequest { + json: br#"{"model":"test","stream":true}"#.to_vec(), + }) + }; + let mut stream = client.respond(input()).await.unwrap().into_inner(); + assert!(matches!( + stream.message().await.unwrap().unwrap().payload, + Some(response_frame::Payload::Headers(_)) + )); + drop(stream); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + if client + .handshake(req(Hello { + protocol_version: 1, + })) + .await + .unwrap() + .into_inner() + .active_responses + == 0 + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let mut second = client.respond(input()).await.unwrap().into_inner(); + assert!( + matches!(second.message().await.unwrap().unwrap().payload,Some(response_frame::Payload::Headers(h)) if h.status==504) + ); +} diff --git a/desktop-core/tests/node_reconnect.rs b/desktop-core/tests/node_reconnect.rs new file mode 100644 index 00000000..6f6e2644 --- /dev/null +++ b/desktop-core/tests/node_reconnect.rs @@ -0,0 +1,132 @@ +use std::{net::SocketAddr, process::Stdio, time::Duration}; +use strata_desktop_core::node_connection::{Connection, Phase, Timing}; +use tokio::{ + io::{AsyncBufReadExt, BufReader}, + process::{Child, Command}, +}; +const TOKEN: &str = "test-only-reconnect-node-credential-123456"; +fn timing() -> Timing { + Timing { + heartbeat: Duration::from_millis(50), + deadline: Duration::from_millis(300), + freshness: Duration::from_millis(500), + retry_min: Duration::from_millis(20), + retry_max: Duration::from_millis(100), + } +} +async fn launch(address: SocketAddr) -> (Child, SocketAddr) { + let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop")) + .args([ + "node", + "--listen", + &address.to_string(), + "--token-env", + "STRATA_TEST_NODE_TOKEN", + ]) + .env("STRATA_TEST_NODE_TOKEN", TOKEN) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut line = String::new(); + tokio::time::timeout( + Duration::from_secs(3), + BufReader::new(child.stdout.take().unwrap()).read_line(&mut line), + ) + .await + .unwrap() + .unwrap(); + let v: serde_json::Value = serde_json::from_str(&line).unwrap(); + ( + child, + v["endpoint"] + .as_str() + .unwrap() + .strip_prefix("http://") + .unwrap() + .parse() + .unwrap(), + ) +} +async fn wait_phase(c: &Connection, p: Phase) { + tokio::time::timeout(Duration::from_secs(3), async { + while c.status().phase != p { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} +#[tokio::test] +async fn killed_process_recovers_same_port_new_epoch_and_nodes_are_independent() { + let (mut process, address) = launch("127.0.0.1:0".parse().unwrap()).await; + let (mut other_process, other_address) = launch("127.0.0.1:0".parse().unwrap()).await; + let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap(); + let other = Connection::with_timing(other_address, TOKEN.into(), timing()).unwrap(); + c.wait_ready(Duration::from_secs(2)).await.unwrap(); + other.wait_ready(Duration::from_secs(2)).await.unwrap(); + let epoch = c.status().agent_epoch.unwrap(); + process.kill().await.unwrap(); + process.wait().await.unwrap(); + wait_phase(&c, Phase::Disconnected).await; + assert!(c.client("hardware.v1").is_err()); + assert!(other.client("hardware.v1").is_ok()); + let (mut replacement, _) = launch(address).await; + c.wait_ready(Duration::from_secs(3)).await.unwrap(); + assert_ne!(c.status().agent_epoch.unwrap(), epoch); + assert_eq!(c.status().active_responses, Some(0)); + assert!(c.client("hardware.v1").is_ok()); + drop(c); + drop(other); + replacement.kill().await.unwrap(); + replacement.wait().await.unwrap(); + other_process.kill().await.unwrap(); + other_process.wait().await.unwrap(); +} +#[tokio::test] +async fn invalid_auth_stays_terminal_across_server_restart() { + let (mut process, address) = launch("127.0.0.1:0".parse().unwrap()).await; + let c = Connection::with_timing( + address, + "incorrect-test-credential-32bytes-long".into(), + timing(), + ) + .unwrap(); + assert_eq!( + c.wait_ready(Duration::from_secs(2)) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + process.kill().await.unwrap(); + process.wait().await.unwrap(); + let (mut replacement, _) = launch(address).await; + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(c.status().phase, Phase::AuthError); + assert!(!c.status().fresh); + drop(c); + replacement.kill().await.unwrap(); + replacement.wait().await.unwrap(); +} +#[tokio::test] +async fn startup_offline_recovers_and_drop_releases_subscription() { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = l.local_addr().unwrap(); + drop(l); + let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap(); + wait_phase(&c, Phase::Disconnected).await; + let (mut process, _) = launch(address).await; + c.wait_ready(Duration::from_secs(3)).await.unwrap(); + drop(c); + // More than the server's 16 observer limit; dropping each owner must release it. + for _ in 0..20 { + let c = Connection::with_timing(address, TOKEN.into(), timing()).unwrap(); + c.wait_ready(Duration::from_secs(2)).await.unwrap(); + drop(c); + tokio::task::yield_now().await; + } + process.kill().await.unwrap(); + process.wait().await.unwrap(); +} diff --git a/desktop-core/tests/planning.rs b/desktop-core/tests/planning.rs new file mode 100644 index 00000000..9ac5d89b --- /dev/null +++ b/desktop-core/tests/planning.rs @@ -0,0 +1,147 @@ +use strata_desktop_core::{ + hardware::{Accelerator, Hardware, Memory, MemoryKind}, + planner::{Requirements, plan}, +}; +const G: u64 = 1024 * 1024 * 1024; +fn host(vram: Option) -> Hardware { + Hardware { + schema_version: 1, + sampled_at_unix_ms: 0, + os: "test".into(), + architecture: "test".into(), + cpu_name: "test".into(), + logical_cpus: 8, + cpu_features: vec![], + memory: Memory { + total_bytes: Some(32 * G), + available_bytes: Some(24 * G), + }, + warnings: vec![], + accelerators: vec![Accelerator { + id: "gpu".into(), + name: "fixture".into(), + vendor: "fixture".into(), + memory_kind: MemoryKind::Dedicated, + memory: Memory { + total_bytes: vram, + available_bytes: vram, + }, + driver: None, + source: "fixture".into(), + }], + } +} +fn req() -> Requirements { + Requirements { + schema_version: 1, + model: "synthetic-runtime-budget".into(), + context_tokens: 1024, + concurrent_requests: 1, + weights_bytes: 10 * G, + kv_bytes_per_token_per_request: G / 1024, + workspace_bytes: G, + load_scratch_bytes: G, + host_overhead_bytes: G, + host_reserve_bytes: 2 * G, + device_reserve_bytes: G, + retains_host_weights: false, + allow_weight_offload: true, + } +} +#[test] +fn eight_gib_needs_offload_sixteen_fits() { + let p = plan(&host(Some(8 * G)), &req()).unwrap(); + assert_eq!(p.candidates[1].fit, "insufficient"); + assert_eq!(p.candidates.last().unwrap().fit, "fits_estimate"); + assert_eq!(p.candidates[1].device_peak_bytes, 13 * G); + assert_eq!( + plan(&host(Some(16 * G)), &req()).unwrap().candidates[1].fit, + "fits_estimate" + ); +} +#[test] +fn cannot_offload_into_unavailable_ram() { + let mut h = host(Some(8 * G)); + h.memory.available_bytes = Some(3 * G); + assert!( + plan(&h, &req()) + .unwrap() + .candidates + .iter() + .all(|c| c.fit == "insufficient") + ); +} +#[test] +fn unknown_is_not_a_fit_and_offload_is_explicit() { + let mut r = req(); + r.allow_weight_offload = false; + let p = plan(&host(None), &r).unwrap(); + assert_eq!(p.candidates.len(), 2); + assert_eq!(p.candidates[1].fit, "unknown"); + assert_eq!(p.execution_compatibility, "not_validated"); +} +#[test] +fn shared_pool_once_with_separate_device_ceiling() { + let mut h = host(Some(16 * G)); + h.accelerators[0].memory_kind = MemoryKind::Shared; + let p = plan(&h, &req()).unwrap(); + assert_eq!(p.candidates[1].host_peak_bytes, 14 * G); + assert_eq!(p.candidates[1].device_peak_bytes, 13 * G); + assert_eq!(p.candidates[1].fit, "fits_estimate"); + h.memory.available_bytes = Some(15 * G); + assert_eq!(plan(&h, &req()).unwrap().candidates[1].fit, "insufficient"); + h.memory.available_bytes = Some(24 * G); + h.accelerators[0].memory.available_bytes = None; + assert_eq!(plan(&h, &req()).unwrap().candidates[1].fit, "unknown"); +} +#[test] +fn retained_host_copy_is_not_free() { + let mut r = req(); + r.retains_host_weights = true; + let h = host(Some(16 * G)); + assert_eq!(plan(&h, &r).unwrap().candidates[1].host_peak_bytes, 12 * G); + let mut shared = h; + shared.accelerators[0].memory_kind = MemoryKind::Shared; + assert_eq!( + plan(&shared, &r).unwrap().candidates[1].host_peak_bytes, + 24 * G + ); +} +#[test] +fn equality_fits_reserve_and_concurrency_change_admission() { + let mut r = req(); + assert_eq!( + plan(&host(Some(14 * G)), &r).unwrap().candidates[1].fit, + "fits_estimate" + ); + r.concurrent_requests = 2; + assert_eq!( + plan(&host(Some(14 * G)), &r).unwrap().candidates[1].fit, + "insufficient" + ); +} +#[test] +fn overflow_invalid_versions_and_inconsistent_memory_rejected() { + let h = host(Some(16 * G)); + let mut r = req(); + r.context_tokens = u64::MAX; + assert!(plan(&h, &r).is_err()); + r = req(); + r.weights_bytes = u64::MAX; + assert!(plan(&h, &r).is_err()); + r = req(); + r.schema_version = 2; + assert!(plan(&h, &r).is_err()); + r = req(); + r.concurrent_requests = 0; + assert!(plan(&h, &r).is_err()); + let mut bad = h; + bad.memory.available_bytes = Some(100 * G); + assert!(plan(&bad, &req()).is_err()); +} +#[test] +fn requirements_reject_typo_instead_of_silently_ignoring_it() { + let mut v = serde_json::to_value(req()).unwrap(); + v["weights_bites"] = 1.into(); + assert!(serde_json::from_value::(v).is_err()); +} diff --git a/desktop-core/tests/pool.rs b/desktop-core/tests/pool.rs new file mode 100644 index 00000000..c9552c5d --- /dev/null +++ b/desktop-core/tests/pool.rs @@ -0,0 +1,124 @@ +use std::time::Duration; +use strata_desktop_core::pool::*; +const WAIT: Duration = Duration::from_secs(3); +fn pool(shared: bool, limit: usize) -> Pool { + Pool::new( + (0..3) + .map(|i| Worker { + id: format!("w{i}"), + group: if shared { "g0".into() } else { format!("g{i}") }, + slots: 1, + request_bytes: 10, + }) + .collect(), + (0..3) + .map(|i| ResourceGroup { + id: format!("g{i}"), + slots: 2, + available_bytes: 15, + }) + .collect(), + limit, + ) + .unwrap() +} +#[tokio::test] +async fn three_workers_and_queue_then_handoff() { + let p = pool(false, 2); + let a = p.acquire(vec![0], WAIT).await.unwrap(); + let b = p.acquire(vec![1], WAIT).await.unwrap(); + let c = p.acquire(vec![2], WAIT).await.unwrap(); + assert_eq!(p.snapshot().active, 3); + let pp = p.clone(); + let fourth = tokio::spawn(async move { pp.acquire(vec![0, 1, 2], WAIT).await.unwrap() }); + tokio::task::yield_now().await; + assert_eq!(p.snapshot().queued, 1); + drop(b); + let d = fourth.await.unwrap(); + assert_eq!(d.worker(), 1); + drop((a, c, d)); + assert_eq!(p.snapshot().active, 0); +} +#[tokio::test] +async fn fifo_and_unrelated_worker_avoids_head_of_line_blocking() { + let p = pool(false, 4); + let hold = p.acquire(vec![0], WAIT).await.unwrap(); + let pp = p.clone(); + let first = tokio::spawn(async move { pp.acquire(vec![0], WAIT).await.unwrap() }); + tokio::task::yield_now().await; + let pp = p.clone(); + let second = tokio::spawn(async move { pp.acquire(vec![0], WAIT).await.unwrap() }); + tokio::task::yield_now().await; + let independent = p.acquire(vec![1], WAIT).await.unwrap(); + drop(hold); + let first = first.await.unwrap(); + assert!(!second.is_finished()); + drop(first); + drop(second.await.unwrap()); + drop(independent); + assert_eq!(p.snapshot().active, 0); +} +#[tokio::test] +async fn cancel_timeout_and_queue_bound_release_every_reservation() { + let p = pool(false, 1); + let hold = p.acquire(vec![0], WAIT).await.unwrap(); + let pp = p.clone(); + let pending = tokio::spawn(async move { pp.acquire(vec![0], WAIT).await }); + tokio::task::yield_now().await; + assert!(matches!( + p.acquire(vec![0], WAIT).await, + Err(AdmissionError::Full) + )); + pending.abort(); + let _ = pending.await; + assert_eq!(p.snapshot().queued, 0); + assert!(matches!( + p.acquire(vec![0], Duration::from_millis(10)).await, + Err(AdmissionError::Expired) + )); + assert_eq!(p.snapshot().queued, 0); + drop(hold); + let lease = p.acquire(vec![0], WAIT).await.unwrap(); + drop(lease); + assert_eq!(p.snapshot().active, 0); +} +#[tokio::test] +async fn shared_memory_budget_prevents_alias_overbooking() { + let p = pool(true, 2); + let a = p.acquire(vec![0], WAIT).await.unwrap(); + assert!(matches!( + p.acquire(vec![1], Duration::from_millis(10)).await, + Err(AdmissionError::Expired) + )); + drop(a); + let b = p.acquire(vec![1], WAIT).await.unwrap(); + drop(b); +} +#[tokio::test] +async fn dispatch_cancel_race_does_not_leak() { + let p = pool(false, 8); + for _ in 0..100 { + let a = p.acquire(vec![0], WAIT).await.unwrap(); + let pp = p.clone(); + let b = tokio::spawn(async move { pp.acquire(vec![0], WAIT).await }); + tokio::task::yield_now().await; + drop(a); + b.abort(); + let _ = b.await; + assert_eq!(p.snapshot().active, 0); + assert_eq!(p.snapshot().queued, 0); + } +} +#[tokio::test] +async fn unhealthy_worker_waits_and_other_worker_continues() { + let p = pool(false, 2); + p.set_ready(0, false).unwrap(); + let pp = p.clone(); + let a = tokio::spawn(async move { pp.acquire(vec![0], WAIT).await.unwrap() }); + tokio::task::yield_now().await; + let b = p.acquire(vec![1], WAIT).await.unwrap(); + assert_eq!(p.snapshot().queued, 1); + p.set_ready(0, true).unwrap(); + drop(a.await.unwrap()); + drop(b); +} diff --git a/desktop-core/tests/tunnel_bootstrap.rs b/desktop-core/tests/tunnel_bootstrap.rs new file mode 100644 index 00000000..4d6d0bbe --- /dev/null +++ b/desktop-core/tests/tunnel_bootstrap.rs @@ -0,0 +1,74 @@ +use std::{process::Stdio, time::Duration}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + process::Command, +}; + +#[tokio::test] +async fn owned_tunnel_bootstrap_ends_at_parent_eof() { + let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop")) + .args(["ssh-tunnel", "--stdio-lifetime"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + input.write_all(br#"{"schema_version":1,"ssh":{"schema_version":1,"id":"fixture","host":"localhost"},"listen":"127.0.0.1:0","remote_port":19999,"max_connections":1} +"#).await.unwrap(); + let mut line = String::new(); + tokio::time::timeout( + Duration::from_secs(5), + BufReader::new(child.stdout.take().unwrap()).read_line(&mut line), + ) + .await + .unwrap() + .unwrap(); + let descriptor: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(descriptor["transport"], "ssh"); + assert_eq!( + descriptor["readiness"], + "requires_authenticated_node_handshake" + ); + let endpoint = descriptor["endpoint"] + .as_str() + .unwrap() + .strip_prefix("http://") + .unwrap(); + assert!(std::net::TcpListener::bind(endpoint).is_err()); + drop(input); + assert!( + tokio::time::timeout(Duration::from_secs(5), child.wait()) + .await + .unwrap() + .unwrap() + .success() + ); + assert!(std::net::TcpListener::bind(endpoint).is_ok()); +} + +#[tokio::test] +async fn incomplete_bootstrap_is_not_an_open_listener() { + let mut child = Command::new(env!("CARGO_BIN_EXE_strata-desktop")) + .args(["ssh-tunnel", "--stdio-lifetime"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"{\"schema_version\":1}") + .await + .unwrap(); + let result = tokio::time::timeout(Duration::from_secs(5), child.wait_with_output()) + .await + .unwrap() + .unwrap(); + assert!(!result.status.success()); + assert!(result.stdout.is_empty()); +} diff --git a/desktop/ConnectionWindow.cs b/desktop/ConnectionWindow.cs new file mode 100644 index 00000000..1d1c9d3e --- /dev/null +++ b/desktop/ConnectionWindow.cs @@ -0,0 +1,75 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Layout; +using Avalonia.Media; +using Grpc.Core; + +namespace Strata.Desktop; + +public sealed class ConnectionWindow : Window +{ + private readonly TextBox host = Field("SSH host або alias"); + private readonly TextBox user = Field("Користувач · необов’язково"); + private readonly TextBox sshPort = Field("SSH порт", "22"); + private readonly TextBox nodePort = Field("Порт запущеного node", "18766"); + private readonly TextBox identity = Field("Абсолютний шлях до ключа · необов’язково"); + private readonly TextBox token = new() { PlaceholderText = "Ключ доступу node", PasswordChar = '●', MaxLength = 4096 }; + private readonly TextBlock status = new() { TextWrapping = TextWrapping.Wrap, Foreground = Brush.Parse("#9DABB9") }; + private readonly Button local = new() { Content = "Цей комп’ютер", Padding = new Thickness(18, 12) }; + private readonly Button connect = new() { Content = "Підключитися через SSH", Padding = new Thickness(18, 12) }; + private readonly CancellationTokenSource lifetime = new(); + private bool transferred; + + public ConnectionWindow(IClassicDesktopStyleApplicationLifetime desktop) + { + Title = "Strata · Підключення"; + Width = 650; Height = 730; MinWidth = 540; MinHeight = 600; + Background = Brush.Parse("#10151C"); + var content = new StackPanel { Margin = new Thickness(32), Spacing = 14 }; + content.Children.Add(new TextBlock { Text = "Де працюватиме Strata?", FontSize = 27, Foreground = Brushes.White }); + content.Children.Add(new TextBlock { Text = "Переглядайте обладнання цього комп’ютера або підключіть віддалений вузол.", TextWrapping = TextWrapping.Wrap }); + content.Children.Add(local); + content.Children.Add(new Separator()); + content.Children.Add(new TextBlock { Text = "Віддалений вузол · SSH", FontSize = 19, Foreground = Brush.Parse("#82DFCB") }); + content.Children.Add(host); content.Children.Add(user); + var ports = new Grid { ColumnDefinitions = new ColumnDefinitions("*,14,*") }; + var sshColumn = new StackPanel { Spacing = 5 }; + sshColumn.Children.Add(new TextBlock { Text = "SSH порт", FontSize = 12 }); sshColumn.Children.Add(sshPort); + var nodeColumn = new StackPanel { Spacing = 5 }; + nodeColumn.Children.Add(new TextBlock { Text = "Порт node", FontSize = 12 }); nodeColumn.Children.Add(nodePort); + ports.Children.Add(sshColumn); Grid.SetColumn(nodeColumn, 2); ports.Children.Add(nodeColumn); content.Children.Add(ports); + content.Children.Add(identity); content.Children.Add(token); + content.Children.Add(new TextBlock { Text = "Вузол має бути запущений, SSH-ключ сервера — уже довірений. Ключ доступу node зберігається лише в пам’яті цієї сесії.", TextWrapping = TextWrapping.Wrap, FontSize = 12, Foreground = Brush.Parse("#9DABB9") }); + content.Children.Add(connect); content.Children.Add(status); + Content = new ScrollViewer { Content = content }; + local.Click += async (_, _) => await Open(desktop, false); + connect.Click += async (_, _) => await Open(desktop, true); + Closed += (_, _) => { lifetime.Cancel(); token.Text = ""; if (!transferred) CoreClient.Close(); }; + } + private async Task Open(IClassicDesktopStyleApplicationLifetime desktop, bool remote) + { + local.IsEnabled = connect.IsEnabled = false; + status.Text = remote ? "Підключення через SSH та перевірка доступу…" : "Запуск локального вузла…"; + try { + CoreClient.RemoteConnection? selection = null; + if (remote) { + if (!int.TryParse(sshPort.Text, out var sp) || !int.TryParse(nodePort.Text, out var np)) + throw new InvalidOperationException("Порти мають бути числами від 1 до 65535."); + static string? Optional(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + selection = new(host.Text?.Trim() ?? "", Optional(user.Text), sp, Optional(identity.Text), np, token.Text ?? ""); + } + await CoreClient.OpenSelection(selection, lifetime.Token); + if (lifetime.IsCancellationRequested) { CoreClient.Close(); return; } + token.Text = ""; + var main = new MainWindow(); desktop.MainWindow = main; transferred = true; + main.Show(); Close(); + } + catch (OperationCanceledException) { status.Text = "Підключення скасовано або перевищено час очікування."; } + catch (RpcException e) { status.Text = e.StatusCode == StatusCode.Unauthenticated ? "Ключ доступу node не підійшов. Виправте його та повторіть." : "Вузол недоступний. Перевірте SSH-доступ, довіру до сервера та порт node."; } + catch (InvalidOperationException e) { status.Text = e.Message; } + catch (Exception) { status.Text = "Не вдалося підключитися. Перевірте параметри та доступність Rust core / OpenSSH."; } + finally { local.IsEnabled = connect.IsEnabled = true; } + } + private static TextBox Field(string hint, string? value = null) => new() { PlaceholderText = hint, Text = value, MaxLength = 4096 }; +} diff --git a/desktop/CoreClient.Connection.cs b/desktop/CoreClient.Connection.cs new file mode 100644 index 00000000..3fad8d80 --- /dev/null +++ b/desktop/CoreClient.Connection.cs @@ -0,0 +1,107 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + internal sealed record RemoteConnection(string Host, string? User, int Port, string? IdentityFile, int NodePort, string Token); + private static RemoteConnection? selectedRemote; + private static bool selectedLocal; + public static string SourceLabel => selectedRemote is { } remote ? $"SSH · {remote.Host}" : + Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") != null && !selectedLocal ? "Налаштований вузол" : "Ваш комп’ютер"; + + // Only before the management window/observers exist; never rebind pending UUIDs. + public static async Task OpenSelection(RemoteConnection? remote, CancellationToken token) + { + if (remote != null) ValidateRemote(remote); + await Gate.WaitAsync(token); + try { + if (client != null) throw new InvalidOperationException("Спочатку закрийте поточну сесію керування."); + CloseTransport(); + selectedRemote = remote; + selectedLocal = remote == null; + } finally { Gate.Release(); } + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + await Connect(timeout.Token); + } + private static void ValidateRemote(RemoteConnection remote) + { + static bool Identifier(string value) => value.Length is > 0 and <= 128 && char.IsAsciiLetterOrDigit(value[0]) + && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-'); + if (remote.Host.Length is 0 or > 253 || !char.IsAsciiLetterOrDigit(remote.Host[0]) + || !remote.Host.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-' or ':') + || remote.User is { } user && !Identifier(user) + || remote.Port is < 1 or > 65535 || remote.NodePort is < 1 or > 65535) + throw new InvalidOperationException("Перевірте SSH host, користувача та порти."); + if (remote.IdentityFile is { } identity && (!Path.IsPathFullyQualified(identity) || identity.Length > 4096 || identity.Any(char.IsControl))) + throw new InvalidOperationException("Потрібен абсолютний шлях до SSH-ключа."); + if (remote.Token.Length is < 32 or > 4096 || remote.Token.Any(c => c < 33 || c > 126)) + throw new InvalidOperationException("Потрібен ключ доступу node: 32–4096 друкованих ASCII-символів."); + } + private static string CoreExecutable() + { + var executable = Environment.GetEnvironmentVariable("STRATA_DESKTOP_CORE") + ?? Path.Combine(AppContext.BaseDirectory, OperatingSystem.IsWindows() ? "strata-desktop.exe" : "strata-desktop"); + if (!Path.IsPathFullyQualified(executable) || !File.Exists(executable)) + throw new InvalidOperationException("Rust core не знайдено. Зберіть desktop-core або вкажіть абсолютний STRATA_DESKTOP_CORE."); + return executable; + } + private static async Task BootstrapRemote(RemoteConnection remote, CancellationToken token) + { + ValidateRemote(remote); + credential = remote.Token; + ownedAgent = new Process { StartInfo = new ProcessStartInfo(CoreExecutable()) { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + RedirectStandardInput = true, CreateNoWindow = true + }}; + ownedAgent.StartInfo.ArgumentList.Add("ssh-tunnel"); + ownedAgent.StartInfo.ArgumentList.Add("--stdio-lifetime"); + ownedAgent.StartInfo.Environment.Remove("STRATA_NODE_TOKEN"); + ownedAgent.StartInfo.Environment.Remove("STRATA_BOOTSTRAP_TOKEN"); + ownedAgent.Start(); + _ = Drain(ownedAgent.StandardError); + var config = new JsonObject { + ["schema_version"] = 1, + ["ssh"] = new JsonObject { ["schema_version"] = 1, ["id"] = "desktop", ["host"] = remote.Host, + ["user"] = remote.User, ["port"] = remote.Port, ["identity_file"] = remote.IdentityFile }, + ["listen"] = "127.0.0.1:0", ["remote_port"] = remote.NodePort, ["max_connections"] = 4 + }; + await ownedAgent.StandardInput.WriteLineAsync(config.ToJsonString().AsMemory(), token); + await ownedAgent.StandardInput.FlushAsync(token); + var line = await ReadLineBounded(ownedAgent.StandardOutput, token); + var descriptor = JsonNode.Parse(line) as JsonObject; + if (descriptor?["schema_version"]?.GetValue() != 1 || descriptor["transport"]?.GetValue() != "ssh") + throw new InvalidOperationException("Несумісний SSH transport."); + _ = Drain(ownedAgent.StandardOutput); + return descriptor["endpoint"]?.GetValue(); + } + + public static async Task ConnectionSelfCheck(string path) + { + var config = JsonNode.Parse(await File.ReadAllTextAsync(path))!.AsObject(); + var ssh = config["ssh"]!; + var remote = new RemoteConnection(ssh["host"]!.GetValue(), ssh["user"]?.GetValue(), + ssh["port"]?.GetValue() ?? 22, ssh["identity_file"]?.GetValue(), + config["remote_port"]!.GetValue(), Environment.GetEnvironmentVariable("STRATA_NODE_TOKEN")!); + try { + await OpenSelection(remote with { Token = new string('x', 64) }, CancellationToken.None); + throw new InvalidOperationException("Incorrect credential accepted"); + } catch (Grpc.Core.RpcException e) when (e.StatusCode == Grpc.Core.StatusCode.Unauthenticated) {} + await OpenSelection(remote, CancellationToken.None); + var transportPid = ownedAgent!.Id; + await SelfCheck(); + try { + await OpenSelection(null, CancellationToken.None); + throw new Exception("Active session silently rebound"); + } catch (InvalidOperationException) {} + Close(); + try { using var process = Process.GetProcessById(transportPid); if (!process.HasExited) throw new Exception("Owned transport survived close"); } + catch (ArgumentException) {} + await OpenSelection(null, CancellationToken.None); + await SelfCheck(); + Close(); + Console.WriteLine("PASS: desktop connection selection, real owned SSH, auth retry, no active rebind, cleanup, local gRPC selection."); + } +} diff --git a/desktop/CoreClient.Worker.cs b/desktop/CoreClient.Worker.cs new file mode 100644 index 00000000..98d2e8fc --- /dev/null +++ b/desktop/CoreClient.Worker.cs @@ -0,0 +1,45 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + public static IWorkerRpc WorkerRpc() => new WorkerRpcClient(); + private sealed class WorkerRpcClient : IWorkerRpc + { + public async Task Read(CancellationToken token) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); + timeout.CancelAfter(TimeSpan.FromSeconds(10)); + var c = await Connect(timeout.Token); + var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + ValidateSnapshot(hello, null); + if (!hello.Capabilities.Contains("worker.lifecycle.v1")) return new(hello.AgentEpoch, null); + var state = await c.WorkerStatusAsync(new Empty(), Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + var after = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: timeout.Token); + ValidateSnapshot(after, hello); + if (after.AgentEpoch != hello.AgentEpoch) + throw new RpcException(new Status(StatusCode.Unavailable, "Node changed")); + if (state.ProfileId.Length > 128 || state.Model.Length > 256 || state.Reason.Length > 256 + || state.Phase is not ("stopped" or "starting" or "ready" or "draining" or "failed")) + throw new InvalidOperationException("Invalid worker state"); + return new(hello.AgentEpoch, state, hello.Capabilities.Contains("worker.journal.v1")); + } + public async Task Submit(WorkerCommand command, CancellationToken token) + { + var c = await Connect(token); + return await c.ControlWorkerAsync(command, Headers(), + deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); + } + public async Task Lookup(string id, CancellationToken token) + { + var c = await Connect(token); + return await c.OperationStatusAsync(new OperationQuery { OperationId = id }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: token); + } + } +} diff --git a/desktop/CoreClient.cs b/desktop/CoreClient.cs new file mode 100644 index 00000000..75a1c1de --- /dev/null +++ b/desktop/CoreClient.cs @@ -0,0 +1,235 @@ +using System.Diagnostics; +using System.Net; +using System.Security.Cryptography; +using System.Text.Json.Nodes; +using Google.Protobuf; +using Grpc.Core; +using Grpc.Net.Client; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + private static readonly SemaphoreSlim Gate = new(1); + private static GrpcChannel? channel; + private static Strata.Node.V1.Node.NodeClient? client; + private static Process? ownedAgent; + private static string credential = ""; + private static Metadata Headers() => new() { { "authorization", "Bearer " + credential } }; + + private static async Task Connect(CancellationToken cancellationToken) + { + await Gate.WaitAsync(cancellationToken); + try + { + if (client != null && (ownedAgent == null || !ownedAgent.HasExited)) return client; + CloseTransport(); + var endpoint = selectedLocal ? null : Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT"); + if (selectedRemote is { } remote) endpoint = await BootstrapRemote(remote, cancellationToken); + else if (endpoint == null) + { + var executable = CoreExecutable(); + credential = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + ownedAgent = new Process { StartInfo = new ProcessStartInfo(executable) { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + RedirectStandardInput = true, CreateNoWindow = true + }}; + foreach (var arg in new[] { "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_BOOTSTRAP_TOKEN", "--stdio-lifetime" }) + ownedAgent.StartInfo.ArgumentList.Add(arg); + ownedAgent.StartInfo.Environment["STRATA_BOOTSTRAP_TOKEN"] = credential; + ownedAgent.Start(); + ownedAgent.StartInfo.Environment.Remove("STRATA_BOOTSTRAP_TOKEN"); + // No remote stderr or credential data is surfaced; drain with no accumulation. + _ = Drain(ownedAgent.StandardError); + var line = await ReadLineBounded(ownedAgent.StandardOutput, cancellationToken); + var descriptor = JsonNode.Parse(line) as JsonObject; + if (descriptor?["schema_version"]?.GetValue() != 1) + throw new InvalidOperationException("Несумісний bootstrap node."); + endpoint = descriptor["endpoint"]?.GetValue(); + _ = Drain(ownedAgent.StandardOutput); + } + else credential = Environment.GetEnvironmentVariable("STRATA_NODE_TOKEN") + ?? throw new InvalidOperationException("Потрібен STRATA_NODE_TOKEN для налаштованого node."); + if (credential.Length < 32 || credential.Length > 4096 || credential.Any(c => c < 33 || c > 126)) + throw new InvalidOperationException("Некоректний credential node."); + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme != "http" + || !IPAddress.TryParse(uri.Host.Trim('[', ']'), out var ip) || !IPAddress.IsLoopback(ip) + || uri.AbsolutePath != "/" || uri.UserInfo.Length != 0 || uri.Query.Length != 0 || uri.Fragment.Length != 0) + throw new InvalidOperationException("Node має бути loopback або локальним SSH-тунелем."); + channel = GrpcChannel.ForAddress(uri, new GrpcChannelOptions { + MaxReceiveMessageSize = 2 * 1024 * 1024 + 1024, + MaxSendMessageSize = 2 * 1024 * 1024 + 1024, + HttpHandler = new SocketsHttpHandler { UseProxy = false, AllowAutoRedirect = false } + }); + var connected = new Strata.Node.V1.Node.NodeClient(channel); + var hello = await connected.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: cancellationToken); + if (hello.ProtocolVersion != 1 || !hello.Capabilities.Contains("hardware.v1") || !hello.Capabilities.Contains("plan.v1")) + throw new InvalidOperationException("Node не підтримує потрібний контракт."); + client = connected; + return connected; + } + catch { CloseTransport(); throw; } + finally { Gate.Release(); } + } + + internal sealed record ConnectionState(string Phase, string? Epoch = null, ulong Sequence = 0, uint ActiveResponses = 0); + + public static async Task Observe(Action publish, CancellationToken token) + { + var delay = 200; + Snapshot? last = null; + while (!token.IsCancellationRequested) + { + try + { + publish(new("connecting")); + using var startup = CancellationTokenSource.CreateLinkedTokenSource(token); + startup.CancelAfter(TimeSpan.FromSeconds(15)); + var c = await Connect(startup.Token); + var hello = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); + ValidateSnapshot(hello, last); + using var call = c.Watch(new Cursor { AgentEpoch = hello.AgentEpoch, Sequence = hello.Sequence }, Headers(), cancellationToken: token); + var pending = call.ResponseStream.MoveNext(token); + var initial = true; + while (!token.IsCancellationRequested) + { + Snapshot next; + using var tick = CancellationTokenSource.CreateLinkedTokenSource(token); + var timer = Task.Delay(TimeSpan.FromSeconds(5), tick.Token); + if (await Task.WhenAny(pending, timer) == pending) + { + tick.Cancel(); + if (!await pending) throw new RpcException(new Status(StatusCode.Unavailable, "Node subscription ended")); + next = call.ResponseStream.Current; + // Heartbeat may have overtaken an already buffered state event. + if (last != null && next.AgentEpoch == last.AgentEpoch && next.Sequence < last.Sequence) + { pending = call.ResponseStream.MoveNext(token); continue; } + pending = call.ResponseStream.MoveNext(token); + } + else + { + token.ThrowIfCancellationRequested(); + if (initial) throw new RpcException(new Status(StatusCode.DeadlineExceeded, "Node snapshot timeout")); + next = await c.HandshakeAsync(new Hello { ProtocolVersion = 1 }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(5), cancellationToken: token); + } + ValidateSnapshot(next, last); + if (!initial && last != null && next.AgentEpoch != last.AgentEpoch) + throw new RpcException(new Status(StatusCode.Unavailable, "Node epoch changed")); + last = next; initial = false; delay = 200; + publish(new("ready", next.AgentEpoch, next.Sequence, next.ActiveResponses)); + } + } + catch (OperationCanceledException) when (token.IsCancellationRequested) { break; } + catch (RpcException) when (token.IsCancellationRequested) { break; } + catch (RpcException e) when (e.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) + { publish(new("auth_error")); return; } + catch (RpcException e) when (e.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented or StatusCode.InvalidArgument) + { publish(new("protocol_error")); return; } + catch (InvalidOperationException) { publish(new("configuration_error")); return; } + catch (Exception e) when (e is RpcException or IOException or OperationCanceledException) + { publish(new("disconnected")); } + try { await Task.Delay(Math.Min(10000, delay + Random.Shared.Next(0, 101)), token); } + catch (OperationCanceledException) { break; } + delay = Math.Min(10000, delay * 2); + } + } + private static void ValidateSnapshot(Snapshot next, Snapshot? previous) + { + if (next.ProtocolVersion != 1 || !next.FullSnapshot || next.AgentEpoch.Length is 0 or > 128 + || next.Sequence == 0 || next.Capabilities.Count > 64 || next.Capabilities.Any(c => c.Length > 128) + || (previous != null && previous.AgentEpoch == next.AgentEpoch && previous.Sequence > next.Sequence)) + throw new RpcException(new Status(StatusCode.FailedPrecondition, "Invalid node snapshot")); + } + + public static async Task Run(CancellationToken cancellationToken, params string[] args) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + var c = await Connect(timeout.Token); + JsonDocument result; + if (args is ["hardware"]) + result = await c.HardwareAsync(new Empty(), Headers(), deadline: DateTime.UtcNow.AddSeconds(10), cancellationToken: timeout.Token); + else if (args is ["plan", var path]) + { + await using var file = File.OpenRead(path); + using var data = new MemoryStream(); + var buffer = new byte[8192]; + int count; + while ((count = await file.ReadAsync(buffer, timeout.Token)) > 0) { + if (data.Length + count > 1024 * 1024) throw new InvalidOperationException("Профіль перевищує 1 MiB."); + data.Write(buffer, 0, count); + } + result = await c.PlanAsync(new JsonDocument { Json = ByteString.CopyFrom(data.ToArray()) }, Headers(), + deadline: DateTime.UtcNow.AddSeconds(10), cancellationToken: timeout.Token); + } + else throw new InvalidOperationException("Непідтриманий виклик core."); + var value = JsonNode.Parse(result.Json.Span) as JsonObject ?? throw new InvalidOperationException("Некоректний документ node."); + if (value["schema_version"]?.GetValue() != 1) throw new InvalidOperationException("Несумісна версія документа node."); + return value; + } + private static async Task ReadLineBounded(StreamReader reader, CancellationToken token) + { + var text = new System.Text.StringBuilder(); var buffer = new char[1]; + while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { + if (buffer[0] == '\n') return text.ToString(); + if (text.Length >= 4096) throw new InvalidOperationException("Node bootstrap завеликий."); + text.Append(buffer[0]); + } + throw new InvalidOperationException("Node не запустився."); + } + private static async Task Drain(StreamReader reader) + { + try { var buffer = new char[4096]; while (await reader.ReadAsync(buffer) > 0) {} } + catch (ObjectDisposedException) {} catch (IOException) {} + } + public static void Close() + { + CloseTransport(); selectedRemote = null; selectedLocal = false; + } + private static void CloseTransport() + { + client = null; channel?.Dispose(); channel = null; credential = ""; + if (ownedAgent is { } process) { + ownedAgent = null; + try { process.StandardInput.Close(); if (!process.WaitForExit(1500)) process.Kill(entireProcessTree: true); } + catch (InvalidOperationException) {} + finally { process.Dispose(); } + } + } + public static async Task ReconnectSelfCheck(bool requireNewEpoch = true) + { + if (Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") == null) + throw new InvalidOperationException("Reconnect check requires an isolated external test node."); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + string? firstEpoch = null; bool disconnected = false; bool recovered = false; + await Observe(state => { + Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(state)); + if (state.Phase == "ready") { + firstEpoch ??= state.Epoch; + if (disconnected && (requireNewEpoch ? state.Epoch != firstEpoch : state.Epoch == firstEpoch)) {recovered = true; timeout.Cancel();} + } + if (state.Phase == "disconnected") disconnected = true; + }, timeout.Token); + if (!recovered) throw new InvalidOperationException("No observed recovery to the expected epoch."); + Console.WriteLine(requireNewEpoch ? "PASS: C# observer recovered after isolated node restart; no inference replay." : "PASS: C# observer recovered after owned SSH transport loss; node epoch unchanged."); + } + + public static async Task SelfCheck() + { + var h = await Run(CancellationToken.None, "hardware"); + if (h["memory"] is not JsonObject || h["accelerators"] is not JsonArray) + throw new InvalidOperationException("Missing hardware contract fields."); + var p = await Run(CancellationToken.None, "plan", Path.Combine(AppContext.BaseDirectory, "example-requirements.json")); + if (p["evidence"]?.GetValue() != "estimated" || p["candidates"] is not JsonArray { Count: > 0 }) + throw new InvalidOperationException("Missing planning contract fields."); + var c = await Connect(CancellationToken.None); + using var watch = c.Watch(new Cursor(), Headers(), deadline: DateTime.UtcNow.AddSeconds(5)); + if (!await watch.ResponseStream.MoveNext(CancellationToken.None) || !watch.ResponseStream.Current.FullSnapshot) + throw new InvalidOperationException("Missing node snapshot."); + Console.WriteLine("PASS: C# → gRPC/HTTP2 → Rust node: authenticated handshake, hardware, plan, snapshot; no inference."); + } +} diff --git a/desktop/MainWindow.cs b/desktop/MainWindow.cs new file mode 100644 index 00000000..79cf20ba --- /dev/null +++ b/desktop/MainWindow.cs @@ -0,0 +1,201 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Platform.Storage; +using System.Text.Json.Nodes; + +namespace Strata.Desktop; + +public sealed class MainWindow : Window +{ + private static readonly IBrush Accent = Brush.Parse("#82DFCB"); + private static readonly IBrush Muted = Brush.Parse("#9DABB9"); + private readonly StackPanel hardwareCards = new() { Spacing = 12 }; + private readonly StackPanel planCards = new() { Spacing = 12 }; + private readonly TextBlock status = Text("Підключення до gRPC-вузла…", 13, Muted); + private readonly TextBlock connectionStatus = Text("Вузол: підключення…", 13, Muted); + private readonly TextBlock details = Text("", 13, Muted); + private readonly Button refresh = Action("Оновити обладнання"); + private readonly Button import = Action("Відкрити профіль…"); + private readonly Button example = Action("Приклад оцінки"); + private readonly WorkerController worker = new(CoreClient.WorkerRpc()); + private readonly TextBlock workerStatus = Text("Модель: перевірка вузла…", 14, Muted); + private readonly Button startWorker = Action("Запустити модель"); + private readonly Button stopWorker = Action("Зупинити модель"); + private readonly CancellationTokenSource lifetime = new(); + + public MainWindow() + { + Title = "Strata · " + CoreClient.SourceLabel; + Width = 1200; Height = 840; MinWidth = 900; MinHeight = 650; + Background = Brush.Parse("#10151C"); + var root = new Grid { ColumnDefinitions = new ColumnDefinitions("220,*") }; + var sidebar = new StackPanel { Margin = new Thickness(24, 32), Spacing = 24 }; + sidebar.Children.Add(Text("strata", 34, Accent, FontWeight.Bold)); + sidebar.Children.Add(Text("ЛОКАЛЬНИЙ ІНТЕЛЕКТ", 10, Muted)); + sidebar.Children.Add(new Border { Background = Brush.Parse("#243830"), CornerRadius = new CornerRadius(8), + Padding = new Thickness(14, 12), Child = Text(CoreClient.SourceLabel, 15, Accent, FontWeight.SemiBold) }); + sidebar.Children.Add(Text("Моделі та підготовка\nНаступний етап", 13, Muted)); + sidebar.Children.Add(Text("Автопідбір\nНаступний етап", 13, Muted)); + sidebar.Children.Add(new Border { Height = 1, Background = Brush.Parse("#303B46") }); + sidebar.Children.Add(Text("DESKTOP PREVIEW", 10, Accent)); + sidebar.Children.Add(Text("Спільний інтерфейс.\nОкреме Rust-ядро.\nДані на вашому пристрої.", 12, Muted)); + root.Children.Add(new Border { Background = Brush.Parse("#161E27"), Child = sidebar }); + var page = new StackPanel { Margin = new Thickness(34, 30), Spacing = 20 }; + page.Children.Add(Text("Рушій починається з вашого заліза", 27, Brushes.White, FontWeight.SemiBold)); + page.Children.Add(Text("Визначте ресурси. Перевірте бюджет пам’яті. Оберіть наступний крок.", 14, Muted)); + var toolbar = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + toolbar.Children.Add(refresh); toolbar.Children.Add(import); toolbar.Children.Add(example); + page.Children.Add(toolbar); + page.Children.Add(status); + page.Children.Add(connectionStatus); + page.Children.Add(workerStatus); + var workerActions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 }; + startWorker.IsEnabled = stopWorker.IsEnabled = false; + workerActions.Children.Add(startWorker); workerActions.Children.Add(stopWorker); + page.Children.Add(workerActions); + startWorker.Click += async (_, _) => await WorkerCommand(true); + stopWorker.Click += async (_, _) => await WorkerCommand(false); + var columns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,24,*") }; + var left = new StackPanel { Spacing = 14 }; + left.Children.Add(Text("ОБЛАДНАННЯ", 11, Accent, FontWeight.SemiBold)); + left.Children.Add(hardwareCards); left.Children.Add(details); + columns.Children.Add(left); + var right = new StackPanel { Spacing = 14 }; + right.Children.Add(Text("ПЛАН РОЗМІЩЕННЯ", 11, Accent, FontWeight.SemiBold)); + right.Children.Add(planCards); Grid.SetColumn(right, 2); columns.Children.Add(right); + page.Children.Add(columns); + var scroll = new ScrollViewer { Content = page, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled }; + Grid.SetColumn(scroll, 1); root.Children.Add(scroll); Content = root; + planCards.Children.Add(Card("Спочатку — вимоги моделі", "Відкрийте JSON-профіль із runtime-розмірами ваг, KV і буферів. Або перегляньте явно позначений синтетичний приклад.")); + planCards.Children.Add(Card("Що вже працює", "Локальне визначення обладнання та оцінка пам’яті. Керування встановленою моделлю доступне на налаштованому керованому вузлі. Завантаження моделей і автоматичні бенчмарки ще попереду.")); + refresh.Click += async (_, _) => await Busy(RefreshHardware); + import.Click += async (_, _) => await PickProfile(); + example.Click += async (_, _) => await Busy(() => LoadPlan(Path.Combine(AppContext.BaseDirectory, "example-requirements.json"))); + Opened += async (_, _) => { + _ = ObserveWorker(); + await Busy(RefreshHardware); + _ = Task.Run(() => CoreClient.Observe(state => Avalonia.Threading.Dispatcher.UIThread.Post(() => { + connectionStatus.Text = state.Phase switch { + "ready" => $"Вузол підключений · активних запитів: {state.ActiveResponses}", + "auth_error" => "Вузол: перевірте credential підключення", + "protocol_error" => "Вузол: несумісний протокол", + "configuration_error" => "Вузол: перевірте налаштування підключення", + "connecting" => "Вузол: підключення…", + _ => "Зв’язок із вузлом втрачено · відновлення…" + }; + connectionStatus.Foreground = state.Phase == "ready" ? Accent : Muted; + }), lifetime.Token)); + }; + Closed += (_, _) => lifetime.Cancel(); + } + + private void RenderWorker() + { + var w = worker.View; + string label = w.Phase switch { + "ready" => "Модель готова", "stopped" => "Модель зупинена", + "starting" => "Завантаження моделі…", "draining" => "Завершення активних запитів…", + "failed" => "Помилка моделі", "unmanaged" => "На цьому вузлі немає профілю запуску моделі", + "auth_error" => "Перевірте доступ до вузла", "reconcile" => "Потрібна звірка стану", + _ => "Стан моделі недоступний · відновлення зв’язку…" + }; + workerStatus.Text = label + (w.Model.Length > 0 ? " · " + w.Model : "") + + (w.Detail.Length > 0 ? "\n" + w.Detail : "") + + (w.OperationId.Length > 0 ? "\nОперація: " + w.OperationId : ""); + startWorker.IsEnabled = w.CanStart; stopWorker.IsEnabled = w.CanStop; + } + private async Task ObserveWorker() + { + try { + while (!lifetime.IsCancellationRequested) { + await worker.Refresh(lifetime.Token); RenderWorker(); + await Task.Delay(1000, lifetime.Token); + } + } catch (OperationCanceledException) {} + } + private async Task WorkerCommand(bool start) + { + startWorker.IsEnabled = stopWorker.IsEnabled = false; + try { await worker.Command(start, lifetime.Token); RenderWorker(); } + catch (OperationCanceledException) {} + } + + private async Task Busy(Func action) + { + refresh.IsEnabled = import.IsEnabled = example.IsEnabled = false; + status.Text = "Зчитування ресурсів вузла…"; status.Foreground = Muted; + try { await action(); status.Text = "Готово · дані вузла · жодних inference-запитів"; } + catch (OperationCanceledException) { status.Text = "Зчитування скасовано або перевищено час очікування."; } + catch (Exception e) { status.Text = e.Message; status.Foreground = Brush.Parse("#FFBF87"); } + finally { refresh.IsEnabled = import.IsEnabled = example.IsEnabled = true; } + } + + private async Task RefreshHardware() + { + var h = await CoreClient.Run(lifetime.Token, "hardware"); + hardwareCards.Children.Clear(); + hardwareCards.Children.Add(Card(S(h, "cpu_name"), $"{S(h, "os")} / {S(h, "architecture")} · {h["logical_cpus"]} потоків\n" + + string.Join(" · ", h["cpu_features"]!.AsArray().Select(v => v!.GetValue())))); + hardwareCards.Children.Add(Card("Оперативна пам’ять", $"{Memory(h["memory"]?["available_bytes"])} доступно\n{Memory(h["memory"]?["total_bytes"])} загалом")); + foreach (var g in h["accelerators"]!.AsArray().OfType()) + { + var shared = S(g, "memory_kind") == "shared"; + hardwareCards.Children.Add(Card(S(g, "name"), shared + ? "Спільна пам’ять із CPU\nЛіміт GPU ще не визначено" + : $"{Memory(g["memory"]?["available_bytes"])} доступно з {Memory(g["memory"]?["total_bytes"])}\nДрайвер: {S(g, "driver")}")); + } + if (h["accelerators"]!.AsArray().Count == 0) + hardwareCards.Children.Add(Card("GPU не визначено", "Це не підтверджує відсутність GPU. Перевірте доступність драйвера й підтримку probe.")); + details.Text = "NPU та сумісність inference-рушіїв перевірятимуться окремо."; + if (h["warnings"] is JsonArray warnings && warnings.Count > 0) + details.Text += "\n\n" + string.Join("\n", warnings.Select(v => v!.GetValue())); + } + + private async Task PickProfile() + { + await Busy(async () => { + var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { + Title = "Профіль вимог моделі (JSON)", AllowMultiple = false, + // macOS type associations can hide valid JSON; the core validates contents. + FileTypeFilter = [FilePickerFileTypes.All] + }); + if (files.Count == 0) return; + var path = files[0].TryGetLocalPath() ?? throw new InvalidOperationException("Потрібен локальний JSON-файл."); + await LoadPlan(path); + }); + } + + private async Task LoadPlan(string path) + { + var p = await CoreClient.Run(lifetime.Token, "plan", path); + planCards.Children.Clear(); + planCards.Children.Add(Card(S(p, "model"), $"Контекст {p["context_tokens"]} · запитів {p["concurrent_requests"]}\nОцінка пам’яті; швидкість і сумісність ще не перевірені.")); + foreach (var c in p["candidates"]!.AsArray().OfType()) + { + var fit = S(c, "fit"); + var label = fit switch { "fits_estimate" => "Вкладається за оцінкою", "insufficient" => "Недостатньо пам’яті", _ => "Потрібні додаткові дані" }; + var message = $"{label}\nПік RAM: {Memory(c["host_peak_bytes"])} · бюджет {Memory(c["host_budget_bytes"])}"; + if (S(c, "device") != "cpu") message += $"\nПік GPU: {Memory(c["device_peak_bytes"])} · бюджет {Memory(c["device_budget_bytes"])}\nВаг на GPU: {c["device_weight_percent"]}%"; + message += "\n" + string.Join("\n", c["reasons"]!.AsArray().Select(v => v!.GetValue())); + planCards.Children.Add(Card($"{S(c, "device")} · {S(c, "placement")}", message.Trim(), fit == "fits_estimate")); + } + } + + private static string S(JsonNode n, string key) => n[key]?.GetValue() ?? "невідомо"; + private static string Memory(JsonNode? n) => n is null ? "невідомо" : $"{n.GetValue() / 1073741824.0:0.0} GiB"; + private static Button Action(string text) => new() { Content = text, Padding = new Thickness(14, 10), CornerRadius = new CornerRadius(7) }; + private static TextBlock Text(string text, double size, IBrush brush, FontWeight? weight = null) => new() { + Text = text, FontSize = size, Foreground = brush, FontWeight = weight ?? FontWeight.Normal, + TextWrapping = TextWrapping.Wrap + }; + private static Border Card(string title, string body, bool positive = false) + { + var content = new StackPanel { Spacing = 9 }; + content.Children.Add(Text(title, 17, positive ? Accent : Brushes.White, FontWeight.SemiBold)); + content.Children.Add(Text(body, 13, Muted)); + return new Border { Background = Brush.Parse("#1A2430"), BorderBrush = Brush.Parse(positive ? "#3D6D61" : "#2C3947"), + BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(12), Padding = new Thickness(20), Child = content }; + } +} diff --git a/desktop/Program.cs b/desktop/Program.cs new file mode 100644 index 00000000..8849f4b5 --- /dev/null +++ b/desktop/Program.cs @@ -0,0 +1,63 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Styling; +using Avalonia.Themes.Fluent; + +namespace Strata.Desktop; + +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + try + { + if (args is ["--self-check-connection", var profile]) + { + try { CoreClient.ConnectionSelfCheck(profile).GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } + if (args is ["--self-check-worker"]) + { + try { CoreClient.WorkerSelfCheck().GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } + if (args is ["--self-check-tunnel-reconnect"]) + { + try { CoreClient.ReconnectSelfCheck(false).GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } + if (args is ["--self-check-reconnect"]) + { + try { CoreClient.ReconnectSelfCheck().GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } + if (args is ["--self-check"]) + { + try { CoreClient.SelfCheck().GetAwaiter().GetResult(); return 0; } + catch (Exception e) { Console.Error.WriteLine(e.Message); return 1; } + } + BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + return 0; + } + finally { CoreClient.Close(); } + } + public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure().UsePlatformDetect(); +} + +public sealed class App : Application +{ + public override void Initialize() + { + Name = "Strata"; + RequestedThemeVariant = ThemeVariant.Dark; + Styles.Add(new FluentTheme()); + } + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + desktop.MainWindow = Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") != null + ? new MainWindow() : new ConnectionWindow(desktop); + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/desktop/README.md b/desktop/README.md new file mode 100644 index 00000000..9a4210f7 --- /dev/null +++ b/desktop/README.md @@ -0,0 +1,141 @@ +# Strata desktop preview + +Shared Avalonia 12.1.3 / .NET 10 UI with an independent Rust 1.99 core. +The preview reads local hardware and evaluates explicit memory requirements. +It does not start inference, download a model, or change a running server. + +## Build and run + +From the repository root: + +```sh +cargo build --locked --manifest-path desktop-core/Cargo.toml +dotnet restore desktop/Strata.Desktop.csproj --locked-mode +dotnet build desktop/Strata.Desktop.csproj --no-restore +dotnet desktop/bin/Debug/net10.0/Strata.Desktop.dll --self-check +dotnet run --project desktop/Strata.Desktop.csproj --no-build +``` + +The headless integration check boots the actual app-local Rust node and uses +generated C# protobuf clients over authenticated gRPC/HTTP2 for handshake, +hardware, memory planning and state subscription. The node is a persistent +process for the lifetime of the preview; it only provides inventory/planning. +`STRATA_DESKTOP_CORE` may override it with an absolute trusted executable path. +CLI users do not need .NET: + +```sh +desktop-core/target/debug/strata-desktop hardware +desktop-core/target/debug/strata-desktop plan desktop-core/examples/requirements.json +``` + +For a local macOS application bundle, run `sh desktop/package-macos.sh`. +The result is `artifacts/desktop/Strata Preview.app`. This is a developer build, +not a signed/notarized release. It includes the .NET runtime and Rust helper. +Windows and Linux have a CI build/headless integration job; their GUI and +packaging still require native verification. Hosted CI has not run yet. + +## What the numbers mean + +Requirements schema v1 uses runtime allocation bytes, not compressed file size. +The example is synthetic, explicitly labelled, and describes no real model. +KV = bytes per token per request × context × concurrency. CPU memory includes +weights, KV, workspace, load scratch and host overhead. Dedicated GPU candidates +check both RAM and VRAM, retaining a host weight copy when requested. Weight +offload candidates are emitted only with explicit backend support in the profile. +Shared memory is counted once, with an independent device allocation ceiling. +Unknown limits remain unknown. A fit is an estimate, never proof of backend +compatibility, quality or speed; available memory must be rechecked before load. + +Inventory currently covers CPU/RAM and runtime CPU features, macOS display +inventory and NVIDIA via nvidia-smi on Windows/Linux. NPU/provider capabilities +and non-NVIDIA GPU probes on Windows/Linux are not implemented. A missing +probe result must not be interpreted as absent hardware. + +The helper launches fixed probes without a shell, limits their output and time, +and collects no prompts, process list, credentials or hostname. Closing the UI +closes stdin of its owned inventory-only node. An external node is never stopped. +The credential is generated in memory and passed via a private child environment; +it is never placed in command arguments or bootstrap output. + +To use an existing local node or SSH-forwarded node, set `STRATA_NODE_ENDPOINT` +to its loopback HTTP URL and `STRATA_NODE_TOKEN` from your credential store. The +same gRPC contract is used; there is no automatic SSH provisioning yet. These +environment values are not persisted. Do not place credentials in Git. + +## Verification, 2026-10-04 + +On Apple M3 / macOS / 24 GiB: 11 Rust tests, strict Clippy, desktop build and +headless hardware/plan integration passed. Real UI hardware cards, example +planning and native JSON picker were exercised. Synthetic tests cover 8/16 GiB, +offload, shared/unknown memory, retained copies, concurrency and overflow. +No inference code changed; no speed or model-quality claim is made. + +## Next delivery units + +- STRA-40: actual model metadata, resumable acquisition and preparation. +- STRA-42: backend capability probes including CPU/GPU/NPU. +- STRA-44: opt-in comparable benchmarks and measured recipe selection. +- STRA-50–53: remote SSH preflight, provisioning, tunnel and UI lifecycle. +- STRA-47: signed platform distributions and native release gates. + +See [product architecture](../docs/cross-platform-application.md) for boundaries. + +The Rust CLI now also has an experimental [pool gateway](../desktop-core/POOL.md) +and [SSH preflight](../desktop-core/REMOTE.md). They are separate CLI capabilities; +the desktop covers node inventory, memory planning and an installed worker’s lifecycle. + +Shared node implementation: [gRPC contract and commands](../desktop-core/GRPC.md). +On macOS the C#→gRPC→Rust self-check passed. Rust integration tests also cover +harness HTTP→gRPC→worker streaming with synthetic responses, auth, versioning, +observer limits, reconnect snapshots and interrupted-stream quarantine. +This is transport evidence, not Metal inference or Windows/Linux qualification. + +Connection recovery: the window displays node connection separately from the +hardware query result. The observer reconnects after transport failure, replaces +state on agent epoch changes and stops automatic retries for auth/protocol errors. +Run `python desktop/tests/reconnect.py` after building to test C# recovery against +an isolated node restart. This test creates and cleans its own local processes; +it never sends model requests or contacts the user's remote endpoint. + + +## Managed model controls + +For an operator-configured persistent node started with `--worker-profile`, set +`STRATA_NODE_ENDPOINT` to its loopback address (or existing SSH forward) and +`STRATA_NODE_TOKEN` to its private credential before launching the desktop. +See the [node commands/profile format](../desktop-core/GRPC.md). The window shows +the model’s phase and provides **Запустити модель** / **Зупинити модель**. Neither +opening nor closing the window changes the model’s running state. With the default +inventory-only node, lifecycle buttons remain disabled. + +During a lost connection the app queries the existing operation UUID instead of +resending Start/Stop. Unknown outcomes or a replaced node block further actions +and show the UUID for operator reconciliation. Installing/downloading a model, +selecting another installed profile and creating SSH tunnels are not yet exposed. + +`python desktop/tests/lifecycle.py` runs the real C# controller/gRPC/managed-child +integration with synthetic data. On macOS it passed start/stop, lost-ack status +recovery, client-close independence and exact Responses byte checks. The test is +in the three-platform CI definition; hosted Actions and interactive inspection of +the new buttons on all platforms remain unverified. No model quality/speed claim. + + +Managed nodes can now use a private durable operation journal via +`--worker-profile PROFILE.json --journal /absolute/private-directory/operations.jsonl`. +Completed command outcomes remain queryable after node restart; interrupted +commands are marked indeterminate and block further mutations for reconciliation. +The desktop can reconcile a pending command against a replacement node that +advertises durable history, without submitting it again. The window's own pending +operation is still in memory; restoring it after closing the app remains pending. + + +## Existing remote node via managed SSH + +The Rust core now owns a loopback SSH transport: +`strata-desktop ssh-tunnel /absolute/private/ssh-tunnel.json`. +Point `STRATA_NODE_ENDPOINT` at its printed endpoint and use the remote node's +credential. The same desktop lifecycle works through this connection. +See [profile and verification](../desktop-core/REMOTE.md). A real isolated +OpenSSH/gRPC integration and forced SSH-disconnect recovery passed on macOS. +Remote node/model installation and the desktop connection form remain pending; +this command does not provision or restart the remote runtime. diff --git a/desktop/Strata.Desktop.csproj b/desktop/Strata.Desktop.csproj new file mode 100644 index 00000000..68e747e2 --- /dev/null +++ b/desktop/Strata.Desktop.csproj @@ -0,0 +1,32 @@ + + + WinExe + net10.0 + enable + enable + true + false + strata-desktop.exe + strata-desktop + ../desktop-core/target/debug/$(CoreName) + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git a/desktop/WorkerController.cs b/desktop/WorkerController.cs new file mode 100644 index 00000000..507124ae --- /dev/null +++ b/desktop/WorkerController.cs @@ -0,0 +1,104 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal sealed record WorkerReading(string Epoch, WorkerState? Worker, bool Durable = false); +internal interface IWorkerRpc +{ + Task Read(CancellationToken token); + Task Submit(WorkerCommand command, CancellationToken token); + Task Lookup(string id, CancellationToken token); +} +internal sealed record WorkerView(string Phase, string Model = "", string Detail = "", bool CanStart = false, + bool CanStop = false, string OperationId = "", uint Pid = 0); + +// One outstanding command, never automatically resubmitted. Polling is read-only. +internal sealed class WorkerController(IWorkerRpc rpc) +{ + private readonly SemaphoreSlim gate = new(1); + private WorkerCommand? pending; + private bool uncertain; + public WorkerView View { get; private set; } = new("connecting"); + private static bool Startable(WorkerState w) => w.Reason != "reconciliation_required" && w.Pid == 0 && w.Phase is "stopped" or "failed"; + private static bool Stoppable(WorkerState w) => w.Reason != "reconciliation_required" && w.Pid != 0 && w.Phase is "ready" or "failed"; + private void Show(WorkerState w, string detail = "") + { + View = new(w.Phase, w.Model, detail.Length > 0 ? detail : w.Reason, + pending == null && Startable(w), pending == null && Stoppable(w), pending?.OperationId ?? "", w.Pid); + } + public async Task Refresh(CancellationToken token) + { + await gate.WaitAsync(token); + try { await RefreshLocked(token); } + catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException) + { Offline(e); } + finally { gate.Release(); } + } + private async Task RefreshLocked(CancellationToken token) + { + var reading = await rpc.Read(token); + if (pending != null && reading.Epoch != pending.ExpectedEpoch && !reading.Durable) uncertain = true; + if (reading.Worker == null) { + View = new("unmanaged", Detail: pending == null ? "" : "Операцію неможливо звірити: вузол змінився.", OperationId: pending?.OperationId ?? ""); + return; + } + if (pending == null) { Show(reading.Worker); return; } + if (uncertain) { Show(reading.Worker, "Вузол або журнал змінився. Потрібна ручна звірка операції; повторного запуску немає."); return; } + WorkerOperation op; + try { op = await rpc.Lookup(pending.OperationId, token); } + catch (RpcException e) when (e.StatusCode == StatusCode.NotFound) { + uncertain = true; Show(reading.Worker, "Результат операції невідомий. Команду не повторено."); return; + } + Validate(op, pending.OperationId); + if (op.Status == "indeterminate") { uncertain = true; Show(reading.Worker, "Операцію перервано рестартом. Потрібна звірка; команду не повторено."); return; } + // Recheck epoch and phase after lookup: a replacement may have occurred between RPCs. + var after = await rpc.Read(token); + if (after.Epoch != reading.Epoch || after.Worker == null || (after.Epoch != pending.ExpectedEpoch && !after.Durable)) { + uncertain = true; View = new("reconcile", Detail: "Вузол змінився. Команду не повторено.", OperationId: pending.OperationId); return; + } + if (op.Status is "succeeded" or "failed") { + pending = null; + Show(after.Worker, op.Status == "succeeded" ? "Операцію завершено." : "Операція не виконана: " + op.Reason); + } + else Show(after.Worker, "Операція виконується…"); + } + public async Task Command(bool start, CancellationToken token) + { + await gate.WaitAsync(token); + try { + if (pending != null) return; + var reading = await rpc.Read(token); + var w = reading.Worker; + if (w == null || !(start ? Startable(w) : Stoppable(w))) { + if (w != null) Show(w, "Стан змінився; команду не надіслано."); + return; + } + pending = new WorkerCommand { + OperationId = Guid.NewGuid().ToString(), ExpectedEpoch = reading.Epoch, + Action = start ? WorkerCommand.Types.Action.Start : WorkerCommand.Types.Action.Stop, + DrainTimeoutMs = start ? 0u : 30000u + }; + uncertain = false; Show(w, "Надсилання команди…"); + // Keep pending even if acknowledgement is lost. Only Lookup follows. + var result = await rpc.Submit(pending.Clone(), token); + Validate(result, pending.OperationId); + await RefreshLocked(token); + } + catch (Exception e) when (e is RpcException or IOException or InvalidOperationException or OperationCanceledException) + { Offline(e); } + finally { gate.Release(); } + } + private void Offline(Exception e) + { + var phase = e is RpcException r && r.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied + ? "auth_error" : "disconnected"; + View = new(phase, Detail: pending == null ? "Оновлюю зв’язок…" : "Очікую результат попередньої операції; команда не повторюється.", + OperationId: pending?.OperationId ?? ""); + } + private static void Validate(WorkerOperation op, string id) + { + if (op.OperationId != id || op.Status is not ("accepted" or "running" or "succeeded" or "failed" or "indeterminate") || op.Reason.Length > 256) + throw new InvalidOperationException("Invalid operation state"); + } +} diff --git a/desktop/WorkerSelfCheck.cs b/desktop/WorkerSelfCheck.cs new file mode 100644 index 00000000..551428e9 --- /dev/null +++ b/desktop/WorkerSelfCheck.cs @@ -0,0 +1,90 @@ +using Grpc.Core; +using Strata.Node.V1; + +namespace Strata.Desktop; + +internal static partial class CoreClient +{ + private sealed class LostAcknowledgementRpc(IWorkerRpc inner) : IWorkerRpc + { + public int Submits; + public Task Read(CancellationToken token) => inner.Read(token); + public Task Lookup(string id, CancellationToken token) => inner.Lookup(id, token); + public async Task Submit(WorkerCommand command, CancellationToken token) + { + Submits++; + await inner.Submit(command, token); + throw new RpcException(new Status(StatusCode.Unavailable, "Synthetic lost acknowledgement")); + } + } + private sealed class ChangedEpochRpc(bool durable = false) : IWorkerRpc + { + public int Submits; + public bool Changed; + public Task Read(CancellationToken token) => Task.FromResult(new WorkerReading( + Changed ? "replacement" : "original", new WorkerState { Phase = "stopped", Model = "synthetic" }, durable)); + public Task Lookup(string id, CancellationToken token) => durable + ? Task.FromResult(new WorkerOperation { OperationId = id, Status = "succeeded" }) + : throw new Exception("Must not query replaced epoch"); + public Task Submit(WorkerCommand command, CancellationToken token) { + Submits++; Changed = true; + throw new RpcException(new Status(StatusCode.Unavailable, "Synthetic epoch replacement")); + } + } + public static async Task WorkerSelfCheck() + { + if (Environment.GetEnvironmentVariable("STRATA_NODE_ENDPOINT") == null) + throw new InvalidOperationException("Lifecycle check requires an isolated configured test node."); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + var token = timeout.Token; + var rpc = new LostAcknowledgementRpc(WorkerRpc()); + var controller = new WorkerController(rpc); + await controller.Refresh(token); + if (!controller.View.CanStart) throw new Exception("Fixture must start stopped"); + await controller.Command(true, token); + var id = controller.View.OperationId; + if (id.Length == 0 || controller.View.CanStart || controller.View.CanStop) throw new Exception("Uncertain command must block duplicates"); + while (controller.View.Phase != "ready" || !controller.View.CanStop) { + await controller.Refresh(token); + await Task.Delay(50, token); + } + if (rpc.Submits != 1) throw new Exception("Mutation was replayed"); + var pid = controller.View.Pid; + // Closing a desktop client must not stop a configured persistent node. + Close(); + await controller.Refresh(token); + if (controller.View.Pid != pid || !controller.View.CanStop) throw new Exception("Worker did not survive client close"); + var c = await Connect(token); + using (var response = c.Respond(new ResponseRequest { Json = Google.Protobuf.ByteString.CopyFromUtf8( + """{"model":"fixture","input":"synthetic","stream":false}""") }, Headers(), cancellationToken: token)) { + using var bytes = new MemoryStream(); bool ended = false; + while (await response.ResponseStream.MoveNext(token)) { + var frame = response.ResponseStream.Current; + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.Data) bytes.Write(frame.Data.Span); + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.End) ended = true; + if (frame.PayloadCase == ResponseFrame.PayloadOneofCase.Headers && frame.Headers.Status != 200) throw new Exception("Response failed"); + } + if (!ended || System.Text.Encoding.UTF8.GetString(bytes.ToArray()) != """{"id":"fixture_response","status":"completed","output":[]}""") + throw new Exception("Response bytes or terminal changed"); + } + await controller.Command(false, token); + while (controller.View.Phase != "stopped" || !controller.View.CanStart) { + await controller.Refresh(token); await Task.Delay(50, token); + } + if (rpc.Submits != 2) throw new Exception("Stop was replayed"); + var changed = new ChangedEpochRpc(); + var epoch = new WorkerController(changed); + await epoch.Refresh(token); await epoch.Command(true, token); await epoch.Refresh(token); + await epoch.Command(true, token); + if (changed.Submits != 1 || epoch.View.CanStart || epoch.View.CanStop || epoch.View.OperationId.Length == 0) + throw new Exception("Epoch replacement enabled unsafe mutation"); + var journalRpc = new ChangedEpochRpc(true); + var journalController = new WorkerController(journalRpc); + await journalController.Refresh(token); + await journalController.Command(true, token); + await journalController.Refresh(token); + if (journalRpc.Submits != 1 || !journalController.View.CanStart || journalController.View.OperationId.Length != 0) + throw new Exception("Durable completed outcome did not reconcile without replay"); + Console.WriteLine("PASS: desktop lifecycle start/stop, lost-ack reconciliation, no duplicate mutation, client-close independence, epoch replacement blocked, byte-exact synthetic Responses."); + } +} diff --git a/desktop/package-macos.sh b/desktop/package-macos.sh new file mode 100644 index 00000000..7411309e --- /dev/null +++ b/desktop/package-macos.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# Local unsigned developer bundle. No install, server access or model loading. +set -eu +repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +case "$(uname -m)" in + arm64) rid=osx-arm64 ;; + x86_64) rid=osx-x64 ;; + *) echo "Unsupported macOS architecture" >&2; exit 1 ;; +esac +test "$(uname -s)" = Darwin +cargo build --locked --manifest-path "$repo/desktop-core/Cargo.toml" -j 2 +bundle="$repo/artifacts/desktop/Strata Preview.app" +mkdir -p "$bundle/Contents/MacOS" +dotnet publish "$repo/desktop/Strata.Desktop.csproj" -r "$rid" --self-contained true \ + -p:UseSharedCompilation=false \ + -p:NuGetLockFilePath="$repo/artifacts/desktop/packages-$rid.lock.json" \ + -o "$bundle/Contents/MacOS" --nologo +cat > "$bundle/Contents/Info.plist" <<'PLIST' + + + + CFBundleIdentifierdev.strata.preview + CFBundleNameStrata Preview + CFBundleDisplayNameStrata Preview + CFBundleExecutableStrata.Desktop + CFBundlePackageTypeAPPL + CFBundleShortVersionString0.1.0 + CFBundleVersion1 + NSHighResolutionCapable + +PLIST +printf '%s\n' "$bundle" diff --git a/desktop/packages.lock.json b/desktop/packages.lock.json new file mode 100644 index 00000000..69ec60a2 --- /dev/null +++ b/desktop/packages.lock.json @@ -0,0 +1,241 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Avalonia.Desktop": { + "type": "Direct", + "requested": "[12.1.3, )", + "resolved": "12.1.3", + "contentHash": "kjCpRlBIK5OZDnQ01Hd43CF0Mq4eQ9ndABiDCJAGtLD7lbzX6KxJ08vIK4N1VAiY4/enAUz8oT8q4O6bSybrBQ==", + "dependencies": { + "Avalonia": "12.1.3", + "Avalonia.HarfBuzz": "12.1.3", + "Avalonia.Native": "12.1.3", + "Avalonia.Skia": "12.1.3", + "Avalonia.Win32": "12.1.3", + "Avalonia.X11": "12.1.3" + } + }, + "Avalonia.Themes.Fluent": { + "type": "Direct", + "requested": "[12.1.3, )", + "resolved": "12.1.3", + "contentHash": "ens/GHfXXk0W1ZScHZ2XG6DFiVyUVKR+0O8QK6zkviMNAPQCNwkftXlRVSFSQGtBYxXoJHZMsKYvCLEtVyzkug==", + "dependencies": { + "Avalonia": "12.1.3" + } + }, + "Google.Protobuf": { + "type": "Direct", + "requested": "[3.36.2, )", + "resolved": "3.36.2", + "contentHash": "Ci1q1iJg74qAE5riTA2FbMS0wPbpruPQI/JQ9DrAsRo2VsSxgt1e/pmxGxgrci+pXJEgrSYg2vPl8rrStZkclQ==" + }, + "Grpc.Net.Client": { + "type": "Direct", + "requested": "[2.84.0, )", + "resolved": "2.84.0", + "contentHash": "My6Fms2YCyAbihTBZZ3kLS39iTY2pkMAzGDBTC6XhPOujg70eB07AEJ7tPiW3tZ70bhFzHcc3+d4j3DaIPF3aA==", + "dependencies": { + "Grpc.Net.Common": "2.84.0", + "Microsoft.Extensions.Logging.Abstractions": "8.0.1" + } + }, + "Grpc.Tools": { + "type": "Direct", + "requested": "[2.84.0, )", + "resolved": "2.84.0", + "contentHash": "SarjdfpQYU/mmdu/fWgSW8kEHQ54jiyG2+I4THu9eubtAud+QJf+1iJdGtoKTJ/ZRaI0qAG+7ttsK2WUTao2OQ==" + }, + "Avalonia": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "l0VGyGn1OwqFrhmIhIHivvrQP0DtBD4Vn2F1vLYgGA2X2qHg0DMVRAln/6xOTLBUYoTopiVAujN0jtH8MpVSeA==", + "dependencies": { + "Avalonia.BuildServices": "11.3.2", + "Avalonia.Remote.Protocol": "12.1.3", + "MicroCom.Runtime": "0.11.6" + } + }, + "Avalonia.Angle.Windows.Natives": { + "type": "Transitive", + "resolved": "2.1.27548.20260419", + "contentHash": "l17nI3XVDN3oMnpjf2pnmJg0YTwK4m6NLsn/itAjDMdObTFxN77D5F1M9sRMSfViSY3KKcse1ROczwgoWLJsnA==" + }, + "Avalonia.BuildServices": { + "type": "Transitive", + "resolved": "11.3.2", + "contentHash": "qHDToxto1e3hci5YqbG9n0Ty8mlp3zBUN5wT66wKqaDVzXyQ0do3EnRILd4Ke9jpvsktaPpgE0YjEk7hornryQ==" + }, + "Avalonia.FreeDesktop": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "yEvk7qm0QPzgQwFZZTAIUXt31sQOSSeOSVTDrcm/Pk+5klNN+8C08kIJs9ZD8RY9esHVk2g6VHPab6DceJYRCw==", + "dependencies": { + "Avalonia": "12.1.3", + "Tmds.DBus.Protocol": "0.94.1" + } + }, + "Avalonia.FreeDesktop.AtSpi": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "t9dP6VQAKGlXtftNuj7QzFtE54AI1qH1dwFmDEJlvI5gweCLNR8ebgRCLlO/bSLWzzV8dZtb6mB/glZ8soisDw==", + "dependencies": { + "Avalonia": "12.1.3" + } + }, + "Avalonia.HarfBuzz": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "XcO9BBsmZHMIK+e+yy1TGsytlhqa7o4ih2Y7B0Q7OKh91GEEerbEc6v/X2kRmluKxyYNSmkwH5Uzj53FtjJngA==", + "dependencies": { + "Avalonia": "12.1.3", + "HarfBuzzSharp": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3" + } + }, + "Avalonia.Native": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "TP6G8mF8vPufxycwe/dfLTsNhqQOGBt2Os5MtJshUGfVQ8zlYUG8K8JckPE+dweuDraAKq305aHXseReD7UgXQ==", + "dependencies": { + "Avalonia": "12.1.3" + } + }, + "Avalonia.Remote.Protocol": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "HcF69DKyihgg5coLOSp7GTqxQvWAy58LMKauwcHA28uSBJVwu0h5+gTNdJA8Sn/nqJVTRDU98zYsk6i1QSwDVQ==" + }, + "Avalonia.Skia": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "fYfSecJ6vQT3zB9vWl2DOoBK6JM4Mzxpz7KbUPxJePjY/yUl2OyhjKCyUcGZF2DV5mpAYfCOT4rdKEk8hP/lCA==", + "dependencies": { + "Avalonia": "12.1.3", + "HarfBuzzSharp": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3", + "SkiaSharp": "3.119.4", + "SkiaSharp.NativeAssets.Linux": "3.119.4", + "SkiaSharp.NativeAssets.WebAssembly": "3.119.4" + } + }, + "Avalonia.Win32": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "RXSOmQGV5uKS9orIeE8a5oGz9QukzBnQTP3dtT9uJUhIIuZracy3ItoW8gtlZGBs3lzhEFTZlOk1Fn/Zxj/iAg==", + "dependencies": { + "Avalonia": "12.1.3", + "Avalonia.Angle.Windows.Natives": "2.1.27548.20260419" + } + }, + "Avalonia.X11": { + "type": "Transitive", + "resolved": "12.1.3", + "contentHash": "NWkfAGgERPlYRKpiB18t5auSFA/Ffd++uZsUEtHPc/maitjydNJVDmtY21pUqR2QvAeTCl1nRAagi+j9bKVyKw==", + "dependencies": { + "Avalonia": "12.1.3", + "Avalonia.FreeDesktop": "12.1.3", + "Avalonia.FreeDesktop.AtSpi": "12.1.3", + "Avalonia.Skia": "12.1.3" + } + }, + "Grpc.Core.Api": { + "type": "Transitive", + "resolved": "2.84.0", + "contentHash": "p2SOMl6q/GZ4/5MLkgboC/z55g4zKUEruRn/g46QgppjQBVnsLZVBU/9VO7n60ll38G3Eo8Zu9b7x+W01GKFVg==" + }, + "Grpc.Net.Common": { + "type": "Transitive", + "resolved": "2.84.0", + "contentHash": "DPxm/H8G/lDRrz997wM0M2zN/PGqVeZKDakhBbtABEbv6WIW4HI9g3BvntBQT6ZUROuGacMzfyyF9e5kiTVFfQ==", + "dependencies": { + "Grpc.Core.Api": "2.84.0" + } + }, + "HarfBuzzSharp": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "NGZ2+ZVNPM+NdHB/asW0/ykWngyHWwcqjrbN2nDeH1B/aptPGlCUl8wkQ2cSJxw5fdWgdmIPmNuTPWpLwNVXWg==", + "dependencies": { + "HarfBuzzSharp.NativeAssets.Win32": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.macOS": "8.3.1.3" + } + }, + "HarfBuzzSharp.NativeAssets.Linux": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "RI6A1LgmooU30+4QIyFt5rmBCzP0VzTR+587IJSGvYIsHHWlahFufihYxtraLfsIhW7I8dn6+xX+DZGygOPKWQ==" + }, + "HarfBuzzSharp.NativeAssets.macOS": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "KPTq0xnslkI6nAo0jh3ptcQPJvZZr7MWYXa2jUe4SnHc9q+JlHElmNXp0sfFoiTgoCX7WOYpYsurypuH9Gehxw==" + }, + "HarfBuzzSharp.NativeAssets.WebAssembly": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "w2QfdNm9Uz/sUa0B5D+OnVQhyq3G/fBq6ibQMdWBlQqqwh0g0/5j3RFvYqZAmRZ5+RzvjVe8o8SFFnWYUSkuxA==" + }, + "HarfBuzzSharp.NativeAssets.Win32": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "bx8CE8Js+XGX8PUxAHCBDEORt5aaBYtMN4Hr9QFs57Xithh6yjUyYqksizH6eRDhJkwsGI+SXWmPmMm8lZC9Pw==" + }, + "MicroCom.Runtime": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "NdNWGDiZ6eS/Mf/9+QHR91cj1K7Hy+PX9yrHI/zM7xFYuj9IWT2uxtB6sCHjrnxAeLV9fut1R6zHDUGKX6f9lQ==" + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "fGLiCRLMYd00JYpClraLjJTNKLmMJPnqxMaiRzEBIIvevlzxz33mXy39Lkd48hu1G+N21S7QpaO5ZzKsI6FRuA==" + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "RIFgaqoaINxkM2KTOw72dmilDmTrYA0ns2KW4lDz4gZ2+o6IQ894CzmdL3StM2oh7QQq44nCWiqKqc4qUI9Jmg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.1" + } + }, + "SkiaSharp": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } + }, + "SkiaSharp.NativeAssets.Linux": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "UAyVzbqNfZsZbKbzj68zXLyUyF/SbTKmzTfOO6qDu++dtIUMMTzPBe8oOuzU/DiewpfKoUUlOSsJmqWc6blxBw==" + }, + "SkiaSharp.NativeAssets.macOS": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "fgBOWEqbY012x7gMfJU4ezgz6dfhJb30Z6YdW35h85Zoe39+a8YNbAAwL29ihPfWoppg5AjvyKNzD1oCvlqWwA==" + }, + "SkiaSharp.NativeAssets.WebAssembly": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "S1HOxtBbD4bYDtA2e9WH5TX+lxqRrTPvKjrjttRhxnHNNu7YY8VFo/LeCP7tNqoTA6PV+8vsvNbmRUEC2ip8RQ==" + }, + "SkiaSharp.NativeAssets.Win32": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "XOpbx/4CReO2wYsq2s6rbvdauc6dntG4Zv499sHGTJ87bwZaFXszFkwql3+FIZMc8kUPeaj3Mx2ezIJmo8a1Kg==" + }, + "Tmds.DBus.Protocol": { + "type": "Transitive", + "resolved": "0.94.1", + "contentHash": "11YMr7FnAbL83bQmVxlhbIKHvSLxjO81D12Ej0QMSGXMDTxNA9MTOa4MQxx43nv5el/efuPHwzyrj6a5ha2gug==" + } + } + } +} \ No newline at end of file diff --git a/desktop/tests/lifecycle.py b/desktop/tests/lifecycle.py new file mode 100644 index 00000000..6ebd4244 --- /dev/null +++ b/desktop/tests/lifecycle.py @@ -0,0 +1,143 @@ +"""Offline desktop lifecycle test. Python is a synthetic backend/test runner only.""" +import asyncio +import json +import os +from pathlib import Path +import secrets +import socket +import sys +import tempfile +import uuid + + +def fixture(): + from http.server import BaseHTTPRequestHandler, HTTPServer + import threading + assert "STRATA_NODE_TOKEN" not in os.environ + host, port = os.environ["STRATA_WORKER_ENDPOINT"].rsplit(":", 1) + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + body = json.dumps({"status": "ok", "loaded": True, "model": os.environ["STRATA_WORKER_MODEL"]}).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", 0))) + body = b'{"id":"fixture_response","status":"completed","output":[]}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + # Last-resort bound if the entire test runner is killed. + timer = threading.Timer(40, lambda: os._exit(0)) + timer.daemon = True + timer.start() + HTTPServer((host, int(port)), Handler).serve_forever() + + +async def main(): + root = Path(__file__).resolve().parents[2] + binary = root / "desktop-core/target/debug" / ("strata-desktop.exe" if os.name == "nt" else "strata-desktop") + dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" + env = os.environ.copy() + env.pop("STRATA_NODE_ENDPOINT", None) + env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) + node = app = None + endpoint = None + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + worker_port = listener.getsockname()[1] + with tempfile.TemporaryDirectory(prefix="strata-lifecycle-") as temp: + profile = Path(temp) / "profile.json" + profile.write_text(json.dumps({ + "schema_version": 1, "id": "fixture", "model": "synthetic", + "executable": sys.executable, "args": [str(Path(__file__).resolve()), "--fixture"], + "endpoint": f"127.0.0.1:{worker_port}", "startup_timeout_ms": 5000, + })) + async def launch(): + process = await asyncio.create_subprocess_exec( + str(binary), "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_NODE_TOKEN", + "--worker-profile", str(profile), "--journal", str(Path(temp) / "operations.jsonl"), env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + ) + address = json.loads(await asyncio.wait_for(process.stdout.readline(), 5))["endpoint"] + return process, address + + async def cli(*args): + process = await asyncio.create_subprocess_exec( + str(binary), "worker", "--node", endpoint.removeprefix("http://"), + "--token-env", "STRATA_NODE_TOKEN", *args, env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + stdout, _ = await asyncio.wait_for(process.communicate(), 6) + assert process.returncode == 0, "CLI failed" + return json.loads(stdout) + + try: + node, endpoint = await launch() + env["STRATA_NODE_ENDPOINT"] = endpoint + app = await asyncio.create_subprocess_exec( + "dotnet", str(dll), "--self-check-worker", env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await asyncio.wait_for(app.communicate(), 30) + if app.returncode != 0: + raise RuntimeError("Desktop lifecycle failed: " + stderr.decode()[:500]) + print(stdout.decode().strip()) + operation = str(uuid.uuid4()) + await cli("stop", operation) + for _ in range(30): + result = await cli("operation", operation) + if result["status"] == "succeeded": + break + await asyncio.sleep(.1) + assert result["status"] == "succeeded" + node.kill() + await node.wait() + node, endpoint = await launch() + assert (await cli("operation", operation))["status"] == "succeeded" + assert (await cli("status"))["phase"] == "stopped" + assert (await cli("stop", operation))["status"] == "succeeded" + print("PASS: durable operation survived real node kill/restart; duplicate returned history without replay.") + + finally: + if app and app.returncode is None: + app.kill() + await app.wait() + if node and node.returncode is None: + try: + if endpoint: + cmd = [str(binary), "worker", "--node", endpoint.removeprefix("http://"), + "--token-env", "STRATA_NODE_TOKEN"] + child = await asyncio.create_subprocess_exec( + *cmd, "stop", str(uuid.uuid4()), env=env, + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL) + await asyncio.wait_for(child.wait(), 6) + for _ in range(30): + child = await asyncio.create_subprocess_exec( + *cmd, "status", env=env, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL) + data, _ = await asyncio.wait_for(child.communicate(), 6) + if child.returncode == 0 and json.loads(data)["phase"] == "stopped": + break + await asyncio.sleep(.1) + finally: + if node.returncode is None: + node.kill() + await node.wait() + with socket.socket() as listener: + assert listener.connect_ex(("127.0.0.1", worker_port)) != 0, "fixture listener leaked" + + +if __name__ == "__main__": + if sys.argv[1:] == ["--fixture"]: + fixture() + else: + asyncio.run(main()) diff --git a/desktop/tests/reconnect.py b/desktop/tests/reconnect.py new file mode 100644 index 00000000..4c016e3d --- /dev/null +++ b/desktop/tests/reconnect.py @@ -0,0 +1,62 @@ +"""Offline CI fault test: C# observer + isolated Rust node; no inference or SSH.""" +import asyncio +import json +import os +from pathlib import Path +import secrets + + +async def main(): + root = Path(__file__).resolve().parents[2] + binary = root / "desktop-core/target/debug" / ("strata-desktop.exe" if os.name == "nt" else "strata-desktop") + dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" + env = os.environ.copy() + env.pop("STRATA_NODE_ENDPOINT", None) + env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) + nodes = [] + app = None + + async def launch(address): + process = await asyncio.create_subprocess_exec( + str(binary), "node", "--listen", address, "--token-env", "STRATA_NODE_TOKEN", + env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + ) + nodes.append(process) + descriptor = json.loads(await asyncio.wait_for(process.stdout.readline(), 5)) + return process, descriptor["endpoint"] + + try: + node, endpoint = await launch("127.0.0.1:0") + env["STRATA_NODE_ENDPOINT"] = endpoint + app = await asyncio.create_subprocess_exec( + "dotnet", str(dll), "--self-check-reconnect", env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + ) + killed = restarted = False + while True: + line = await asyncio.wait_for(app.stdout.readline(), 28) + if not line: + break + message = line.decode().strip() + print(message, flush=True) + if message.startswith("{"): + phase = json.loads(message)["Phase"] + if phase == "ready" and not killed: + node.kill() + await node.wait() + killed = True + elif phase == "disconnected" and killed and not restarted: + await launch(endpoint.removeprefix("http://")) + restarted = True + code = await asyncio.wait_for(app.wait(), 5) + if code != 0 or not restarted: + raise RuntimeError("C# reconnect check failed") + finally: + for process in nodes + ([app] if app else []): + if process.returncode is None: + process.kill() + await process.wait() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/desktop/tests/remote_install.py b/desktop/tests/remote_install.py new file mode 100644 index 00000000..47e3486f --- /dev/null +++ b/desktop/tests/remote_install.py @@ -0,0 +1,149 @@ +"""Real isolated SSH install/activate transactions. Never starts an inference worker. +Uses a unique private installation slot and removes only that slot on completion. +""" +import asyncio +import getpass +import hashlib +import json +import os +from pathlib import Path +import platform +import secrets +import shlex +import shutil +import socket +import tempfile + + +async def main(): + root = Path(__file__).resolve().parents[2] + binary = root / "desktop-core/target/debug/strata-desktop" + ssh = shutil.which("ssh") + sshd = shutil.which("sshd") or "/usr/sbin/sshd" + assert os.name != "nt" and ssh and Path(sshd).is_file() + slot = "install-test-" + secrets.token_hex(12) + installed = Path.home() / ".strata-next/installations" / slot + assert not installed.exists() + processes = [] + with tempfile.TemporaryDirectory(prefix="strata-install-test-") as folder: + p = Path(folder) + env = os.environ.copy() + + async def run(*args, timeout=60, **kwargs): + proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, **kwargs) + processes.append(proc) + out, err = await asyncio.wait_for(proc.communicate(), timeout) + return proc.returncode, out, err + + try: + for key in ("host", "client"): + rc, _, _ = await run("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(p / key)) + assert rc == 0 + (p / "authorized").write_text((p / "client.pub").read_text()) + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + (p / "sshd.conf").write_text( + f"Port {port}\nListenAddress 127.0.0.1\nHostKey {p}/host\nPidFile {p}/pid\n" + f"UsePAM no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n" + f"AuthorizedKeysFile {p}/authorized\nAllowUsers {getpass.getuser()}\nLogLevel ERROR\n") + daemon = await asyncio.create_subprocess_exec(sshd, "-D", "-e", "-f", str(p / "sshd.conf"), + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE) + processes.append(daemon) + await asyncio.sleep(.2) + assert daemon.returncode is None, "isolated sshd failed" + public = " ".join((p / "host.pub").read_text().split()[:2]) + (p / "known_hosts").write_text(f"[127.0.0.1]:{port} {public}\n") + (p / "ssh.conf").write_text(f'UserKnownHostsFile "{p}/known_hosts"\nIdentitiesOnly yes\n') + (p / "bin").mkdir() + wrapper = p / "bin/ssh" + ssh_exec = shlex.quote(ssh) + " -F " + shlex.quote(str(p / "ssh.conf")) + ' "$@"\n' + wrapper.write_text("#!/bin/sh\nexec " + ssh_exec) + wrapper.chmod(0o700) + env["PATH"] = str(p / "bin") + os.pathsep + env["PATH"] + worker = p / "worker" + worker.write_text("#!/bin/sh\nprintf unexpected > " + shlex.quote(str(p / "worker-started")) + "\n") + worker.chmod(0o700) + profile = {"schema_version": 1, "id": "synthetic", "model": "fixture", "executable": str(worker), + "args": ["private-fixture-marker"], "endpoint": "127.0.0.1:19999", "startup_timeout_ms": 1000} + (p / "worker.json").write_text(json.dumps(profile)) + target = {"ssh": {"schema_version": 1, "id": "fixture", "host": "127.0.0.1", "user": getpass.getuser(), + "port": port, "identity_file": str(p / "client")}, "slot": slot, + "os": "macos" if platform.system() == "Darwin" else "linux", + "arch": "aarch64" if platform.machine() in ("arm64", "aarch64") else "x86_64"} + config = {"schema_version": 1, "target": target, "runtime": str(binary), + "runtime_sha256": hashlib.file_digest(binary.open("rb"), "sha256").hexdigest(), + "worker_profile": str(p / "worker.json")} + + async def command(name, value, success=True): + (p / "command.json").write_text(json.dumps(value)) + rc, out, err = await run(str(binary), name, str(p / "command.json"), env=env) + assert (rc == 0) == success, (rc, out, err) + assert b"private-fixture-marker" not in out + err + return json.loads(out) if success else None + + first = await command("remote-install", config) + assert first["outcome"] == "installed" and not first["serving_changed"] + current = lambda: (installed / "current").read_text().strip() + assert current() == first["release"] + assert (installed.stat().st_mode & 0o777) == 0o700 + assert hashlib.file_digest((installed / "releases" / current() / "strata-desktop").open("rb"), "sha256").hexdigest() == config["runtime_sha256"] + repeated = await command("remote-install", config) + assert repeated["release"] == first["release"] and repeated["outcome"] == "reused" + # A new profile creates a separate immutable bundle. + profile["model"] = "fixture-next" + (p / "worker.json").write_text(json.dumps(profile)) + second = await command("remote-install", config) + assert second["release"] != first["release"] and current() == second["release"] + rollback = {"schema_version": 1, "target": target, "runtime_sha256": first["runtime_sha256"], + "profile_sha256": first["profile_sha256"]} + assert (await command("remote-activate", rollback))["outcome"] == "activated" + assert current() == first["release"] + # Target-side profile failure cannot replace a working selection. + profile["executable"] = "/nonexistent-strata-test-worker" + (p / "worker.json").write_text(json.dumps(profile)) + await command("remote-install", config, False) + assert current() == first["release"] + await command("remote-install", {**config, "runtime_sha256": "0" * 64}, False) + await command("remote-activate", {**rollback, "target": {**target, "os": "linux" if target["os"] == "macos" else "macos"}}, False) + assert current() == first["release"] + # A concurrent/stale lock is fail-closed and is not removed by another invocation. + (installed / ".lock").mkdir() + await command("remote-activate", rollback, False) + assert (installed / ".lock").is_dir() + (installed / ".lock").rmdir() + # A stale marker belongs to the earlier operation and is not deleted. + (installed / ".current-next").write_text("retain-for-inspection") + await command("remote-activate", rollback, False) + assert (installed / ".current-next").read_text() == "retain-for-inspection" + (installed / ".current-next").unlink() + # Truncated transfer cleans its staging and preserves selection. + wrapper.write_text("#!/bin/sh\nhead -c 100 | " + ssh_exec) + await command("remote-install", config, False) + wrapper.write_text("#!/bin/sh\nexec " + ssh_exec) + assert current() == first["release"] + assert not list(installed.glob(".stage.*")) and not (installed / ".lock").exists() + # Neither a bad retained release nor unsafe marker is activated. + retained = installed / "releases" / second["release"] / "worker.json" + retained.write_text("{}") + await command("remote-activate", {**rollback, "profile_sha256": second["profile_sha256"]}, False) + assert current() == first["release"] + (installed / "current").unlink() + (p / "untouched").write_text("sentinel") + (installed / "current").symlink_to(p / "untouched") + await command("remote-activate", rollback, False) + assert (p / "untouched").read_text() == "sentinel" + assert not (p / "worker-started").exists(), "installer must not start backend" + print("PASS: real SSH install, repeat, changed profile, rollback, private permissions, wrong digest/OS/profile, slot lock, truncated upload cleanup, corrupt release and symlink rejection; no worker launched.") + finally: + for proc in reversed(processes): + if proc.returncode is None: + proc.kill() + await proc.wait() + if installed.exists(): + shutil.rmtree(installed) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/desktop/tests/ssh_tunnel.py b/desktop/tests/ssh_tunnel.py new file mode 100644 index 00000000..9ab4983e --- /dev/null +++ b/desktop/tests/ssh_tunnel.py @@ -0,0 +1,130 @@ +"""Optional real localhost OpenSSH integration. Isolated host/user keys, no GPU. +Requires Unix ssh, ssh-keygen and a runnable sshd. Never changes ~/.ssh or services. +""" +import asyncio +import getpass +import json +import os +from pathlib import Path +import secrets +import shlex +import shutil +import signal +import socket +import tempfile + + +async def main(): + root = Path(__file__).resolve().parents[2] + sshd = shutil.which("sshd") or "/usr/sbin/sshd" + ssh = shutil.which("ssh") + if os.name == "nt" or not ssh or not Path(sshd).is_file(): + raise RuntimeError("This optional integration requires a disposable Unix sshd") + binary = root / "desktop-core/target/debug/strata-desktop" + dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" + processes = [] + with tempfile.TemporaryDirectory(prefix="strata-ssh-integration-") as folder: + p = Path(folder) + env = os.environ.copy() + env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) + env.pop("STRATA_NODE_ENDPOINT", None) + + async def launch(*args, **kwargs): + process = await asyncio.create_subprocess_exec(*args, **kwargs) + processes.append(process) + return process + + async def output(*args): + process = await launch(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + out, err = await asyncio.wait_for(process.communicate(), 5) + if process.returncode: + raise RuntimeError("Fixture command failed") + return out + + try: + for key in ("host", "client"): + await output("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(p / key)) + (p / "authorized").write_text((p / "client.pub").read_text()) + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + (p / "sshd.conf").write_text( + f"Port {port}\nListenAddress 127.0.0.1\nHostKey {p}/host\n" + f"PidFile {p}/pid\nUsePAM no\nPasswordAuthentication no\n" + f"KbdInteractiveAuthentication no\nAuthorizedKeysFile {p}/authorized\n" + f"AllowUsers {getpass.getuser()}\nAllowTcpForwarding local\nLogLevel ERROR\n") + daemon = await launch(sshd, "-D", "-e", "-f", str(p / "sshd.conf"), + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE) + await asyncio.sleep(.2) + if daemon.returncode is not None: + raise RuntimeError("Isolated sshd could not start") + public = " ".join((p / "host.pub").read_text().split()[:2]) + (p / "known_hosts").write_text(f"[127.0.0.1]:{port} {public}\n") + (p / "ssh.conf").write_text(f'UserKnownHostsFile "{p}/known_hosts"\nIdentitiesOnly yes\n') + bindir = p / "bin" + bindir.mkdir() + wrapper = bindir / "ssh" + wrapper.write_text("#!/bin/sh\nprintf '%s\\n' \"$$\" > " + shlex.quote(str(p / "ssh.pid")) + "\nexec " + shlex.quote(ssh) + " -F " + shlex.quote(str(p / "ssh.conf")) + ' "$@"\n') + wrapper.chmod(0o700) + env["PATH"] = str(bindir) + os.pathsep + env["PATH"] + node = await launch(str(binary), "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_NODE_TOKEN", + env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + node_endpoint = json.loads(await asyncio.wait_for(node.stdout.readline(), 5))["endpoint"] + profile = p / "tunnel.json" + profile.write_text(json.dumps({ + "schema_version": 1, "ssh": {"schema_version": 1, "id": "fixture", "host": "127.0.0.1", + "user": getpass.getuser(), "port": port, "identity_file": str(p / "client")}, + "listen": "127.0.0.1:0", "remote_port": int(node_endpoint.rsplit(":", 1)[1]), "max_connections": 4, + })) + editor = await launch("dotnet", str(dll), "--self-check-connection", str(profile), env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + editor_out, editor_err = await asyncio.wait_for(editor.communicate(), 35) + assert editor.returncode == 0, editor_err.decode()[:250] + assert b"desktop connection selection" in editor_out + assert node.returncode is None, "connection editor must preserve remote node" + tunnel = await launch(str(binary), "ssh-tunnel", str(profile), env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + endpoint = json.loads(await asyncio.wait_for(tunnel.stdout.readline(), 5))["endpoint"] + env["STRATA_NODE_ENDPOINT"] = endpoint + for _ in range(2): + app = await launch("dotnet", str(dll), "--self-check", env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + stdout, stderr = await asyncio.wait_for(app.communicate(), 25) + if app.returncode: + raise RuntimeError("C# through real SSH failed: " + stderr.decode()[:250]) + observer = await launch("dotnet", str(dll), "--self-check-tunnel-reconnect", env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + interrupted = False + while True: + line = await asyncio.wait_for(observer.stdout.readline(), 28) + if not line: + break + message = line.decode().strip() + if message.startswith("{") and json.loads(message)["Phase"] == "ready" and not interrupted: + pid = int((p / "ssh.pid").read_text()) + parent = int((await output("ps", "-o", "ppid=", "-p", str(pid))).strip()) + assert parent == tunnel.pid, "refusing to signal an unowned process" + os.kill(pid, signal.SIGTERM) + interrupted = True + assert await asyncio.wait_for(observer.wait(), 5) == 0 and interrupted + # Existing listener reconnects through newly spawned owned SSH connections. + tunnel.send_signal(signal.SIGINT) + assert await asyncio.wait_for(tunnel.wait(), 5) == 0 + assert node.returncode is None and daemon.returncode is None + print("PASS: C# -> owned loopback tunnel -> real isolated OpenSSH -> Rust gRPC node; two client sessions, forced SSH disconnect/recovery with unchanged node, graceful cleanup.") + finally: + for process in reversed(processes): + if process.returncode is None: + if process is locals().get("tunnel"): + process.send_signal(signal.SIGINT) + try: + await asyncio.wait_for(process.wait(), 5) + continue + except asyncio.TimeoutError: + pass + process.kill() + await process.wait() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/docs/api-contract.md b/docs/api-contract.md new file mode 100644 index 00000000..0954d604 --- /dev/null +++ b/docs/api-contract.md @@ -0,0 +1,743 @@ +# Native API contract status + +## Idle SSE transport + +Native Responses (text, tools and buffered structured/reasoning output), Chat +Completions and Messages streams emit `: keep-alive` SSE comments after 15 seconds +without a stream event. These transport comments contain no model output, usage, +sequence number or completion signal. SSE clients must ignore comment-only frames. +The internal adapters and offline replay verifier do so. A finished stream ends +normally; keep-alive does not extend generation deadlines or retain disconnected +requests. Normal backpressure still applies; this is not a guarantee against +proxy timeouts shorter than 15 seconds or intermediaries that buffer SSE. + +## Chat Completions (text/function subset) + +`POST /v1/chat/completions` uses the native Responses generation path. The wire +shape follows [Chat Completions create](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create): +JSON `chat.completion` and live SSE `chat.completion.chunk` with one indexed choice, +assistant content/function calls, `stop` / `length` / `tool_calls` finish reasons, +and a final `data: [DONE]`. SSE text deltas arrive before engine completion. +Function calls are published only after native tool validation, with a complete +argument string in one delta per call. This deliberately does not stream +unvalidated argument fragments. + +Supported inputs: + +- `model`, `messages` with system/developer/user/assistant text and tool results; + text strings or arrays of `{"type":"text","text":"..."}` parts; +- assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and + tool `tool_call_id`/text; complete returned assistant messages can be reused; +- function tools, `auto`/`none`/`required` or a forced function name, + `parallel_tool_calls`, temperature and top_p; +- `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`; +- `response_format` text, json_object, or json_schema containing name/schema/strict + under `json_schema`; the same native schema subset and final validation apply. + This is validation of generated output, not constrained token sampling; +- `stream` and `stream_options.include_usage`: when requested, normal chunks carry + `usage: null`, followed by a final empty-choices usage chunk before `[DONE]`. + +This first subset always uses `reasoning_effort: none` (also the default here) +and `store: false`; no hidden reasoning is requested or returned. Other efforts, +storage, multiple choices, multimodal input/output, custom/namespace tools, +custom stop sequences, log probabilities, nonzero presence/frequency penalties, +schema descriptions, non-null refusal text and unknown fields are rejected before +worker generation. It does not implement the full upstream API or stored Chat +retrieval. Omitted optional values use existing Responses defaults, including its +output-token limit. A Chat ID is not a Responses history ID. + +Usage renames native input/output/total counters to prompt/completion/total tokens, +including cached/reasoning detail counters. Incomplete output uses `length` and +does not publish a truncated tool call. An error emits the native error object +(and `[DONE]` for SSE) without a successful finish reason or final usage. Text +already streamed before final schema validation can precede that error. + +Auth, 16 MiB request bodies, admission/drain/queue limits and worker cancellation +are shared with Responses. The adapter bounds each native SSE event or JSON body +at 64 MiB; exceeding it fails explicitly. A disconnected Chat stream drops the +native stream consumer, triggering existing STOP/drain isolation; a failed request +is never replayed automatically. Request text and completions are not persisted. + +The CPU HTTP gate compares actual engine `GEN` token IDs and fixture outputs +against equivalent Responses with tolerance zero, including tools/continuation, +Unicode, JSON/SSE/usage, errors and live disconnect→STOP→fresh request. This is +protocol qualification only; real-model/harness rollout remains a separate gate. + +## Anthropic Messages (text/client-tool subset) + +`POST /v1/messages` uses the same native Responses worker, with +`anthropic-version: 2023-06-01`. It follows the [Messages request/response](https://platform.claude.com/docs/en/api/messages/create) +and [named streaming events](https://platform.claude.com/docs/en/build-with-claude/streaming) +shapes for text and client tools. This serves the configured local model, not a +Claude model or an Anthropic cloud service. + +Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks, +user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice` +(`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`, +temperature (0..1) and top_p. Text parts join with newlines; consecutive turns of +the same role combine. This initial subset requires first and last user messages; +assistant prefill is rejected. Assistant `tool_use` carries an object `input` and +ID; user `tool_result` returns the same `tool_use_id` and text or text blocks. +Omitted result `content` means empty text; explicit null and non-text blocks remain +invalid. [Client-tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls) +with `is_error: true` are supported. Because the native template has text tool +outputs, the adapter serializes `{"content":"","is_error":true}` +as that call's tool output, preserving the flag and text (including escaped +control characters). Normal/`is_error: false` results retain their existing text +unchanged. Counting and serving share this conversion. This supports transport +of failures; recovery behavior still requires model qualification. +Tool names, arguments, results and choice policies reuse native validation. + +Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless. +Thinking/redacted signatures, images/documents, cache_control, nonempty +stop_sequences, server tools, top_k, metadata, structured-output options, +beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent. + +`POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens) +and returns `{"input_tokens": N}`. It accepts `model`, `messages`, optional `system`, +`tools`, `tool_choice` and disabled `thinking` from the subset above. Generation +fields (`max_tokens`, `stream`, sampling options) and unknown fields are rejected. +It uses the same serving conversion, prompt template and configured local tokenizer; +the count includes system/tool overhead and the generation prefix, without a cache +discount. It is not a Claude tokenizer estimate or a context/VRAM fit guarantee. +No worker generation or response-history writes occur, and it works while the +worker is unavailable if the tokenizer is configured. The same Messages version, +key/Bearer, body limit, admission/drain and error rules apply. CPU HTTP fixtures +compare the count to actual GEN input IDs with tolerance zero, including tool history. + +JSON returns ordered text/tool_use blocks with `end_turn`, `tool_use` or +`max_tokens` stop reasons and null stop_sequence. SSE uses message_start, +content_block_start/delta/stop, message_delta and message_stop (no `[DONE]`). +Text streams before DONE; validated tool inputs arrive as one complete JSON string +in an input_json_delta. There is no fine-grained unvalidated tool streaming. +Errors use `{"type":"error","error":{"type":"...","message":"..."}}` and a named +SSE error event; failed streams never emit a successful message_stop. Partial +text can precede a final validation error. Malformed or incomplete tool syntax +fails explicitly instead of publishing a tool block. + +Engine counters become known at DONE: message_start usage is provisional zero, +and the final message_delta supplies cumulative input/output/cache totals. +This uses the [SDK's optional cumulative input/cache usage fields](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_delta_usage.py). +Clients must replace these totals, not add them. input_tokens excludes native +reused tokens, cache_read_input_tokens reports reuse, cache_creation_input_tokens +is zero (no provider cache-directive contract), and output_tokens is native total +output. Older clients that ignore final input/cache updates may display zero input +usage during streaming. JSON carries final totals directly. + +The existing local key can be sent as `x-api-key` **only on this route**, or as +Bearer. When authentication is configured, duplicate keys or a key combined with +Authorization are rejected; other API routes retain Bearer authentication. +The route shares the 16 MiB body limit, admission/drain and cancellation rules. +The bounded native SSE reader (64 MiB/event) is shared with Chat; each adapter +buffers at most eight output events. Disconnect releases the native consumer, +sends STOP and preserves the next request. No request/response history is stored. + +The actual CPU HTTP gate compares GEN tokens and fixture output to equivalent +Responses (tolerance zero), reconstructs ordered JSON from named SSE, and checks +Unicode, system/combined turns, tools/continuation, usage, headers/errors, +admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth +regressions run alongside it; real-model/harness/GPU qualification remains open. + +## Model discovery + +`GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or +an empty `data` array when no ID is configured. `GET /v1/models/{id}` returns +the same record; percent-encode the ID as one path segment (including `/`). +Unknown IDs return JSON `404 model_not_found`. Both routes use existing optional +bearer authentication. Nonempty query parameters return `400 unsupported_query`; +POST and DELETE are unsupported and never install or remove a model. + +The response follows the [Models list](https://developers.openai.com/api/reference/resources/models/methods/list) +and [retrieve](https://developers.openai.com/api/reference/resources/models/methods/retrieve) +object shapes: `id`, `object: "model"`, `created: 0`, `owned_by: "local"`, wrapped +in `{"object":"list","data":[...]}` for the list. `created: 0` is this runtime's +explicit unknown-timestamp sentinel; `local` identifies a local deployment, +not the upstream model owner. No model provenance metadata is inferred. + +This is configuration discovery. It stays available while the worker is loading, +failed or draining and does not acquire a generation slot or touch model files. +Use `/ready` to check inference availability. Listing does not download, start, +test or certify the model, and does not expose filesystem paths or credentials. + +## Input token counting + +`POST /v1/responses/input_tokens` returns +`{"object":"response.input_tokens","input_tokens":123}` using the same native +history expansion, prompt template and tokenizer as generation. The shape follows +the [Responses input token count endpoint](https://developers.openai.com/api/reference/resources/responses/subresources/input_tokens/methods/count). +The local subset requires `model` and `input` and accepts the supported create-request +fields; unknown fields and unsupported live features are rejected. Instructions, +reasoning, text format and tool definitions contribute exactly as they do to the +rendered generation prompt. `previous_response_id` includes the saved transcript +and new input; new instructions replace prior instructions. Missing, deleted or +evicted parents return `404 response_not_found`. + +Counting requires a configured tokenizer, but does not require a ready worker, +queue inference, create a response ID or modify history (`store` has no effect). +It always returns ordinary JSON, including when `stream: true` is supplied. +Generation-only settings are validated but do not generate output. The count is +for the full rendered prompt, not only newly evaluated tokens or a prediction of +cache reuse, output length, model quality or available context space. It does not +truncate input or guarantee the request fits the worker's context. + +The route shares optional bearer auth, the 16 MiB body limit and bounded HTTP +admission with create: drain returns 503 and exhausted admission returns 429. +It remains available during worker failure when the service is not draining. +The isolated CPU test compares counts against actual `GEN` token IDs, with exact +integer equality; this does not qualify real-model inference. + +## Engine activity metrics + +`GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional +bearer key as `/status`. This is a native JSON endpoint, not Prometheus text. +`/status` remains a stable discovery response. Metrics require the new binary; +the preserved console trial has not been upgraded to this feature. + +- `active` and `active_elapsed_ms` cover an admitted generation from the attempt + to write `GEN` until engine `DONE`, `ERR`, or supervisor interruption. They + do not indicate GPU utilization or HTTP response completion. +- `queue_capacity` and `queue_used` describe the bounded command channel + (including reserved capacity), excluding the active command and HTTP handlers + waiting to enqueue. An unconfigured channel reports null. These snapshots + are observations, not an admission or safe-restart guarantee. +- `generation.started` counts admitted attempts. Context/validation rejections, + abandoned queued requests and requests rejected during restart are excluded. + `completed` counts non-cancelled DONEs, including length stops. `cancelled` + counts DONEs with cancel finish or a disconnected consumer. `failed_or_interrupted` + counts started attempts without DONE, including engine ERR, protocol failure, + expired cancellation drain and shutdown. Each attempt enters one terminal + bucket. Engine completion does not imply valid JSON/tool calls or task success. +- `done_generated_tokens`, `done_prompt_tokens`, `done_decode_ms`, and + `done_prefill_ms` sum engine DONE values, including cancelled generations. + Counts for failed attempts are unknown and excluded. Prompt counts are engine + input counts, not necessarily newly evaluated tokens. Integer totals saturate + at u64 max and timing totals at the largest finite f64. +- `done_decode_tokens_per_second` is total DONE tokens divided by total DONE + decode seconds. `last_done` exposes the last DONE's counts, milliseconds, + decode rate, raw finish reason, optional reused-token/draft/expert counters. + Unavailable counters and zero-duration/nonfinite rates are null. There is no + instantaneous token speed, prefill rate, TTFT, percentile or quality score. + +Counters survive supervised child restarts and reset when the control-plane +process restarts. They contain no prompts, generated text, token IDs or keys. +Updates happen at generation boundaries; no per-token metrics lock is added. +Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support +observation; paired workload and quality measurements remain necessary for any +performance claim. + +The Rust control plane has a `POST /v1/responses` route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns `503 worker_not_ready` until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker `DONE`. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return `501 unsupported_live_feature`; a ready worker without tokenizer returns `501 inference_adapter_missing`. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open. + +The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in `response.completed`. Tool arguments must form a JSON object. `text.format` supports `text`, `json_object`, and `json_schema` validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at `benchmarks/fixtures/responses/structured-tool.json` demonstrates text plus a tool call; it is not evidence of live Codex compatibility. + +For native Qwen tool parameters, a direct property `type: "string"` preserves +raw text, including quotes. A direct type array containing `"string"` now does +the same unless the text parses as a declared **non-string** JSON type. Thus +`["string", "null"]` preserves `123`, `false`, `{}` and quoted text as strings, +while the literal `null` selects null. `["string", "integer"]` selects an integer +for `123` and a string for `1.5`. This is a deterministic interpretation of an +ambiguous raw-text format, not a search for any schema-valid coercion. Full-schema +validation still runs before publishing a callable item; enum/range violations +are not retried as strings. Scalar declarations and untyped handling retain +their previous behavior. Type inference through `$ref`, `anyOf` or `oneOf` is +not added by this rule. JSON and both live SSE paths use the same decoder; +CPU fixtures verify argument equality, not real-model tool-call quality. + +`control-plane/src/wire.rs` encodes the upstream `GEN` request line and parses the current `T`, `PP`, `DONE`, and `ERR` output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events. + +Current request parsing supports `model`, string or array `input`, `stream`, `instructions`, `max_output_tokens`, `previous_response_id`, `parallel_tool_calls`, `reasoning`, `text`, named function `tools`, `tool_choice`, `temperature`, `top_p`, `truncation`, `metadata`, and `store`. Unknown fields are rejected. Terminal responses are stored by default; `store: false` disables this. `previous_response_id` replays a stored response with the new input, including function calls and matching results. By default the store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB. + +### Opt-in durable history (Unix preview) + +Set `response_history_dir` in the serve config or `STRATA_RESPONSE_HISTORY_DIR` +(environment wins) to an absolute dedicated directory whose parent already exists. +The service creates it with mode `0700`; an existing directory must be owned by +its user with exactly that mode. Snapshot and lock files must be owned regular +`0600` files with one link. Symlinks are refused. An OS lock permits only one +service to use the directory. `check-config` reports `durable_unchecked` without +opening, creating or locking it. `provision` also leaves history untouched. + +This explicitly persists **plaintext input, tool results, and terminal responses**; +use a private external volume, outside Git. It has the same single-operator API +key scope as memory history, with no encryption or tenant separation. Changing +API keys does not erase the store. `store: false` writes nothing. Omitting the +option retains memory-only behavior. Windows durable storage is not supported. + +Completed/incomplete responses, expanded continuation transcripts and input-item +IDs survive service restarts. DELETE and oldest-entry eviction are committed too. +The existing limits remain 64 responses and 128 MiB of serialized response plus +transcript data. A versioned snapshot is bounded to 129 MiB including metadata; +this is not a total resident-memory bound. Each mutation writes a full snapshot +on a blocking pool, flushes it, atomically renames it and flushes the directory +before acknowledging success. Budget space for the current and staged snapshots. +This feature is not a throughput optimization. + +Startup validates the store before asset preparation, worker or listener startup. +Invalid schema, SHA-256 checksum mismatch, corruption, insecure files, excess size or an occupied lock fail +startup without resetting history. An interrupted unpublished stage is discarded +under the lock; the committed snapshot is restored. Disk failures produce the +existing `response_storage_failed` JSON error or terminal SSE `response.failed`, +never a false successful commit. Earlier text deltas may already be visible. +A failed store fences further mutations until restart; existing in-memory GETs +remain available. Failure before rename preserves the previous snapshot. Failure +after rename while flushing the directory has an **uncertain outcome**: the +request was not acknowledged, but its record can be present after restart. +A disconnected client can likewise miss an already committed result. DELETE is +logical deletion, not secure erasure of filesystem blocks or backups. +No in-progress stream, worker state, KV state or automatic retry is restored. + + +Before switching the testing runtime, exercise all engine stop conditions and tool calls with the real tokenizer and model on Linux GPU, and compare sanitized real Codex replays against the upstream Python server. Native reasoning now has its own output items, streaming events and continuation path. Do not mark Gate A complete based on synthetic fixtures. + +## Engine prefix metadata + +The engine's `RESUME ` and `REUSED ` lines are validated as nonnegative +prefix counts and treated as nonterminal metadata. Usage counters come from +`DONE`. These lines must not fail or finish a generation; unknown wire tags +and malformed counts still fail the protocol. + +## Stored response resources + +`GET /v1/responses/{response_id}` returns the exact saved completed or incomplete +response object, including output, tool call IDs/arguments, reasoning, metadata +and usage. `DELETE` on the same path returns +`{"id":"...","object":"response.deleted","deleted":true}` and removes that +entry's response and continuation transcript. These route shapes follow the +official OpenAI [retrieve](https://developers.openai.com/api/reference/resources/responses/methods/retrieve) +and [delete](https://developers.openai.com/api/reference/resources/responses/methods/delete) +references; the implementation supports the bounded history subset described here. + +- Both routes share the optional bearer authentication policy. They remain + available while draining or when the worker is unavailable; they do not invoke + the model. There is still one operator credential, without tenant isolation. +- Unknown, deleted, evicted, memory-only restarted and `store:false` IDs return + `404 response_not_found`. Repeated deletion also returns 404. Failed generations + are not stored; these routes do not poll or cancel in-progress jobs. +- Nonempty query strings return `400 unsupported_query`. Retrieval streaming, + stream resumption and optional include/query fields are not implemented. +- The shared FIFO limit is 64 entries or **128 MiB of serialized response plus + transcript data**. Both objects count toward the budget; this is not a process + RSS cap. Oversized records fail storage before publishing a successful terminal + response. Eviction removes both objects together; retrieval does not refresh + retention order. Disk storage is disabled unless explicitly configured above. +- Deletion prevents subsequent continuation using that ID. It does not erase + copies already included in descendant responses or an in-flight request that + obtained the transcript before deletion, and does not cancel generation. + +These routes require the newer preview; the preserved user trial is unchanged. +CPU verification: `python3 scripts/smoke-response-history.py /path/to/strata-next`; +add `--durable` for actual process restart, corruption and disk-failure coverage. + +### Input item listing + +`GET /v1/responses/{response_id}/input_items` returns an authenticated list with +`data`, `first_id`, `last_id`, and `has_more`, following the documented +[OpenAI input-items route](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_items/methods/list). +It accepts `order=asc|desc` (default `desc`), `limit=1..100` (default 20), and an +`after` item cursor. Unknown, duplicate or malformed query options and foreign +cursors return `400 invalid_input_items_query`; optional `include` is not supported. + +This is a projection of the stored effective input, including expanded +`previous_response_id` history and excluding this response's own output. +Instructions remain a separate request field and are not added to the list. +Message text is projected into role-appropriate typed text parts. List item IDs identify occurrences +within this response and remain stable while it is retained; they replace +client item IDs in this view so duplicate IDs cannot make pagination ambiguous. +Tool `call_id`, name, namespace, arguments and custom input are unchanged. +The transcript used to render subsequent model prompts is never modified. + +The route shares the configured history retention, deletion and authentication +policy. It works during drain/worker outage without generating tokens. Missing, +`store:false`, deleted and evicted responses return 404. Restart clears default +memory history; the opt-in durable store described above also preserves these +input pages. No payload logging or tenant isolation is added. +CPU HTTP coverage includes both response modes, exact tool-payload replay, +pagination, stable cursors, failure cases and no extra worker generation. + +## Cancellation failure isolation + +Dropping a generation receiver sends `STOP` and drains that generation's output +for at most 20 seconds. Tokens or progress emitted after `STOP` are discarded +and do not extend the deadline. A terminal line before the deadline permits the +next queued request. If the worker does not terminate in time, readiness is +revoked, the process is killed and reaped, and queued receivers are closed. +The supervisor never reuses an unaligned output stream. + +Both text and function-call SSE relays observe the HTTP consumer closing even +while the engine produces no events. They then drop their generation receiver +so cancellation reaches the supervisor immediately. + +A sanitized shell worker that consumes `STOP` without reporting `DONE` covers +this failure path. This regression does not qualify full-model soak stability. + +## Worker recovery policy + +After a failure of a worker that previously sent `READY`, the supervisor can +start a fresh process. The default lifetime budget is three restarts, with +delays of 2, 4 and 8 seconds. Set `engine.max_restarts` in the JSON config or +`STRATA_MAX_WORKER_RESTARTS` to an integer from 0 through 3; zero disables +recovery. Environment overrides the file. Successful requests do not replenish +the lifetime budget. Initial or replacement startup failure stops recovery. + +An active failed generation is not retried. Queued commands are failed during +recovery; requests arriving while restarting or starting are rejected. The +worker reports `restarting` during backoff, then `starting`, with no context or +readiness until a new positive `READY` handshake. Shutdown interrupts backoff. +After the lifetime budget is exhausted, the runtime must be restarted by its +operator. A real-model reload has passed; sustained soak remains open. + +## Live structured text + +Requests may select `text.format.type` as +`json_object` or `json_schema`. The runtime adds JSON-format instructions and, +for schemas, the schema itself to the model prompt. Invalid schemas and external +references are rejected before worker admission. Completed text must parse as +an object and, in schema mode, pass the supplied schema. The same validation +applies with `strict` true, false, or omitted. This implementation uses prompt +guidance and final validation; it does not yet constrain next-token sampling +with a JSON grammar and cannot guarantee successful generation for every schema. + +JSON requests return HTTP 502 if completed model output fails validation. +Structured SSE sends `response.created` / `response.in_progress` immediately, +then buffers output until engine DONE. Valid output is emitted with the normal +item/text/terminal events. Invalid completed output emits `response.failed` +without publishing text or function-call items. This buffering trades token-by- +token structured output for validation before publication. Plain text streaming +is unchanged. Disconnect still cancels the active generation while buffering. + +A token-budget stop returns `response.incomplete` with +`incomplete_details.reason: "max_output_tokens"`; its partial text may be invalid +JSON and must not be treated as a schema-valid completed result. Tool-only turns +remain valid: their arguments are checked against the tool schema, while the +text format applies to the eventual answer after tool results. History stores +successful and incomplete responses, never schema-failed responses. + +Example format: + +```json +{"text":{"format":{"type":"json_schema","name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}} +``` + +The field names and incomplete-result handling follow the +[OpenAI structured output contract](https://developers.openai.com/api/docs/guides/structured-outputs). +Recorded Codex/MCP replay remains a separate milestone. + +## Native Qwen reasoning + +`reasoning.effort` accepts `none`, `low`, `medium`, `high`, or `xhigh`. +Omitted/null effort uses upstream's `xhigh` default. The pinned model template +maps `high` to its xhigh instruction; `none` closes the thinking block in the +prompt. Effort is a template instruction, not a separate token budget. +`max_output_tokens` includes both reasoning and answer tokens. + +Generated reasoning is returned as an output item with `type: "reasoning"`, +`content: [{"type":"reasoning_text","text":"..."}]` and `summary: []`. +SSE emits `response.reasoning_text.delta` during generation, followed by its +text/content/item done events and the normal answer or function-call events. +The current reasoning path buffers the final answer/tool items until DONE; +structured answers are validated before publication. `effort: none` plain-text +and tool streaming retain their incremental behavior. Disconnect during +reasoning cancels the worker generation. + +The first Qwen `` marker separates reasoning from answer text, even +when split over tokens. A normal stop without that marker fails; a token-budget +stop while thinking returns an incomplete reasoning item and no invented final +answer. `usage.output_tokens_details.reasoning_tokens` counts original emitted +tokens up to and including the closing-marker token; if one token straddles the +boundary it is assigned to reasoning. Truncated thinking counts all its tokens. +EOS tokens remain in total output usage, not reasoning usage. + +Stored continuation and stateless replay preserve raw reasoning alongside +assistant messages/tool calls in the Qwen template. Reasoning-only incomplete +turns can precede a new user message. Summary-only and encrypted reasoning +cannot reconstruct this local model's raw context and are rejected explicitly. +`reasoning.summary: "auto"` or null is accepted, but no summarizer is implemented: +summary remains empty, and raw text is never mislabeled as a summary. Explicit +`concise`/`detailed` summaries are unsupported. + +The reasoning content and event shapes follow the +[Responses raw-reasoning extension](https://developers.openai.com/cookbook/articles/gpt-oss/handle-raw-cot). +This local Qwen implementation does not provide OpenAI encrypted reasoning. + +## Console request compatibility + +The native route accepts the console's `include`, `prompt_cache_key`, and +string-valued `client_metadata` fields. Only `reasoning.encrypted_content` is +accepted in `include`: it is an optional inclusion hint, and this runtime still +returns **raw reasoning content, not encrypted content**. Metadata is not added +to the model prompt or persisted by the runtime. The cache key is a routing hint; +it does not partition the single worker's token-verified prefix cache. + +Function namespaces are lowered to deterministic, collision-checked aliases for +the Qwen template. Output items retain the original function `name` and +`namespace`, and replay uses the same alias even for historical functions no +longer advertised. Duplicate identities, alias collisions, nested namespaces, +custom/free-form tools, and server-side web search are rejected. Typed argument +validation applies after namespace lowering on both JSON and SSE paths. +`function_call_output.output` accepts text or an array of `input_text` parts; +parts are joined with a newline. Image/file parts remain unsupported. + +When `max_output_tokens` is omitted, generation reserves up to 32,768 tokens, +limited by the remaining context minus the worker's eight-token margin. An +explicit output limit is preserved. Configuring `model` (or `STRATA_MODEL_ID`) +exposes that identity in `/status` and rejects requests for another model. +An omitted configured identity preserves the earlier single-worker API behavior. + +The opt-in console integration is installed with +`python3 scripts/install-qwen-native.py`. It adds the `strata-native` backend to +`qwen-codex-ctl` and uses a direct Responses provider in `qwen-codex`. This path +has no Python serving bridge. The launcher itself remains a local convenience +script. Existing selections remain unchanged, and an installation backup is +retained. `QWEN_CODEX_PROFILE` selects a separate console profile for tests. + +The native preview requires a loopback connection (an SSH tunnel for a remote +GPU). Optional bearer authentication is described below; it does not add TLS. +Native discovery uses +`/status`, requires a configured model identity and a ready 256K worker, and does +not synthesize legacy `/props` or `/slots`. `stop` refuses to operate on this +externally managed runtime; `logs` identifies its host-side logs. + +### Optional bearer authentication + +Set `api_key_file` in the server JSON configuration or `STRATA_API_KEY_FILE` +(takes precedence) to enable one operator credential. The source must be a +regular private file (no group/other permissions on Unix), containing 32–512 +printable ASCII bytes without whitespace; an optional trailing LF/CRLF is +accepted. Total file size is bounded at 514 bytes. Invalid/missing sources fail +startup before binding or launching the engine. FIFO sources fail without +blocking. Without a configured file, previous authentication-free behavior is +unchanged; the existing trial remains in that mode on loopback. + +All routes except minimal `/health` require `Authorization: Bearer TOKEN`. +Missing, wrong, malformed or repeated Authorization headers return a generic +401 `invalid_api_key` and `WWW-Authenticate: Bearer` before request parsing. +`/status` and `/ready` are protected as well. No supplied credential is echoed. +The server's retained credential state is a SHA-256 digest, compared using +`subtle::ConstantTimeEq`; the key is never sent to the engine. This is one shared +operator credential, not multi-user authorization or response-history isolation. +Changing the key requires a deliberate server restart; hot rotation is not +implemented. + +Rerun `scripts/install-qwen-native.py` to upgrade an existing native launcher; +fresh installs also include key-file support. Then an authenticated endpoint can +be selected with `qwen-codex-ctl connect strata-native --url LOOPBACK_URL +--key-file PRIVATE_FILE`. Discovery validates file permissions and uses the +credential header. Agent launch configures `/bin/cat` as the provider's auth +command, with only the absolute key-file path in its arguments. The token is +not written to launcher argv, environment or generated configuration. Existing +`--no-auth` connections and `native-service` commands remain unchanged. + +Approval/review requests can append developer messages after user input. The +native adapter stably coalesces these instruction messages into the leading +Qwen system section, preserving their content and order. It does not demote +approval instructions to user messages or bypass the console's review step. + +Stateless replay keeps adjacent assistant commentary and function calls in one +assistant turn, with their reasoning content attached. The commentary-to-call +separator matches the pinned Qwen template, including trimming commentary's +trailing whitespace. The sanitized `commentary-tool-prompt.json` fixture checks +this against an independently rendered upstream template, byte for byte. + +Parallel tool outputs are matched by `call_id` and replayed in their original +call order. Qwen's tool-response markup has no ID field, so retaining arrival +order would swap results when parallel tools finish in another order. A +regression checks that ordered and reversed delivery produce identical prompts. + +An omitted `temperature` uses the engine's greedy default (`0`), and response +metadata reports `0`. Explicit temperature values are preserved. This reflects +the existing engine protocol rather than changing sampling for console runs. + +## Custom text tools + +Native Responses accepts `{"type":"custom","name":"run"}` with an optional +string description and optional `"format":{"type":"text"}`. Namespace +containers may include custom tools. Regex format has the validation-only +preview described below. Lark, unknown custom fields and non-text outputs are +explicitly rejected. `tool_choice` supports `auto`, `none`, `required`, `allowed_tools`, and forced top-level custom +tools; see [Tool choice and call count](#tool-choice-and-call-count). + +Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and +optional `namespace`; they never expose the internal JSON `arguments` wrapper. +SSE uses `response.custom_tool_call_input.delta` and +`response.custom_tool_call_input.done`, bracketed by the normal output-item +events. The names and public fields follow the official +[custom tools contract](https://developers.openai.com/api/docs/guides/function-calling) +and [streaming events](https://developers.openai.com/api/reference/resources/responses/streaming-events). + +Internally, the Qwen template receives a function with one required string +parameter named `input`. Its complete envelope is validated before a callable +item is published. The public input is unwrapped without trimming or interpreting +its contents. This uses the engine's existing tool markup and its delimiter +limitations; it adds no grammar-constrained decoding. In ordinary text streaming, +validated complete calls can appear before engine DONE. Reasoning/structured +paths retain their existing buffering rules. + +Replay accepts `custom_tool_call_output` with a string or `input_text` parts, +including `previous_response_id` continuation. Call IDs, namespace identities +and function/custom output kinds must remain paired; mixed parallel outputs +are reordered by call order. No custom tool is executed by the runtime. + +CPU fixtures verify transport and replay, including multiline Unicode and +whitespace, with exact equality. Real-model custom-tool quality and constrained +sampling remain unqualified; the existing GPU user trial has not been upgraded. + +### Regex custom input validation preview + +The native preview also accepts +`"format":{"type":"grammar","syntax":"regex","definition":"[0-9]+"}`. +The request shape and Rust regex dialect follow the official +[Regex CFG documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg). +Strata provides prompt guidance and complete-input validation; it does **not** +constrain token sampling. A mismatch fails the response rather than repairing +or retrying the call. This distinction applies to this preview even though the +wire format uses `grammar`. + +The entire input must match, including whitespace and Unicode; a substring match +is insufficient. Valid input is returned byte-for-byte. A completed call is +validated before its item-added, input delta or done events. Invalid input +produces a JSON generation failure or terminal `response.failed`; no callable +item for that invalid call is published. Earlier valid calls/text in a stream +cannot be retracted. Namespace lowering and continuation preserve their existing +identities and exact inputs. Replayed historical calls are not revalidated under +new tool definitions. + +Definitions must be nonempty single-line strings, at most 8192 bytes; use escaped +`\n` to match newlines. Each request allows at most 32 regex tools and 64 KiB of +definitions, including namespaced tools. Each compiled regex and DFA cache has a +1 MiB limit; AST nesting is limited to 64. Lookarounds, backreferences, lazy +repetitions, verbose (`x`) and swap-greed (`U`) flags are rejected before inference, +as are malformed/unknown format fields and Lark. These are compilation/cache +bounds, not a total runtime memory or latency guarantee. Existing unformatted +and explicit text custom tools retain their semantics. + +## Tool choice and call count + +`tool_choice` omitted or `"auto"` preserves automatic tool selection. +`"none"` hides current tool declarations from the prompt and prevents any +generated callable item from being published. Declarations are still validated, +response metadata preserves the caller's tools/choice, and historical calls and +results remain in the replay transcript. Literal text that resembles tool markup +with no declared tools remains text, as in the existing no-tools path. + +`parallel_tool_calls: false` permits zero or one function/custom call per +response, across all namespaces. Prompt guidance asks for at most one call; +the server enforces the count. Default/true permits multiple calls. These wire +semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). + +`"required"` requires at least one function/custom call at successful completion. +It needs a nonempty callable catalog (400 otherwise); together with +`parallel_tool_calls: false` it requires exactly one call. Namespaced calls +participate in the same count. + +`{"type":"function","name":"lookup"}` forces exactly one call to the declared +top-level function `lookup`, regardless of the parallel flag. Missing/unknown +names, custom tools selected as functions and extra selector fields fail with +400 before inference. A name is never treated as an internal namespace alias. +`{"type":"custom","name":"patch"}` likewise forces exactly one declared +top-level custom tool. Its text input is restored without modification; an +optional supported regex format is still validated before publication. The +selector must match the original tool's type, not its internal function lowering. +This [official custom selector example](https://developers.openai.com/cookbook/examples/partners/aws/openai_models_with_amazon_bedrock#44-use-a-custom-text-tool) +uses the same type/name shape. Forced namespaced selectors remain unsupported. +Unsupported choice kinds return 501; no choice is silently replaced with auto. + +`{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"lookup"}]}` +restricts new calls to a subset of declared top-level function/custom tools. +`mode: "required"` also requires at least one allowed call on successful +completion, as specified in the official [allowed-tools mode schema](https://github.com/openai/openai-python/blob/main/src/openai/types/responses/tool_choice_allowed_param.py). +The full declarations and historical calls/results remain in the prompt and +response metadata. Prompt guidance identifies the subset; the server rejects +disallowed calls before publishing their item or input/argument events. +This does not guarantee prompt-cache reuse or model compliance. + +The envelope accepts exactly `type`, `mode`, and `tools`; each selector accepts +exactly `type` and `name` matching its original declaration. Missing fields, +unknown names, wrong types, duplicate selectors, namespaced/internal aliases, +built-in tool selectors and extra fields return 400 before generation. +An empty auto subset permits text only; an empty required subset is rejected. +Multiple allowed calls are permitted unless `parallel_tool_calls: false`. + +These policies add prompt guidance while retaining declarations and history. +Their minimum count applies only to successful completion: a token-limit +`incomplete` response may contain no complete call. Wrong names and excessive +counts remain invalid even for incomplete responses. Initial streaming envelopes +are not subjected to a completion minimum. Original choice metadata is echoed. + +Buffered output that violates the policy fails with 502 before any callable +output is returned. In ordinary live SSE, a first valid call may already have +been published: a second call is rejected before its item/argument/input events, +and the stream ends with `response.failed`. Forced choice rejects a wrong first +call before publishing it; required choice with zero calls fails at completion. +Under none, no callable item is +published. Earlier valid text/calls cannot be retracted. Reasoning/structured +paths keep their existing buffering behavior. The runtime does not truncate, +repair or retry tool calls; these policies do not implement constrained sampling +or parallel GPU requests. + +## Active generation deadline + +An operator can opt into `engine.generation_timeout_s` / +`STRATA_GENERATION_TIMEOUT_S` (1–86400 seconds, absent means disabled). +The deadline covers an active command, including worker pipe and result-channel +backpressure. It excludes request parsing, tokenization and command queue wait. +It is an absolute execution budget, not an idle-token timer or client end-to-end +deadline. Timeout fails the worker, kills/reaps it and uses the existing finite +restart policy. No active or queued request is replayed. + +For a connected client consuming its response, buffered requests return 502 +`generation_failed` with `generation exceeded configured execution deadline`; +SSE ends in `response.failed`, retaining its preceding event sequence. The +generation counts once as failed/interrupted. Failure delivery after process +cleanup is bounded to one second; a full streaming channel is then closed, +and the adapter emits a failure once the consumer drains buffered events. +Delivery cannot be guaranteed to a disconnected/non-reading client. This setting +does not replace HTTP/proxy timeouts. The default leaves existing long-context +generation behavior unchanged. + +## Admission lifecycle + +`POST /admin/drain`, `POST /admin/resume` and `GET /admin/lifecycle` expose the +native [maintenance drain protocol](../deploy/README.md#drain-before-maintenance). +They use the existing optional bearer gate. During drain, new Responses +requests fail with 503 `runtime_draining` before request-body validation; +previously admitted work continues. `/ready` returns 503 and `/status.ready` +becomes false. Response protocol events and worker output remain unchanged. + +The configured `max_in_flight_requests` (default 17, range 1–256, overridden by +`STRATA_MAX_IN_FLIGHT_REQUESTS`) bounds concurrent POST Responses handlers before +JSON parsing or tokenization. A request holds capacity through response-body +completion/drop. When full, additional POST requests receive HTTP 429, +`Retry-After: 1`, and error code `runtime_overloaded`. Authentication runs first; +drain's 503 takes precedence over overload. Transient overload does not change +readiness. Health, management and stored-response GET/DELETE remain accessible. +Lifecycle reports `max_in_flight_requests` and `available_request_slots` (capacity +minus tracked requests, independent of drain mode); `check-config` reports the +configured maximum. + +This bounds HTTP inference handlers, not GPU slots or generation jobs. The +worker still executes serially. On disconnect the HTTP guard can be released +while a generation's separate guard waits for STOP cleanup. This is not a cap +on TCP connections, total process memory, or GPU memory, and does not implement +batching. Admitted requests retain the existing queue and response semantics. + +### Signal shutdown grace + +Top-level `shutdown_grace_s`, overridden by `STRATA_SHUTDOWN_GRACE_S`, accepts +integer seconds 0–20; default 0 preserves immediate worker interruption. +`check-config` reports the effective value. With positive grace, SIGTERM/SIGINT +sets irreversible admission drain, makes readiness false and waits for both +tracked HTTP requests and generation jobs to reach zero, up to the deadline. +Already admitted requests can enqueue and finish during this interval. New +requests receive 503 `runtime_draining` while the listener remains open. + +Lifecycle adds `shutting_down`. After a signal, `/admin/resume` returns the +current lifecycle with both `shutting_down` and `draining` true; it cannot reopen +admission. Ordinary administrative drain/resume remains reversible. The wait +ends early when both counters clear (checked every 25 ms), or on expiry proceeds +to existing worker interruption/QUIT and HTTP shutdown. A signal does not imply +that every request will finish: expiry can produce failed responses. + +This setting bounds the admission drain phase only. Worker/process and HTTP +connection cleanup follow it. The rendered systemd unit retains its 45-second +hard stop; the 20-second grace cap reserves time for worker cleanup. Standalone +execution has no new overall exit deadline. For longer maintenance, explicitly +drain and wait before sending the stop signal. diff --git a/docs/architecture/independent-nvidia-engine.md b/docs/architecture/independent-nvidia-engine.md new file mode 100644 index 00000000..b700e509 --- /dev/null +++ b/docs/architecture/independent-nvidia-engine.md @@ -0,0 +1,222 @@ +# Independent NVIDIA engine: architecture handoff + +**Status:** architecture proposal, awaiting Tech Lead review. This is a source +inventory and migration design; it does not claim a working inference engine. + +**Decision already made by the project owner:** Rust owns the runtime. Strata is +an upstream source for selected behavior and algorithms, not a build, runtime, +or deployment dependency. The new implementation repository is the private +Gitea repository `git@vezha.io:para/leleka.git`; its remote is reachable and was +empty when checked on 2026-10-05. Keep this architecture record and the existing +Strata provenance in `strata-next`; implement the replacement in Leleka. + +## 1. Options and recommendation + +| Option | Benefits | Costs and risks | Decision | +| --- | --- | --- | --- | +| Keep the current C++ Strata engine and Rust control plane | Reuses the most inference code; shortest path to the existing Qwen setup | Production remains coupled to Strata's executable, `--serve` wire format, build and model profile | Reject as the target; preserve only as the behavior/reference baseline | +| Rust-owned engine and scheduler, with CUDA C++ kernels behind a narrow internal ABI | Rust owns model loading, tensors, routing, KV, admission, scheduling, lifecycle and API integration; existing CUDA kernels can be ported in measured steps | Initial CUDA kernels still need the CUDA build toolchain; FFI ownership, shape and stream contracts need tests | **Recommend.** This meets the owner's independence goal without pretending CUDA kernels can be safely rewritten in one pass | +| Rewrite all runtime and kernels in Rust immediately | One main language and fewer long-term language boundaries | Rust does not remove the need for CUDA/PTX; kernel parity and performance need separate proofs, and a big-bang rewrite delays a usable runtime | Reject as the first migration stage; replace individual kernels only after parity and paired performance gates | +| Rust host with a separate Python/C++ serving engine | Can compose existing libraries quickly | Keeps a second runtime, protocol bridge, process lifecycle and extra packaging dependencies; violates the desired self-contained production runtime | Reject for production. Python remains allowed only for offline research/evaluation where useful | + +This is a staged C++/Python-to-Rust migration, not a literal syntax +translation. Move ownership of serving behavior first. Keep CUDA C++ only at a +small kernel boundary while each kernel is ported or replaced against a numeric +oracle. The shipped Linux runtime should need an installed NVIDIA driver, not +the CUDA toolkit, a compiler, Python, or a Strata installation. Build-time CUDA +toolkit use is acceptable. The release gate must inspect the final artifact's +ELF dependencies to prove the driver-only installation claim. + +## 2. Existing coupling inventory + +The current repository is an intermediate product. These references explain +what Leleka must replace; they are not a requirement to copy the imported tree. + +| Area | Current source | What it means for independence | +| --- | --- | --- | +| CPU engine build | [`scripts/build-cpu.sh`](../../scripts/build-cpu.sh#L13) configures CMake from `engine/strata/` | Remove this from the Leleka build and release path | +| CUDA engine build | [`scripts/build-static-cuda.sh`](../../scripts/build-static-cuda.sh#L14) compiles target `strata`; its checks run the imported engine's ELF audit and `--help` | Replace the engine source and qualify the new binary; do not call `--help` an inference test | +| Hosted CUDA package workflow | [`.github/workflows/linux.yml`](../../.github/workflows/linux.yml#L139) builds the actual Strata engine; later steps combine and package it | Leleka CI must build its own runtime from pinned sources and retain build provenance | +| CLI image license | [`deploy/Dockerfile.static-cli`](../../deploy/Dockerfile.static-cli#L13) copies the imported engine license into the CLI-only image | Preserve required notices for any source actually reused; remove the Strata license copy only when no Strata code is shipped | +| Worker process boundary | [`worker.rs`](../../control-plane/src/worker.rs#L84) accepts an executable and arguments; the worker process is supervised and generation is sent to it | Replace the serving child process with an in-process Rust `InferenceBackend`; keep process isolation as an optional later boundary | +| Strata serving wire | [`wire.rs`](../../control-plane/src/wire.rs#L1) explicitly implements the resident Strata `--serve` stdin/stdout protocol | Delete this adapter from the replacement path; the public API must not inherit this private wire protocol | +| Embedded engine package | [`embedded_engine.rs`](../../control-plane/src/embedded_engine.rs#L1) stores and starts a separately built engine executable, and says model/shared libraries are not bundled | Package the Rust engine directly; model assets remain independently acquired and SHA-verified | +| Qwen-only model prep | [`native_model.rs`](../../control-plane/src/native_model.rs#L30) has one `RuntimeProfile::Qwen4expFlashNext`; GGUF/native pack helpers are preparation code, not an inference implementation | Keep Qwen import/preparation behind a model adapter or offline tool; define a versioned model descriptor instead of extending a single-profile enum | +| Build-time GGML C code | [`build.rs`](../../control-plane/build.rs#L6) compiles a vendored pinned `ggml-quants.c` plus `ggml_bridge.c`; [`ggml_bridge.rs`](../../control-plane/src/ggml_bridge.rs) uses it for GGUF quant conversion | This is a preprocessing dependency rather than serving inference. Move it to an optional offline packer crate so the shipped serving CLI does not need a C compiler or GGML bridge | +| Offline scripts | [`compare-real-tokenizer.py`](../../scripts/compare-real-tokenizer.py), [`prepare-keyless-routing.py`](../../scripts/prepare-keyless-routing.py), and pack smoke scripts import Strata tools or inspect Strata sources | Replace or retire them one at a time; keep them out of serving and never silently treat their output as production support | +| KAR experimental adapters | [`gpu/kar/README.md`](../../gpu/kar/README.md#L3) documents a narrow experimental expert component and explicit limits | Port the file/container concepts and proven kernels selectively; do not port the Strata callback as the new runtime boundary | +| Provenance | [`docs/upstream.md`](../upstream.md#L1) pins the imported Strata SHA and describes subtree update procedure | Preserve this historical record unchanged. Add a separate Leleka source/provenance manifest; do not rewrite the old upstream identity | + +`responses.rs` is a Rust protocol layer that currently consumes worker/tokenizer +types. Its role can remain in the Rust control plane, but it must call the new +backend API rather than depend on Strata's tokenizer, worker executable or +wire format. The public `/v1/responses`, SSE, cancellation, auth and health +contracts need their own replay tests; the model engine should not implement +HTTP semantics. + +## 3. Leleka backend boundary + +### Ownership + +Leleka is a Rust workspace with at least these logical crates: + +1. `leleka-api`: versioned request, model descriptor, capability, memory-plan, + error and event types. No CUDA or model implementation dependency. +2. `leleka-engine`: Rust-owned model loader, tensor/layout registry, tokenizer + integration, router, KV allocator, scheduler, sampling and lifecycle. +3. `leleka-cuda`: safe Rust wrappers over a narrow private CUDA C ABI. It owns + device/context/stream/event/buffer lifetimes; kernels cannot retain pointers + after the wrapper's borrow or stream completion. +4. `leleka-server`: HTTP/API translation, SSE, auth, cancellation and + observability. It talks to `leleka-api`, not to model-specific tensor layouts. +5. `leleka-tools`: offline conversion/evaluation only. It is not a dependency + of the serving binary and may contain Python during the transition. + +The initial backend is compiled into the process. Rust trait objects are not a +stable cross-version plugin ABI; if external native plugins are needed later, +define a layout-safe C ABI with explicit size/version fields and opaque handles. + +### Versioned contract (proposal) + +`leleka-api` has an explicit `API_MAJOR` and a capability-schema version. +Incompatible event, layout or error semantic changes increment the major +version. Release metadata records engine commit, CUDA kernel source digests, +toolchain, model adapter version and supported quantization IDs. + +The backend contract contains these operations: + +- `capabilities() -> CapabilitySet`: architecture IDs, quantization/layout + identifiers, attention/KV forms, limits, cancellation and streaming support. +- `load(ModelArtifact, ModelConfig) -> LoadedModel`: validate artifact digest, + descriptor, hardware/driver constraints and required tensors before publishing + a ready model. Partial failure drops all owned allocations. +- `memory_plan(ModelDescriptor, RequestDemand) -> MemoryPlan` and + `admit(MemoryPlan) -> Result`: account for + weights, cache, KV, scratch/workspace, simultaneous slots and safety margin; + reject before mutation when the request cannot fit. +- `health()`, `readiness()` and `model_metadata()`: readiness is false until + weights, kernels, tokenizer and required runtime state are verified. +- `generate(Request, CancellationToken) -> Stream`: stream + token IDs and optional token bytes/diagnostics plus a single terminal result. + The server maps those events to Responses/chat SSE. The stream has bounded + backpressure and a request ID. +- `cancel(request_id)` and `drain(deadline)`: stop future work, cancel active + work at a documented safe boundary, then release allocations exactly once. +- `unload()`: reject new admissions, drain/cancel according to policy, release + model/KV/cache ownership, then report unloaded. + +Errors are typed: `UnsupportedArchitecture`, `UnsupportedQuantization`, +`UnsupportedCapability`, `ArtifactMismatch`, `InsufficientMemory`, +`DriverIncompatible`, `LoadFailure`, `Cancelled`, `DeadlineExceeded`, +`DeviceLost`, `BackendFault`, and `ProtocolViolation`. No unsupported format +may silently fall back to a lossy conversion. Every accepted generation emits +exactly one terminal event (`completed`, `cancelled`, `length`, or `failed`); +after a terminal event no more deltas for that request are legal. Error details +are machine-readable and safe for API mapping; raw prompts, model tensors and +secret values are never diagnostics. + +The model descriptor is immutable per loaded model and includes architecture +family/revision, layer and expert geometry, router semantics, attention/KV +layout, tokenizer/template digests, tensor names/shapes, quantization scheme, +packing schema, context bound, required auxiliary heads and artifact digest. +Model-family names alone do not authorize tensor reinterpretation. + +## 4. Capability and optimization portability + +| Concept | Reusable part | Model/quantization-specific part | Safe behavior until qualified | +| --- | --- | --- | --- | +| Compressed weights resident in VRAM | Block store, byte-range validation, residency planner and bounded scratch allocation | Archive/tensor mapping, scale/group geometry, codebook and dequant arithmetic | Accept only exact versioned pack schema and tensor digest; otherwise reject or use an explicitly supported native format | +| Bounded expert cache | LRU/admission/eviction accounting and metrics | Expert IDs, dimensions, routing semantics, packed payload size and CUDA tile geometry | Cache only verified experts from the loaded descriptor; evict or fall back to a verified native path | +| KAR decoder | Container reader and generic bounded decode orchestration after schema validation | Current KAR top-down group-32 expert shape, levels, quant bytes and F32 accumulation; current code does not establish model-quality parity | Experimental opt-in only; reject shape/schema mismatch; never claim full-model residency or speed from the component probe | +| Expert routing and scheduling | Queue, batching windows, cancellation, fair admission and cost accounting | Router weights, top-k, shared/routed experts, normalization, correction bias and token-to-expert mapping | Use the model adapter's exact reference routing; unsupported router versions fail closed | +| KV allocation/streaming | Page/slot allocator, budget policy, asynchronous transfer lifecycle and accounting | MHA/GQA/MLA tensor layout, head sizes, position encoding, quantization, scales and block packing | Select only a declared KV format supported by that adapter; otherwise reject or use its verified lossless/default format | +| PLE | Sparse table paging/cache and row-request abstraction | Table meaning, lookup geometry, packing and exact association with model layers/experts | Disable unless manifest binds PLE artifact to model digest and adapter validates geometry | +| MTP/speculative decoding | Draft/verify scheduler mechanics and accepted-token counters | Trained draft heads, tokenizer, logits alignment, depth and model-specific verification semantics | Disable by default; enable only for an artifact declaring compatible heads and after exact greedy/quality gates | +| Value-only KV / lossy KV | Cache policy experiments and measurement hooks | Quality behavior depends on the exact model, workload, context and cache policy | Keep disabled; the existing Qwen V-only pretrained quality screen failed | +| Tokenizer and chat template | Byte streaming and API event mapping | Vocabulary, merge rules, special tokens, template and tool-call grammar | Require matching digests; no approximate tokenizer/template fallback | + +“MoE-compatible” means the model uses sparse experts, not that its weights, +router, attention, tokenizer, cache, quantization or speculative heads can be +reused. Every matrix row must be keyed by a model and pack manifest, not a broad +architecture label. + +## 5. Candidate model families and evidence gaps + +These are adapter/evaluation candidates, not supported models. + +| Candidate | Public artifact and license evidence | Compatibility and the first port-specific work | Evaluation feasibility and blocker | +| --- | --- | --- | --- | +| Mistral Mixtral-8x7B-v0.1 | Official [model card](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) lists Apache-2.0 and describes a sparse MoE; official weights are available | Conventional attention plus sparse expert feed-forward gives a second-vendor router/weight-map adapter. Validate safetensors mapping and select a documented quant pack; do not reuse Qwen IQ3 conversion | Public reference weights and a reference runtime make tensor/logit and greedy-token oracle generation feasible. No Mixtral tensor map, converted artifact, quality corpus, or protocol trace is currently checked in; 32-GB fit at useful context depends on quantization and remains unproven | +| DeepSeek-V2-Lite | Official [model card](https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite) lists 16B total / 2.4B active parameters, safetensors and the DeepSeek model license; the [paper](https://arxiv.org/abs/2405.04434) describes MLA + DeepSeekMoE | Distinct latent-attention KV state and DeepSeekMoE routing require a separate attention/KV and router adapter. Published model context is 32K; do not assume Qwen's 256K/512K profile | Public reference weights/paper permit an adapter smoke and deterministic oracle suite. The model license has use-based conditions; compliance review and the exact license must accompany any distribution. No converted artifact or project quality/protocol evidence exists; 32-GB quantized launch and long-context target are unproven | + +If the owner wants the first extra family to be easier to serve on a 32-GB +card, Qwen3 MoE is a lower-variance adapter step but does not demonstrate a +second vendor or distinct attention family. Mixtral and DeepSeek-V2-Lite are +therefore the stronger architecture-coverage candidates; lawful artifact +selection and evaluation-data availability remain explicit gates. + +## 6. Migration and qualification stages + +1. **Repository and interface foundation (Leleka).** Create a clean Rust + workspace in the new Gitea repo, record licenses/provenance, pin Rust/CUDA + build inputs, define the API/capability schema, and add mock-backend + lifecycle/cancellation/memory-admission tests. No model or GPU is needed. +2. **Qwen correctness path.** Add a Qwen adapter and one explicit lossless + quant/pack path. Compare tokenizer IDs, tensor loads/dequant bytes, routing, + logits and greedy token IDs against the pinned reference. Then replay + sanitized real protocol traces: non-streaming, SSE terminal events, tool + calls/results, cancellation, timeout, reconnect and worker/device failure. +3. **Linux NVIDIA runtime artifact.** Build a reproducible self-contained + executable/image in CI. On a clean Linux host with an NVIDIA driver, audit + ELF dependencies, load the model, verify readiness, exercise API/cancel, + stop/restart and rollback. Host installation must not need Strata, Python, + CUDA toolkit or compilers. Model assets remain separately pinned and + integrity-checked. +4. **Port optimizations one at a time.** Start with bounded expert residency, + then KV policy/streaming, then exact-format KAR work, then optional PLE/MTP. + Each stage has a numeric oracle and its own isolated quality gate; lossy or + experimental arms remain off by default. Port CUDA kernels only when exact + output/tensor requirements pass and paired end-to-end measurements justify + keeping them. +5. **Model-family expansion.** Land Mixtral adapter + exact quant path and + protocol/quality suite; separately land DeepSeek-V2-Lite with MLA/KV tests + and license review. Passing one family does not imply support for other MoE + variants. +6. **Cutover.** Preserve Strata as the reference until the same sanitized API, + model, quality and deployment suites pass. Run a controlled paired workload + comparison with engine/model/config/cache/token counts recorded. Canary on a + separate port/service with artifact rollback; keep the last accepted + runtime selectable until the new build passes gates. Only after acceptance + remove Strata from the Leleka production/release path; retain historical + source provenance in `strata-next`. + +No stage claims performance from compilation, synthetic kernels, mock-backend +tests, source inspection, or model loading alone. Required project profiles +remain `1 x 512K` and `2 x 256K` on the stated target; `1 x 256K` is an interim +local profile and cannot stand in for them. + +## 7. Immediate implementation work breakdown + +The next implementation tasks belong in Leleka, after this handoff receives +Tech Lead acceptance: + +1. Establish clean repo/CI and the versioned `leleka-api` crate with a mock + backend; verify no Strata import/build/runtime dependency. +2. Move the Rust control-plane event/API contract behind `leleka-api`; add + lifecycle, cancellation, single-terminal-event and admission tests. +3. Split offline GGUF/tokenizer preparation from the serving build; pin source + and artifact digests, with no production Python import. +4. Add the Rust-owned engine/model-loader skeleton and CUDA safe-wrapper crate; + first acceptance is CPU/mock behavior plus CUDA driver/toolchain contract, + not GPU inference. +5. Implement one Qwen lossless model path, exact numerical/token parity, then + run its real NVIDIA/protocol/quality gates on a host explicitly reserved for + qualification. +6. Create separately scoped Mixtral and DeepSeek adapter tasks only after the + corresponding legal artifact, supported quantization and evaluation corpus + are pinned. + +These are proposed bounded work items, not evidence that the deliverables +already exist. The new repository was empty at the time of this handoff; no +model files, traces, credentials, build artifacts or user workload data are +copied into it. diff --git a/docs/build-validation.md b/docs/build-validation.md new file mode 100644 index 00000000..6edfc9ca --- /dev/null +++ b/docs/build-validation.md @@ -0,0 +1,911 @@ +# Build validation + +## 2026-10-03 — experimental PLE quality arm + +The imported engine builds on Linux CUDA 13.2/sm_120 with the optional +`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` flag. The ordinary build still succeeds +with the flag off. A synthetic KAR-2 archive with four 160-value PLE rows in +two parts was generated by the Rust CLI. The independent Rust decoder and the +new Strata `PleTable` probe matched FNV-1a checksums for all four rows, including +the boundary between parts: `20c844888ce711a5`, `6a219cbf159362a5`, +`62bed3d23ae584a5`, and `68137da89d55afa5`. The fixture was deleted from +both hosts after the check. This verifies row layout, bit order, scale/book +reconstruction, and part indexing on a synthetic archive; real-model output +and paired throughput remain unmeasured. + +## 2026-10-02 — source-only build + +- Strata upstream commit: `d9ab8435f654c368c586340d490915f6addf56a3`. +- Host: macOS arm64; AppleClang 21.0.0; CMake 3.31.10; Ninja 1.13.2. +- Command: `PATH="$PWD/artifacts/tool-venv/bin:$PATH" scripts/build-cpu.sh`. +- CMake flags: CUDA off, HIP off, upstream broad test suite off, conversation tests on. +- Built: `strata-gguf`, `strata-dequant`, `strata-plan`, and five CPU test executables. +- Result: 5/5 CTest tests passed. +- Scope: source compilation and CPU tests only. No CUDA build, model inference, or performance measurement was performed. + +The test toolchain was installed into ignored `artifacts/tool-venv/` for this run; it is not a production dependency. + +## 2026-10-02 — Rust control-plane smoke test + +- `cargo fmt --check` and `cargo check --locked` passed with Rust 1.95.0. +- With no worker configured: `/health` returned 200 and `/ready` returned 503. +- With an ignored local fake engine that emitted `READY 262144 stop`: `/ready` returned 200 with `max_context: 262144`; Ctrl-C shut down both processes. +- With a fake engine that exited after `READY`: `/ready` returned 503 with `worker: failed`. +- `/v1/responses` is not implemented and returned 404. No model inference was tested. + +## 2026-10-02 — local worker contract checks + +- Added JSON file configuration with environment overrides and a bounded startup timeout. +- Four local tests pass against a fake engine process: valid `READY` handshake, graceful `QUIT`, worker exit, and startup timeout. +- The tests require neither the RTX 5090 nor model files. + +## 2026-10-02 — Responses contract and Rust 1.99 + +- Pinned Rust 1.99.0 with `rust-toolchain.toml` and `rust-version = "1.99"`. +- `scripts/check-local.sh` passed: rustfmt, Clippy with warnings denied, 12 Rust tests, synthetic Responses SSE replay, and 5 CPU CTest tests. +- The replay checks the local response builder and Strata pipe parser only. `/v1/responses` still returns an explicit 501 when the worker is ready because the inference adapter is not connected. +- No CUDA build, model inference, real Codex replay, or performance measurement was performed. + +## 2026-10-02 — internal worker generation exchange + +- A fake resident worker accepted a `GEN` command and returned `PP`, `T`, and `DONE` through the Rust supervisor. +- Context admission rejected a request exceeding the worker's `READY 262144` limit without failing the worker. +- Rust 1.99 Clippy with warnings denied and all 13 Rust tests passed. This is a pipe test only; the HTTP inference adapter is still absent. + +## 2026-10-02 — model CLI and Linux delivery preparation + +- Added an embedded, commit-pinned IQ3_S manifest, resumable `model fetch`, full-size/SHA-256 `model verify`, and bounded GGUF v3 `model inspect`. +- `scripts/check-local.sh` passed on macOS arm64 with pinned Rust 1.99.0: rustfmt, Clippy with warnings denied, 18 Rust tests, synthetic Responses SSE replay, and 5 CPU CTest tests. +- The interrupted-transfer test resumes a local HTTP fixture and rejects a corrupted final file. The GGUF test parses a synthetic v3 header and rejects truncation. +- The real 83.6 GB model was not downloaded or inspected. The Hub-provided LFS ETags are recorded as expected SHA-256 values but have not been measured locally. +- The Linux/arm64 Docker musl CLI image built and its `--version` command ran inside a `scratch` container. The current source was also cross-compiled locally for `aarch64-unknown-linux-musl`; `file` reported a statically linked ELF, and `readelf` found no interpreter or dynamic section. +- Mounted the current binary into that `scratch` image. It fetched Rust 1.99.0's pinned README over HTTPS (`3,304` bytes), verified the manifest SHA-256 (`b3f6ef2fef88b98cb9ec013a5c86213095e53e40eb228679574e4d06517f33c8`), and matched the host reference byte for byte. This verifies embedded TLS roots and the small-file acquisition path, not the 83.6 GB model transfer. +- The Strata Next GitHub repository does not exist yet. This local checkout has only the `strata-upstream` remote, so the workflow has not run on GitHub Actions. No GPU node was used. + +## 2026-10-02 — worker cancellation contract + +- A dropped generation receiver now causes `STOP`, drains the worker's terminal `DONE`, and leaves the resident worker ready for a second request. +- Shutdown during an active generation sends `STOP` before `QUIT` and closes the pending result receiver. +- The two focused fake-worker tests pass, along with Rust 1.99 Clippy with warnings denied. No GPU inference was used. + +## 2026-10-02 — native tokenizer asset extraction + +- Added `model extract-tokenizer` for validated GGUF v3 `gpt2`/`qwen35` metadata. It writes five tokenizer files into a staging directory and publishes the directory on completion. +- A synthetic GGUF with vocabulary, merges, token types, special ID, and chat template produced the same parsed JSON and exact text files as the pinned upstream `tools/strata_tokenizer.py` (5/5 files). The upstream comparison used Python `regex` only as an offline test dependency under ignored `artifacts/tool-venv/`. +- Rust 1.99 formatting, Clippy with warnings denied, and 21 Rust tests passed at this stage. The real model tokenizer and packed weights were not validated. + +## 2026-10-02 — native BPE parity + +- Added qwen35 byte-level BPE encoding and decoding in Rust, including rank-ordered merges, a heap path for long pieces, control and user-defined literal handling, and a CLI path for text on standard input. +- Compared 20 corpus strings in both special-token modes against the pinned upstream Python tokenizer with a synthetic complete byte vocabulary: 40/40 token-ID sequences and decoded strings matched. Cases included multilingual text, emoji, combining marks, C0 bytes, long repeated text, and near-miss literals. +- Added fixed oracle ID cases to Rust tests. The real IQ3_S tokenizer and end-to-end generation remain untested. +- `scripts/check-local.sh` passed after this change: rustfmt, Clippy with warnings denied, 24 Rust tests, synthetic SSE replay, and 5 CPU CTest tests. +- Rebuilt the current source as a statically linked Linux/arm64 musl CLI. Mounted it into the `scratch` image and confirmed `model tokenize` returned the oracle IDs for `Hello, world!`. The actual model weights and GPU were not used. + +## 2026-10-02 — text inference preview and KAR-2 verification + +- Qwen text-only prompt assembly matches eight pinned upstream golden cases byte for byte. A synthetic in-process worker receives the expected native token IDs through the HTTP Responses route and returns a completed non-streaming text response. Live streaming, reasoning output, tools, and real-model inference remain unverified. +- Added bounded KAR-2 metadata inspection, streaming CRC-32 verification of every tensor section, and optional source-manifest verification. The latter checks each shard's size and SHA-256, then hashes the shards in ascending byte-wise filename order against the archive's source digest and byte count. +- Independently generated a 1,280-byte two-tensor RAW/NESTED archive with koference `r08/code/kar_container.py` at commit `806d2398ae1daaceb2917242911e5680cbfb3608`. Its Python reader and the Rust `model verify-kar` both accepted the archive and both tensor CRCs. A two-file synthetic source manifest passed the Rust source-identity check. The temporary archive and source bytes were kept out of Git. +- Rust 1.99 formatting, Clippy with warnings denied, and 31 Rust tests pass after adding a disk-space preflight that rejects an impossible model transfer before networking. The full `scripts/check-local.sh` cannot reach CPU engine tests on this machine because CMake ≥3.24 is absent; the local GitHub Actions workflow installs CMake, but it cannot run on a hosted runner until the Strata Next GitHub repository exists. +- Rebuilt the current CLI as a Linux/arm64 musl executable in a `scratch` image. `--version`, KAR-2 payload verification, and the optional two-shard source-identity check all ran successfully inside the image against the synthetic koference archive. This proves the current static CLI starts without a user-space loader, not that a GPU engine or real model runs. No model weights or GPU node were used. +- Ported the koference KAR-2 container writer for already encoded RAW/NESTED tensor slices to Rust. A native two-tensor archive has the same SHA-256, `013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2`, as the independently generated reference archive at koference commit `806d2398ae1daaceb2917242911e5680cbfb3608`. The writer's temporary output passes native payload verification before publication. This fixture is synthetic and does not establish model quality or a bounded-memory full-model conversion. +- Rust 1.99 formatting, Clippy with warnings denied, and all 32 Rust tests pass with the native writer. +- Added a GGUF tensor index that checks exact source block lengths and can hash one tensor with a fixed 1 MiB buffer. A synthetic mixed F32/IQ3_S fixture verifies offsets, lengths, and rejection of overlapping sections, a misaligned quantized row, and an unsupported type. All 33 Rust tests and Clippy with warnings denied pass; this is a source-layout check, not a KAR encoder or model conversion. +- The `model index /tmp/strata-next-index-smoke.gguf --hash` CLI emitted the expected two JSON records: F32 at absolute offset 128 with 16 bytes, and IQ3_S at 160 with 110 bytes; both SHA-256 values matched the synthetic zero payloads. `cargo check --locked --target aarch64-unknown-linux-musl` passed with this source. +- The KAR writer's file-backed RAW path generated the same complete archive bytes as its in-memory path, rejected a changed source digest without publishing a destination, and passed a separate 1,048,580-byte input crossing the 1 MiB copy boundary. Rust 1.99 formatting, Clippy with warnings denied, all 34 tests, and Linux/arm64 musl cross-check pass. NESTED encoded data is still in-memory, so full-model conversion is not bounded yet. +- Added a file-backed NESTED path for already coded KAR sections. A synthetic file-backed section produces the same complete archive bytes as the in-memory writer; corrupted scale, nonzero padding, and wrong section digest each fail before publication. The path streams through 1 MiB and retains no full encoded tensor in RAM. All 35 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source-to-NESTED encoder is still missing, so this does not complete model conversion. +- Added an experimental native f32-to-KAR bit-plane encoder with supplied thresholds. A synthetic four-cell pattern produced the koference word layout (`0xcccccccc`, `0xaaaaaaaa`), then passed through the KAR writer and verifier. IEEE f16 scale conversion tests include the smallest subnormal and ties-to-even. All 37 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Calibration fitting, IQ3_S decoding, bounded source conversion, and full-model quality remain open. +- Added bounded CPU prefix decoding for the synthetic tensor: a five-value slice reconstructed at levels 1 and 2 exactly as the supplied f16 books specify, and an out-of-range slice was rejected. This oracle has not yet been compared with the koference GPU decoder on hardware. +- Ported top-down nested boundary and book fitting for a supplied normalized sample. Two pinned koference Python fixtures match the Rust f32 boundary bits and f16 book values; a degenerate sample is rejected. The f64-to-f16 path avoids double rounding of fitted means. All 38 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This only establishes synthetic calibration parity, not representative model sampling or a quality result. +- Connected a small synthetic F32 GGUF to `model prepare-f32-preview`: it produced a verified KAR-2 archive with source SHA-256 `f2bff437d5a53e8ddf7f43ee41acf3baebb7fb5f27eefb079f5bc1634def6f2c` and archive SHA-256 `fe049ca40305d5380caaa278f34a9149ae2d5761ea9544b58a0eb73775cd6810`. The separate `model verify-kar` command passed. A valid synthetic IQ3_S GGUF was rejected by the F32 preview, without creating an archive. All 40 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This is a bounded experimental integration path, not full-model preparation. +- Refactored the F32 preview to write each tensor's canonical NESTED section to a private staging directory, then assemble the KAR archive from file-backed sections. The native section bytes match the in-memory writer. A two-tensor fixture succeeds and leaves no staging directory; corrupting the second tensor to NaN fails after the first section and also cleans staging without publishing an archive. The preview source-size and per-tensor limits remain; IQ3_S source decoding and full-model quality remain open. +- Added a native IQ3_S CPU block decoder with the pinned ggml grid table (SHA-256 `bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`). A deterministic mixed 110-byte block produced 256 F32 values whose byte digest `cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec` matches an independent Python calculation from the upstream layout; constant, sign, multi-block, and malformed-scale cases also pass. All 41 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. This has not been compared with a real tensor or GPU. The ggml MIT license is copied into the control binary and shown by `--ggml-license`. +- Added `model derive-iq3-identity` for a single all-IQ3_S GGUF. It hashes the original GGUF and a virtual contiguous little-endian F32 stream, with per-tensor original/derived digests and offsets, using a 256-block input buffer; no expanded file is written. A two-tensor fixture with reversed physical and directory order matched an independently assembled F32 stream digest. All 42 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed tensor types, shard sets, real-model parity, and KAR publication remain unverified. +- Added `model prepare-iq3-preview` for a small all-IQ3_S GGUF. A synthetic one-tensor input produced a KAR-2 archive with the virtual F32 source digest and a provenance sidecar binding the original GGUF, derived stream, and archive SHA-256 values. The archive passed payload verification. A preexisting sidecar blocked publication and the newly written archive was removed. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The source decoder and compressed output have not passed a real-model quality gate or GPU test. +- Added `model verify-iq3-preview` to recompute the original and virtual F32 identities, check KAR per-tensor source records and payload CRCs, and compare the provenance sidecar with the archive hash. The synthetic IQ3 preview verified; changing the sidecar's archive digest caused rejection, and restoring it passed again. A separate `cargo build --locked` CLI smoke generated and verified a temporary one-tensor archive: virtual F32 SHA-256 `9d1f76b4ef22e4b0e1f7e8d13cd3ff91516c884e9b8aa8107c8932bfd64fed85`, archive SHA-256 `c4d4e843165aa2599206458f0550c24eaafe95c3dacffec5e736950e16d1769c`. All 43 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check passed. This is identity/integrity verification, not an assessment of model quality or GPU behavior. +- Added `model derive-mixed-identity` for one GGUF containing IQ3_S and F32/F16/BF16 tensors. A four-tensor fixture with directory order different from physical order matched the independently assembled F32 byte-stream SHA-256, including half and bfloat conversions, and the all-IQ3-only derivation rejected it. The command uses a fixed 28,160-byte source buffer and writes no expanded file. All 44 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed KAR preparation, real-model parity, and GPU quality remain open. +- Added `model prepare-mixed-preview` and `model verify-mixed-preview`, with a separate versioned sidecar carrying each original tensor kind and digest. A four-type synthetic GGUF passed preparation and verification in Rust tests. A separate two-type CLI smoke produced a KAR archive whose virtual F32 SHA-256 was `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7`; the verifier matched the source, sidecar, KAR source records, and payload CRCs. All 45 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The preview remains capped at 64 MiB input and is not approved for serving. +- Added `model derive-sharded-identity` for manifest-pinned GGUF shards. A two-file fixture deliberately listed IQ3_S before F32 in its manifest; native derivation sorted filenames, checked both size/SHA-256 values, and assigned global F32 offsets 0 and 128. Replacing a manifest SHA-256 with the wrong value was rejected. A separate CLI smoke emitted the expected derived stream SHA-256 `e529f5e2f7aac1aa5509fabe728d84ab876c64754635963825e265cd70cb8b05`. All 46 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. No sharded KAR archive or real-model conversion was attempted. +- Extracted the shared one-tensor preview encoder and reconstruction check for future sharded preparation. Existing F32, IQ3_S, and mixed preview tests passed. Rebuilt the CLI and reran the pinned two-type mixed fixture: the derived F32 SHA-256 remained `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7` and the full KAR archive SHA-256 remained `4053e787d46b2cf2bca3d67e38d06e1ee96a157e80e3155c8dbdbf36835df88c` byte for byte. This is a non-lossy refactor of the preview implementation, not a quality result for the lossy format. +- Added a CI-only synthetic mixed GGUF/KAR smoke script for the Linux musl release binary. The workflow is configured to reject an ELF interpreter or `NEEDED` dynamic library, run the CLI through derivation, preparation, and source/provenance/archive verification, and check the pinned derived/archive SHA-256 values before uploading. The script passed locally against the current macOS debug CLI. The hosted workflow cannot run until the Strata Next GitHub repository exists and this checkout is connected to it. Python is used only to create the CI fixture, not by production serving. +- Added `model prepare-sharded-preview` and `model verify-sharded-preview` for two or more manifest-pinned GGUF files under the existing 64 MiB preview limit. A two-shard synthetic Rust test passed archive preparation, provenance verification, and source-record checks; changing a pinned manifest digest caused rejection. A separate CLI smoke built and verified an archive with derived F32 SHA-256 `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7` and archive SHA-256 `49206cc99935dad8ddc1cb342dfc263548285e04767237c2c377c23d33a88479`. All 47 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check passed. No full-model conversion, CUDA decode, or throughput comparison was performed. +- Added `model prepare-sharded-streamed` and `model verify-sharded-streamed`: the experimental path samples at most 65,536 normalized values per tensor, writes nested or exact RAW F32 sections from bounded GGUF chunks, checks per-tensor physical/virtual digests, rehashes each shard, assembles a KAR-2 archive, and binds a separate versioned sidecar. The two-shard F32/IQ3_S synthetic test verifies the archive, reconstructs a dense tensor on CPU, rejects a changed preparation level and pinned shard digest, and refuses to overwrite the archive. All 56 Rust tests and Clippy with warnings denied passed locally. The CLI reports actual archive bytes and accounted bits per weight. Real Qwen shards have not been converted, and no GPU quality or speed result exists. +- Extended the existing static-CLI smoke script with two manifest-pinned synthetic shards. The local macOS CLI prepared and independently verified their streamed archive; its SHA-256 is pinned as `51688d265860172feca39e296f9142b1ed16800496bae4b06b4b8d8fa11d806e`. This script is wired into the Linux musl workflow, but hosted GitHub Actions has not run because this checkout has no remote repository. The fixture is synthetic and says nothing about full-model size or quality. +- Added opt-in `model ensure-sharded-streamed`: fetches pinned GGUF shards, verifies source bytes, creates and verifies the streamed archive, then rehashes and checks source/provenance/payload on reuse. A local CLI smoke created and reused the synthetic two-shard archive and rejected a rerun with a changed level without modifying the existing file. Full 83.6 GB model preparation has not run; the local checkout had about 121 GiB free at this step, insufficient for source plus staged and final archive. No full-model size is reported yet. +- Began the pinned Qwen3.8 IQ3_S model download into a local model directory outside Git. Read only the header/directory bytes from the partially downloaded first shard and an HTTPS range of the second: 1,223 and 1 tensors respectively, 13 GGUF types, and 176,943,899,520 total elements. The second shard omits `general.architecture`. Summing the KAR-2 level-2 nested layout over these unverified directory entries gives 55,295,262,208 payload bytes (55.30 GB); this assumes every tensor uses nested encoding, excludes small container overhead, and is **not** an observed archive size or a quality result. The full shard hashes still need to match the manifest. +- The KAR writer now has an internal consuming mode for private file-backed sections: after each verified copy into its temporary archive, it removes that staged section, reducing peak disk use. The normal non-consuming writer remains available. A dedicated test verifies staged RAW removal and a valid published archive; the two-shard test now also covers a shard with no architecture metadata. Local targeted tests and Clippy with warnings denied pass. Real mixed quantization types beyond F32/F16/BF16/IQ3_S still need native decoding before the full archive can be prepared. +- Vendored the pinned llama.cpp/ggml C dequantizer source and required headers at Strata's upstream ggml commit `3cf03257f219afbe7334045ff7c6a06ac68c627d`, recorded checksums and license, and linked it statically through Cargo for offline preparation. The bounded visitor now handles every quantized kind found in the two actual Qwen headers: 8, 12, 13, 14, 18, 20, 21, 22, 23, and 42, in addition to F32/F16/BF16. A synthetic IQ3_S block matched the independent Rust decoder exactly; Q8_0 and Q2_0 matched known values; one zero block of each actual kind decoded through the visitor. The streamed two-shard test exercises an IQ4_NL RAW fallback. All 60 Rust tests and Clippy with warnings denied passed locally. The static CLI smoke now includes an IQ4_NL shard, with pinned archive SHA-256 `07751adc1f7115258b95613203c935f05cbe28a364f77717e8a1bc64cb79c8fa`. Real model source SHA-256 remains unmeasured. +- On a **provisional real-data sample** from the partially downloaded first Qwen shard, a 28,835,840-byte leading slice of `blk.17.ffn_gate_exps.weight` (IQ3_S, starting at absolute GGUF offset 19,192,385,920) and the 921,600-byte `blk.0.ffn_down_shexp.weight` (IQ4_NL, offset 1,385,570,304) were wrapped as two minimal GGUF shards outside Git. Their GGUF bytes total 29,757,760 and their level-2 KAR-2 archive is 21,485,056 bytes (72.1998% of this sample, 2.500179 accounted bits per weight), SHA-256 `ebacd3cd488274a21bc94630c841d157b5633ce62721bb991c39b78dad8cef23`. The dedicated verifier matched manifest source hashes, derived-F32 identity, provenance, KAR source records, and payload CRCs. The maximum tensor relative L2 error was **0.40491666**, so this level is not approved for serving. The full source shard hash has not yet been checked; this sample is not representative of whole-model size or quality. `scripts/measure-real-sample.py` reproduces this measurement into an output directory outside Git; pass `--index-gguf` only while the source is a partial download, and `--source-sha256` after its full hash is known. The chosen source GGUF offsets are absolute as printed by `model index`; no data-start offset is added. +- Repeated the same sample through `scripts/measure-real-sample.py`: level 2 reproduced the same 21,485,056-byte archive and SHA-256. Level 3 gave a 30,078,464-byte archive (101.0777% of sampled GGUF input), SHA-256 `3e6bc55254ba30bea5ed4f40c970ac9290ad4b1fd160e5c92e71caaaff0328e2`, and maximum tensor relative L2 error **0.18060363**. Both archives passed the dedicated manifest/provenance/payload verifier. These measurements show a sample rate/error tradeoff, not a whole-model compression or agent-quality result; neither rate is enabled for serving. +- `cargo run --locked --release --example compare-iq3-s -- 262144` compared every block in the sampled real IQ3_S slice: **262,144 blocks / 67,108,864 F32 values were bit-identical** between the independent Rust decoder and the pinned ggml C decoder. This is a non-lossy decoder parity check on source bytes from the incomplete first shard; the complete shard still needs manifest SHA-256 verification. +- Built the committed static-CLI Dockerfile on an arm64 Linux container with `RUST_TARGET=aarch64-unknown-linux-musl`. The resulting single `strata-next` ELF is 14 MiB (`file` reports `statically linked`), SHA-256 `3faa76d410f08134cb39bc77009674ffba8e9a3190bfa7af0099028ed5282285`. The `scratch` image ran `--version` successfully and independently verified the real-slice level-2 KAR archive through a read-only bind mount, including manifest source hashes, provenance, source records, and payload CRCs. This validates the Linux/arm64 static control-plane/CLI artifact, not the x86_64 release path or a CUDA-enabled inference runtime. Hosted GitHub Actions still has not run because this checkout has no GitHub repository or remote. +- The same reproducible sampler has an `--profile expert` option using the same 28,835,840-byte IQ3_S slice plus a 28,800,000-byte leading slice of the much larger `blk.0.ffn_down_exps.weight` IQ4_NL tensor (absolute GGUF offset 913,711,104). The two minimal GGUF inputs total 57,636,160 bytes. Level 2 produced a verified 36,973,056-byte KAR-2 archive (64.1491% of sampled input), SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, with maximum tensor relative L2 **0.33925502**. Level 3 produced a verified 51,761,664-byte archive (89.8076%), SHA-256 `1f94757878575541d3a1568e7ba8d9e680ba6afed2c1199ae63d4c342a6203f8`, with maximum tensor relative L2 **0.16425464**. These are rates for selected slices from an incomplete shard, not an estimate with validated uncertainty for the full model, and neither rate is approved for serving. +- The first complete Qwen shard was fetched and matched its manifest SHA-256 `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`. Repeating `scripts/measure-real-sample.py --profile expert --levels 2 --source-sha256 ` on this verified file reproduced the same two slice digests, 36,973,056-byte archive, archive SHA-256 `03a971fc1ff0a50c34a24fb5a29df76116f16fe9dec98ed61c3429a8f322af48`, and maximum relative L2 0.33925502. The second source shard is still downloading. +- Added bounded CPU decode of an arbitrary nested KAR tensor range, reading only the relevant scales and bit-plane words after archive verification. A 96-element synthetic archive test covers ranges crossing group boundaries. On the verified-source level-2 expert sample, `compare-kar-range` independently decoded three one-million-value archive ranges and compared them with pinned ggml source decoding: IQ3_S at starts 0 and 33,000,013 had relative L2 0.32941509 and 0.32867352; IQ4_NL at start 25,000,017 had 0.34136948. The same IQ4_NL range from the level-3 archive had 0.16519821. This checks stored archive reconstruction on selected ranges, not GPU execution or model-level quality. +- Corrected a dispatch error found by comparing the native C bridge with pinned `ggml.h`: GGUF kind 18 is `IQ3_XXS` (98 bytes/block) and kind 22 is `IQ2_S` (82 bytes/block); the initial bridge had these two decoders reversed. Dispatch now uses ggml enum names and `decode_into` rejects any mismatch between the C `sizeof` result and the Rust GGUF block geometry before C reads source bytes. Cargo explicitly watches the bridge C and vendored ggml sources, so a C edit rebuilds the native archive. The streamed builder, provenance schema, and virtual-F32 derivation were bumped to v3 to prevent reuse of v2 archives with potentially incorrect kind-18/22 values. The v3 synthetic streamed archive SHA-256 is `c897a2b5016d5734925269b7dc223c33f944f10bc178a85db4b322cbaf058b5a`; the v3 IQ4_NL fixture archive SHA-256 is `955b626c2c206b272b690b301168d01824563bb88dc9963698035c3acb619ba2`. The old v2 hashes above are historical and cannot pass the current streamed verifier. +- `scan-quant-blocks` decoded the first real block of each of the 13 GGUF kinds in the SHA-256-verified first shard and found only finite F32 values. Its kind-18 IQ3_XXS block F32 SHA-256 was `aaf601ac40a43dc9af448936d6ab439a9837f01d13b835574d94af2eb62a2a1e`; kind-22 IQ2_S was `4c4b80c73da67911a002589646c61aed4fe8e0139b3152cffd0b3e4ac4e540de`. The source-verified expert-slice level-2 archive under v3 is still 36,973,056 bytes with maximum relative L2 0.33925502, but its new archive SHA-256 is `9c8d195c80cb4a04789d8f53847811214d5abc3f8c652185000f0055f435522f`. All 62 Rust tests, Clippy with warnings denied, and the updated static CLI synthetic smoke passed locally. The Linux static image must be rebuilt for this v3 correction. +- Extracted the first verified shard’s 248,320-token/247,587-merge tokenizer to an external directory. The native CLI and pinned upstream `strata_tokenizer.py` agreed on IDs and exact decode/encode roundtrips for 20 real-vocabulary cases spanning Cyrillic, CJK, emoji, combining marks, whitespace, C0 controls, long BPE runs, and control/user-defined special tokens, both with and without special parsing. `scripts/compare-real-tokenizer.py` reproduces this offline check; Python and `regex` are evaluation dependencies only, not serving dependencies. +- The second complete Qwen shard was fetched outside Git and matched its manifest SHA-256 `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`; the first complete shard remains verified at `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`. The total GGUF file size is 83,617,662,656 bytes. These are verified source bytes, not a KAR archive size. +- Streamed KAR policy v4 partitions a tensor whose bit-plane stride would exceed KAR-2's `u32` limit. The real 51,200,245,760-element `per_layer_token_embd.weight` is planned as adjacent 32,000,000,000- and 19,200,245,760-element records with checked GGUF block boundaries and contiguous virtual F32 offsets. The part planner checks physical and derived parent hashes; provenance records parent dimensions and each part's source/F32 hashes and offsets. A small forced split fixture passed end-to-end preparation, independent archive/provenance verification, and CPU reconstruction for both parts. Calibration sampling now seeks to at most 65,536 normalized groups for tensors over 1,048,576 elements; F32 and IQ3_S sparse samples matched the complete-stream sampler exactly in dedicated tests. All 65 Rust tests and Clippy with warnings denied passed locally, and the v4 synthetic static-CLI smoke passed against the macOS binary. The Linux/arm64 v4 static validation is recorded below. +- Both SHA-256-verified source shards supplied a reproducible 57,636,160-byte two-tensor sample: a 28,835,840-byte IQ3_S expert slice plus 28,800,000 bytes from the giant `per_layer_token_embd.weight` IQ4_NL tensor. V4 level 2 produced a verified 36,973,056-byte KAR-2 archive (64.1491% of sampled GGUF size), SHA-256 `b1630baa94d01b52916e2d3fbcf73042542a1d4e2f9108517333497cf677db8d`, with maximum tensor relative L2 error 0.33378769. Level 3 produced 51,761,664 bytes (89.8076%), SHA-256 `91ce9e0c5c804a293f3b03aea8644871ef2981ecb562c5417a3c74afa850caa5`, with maximum tensor relative L2 error 0.16037559. Both archives passed source/provenance/payload verification. These are sampled size and reconstruction errors only; neither is a full-model size, model quality gate, or serving approval. +- The optimized macOS release CLI recreated the same v4 level-2 per-layer sample byte for byte: 36,973,056 bytes, archive SHA-256 `b1630baa94d01b52916e2d3fbcf73042542a1d4e2f9108517333497cf677db8d`, and the same 0.33378769 maximum tensor relative L2 as the debug CLI. The release verifier independently matched source manifests, provenance, source records, and payload CRCs. +- On the verified second-shard `per_layer_token_embd.weight` slice, `compare-kar-range` independently decoded one million archived F32 values starting at 25,000,017 and compared them with pinned ggml IQ4_NL source dequantization. L2 reconstruction had relative L2 0.33396194 and maximum absolute error 0.01647477; L3 had 0.15970538 and 0.00811461. This checks one real range of stored KAR output against source values on CPU, not model-level quality or GPU execution. +- Rebuilt the v4 static CLI in the committed Dockerfile for `aarch64-unknown-linux-musl`. The executable is a 14 MiB statically linked Linux/arm64 ELF, SHA-256 `656fefeb0cf8aa7c2b804a162f264e1d59689beadcdc6eb544dc4fe2fa92fc62`. Its `scratch` image ran `--version` and independently verified the v4 real per-layer L2 sample through a read-only bind mount, including manifest source hashes, provenance, source records, and payload CRCs. This validates the current Linux/arm64 CLI path; Linux/x86_64 and CUDA inference remain untested. + +## 2026-10-03 — complete two-shard KAR-2 size + +- Host: macOS arm64; release CLI at commit `edf0617`; KAR-2 experimental streamed policy v4, group 32, level 2. Both source GGUF shards matched the embedded manifest SHA-256 before conversion and were rehashed by the preparation command. +- Command: `strata-next model prepare-sharded-streamed qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --output /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --levels 2`. +- The complete archive has **55,295,529,472 bytes** (51.49797487 GiB) across 1,225 KAR records; the two GGUF shards have 83,617,662,656 bytes. Archive/source ratio is 0.66129006, saving 28,322,133,184 bytes (33.87099%). Accounted rate is 2.500025 bits per derived F32 weight. Archive SHA-256 is `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; derived F32 SHA-256 is `c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479`. +- The writer's full payload CRC verification passed before atomic publication, and a versioned provenance sidecar was written. The maximum tensor relative L2 error measured during encoding was 0.68008092. This is **not** a model-level quality result or permission to serve with KAR-2. No Linux GPU inference, GPU decode, or paired end-to-end throughput result exists yet. +- A separate `model verify-sharded-streamed /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --manifest qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --levels 2` run exited successfully. It recomputed the derived F32 source identity, checked both manifest shards, all 1,225 KAR source records and payload CRCs, the archive SHA-256, and the v4 provenance policy. The provenance sidecar SHA-256 is `3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5`. Temporary section files, old real-data slices, local header fixtures, and superseded local Docker images were removed; both verified GGUF shards, the final KAR, and its provenance remain outside Git. + +## 2026-10-03 — outer block codec and selective precision probes + +- Read 18 independent 1,536,036-byte KAR expert sections from the verified full archive (gate/up/down records at layers 0, 3, 14, 24, 37, and 45 for experts 0, 127, and 511). On the same 18 blocks, mean compressed/raw ratios were 0.988025 for LZ4 HC (`lz4 -9`, 1.10.0), 0.935372 for Deflate (`zlib` level 9), and 0.915421 for xz (`xz -9e`, XZ Utils 5.8.4). Median xz ratio was 0.914897, with a range of 0.904669–0.930424. One block per codec decompressed byte-identically. These are CPU encoding and size observations only, without a CUDA decoder, PCIe measurement, or end-to-end A/B result. +- A separate sparse scan of 26 aligned 32 MiB windows spaced 2 GiB across the archive gave mean xz ratio 0.895215, median 1.000051, and range 0.418332–1.000051. The large spread shows that a full-archive size cannot be inferred reliably from a few windows; no complete outer-compressed archive was produced. +- The streamed Rust preparer now retains relative L2, source kind, and section bytes per KAR record in its result and prints the worst 20 when creating a new archive. A forced-split fixture checked that all records are represented and their maximum equals the summary maximum. The existing full archive was created before this diagnostic and has no per-record report; reusing it will not fabricate one. All 65 Rust tests, Clippy with warnings denied, and `git diff --check` passed locally. + +## 2026-10-03 — sampled distortion of the existing complete archive + +- Added `model analyze-sharded-kar` and a reusable verified CPU range decoder. The strict mode checks complete source derivation, archive payloads, and provenance. Its first full-model run was stopped after about 13 minutes because repeated derivation of the 707,775,598,080-byte virtual F32 stream made it unnecessarily expensive; it had produced no report or intermediate model files. A separate `--assume-verified` mode uses the earlier independent full verification of the immutable archive and source shards, checks current metadata and provenance mapping, and reads only sample windows. Synthetic compressed and RAW archives gave identical sampled relative L2 in strict and fast modes. The fast mode does **not** rehash source or archive payloads and says so in its output. +- The fast real-model run produced `/Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.sampled-distortion.json` outside Git: 1,225 records, 12,276,608 sampled values, 546,787 JSON bytes, report SHA-256 `1452b55705b9f723747df7dba47fd0484ae8b4140b0022cacceefb16970b5bbf`, bound to the previously verified archive SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. Each record uses up to three nonoverlapping GGUF-block-aligned windows of at most 4,096 values (beginning, middle, end). The median sampled relative L2 is 0.363209; 22 records are at least 0.5 and 207 at least 0.4. The largest sampled value is 0.77458222 in `blk.0.ffn_gate_inp.weight`; 0.74248190 and 0.73494266 occur in the same tensor family at blocks 30 and 14. A window's relative L2 can exceed the earlier full-record maximum of 0.68008092 because it measures a different subset, and it is not a full-record bound or model-quality result. +- The 22 records at or above 0.5 contain 43,008,000 values. Adding one KAR bit plane only to these records would nominally add 5.13 MiB of plane bits before alignment and metadata; a serving loader and GPU path still need to apply this mixed-rate overlay. An external proposal list, `/Users/para/.local/share/strata-next/qwen-iq3-s-l3-candidates.json`, has SHA-256 `6c82c80c8edfb7a8b0e83c8ebd690339843b83a9dce0020967e7146cbcb41120`. It is a diagnostic proposal, not an approved precision policy or proof of improved model quality. The split `per_layer_token_embd.weight` sampled at 0.33714705 and 0.33125633; `token_embd.weight` at 0.33737772 and `output.weight` at 0.37104131. + +## 2026-10-03 — selected L3 overlay and paired tensor comparison + +- `model prepare-kar-overlay` encoded the 22 proposed unsplit records from the original GGUF shards at KAR level 3. Each selected physical GGUF and virtual F32 digest matched the full base provenance during encoding; the KAR writer and an independent pass verified the overlay records and payloads. The overlay is `/Users/para/.local/share/strata-next/qwen-iq3-s-l3-overlay.kar`, **18,827,008 bytes** (17.955 MiB), SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`, with 22 records. The corresponding base archive sections occupy 13,445,632 bytes, so the standalone overlay file exceeds those sections by 5,381,376 bytes, including its own header/directory/alignment. The overlay provenance is 6,039 bytes, SHA-256 `403eeca17d09bd51b3c5f6bae2587c62c483707e346577ab3df6feed2a2a7958`. Private staging sections were removed. +- `model compare-kar-overlay` decoded every value of the same 22 tensors from the base L2 and overlay L3 archives, compared both to pinned GGUF dequantization, and recomputed each selected source tensor's physical and F32 SHA-256. Its external report `/Users/para/.local/share/strata-next/qwen-iq3-s-l2-vs-l3-overlay.json` is 4,226 bytes, SHA-256 `6413b353381749c5d0cc0eb91ed5bf93e6b8a9c36fd7f6db9942fd20a7478e97`. All 22 full-record relative L2 errors decreased. The median across selected records was 0.50734744 at L2 and 0.22607999 at L3; the largest selected-record error decreased from 0.62459845 to 0.28435756. For `blk.0.ffn_gate_inp.weight`, the paired full-record values were 0.62459845 and 0.28435756. This is a numerical weight reconstruction result, **not** a model-quality result or a GPU/PCIe performance result. The large base archive's earlier full verification is assumed by this comparison, while the selected source tensors and small overlay were freshly checked. +- All 67 Rust tests, Clippy with warnings denied, and `git diff --check` passed after the overlay work. A current macOS arm64 release CLI was saved outside Git at `/Users/para/.local/share/strata-next/bin/strata-next-overlay-probe` (13,691,888 bytes, SHA-256 `df2ce4c26dbf000f5935fe79a31a8ef73aea64ee5e48a1f5a5888d3751c94817`). `cargo clean --profile dev` and `cargo clean --profile release` removed their build outputs; the private overlay section staging directory is gone. Verified GGUF shards, the full base KAR, overlay, and reports remain for reproduction. + +## 2026-10-03 — live text SSE preview + +- The restricted `/v1/responses` text path now forwards worker token events through bounded channels as live SSE deltas. It emits `response.created`, `response.in_progress`, output item/content part events, UTF-8-safe text deltas, and a `response.completed` terminal event with continuous sequence numbers. A worker failure emits `response.failed`; dropping the client stream closes its worker receiver so the supervisor sends `STOP` and drains the current generation. +- A synthetic HTTP test received the first text delta before any `DONE` event, then checked the final text and event ordering. A resident mock worker accepted another request after its streaming receiver was dropped. A UTF-8 test checked tokens that split a multi-byte character. All 70 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. This validates the local protocol path only; no real model, Linux GPU, Codex tool call, or end-to-end throughput was tested. +- Follow-up terminal tests checked that worker errors produce `response.failed` and output-token exhaustion produces `response.incomplete` with `incomplete_details.reason=max_output_tokens`, in both the response trace and live SSE path. A length-limited response is no longer misreported as an HTTP gateway failure. All 73 Rust tests and Clippy with warnings denied passed locally. +- A Rust parser now accepts complete Qwen `` output in the buffered Responses path. It preserves literal closing-tag examples inside string parameter values, converts declared non-string JSON values, rejects unfinished/undeclared calls, and validates finished argument objects against the request's local JSON Schema without remote references. Function declarations with duplicate or unsafe names are rejected before generation. A synthetic HTTP test returned a `function_call` with exact string and integer values. All 78 Rust tests and Clippy with warnings denied passed at that step. Streaming tool calls and real-model validation remain open; the tool prompt is an adaptation of the upstream template rather than an established byte-for-byte parity result. +- The route now accepts a text-only `input` array for stateless continuation: earlier `function_call` items with JSON-object arguments must be paired with matching `function_call_output` text before a new generation. The Rust prompt includes the Qwen function and tool-response blocks; mismatched call IDs or incomplete pairs return a request error. A synthetic HTTP continuation reached the mock worker with the tool response intact and returned the next text answer. All 80 Rust tests, Clippy with warnings denied, and `git diff --check` passed. `previous_response_id` storage, multimodal items, reasoning replay, and real-model parity remain unimplemented. +- The representative upstream `tool call and response` golden prompt now matches the Rust tool renderer byte for byte, including the tool schema JSON, function call block, and tool response turn. This checks one pinned case rather than arbitrary tool schemas or real-model behavior. All 81 Rust tests and Clippy with warnings denied passed after the formatting change. + +- The incremental Qwen tool parser now holds split `` markers, including literal closing-tag examples inside parameter values. The live SSE path emits text deltas and a completed, schema-validated function call before worker `DONE`; unfinished and schema-invalid calls end in `response.failed` without publishing arguments. Synthetic worker tests check sequence order and terminal events. This has not been exercised against a real model or Codex client yet. + +- After commit `122c5f0`, `cargo test --locked` passed 85 Rust tests, Clippy with warnings denied passed, and the Linux/arm64 musl CLI cross-build succeeded. The 15 MiB ELF has no `INTERP` or `DYNAMIC` program header and ran `--version` from an arm64 `scratch` container. Its SHA-256 is `13e25f38445ada0b8f99e8a262580484342bdbfd28da39154957aaf29706054b`. This validates the CLI/control plane, not the CUDA worker or compressed-model serving. The superseded local static CLI copy was removed. + +- The HTTP route now stores terminal responses by default in a bounded, process-local cache and can render a `previous_response_id` chain with a new `function_call_output`. A synthetic two-turn worker test checked that the earlier user request, function call, and tool result reach the second Qwen prompt; unknown IDs return 404. This does not establish compatibility with a real Codex session, and the cache does not survive restart. + +- Commit `5a96652` passed 87 Rust tests, Clippy with warnings denied, and `git diff --check`. The updated Linux/arm64 musl CLI ran `--version` in `scratch`, has no `INTERP` or `DYNAMIC` program header, and hashes to `ffff43a30c75f2009a996079e4a8d45698658b3ba8a91a449a2cf87d9645d20c`. It remains a CLI/control-plane artifact without the CUDA engine. The prior local CLI copy was removed after verifying this one. + +- The new `model resolve-kar-overlay` command recomputes full SHA-256 and payload CRCs for the base and overlay archives, validates their shared virtual-F32 source, and maps every tensor name to a base or replacement record. A synthetic fixture rejected a modified overlay provenance digest. The real release-build run on macOS arm64 completed in 407.7 seconds without staging a model copy: base SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`, overlay SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`, 1,225 base records, and 22 selected replacements. The large `per_layer_token_embd.weight` parent correctly resolves through two adjacent KAR records. This validates archive identity and selection only; it does not test GPU residency, CUDA decode, model quality, or inference speed. + +- The CLI from commit `d62c6ce` cross-built for `aarch64-unknown-linux-musl` and ran `--version` in an arm64 `scratch` container. Its ELF has no interpreter or dynamic program header; SHA-256 is `ae22b63d19c11e1de3c5d5279edbdef8042acee89a3fc1192baab25fa41efa7a`. The superseded local static CLI copy was removed. This binary still excludes the CUDA inference engine. +- `cargo check --locked --target aarch64-unknown-linux-musl` passed for the current Rust code. A first release link on macOS chose the host `cc` and failed on ELF flags; setting `CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-musl-gcc` made `cargo build --locked --release --target aarch64-unknown-linux-musl --bin strata-next` pass. The 15,141,536-byte Linux/arm64 ELF is statically linked, has no `INTERP` program header or dynamic section, and returned `strata-next 0.1.0` inside the existing Linux/arm64 `scratch` container. External copy: `/Users/para/.local/share/strata-next/bin/strata-next-linux-arm64-musl-8704ef3`, SHA-256 `78723399f292816e5f894ebf64b11ecf369eb68cef6478e363d71539d2b787ac`. This is a control-plane/CLI artifact, not a CUDA inference runtime or x86_64 release validation. + +## 2026-10-03 — precision overlay for one partitioned PLE record + +- Overlay preparation and paired comparison now resolve a selected PLE partition to its exact GGUF byte range and base KAR virtual source record. A synthetic v5 fixture encoded both an unsplit dense record and one of four PLE parts at level 3, verified the two replacement mappings, and compared both full records against the GGUF values. Altering the part's source byte offset caused comparison to fail. This validates record mapping and reconstruction for small synthetic data; no full v5 archive or model-level quality result exists yet. +- All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The local build directory was cleaned after validation; preserved GGUF shards and v4 KAR artifacts were not changed. + +## 2026-10-03 — one-row CUDA smoke path + +- The isolated CUDA smoke target now accepts `--row ROW_ID` for a compressed record, including a selected PLE part from an overlay. It checks the local row bound, stages the record's compressed prefix, calls `kar_decode_rows` on a CUDA stream, and hashes only the one-row output. This reduces the output allocation for the smoke path; it does not reduce the initial compressed prefix transfer or integrate decoding into Strata's multiply path. +- Local Clang C++20 syntax checking with a temporary CUDA API declaration stub passed. No CUDA toolkit or GPU execution was available on the Mac. A read-only check of the Linux RTX 5090 at this step found 31,867/32,607 MiB VRAM in use by existing processes under driver 595.91.07, so neither the kernel result nor CPU/GPU row parity is claimed yet. +- The Rust `model checksum-kar-row` oracle verifies the complete KAR archive and decodes a bounded row for checksum comparison. On the synthetic 32-value fixture its row-0 values match the existing full-tensor CPU decoder exactly: both CLI paths returned FNV-1a `ff9fd7a827b333a5`; an out-of-range row is rejected. The temporary fixture was removed. All 90 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. + +## 2026-10-03 — verified base plus overlay VRAM accounting + +- `model plan-kar-overlay-memory` verifies complete base and overlay archive SHA-256 values, payload CRCs, provenance, and 22 replacement mappings before calculating selected compressed residency. A synthetic v5 fixture selected six records with two overlay replacements and counted each exactly once. All 90 Rust tests and Clippy with warnings denied passed locally. +- The release CLI ran against the preserved real v4 base and level-3 overlay in 421.0 seconds. Verified archive SHA-256 values were `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5` and `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`. At base level 2, overlay level 3, and a hypothetical 24,576 MiB GPU budget, 1,225 selected records (22 replacements) require **55,300,367,408 bytes** of compressed residency: 55,281,550,704 from selected base records and 18,816,704 from overlay records. That is 5,376,352 bytes more than the earlier base-only compressed plan. The largest full F32 scratch is 128,000,000,000 bytes, and two PLE records exceed the per-record full-decode budget while their one-row output bounds fit. All-selected residency plus one largest scratch is 183,300,367,408 bytes, so a 32 GB card cannot keep all selected records resident. This is verified archive metadata arithmetic, **not** measured GPU allocation, model quality, or inference throughput. +- The external report is `/Users/para/.local/share/strata-next/qwen-iq3-s-selected-overlay-memory.json`, 3,586 bytes, SHA-256 `488a79973f90937429af1483bafe648441cd6e76ceb3a9f9edf9c16c7fcf376c`. The verified source shards, base archive, overlay, and this report remain outside Git. The local release build output was removed after the run. + +## 2026-10-03 — KAR preparation space guard + +- Streamed sharded preparation now checks the output volume before creating private section files. Its conservative lower bound takes the smaller of the mandatory bit-plane bytes and the F32 RAW fallback for each planned part. For the target virtual F32 size of 707,775,598,080 bytes at level 2, the aggregate bit-plane floor alone is 44,235,974,880 bytes before scales, codebooks, alignment, and provenance. The current Mac volume has about 23 GiB free and the occupied Linux host's root volume about 18 GiB free, so neither can hold a second full archive. This guard avoids starting section writes on a clearly undersized volume; source identity calculation still precedes it, and passing the bound does not guarantee a completed archive. +- All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. The v5 partitioned synthetic archive still prepares and verifies under the space guard. + +## 2026-10-03 — fast rejection before existing-shard rehash + +- `model ensure-sharded-streamed` now uses the GGUF directories of already-present, size-matched shards to reject an impossible new archive before `model fetch` rehashes the source. This metadata is not treated as verified input for acceptance: if the lower bound fits, the existing SHA-256 and preparation checks still run. Missing shards retain the normal download path, and reuse of an existing archive does not require a second archive's free space. +- With both real IQ3_S shards present, a v5 level-2 request at `--ple-part-elements 100000000` failed in **0.495 s** from an already-built debug CLI. The directory-derived minimum was 44,235,975,168 bytes; the output volume had 22,671,552,512 bytes available in that run. The command returned `KAR minimum payload does not fit` before source hashing and created no v5 archive. No model bytes or new archive were written. All 91 Rust tests, Clippy with warnings denied, and `git diff --check` passed on macOS arm64. + +## 2026-10-03 — shared-GPU smoke admission + +- The isolated CUDA smoke path now rejects a compressed record whose staged prefix, F32 output, and optional row ID would cross a free-VRAM reserve of `max(512 MiB, total VRAM / 16)`. It checks the selected record's declared level before estimating memory and performs the admission check before CUDA allocations. Allocation can still fail if another process consumes VRAM after the check. +- Local `clang++ -std=c++20 -Wall -Wextra -Werror -fsyntax-only` passed for the smoke source with a temporary CUDA API declaration stub; `git diff --check` passed. No CUDA execution or CPU/GPU checksum comparison was performed because the Linux RTX 5090 remained occupied. The temporary stub was removed. +- The original full-tensor size cap also rejected split PLE records in `--row` mode despite their bounded output. The smoke input check now caps the actual decoded output at 100 million F32 values, allowing a larger compressed record when only one row is requested. The compressed-prefix VRAM admission check still applies. This change has no GPU runtime result yet. + +## 2026-10-03 — resumable transfer retry + +- `model fetch` now makes at most four attempts per shard for transient transport, timeout, short-body, and HTTP 408/429/5xx failures, with 1/2/4-second waits. Each attempt reopens and rehashes its `.part` file before resume; malformed Content-Range, storage errors, and SHA-256 mismatch remain terminal. Local HTTP tests recovered from a 503 while resuming an existing partial file and from a short 200 response by requesting the newly missing range. Both published only the manifest-matching completed file. +- All 93 Rust tests and Clippy with warnings denied passed on macOS arm64. No real model download was repeated for this policy change; hosted CI and Linux GPU inference remain pending. + +## 2026-10-03 — optional private Hub download credential + +- `model fetch` now reads optional `HF_TOKEN` at runtime and attaches a Bearer header only to the exact HTTPS `huggingface.co` host. The token is not placed in manifests, logs, or model artifacts. Manifest URLs and redirects containing userinfo are rejected; reqwest removes sensitive headers when a redirect changes host, port, or scheme. A request-builder test checks that a lookalike domain and local fixture URLs receive no token. No private model was fetched during this validation. +- All 95 Rust tests, Clippy with warnings denied, rustfmt, and `git diff --check` passed on macOS arm64 before the Linux cross-build. The new tests cover exact-host credential scoping and rejection of URL-embedded credentials. + +## 2026-10-03 — private Linux x86_64 preparation host + +- Cross-built the Rust control-plane/CLI at commit `3a96103` for `x86_64-unknown-linux-musl` on macOS arm64 using the pinned Rust 1.99 toolchain and musl cross compiler. The 16 MiB ELF reports static PIE, has no ELF interpreter or `DT_NEEDED` library, and has SHA-256 `d49e02212537b0290717dd7c0818c8ce1b4569712cba4c1bf5acd394285007de`. A private copy at `/home/para/.local/bin/strata-next-x86_64-musl-3a96103` on the Linux RTX 5090 host matched that digest, returned `strata-next 0.1.0`, and passed `doctor` under driver 595.91.07. This validates the CLI and driver check, not GPU inference or a single-file CUDA engine. +- The host's NTFS model volume had both expected-size IQ3_S source shards. An old incomplete Q5_K_XL download and nine unneeded experiment-copy directories containing only Q4_K_XL GGUF duplicates were removed after checking current process use, reclaiming 634,919,717,485 bytes in total. Available space rose from about 91 GiB to 683 GiB. The current Strata process's IQ3_S shards, pack, and MTP files were left intact. Low-priority SHA-256 verification of the remote IQ3_S shards matched the manifest values `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. Only after this check, their 83,617,662,656-byte duplicate copies were removed from the Mac; the v4 KAR archive and overlay remain. The Mac's ten authorized Time Machine local snapshots were then removed, raising reported free space from 17 GiB to 138 GiB. The local cross-build directory was removed after the private Linux copy passed its checks. + +## 2026-10-03 — RTX 5090 KAR CUDA smoke + +- On Linux x86_64, driver 595.91.07 and CUDA toolkit/runtime 13.2, compiled the pinned `libkar.cu` plus the local smoke target for `sm_120`. The current Strata server was idle; one synthetic non-streaming Chat Completions request completed with `finish_reason=stop` and 39 prompt / 4 completion tokens. Its raw response and timings are stored privately at `/mnt/microcrm-flash-preflight/microcrm-flash-next-experiment/strata-next/baseline-smoke-iq3-s.json`. The server used engine commit `30ec18ec7094550fcc594fd948220d511d80464e` with six dirty paths, engine binary SHA-256 `f631b32495440f1dde716734559e757b76f5436c34ca49164cb97bd80b4b18e7`, and config SHA-256 `ac4eebc189350a6392078f168c71cabb45042221e0f7321006922002c1b2a3e0`. This four-token request is a readiness smoke, not a throughput baseline. +- The server's authorized `/unload` returned `unloaded`; GPU memory use fell from 31,867 to 34 MiB while its HTTP process stayed ready for `/load`. On a 32-element KAR fixture, both full and one-row GPU decoding matched the CPU FNV-1a `ff9fd7a827b333a5`. Thirty warm GPU iterations gave medians 0.002816 ms full and 0.003136 ms row, with compressed residency 64 bytes. These are tiny-kernel timings, not a model speed claim. +- The verified 18,827,008-byte real level-3 overlay was copied privately to the NTFS volume and matched its known SHA-256 `4f308e611e189b0fe8dde75287e55c65c4800bf7da8e6a5c2acef96d70c67471`. Full GPU decoding of `blk.34.ssm_beta.weight` at level 3 matched the independent CPU byte checksum `7a8bd0b57620bfea` across 122,880 F32 values; one-row GPU decoding of `blk.0.ffn_gate_inp.weight` matched CPU byte checksum `1a84ea920505914` across 2,560 F32 values. Each used 30 warm iterations; GPU medians were about 0.003168 ms on these small outputs. This checks CPU/CUDA reconstruction for two real records, not an end-to-end model-quality or throughput result. +- A private v5 PLE-partitioned level-2 conversion is running on the verified remote GGUF shards with low CPU/I/O priority. The v4 base archive is being copied privately for the larger PLE row and overlay-selection smoke checks. No v5 size, model quality gate, or compressed-model inference result is claimed before those jobs finish and independent verification passes. + +## 2026-10-03 — warm control arm and complete overlay decoder parity + +- `scripts/bench-chat-paired.py` and a public three-case synthetic suite now record per-case quality and paired wall time when two endpoints exist. The current server initially returned HTTP 400 while its `/health` reported `loaded: true` with `max_context: 0`; the harness now optionally waits for nonzero context before sending requests. After the model became ready, 15/15 timed baseline responses passed arithmetic, retrieval, and function-call checks (five repetitions each). Median HTTP wall time was 0.0959 s overall, 0.0959 s arithmetic, 0.0670 s retrieval, and 0.1613 s function call. The private response report and hardware/config metadata are on the remote NTFS experiment volume. Archive transfer and conversion were concurrently active, and no compressed endpoint exists, so this is a functional warm control arm, not a paired A/B speed result. The standard server was unloaded through its API after the run; VRAM use returned to 34 MiB. +- `scripts/check-kar-cuda-records.py` compared Rust CPU and CUDA reconstruction checksums for all 22 records in the private level-3 precision overlay. The checksum matched for **22/22** real records: full output for records up to one million values and row 0 for larger records. Thirty warm CUDA iterations per record gave isolated median decode times from 0.002496 to 0.003200 ms; recorded compressed residency ranged from 53,792 to 13,762,592 bytes. Transfer/setup time, matrix multiplication, and model-level quality are outside this measurement. The independent paired full-record L2 report for those same 22 records has median relative L2 0.50735 at base level 2 and 0.22608 at overlay level 3; this improvement is numerical, not a passed model-quality gate. The model-free temporary GPU fixture was removed after validation. +- A local release CLI independently verified the complete 55,295,529,472-byte v4 archive and decoded row 0 of `per_layer_token_embd.weight#strata-part-001-of-002` at level 2. Its 160 F32 values have FNV-1a `c6f74b955ce5a5ae`. This is the CPU oracle for a later GPU check after the remote v4 transfer finishes and its SHA-256 is verified. The temporary local Cargo build directory was removed after this run. +- The local CI entry point now checks Python syntax for both new offline measurement scripts and runs a mock HTTP A/B test. That test delays readiness until `max_context` becomes nonzero, requires bearer authentication, checks three case results per arm and paired output equality, and confirms the private report has mode 0600 without the token. It passed locally with Python 3; hosted GitHub Actions still cannot run until a repository is created. + +## 2026-10-03 — selective KAR row transfer prototype + +- Added an isolated CUDA prototype that verifies a KAR archive, gathers only the requested rows' scales and plane words into one compact packet, and decodes that packet on GPU. On RTX 5090 (driver 595.91.07, CUDA 13.2), level-3 `blk.0.ffn_gate_inp.weight` rows 0 and 1 each reconstructed to the same FNV-1a values as the independently verified Rust CPU decoder: `1a84ea920505914` and `b9359351c81dc9fb`. One row used a 1,136-byte H2D packet versus a 573,472-byte complete record prefix; two rows used 2,256 bytes versus the same prefix. The first kernel's one-row test had median H2D event time 0.003008 ms and decode event time 0.007328 ms over 30 warm iterations. A later two-row run measured 0.009110 ms to build the packet from the mapped, already-verified archive; its separate payload verification took 42.405 ms. Storage/cache state affects both host measurements. The existing full-prefix smoke on the same record reported `reserve_ms=0.044608` and warm decode median 0.003200 ms, but its reserve includes allocation/synchronization and the two programs have different setup paths, so these timing numbers are not a paired speedup claim. The first instrumented prototype binary SHA-256 was `c4c987a514b1ceb0a620b178ff99f63c1dd75f4f71abc98a7e01267ae8d83c10`; it was built with the server's CUDA 13.2 `nvcc`. The server lacks CMake, so the new CMake target itself has not run there; the direct `nvcc` build and real CUDA execution passed. +- An isolated copy of the imported Strata engine source was configured and built as the `strata` target on the RTX 5090 host with CUDA 13.2, `sm_120`, GCC 15.2, and CMake 4.4.3. Its pinned llama.cpp dependency resolved to `3cf03257f219afbe7334045ff7c6a06ac68c627d`, and the executable SHA-256 is `22542ee4c80a67f8796bd6f03048da29af704a3df44a75bccce6aad9930f41be`. The CLI started and printed usage for `--version` (that flag is unsupported). This checks reproducible compilation of the fork without touching the active server process; no model was loaded with the new executable yet. The isolated source/build occupies about 791 MiB on ext4 and can be cleaned after candidate validation. +- The selective-row kernel was changed to eight neighboring threads per 32-value coded word with compile-time precision specialization. Its current binary SHA-256 is `d5a0343f042c71cbf1dbcaa749c83af387f08174396b046247bf5b87aa982a93`. On the same two real overlay rows, the byte checksums stayed exact and 30 warm GPU decode events had median 0.003200 ms for two rows, versus 0.009344 ms in the earlier single-thread-per-word prototype. This is a kernel-only before/after under separate executions; packet transfer and host work were measured separately, and neither result says anything about model throughput. + + +## 2026-10-04 — native cancellation failure isolation + +- The Rust supervisor previously waited indefinitely for `DONE` after `STOP`. + It now drains for at most 20 seconds, discards post-cancellation events, + revokes readiness before killing/reaping an uncooperative worker, and releases + queued requests without reusing an unaligned wire stream. +- A real HTTP test on Linux x86_64 exposed a second defect: idle text/tool SSE + relay tasks did not observe a disconnected client until another engine event + arrived. Both relays now observe the downstream channel closing immediately. + The regression covers both idle text and idle function-call streams. +- `cargo test --locked` passed **98 tests**, including cooperative cancellation, + unchanged successful mock-worker token output, and uncooperative STOP. + Rust format, Clippy with warnings denied, Python syntax and diff checks passed. +- The static musl CLI ran `scripts/smoke-worker-cancel.py` on the Linux host: + STOP was delivered after HTTP disconnect; termination took **20.002 seconds**; + the queued request received HTTP 503 `worker_not_ready`; readiness was Failed + with no context; the worker was reaped; `/health` still returned 200. + This uses sanitized mock engine/tokenizer assets, no model or GPU inference. +- Verified ELF has no interpreter or dynamic library dependencies. Size: + **16,963,568 bytes**; SHA-256: + `4caa3ec4bf4657dadfa6d008351f493a70c99fcc32479255d30dc1684a62018d`. + One private CLI artifact is retained; remote uploaded test binary/script and + temporary fixtures were removed. The private verification JSON remains. +- The HTTP regression is added to the static CLI GitHub Actions job. Hosted + Actions has not run because the project still has no GitHub repository. + Automatic restart, real-model replay and soak stability remain open; + no production profile switch or throughput improvement is claimed. + + +## 2026-10-04 — bounded native worker recovery + +- Added an outer supervisor recovery loop after a post-READY crash or protocol + failure. Default lifetime budget: three restarts, with 2/4/8-second backoff; + `engine.max_restarts` / `STRATA_MAX_WORKER_RESTARTS` accepts 0 through 3. + Zero disables recovery. Startup failures stop the loop. Successful requests + do not replenish its budget. No failed generation is automatically replayed. +- Active and queued requests fail; commands received during backoff or startup + are rejected. Readiness has no context in `restarting`/`starting` and returns + only after a fresh positive handshake. Shutdown interrupts backoff. +- All **102 Rust tests**, format, Clippy with warnings denied, Python syntax and + diff checks passed. New failure fixtures cover crash-once recovery, active + and queued request isolation, rejected commands during backoff/startup, + perpetual crash budget exhaustion, startup failure and shutdown preventing + respawn. Existing cooperative cancellation and output fixtures remain green. +- The actual static Linux x86_64 CLI passed both HTTP smoke modes. Recovery + took **2.013 seconds** with a one-restart budget. The failed request and a + request during recovery got 503; a fresh post-READY request got 200 with + expected text `A`. Exactly two process starts and two generations were + observed: the failed generation was not replayed. With recovery disabled, + STOP failure isolation again passed at **20.002 seconds**, with queued 503, + Failed readiness, reaped worker and health 200. +- Static ELF: **16,984,160 bytes**, no INTERP/NEEDED; SHA-256: + `eb90708ccce588e16bfab4af2a1346de1c9033a7bd57664c457c746907dfcf76`. + Both HTTP checks use sanitized fixtures; no real model/GPU load or soak is + claimed. CI definitions now include recovery; hosted Actions has not run. + Production console profiles have not been switched. + +## 2026-10-04 — actual-model native Responses qualification + +- A real IQ3_S generation on the RTX 5090 exposed missing `RESUME`/`REUSED` + handling in the Rust wire parser. Both prefix-count metadata lines now parse + without ending a request; invalid counts and unknown tags still fail closed. +- All 102 Rust tests, format and Clippy with warnings denied passed. The static + Linux CLI then passed text JSON/SSE and typed function-call JSON/SSE on the + actual baseline model. Both streams had contiguous event numbers and exactly + one terminal event. A two-turn tool result continuation also passed. +- Real HTTP disconnect released the same worker for a successful next request. + Killing the owned engine child produced a failed terminal event and rejected + requests while unavailable; a new worker reached READY in 25.4056 seconds, + then answered correctly. This is one reload under warm storage caches. +- Static CLI: 16,983,824 bytes, SHA-256 + `ee1dd490c64efb636025da74868dad1a59662eb2f95409513f7b900b01d534be`; + no ELF interpreter or required shared libraries. Serving directly used Rust + and the C++ engine; Python only drove offline tests. +- See [the complete scope, configuration and results](experiments/2026-10-04-native-responses.md). + This is not a paired speed result, full Codex replay, reasoning/structured + output qualification or soak. Production profiles remain unchanged; hosted + Actions has not run. Temporary test assets and remote CLI were removed. + +## 2026-10-04 — live structured output feature + +- Connected native Responses `text.format=json_object/json_schema` to live + generation, prompt guidance, schema validation, JSON and SSE, and tool-result + continuation. Structured SSE holds generated items until DONE and validation; + schema failures publish only a failed terminal. Token limits return an + explicitly incomplete response whose partial text may not be valid JSON. + This is validated generation, not a token-level grammar decoder. +- All **105 Rust tests**, formatting, Clippy with warnings denied and diff + checks passed. New live-route cases cover JSON/SSE parity, wrong JSON/types, + token limits, tool-only turns, history, schema rejection before admission, + no structured deltas before DONE, and cancellation while buffering. Existing + plain-text and tool streaming tests remain green. These run in the existing + Rust CI job; hosted GitHub Actions has not run. +- Actual private IQ3_S model, baseline engine/config/hardware from the + [native Responses report](experiments/2026-10-04-native-responses.md): **8/8** + feature checks passed on RTX 5090, greedy, reasoning none, one slot/256K, + INT8 K+V resident32K, spec4. JSON and schema JSON produced the expected + objects in both nonstreaming and SSE modes; SSE sequences were contiguous + with one terminal. One-token limits returned incomplete in both modes. + A typed `record_value(7)` tool call followed by its result produced the exact + schema-valid object `{"confirmation_code":"RECORDED-731"}` over SSE. +- Single-request HTTP wall times, recorded only as functional diagnostics: + object JSON 0.4943 s; schema JSON 0.6286 s; limited JSON 0.0424 s; + object SSE 0.3174 s; schema SSE 0.3298 s; limited SSE 0.0378 s; + tool call 0.8696 s; structured continuation 0.2837 s. Requests were sequential + with mixed prefix reuse; these are not an A/B speed comparison or statistics. +- Static musl CLI: **17,046,600 bytes**, SHA-256 + `b1276083b9a71ea74a0cdefd66f968d064a6dc430a177dc2cd9509a25294b6dc`. + Private raw evidence and offline driver: + `/home/para/.cache/strata-next/native-structured-20261004`. + Initial test setup pointed to the extraction parent rather than its tokenizer + child; correcting that private configuration allowed startup. No serving + code workaround or Python serving component was added. +- The isolated runtime, uploaded CLI, extracted tokenizer and temporary config + were removed after checks. Source model shards and production profiles were + unchanged. Native reasoning remains a separate feature; full agent replay + and soak are still required for production qualification. + +## 2026-10-04 — native reasoning feature + +- Added effort selection (`none/low/medium/high/xhigh`, default upstream xhigh), + raw reasoning output items, live `response.reasoning_text.delta` events, + separate final answer/tool items, original-token reasoning usage, and raw + reasoning replay in stored/stateless tool continuation. Closing Qwen markers + split across tokens are handled without leaking them into either text field. + Thinking truncated by the output budget returns incomplete reasoning without + inventing an answer; a normal stop missing the boundary fails explicitly. +- Reasoning deltas stream live; final answer/tool items on this path are + buffered until DONE. Structured answers remain schema-validated. There is no + summarizer: `summary:auto` returns an empty summary plus raw reasoning content; + raw thoughts are never labeled as summaries. Encrypted/summary-only context + replay is unsupported. These limits are documented in `api-contract.md`. +- **110 Rust tests**, formatting, Clippy with warnings denied, and diff checks + passed. New tests cover UTF-8/marker splits at every byte, original special- + token counting, effort validation/template selection, JSON/SSE parity, + structured answers, typed tools, unfinished reasoning, live deltas before + DONE, context replay, and idle cancellation. Existing no-reasoning paths pass. +- **8/8 actual IQ3_S RTX 5090 feature checks passed** on the same baseline + engine/hardware/configuration as the native Responses report. Requests were + greedy, low effort unless marked default, maximum 512 output tokens except + the one-token limit tests. SSE reasoning deltas concatenate exactly to final + reasoning content; event sequences are contiguous with one terminal. + +| Case | Reasoning / total output tokens | First reasoning delta | HTTP wall | Result | +| --- | ---: | ---: | ---: | --- | +| Low text JSON | 23 / 26 | N/A | 0.6743 s | Answer `4` | +| One-token JSON | 1 / 1 | N/A | 0.0382 s | Incomplete reasoning | +| Low text SSE | 23 / 26 | 0.0379 s | 0.2239 s | Answer `4` | +| One-token SSE | 1 / 1 | 0.0337 s | 0.0342 s | Incomplete reasoning | +| Reasoning + schema SSE | 26 / 33 | 0.3309 s | 0.6854 s | `{"answer":4}` | +| Default effort SSE | 35 / 38 | 0.4384 s | 0.7320 s | Answer `4` | +| Reasoning + tool JSON | 26 / 53 | N/A | 1.4660 s | Typed `record_value(7)` | +| Tool result continuation SSE | 27 / 36 | 0.1575 s | 0.4135 s | `RECORDED-731` | + +These are single sequential functional checks with mixed prefix reuse, not a +paired throughput result or full model-quality evaluation. Private evidence: +`/home/para/.cache/strata-next/native-reasoning-20261004` (includes the driver, +raw responses/events, token usage and logs). Model files were not rehashed. +Static CLI: **17,083,088 bytes**, SHA-256 +`949696b3e915cc662f6622cb284eab46fd8d372bc82233276a0d04a1bb82eb3b`. +The isolated worker and temporary uploaded CLI/tokenizer/config were removed +after measurement; the latest CLI is retained privately on the laptop. +Production profiles remain unchanged. Full console-harness replay and sustained +soak still remain; hosted Actions has not run. + +## Native console compatibility, 2026-10-04 + +- An isolated local capture of the installed Codex CLI confirmed its actual + request fields, function namespaces and optional encrypted-reasoning include. + Capture/configs remain private outside Git. The native route now accepts that + envelope and preserves namespace identities through prompt, output and replay. +- Added optional configured model identity and direct `strata-native` discovery + in the installed qwen launcher. The installer is reproducible in + `scripts/install-qwen-native.py`; it preserves the selected connection and + existing MCP configuration. Native traffic bypasses `responses_bridge.py`. +- A real IQ3_S RTX 5090 console smoke run wrote `answer.txt`, read it through the + console shell tool and completed successfully: 370 output tokens, including + 190 reasoning tokens, across two native requests. The file contains exactly + two bytes, `42`. The console reported 45,944 cumulative input tokens and + 23,045 reused tokens. This is a functional check, not a speed comparison. +- The first full Three.js/MCP qualification attempt exposed an unsupported + array-valued tool result after a successful MCP project search. The runtime + rejected it with `tool output needs text`. Added text-part array replay and + a regression, retaining the failed attempt privately. A fresh agent run is + required after the fix; the failure is not counted as a successful benchmark. +- The next attempt reached native approval review, which failed because the + pinned prompt renderer required developer messages to be at the beginning. + The adapter now stably coalesces instruction messages at the front without + dropping their content or demoting their role. Approval remains enabled. + The incomplete attempt is retained; it produced no game and is not a pass. +- 113 Rust tests, format, and Clippy with warnings denied pass. New regressions + cover the captured envelope shape, namespace collision rejection, live + namespaced item identity, tool text-part replay, and late approval + instructions. A fresh install into a temporary launcher copy matches the + installed integration byte-for-byte; a second install is idempotent. +- The fresh console run after those fixes had no transport/protocol errors and + produced a game that passed 23/23 independent browser checks (all eight win + lines, locked terminal boards, restart, draw, occupied-cell handling, mobile + clicking/layout, and no page errors). However, the agent stopped while + preparing its own browser verification; its MCP task TEST-9 remained + incomplete. Exit code zero and `turn.completed` are not sufficient evidence + of task completion. No assistance or continuation prompt was supplied. +- That incomplete run took 452.02 s. The console reported 21,622 output tokens, + including 9,225 reasoning tokens. The engine recorded 24 requests including + approval reviews, 23,180 generated tokens and weighted decode 102.26 tok/s + (per-request median 103.75; p10–p90 70.0–129.75). These are diagnostic numbers + from an incomplete task, not a paired throughput improvement. +- Further prompt inspection found that commentary and a subsequent tool call + from the same response were replayed as separate assistant turns. They now + remain one turn, with reasoning retained and the pinned Qwen template's exact + spacing. A sanitized golden fixture was generated using the pinned local + template with Jinja2 3.1.6; native rendering matches it byte-for-byte. A fresh + independent run is needed to qualify this revision. +- Follow-up protocol checks preserve parallel result identity even when result + delivery order differs: both histories render identically in call order. + Response metadata now reports the actual greedy default temperature (`0`), + confirmed in the running fork's source (`req_temperature = 0.0f`). This does + not change sampling. The earlier console diagnostics used that greedy default. + All 116 Rust tests, format and Clippy with warnings denied pass after these + two checks. The full console run on the preceding revision is kept separate + from the follow-up protocol fixture results. +- The subsequent unassisted console run on a3770ed completed TEST-10 and its + game: 43:07 wall time, 68 main model responses, 68,403 output tokens and + 116.91 weighted decode tok/s. Agent tests passed 132/132; independent browser + checks passed 23/23. One undeclared tool name was safely rejected and retried + by the harness. These are single-run functional statistics, not a speedup. +- The deployed 93e2a9b follow-up passed ordered/reversed parallel tool result + replay on the real model with identical correct greedy output (tolerance 0) + and completed terminal states. Native launcher status and HTTP readiness + pass. The text console profile is available for a user trial; broader scope + and unverified limits are recorded in + [the full report](experiments/2026-10-04-native-console.md). + +## Native service-unit primitive — 2026-10-04 + +- STRA-15 adds `service-unit` rendering and explicit `serve --config FILE`. + This is an installable user-service primitive; managed console start/stop is + still pending. It neither migrates nor restarts the current trial endpoint. +- All 119 Rust tests passed after adding the module/config flag; the three + focused service tests and Clippy with warnings denied passed again after the + systemd path fixes. Formatting passed. Linux musl release compiled. +- Actual systemd 259 on rnr5090 passed `systemd-analyze --user verify` and the + isolated CPU-only lifecycle smoke. It checked literal spaces/percent/dollar + in the binary path, quote/backslash config and working-directory paths, + explicit config precedence over an intentionally invalid STRATA_CONFIG, + EnvironmentFile model override, HTTP health 200, readiness 503 without a + worker, exact process executable/cwd and disappearance on stop. +- The first real parser check caught that WorkingDirectory/EnvironmentFile are + raw path directives, unlike ExecStart arguments. The second caught systemd's + own executable-name rejection of quotes/backslashes. Rendering now handles + each directive separately and rejects unsupported executable/environment-file + paths explicitly. These rules were checked against the installed manual and + [systemd v259's parser](https://github.com/systemd/systemd/blob/v259/src/core/load-fragment.c). +- The temporary unit, configuration, smoke script and remote executable were + removed; no matching smoke user units remain. Local release cleanup removed + 93.8 MiB. A separate private service-preview binary was retained: 17,149,088 + bytes, SHA-256 + `a4c2430803ef7fa19692f6a3a104e59e8eb3b430743c356ac8b19c2fef5aed9c`. +- The active GPU supervisor remained PID 4031422, start ticks 558428413 before + and after, and still reported ready. No inference or model-loading request + was sent to it. The new binary was not deployed over the trial binary. +- Unit syntax smoke is wired into Linux CI; hosted Actions remain unexecuted. + GPU shutdown under a systemd-managed service and login/boot persistence have + not been qualified by this CPU-only smoke. Instructions are in + [deployment](../deploy/README.md#native-linux-service-lifecycle). + +## Console service control — 2026-10-04 + +- STRA-16 adds explicit `qwen-codex-ctl native-service start/stop/status/logs` + for a named systemd user unit over SSH. It does not select a model, provision + a unit, create a tunnel, or infer model readiness from process state. +- Seven focused Python checks passed: idempotent operations, selector rejection + before SSH, missing/invalid status, bounded unit-specific logs, installer + backup/idempotence/profile preservation and refusal to overwrite an unrelated + helper. The test is included in `scripts/check-local.sh` for future Linux CI. +- The installed real controller completed status/start/start/status/logs/stop/ + stop/status against `strata-next-controller-smoke-20261004.service` on + rnr5090. This isolated CPU-only native service reported the expected model + identity via HTTP and correctly remained unready without an engine. The + second start and second stop reported `changed: false`. The normal default + `strata-next.service` was absent and was not created by a status call. +- The laptop integration is installed with a private backup; the normal + connection remains unchanged. This is client-side Python only; inference + still runs directly through Rust and the existing engine. +- Real GPU service migration, managed GPU stop during active generation and + login/boot persistence remain unqualified. The external trial endpoint is + preserved; these commands do not adopt it. Raw smoke results are private in + `~/.cache/strata-next/native-console-20261004/controller-service-quality.json`. + +## Optional native API auth — 2026-10-04 + +- STRA-17 adds private file-backed bearer authentication. All routes except + `/health` are protected when configured; auth-off remains compatible. Invalid + key files fail before bind/worker startup. Stored credential state is a hash; + fixed-size comparison uses the already locked `subtle` 2.6.1 dependency. +- **122 Rust tests**, formatting and Clippy with warnings denied passed; the + static musl release built. CPU-only real HTTP smoke on rnr5090 passed missing, + wrong and duplicate-header rejection before JSON parsing; correct-key status, + public health, protected readiness, malformed/oversized/insecure/missing key + files, nonblocking FIFO rejection, absence of token echo and auth-off behavior. +- Native launcher upgrade, fresh installation from the prior clean launcher, + repeated installation and coexistence with `native-service` passed. The + installed launcher's exec was intercepted without launching an agent: the + auth command read exactly the private test token while neither argv nor + environment contained it. Insecure key permissions were rejected. The native + unauthenticated trial still passes discovery. Seven service-controller tests + also remain green. This is not a full authenticated model/agent qualification. +- Tests caught and fixed an installer-only indentation error on the fresh path; + existing-install upgrade was unaffected. Temporary credentials and copied + launchers were removed automatically. The remote CPU smoke executable/script + were removed; local release cleanup freed 93.8 MiB. The superseded service-only + preview was removed after retaining the combined feature preview (17,206,032 + bytes, SHA-256 + `1f069d66e4546077e3d2494fc725cde994166769d98e506f2c73ab55d1eea121`). +- The GPU trial remains on its prior qualified binary, PID 4031422/start ticks + 558428413, still ready. It was not restarted or sent inference requests. + Hosted CI and independent security review remain pending. This feature does + not add TLS, multi-user isolation or hot key rotation; loopback plus SSH + remains the console transport boundary. + +## Native generation metrics — 2026-10-04 + +- STRA-18 adds a separate authenticated JSON `/metrics` endpoint. It reports + admitted generation activity, bounded channel occupancy, completion/cancellation/ + failure counters, last DONE telemetry and weighted DONE decode rate. `/status` + stays unchanged for console discovery. No prompts, generated text or token IDs + are captured; metrics update only at generation boundaries. +- **124 Rust library tests** passed, along with formatting, Clippy all-targets + with warnings denied and a static Linux musl release build. Existing mock + worker checks now assert active state, cancellation and subsequent generation, + ERR without restart, context rejection exclusion, shutdown interruption and + counters surviving crash/restart. Token events and terminal ordering remain + identical to the fixtures (tolerance zero); no model parameters changed. +- A real HTTP CPU fixture verifies JSON schema, queue occupancy and stable + discovery. Rate tests cover zero duration, overflow and disconnected DONE. + The existing Linux auth smoke now checks protected and authenticated metrics, + initial null/zero values, and auth-off access. This extended smoke passed on + rnr5090 using a temporary process with no engine/GPU and is already included + by the existing CI smoke step. Hosted GitHub Actions have not run. +- Retained combined feature preview: 17,228,336 bytes, SHA-256 + `389d7784c065f978a8b1d0a064b4f3b619e03c6a65895c64b89d278c383df798`. + It supersedes the previous feature preview only. The GPU trial binary and + SSH tunnel remain untouched; PID 4031422/start ticks 558428413 were confirmed. + The trial does not expose the new metrics until a deliberate future upgrade. +- Remote smoke files were removed, ephemeral test keys/configs were cleaned by + the smoke harness, and release cleanup freed 93.8 MiB. The reusable debug build + and private final preview remain. Independent QA and real-model telemetry + qualification are pending; this change claims no speedup or soak stability. + +## Custom text tool transport — 2026-10-04 + +- STRA-19 implements custom text declarations, namespace restoration, native + custom call/input SSE events and typed call/output replay. Qwen uses its + existing one-string function parameter internally. Grammar formats and + unsupported custom fields fail explicitly; no grammar constraint is claimed. +- **127 Rust library tests** passed, formatting and all-target Clippy with + warnings denied passed, and the static Linux musl release built. New coverage + verifies exact multiline/Unicode/whitespace input, namespace and call identity, + public event fields, invalid envelopes, mismatched output kinds and mixed + parallel output ordering. Existing stored continuation and reasoning tests now + exercise both function and custom calls. An incremental test observes custom + input before engine DONE and verifies one matching terminal response. +- `scripts/smoke-custom-tools.py` passed on rnr5090 with the static binary and + a synthetic CPU shell engine: JSON and SSE, reasoning none/low, exact input, + stored continuation and grammar rejection before admission. The smoke is + added to the Linux workflow; hosted GitHub Actions have not run. These are + protocol checks, not model quality or performance measurements. Existing + function/template regressions passed with exact fixture equality. +- Retained combined preview: 17,244,760 bytes, SHA-256 + `b10a7ce9ec8cc85fa99305ba90a9f2b547c22ab0edc407c719355594c5c0c63d`. + The superseded preview was replaced. Temporary remote smoke files and local + smoke bytecode were removed; release cleanup freed 93.8 MiB. Final preview + remains private, with reusable debug build retained. +- User trial is still the earlier qualified binary, PID 4031422/start ticks + 558428413, with readiness and tunnel intact. No GPU inference or agent task + was started, assisted or interrupted. Custom-tool real-model qualification, + grammar support and independent QA remain pending. + +## Native admission drain — 2026-10-04 + +- STRA-20 adds `/admin/drain`, `/admin/resume` and `/admin/lifecycle`, protected + by the existing optional auth gate. New Responses admissions receive 503 + during drain and readiness is withdrawn; already admitted JSON/SSE requests + continue. No worker stop, reload or model switch is performed by these APIs. +- RAII guards track request/body lifetime separately from generation-command + lifetime. The command guard remains held through STOP drain or failed-worker + cleanup, avoiding a false drained result when an HTTP client disconnects. + Frame and trailer forwarding is unchanged. Direct `http-body` dependency + uses the already locked 1.1.0; no dependency version changed. +- **130 Rust library tests**, formatting, all-target Clippy with warnings denied + and static musl build passed. New checks cover admission before JSON parsing, + idempotence, body/trailer equality, distinct request/command lifetimes, + worker-state gating and a cancelled worker held until its STOP terminal line. + Existing function/custom/reasoning and worker recovery fixtures remain green. +- On rnr5090, `scripts/smoke-native-drain.py` passed with a synthetic CPU engine: + one active SSE and one queued JSON response completed with the exact expected + text and terminal event after drain. New admissions were rejected, readiness + stayed false, drained became true only after completion, and resume accepted + a fresh request. Extended auth smoke passed unauthorized admin rejection and + authorized drain/resume. The new drain smoke is wired into Linux CI; hosted + Actions have not run. These checks do not qualify full-model maintenance. +- Retained combined private preview: 17,304,272 bytes, SHA-256 + `e1e7aa29aec1f7d1aeb157920e76ae3daccff957852adee46cc36e599a7c71a2`. + Previous preview was superseded. Remote temporary files and generated smoke + bytecode were removed; release cleanup freed 93.8 MiB. +- GPU trial remains unchanged and ready at PID 4031422/start ticks 558428413, + with its existing SSH tunnel. No inference request or admin mutation was sent + to that trial. Independent QA, GPU maintenance and soak qualification remain. + Drain has no forced timeout or persistence across control-plane restarts; + exact operator semantics are documented in `deploy/README.md`. + +## Native API console control — 2026-10-04 + +- STRA-21 adds `qwen-codex-ctl native-api` commands for status, metrics, + lifecycle, drain and resume, including optional drain waiting. The installer + backs up the launcher and preserves its selected connection. Explicit URL + overrides require explicit authentication and never inherit another target's + key. API identity is checked before admission mutations. There is no automatic + service stop, resume, model switch or tunnel management. +- Eight new Python behavior tests passed: invalid target rejection before I/O, + native identity before mutation, drain completion/timeout/concurrent resume, + response validation, auth selection, direct HTTP without proxy/redirect, + bounded responses and suppression of literal or escaped credential echoes, + installer idempotence and coexistence with native-service in both orders. + All seven existing native-service tests and the installed launcher auth test + passed. `check-local.sh` includes the new tests for future Linux CI; hosted + GitHub Actions have not run. +- Built the current macOS debug control plane and tested the actual installed + controller against an isolated authenticated CPU-only endpoint: all five + commands, repeated drain/resume, drain wait, selected-profile authentication, + explicit key override, and unauthorized mutation rejection passed. Temporary + server, key, config, profile and logs were removed. The normal user connection + was compared before/after and remained byte-identical. This checks console + integration, not model quality or GPU maintenance. +- Read-only `native-api status` succeeded through the preserved GPU tunnel. + PID 4031422/start ticks 558428413 remained unchanged. No inference or admin + mutation was sent to the user trial. Its older runtime still lacks metrics + and admin routes; the client reports unsupported HTTP responses explicitly. + Linux feature-preview binary remains unchanged from STRA-20. Independent QA + and a deliberate future managed GPU deployment remain pending. + +## Embedded native engine package — 2026-10-04 + +- STRA-22 adds an opt-in Linux engine payload to the Rust executable. Build-time + SHA-256, declared source revision and target ELF header checks precede byte + embedding. Default builds remain payload-free. `engine-info` exposes payload + identity, and `--engine-license` retains the imported MIT notice. Serving uses + the payload only with explicit `engine.executable: "@embedded"`. +- Linux execution uses an executable, sealed memfd retained until supervisor + shutdown, including worker restarts; external engine configuration is unchanged. + No executable is extracted to a persistent path. No weights, CUDA libraries + or NVIDIA driver are bundled. The upstream provenance record is unchanged. +- **132 macOS Rust library tests**, formatting and all-target Clippy passed. + Tests cover payload digest/architecture/revision rejection and explicit + selection. The Linux-specific unit test additionally covers shrink/grow/write + seals and descriptor cleanup; its hosted CI execution remains pending. +- Static Linux build with a synthetic CPU ELF passed on rnr5090: embedded digest + equals the source byte for byte; seals prevent writes; worker READY and HTTP + generation return the expected `A`; forced worker crash restarts from the same + payload; output equals the external-file baseline exactly (zero tolerance); + graceful termination removes both worker PIDs and the parent memfd path. + Smoke code handles transient `/proc` socket descriptors and ETXTBSY for a + running executable. This is a packaging/protocol test, not model quality or + performance evidence. The smoke is wired into Linux CI; Actions have not run. +- A private combined preview also embeds the existing qualified engine binary: + engine size 45,680,928 bytes, SHA-256 + `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. + Declared source revision follows its retained `engine-fork-f80a3e0` build + directory: `f80a3e007354a6137c409b760dc70f8f80a3af2c`; no reproducible engine + rebuild was performed in this step. Its byte identity is verified directly. + Combined executable: 63,007,200 bytes, SHA-256 + `ec21fb36fc0ed665fab063877a575b8376d7e8fd9aacbd43889851ac46fd3f5d`, + retained privately as `strata-next-linux-x86_64-musl-embedded-preview`. + `engine-info` and license output ran on Linux without loading the GPU engine. + Outer ELF has no INTERP/NEEDED entries. The embedded ELF still requires + libcudart.so.13, libcublas.so.13, libstdc++, libgcc, libc and libm; its existing + CUDA library RUNPATH is host-specific. This is not a fully static GPU package + or clean-node deployment qualification. +- The active user trial remained PID 4031422/start ticks 558428413. No inference, + admission mutation, GPU load or tunnel restart was performed. Independent QA, + clean-node library packaging and real-model embedded startup remain pending. +- The default CLI was also checked to reject `@embedded` before opening its + listener when no payload is present. Temporary remote smokes and local input + copies were removed; release cleanup freed 108.0 MiB. The private final + package and the reusable debug build remain. + +## Static CUDA toolkit engine profile — 2026-10-04 + +- STRA-23 adds `STRATA_CUDA_STATIC`, default OFF, requiring Linux/GNU/CUDA. + CMake selects static runtime/cuBLAS targets, including the explicit KAR and + parity runtime links; the `strata` executable links GNU C++/GCC runtimes + statically and omits build-host RPATH. No engine arithmetic source changed. +- A full isolated SM 120 Release build passed on rnr5090 with GCC 15, + CUDA 13.2.86 and portable GGML AVX2 configuration. Compilation ran at nice 10 + with two jobs. Only `--help` was executed, with empty CUDA_VISIBLE_DEVICES and + LD_LIBRARY_PATH removed; no model or GPU context was initialized by the test. +- ELF audit passed: DT_NEEDED contains only libm.so.6, libc.so.6 and + ld-linux-x86-64.so.2; no RPATH/RUNPATH, libcudart, cuBLAS, libstdc++ or libgcc_s + shared dependency remains. Minimum versioned glibc requirement is **2.43**. + Runtime `dlopen` dependencies and model behavior remain unqualified. +- Engine artifact: **593,942,184 bytes**, SHA-256 + `389b518c3c8afaccd20bab78f538e008ff996d11dacb08abe73e315a853c6b11`. + Retained privately on the Linux host as `strata-cuda-static-preview`. + This exceeds the existing embedded payload cap of 128 MiB; the 63 MB combined + preview from STRA-22 remains unchanged. This candidate is not fully static or + qualified for older glibc distributions. +- Five default Linux CPU tests passed: conversation cache, conversation memory, + cache retention, coupled draft and BF16 conversion. A real-ELF fixture gate + passed accepted libc-only linkage, rejection of a toolkit RUNPATH and rejection + of a fake libcudart DT_NEEDED dependency. Invalid CUDA-off/static-on configuration + failed before CUDA setup. Default CUDA configuration still selects shared + libcudart/cuBLAS. Local macOS CMake was unavailable; these checks ran on Linux. +- The ELF fixture is in local/CI checks, and an opt-in private-runner dispatch + builds/audits the static profile without publishing it. Hosted Actions have not + run. Numerical/model parity, clean-node qualification and performance evidence + are pending; no serving default or active user endpoint was changed. +- The preserved trial still reported ready at PID 4031422/start ticks 558428413; + its SSH tunnel was unchanged. The 1.3 GiB isolated source/build directory was + removed after retaining the private candidate, link command, CMake cache and + build/test logs. No original toolkit archives, baseline binaries or model + files were removed. +# Static CLI OCI acceptance (STRA-66) + +`deploy/Dockerfile.static-cli` builds the Rust CLI/control plane into `scratch`. +Its build context includes the upstream license used by `--engine-license`; +the other engine files remain excluded. Build and verify it with: + +```sh +docker build -f deploy/Dockerfile.static-cli -t strata-cli-check . +python3 scripts/smoke-cli-container.py strata-cli-check +docker image rm strata-cli-check +``` + +On an arm64 Linux Docker host, pass +`--build-arg RUST_TARGET=aarch64-unknown-linux-musl` to the build. The hosted +`linux-cli-container` job builds the actual x86_64 image and checks the exact +upstream license, CLI version, missing embedded engine/model, HTTP health, +not-ready response, and graceful shutdown in an isolated non-root read-only +container. CLI prereleases require this check as well as the static binary job. +This is a CLI-only image: full CUDA OCI deployment, model startup and GPU +readiness remain separate acceptance gates. No image is pushed to a registry. + +## Isolated hosted CUDA packaging (STRA-69) + +`workflow_dispatch` input `hosted_cuda_package=true` selects a private-repository +Ubuntu 24.04 CPU job. It never targets the private GPU runner. The existing +`static_cuda_package` and `keyless_gpu` inputs remain false unless explicitly +selected. This build does not load a model or install a driver. + +The build-only `scripts/bootstrap-cuda-toolkit.py` assembles seven components +from NVIDIA's [CUDA 13.0.1 redistrib manifest](https://developer.download.nvidia.com/compute/cuda/redist/redistrib_13.0.1.json), +using its committed manifest/component SHA256 and size pins in +`deploy/cuda-toolkit.lock.json`. Download size is 872,943,748 bytes. A fresh private +prefix, bounded downloads/expansion, safe tar extraction, collision/link checks +and retained component licenses avoid a system CUDA installation. This is a +build dependency bootstrap, not an end-user runtime installer. NVIDIA documents +[component assembly and supported host compilers](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-installation-guide-linux/index.html). +The job explicitly uses GCC 13, one engine compile job, two Rust build jobs and a +150-minute job limit; it refuses acquisition below 6 GiB RAM or 12 GiB free disk. +Actual host/compiler versions and initial resources are recorded. Toolkit bytes +are pinned; hosted OS/compiler patch updates mean byte-identical rebuilds are +not asserted. + +Nonempty Linux engine payloads use a target-assembler `.incbin` in a read-only +ELF section after the existing bounded SHA/ELF verification. Rust references +that immutable section through an exact-length external static; it does not +parse a 600+ MB engine as a Rust byte-array constant. Empty/nonembedded builds +remain unchanged. The hosted packaging step records memory/disk counters and +`time -v` resource usage. Two initial hosted attempts received runner shutdown +signals during the previous Rust embedding path; those logs do not establish +an OOM diagnosis. Exact memfd bytes, seals, restart and external-worker output +equality remain mandatory checks for this build-path change. + +Existing static-engine, combined-package and OCI builders supply the actual +compile/link, dependency/ABI, embedded identity and GPU-hidden help gates. +The private `strata-next-hosted-cuda-preview` artifact retains package checksums, +source provenance, image archive/receipt, exact toolkit manifest/toolchain data +and component license archive. Retention is seven days. Successful upload is +required; an ephemeral hosted runner is not durable fallback storage if upload +fails. Owned build directories and image are cleaned. Tests use deliberately +invalid archives/receipts and do not require CUDA; only a successful manual +actual-CUDA job qualifies compilation and packaging. GPU driver loading, +full-model/MTP inference, quality and clean-node rollback remain separate gates. + +```sh +gh workflow run linux.yml --ref COMMITTED_REF -f hosted_cuda_package=true +``` + +## Native per-user installation (STRA-72) + +On Linux with a running systemd user manager: + +```sh +/opt/strata-next service-install --config /srv/strata/config.json \ + --working-dir /srv/strata --env-file /srv/strata/runtime.env \ + --unit strata-next-preview.service --start +``` + +`--env-file` and `--start` are optional. The command reuses `service-unit`'s +literal-path renderer and installs a private regular file under +`$XDG_CONFIG_HOME/systemd/user` (default `$HOME/.config/systemd/user`). It +atomically publishes without replacing an existing file. An identical owned +private file is reused; differing content, symlinks and special files fail. +Use a new unit name for a different deployment. Config, binary, working directory +and optional environment file must already exist at absolute paths; keep them +at stable locations. Configuration/model validation still occurs in `serve`. + +Before start, it checks that the manager resolves this unit file without existing +drop-ins; a different XDG search path or overriding runtime unit fails closed. +The command runs user `daemon-reload`, then optional `start`, each with a +30-second client deadline. It never uses sudo, enables login startup or configures +lingering. Failure retains the installed unit for explicit retry. A timed-out +systemctl client is killed/reaped, but a job already accepted by the manager may +still be pending: inspect `systemctl --user status UNIT` before retrying. +Successful start is process activation, not model readiness; use `wait-ready` below. +The JSON `enable_requested: false` records that this command did not enable the +unit; it does not query or undo an existing enablement. + +The existing `smoke-service-unit.py --lifecycle` now exercises native installation, +exact reuse, conflict preservation and actual user-manager start/health/stop on +an isolated hosted Linux runner, with a control-only service. Offline manager +failure/retry and symlink checks also run. This does not qualify GPU/model loading, +boot persistence, runtime upgrades or automatic rollback of a live GPU service. + +## Native readiness waiter (STRA-78) + +After activation, or through an existing SSH loopback tunnel: + +```sh +/opt/strata-next wait-ready --url http://127.0.0.1:18082 \ + --model strata-native-iq3-s --key-file /srv/strata/api.key --timeout-s 300 +``` + +Only `GET /status` is sent. Success emits JSON with `ready`, `service`, `model` +and `attempts`; it requires the exact model ID, `service: strata-control`, +`worker: ready` and `ready: true`. This is a readiness snapshot, not an inference +or quality probe, and availability may change immediately afterward. + +The timeout defaults to 300 seconds (range 1..3600) and bounds the entire network +wait, including slow headers, body chunks and retry delays. Parameter/key-file +validation precedes that budget. Each HTTP attempt is also capped at 3 seconds; +network failures, HTTP 429/5xx and loading/unready states retry every 250 ms. +Authentication failures, redirects, wrong identity and malformed or oversized +responses fail immediately. The body limit is 64 KiB. Errors do not print peer +bodies, credentials or transport URLs. + +The URL must be an HTTP origin with a literal loopback IP, no credentials, +non-root path, query or fragment. IPv4 and IPv6 loopback are supported; remote +servers require an existing SSH tunnel. Environment proxies and redirects are +disabled. Optional `--key-file` uses the same bounded regular-file/private-mode +and token-format checks as server authentication; omit it for an unkeyed service. +No model, engine or config is loaded by this command, and no service/tunnel is +created, restarted or modified. It does not upgrade the installed Python switch +controller or alter its existing readiness logic. + +The hosted CPU HTTP gate checks exact identity, loading/retry, auth, redirect +refusal, proxy bypass, oversized/chunked responses, slow header/body deadlines, +private key validation and an actual native service's worker-ready/worker-exit +states. No generation command is sent; real GPU/model qualification remains open. diff --git a/docs/compressed-runtime.md b/docs/compressed-runtime.md new file mode 100644 index 00000000..5c027abc --- /dev/null +++ b/docs/compressed-runtime.md @@ -0,0 +1,169 @@ +# Compressed model runtime contract + +## Experimental model quality arm + +The imported Strata engine has an optional Linux CUDA build flag, +`STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, with `STRATA_NEXT_KAR_DIR` pointing at +`gpu/kar`. It adds `--ple-kar ARCHIVE --ple-kar-level 2` to `strata generate`. +With those flags, the PLE lookup table is decoded from KAR on the CPU, while +the native pack and GGUF shards still supply every other weight. The archive +is checked by `libkar` including all payload CRCs, and its PLE parts must have +the expected F32 geometry and complete row count. Check the known archive +SHA-256 and sidecar for a validated run. A supervised smoke run may skip the +separate full-file SHA pass while recording that it was skipped; the engine +still checks payload CRCs. The feature is off in ordinary builds. +`strata_next_kar_ple_probe ARCHIVE 2 ROW...` prints FNV-1a checksums for +comparison with `strata-next model checksum-kar-row` on the matching part. + +This arm measures whether PLE transcoding changes whole-model output and task +quality. It does not load the full compressed model, stage sparse PLE packets +to CUDA, or establish a model throughput gain. Use the same engine source, +model pack, sampling, workload, and server wrapper for control and candidate; +load the arms sequentially on a 32 GB GPU. The private +`scripts/compare-chat-reports.py` pairs two single-arm benchmark reports by +case and repetition and records quality and HTTP wall-time ratios. The times +remain descriptive until run order, disk/cache state, and interference are +controlled. +When Strata reports its `timings`, the comparison also records paired prompt +and decode token rates by case and category; those rates must be interpreted +with their token counts and cache state. + +`scripts/bench-chat-sequential-server.py` can run those arms one after the +other against the same private Strata server configuration. It verifies the +expected KAR SHA-256 first by default; `--skip-kar-sha256-check` skips only +that separate pass for an experimental smoke and marks it unverified in the +metadata. It writes temporary config files in tmpfs with mode +0600, starts only its own server process, unloads each model after the arm, +and keeps response reports outside Git. The candidate adds the experimental +PLE flags only; the original server configuration is never edited. +The frozen public `quality-v1.json` suite has eight deterministic cases across +reasoning, retrieval, instruction following, and function calls. One retrieval +case expands 4,400 filler rows around a single code before sending the prompt. +Passing this smoke suite is only an initial check; perplexity, real agent task +completion, 256K/512K context, and the full compressed-weight arm still need +their separate gates. + +The first paired Linux RTX 5090 measurement is recorded in +[`docs/experiments/2026-10-03-kar-ple-ab.md`](experiments/2026-10-03-kar-ple-ab.md). +Its CPU PLE arm preserved the tested outputs but did not improve prefill or +end-to-end latency. It does not test compressed VRAM expert residency. + +For offline cache sizing, an isolated Linux build can set +`STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` and provide a new private file path in +`STRATA_PLE_ROW_TRACE_PATH`. The engine writes one line of 16 global PLE row +IDs per token passed to `ngram_rows`, with mode `0600`. The compile flag is off by +default; without the environment variable even that experimental build does +not create a trace. The file can reveal request structure, so keep it outside +Git and remove it after aggregate analysis. The trace includes speculative +row calculations and does not label prefill versus decode. Use +`scripts/ple-cache-reuse.py --rows-trace TRACE` for an ideal cache screen and +`scripts/split-ple-row-trace.py` to map global IDs into a KAR part's local +range before the isolated CUDA cache smoke. Neither script runs in serving. +The [batch-capacity probe](experiments/2026-10-03-ple-cache-batch-capacity.md) +checks that a CUDA decode batch cannot name more distinct rows than the +bounded cache can hold, and records the three engine PLE handoff sites. + +An experimental engine build with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` +accepts `--ple-kar ARCHIVE --ple-kar-level 2 --ple-kar-gpu-cache-mib N`. +The opt-in cache keeps selected 50-byte KAR PLE rows in 64-byte VRAM slots +and decodes prefill and normal token rows on CUDA. It divides a prefill +request into cache-sized batches when needed. Speculative verification still +uses the same archive's CPU gather because its captured graph reads mapped +host memory. This serves only the PLE tensor from KAR; other model weights +remain in the native pack. Keep it experimental until full-model quality, +GPU memory pressure, and paired agent throughput pass their gates. + +## Artifact pipeline + +`strata-next model fetch` downloads the pinned source shards to an external volume. `model verify` checks their size and SHA-256 before any conversion. The current experimental `model prepare-sharded-streamed` builds a KAR-2 archive and a provenance sidecar with source and archive digests, codec policy, and tensor mapping; it writes to a staging path and publishes the finished archive without replacing an existing file. A production `model prepare --format kar2` still needs a per-class rate policy, tokenizer identity, and full-model quality approval. The final one-command `serve` flow should run missing fetch/verify/prepare stages automatically, reuse a verified prepared archive on subsequent starts, and never treat an incomplete stage as usable. Neither source shards nor the archive belong in Git or CI artifacts. + +The first source profile is Qwen3.8-Flash-Next IQ3_S, which is already quantized. KAR transcoding of it is a **lossy experiment** until full-model quality is measured. A higher-fidelity source may be needed if the IQ3_S → KAR path exceeds the error budget. Keep the verified native IQ3_S pack as the control arm and recovery path; never infer model quality from archive size or isolated tensor error alone. + +The tokenizer vocabulary, merge rules, and token-ID-to-text decoder belong in host RAM and run in Rust; they need no VRAM residency. Model embedding and output matrices are weights, even when their dimensions include the vocabulary size. Their placement and precision must be planned separately from tokenizer metadata. CPU placement of those matrices is possible but adds transfer or compute cost that must be measured on the target workload. + +KAR-2, as specified by the local koference project at commit `806d2398ae1daaceb2917242911e5680cbfb3608` (`r08/docs/format-kar-v2.md`, `r08/code/libkar.h`), is one archive per model with a source digest, directory digest, payload checks, and per-tensor precision levels. The Rust command should call a validated native encoder or a stable `libkar` API; Python may be used for offline research, calibration, and differential tests, but not by production serving. The decoder must reject an archive whose identity, bounds, checksums, or tensor layout do not match the expected model. + +The current `model inspect-kar` command performs bounded structural checks, header CRC-32, directory SHA-256, source identity reporting, and tensor section checks. `model verify-kar` additionally scans every tensor section and checks its payload CRC-32 with bounded memory. With `--manifest SPEC --source-dir DIR`, it verifies each source shard's size and SHA-256, then hashes the shards in filename order and compares the concatenated digest and byte count with the archive header. The sharded derived-F32 archives below require their dedicated verifier because the physical GGUF shard digest differs from the virtual F32 source digest. These checks do not constitute a model-quality or GPU execution result. + +The Rust `kar_writer` module emits a KAR-2 container from already coded RAW/NESTED tensor slices. A synthetic two-tensor output matches the pinned koference reference writer byte for byte, including header, directory, aligned payload, CRCs, and digest. The writer verifies its temporary file before atomic no-replace publication and rejects non-finite f16 scales/books. It does not choose a compression rate or approve a serving configuration. + +`strata-next model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. The KAR writer can stream both RAW tensor bytes and pre-encoded NESTED sections from files through a 1 MiB buffer. It checks the RAW source digest or NESTED section digest; the latter also checks finite f16 scales/books and zero alignment padding. The experimental native encoder supplies these sections for all GGUF types found in the target model. + +An experimental native `kar_codec::encode_with_boundaries` converts one in-memory f32 tensor to group scales and MSB-first bit planes using nested boundaries. `kar_codec::fit_topdown` fits those boundaries and f16 books to an already selected normalized sample; pinned synthetic fixtures match koference's Python reference. It rounds scales to IEEE f16 before assigning cells and uses the same bit-within-u32 order as koference's CUDA decoder. `kar_codec::decode_range` reconstructs a selected prefix into a caller-sized CPU buffer, giving a small numerical oracle for later CUDA checks. The streamed pipeline separately handles source decoding, bounded calibration and encoding, while model rate selection and lossy serving approval remain open. + +`strata-next model prepare-f32-preview FILE.gguf --output FILE.kar --levels N` connects the GGUF index, native calibration, encoder, CPU reconstruction check, and verified KAR writer. It accepts only a single F32 GGUF no larger than 64 MiB, at most 1000 tensors, with at most 1 million elements per tensor. Each encoded tensor is written to a private staging section and released from memory before the next tensor; the archive writer reads those sections with a 1 MiB buffer. Staging is cleaned after success or failure. It fits each tensor from all normalized values, records the rate in the KAR builder identity, and prints source/archive SHA-256 plus the maximum tensor relative L2. This command is an explicitly lossy integration preview. IQ3_S input is rejected, and no output from this command is eligible for serving until the full-model quality gate passes. + +The Rust `iq3_s` module now decodes one GGUF IQ3_S block (110 bytes, 256 F32 outputs) or a caller-sized sequence of complete blocks. Its 512-entry grid is copied from the pinned Strata/ggml tree, checked by SHA-256, and carries the ggml MIT notice in the binary through `--ggml-license`. Synthetic block output matches an independent Python calculation. A real-data slice of 262,144 IQ3_S blocks also produced 67,108,864 bit-identical F32 values against the pinned ggml CPU decoder. Both complete source shards have since passed their manifest SHA-256 checks. + +KAR-2 records `source_dtype` only as F32, F16, or BF16. An IQ3_S GGUF cannot be identified directly as a KAR-2 tensor source without violating that field. `model derive-iq3-identity FILE.gguf` computes a versioned **virtual F32 source identity** for a single GGUF whose tensors are all IQ3_S. It streams dequantized little-endian F32 values in GGUF tensor-directory order, reports the derived stream and per-tensor digests/offsets alongside the original GGUF and IQ3 tensor digests, and does not materialize the expanded data. The original GGUF digest belongs in a separate provenance manifest; the existing `verify-kar --manifest` checks physical source files and must not be used as proof of this virtual stream. + +`model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N` uses that identity to create a small, explicitly experimental KAR archive with F32 source dtype, virtual F32 tensor offsets/digests, and the derived stream digest. The original GGUF and IQ3 digests go into `FILE.kar.provenance.json`, published after the archive and bound to its SHA-256. If provenance publication fails, the new archive is removed. `model verify-iq3-preview FILE.kar --source FILE.gguf` recomputes the virtual source, checks every KAR tensor's F32 source record, scans payload CRCs, and compares the sidecar to the source and archive. It shares the F32 preview's 64 MiB source, 1000 tensor, and 1 million elements per tensor limits; source types must all be IQ3_S. Mixed-type shards, multi-shard identity, real tensor parity, and the full-model quality gate remain open. Neither preview archive is eligible for serving. + +`model derive-mixed-identity FILE.gguf` extends the virtual F32 identity to a single GGUF containing IQ3_S plus other supported types. It preserves F32 bit patterns, expands F16 and BF16 to F32, and uses the pinned Rust IQ3_S decoder or statically linked ggml C CPU dequantizers for other quantized types. The virtual stream digest covers values in tensor-directory order and excludes GGUF headers and padding. The command reports original type and source digest per tensor. `model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N` encodes a small bounded source and verifies its sidecar; that preview still uses the original four source kinds and is not eligible for serving. + +`model derive-sharded-identity MANIFEST --source-dir DIR` computes a virtual F32 identity across two or more GGUF shards. It sorts shards by byte-wise filename, checks each shard size and SHA-256 against the pinned manifest, rejects symlinks and duplicate tensor names, then concatenates decoded tensor values in each shard's directory order. The output includes per-shard identities and global derived tensor offsets. `model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` uses that identity to assemble a small experimental KAR from file-backed encoded sections, with a sidecar that binds every shard, tensor, and the archive digest. `model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR` recomputes and checks those links and the KAR payload CRCs. The 64 MiB preview cap, real-model quality gate, other tensor formats, and GPU path remain open. + +The native `gguf_f32_stream` visitor yields source bytes and derived little-endian F32 bytes in bounded chunks. Besides F32, F16, BF16 and the independent Rust IQ3_S path, it uses the pinned ggml CPU dequantizers for actual target kinds Q8_0, Q4_K, Q5_K, Q6_K, IQ2_S, IQ4_NL, IQ3_XXS, IQ4_XS and Q2_0. The ggml C source at llama.cpp commit `3cf03257f219afbe7334045ff7c6a06ac68c627d` is vendored with hashes and linked statically into the Rust executable. A pinned synthetic IQ3_S block matches the independent Rust decoder exactly; one block of each real target quant type passes the bounded visitor. Both source shards are SHA-256 verified; real-model quality remains open. + +The C bridge dispatches by named ggml type constants and checks its native block size against the Rust GGUF index before reading. This corrected an early kind-18/kind-22 swap (`IQ3_XXS` versus `IQ2_S`). Streamed archives now use v4 builder/provenance/derivation identifiers because giant GGUF tensors require multiple KAR-2 records; earlier streamed archives are rejected by the current verifier. Both target shards are SHA-256 verified, and one real block of every type in the first shard decoded to finite F32 values. The complete model-quality gate remains open. + +The experimental `kar_sample` primitive normalizes these streamed values in reusable groups of 32 with the same rounded f16 scale logic as the existing codec. It takes at most 65,536 values from deterministic, digest-seeded positions spread across the padded tensor. For tensors over 1,048,576 elements it seeks directly to the selected GGUF blocks; F32 and IQ3_S sparse samples matched full-stream samples in tests. This sample is not a validated rate policy; per-class policy and the real-model quality gate remain open. + +The `kar_stream_encode` primitive writes one canonical nested section directly from bounded GGUF chunks using the supplied calibration. It keeps only a group, source chunk, and buffered file writers in memory, hashes both physical and virtual sources, and computes tensor relative L2. A synthetic section matches the existing in-memory writer byte for byte and passes KAR-2 archive verification; an IQ3_S stream crossing a chunk boundary preserves source and derived digests. + +`model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` now connects the bounded visitor, deterministic 65,536-value calibration sample, file-backed section encoder, and KAR-2 archive writer across manifest-pinned GGUF shards. It has no 64 MiB preview cap or per-tensor allocation. If a tensor cannot supply a valid nested calibration, it is copied as virtual F32 into a RAW section instead of being discarded. Every streamed tensor's physical and virtual digest is checked against an independently derived identity, every shard is hashed again after preparation, and the archive and separate preparation-policy provenance are published without replacing existing files. Oversized tensors are split into adjacent records with checked source and virtual offsets and part hashes. `model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N` independently verifies the shards, virtual tensor source records, archive payload CRCs, and sidecar binding. A small forced-split test reconstructs both records on CPU. Both real target shards and selected KAR slices are verified; full-model rate choice, quality, and Linux GPU loader still need validation. This command is experimental and its output is not eligible for serving. + +The streamed preparer tracks relative L2 and encoded bytes per KAR record and prints the twenty records with the largest relative L2 on a newly created archive. The existing 51.50 GiB archive predates that recording and has only its full-record maximum of 0.68008092. `model analyze-sharded-kar` can now compare small source/archive windows for every record in that existing archive; its `--assume-verified` mode uses the earlier full source/archive verification and marks that assumption in the report. This ranks candidates for more precision but is not a full-record error bound or a model-quality score; a split parent tensor appears as multiple records. A selective precision policy can encode sensitive records at more KAR levels, retain an exact representation, or add independently addressable residual blocks. Residuals need archive integrity checks and must be included in transfer, VRAM, and CUDA decode budgets. Choose the policy after per-class distortion measurements and the separate model-quality gate; a lossless outer codec cannot repair KAR quantization error. + +An experimental KAR overlay now carries higher-precision replacement records for a selected subset without rebuilding the full archive. Its provenance binds the base archive and candidate policy digests; selected physical and virtual source digests are checked during encoding. The overlay is independently verified, and the CPU comparison command measures paired full-record error against both archives. A serving loader must still select overlay records by name, verify both artifacts together, and account for their VRAM residency and transfer before this can affect inference. An overlay is not an additive residual: it replaces the selected base record when enabled. + +If selective higher precision does not pass the model-quality gate, an exact +correction tier can be evaluated separately. Its contract is bitwise equality +to a named GGUF dequantization baseline, including values such as signed zero; +ordinary floating-point addition of a residual is not sufficient to promise +that. One candidate is an XOR of the base F32 bit pattern with the reference +F32 bit pattern, packed in independently addressable blocks and decoded on +CUDA. Another is to retain exact original GGUF quantized blocks for selected +tensors. In both cases, record the bytes of the base plus correction, PCIe +traffic, CUDA decode cost, and full-model quality. If exact data removes the +size or transfer advantage, the exact tier is a correctness fallback rather +than a performance win. + +`model resolve-kar-overlay --base BASE.kar --overlay OVERLAY.kar` now emits a verified tensor-to-archive mapping for a future loader. It recomputes both archive SHA-256 values, validates every payload CRC, checks the shared virtual-F32 source identity, and rejects a replacement with a different source digest, offset, or dimensions. The command does not load weights or enable overlay serving. Keep both archives immutable after resolution; a GPU loader must validate their identities again before using this mapping. + +The isolated Linux CUDA smoke target accepts an optional overlay path and routes a requested tensor to the selected archive after payload, common source identity, name, shape, dtype, per-record source digest, and source-offset checks. `--row ROW_ID` selects one local row of a compressed record and decodes it into a one-row GPU output buffer after staging that record's complete compressed level prefix. Run the full Rust resolver first for complete archive hashes and provenance. This exercises compressed VRAM residency and CUDA decoding for one selected record when the GPU is available; it does not integrate with Strata's matrix multiplication, schedule a model, or pass the quality gate. + +For sparse PLE lookups, a small decoded output alone is insufficient: the full-record `kar_reserve` transfer can dominate PCIe traffic. Even a 100-million-element partition remains too coarse to stage afresh for a 160-value row. The isolated `strata-kar-sparse-row-smoke` therefore assembles a compact packet of only each requested row's codebook, group scales, and bit-plane words, transfers the packet, and decodes it on CUDA. This keeps the KAR-2 archive unchanged and does not require millions of tiny directory records. It is a prototype, not a serving source: production integration must verify immutable archive identity once, keep a bounded row or packet cache, account for host page faults and packet assembly, and pass full-model quality and paired latency gates. The original GGUF PLE row is 90 bytes on disk; the current engine expands it to 640 F32 bytes for GPU upload. Compare complete storage, host, PCIe, and GPU costs before selecting a policy. + +The CPU quality oracle can decode up to one million values from an arbitrary nested tensor offset with bounded memory, reading only the needed scales and plane words after archive verification. `cargo run --release --example compare-kar-range -- FILE.gguf FILE.kar LEVEL START COUNT` compares this archived output against pinned ggml dequantization of a one-tensor GGUF sample. On source-verified real slices, independent level-2 archive reconstruction gave relative L2 around 0.33–0.34 for sampled IQ3_S and IQ4_NL ranges; level 3 reduced one IQ4_NL range to 0.165. This is a numerical roundtrip check on selected ranges, not an agent-quality gate. + +`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation. + +`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally. + +The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape. + +## GPU path + +`strata-next model plan-kar-memory FILE.kar --level 2 --budget-mib 24576` reads validated KAR metadata and reports compressed-prefix residency, full F32 decode scratch, the largest single-record peak, and records whose full decode exceeds the supplied VRAM slice. The budget must be the memory left after the engine, KV cache, and other allocations; it is not the card's advertised capacity. `one_row_peak_bytes` is only a geometric lower bound for records that `kar_decode_rows()` can address. It does not mean the model can compute from one row of an arbitrary expert or projection. This command does not scan payload CRCs or approve the archive for serving. + +`strata-next model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level 2 --overlay-level 3 --budget-mib 24576` first verifies both complete archive hashes, payload CRCs, provenance, and every replacement mapping. It then counts exactly one selected record per tensor at its chosen precision level, separating base and overlay compressed residency and reporting the largest F32 scratch and one-row lower bound. Keep both archives immutable after this check. This is still a memory calculation, not GPU admission or permission to serve a lossy model. + +On the verified Qwen3.8-Flash-Next IQ3_S level-2 archive, the metadata plan at a hypothetical 24,576 MiB slice reports 55,294,991,056 bytes if all compressed records were resident, so residency must be selective. Two split `per_layer_token_embd.weight` records exceed that slice for full F32 decode: their compressed-prefix-plus-output peaks are 138,000,000,016 and 82,801,059,856 bytes. Their one-row lower bounds are 10,000,000,656 and 6,000,077,456 bytes. `kar_decode_rows()` avoids the huge F32 output but `kar_reserve()` still stages the complete 10.0 GB or 6.0 GB compressed record. Efficient cold row lookup therefore needs smaller addressable PLE parts or a sparse staging kernel. The engine must not allocate the full decoded table on the target card. These are metadata arithmetic, not GPU measurements or quality results. + +For the target compressed runtime, copy the selected KAR data to VRAM in compressed form. Keep at least the working layer and selected experts decoded or decode them into a bounded scratch buffer on a CUDA stream before multiply. Use `kar_decode_rows()` for sparse per-layer embedding lookups. The scheduler must account for archive residency, precision level, transfers, decode, and multiply, and measure cold misses separately from warm expert-cache hits. The archive format and decoded numerical values must be compared with the koference CPU oracle before an end-to-end speed claim. + +The user-facing Linux command checks the installed NVIDIA driver and starts the native engine. It does not carry the driver. The single-file GPU packaging goal still needs a real Linux CUDA build and loader test. + +## Cache profiles + +| Profile | Attention state | Status | +| --- | --- | --- | +| `with-key` | K and V cache, using the selected baseline KV format | Control profile for quality and performance | +| `without-key` | Value-Only cache with a validated `Wq_keyless` transform; separate QSA indexer keys remain | Experimental until the Keyless quality gate passes | + +Record the model digest, archive digest, cache profile, KV format, context length, slot count, and hardware with every comparison. Test `without-key` on held-out activation traces and full 256K/512K agent workloads; report memory savings, quality, and throughput separately. A cache profile cannot silently change when an archive is selected. + +## Test-runtime switch + +The testing runtime can first receive shadow traffic after a real Linux GPU smoke test proves model loading and a complete text response. Replacing the current test endpoint requires live Responses streaming, cancellation and tool-call integrity, sanitized Codex replay, a verified compressed GPU path, both cache profiles labeled accurately, and a one-step rollback to the current runtime. `without-key` can be tested separately before it is eligible as a default. diff --git a/docs/cross-platform-application.md b/docs/cross-platform-application.md new file mode 100644 index 00000000..995ee28e --- /dev/null +++ b/docs/cross-platform-application.md @@ -0,0 +1,598 @@ +# Strata: застосунок для локальних і віддалених моделей + +**Статус:** архітектура продукту; початкова реалізація desktop, 2026-10-04. +**MCP:** STRA-36, епік STRA-37; desktop STRA-48/49, remote STRA-50–53. + +Цей документ описує запит користувача на macOS, Windows і Linux застосунок із +автоматичною підготовкою моделей. Він доповнює [PROJECT_CHARTER](../PROJECT_CHARTER.md), +але не оголошує завершеними Linux milestones або реалізованими нові платформи. +Порядок пріоритетів незмінний: коректність, якість, швидкість виконання задачі. +Активне користувацьке випробування продовжується без змін runtime. + +## 1. Що отримує користувач + +Основний сценарій: **вибрати модель → підготувати для цього комп'ютера → запустити**. +Застосунок сам визначає сумісні рушії, завантажує потрібні компоненти й модель, +оцінює пам'ять, створює придатне представлення та перевіряє його. Показує прогрес, +можливість продовжити перерване завантаження і конкретну причину несумісності. + +Основні розділи: + +- **Моделі:** каталог, локальний імпорт, версії, розміри оригіналу й підготовлених + варіантів, ліцензія, сумісність, результати перевірки якості. +- **Запуск:** модель, контекст, паралельні запити, режим швидкості/енергії, + фактичний пристрій виконання та оцінка пам'яті. +- **Діалог і API:** простий playground та endpoint для зовнішнього harness. +- **Підготовка:** відновлювані download/conversion/compression/validation jobs. +- **Стан:** TTFT, prefill/decode, токени, RAM/VRAM, черга, помилки. Тексти запитів + не потрібні для стандартної телеметрії. +- **Комп'ютери:** локальний пристрій або явно підключений приватний сервер. + +CLI має ті самі можливості на всіх трьох ОС. GUI можна закрити, залишивши +сервер працювати; команда зупинки явна. Автозапуск вмикається користувачем. +Запропоновані команди, ще не поточний контракт CLI: + +```text +strata model add +strata model prepare --quality preserve +strata run --device auto +strata jobs watch +strata status --json +strata stop +``` + +## 2. Спільне ядро й інтерфейси ОС + +```mermaid +flowchart TD + M[macOS: Avalonia + OS integration] --> C[Спільний protobuf / gRPC API] + W[Windows: Avalonia + OS integration] --> C + L[Linux: Avalonia + OS integration] --> C + CLI[Спільний Rust CLI] --> C + C --> D[Rust service: моделі, jobs, lifecycle, planner] + API[Responses HTTP / SSE] --> D + D --> A[Node agent: local loopback або SSH tunnel, gRPC] + A --> S[Strata worker] + A --> G[Загальний worker: llama.cpp] + A --> N[Платформні workers: Core ML / Windows ML / OpenVINO] + S --> H[CPU / GPU / NPU відповідно до можливостей worker] + G --> H + N --> H +``` + +| Платформа | Пропонований UI | Інтеграція | +| --- | --- | --- | +| macOS | Avalonia, C#/.NET | системні меню й діалоги, shortcuts, Keychain, accessibility, power/sleep | +| Windows | Avalonia, C#/.NET | системні діалоги, credentials, notifications, signed installer | +| Linux | Avalonia, C#/.NET | portals, desktop integration, Secret Service; CLI/headless незалежний від desktop | + +**Рішення реалізації 2026-10-04:** спільний Avalonia UI замінює початкову +пропозицію трьох окремих SwiftUI/WinUI/GTK оболонок. Rust містить portable +контракти й планувальник; UI містить представлення та платформні інтеграції. +Контроли Avalonia не означають автоматичної нативної інтеграції кожної ОС: +меню, accessibility, сховища секретів, power/sleep перевіряються окремо. +Поточний desktop використовує дочірній Rust node і спільний gRPC/HTTP2 контракт; +JSON schema v1 для inventory/planner передається всередині protobuf envelopes. Див. [desktop README](../desktop/README.md). + +**Уточнення користувача 2026-10-04:** management та application-to-worker +transport — спільний версійований protobuf/gRPC контракт для локальних і +віддалених вузлів. Це замінює попередню пропозицію окремого локального JSON-RPC. +Локальний agent є звичайним вузлом пулу: authenticated loopback без SSH; +віддалений — той самий API через SSH tunnel. C# UI та Rust CLI/service +використовують клієнти, згенеровані зі спільної схеми. Desktop уже використовує цей контракт для inventory/planner. Самостійні CLI +команди з JSON збережені для користувачів консолі. +Job events мають sequence number; після reconnect клієнт отримує snapshot і +подальші події. Ваги, tensors і виклики окремих шарів не проходять через gRPC +під час inference: обчислення залишаються всередині worker. + +Inference HTTP/SSE — окремий стабільний контракт: tool calls, reasoning, +cancellation, terminal events та usage. Backend adapter повинен реально +підтримати кожну заявлену capability. Простий chat endpoint не є доказом повної +сумісності Responses або harness. + +## 3. Автовибір прискорення, включно з офісним ноутбуком + +**NPU — повноцінна ціль планувальника.** Для ноутбука без дискретної GPU +порівнюємо сумісні NPU-only, iGPU, CPU SIMD та hybrid plans. Мета — найкращий +виміряний результат для вибраної моделі за заданих обмежень, включно з батареєю +й температурою. Не вимагаємо одночасно завантажити всі пристрої до 100%. + +Визначаємо фактичне обладнання та доступність runtime: + +- CPU ISA, OS-enabled registers, ядра, RAM, bandwidth, NUMA; AVX2/AVX-512/VNNI + або ARM SIMD лише за наявності відповідних можливостей. Portable binary + вибирає спеціалізовані kernels під час запуску. +- GPU, backend, driver, device features, доступна пам'ять, unified/discrete + memory, підтримувані quant formats і kernels. +- NPU, runtime/provider, підтримувані operators, shapes, precision, context, + compilation/cache constraints; фактичний розподіл graph між пристроями. +- Живлення, memory pressure, температурний режим і резерв для ОС та інших програм. + +AVX не закінчується з появою NPU: Core Ultra також має AVX2. +Перевіряємо capabilities конкретного SKU, а не правило «покоління 14/15». +[Intel AVX2](https://edc.intel.com/content/www/us/en/design/products/platforms/details/meteor-lake-u-p/core-ultra-processor-datasheet-volume-1-of-2/002/intel-advanced-vector-extensions-2-intel-avx2/). + +| Обладнання | Початковий шлях | Наступні кандидати | +| --- | --- | --- | +| Apple Silicon | Metal GPU + ARM CPU через загальний engine | Core ML/ANE для сумісного graph та precision | +| Windows/Linux + NVIDIA | CUDA | CPU/GPU offload за memory plan | +| Windows офісний ноутбук з NPU | доступні CPU/iGPU та NPU providers | NPU-only і hybrid prefill/decode, за підтримки моделі | +| AMD/Intel GPU | кваліфікований backend загального engine | HIP/SYCL/Vulkan за відповідною support matrix | +| CPU-only | спеціалізований SIMD backend | threads/batch/cache tuning під RAM bandwidth | + +Windows сам по собі не обмежує модель CPU: CUDA доступна й на Windows. +Metal, CUDA та CPU шляхи вже існують у +[llama.cpp](https://github.com/ggml-org/llama.cpp), але їхня інтеграція й перевірка +в нашому застосунку — окрема робота. +[Core ML](https://developer.apple.com/documentation/coreml/mlcomputeunits) +дозволяє системі використовувати CPU/GPU/Neural Engine. Це не означає, що +довільний graph повністю виконається на ANE. +[Windows ML](https://learn.microsoft.com/en-us/windows/ai/new-windows-ml/overview) +надає execution providers для CPU/GPU/NPU; вимоги ОС/драйверів і підтримка +моделі перевіряються для конкретного provider. + +Hybrid execution практично існує: AMD описує LLM режими з NPU prefill і GPU +decode. Однак список моделей, quantization і допустимий контекст обмежені +конкретним пакетом; їх не переносимо на наш 256K Qwen автоматично. +[Ryzen AI model list](https://ryzenai.docs.amd.com/en/main/llm_list.html). + +### Рекомендації за обсягом пам'яті та конкретним обладнанням + +Каталог пропонує кілька придатних конфігурацій для фактичного комп'ютера, +включно з GPU класів 8, 12, 16, 24, 32 GiB та іншими значеннями. Ці класи — +групування для UI, не жорстка таблиця «стільки VRAM = така модель». +Окремо враховуємо total/free VRAM, доступну RAM, unified memory, GPU architecture, +bandwidth, CPU, driver/backend і вартість передач/offload. В unified memory +не додаємо один і той самий фізичний pool двічі як RAM плюс VRAM. + +Memory plan включає resident weights/experts, KV за заданим контекстом і +паралельністю, activations, scratch/decoder workspace, runtime overhead, +пік завантаження та резерв для desktop/ОС/інших процесів. Невеликий архів +сам по собі не означає, що модель поміститься під час виконання. + +Картки рекомендованих варіантів показують: + +- модель і quant, точний device/backend, контекст і кількість запитів; +- повне розміщення на GPU або частковий offload у RAM/CPU; +- оцінку steady/peak RAM і VRAM та запас, статус якості; +- швидкість лише з релевантних вимірів або явну позначку «ще не виміряно»; +- дії «Запустити» та «Перевірити бенчмарком на моєму комп'ютері». + +Приклад вибору для 8/16 GiB: перевірити компактну модель повністю на GPU та +більшу з частковим offload, якщо вистачає RAM і backend це підтримує. Це +кандидати для порівняння, а не гарантія конкретного розміру моделі/контексту. +Коротший контекст, інша модель або агресивніша quantization пропонуються як +окрема альтернатива зі зміненими умовами, без прихованої заміни вибору. +Якщо придатного плану немає, пояснити дефіцит ресурсу й запропонувати меншу +модель або явно налаштований remote endpoint. + +Результати RTX 5090 не переносяться як виміряна швидкість на інші карти. +Обмеження allocation до 8/16 GiB на 5090 перевіряє лише частину memory planner; +воно не імітує bandwidth/compute/driver поведінку реальної карти цього класу. +Qualification matrix має включати справжні 8 і 16 GiB конфігурації, а також +shared-memory notebook; до перевірки рекомендації мають статус estimated. +Безпосередньо перед load повторно перевірити доступний memory budget. + +**Уточнення користувача:** 8 GiB laptop GPU — пріоритетний масовий сценарій. +Користувач має для майбутніх тестів ноутбук з RTX 3080 16 ГБ; це доступний +кандидат qualification hardware, ще не перевірений нами. Перед запуском +зафіксувати ОС, driver, GPU identity/фактичну VRAM, RAM, TGP/power mode й thermal +state. Порівняти cold/warm та sustained runs від мережі з однаковими задачами. +Кваліфікація 3080 16 ГБ не замінює реального 8 ГБ ноутбука. Адреса/доступ та +вільний час пристрою мають бути визначені до експериментів; надання цієї +інформації про обладнання саме по собі не запускає тест. + +### Алгоритм вибору + +1. Відсіяти несумісні model/backend/device combinations. +2. Побудувати плани розміщення ваг, activation buffers і KV з резервом пам'яті. +3. Відсіяти варіанти, що порушують політику якості або потрібні tool surfaces. +4. На вільному пристрої виміряти cold/warm TTFT, prefill, decode, task throughput, + peak memory та, якщо є достовірні counters, energy. Врахувати copies/sync і + тривалу роботу після прогрівання, а не лише короткий burst. +5. Обрати профіль: «Швидкість», «Тихо/батарея», «Мінімум пам'яті» або Auto. + Політика якості задається окремо; економія батареї не дозволяє приховані втрати. +6. Зберегти recipe за model/engine/driver/hardware/quality/power identities. + Зміна значущих компонентів робить попередню кваліфікацію неактуальною. + +Ділити graph довільно між NPU/GPU не плануємо: використовуємо підтримані +provider-ом розбиття або окремо кваліфіковані межі. KV має залишатися сумісним +між prefill і decode. Надлишкові передачі можуть перекрити виграш прискорювача. +Непідтриманий NPU план пояснюється в UI; fallback не змінює модель чи precision +без згоди. Автокалібрування не запускається під час активної роботи користувача. + +### Автоматичні бенчмарки за вибором користувача + +На картці моделі є дія **«Підібрати найкращі налаштування для мого комп'ютера»**. +Це окремий відновлюваний job. Перед запуском користувач бачить кількість +кандидатів, оцінку часу/тимчасового диска та вибирає сценарій: діалог, довгий +контекст, coding agent або паралельні запити. Контекст і кількість одночасних +запитів є умовами задачі: менше вікно не може непомітно виграти порівняння. + +Два режими пошуку: + +- **Швидкий:** обмежений бюджет часу, попередній відбір і детальна перевірка + найкращих кандидатів. Звіт явно показує неперевірені комбінації. +- **Повний:** усі сумісні комбінації в оголошеній скінченній матриці параметрів, + із pause/resume. Перебір може тривати довго; до запуску показуємо оцінку. + Досягнення ліміту часу залишає результат частковим, а не «все перевірено». + +Матриця включає backend/device, CPU threads, offload, розміщення й місткість +кешів, compression recipe/block size, device decode, batch/microbatch та +speculation там, де їх підтримують модель і engine. KV quantization, V-only та +інші lossy варіанти потрапляють в окремий явно дозволений експериментальний +набір. Вхідна модель, tokenizer, задача й політика якості зафіксовані; +порівняння іншої квантизації моделі показується окремо. + +Порядок виконання: + +1. Зафіксувати модель/digest, software/hardware identities, живлення, параметри + сценарію та визначений baseline. Відсіяти несумісні або небезпечні для + memory budget кандидати із поясненням. +2. Перевірити output/tensor parity для non-lossy змін; для lossy — окремі + quality gates charter. Невдалий або незавершений прогін не може перемогти + завдяки меншій кількості токенів. +3. Виконати парні повтори baseline/candidate з однаковим workload, sampling + policy та cold/warm cache умовами; чергувати порядок для зменшення thermal + drift. За шумного стороннього навантаження позначити результат забрудненим. +4. Для фіналістів повторити незалежні перевірочні задачі, які не використовувалися + для підбору; не перетворювати tuning score на доказ збереження якості. +5. Надати таблицю: quality status, TTFT, prefill/decode, input/output/reused + tokens, час завершеної задачі, RAM/VRAM, доступні energy дані, кількість + повторів і діапазон невизначеності. Для agent workload окремо рахувати + model requests, tool calls та очікування інструментів/компіляції. +6. Рекомендувати найкращий перевірений профіль для вибраного сценарію. Якщо + різниця в межах шуму, не оголошувати прискорення; залишити baseline або + запропонувати еквівалентний дешевший за пам'яттю/енергією варіант. Для заяв + про малі прирости дотримуватися повторів і статистики charter. + +Глобального «найшвидшого для всіх задач» профілю не обіцяємо. Зберігаємо recipe +разом із workload fingerprint, покриттям пошуку, quality evidence та версіями. +Користувач може застосувати переможця, залишити попередній профіль або окремо +вибрати «застосувати найкращий після завершення» перед запуском job. +Автоматичне застосування проходить звичайну switch transaction із rollback. + +Benchmark job отримує exclusive lease на керований worker: активна користувацька +сесія не переривається. Скасування/помилка/OOM завершують лише власний candidate, +зберігають уже отримані результати й відновлюють попередній профіль за можливості; +помилка відновлення показується явно. Нові engine/driver/model versions позначають +результат як застарілий і пропонують повторити перевірку. Приватні задачі +користувача використовуються лише за його вибором; стандартний набір — локальний, +версійований і без передачі prompts назовні. Поточне випробування користувача +не є дозволом запускати цей підбір зараз. + +## 4. Що переноситься на інші моделі + +Наявний engine спеціалізований під `qwen4exp`; це видно в +`engine/strata/src/program/generate.cpp`, model geometry та CUDA kernels. +Загальний формат tensors не робить execution graph універсальним. +Підтримка нової моделі має три окремі рівні: **прочитати → коректно виконати → +виконати з конкретною оптимізацією**. + +| Підхід | Залежність від моделі | Необхідна адаптація | +| --- | --- | --- | +| Download, manifests, resume, lifecycle, telemetry | низька | формат, metadata, ліцензія | +| Блокове lossless-стиснення ваг | принцип загальний | codec, tensor layout, entropy; виграш не гарантований | +| Стиснені ваги на GPU, decode потрібного блока | загальна ідея | decoder для пристрою, integration із matmul, memory scheduling | +| KAR progressive/lossy представлення | tensor codec можна адаптувати | діапазони/геометрія tensors, allocation точності, quality gate кожної моделі | +| Поточний KAR PLE row cache | висока | потрібна відповідна PLE lookup table; у моделі без PLE ця оптимізація відсутня | +| Кеш активних експертів | MoE | router, expert layout, activation distribution; dense-модель не має такого router | +| KV paging/reuse/quantization | середня/висока | attention layout, позиції, state identity; квантований KV має окрему перевірку якості | +| V-only | дуже висока | attention math, norms, RoPE, indexer; можливе навчання/адаптація моделі | +| Speculative decoding | метод загальний | сумісний draft/tokenizer, точний verifier; MTP потребує відповідного шляху моделі | + +Отже, **продукт не прив'язуємо до одного Qwen, але не обіцяємо всі трюки кожній +моделі**. Model adapter описує graph, tokenizer, chat template, tool/reasoning +serialization і capabilities. Optimization recipe окремо задає сумісність +із model architecture, quant, backend та hardware і посилається на validation. + +Поточний користувацький профіль — KAR для PLE з додатковою втратою точності; +це не доказ повного KAR-resident engine для довільної моделі. +[Реальний GPU PLE експеримент](experiments/2026-10-03-agent-gpu-kar-threejs.md). +V-only retrofit нашої Qwen не пройшов агентну перевірку якості, хоча kernel +тести пройшли. Це не заборона методу для інших моделей і не підстава вмикати +його для них автоматично. +[Звіт V-only](experiments/2026-10-04-keyless-runtime.md). + +Перенесення decoder на Metal є окремою kernel-роботою. Для NPU довільний CUDA +decoder непридатний: потрібний підтриманий graph/operator або інше представлення. +Розпакування на CPU перед NPU може економити диск, але не дає автоматично +compressed residency чи меншого device traffic. Розрізняємо ці можливості в UI. + +## 5. Модель, стиснення та збереження якості + +Durable pipeline: + +```text +resolve pinned source → download/resume → verify → inspect +→ estimate temporary disk/RAM → prepare candidate → validate +→ measure eligible plan → atomically publish artifact → load +``` + +SQLite WAL зберігає registry, jobs, checkpoints і recipes; service — один writer. +Ваги зберігаються immutable файлами поза DB. Manifest містить source revision, +digests, tokenizer/template, tensor representation, encoder/engine versions, +точність, dependencies (включно з correction layer), результати перевірок. +Після аварії продовжуємо з перевіреного checkpoint; незавершений artifact не +стає доступним для serving. Cancel прибирає лише job-owned temporary files. + +Типова політика — **без додаткових втрат відносно вибраної вхідної моделі**. +IQ3/IQ4 уже квантовані: точне відновлення їхніх bytes не повертає FP16 оригінал. +Lossless recipe визначає, що саме відновлюється точно: bytes quantized blocks +або canonical tensor values. Correction layer мусить забезпечити цей контракт; +його розмір може прибрати всю користь стискання. Інші kernels можуть мати +відмінне FP округлення навіть із точними вагами: числові tolerances та greedy +output порівнюємо з визначеним baseline. + +Lossy recipes позначаються явно й мають незалежні perplexity, retrieval, +tool-call та task-completion gates за charter. Вдалий короткий діалог не є +quality gate. Наявний свідомо вибраний користувачем experimental profile не +переписує цю політику типових налаштувань. + +Окремі capability flags: + +- `compressed_storage`: економія диска; +- `compressed_transfer`: передавання стиснених blocks; +- `compressed_residency`: blocks залишаються стисненими на device; +- `decode_on_device`: decoder виконується на device; +- `fused_decode_compute`: computation споживає blocks без повної materialization. + +Жоден flag не випливає автоматично з попереднього. Якщо стискання не допомогло, +зберігаємо придатний вихідний варіант і показуємо результат. Після верифікації +повного runnable bundle можна прибрати відтворювані source/intermediate copies +відповідно до політики користувача; не видаляємо потрібні correction dependencies. + +## 6. Lifecycle, ізоляція й безпека + +Workers — окремі процеси з versioned handshake і контрактом +`probe/prepare/load/generate/cancel/drain/unload/stats`. Capability negotiation +включає model architectures, quant, context/slots, tools/reasoning/structured +output, compressed flags, ОС і driver constraints. Failure одного worker +не повинен втратити durable registry або лишити незавершений API stream. + +Switch transaction: підготувати target → перевірити ресурси й dependencies → +дочекатись завершення активних запитів за вибраною користувачем політикою → +вивантажити керований worker → завантажити target → readiness → опублікувати endpoint. +При невдачі спробувати відновити попередній recipe й явно показати результат. +Сторонні GPU процеси не зупиняти. За невідомої або неповної власності ресурсів +перемикання відмовляє з діагностикою. Наявний switch controller — відправна точка: +[STRA-35](experiments/2026-10-04-model-switch.md). + +Model code з репозиторіїв не виконуємо автоматично. Download/extraction обмежують +розмір і paths; engine packages мають pinned versions і перевірені підписи. +API типово loopback з authentication; management доступний власнику через IPC. +Remote — явно налаштований SSH/TLS endpoint. Credentials: Keychain, Windows +credential storage, Linux Secret Service; для headless — захищений локальний +secret file як явна альтернатива. Логи й telemetry без prompts/secrets за замовчуванням. + +## 7. Доставка та CI/CD + +Один встановлений продукт із CLI; пакети окремі для ОС/architecture. +Немає одного executable, спільного для Windows/macOS/Linux. Rust control plane +залишається без Python у production serving. Native preparation — ціль продукту; +offline Python experiments не стають прихованою runtime dependency. +Engine packs завантажуються за потреби; драйвери ОС/GPU не вшиваємо. + +macOS: signed/notarized app і CLI; Windows: signed installer/пакет та CLI; +Linux: CLI archive спочатку, desktop package далі. Background service per-user: +launch agent, Windows user process або systemd user; foreground mode не +потребує системного service manager. Updates завантажуються окремо, перевіряються +і застосовуються між сесіями з rollback, без зупинки активної генерації. + +CI матриця першого розширення: Linux x86_64, Windows x86_64, macOS arm64. +Інші CPU architectures і мінімальні версії ОС — після кваліфікації dependencies. +На всіх ОС: Rust checks, IPC/API contract fixtures, fake-worker crash/reconnect, +job recovery, installer/CLI smokes, path/permission checks. На реальному залізі: +NVIDIA Linux, Metal Mac, Windows CPU/GPU і окремі Intel/AMD NPU SKU. Для NPU +перевіряємо фактичний execution placement, не лише успішне відкриття provider. +Приватні weights і captures не потрапляють у Git або публічні CI artifacts. + +Linux workflow уже є в репозиторії; hosted GitHub Actions run та видачу signed +desktop packages цей документ не підтверджує. Сертифікати, signing і release +infrastructure — окремі delivery dependencies. + +## 8. Послідовність реалізації + +1. **Спільний контракт і CLI:** винести registry/jobs/capabilities/lifecycle із + поточної Linux реалізації. Gate: existing Responses/harness поведінка збережена, + recovery та explicit unsupported responses перевірені. +2. **Mac UI + remote/local:** native shell керує перевіреним Linux endpoint; + додати local Metal worker і одну реально перевірену невелику модель іншої + архітектури. Gate: самостійна агентна задача, tools, cancellation, memory bounds. +3. **Офісний NPU ноутбук:** один конкретний AMD або Intel SKU, одна підтримана + модель; CPU/iGPU/NPU/hybrid порівняння якості, швидкості й енергії. Gate: + відомий execution placement і збереження якості; потім розширення matrix. +4. **Windows UI та Linux UI:** підключити до того самого контракту, package/update + recovery й OS integration. Linux CLI залишається повноцінним server продуктом. +5. **Автоматичні compression recipes:** спочатку точне відновлення + чесні + memory/speed результати; потім Metal/device decoders, інші tensors/архітектури + та явно експериментальні lossy recipes з окремими gates. + +UI, engine portability і нові model optimizations мають окремі implementation +задачі. Цей етап завершується дизайном; він не запускає нові експерименти й не +змінює активну сесію користувача. + +## Remote inference через SSH — STRA-50 + +Ціль виконання є явною: `Local` або `Remote`. Вибір remote зберігає той самий +сценарій «модель → підготовка → запуск», але ресурси, модельні файли та jobs +належать серверу. Ноутбук зберігає налаштування підключення, UI й локальний endpoint. +Параметри SSH: host/alias, port, user, посилання на ключ або системний SSH agent. +Приватні ключі й паролі не зберігаються у профілі/логах/репозиторії. + +Послідовність майстра: + +1. Перевірка SSH і host identity. Невідомий ключ показується користувачу для + довіри; змінений ключ зупиняє підключення. Перевірка host key не вимикається. +2. Read-only preflight сервера: ОС, архітектура, CPU ISA, RAM/VRAM, драйвер, + прискорювачі, доступне місце. План використовує серверні ресурси. +3. Підбір сумісного перевіреного runtime-артефакта. Встановлення у власну + користувацьку теку через staging і атомарну активацію, без автоматичного sudo + або заміни драйвера. Manifest фіксує версію, digest, capabilities та ownership. +4. Завантаження моделі прямо на сервер; підготовка/стискання та quality gate + згідно політики. Можна імпортувати вже наявний файл без повторної передачі. +5. Запуск керованого worker на серверному loopback. Заміна активної моделі + відбувається лише через явну дію перемикання, з перевіркою запитів і rollback. +6. Власний SSH-тунель до `127.0.0.1:`. Перевірка зайнятого порту; + endpoint для harness показується лише після готовності моделі й тунелю. + +Стани `disconnected → verifying → inspecting → preparing → starting → ready` +доповнюються `reconnecting`, `failed`, `stopping`. UI окремо показує SSH, +підготовку моделі та inference readiness. Зникнення тунелю не означає аварії +worker. Після sleep/network interruption відновлюємо transport і читаємо стан; +частково виданий inference-запит автоматично не повторюємо. Закриття UI, +зупинка тунелю та зупинка remote runtime — різні дії. Зупиняємо лише власний +процес з перевіреним instance id/PID/start time, не стороннє GPU навантаження. + +Перший remote worker target — Linux. Mac/Windows/Linux є клієнтами; підтримка +remote worker на інших ОС додається за фактичною підтримкою engine, не лише UI. +Автопідбір зберігає серверний hardware/driver fingerprint, конфігурацію моделі, +cache state й network latency окремо від decode/prefill. + +Реалізація декомпозована в MCP: STRA-51 (профіль/preflight), STRA-52 +(provisioning), STRA-53 (tunnel/UI). На цьому етапі це специфікація; готового +SSH deployment у новому desktop ще немає. Інтеграційний gate — окремий чистий +Linux host: install/resume/rollback, Responses tool calls через тунель, +перепідключення й cancellation. Поточний користувацький сервер не є стендом +для руйнівних перевірок. + +## Пул локальних і SSH-вузлів — STRA-54 + +Користувач може додати **кілька** цілей виконання одночасно. Local/Remote — +властивість вузла, а не глобальний перемикач застосунку. Один Rust gateway на +ноутбуці представляє їх harness як каталог моделей і явно налаштовані пули. +Це desktop-сценарій горизонтального масштабування з G9/M6 charter. + +```mermaid +flowchart LR + H[Harness: паралельні запити] --> G[Локальний Responses gateway] + G --> Q[Планувальник: модель, capabilities, вільні слоти] + Q --> L[Mac: локальна модель] + Q --> T1[SSH tunnel A] + Q --> T2[SSH tunnel B] + T1 --> A[Сервер A: модель і власний KV state] + T2 --> B[Сервер B: модель і власний KV state] +``` + +### Контракт і вибір моделі + +- `Node`: стабільний id, local/SSH transport, hardware fingerprint, ownership, + trust scope, окремі connection/readiness стани й доступні ресурси. +- `Deployment`: node id, модель/digest, quantization/recipe, quality status, + engine version, capabilities, max context, слоти й resource group. +- `Pool`: явний список deployments і правила маршрутизації. Точний model id + направляється тільки до відповідного deployment або еквівалентних replicas. + Пул різних моделей вмикається явно, з дозволеними задачами, capabilities, + quality/privacy constraints; вибір конкретної моделі не підміняється мовчки. +- Gateway надає `/v1/models` з доступними model/deployment IDs та pool aliases, + `/v1/responses` для виконання і окремий management API для стану пулу. + Відповідь/метрики зберігають фактично вибрану модель, вузол та recipe. + Віддалений вузол отримує дані лише для призначеного йому запиту; telemetry + за замовчуванням не містить prompts, коду або секретів. + +### Паралельність і стан + +Один вільний сумісний слот на кожному з трьох незалежних вузлів дозволяє +виконати три незалежні запити одночасно. Harness має сам надсилати їх +паралельно; gateway не розбиває послідовну агентну задачу автоматично. +Наявність трьох моделей у каталозі не означає три вільні слоти: перевіряємо +фактичну готовність, RAM/VRAM і спільні GPU resource groups. Два SSH aliases +до одного worker не подвоюють його місткість. + +Admission атомарно резервує слот і memory budget. Далі кожен запит має власні +stream, cancellation, usage і terminal state; загального inference lock немає. +Усі terminal/error/cancel шляхи звільняють reservation. Черга обмежена й +справедлива, з timeout/backpressure. Метрики розділяють queue, network, prefill, +decode та end-to-end час; додавання вузлів не є гарантією трикратного прискорення. + +Conversation/`previous_response_id` прив'язується до власника стану, моделі та +версії. Окремі незалежні сесії можна розподіляти; продовження сесії не мігрує +мовчки. За втрати її вузла gateway повертає визначену помилку або пропонує явне +відновлення з повної історії, коли воно підтримане. Перерваний SSE і неоднозначну +відправку автоматично не повторюємо без worker-side deduplication. Втрата одного +вузла не скасовує запити на інших. SSH reconnect і retries не можуть повторити +tool calls або створити другий terminal event. + +### UI та gate + +Розділ «Комп'ютери» містить кілька локальних/remote вузлів. Картки показують +модель, слоти, запити, чергу, ресурси, tunnel/readiness та помилки. Редактор пулу +дозволяє включити вузли, вибрати дозволені моделі й routing policy; endpoint +для harness залишається один. GUI і gateway мають незалежний lifecycle. + +MCP: STRA-55 — registry/deployments/pools; STRA-56 — scheduler/admission/stream +isolation; STRA-57 — UI і інтеграційний gate. Автотести з fake workers доводять +маршрутизацію, races, overload, cancellation і failure isolation. Приймання на +реальному local + 2 SSH стенді вимагає трьох перекритих у часі harness-запитів, +коректних незалежних tool calls/terminal events, фактичного model attribution +та виміряної concurrency. Цей розділ фіксує дизайн; pool gateway ще не реалізований. + +**Оновлення реалізації:** експериментальний Rust gateway і bounded queue вже є +у `desktop-core` (STRA-56); три паралельні fake workers та черга перевірені через +реальний loopback HTTP. Це ще не інтеграція з GUI/керованими SSH agents і не +real-model gate. Контракт і поточні обмеження: [POOL.md](../desktop-core/POOL.md). + +## Постійний node agent і gRPC — STRA-58/59 + +Рішення користувача: невеликий Rust agent працює на локальному комп'ютері та +кожному віддаленому сервері й керує власними workers/jobs через однаковий API. +SSH потрібний для першого віддаленого встановлення, перевірки +ідентичності й тунелю. Після bootstrap основний management transport — +версійований gRPC канал між локальним Rust service та node agent. Harness +продовжує використовувати локальний Responses HTTP/SSE endpoint. + +Один логічний канал на вузол містить окремі RPC-потоки: + +- handshake/version/capabilities та snapshot; +- типізовані команди lifecycle/job/admission/cancel і acknowledgement; +- підписку на state/job events і числові метрики; +- окремий потік inference для кожного запиту, з власним backpressure. + +Повідомлення різних запитів не складаються в одну необмежену чергу. Окремі +HTTP/2 streams і bounded application queues запобігають блокуванню control +великим потоком метрик; низькопріоритетні метрики можна об'єднувати до останнього +значення. Загальні transport limits і bandwidth залишаються спільними. +gRPC має transport flow control, але політику черг визначає застосунок. +[gRPC flow control](https://grpc.io/docs/guides/flow-control/). + +Відновлення після обриву: + +1. Клієнт позначає вузол disconnected і тимчасово припиняє новий admission. + Сам disconnect спостерігача не звільняє зайняті слоти на сервері. +2. Відновлює tunnel/channel з exponential backoff, jitter та узгодженим + keepalive; reconnect до інших вузлів незалежний. Auth/schema mismatch + має окремий стан, не нескінченний швидкий retry. +3. Передає `agent_epoch` і останній застосований `event_seq`. Сервер віддає + збережені події; за gap/нового epoch клієнт отримує узгоджений snapshot + із cursor, потім нові події. UI дедуплікує вже застосовані sequence numbers. +4. Команди мають `operation_id`, digest параметрів і збережений стан виконання. + Повтор тієї самої команди повертає її результат, інші параметри з тим самим + id відхиляються. Після втрати ack спочатку звіряється статус операції. + Для рестарту агента потрібний стійкий журнал/reconciliation процесів; + один gRPC retry не гарантує exactly-once execution. +5. Inference із неоднозначним прийманням або вже виданими токенами автоматично + не запускається заново. Resume потоку дозволяється лише за окремого + bounded replay-контракту; інакше повертається явний interrupted стан. + +Автоматичні gRPC retries не замінюють application-level reconciliation, +а keepalive лише виявляє transport failure, не доводить готовність моделі. +[gRPC retry](https://grpc.io/docs/guides/retry/), +[gRPC keepalive](https://grpc.io/docs/guides/keepalive/). + +Локальний transport — gRPC на loopback; віддалений — такий самий gRPC через SSH. +Обидва потребують per-install автентифікації та захищеного зберігання/отримання +credential; localhost не є винятком для auth. Прямий network gRPC потребує mTLS +і явного enrollment. Local та remote проходять однаковий contract suite: +capabilities, lifecycle/jobs, inference/tool calls/terminal events, cancel ack, +bounded queues, reconnect та reconciliation. Закриття локального UI саме по +собі не зупиняє worker чи запит; явна зупинка — окрема команда lifecycle. +Agent має перелік дозволених команд; RPC «виконай довільний shell» відсутній. +Ваги завантажуються сервером або окремим bounded transfer, не event bus. +UI можна закрити, не зупиняючи remote agent чи inference за замовчуванням. + +MCP: STRA-58 — agent/protobuf/control/event service; STRA-59 — reconnect, +resume і reconciliation клієнта. STRA-52/53 використовують цей контракт для +provisioning/tunnel. Початковий gRPC node реалізований локально: handshake/auth, +inventory/planner, snapshot subscription та Responses adapter; див. +[GRPC.md](../desktop-core/GRPC.md). Durable lifecycle/jobs та автоматичне +відновлення ще не завершені. На користувацькому сервері node не встановлено. diff --git a/docs/experiments/2026-10-03-agent-ab-threejs.md b/docs/experiments/2026-10-03-agent-ab-threejs.md new file mode 100644 index 00000000..c68fdb5f --- /dev/null +++ b/docs/experiments/2026-10-03-agent-ab-threejs.md @@ -0,0 +1,78 @@ +# Three.js agent task: native Strata versus KAR PLE, 2026-10-03 + +## Scope and fixed setup + +One Codex agent per arm received the identical prompt (SHA-256 +`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`): +build a single-file Three.js/WebGL tic-tac-toe game, verify it, and complete +the dedicated LeaseVibe test-project workflow. The agents ran sequentially in +separate empty workspaces. No operator changed either game's files or helped +either agent while it worked. The original Strata launcher profile was left +untouched. Test project tasks were `TEST-2` (baseline) and `TEST-3` (KAR PLE), +both reported Done by their agents. + +Both arms used the Linux RTX 5090 host, driver 595.91.07, CUDA 13.2, the same +Qwen3.8-Flash-Next IQ3_S shards, source commit and engine configuration listed +in [the paired inference report](2026-10-03-kar-ple-ab.md). Each had one 256K +slot, INT8 **K+V** cache with 32,768 resident cells, MTP speculation depth 4, +and Strata's ordinary expert cache. The candidate used level-2 KAR only for +the PLE table, read and decoded on CPU. The model shards and KAR artifact were +on NTFS. This was neither the proposed compressed expert cache in VRAM nor +the experimental V-only KV path. The two agents followed different tool and +generation trajectories; this is one agent run per arm, not a paired +statistical benchmark. + +## End-to-end observations + +| Metric | Native baseline | KAR PLE candidate | +| --- | ---: | ---: | +| Full agent wall time | 2,162.44 s (36m02s) | 1,810.22 s (30m10s) | +| Codex CLI input tokens | 3,297,339 | 3,226,901 | +| Codex CLI cached input tokens | 1,100,546 | 741,408 | +| Codex CLI output tokens | 52,878 | 37,439 | +| Output tokens / full wall second | 24.45 | 20.68 | +| Completed bridge requests | 97 | 95 | +| Median request decode rate | 62.0 tok/s | 118.9 tok/s | +| Decode tokens / sum of decode time | 52.35 tok/s | 44.06 tok/s | +| Prompt tokens / sum of prompt time | 3,804 tok/s | 5,312 tok/s | +| Median first-token latency | 7.49 s | 8.50 s | +| Final HTML size | 13,930 bytes | 15,771 bytes | +| Shared browser checks | 6/6 | 6/6 | + +The candidate's full task was 16.3% shorter, but its output-token count was +29.2% lower. Its output tokens per full wall second were 15.4% lower. The +per-request median decode rate is strongly affected by request length: +candidate had 30 requests below 100 generated tokens versus five in the +baseline. Weighting by all measured decode time reverses the median's apparent +gain. Neither ratio isolates an engine effect in these divergent agent traces. +MCP schema rejections and later corrected calls are ordinary parts of the +workflow; they are included in wall time and were not scored as quality defects. + +The operator's same browser test ran after both agents finished, without +editing their files: each loaded without a page error, rendered a visible +WebGL canvas, completed a row win through real clicks, blocked moves after +the win, restarted to an empty board, and reached a draw through real clicks. +Both scored 6/6. Their own agent tests reported 37 Chrome assertions and +29 Chromium assertions respectively; these are different suites and their +counts are not comparable quality scores. This task did not measure model +perplexity, long-context retrieval, tool-call fidelity over a dataset, or +V-only KV quality. + +Private prompt, final HTML files, raw event streams, bridge logs, and the +common browser test remain outside Git under +`/Users/para/.cache/strata-next/agent-ab-threejs-20261003/` and +`/Users/para/.codex-qwen-interactive/bridge-logs/`. The final HTML digests +are `c4bc939d7fabd51f2a95d95c430c04fdaf64c9e27d2fd0300baebc3b59e0bfe4` +(baseline) and `9a944c1e1d23042f362eb6078fb49aa07b45eb677ad631edd77308fff005dbc5` +(KAR PLE). + +## Decision + +This agent task provides a successful functional comparison, not evidence of +a KAR performance improvement. The earlier paired inference suite found +matched short outputs but no CPU PLE speedup. The current runtime should not +be replaced on the basis of these runs. The next performance experiment must +integrate a bounded GPU-resident compressed weight cache and CUDA decoding +into the actual inference path, then compare identical requests and agent +tasks with a quality gate. V-only KV is a separate lossy mode and needs its +own long-context and tool-call quality gate before any default use. diff --git a/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md b/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md new file mode 100644 index 00000000..1987c48b --- /dev/null +++ b/docs/experiments/2026-10-03-agent-gpu-kar-threejs.md @@ -0,0 +1,82 @@ +# Three.js agent task with GPU KAR PLE, 2026-10-03 + +## Workload + +The same coding task as the earlier [native versus CPU KAR agent run](2026-10-03-agent-ab-threejs.md) was sent through `codex-qwen` to each available profile. The prompt SHA-256 was +`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. +Each agent worked alone in a separate empty directory, built a single-file +Three.js/WebGL tic-tac-toe game, verified it, and advanced one new task in the +dedicated LeaseVibe test project. The operator did not change any agent's +files or guide its MCP calls. Runs were sequential on the same RTX 5090 +(driver 595.91.07, CUDA 13.2); one 256K slot, INT8 K+V, 32K resident KV cells, +and MTP depth 4. All normal expert weights stayed in the native IQ3_S pack. +The KAR arms replaced only the PLE table; GPU KAR used a 64 MiB compressed +GPU row cache. The private archive was never published. + +The three runs below use the current launcher and fresh engine starts. +Native engine SHA-256 was +`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`; +CPU KAR engine SHA-256 was +`099c32ce2195385b0367755c25f8e9a9cdf56282980208c6c4879712bbe0e5bc`; +GPU KAR engine SHA-256 was +`f5a2dfb49a7a1c35a6549f41901dabf5505b98c6a5a9b4801ea3d2c70729f0e5`. + +## Completed agent results + +"Iterations" below means completed model requests. Tool calls count completed +shell and MCP calls. The decode rate is total engine-generated tokens divided +by total engine-reported decode time across completed requests. CLI token +counts include the agent's full conversation accounting. One task per profile +is an end-to-end observation, not a paired inference benchmark. + +| Profile | Requests | Tool calls | CLI input tokens | Cached input tokens | CLI output tokens | Weighted decode tok/s | Full task time | Independent browser checks | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Native, fresh repeat | 49 | 59 | 3,380,308 | 3,325,362 | 49,854 | 115.7 | 634.27 s | 6/6 | +| CPU KAR PLE, fresh repeat | 70 | 70 | 5,498,472 | 5,440,802 | 64,006 | 150.3 | 707.59 s | 6/6 | +| GPU KAR PLE, fresh | 68 | 73 | 4,955,852 | 4,908,060 | 69,101 | 150.1 | 712.29 s | 6/6 | + +The independent browser check loaded each game without page errors, found a +visible WebGL canvas, played a row win with real clicks, verified that moves +stop after a win, restarted the board, and played a draw. It did not score +visual polish, accessibility, or broad model quality. Agent-authored test +suites differed and their assertion counts are not comparable. + +The fresh native agent finished 78.02 s sooner than GPU KAR and 73.32 s sooner +than CPU KAR, while generating 19,247 and 14,152 fewer output tokens, +respectively. Its weighted decode throughput was lower. The two KAR arms +finished within 4.70 s of each other and had essentially the same weighted +decode rate, despite following different agent paths. All three fresh runs +had heavy prefix reuse: 98.4% of CLI input tokens cached for native, 99.0% +for CPU KAR, and 99.0% for GPU KAR. The older native/CPU KAR runs had much +lower cache reuse, so their wall times cannot isolate the GPU row decoder's +effect. A separate fixed-prompt serving comparison found no established GPU +KAR speedup. + +All outputs are different games and different agent trajectories. These +observations show task completion and quantify cost; they do not establish a +GPU KAR throughput gain or broad quality preservation. GPU KAR's higher +generation rate than native in this sample did not compensate for the extra +agent work in full task time. GPU and CPU KAR were nearly equal. There is no +accepted end-to-end performance improvement for the PLE-only GPU cache. + +The private output files and logs remain outside Git at +`/Users/para/.cache/strata-next/agent-ab-threejs-20261003/`. The GPU game's +SHA-256 is +`6704a931d08e05377f7d0f3479078dbba338636f29152c9b681c9163681085a0`; +the native repeat's is +`ba4c30e32352cab5e0971d1e7d3c82357010a2b3237beb1df2b440b08d4e159b`; +the CPU KAR repeat's is +`682137c96cf99fa06aec1789e098662a60060a9e3d49f8845ef86097b4da737d`. + +## Unavailable profiles + +The current server has one FIFO inference sequence. `conversation-cache-slots` +parks state between requests; it does not run two simultaneous 256K agents. +The QSA attention path still stores and reads K and V. The custom offline +V→K regression had 0.3023 relative L2 attention-output error on a limited +held-out proxy. It did not implement the cited Keyless Attention method. +No physical without-key serving profile or model-level quality gate exists. +V-only has no agent result; its speed and quality effect are unmeasured. +The later two-process 2×256K agent experiment is recorded separately in +[the dual-worker report](2026-10-03-dual-256-agent.md); it does not implement +two slots within one engine. diff --git a/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md b/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md new file mode 100644 index 00000000..ad57e4cf --- /dev/null +++ b/docs/experiments/2026-10-03-bounded-ple-cache-smoke.md @@ -0,0 +1,66 @@ +# Bounded compressed PLE row cache smoke, 2026-10-03 + +## Setup + +This is the first **functional** GPU cache probe following the +[offline row-locality screen](2026-10-03-ple-cache-reuse.md). The program +`gpu/kar/src/kar_row_cache_smoke.cu` was compiled on Linux for `sm_120` with +CUDA 13.2.86 and the repository's pinned `libkar` object. The new CMake target +also configured and built successfully with CUDA 13.2.86 and Ninja on that +host. Hardware was an +RTX 5090 (32,607 MiB reported VRAM), NVIDIA driver 595.91.07, 600 W reported +power limit. The private Qwen3.8-Flash-Next IQ3_S KAR v4 archive and its +provenance are described in the [paired KAR report](2026-10-03-kar-ple-ab.md). +The selected record was `per_layer_token_embd.weight#strata-part-001-of-002` +at level 2. Payload CRCs were verified before any row access; no full-archive +SHA-256 pass was added. The two pinned GGUF source-shard SHA-256 values are +`4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` +and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +The archive's source-side SHA-256 was +`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; +the remote file was not independently SHA-checked, as recorded in the paired +report. The repository base before this probe was `49b091c`. + +The probe reserves only a bounded compressed-row cache, an update buffer, +slot IDs, a four-entry codebook, and the current F32 output. The CPU maps +row IDs to slots with LRU replacement. Each missed PLE row admits 50 +compressed bytes from the verified archive into a 64-byte VRAM slot. It +uploads a 56-byte update record per miss and four-byte slot ID per access; +the update record includes its slot number and two padding bytes. A CUDA +scatter kernel writes the row to its assigned slot, then another kernel +decodes the selected rows in VRAM. Every batch is compared byte for byte with +a fresh, independently gathered CPU decode of the encoded archive rows. + +## Correctness checks + +Both private traces used 16 row IDs per batch and a 1 MiB cache with 16,384 +slots. The five-batch trace requested rows 0–15, reversed them, repeated +them, requested 100–115, then revisited 0–15. The eviction trace filled the +cache with rows 0–16,399, repeated the last 16, then revisited the first 16. +The observed counts matched the expected LRU behavior exactly. + +| Trace | Batches | Accesses | Hits | Misses | Row bytes admitted | Actual H2D argument bytes | CPU parity | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | +| Reuse | 5 | 80 | 48 | 32 | 1,600 | 2,112 | Exact for all batches | +| Eviction | 1,027 | 16,432 | 16 | 16,416 | 820,800 | 985,024 | Exact for all batches | + +The eviction run's archive CRC verification took 80,131 ms. The first run +preceded the verification-time field and did not record that duration. The +sum of CUDA-event stages was 0.105 ms for five reuse batches and 7.047 ms +for 1,027 eviction batches. Those event sums include update and slot-ID +copies plus the scatter and decode kernels. The source arrays were ordinary +host memory, so the event sums may omit some host-side copy or staging time. +They exclude archive verification, CPU LRU lookup, output readback, CPU +reference decoding, and the rest of model inference. No throughput or +speedup claim follows. The output hash chains were `64284b0dfd5bfad9` +and `210c15ebb02c4a16`, respectively; exact per-batch CPU parity is the +stronger correctness check. + +This smoke keeps 1 MiB of cache payload allocated; it does not hold a 10 GB +PLE record in VRAM. It proves compressed row admission, hits, eviction, and +CUDA decoding work together on the real archive under the tested traces. +It does **not** yet use actual model request row IDs or connect decoded rows +to Strata's PLE consumer. It does not establish model quality, expert/KV +pressure, or end-to-end agent speed. The next step is a captured prefill and +decode row trace, then serving-path integration with a quality gate and +paired throughput measurement against the native baseline. diff --git a/docs/experiments/2026-10-03-dual-256-agent.md b/docs/experiments/2026-10-03-dual-256-agent.md new file mode 100644 index 00000000..73e30f8d --- /dev/null +++ b/docs/experiments/2026-10-03-dual-256-agent.md @@ -0,0 +1,105 @@ +# Two independent 256K workers on one RTX 5090, 2026-10-03 + +## Setup and physical concurrency + +The opt-in Linux controller `scripts/strata-dual-256-experiment.py` started two +independent native Strata workers on the same RTX 5090 (driver 595.91.07, +CUDA 13.2). Each used the verified Qwen3.8-Flash-Next IQ3_S source, context +262,144, INT8 K+V with 32,768 resident cells, MTP depth 4, and the same +baseline engine binary SHA-256 +`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. +The two workers listened on private experimental ports 18081 and 18082; +the normal service on 8080 was unchanged. The expert-cache request was +2,000 slots per worker; native sized allocation reported 2,582 actual slots. +Both workers reached readiness with 262,144-token context. Together they +used 28,218 MiB GPU memory at readiness and about 28,406 MiB while two +agents were active. The original one-worker agent profile had about 11,700 +expert slots, so this is a different memory/performance policy. + +A parallel Chat Completions smoke sent the same long synthetic request to +both ports with a barrier. Both returned `OK`, `finish_reason=stop`, and +42 completion tokens in 7.39 seconds; concurrent `/slots` sampling observed +both workers in `is_processing` state. This proves simultaneous model work on +one GPU. It is not an end-to-end agent throughput measurement. + +The controller writes credential-bearing configs only under private `/dev/shm` +paths, validates an idle GPU before starting, and stops only its recorded +worker process groups. Model weights and request data are not placed in Git. +This is a two-process experiment; a production Rust scheduler and batching +inside one engine still need separate implementation. + +## Agent task + +Two independent `codex-qwen` sessions started on the same Three.js tic-tac-toe +prompt used in the [single-worker comparison](2026-10-03-agent-gpu-kar-threejs.md). +They work in separate empty directories and use the shared dedicated MCP test +project. No operator changed their files or guided their calls. The second +agent started 25.7 seconds after the first. Both produced one working WebGL +game. An independent browser replay for each passed the same six checks used +for the single-worker games: no page error, visible canvas, row win through +clicks, locked board after a win, restart, and draw through clicks. + +| Run | Completed model requests | Tool calls | CLI input / cached tokens | CLI output tokens | Weighted decode tok/s | Wall time | Browser checks | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Native single worker, earlier fresh run | 49 | 59 | 3,380,308 / 3,325,362 | 49,854 | 115.7 | 634.27 s | 6/6 | +| CPU KAR PLE single worker, earlier fresh run | 70 | 70 | 5,498,472 / 5,440,802 | 64,006 | 150.3 | 707.59 s | 6/6 | +| GPU KAR PLE single worker, earlier fresh run | 68 | 73 | 4,955,852 / 4,908,060 | 69,101 | 150.1 | 712.29 s | 6/6 | +| Dual worker A, native | 69 | 71 | 6,472,001 / 6,395,938 | 78,286 | 35.32 | 3,721.36 s | 6/6 | +| Dual worker B, native | 71 | 74 | 6,178,149 / 6,105,218 | 60,337 | 29.21 | 2,615.25 s | 6/6 | + +The pair finished when A finished, **3,721.36 seconds** (62m 01s) after A +started. Together they produced 138,623 output tokens, an end-to-end aggregate +of **37.25 output tok/s** over that wall time; the weighted decode-only rate +across both was 32.37 tok/s. Four bridge requests failed and were retried; +one A request waited 968.43 seconds before timing out. Its server log had +stopped progressing while the GPU was idle. The engine log shows generation +continuing after the server's last token-progress line, so the available logs +do not isolate whether parsing or HTTP delivery stalled. This is a stability failure even +though A eventually completed the task. Per-request decode rates had long +tails: A median 64.9, p10–p90 20.8–78.6 tok/s; B median 55.4, p10–p90 +19.9–71.6 tok/s. A's first 20 completed requests weighted 22.6 tok/s while +both agents competed; its last eight after B finished weighted 66.3 tok/s. + +This dual-process profile **does not improve end-to-end throughput** on this +workload. Its expert cache is much smaller than the single-worker profile, the +agents followed different paths, and the 968-second stall dominates A's wall +time. The one-run comparison is directional, not an isolated estimate of the +cost of request concurrency. It does prove two full 256K contexts and two +simultaneous requests fit on this GPU. A production one-engine two-slot +scheduler remains unbuilt and unmeasured. + +## One endpoint, two requests + +The requested interface is one endpoint that accepts two simultaneous requests +from a client. The first run above instead used two independent agent clients +on separate ports; it measures GPU feasibility and end-to-end contention but +does not by itself prove that interface. The experimental +`scripts/strata-dual-request-proxy.py` now admits one request to each worker +through a single HTTP address. A local barrier test confirmed that two +concurrent calls to that address reached distinct workers. The proxy preserves +the first worker for serial requests so a single agent can reuse its prefix +cache. A second local barrier test confirmed that both streamed responses +delivered their terminal SSE event. After both agents completed, one client +sent two simultaneous Chat Completions to that same address. Both workers +reported `is_processing=true` at the same time. Both returned 30 completion +tokens, `finish_reason=stop`, and nonempty content; their individual latencies +were 3.82 and 3.80 seconds, and the pair took 3.88 seconds. This is +HTTP-level concurrency across two processes, not continuous batching in one +model process. It is a short correctness smoke, not a speed claim for a +long-running agent. + +The experimental proxy and workers were stopped after testing. GPU memory +fell to 34 MiB; temporary credential configs under `/dev/shm` were removed. +Private model shards and the validated KAR archive were retained. The two +games and event logs remain in the ignored local experiment directory to +reproduce these measurements. + +## Ordinary Strata stability follow-up + +The experiment used the separately installed ordinary Strata source at commit +`30ec18e`. Its stability follow-up is recorded in the +[ordinary Strata report](2026-10-03-ordinary-strata-stability-ab.md), including +client-disconnect cancellation, bounded cleanup and response writes, an +engine-restart race fix, real-model disconnect recovery, and 59 passing +server tests. Those changes limit abandoned requests; the earlier +pre-disconnect stall's exact cause remains unconfirmed. diff --git a/docs/experiments/2026-10-03-expert-cache-pressure.md b/docs/experiments/2026-10-03-expert-cache-pressure.md new file mode 100644 index 00000000..4ee37156 --- /dev/null +++ b/docs/experiments/2026-10-03-expert-cache-pressure.md @@ -0,0 +1,66 @@ +# Expert-cache pressure from a proposed 10 GiB resident KAR record, 2026-10-03 + +## Question and method + +On the 32 GB RTX 5090, can Strata give 10 GiB to one compressed PLE record +without a material cost to its expert cache? This is a **capacity-pressure +probe**, not a KAR-serving run. The model still read its ordinary IQ4_NL PLE +table and all other normal weights. Only Strata's `--vram-reserve-mib` changed: +700 MiB in the baseline arm and 10,940 MiB in the pressure arm. The extra +10,240 MiB matches the approximate 10 GiB footprint of the first resident +level-2 PLE record measured in [the CUDA row report](2026-10-03-gpu-resident-rows.md). +The reserve is a planner budget, not an actual KAR allocation. + +Hardware was one Linux RTX 5090 (32,607 MiB reported by `nvidia-smi`), NVIDIA +driver 595.91.07. The same Qwen3.8-Flash-Next IQ3_S native pack, source GGUF +shards, Strata binary (SHA-256 +`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`), +and configuration were used in both arms; see +[the earlier paired report](2026-10-03-kar-ple-ab.md) for model digests. The +configuration used one 256K context, INT8 K+V, 32,768 resident KV cells, +MTP speculation depth 4, `--expert-cache auto`, and a native expert profile. +A private 54-token coding prompt produced 160 tokens in each run. The prompt's +SHA-256 was +`02119df5dbcaa7ae797e45fd4591ad1028c5d7e5f8c3b97a802529a8d2ecb2a7`. +The first cold pair was discarded from rate comparison because model loading +took 286.79 s in the first arm and 18.51 s in the second. The three measured +pairs alternated arm order A→B, B→A, A→B. The offline controller and private +raw output are under `scripts/bench-expert-reserve.py` and +`/home/para/.cache/strata-next/expert-reserve-warm-20261003/` respectively. + +## Observation + +| Measure | 700 MiB reserve | 10,940 MiB reserve | +| --- | ---: | ---: | +| Expert slots | 12,569 | 7,312 | +| Expert cache | 23.87 GiB | 13.86 GiB | +| Distinct CPU experts per layer, three runs | 1.34, 1.34, 1.34 | 3.35, 3.78, 3.47 | +| Distinct PCIe experts per layer, three runs | 0.90, 0.90, 0.90 | 3.06, 3.52, 3.21 | +| Decode tokens/s, paired in run order | 58.46, 105.96, 166.30 | 18.85, 81.10, 55.91 | +| Prefill tokens/s, paired in run order | 224.28, 129.01, 264.85 | 191.01, 109.49, 192.79 | + +The reserve displaced **5,257 expert slots** and about **10.01 GiB** of the +expert cache. All three pressure-arm decode rates were lower, with paired +pressure/baseline ratios 0.322, 0.765, and 0.336. These rates have large +run-to-run variation. The model repeatedly stalled on NTFS reads during +loading; the reported full process wall times ranged from 18 to 288 seconds. +The 54-token prompt is not the required 256K workload. This small sample +does not estimate a reliable end-to-end slowdown or quantify quality. + +Greedy output IDs differed between the arms starting at output index 1 in +all three pairs. The baseline arm's output was stable across its three runs; +the pressure arm produced two different 160-token sequences. Changing the +expert cache can change GPU/CPU expert arithmetic and routing, so an exact +greedy match was not assumed. No judged task-quality or tool-call gate was +run. The output difference is an additional reason not to treat this as a +runtime-acceptance test. + +## Decision for the next prototype + +Reserving an entire 10 GiB PLE part on a 32 GB card causes substantial expert +cache displacement before any CUDA row decoding is connected to inference. +The next prototype should bound PLE residency to selected blocks or packets, +or first reduce the expert cache footprint. It must then measure actual +admission/eviction, PLE decode and compute, expert hit/miss changes, and +paired full-model and agent quality. Keep the native runtime as the reference +until those gates pass. diff --git a/docs/experiments/2026-10-03-gpu-resident-rows.md b/docs/experiments/2026-10-03-gpu-resident-rows.md new file mode 100644 index 00000000..617cb444 --- /dev/null +++ b/docs/experiments/2026-10-03-gpu-resident-rows.md @@ -0,0 +1,82 @@ +# Resident KAR rows on RTX 5090, 2026-10-03 + +## Setup + +This isolated CUDA experiment measured the proposed compressed-VRAM geometry +for a real Qwen3.8-Flash-Next IQ3_S PLE partition. Hardware was the Linux +RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2. The selected level-2 record was +`per_layer_token_embd.weight#strata-part-001-of-002` in the private v4 archive +described in [the paired report](2026-10-03-kar-ple-ab.md). The benchmark +binary was rebuilt from this repository's pinned `libkar` plus the +`strata-kar-gpu-smoke --rows` extension. The archive was opened with payload +CRC verification before timing. Data and executable builds remain outside Git +on the Linux host. + +The command was: + +```text +strata-kar-gpu-smoke MODEL.kar 'per_layer_token_embd.weight#strata-part-001-of-002' 2 100 --rows 4096 42 +``` + +It admitted one compressed level prefix to VRAM, uploaded 4,096 deterministic +row IDs, warmed the CUDA decoder, then measured 100 repeats of the same rows. +The result was: + +| Measure | Result | +| --- | ---: | +| Record shape | 200,000,000 rows × 160 values | +| Compressed record resident in VRAM | 10,000,000,016 bytes | +| Compressed bytes per row | 50.0 | +| Original IQ4_NL bytes per row | 90 | +| Initial reserve | 497.54 ms | +| Decoded output | 655,360 F32 values (2,621,440 bytes) | +| Warm CUDA decode median | 0.00512 ms | +| Output FNV-1a 64 | `4c459b6ac39d3431` | + +For this partition, the compressed GPU representation uses about **44.4% less +space per row** than its original IQ4_NL table (50 versus 90 bytes), before +GPU allocator overhead. The fast warm decoder shows that a **resident** +compressed record can supply selected rows cheaply. This does not measure +archive admission frequency, +replacement policy, row-ID transfer per request, host page faults, matrix +multiplication, or agent throughput. The 10 GB record competes directly with +the existing expert and KV caches on a 32 GB card. The timed batch reused the +same row IDs, so a varying-request benchmark is still needed. The full archive +does not fit on the card. No serving code used this GPU output, and the batch +checksum was not independently compared to CPU reconstruction; the previous +single-row CPU/CUDA parity check covers the underlying decoder only. These +limits prevent a performance or model-quality claim for the runtime. + +## Follow-up: changing row IDs and independent batch parity + +The same RTX 5090 and archive were used with a rebuilt smoke binary (CUDA +12.8.1 toolkit, driver API 13.2). The `--rows-ple` mode uses the deterministic +row generator from Strata's CPU PLE probe. For 4,096 random rows, level 2, +seed 42, and 100 warm repeats, the resident decoder's complete F32 output +checksum was `00cc55a3da2ef31b`, **identical** to the independent CPU KAR +gather's checksum on the same rows. This closes the batch parity gap in the +first measurement. The native IQ4_NL gather's different checksum is expected +because KAR level 2 is lossy; full-model quality has a separate gate. + +`--rows-ple-vary` then replaced every row ID before each timed repeat, using +pinned host memory for the ID upload. The host generated the next ID batch +outside the timed CUDA events. Each invocation verified the archive payload +CRCs, staged the 10,000,000,016-byte prefix once, and ran 100 repeats. The +medians below are CUDA-event times in microseconds, not request latency: + +| Rows per batch | ID upload | Resident decode | Upload + decode | +| ---: | ---: | ---: | ---: | +| 16 | 2.912 | 3.200 | 6.048 | +| 4,096 | 3.136 | 5.632 | 8.704 | + +The 4,096-row fixed-ID parity run had a 4.512 µs warm decode median. The +changing-ID result includes the different memory access pattern but still +excludes PLE projection, cache admission and eviction, host ID generation, +competing expert/KV cache pressure, and the rest of inference. Its final-batch +checksum (`571247f5d41f34ae`) is not compared with the CPU probe's first +batch. The 16-row changing-ID final checksum was `c4bf921377ba537e`. +No inference speedup or full-model quality result follows from these numbers. + +Next: implement a bounded resident cache, measure expert/KV displacement, +wire the decoded rows into the PLE consumer, then run paired inference and +agent quality gates. Keep the native profile available for rollback. diff --git a/docs/experiments/2026-10-03-kar-ple-ab.md b/docs/experiments/2026-10-03-kar-ple-ab.md new file mode 100644 index 00000000..fca3758d --- /dev/null +++ b/docs/experiments/2026-10-03-kar-ple-ab.md @@ -0,0 +1,53 @@ +# KAR PLE CPU arm on RTX 5090, 2026-10-03 + +## Question + +Does reading the Qwen3.8-Flash-Next PLE table from level-2 KAR preserve output and improve inference throughput compared with Strata's native IQ4_NL PLE table? + +## Fixed configuration + +- One NVIDIA GeForce RTX 5090, driver 595.91.07, CUDA 13.2 toolkit, Linux. +- Qwen3.8-Flash-Next IQ3_S, two pinned GGUF shards. Their SHA-256 values are `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +- Same Strata engine source, `30ec18ec7094550fcc594fd948220d511d80464e`, in both arms. Baseline binary SHA-256: `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. Candidate binary SHA-256: `099c32ce2195385b0367755c25f8e9a9cdf56282980208c6c4879712bbe0e5bc`. +- Context 262,144; INT8 K+V cache with 32,768 resident cells; MTP speculation depth 4; expert cache auto; prefill auto; 700 MiB VRAM reserve. Both arms used the same native pack and GGUF source. The candidate changed only the PLE source to level-2 KAR. +- KAR v4: 55,295,529,472 bytes; source-side SHA-256 `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. Rsync completed successfully and the engine verified KAR payload CRCs when opening it. At the user's request, the separate remote full-file SHA pass was skipped; the remote file's SHA-256 is therefore **not independently confirmed**. +- Arms ran sequentially on one GPU. The concurrent v5 converter was stopped during measured requests and resumed afterward. The model files were on NTFS. Raw private responses and logs remain outside Git under `/home/para/.cache/strata-next/quality-ab-e601cb3/` and `/home/para/.cache/strata-next/cold-ab-770d6a5/` on `rnr5090`. + +## Paired result + +The public synthetic eight-case suite covered arithmetic, retrieval, instruction priority, and tool calls. Five measured repetitions per case followed one warmup. Both arms passed **40/40** measured quality checks, and all **40/40** normalized outputs matched. Candidate-over-baseline median HTTP wall-time ratio was **1.0106** (a larger number is slower). Warm measured prompt-rate ratio was **0.9895** and decode-rate ratio **1.0088**. These short, largely prefix-cached outputs do not establish a decode gain. The single initial 79,258-token request had no prefix-cache reuse: baseline **6,063.9 tok/s, 13.374 s**; candidate **3,884.2 tok/s, 21.196 s**. + +A second suite used three distinct initial 79,259–79,260-token prompts with `cache_n=0` in each arm. The first-request results were: + +| Case | Baseline prefill tok/s | KAR PLE prefill tok/s | Baseline wall s | KAR PLE wall s | Quality | +| --- | ---: | ---: | ---: | ---: | --- | +| alpha | 5,988.1 | 5,332.6 | 13.626 | 15.247 | both pass | +| beta | 6,109.0 | 4,868.3 | 13.233 | 18.969 | both pass | +| gamma | 6,096.9 | 6,102.0 | 13.281 | 14.965 | both pass | + +The median paired candidate/baseline prefill-rate ratio was **0.8905**; the median first-request wall-time ratio was **1.1268**. All three first outputs and all three measured cached outputs matched between arms. This sample supports **no speedup** from the CPU PLE path. The spread is material, so it does not justify a precise slowdown claim or a production quality decision. There was no live agent workload, perplexity test, 512K context test, or test of the full compressed model. + +## Interpretation and next gate + +The candidate still held the ordinary Strata expert cache in VRAM (about 22.19 GiB for 11,697 slots after loading). KAR PLE remained mapped in host memory and was decoded on CPU. This experiment does **not** test compressed expert weights resident in VRAM or CUDA decoding in the serving path. The next useful gate is a bounded compressed GPU cache with the actual transfer, decode, multiply, eviction, and quality costs measured against the same native arm. Until that exists and passes full-model and agent-task quality gates, the testing runtime must remain on its current baseline. + +The original paired reports inherited `profile`, `storage`, and GPU-clock text from an earlier functional smoke metadata file. Those inherited labels do not describe this run. The facts above come from the current run commands, live GPU inspection, logs, and paired reports. The benchmark harness has since been changed to capture live GPU details and exclude those stale labels from future reports. + +## Sparse CUDA row microbenchmark + +The isolated `strata-kar-sparse-row-smoke` read the same v4 archive, checked its payload CRCs, assembled selected PLE rows into a compact packet, uploaded it, and decoded F32 rows on RTX 5090. Row 0's GPU FNV-1a checksum, `c6f74b955ce5a5ae`, matched the independent Rust row decoder. The table uses medians of 1,000 warm CUDA event measurements; host packet assembly was measured separately. Times from different invocations are not paired inference results. + +| Rows | Selection | Packet bytes | F32 upload bytes | Packet H2D + CUDA decode | F32 upload | Host packet build | +| ---: | --- | ---: | ---: | ---: | ---: | ---: | +| 16 | consecutive | 808 | 10,240 | 5.54 µs | 1.60 µs | 0.010 ms first | +| 128 | consecutive | 6,408 | 81,920 | 6.37 µs | 4.16 µs | 0.012 ms first | +| 4,096 | consecutive | 204,808 | 2,621,440 | 21.73 µs | 96.38 µs | 0.052 ms first | +| 4,096 | pseudorandom, seed 42 | 204,808 | 2,621,440 | 21.66 µs | 90.78 µs | 20.61 ms first; 0.369 ms warm median | + +The 4,096-row random sample was drawn from the first 200 million-row PLE part. Its whole-output GPU checksum matched Strata's KAR CPU gather checksum (`00cc55a3da2ef31b`). In the same process and for the same random row IDs, Strata's native IQ4_NL PLE gather had a **0.252 ms** warm median; CPU KAR gather had a **1.327 ms** warm median over five alternated repeats. Native's first gather had 5.485 s of storage page faults, while KAR had been warmed by the full-archive CRC scan, so those first-run times are not comparable. Repeated packet assembly plus its GPU stage was about 0.391 ms, before any scheduler, page-fault, or model integration cost. At this row count and with these cache conditions it did not establish a gain over native gather plus F32 upload. The contiguous-row GPU-stage win is real but is a microbenchmark result, not an agent throughput result. + +The current KAR bit planes place pieces of one random row far apart in the file. A row-oriented or block-oriented layout, or a bounded prepacked cache, is needed before sparse GPU decoding can plausibly improve random-access prefill. Any new layout must include conversion cost, cache residency, quality, and paired end-to-end measurements. + +## Outer LZMA sample + +Three independent 32 MiB slices of the local v4 archive were compressed with Python `lzma` preset `9 | PRESET_EXTREME`. Slices near offsets 1 GiB and 25 GiB shrank to 31,144,624 bytes (7.18% smaller) and 30,949,856 bytes (7.76% smaller). A slice near 50 GiB grew to 33,556,152 bytes. Each slice took about 9–10 seconds to compress. These samples do not predict a full-archive size. LZMA is also not a measured GPU-decodable runtime codec; its storage saving cannot be counted as an inference speedup. diff --git a/docs/experiments/2026-10-03-long-ple-serving.md b/docs/experiments/2026-10-03-long-ple-serving.md new file mode 100644 index 00000000..7ed60046 --- /dev/null +++ b/docs/experiments/2026-10-03-long-ple-serving.md @@ -0,0 +1,83 @@ +# Long-prompt PLE serving control, 2026-10-03 + +## Setup + +An opt-in Linux CUDA engine compared three PLE sources on the same RTX 5090: +native IQ4_NL from the original GGUF, level-2 KAR decoded on CPU, and a +64 MiB compressed KAR row cache decoded on GPU. All other weights used the +same IQ3_S native pack. The host ran NVIDIA driver 595.91.07, CUDA 13.2.86, +and a 600 W reported GPU power limit. The engine binary SHA-256 was +`de121803e66479e64f7976c12540b2d2bc2e31faf78ea3069b1f88f2197575e9`. +Source shard and KAR archive identities are in the +[CPU KAR comparison](2026-10-03-kar-ple-ab.md). The private archive remained +on NTFS; this run checked KAR payload CRCs during startup and did not repeat +a full remote SHA-256 pass. + +The prompt came from public fixture `cold-alpha` in +`benchmarks/fixtures/chat/cold-prefill-v1.json`. It contains a valid audit +code amid decoys and filler, with a required exact final answer. The Rust +tokenizer and a Qwen user/assistant frame produced 79,255 token IDs; +formatted prompt SHA-256 was +`bf5b5803d6b325b31ce640f1b94dd1ceb0bd34c77a697ac34b0b2a2b04165bca`. +Each arm used one 256K slot, INT8 K+V cache with 32,768 resident cells, +MTP depth 4, 11,763 actual expert slots, static expert residency, normal +end-of-turn stopping, and at most 128 output tokens. The native `--serve` +protocol had prompt and conversation reuse disabled. One warmup and two +measured requests ran per arm, in native, CPU KAR, GPU KAR order. Startup +and 55 GB archive verification were excluded from request rates. Raw token +IDs and private engine logs stayed outside Git and were removed after quality +inspection. + +## First measured result + +| PLE source | Median prefill tok/s | Median decode tok/s | Generated tokens | Output-ID hash stable | +| --- | ---: | ---: | ---: | --- | +| Native GGUF | 6,235.5 | 143.4 | 94 | Yes | +| CPU KAR level 2 | 6,223.7 | 148.9 | 100 | Yes | +| GPU KAR level 2 cache | 6,263.6 | 150.1 | 100 | Yes | + +The two GPU outputs were token-exact against the two CPU KAR outputs, but +both KAR arms differed from native at the token level. Decode rates across +native and KAR are therefore **not paired on the same generated sequence**. +GPU-versus-CPU KAR rates differed by less than 1% on this prompt; two repeats +and fixed arm order cannot establish a throughput improvement. Native and GPU +prefill medians differ by about +0.45% in favor of GPU, below a credible +improvement claim with this sample. Decode rates across native and KAR also +have different generated sequences and cannot be treated as matched work. + +The GPU cache reported 3,803,080 hits and 1,112 misses across warmup and +measured requests, a 99.97% hit rate. This repeated-filler prompt has very +high row reuse. The candidate uploaded 55,600 compressed row bytes and +15,279,040 H2D argument bytes in all. These are requested API payload bytes, +not measured PCIe transactions. A highly repetitive prompt may conceal the +cache-miss cost of a varied agent workload. + +## Quality check + +A separate private run captured token IDs for one measured native request and +one measured GPU KAR request after one warmup each. The output hashes were +stable against the first run: native +`4b7bbab11e1ab5b17d5d4af9fba622805418f9fa0bd0c9882d272559c2708af3` +(94 tokens), GPU KAR +`6ad5326860d9111a3b5c3572445870a61d75e2c2fc28be6fb2f24c0b71b0a293` +(100 tokens). Rust detokenization showed different reasoning trajectories, +but **both final answers were exactly `amber-731`**, satisfying the fixture's +required text. This one task passes for both arms. It is not a perplexity, +tool-call, agent-workflow, or broad long-context quality gate. The current +test runtime remains unchanged. + +## Opt-in agent harness profile + +The private `codex-qwen-ctl` model list now includes +`strata-next-kar-ple-gpu`, labeled experimental. Its tracked remote controller +source is `scripts/strata-agent-profile.py`; it selects the level-2 archive, +64 MiB compressed GPU PLE cache, and the unchanged INT8 K+V 1×256K profile. +The launcher entry on the laptop is outside this repository. The durable +Linux engine build SHA-256 is +`f5a2dfb49a7a1c35a6549f41901dabf5505b98c6a5a9b4801ea3d2c70729f0e5`. +The separate server on port 18081 reached readiness, reported context +262,144, and returned HTTP 200, `finish_reason=stop`, content `OK` for a +short Chat Completions smoke. It was then stopped and its temporary logs +removed; the normal Strata endpoint on port 8080 was not changed. No agent +task has yet been run through this GPU profile. The V-only KV profile is not +listed because it has no physical runtime or passing quality gate. diff --git a/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md b/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md new file mode 100644 index 00000000..b9ee69ae --- /dev/null +++ b/docs/experiments/2026-10-03-ordinary-strata-stability-ab.md @@ -0,0 +1,82 @@ +# Ordinary Strata: stability and speed check + +The separately installed ordinary Strata server was tested before and after +client-disconnect and engine-restart fixes. The established native agent +baseline is in the [Three.js agent report](2026-10-03-agent-gpu-kar-threejs.md): +49 model requests, 59 tool calls, 49,854 output tokens, 115.7 weighted decode +tok/s, 634.27 s wall, and 6/6 independent browser checks. The HTTP check +below isolates serving behaviour; it is not a new end-to-end agent result +or a KAR comparison. + +## Setup + +- Linux RTX 5090, driver 595.91.07, CUDA 13.2.2, 600 W power limit. +- Qwen3.8-Flash-Next IQ3_S, two source GGUF shard SHA-256 digests: + `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`, + `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +- Same engine binary for both arms, SHA-256 + `f631b32495440f1dde716734559e757b76f5436c34ca49164cb97bd80b4b18e7`, + build manifest version 0.1.30, source ID `5117b3ee3a6ffbaf`. +- Ordinary Strata HTTP server source: baseline `30ec18e`; patched branch + `stability-client-disconnect-20261003`, commits `ee8c926`, `5361247`, + `9ed8d4d`, `df83985`. +- One 256K slot, INT8 K+V cache, 32K resident KV, MTP `--spec 4`, + `--spec-min-p 0.5`, automatic expert cache, same engine arguments and + model for both arms. +- Identical 124,984-token prompt, `temperature=0`, `max_tokens=512`, + non-streaming Chat Completions. Prompt SHA-256: + `d2edd95ece7ed1530373dbc833efb7ebb553becef2bcde641a132c86b1ee9ce0`. + Each arm starts a fresh server, makes one cold request, then repeats the + request with a warm prefix cache. Arms run sequentially without GPU + contention. Raw, private result files and the benchmark script are under + `/home/para/.cache/strata-next/ordinary-ab/` on the GPU host. The result + JSON contains a prompt digest rather than the prompt body and excludes + credentials. Server logs remain private on that host. + +## Initial five-request A/B + +| Arm | Cold wall | Cold prefill | Warm cache | Warm wall median (p10–p90) | Warm weighted decode | +| --- | ---: | ---: | ---: | ---: | ---: | +| Original | 39.538 s | 124,984 tokens / 22.856 s | 124,979 / 124,984 tokens | 6.938 s (4.807–13.096) | 62.9 tok/s | +| Patched through `5361247` | 31.367 s | 124,984 tokens / 22.840 s | 124,979 / 124,984 tokens | 5.617 s (4.984–6.133) | 95.8 tok/s | + +All requests returned exactly 512 output tokens and `finish_reason=length`. +The two cold-prefill rates were 5,468 and 5,472 tokens/s, respectively. +The four warm requests per arm had substantial decode variation, including +within the original arm. Exact greedy output hashes differed even among +repeats within the same arm, so this run does **not** pass an exact-output +quality gate and does not establish a speed improvement. TTFT was not +captured separately. The initial result is a useful smoke test but too +small for a performance claim. + +## Stability checks + +The patched Python HTTP server cancels buffered and streamed requests when +the client disconnects. If an abandoned engine run does not acknowledge STOP, +cleanup times out and kills the engine instead of holding the single FIFO +indefinitely. An old stdout pump is tied to its own process and queue; a +restart resets the new engine's ended state after process creation so the +old pump cannot revoke it during startup. A 60-second socket-write timeout +also bounds an SSE client that remains connected but stops reading. This +timeout is a mitigation for a plausible delivery stall, not proof of the +exact cause of the earlier incident. + +The ordinary server's `serve.test_disconnect` and `serve.test_server` suite +passed 59 tests. The added tests cover all four OpenAI/Anthropic × +buffered/streaming disconnect cases, STOP timeout, both stdout-pump +restart races, and a client that stops reading SSE while the model is +producing a large response. On the real IQ3_S model, closing a long request while the +slot was processing released the slot in **4.817 s**; a following request +completed with `finish_reason=stop` and 27 output tokens. The temporary +server was unloaded and stopped after the check. + +These fixes bound abandoned-work cleanup and recoverability. They do not +identify the root cause of the earlier 968-second dual-worker stall, which +occurred before client timeout and may involve response parsing or delivery. +The ordinary Python server remains distinct from the Strata Next Rust +control plane. + +An attempted full agent run on the patched ordinary server was interrupted +before completion. It has no comparable task time, token total, or quality +score and is excluded from the table. The isolated server was stopped, GPU +memory returned to 34 MiB, and its temporary credential config was removed. diff --git a/docs/experiments/2026-10-03-ple-cache-batch-capacity.md b/docs/experiments/2026-10-03-ple-cache-batch-capacity.md new file mode 100644 index 00000000..1d019640 --- /dev/null +++ b/docs/experiments/2026-10-03-ple-cache-batch-capacity.md @@ -0,0 +1,47 @@ +# PLE cache batch capacity and serving boundary, 2026-10-03 + +## Capacity guard + +The bounded CUDA PLE row probe now checks the number of **distinct** rows in +each decode batch against its slot count before changing the LRU cache. An +accessed row becomes most recent, so ordinary LRU preserves every row named +by a batch while the batch has at most one distinct row per slot. Without the +capacity check, an overfull batch could reuse a slot still named by an +earlier output position and silently decode the wrong row. The previous +probe's batches had at most 128 rows and its minimum 1 MiB cache had 16,384 +slots; this guard does not change those earlier results. A `slots:N` argument +allows a small capacity to test the boundary without allocating 1 MiB. + +On the Linux RTX 5090 with CUDA 13.2.86 and driver 595.91.07, the private +Qwen3.8-Flash-Next KAR v4 archive was opened with payload CRC verification. +The 4-slot trace `0 1 2 3`, `0 4 5 6`, `6 5 4 0` completed 12 row accesses +with 5 hits, 7 misses, and byte-exact CUDA/independent CPU decoded output in +all three batches. Its output hash chain was `3d7ceb5de9b5faf6`. A separate +5-distinct-row batch with the same 4 slots exited with the explicit +`a batch needs more distinct rows than cache slots` error. Both runs performed +the archive's full payload CRC pass; the valid run recorded 87,635 ms for +that pass. The code was compiled with `nvcc -std=c++17 -arch=sm_120 -O2`. + +The probe accepts `--trust-previously-verified-archive` as an explicit final +argument for repeated development runs. It still parses and checks the KAR +directory but skips the full payload CRC pass. Its output states +`payload_crc_verified=no`; the default remains full verification. This +option is only for a probe against an archive verified earlier in the same +experiment. It is not a serving integrity policy. Repeating the valid trace +with the final source and this option took 2.171 ms to open the archive and +again produced exact CPU parity and hash chain `3d7ceb5de9b5faf6`. The +overfull trace exited with the same error in this mode. + +## Serving handoff + +Three engine consumers require PLE rows. Decode computes 16 row IDs in +`ple_issue_token` and transfers 2,560 F32 values to `PleRun::emb_dev` in +`ple_finish_token`. Prefill gathers 16 IDs per token into one of two pinned +host buffers, then uploads each chunk to `m.ple_emb`. Speculative verification +gathers candidate rows into mapped host memory `h_ple_`, which its captured +graph reads. A serving CUDA cache must cover all three paths or keep an +explicit, quality-checked CPU fallback for verification. It must split a +prefill batch before its distinct-row count exceeds available slots, preserve +the lifetime of asynchronous upload buffers, and account for expert and KV +headroom before allocating VRAM. No serving path uses this probe yet; no +end-to-end speed or model-quality result is claimed here. diff --git a/docs/experiments/2026-10-03-ple-cache-reuse.md b/docs/experiments/2026-10-03-ple-cache-reuse.md new file mode 100644 index 00000000..4b5ef7a5 --- /dev/null +++ b/docs/experiments/2026-10-03-ple-cache-reuse.md @@ -0,0 +1,93 @@ +# PLE compressed-row cache locality screen, 2026-10-03 + +## Question and scope + +The [row-major packet probe](2026-10-03-row-major-ple-probe.md) made small +compressed-row gathers cheaper in warm host RAM. This offline screen asks how +often a bounded GPU cache *might* reuse those rows, and whether admitting +whole 16- or 64-row blocks would waste capacity and transfers. It does not +run inference or measure GPU cache performance. + +Repository HEAD for the screen was `7998f814bc8d431914de9811f594a6d3c7f1533f`. +The PLE hash constants and EOS boundary semantics came from the pinned +`engine/strata/src/kernels/ngram.cpp` and +`engine/strata/include/strata/kernels/ngram.hpp` at that revision. The script +replays the same 16 head indices per token. The target representation is the +private Qwen3.8-Flash-Next IQ3_S KAR v4 archive's level-2 PLE row: 160 values +stored in 50 compressed bytes. This 50-byte value excludes metadata, hash +tables, allocator fragmentation, cache control, and GPU transaction overhead. +The archive provenance is recorded in the [paired KAR report](2026-10-03-kar-ple-ab.md). + +## Inputs and method + +All source text, token IDs, agent events, model assets, and per-row traces +remained outside Git. The script `scripts/ple-cache-reuse.py` stores only +aggregate results. The code corpus was the first 59 sorted tracked source +files with code suffixes from `engine/strata/src`, `control-plane/src`, and `gpu/kar/src`, up to +1,104,686 bytes; its SHA-256 is +`ceaa7f954876bc39f9802965aea8f5599dec3474988f3286acca58cff64189a8`. +The pinned Strata Qwen tokenizer returned 314,064 tokens; the first 262,144 +were analyzed. The private token-array SHA-256 is +`59bcbbfb986eee79086faf1f3fa4f86a1bdd93e9ed0b68e56313b00c98880aad`. + +The other two corpora reconstruct text from completed Three.js agent event +logs: visible reasoning/messages, command text/output, and MCP call +arguments/results. They are **proxies**, not captured model request token +streams. Repeated tool output or serialized fields can exaggerate locality; +omitted system/prompt formatting can shift it. The baseline event file +SHA-256 is `5b939b92e0961274ec99be1fc6661a6566003143bdc053fa9fa442d897a96073`; +it yielded 352,676 IDs from the Rust Qwen tokenizer, of which 262,144 were +analyzed (private token-array SHA-256 +`df3d3521ecce8625d093535c20c0ae889953e9230da750854c1ad804cb0d1474`). The +KAR-ple event SHA-256 is +`f72f686a7e69851b2f3661beb27c7d4f02394565592ac97886631906c683ab47`; +all 80,628 tokenizer IDs were analyzed (private token-array SHA-256 +`c6fd5510ea5efa0e8d44f4dc012624167b7057097a5d1b7aa15d7af231146cb1`). The two arms have different text +lengths and composition, so their hit rates are not a paired performance +comparison. + +For each token the script computes eight bigram and eight trigram PLE row IDs +with the engine's 64-bit wrapping XOR hash. It then simulates fully +associative LRU caches, initially empty, at 64, 256, and 1,024 MiB nominal +compressed-payload budgets. A miss admits either the requested 50-byte row, +the aligned 16-row group (800 bytes), or the aligned 64-row group (3,200 +bytes). `Ideal admission` is miss count times those sizes. It is not measured +PCIe traffic or storage I/O. The simulation assumes free lookups and eviction, +perfect packing, and no GPU cache or producer work. + +| Corpus | Tokens | PLE row accesses | Unique rows | 64 MiB row hit | 64 MiB 16-row hit | 64 MiB 64-row hit | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Tracked code | 262,144 | 4,194,304 | 1,080,010 | 74.25% | 67.82% | 58.41% | +| Baseline agent event proxy | 262,144 | 4,194,304 | 255,930 | 93.90% | 93.76% | 92.32% | +| KAR-ple agent event proxy | 80,628 | 1,290,048 | 383,788 | 70.25% | 67.21% | 57.92% | + +| Corpus | 64 MiB row admission | 64 MiB 16-row admission | 64 MiB 64-row admission | 256 MiB 64-row hit | 1,024 MiB 64-row hit | +| --- | ---: | ---: | ---: | ---: | ---: | +| Tracked code | 54.0 MB | 1,079.9 MB | 5,581.6 MB | 68.26% | 74.92% | +| Baseline agent event proxy | 12.8 MB | 209.4 MB | 1,031.4 MB | 93.83% | 94.05% | +| KAR-ple agent event proxy | 19.2 MB | 338.4 MB | 1,737.2 MB | 67.62% | 71.06% | + +The largest unique-row set occupies 54.0 MB of compressed payload, so the +ideal 64 MiB row cache has no capacity misses in these finite prefixes: its +misses are compulsory. The 16- and 64-row groups also fetch many adjacent +rows never requested. Larger block budgets recover some hits, but the ideal +admission volume remains far above row admission. This argues for +**row-granular GPU admission** or compact packets containing only requested +rows, even if the private on-disk representation uses larger blocks for +indexing and sequential reads. + +## Decision and next verification + +Treat this as a design screen, not evidence of faster inference. Implement a +small bounded compressed-row cache with explicit hit/miss and upload-byte +telemetry, plus eviction under expert/KV pressure. Measure the same token +stream and model output against the native baseline on the Linux RTX 5090. +Capture actual PLE row-ID traces from prefill and decode to repeat the reuse +analysis, especially for 256K/512K contexts and two slots. A quality gate +and paired end-to-end agent runs are required before enabling the path. + +To reproduce with the private token array and pinned source: + +```text +python3 scripts/ple-cache-reuse.py --tokens TOKENS.json --ngram-source engine/strata/src/kernels/ngram.cpp --ngram-header engine/strata/include/strata/kernels/ngram.hpp --max-tokens 262144 +``` diff --git a/docs/experiments/2026-10-03-real-ple-row-trace.md b/docs/experiments/2026-10-03-real-ple-row-trace.md new file mode 100644 index 00000000..33c20560 --- /dev/null +++ b/docs/experiments/2026-10-03-real-ple-row-trace.md @@ -0,0 +1,94 @@ +# Real Strata PLE row trace and bounded CUDA cache, 2026-10-03 + +## Purpose and safeguards + +The [bounded cache smoke](2026-10-03-bounded-ple-cache-smoke.md) initially +used constructed row sequences. This run captured the actual 16 PLE row IDs +computed by an isolated Linux Strata engine while it processed a model +request. The engine change is guarded by the new +`STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` CMake option, whose default is OFF. +Even in that build, a new private `STRATA_PLE_ROW_TRACE_PATH` must be set. +The trace file was created exclusively with mode `0600`; it contained row +IDs, not prompt text or model weights. No installed service, test endpoint, +or original Strata checkout was changed. + +The host was the Linux RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2.86. +The model was Qwen3.8-Flash-Next IQ3_S with the two pinned GGUF shard +SHA-256 values `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` +and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +The native pack and normal K+V, expert, prefill, and speculation settings +came from the private baseline server configuration. The experimental +engine was built from repository base commit `139efbd` plus the trace patch. +The trace-enabled binary SHA-256 was +`91b0c6dc91a2c666b102cc8a55840df06391f8937b2369374b921fdcc9bed3e2`. +The same isolated source was then rebuilt with the trace option OFF. Its +binary SHA-256 was +`1f2f9325539a2a7ee4bc2a547ad0a92582c70d30ab56add56c53092377955a0a`. +That binary contained no trace environment marker and created no trace file. + +The short text-only prompt repeated the same public programming sentence +128 times. The pinned tokenizer produced 2,432 tokens; greedy generation was +limited to 16 new tokens. The process completed with exit code 0. This input +checks capture and decoding on the real model, but its repetition makes it +unsuitable for an agent cache hit-rate or speed estimate. Its first-request +wall time included model loading and trace I/O. The engine reported 2,431 +prefill tokens; the trace held 2,450 data lines (plus one header), including +the prompt and subsequent decode/speculative row calculations. Trace SHA-256 +was `630a7c2dc444afd67174d9979d7f827d40e112ee0f413ea5ae3fd5f908f92c3f`. + +An independent offline hash of the same 2,432 prompt token IDs matched +**all 38,912 row IDs** in the trace's first 2,432 lines, with no shift. +This confirms that the captured indices and line order reflect the pinned +Strata PLE hash for this request. The remaining 18 lines were generated or +speculative work and were not paired with a separate token-ID oracle. +The untraced control processed the same 2,432 prompt IDs and returned the +**same 16 greedy output IDs**. Their little-endian u32 sequence SHA-256 was +`1ec6b37e9ef3cc07a5c84c58437def212a508fd5f5e9c948bd8159be5ad30bc2`. +This is a non-lossy output check for this one short request, not a broader +quality gate or paired throughput measurement. + +## Real trace through the isolated GPU cache + +The full trace contained 39,200 row accesses but only 328 unique IDs. The +ideal 1 MiB row cache screen reported 99.1633% hits; 16- and 64-row blocks +had the same ideal hit rate on this repeated input but admitted 16x and 64x +more compressed payload for the compulsory misses. The 1 MiB screen assumed +50 bytes per slot and free metadata. The CUDA prototype actually reserves +64 bytes per row slot, so its physical capacity is 16,384 rows. Both sizes +are much larger than the 328 unique IDs here. + +`scripts/split-ple-row-trace.py` preserved per-token order and mapped the +global IDs into the archive's two PLE records. The first record had 10 rows +per token, the second six. The split trace SHA-256 values were +`f487da779c5eadbd8adcb028c51b0ee3aeca3c4aab72c99303abe6e70112034d` +and `f40043c0afb5d0d0c4f6b86297e795b910b1894d01a51a6d30bc1fffb1dfe536`. +On each record, `strata-kar-row-cache-smoke` verified the same private KAR +archive's payload CRCs and ran the exact captured row batches through the +compressed 1 MiB VRAM cache and CUDA decoder. + +| KAR PLE part | Batches | Row accesses | Hits | Misses | Compressed bytes admitted | Actual H2D argument bytes | CPU/CUDA values | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | +| 001 of 002 | 2,450 | 24,500 | 24,298 | 202 | 10,100 | 109,312 | Exact for every batch | +| 002 of 002 | 2,450 | 14,700 | 14,574 | 126 | 6,300 | 65,856 | Exact for every batch | + +The H2D byte column counts update records and per-batch slot IDs; it excludes +the one-time eight-byte codebook upload and CUDA driver transaction overhead. + +The KAR archive's source-side SHA-256 was +`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; +as [previously recorded](2026-10-03-kar-ple-ab.md), the remote file was not +separately SHA-checked. The archive CRC pass took 115.6 s and 90.4 s in the +two separate invocations. The CUDA-event stage sums were 10.55 ms and +9.80 ms across 2,450 batches per part. They exclude archive verification, +CPU LRU planning, output readback, reference decoding, PLE projection, and +the rest of inference; pageable input memory may add host-side staging not +represented by those events. They are not paired A/B request timings. + +The captured row sequence and both CUDA outputs establish a concrete +functional path from real model PLE indices to bounded compressed-VRAM +admission and exact CPU/CUDA reconstruction. The CUDA cache is still a +separate executable, not the serving PLE consumer. The prompt's heavy +repetition, absent expert/KV contention, and lack of a paired quality suite +prevent any inference speed or model-quality claim. Next, capture a varied +agent or code prompt, wire the cache into serving, then run paired end-to-end +speed and quality gates before considering a test-runtime switch. diff --git a/docs/experiments/2026-10-03-row-major-ple-probe.md b/docs/experiments/2026-10-03-row-major-ple-probe.md new file mode 100644 index 00000000..80d30632 --- /dev/null +++ b/docs/experiments/2026-10-03-row-major-ple-probe.md @@ -0,0 +1,58 @@ +# Row-major PLE packet assembly probe, 2026-10-03 + +## Purpose and setup + +The earlier [expert-cache pressure test](2026-10-03-expert-cache-pressure.md) +showed that keeping one 10 GiB compressed PLE record in 32 GB of VRAM +displaces 5,257 expert slots. This isolated probe asks whether a row-oriented +layout can instead assemble **small compressed packets** fast enough for GPU +transfer and CUDA decoding. + +On the Linux RTX 5090, NVIDIA driver 595.91.07, a private Qwen3.8-Flash-Next +IQ3_S KAR v4 archive was opened with full payload CRC verification. The same +first PLE part, level 2, and deterministic random row IDs (seed 42) were used +in both arms. The code was built with CUDA 12.8.1 for `sm_120`. The archive's +model provenance and quality limits are in +[the prior paired report](2026-10-03-kar-ple-ab.md). + +The control arm assembled row packets directly from KAR's separate scales and +bit-plane regions. The candidate transposed **all 200 million rows of this +part** into a 10,000,000,000-byte private RAM array: five scales and two sets +of five bit-plane words per 160-value row, or 50 bytes/row. The candidate +then assembled the same GPU packet from that array. The CUDA upload and +decoder were identical in both arms. No secondary archive was written and no +10 GiB GPU allocation was made. The RAM array is an **upper bound** for a +future row-oriented on-disk layout, not a deployable bounded cache. + +| Rows per request | Source layout | First packet build | Warm packet build median | GPU upload + decode median | Packet bytes | F32 checksum | +| ---: | --- | ---: | ---: | ---: | ---: | --- | +| 16 | Current KAR | 0.1140 ms | 0.000280 ms | 0.005952 ms | 808 | `37855ae97b50a8cf` | +| 16 | Row-major RAM | 0.00245 ms | 0.000080 ms | 0.005952 ms | 808 | `37855ae97b50a8cf` | +| 4,096 | Current KAR | 20.371 ms | 0.163799 ms | 0.021664 ms | 204,808 | `00cc55a3da2ef31b` | +| 4,096 | Row-major RAM | 1.036 ms | 0.027480 ms | 0.021632 ms | 204,808 | `00cc55a3da2ef31b` | + +The 4,096-row checksum also matched the independent CPU KAR gather in the +[resident-row experiment](2026-10-03-gpu-resident-rows.md). The 16-row control +and candidate matched each other byte for byte, including each row checksum. +One-time row-major RAM construction took 2.37–3.97 s per invocation **after** +the archive scan; archive verification itself took 80–86 s. Neither cost is +included in packet or GPU stage timings. Each arm and row count had one +invocation with 100 warm GPU repetitions and five warm packet builds. These +short kernel timings do not establish end-to-end throughput. + +For 4,096 scattered rows, the row-major array cut warm host packet assembly +from 0.164 to 0.027 ms. For a 16-row token it cut first assembly from 0.114 +to 0.00245 ms, while the warm GPU stage stayed around 5.95 µs. Direct F32 +upload of 16 rows took about 1.47 µs in this same smoke target, but that +comparison excludes the original PLE table's CPU read/dequantization. The +row-major array consumes 10 GB of **host RAM**, and all requests came from +warm memory after an archive-wide CRC scan. Cold random storage reads, PLE +projection, expert/KV cache interaction, scheduler overhead, and model +quality were not measured. + +The next artifact should encode small row-major blocks inside a verified, +provenance-bound model format. A bounded GPU cache can then admit only +requested compressed blocks, decode them on the PLE stream, and evict them +without sacrificing most expert slots. Before choosing block size or a +production path, measure real PLE row reuse, cold storage page faults, full +request latency, and model/tool-call quality against the native baseline. diff --git a/docs/experiments/2026-10-03-serving-gpu-ple.md b/docs/experiments/2026-10-03-serving-gpu-ple.md new file mode 100644 index 00000000..a6a30640 --- /dev/null +++ b/docs/experiments/2026-10-03-serving-gpu-ple.md @@ -0,0 +1,139 @@ +# Experimental GPU PLE cache in Strata serving, 2026-10-03 + +## Scope and implementation + +This is an opt-in PLE-only integration into the Linux CUDA Strata fork. The +normal expert, projection, embedding, and KV paths still use the native pack. +`--ple-kar ARCHIVE --ple-kar-level 2 --ple-kar-gpu-cache-mib N` keeps selected +50-byte compressed PLE rows in bounded 64-byte VRAM slots, uploads only cache +misses, and decodes requested rows into the existing F32 PLE consumer buffer +on CUDA. Prefill and ordinary token decode use it. Speculative verification +still gathers the same KAR rows on CPU because its captured graph reads mapped +host memory. The option is disabled by default. + +The CUDA component owns pinned update and slot-ID staging buffers. It waits +for its previous CUDA completion event before reusing them, including when +callers change streams. An overfull batch is rejected before mutating LRU +state; the engine divides a prefill gather by slot capacity so a small cache +can proceed. The archive is payload-CRC-verified before the cache opens. This +does not constitute full compressed-weight serving or a model quality gate. + +## Correctness on the target GPU + +Hardware was a Linux RTX 5090, NVIDIA driver 595.91.07, CUDA 13.2.86 and a +600 W reported power limit. The private Qwen3.8-Flash-Next IQ3_S KAR v4 +archive and source-shard identities are recorded in the +[CPU KAR comparison](2026-10-03-kar-ple-ab.md). The test preserved the verified +source shards and archive on the external model volume. + +An isolated component probe read rows on both sides of the boundary at global +row 200,000,000. Across three batches and 18 accesses it produced a byte-exact +CUDA/independent CPU match, with 8 hits and 10 misses in a 1 MiB cache. The +probe also rejected a batch with more distinct rows than slots. The archive's +payload CRCs passed. + +The integrated engine probe then gathered 32,768 adjacent rows starting at +199,990,000, crossing the same part boundary. Its 1 MiB cache had 16,384 +slots, so the engine issued two CUDA batches. The complete F32 output matched +the engine's CPU KAR gather byte for byte; FNV-1a64 was +`7e6a191b508d0461`. This probe had zero cache hits and 32,768 misses by +design, and uploaded 1,966,080 argument bytes. It checks the small-cache +batch split and the two-part row mapping. + +After lifting the prefill gather's 4,096-token guard, a final engine build +compared 65,552 rows (4,097 tokens) from the same start row, again crossing +the part boundary and splitting over the 16,384-slot cache. CPU/CUDA F32 +output was byte-exact, FNV-1a64 `450b9dc4bfd7320d`; zero hits, +65,552 misses, 3,277,600 compressed row bytes, and 3,933,120 H2D argument +bytes were reported. This covers a prefill batch larger than the old guard. +The final rebuilt engine binary SHA-256 was +`f00569d3071577d3f9ecb0bc92d3f9f86c4b1eb7ca0059b1443f52b7410874ed`. + +## First full-model functional pair and order reversal + +One process per arm used a 2,048-token synthetic prompt containing token IDs +1 through 2,048, 16 greedy output tokens, one 256K context, INT8 K+V with +32,768 resident cells, MTP depth 4, the same native pack and source GGUF +shards, and a 64 MiB GPU PLE cache in the candidate. CPU KAR and GPU-cache +arms ran sequentially. The first pair used `--expert-cache 10000`; profile +packing made the actual expert counts differ (12,691 CPU, 12,656 GPU), so it +is a functional comparison only. Both arms produced the same 16 output IDs, +SHA-256 `b4dd327bdcee9ad184003caf38747352ca5689b9208d2b46ef366fa1f50147a6`. + +The next four runs used `--expert-cache 9000`, resulting in **11,763 expert +slots in every arm**. The order was GPU, CPU, CPU, GPU. All four produced the +same 16 greedy IDs. The process binary for this four-run sequence was SHA-256 +`a27d1fc9c9f240d499346f93c1f184c7d30c076819af66691ceac0cd6b4a9b9c`. + +| Order | PLE arm | Prefill tok/s | Decode tok/s | PLE time within prefill | Output IDs | +| ---: | --- | ---: | ---: | ---: | --- | +| 1 | GPU cache | 67.34 | 34.68 | 29,278.2 ms | Same | +| 2 | CPU KAR | 1,970.40 | 78.73 | 214.0 ms | Same | +| 3 | CPU KAR | 2,182.63 | 89.41 | 138.9 ms | Same | +| 4 | GPU cache | 640.16 | 75.59 | 2,429.9 ms | Same | + +The GPU arm saw 32,752 PLE row accesses with only **3 hits** in each run. +Its 32,749 misses admitted 1,637,450 compressed bytes and sent 1,964,952 +argument bytes across H2D, versus 20,961,280 F32 PLE bytes in the CPU +prefill upload. Those are API payload sizes, not measured PCIe transactions. +The lower transfer size did **not** translate into a demonstrated speedup: +random reads and host packet assembly from the NTFS archive dominated this +low-reuse prompt. Arm order and file-cache state changed PLE time by orders +of magnitude. The final warm-order GPU arm was slower than the adjacent CPU +arm, but these one-shot runs cannot isolate the cache's own steady-state +effect. The prompt is synthetic and does not judge task quality. + +## Repeated requests in a loaded process + +The native `--serve` protocol ran each arm in one process, with two warmup +requests and five measured requests per prompt, `--prompt-cache 0`, and +`--conversation-cache-mib 0`. The same 11,763 actual expert slots, 256K +context, INT8 K+V, 32,768 resident cells, MTP depth 4, native pack, KAR +archive, and 64 MiB candidate cache were used. One synthetic prompt had +2,048 distinct token IDs; the other repeated IDs 1–128 sixteen times. CPU +started first. Every corresponding CPU/GPU request produced the same output +IDs and finish reason. For the repeated prompt, output length changed within +*both* arms in the same request order (16, 16, 16, 3, 3); this test therefore +does not establish deterministic output for repeated requests. + +| Prompt | CPU median prefill tok/s | GPU median prefill tok/s | CPU median prefill ms | GPU median prefill ms | CPU/GPU median decode ms | +| --- | ---: | ---: | ---: | ---: | --- | +| Distinct IDs | 2,978.0 | 3,027.8 | 687.7 | 676.4 | 22.3 / 21.9 (2 generated tokens) | +| Repeated IDs | 3,010.9 | 3,037.2 | 680.2 | 674.3 | 151.5 / 150.0 (mixed output lengths) | + +The measured prefill-rate differences are approximately +1.7% and +0.9%. +Five repeats per arm, fixed startup order, synthetic prompts, and short or +unstable generations do not establish a repeatable performance gain. + +## Reversed-order 128-token control + +A second same-process sequence started GPU first, then CPU. Both arms used +`--adapt-swaps 0` for static expert residency and an unreachable EOS ID so +each request completed 128 output tokens. Each prompt had two warmups and +five measured repeats, with prompt/conversation reuse disabled. Actual +expert slots were 11,763 in both arms; the binary SHA-256 was +`0566013995d6d8b2fdf817bbe9e6fcbb6a1d7c0f756d2a4382967be9fcaef6de`. +All 10 CPU/GPU output pairs were token-exact (20 outputs total), and each +prompt's five output hashes were stable within both arms. Draft acceptance +matched exactly: 71/108 for distinct IDs and 90/108 for repeated IDs. On the +final repeated +request, both arms reported 83.2% decode expert-cache hits (54,326/65,298) +and 99.29% KV-streaming hits (918,060 block reads; 26.3 MiB from RAM). + +| Prompt | Arm | Median prefill tok/s | Median decode tok/s | Median prefill ms | Median decode ms | +| --- | --- | ---: | ---: | ---: | ---: | +| Distinct IDs | CPU | 2,984.6 | 133.04 | 686.2 | 962.1 | +| Distinct IDs | GPU | 3,035.4 | 133.70 | 674.7 | 957.4 | +| Repeated IDs | CPU | 3,015.3 | 147.75 | 679.2 | 866.3 | +| Repeated IDs | GPU | 3,032.7 | 148.29 | 675.3 | 863.2 | + +Paired GPU/CPU rate ratios over five repeats were 1.0146–1.0181 for distinct +prefill, 1.0041–1.0075 for distinct decode, 1.0053–1.0080 for repeated +prefill, and 1.0029–1.0058 for repeated decode. These narrow within-process +ranges are encouraging but are smaller than startup/file-cache variation +between processes. There were only five pairs per prompt, synthetic 2K +prompts, and no native PLE arm in this control. The earlier native-versus-CPU +KAR test found no overall gain. We therefore keep the GPU path experimental +and make **no accepted end-to-end speedup claim**. A real 256K agent +workload, tool-call quality gate, at least 30 pairs for a 1% claim, cold/warm +stratification, and whole-model GPU memory-pressure measurement remain open. diff --git a/docs/experiments/2026-10-03-v-only-screen.md b/docs/experiments/2026-10-03-v-only-screen.md new file mode 100644 index 00000000..7d1ca443 --- /dev/null +++ b/docs/experiments/2026-10-03-v-only-screen.md @@ -0,0 +1,105 @@ +# V-only KV feasibility screen, 2026-10-03 + +## Question and scope + +**Methodology correction:** this custom V→K regression screen is not a +replication of the cited Keyless Attention method. Its results cannot be +used to judge that method or the quality effect of physically removing K. +The cited [Keyless Attention paper, §§2.2–2.4 and §4](https://arxiv.org/html/2606.21848v1) +uses a dedicated value-space query-routing projection and trains its +evaluated models from scratch. Exact conversion of existing multi-head +weights has an explicit subspace condition. Our earlier small activation +regressions did not establish that condition or implement that routing. + +Can the full QSA attention key be replaced by a cheap transform of the cached +value? This is an **offline activation and attention screen**, not a V-only +serving run. The normal K+V cache remained allocated in every model run. The +separate QSA indexer keys were unchanged. The user goal requires model quality +and throughput with a real V-only cache; these data only reject the simple +candidate studied here. + +The host was the Linux RTX 5090 (driver 595.91.07, CUDA 13.2) and the same +Qwen3.8-Flash-Next IQ3_S shards and Strata source as +[the paired report](2026-10-03-kar-ple-ab.md). Greedy runs used `--kv int8`, +one 4K context slot, `--kv-resident 4096`, `--expert-cache 8192`, +`--prefill 512`, `--spec 4`, and 160 output tokens. The short context makes +this a screening experiment, not the charter's 256K quality gate. + +An opt-in debug build copied K, V and Q activations from Strata's ordinary +speculative verifier into private files. Only the first token of each verifier +window was used, excluding speculative draft rows. The second prompt's 160 +greedy output IDs were **identical** between the original engine, the K/V +trace build and the final K/V/Q trace build. A first attempt to copy Q before +the attention kernel changed output IDs after token 26; those measurements +were discarded. Moving the diagnostic copy after attention restored all 160 +greedy IDs. Trace collection is refused in `--serve` and for more than 512 +generated tokens. + +## Reconstruction on held-out activations + +For each of 12 QSA layers and two KV heads, the candidate learned an +independent affine 2×2 map for every adjacent V pair to predict the +post-normalization, post-RoPE K pair. This is 128 small maps per head, fitted +with ridge regularization on the first coding prompt. It was compared with +directly copying V into K and with predicting each K dimension by its +training mean. The independent second coding prompt had 51 captured verifier +windows; the first had 57. Lower relative L2 error is better. + +| Held-out K predictor | Relative L2 error | +| --- | ---: | +| Copy V | 1.0933 | +| Per-dimension training mean | 0.8595 | +| Learned 2×2 V→K maps | 0.8788 | + +A within-prompt 34/23-window split also gave 0.8685 for the learned maps +versus 0.8537 for the mean. Thus the proposed small transform did not beat +the mean-K control in either split. + +## Attention proxy on real Q activations + +Using an independent, output-parity-checked trace of the second prompt, +offline attention compared each real Q with only the earlier generated-token +keys captured by this diagnostic. It did **not** include the complete prompt, +QSA indexer's selected cells, cache quantization, or the rest of the model. +Across 13,248 head/query comparisons, the results were: + +| K proxy | Best-key agreement | Mean top-5 overlap | Attention-output relative L2 | +| --- | ---: | ---: | ---: | +| Copy V | 5.87% | 27.51% | 0.3680 | +| Learned 2×2 V→K | 8.07% | 31.19% | 0.3555 | +| Position-aware 2×2 V→K | 10.74% | 35.21% | 0.3479 | +| Position-aware ridge V→K | 26.77% | 55.02% | 0.3023 | + +The third candidate removes the model's default, unscaled NeoX RoPE +(64 rotated dimensions, base 10 million) from calibration K before fitting +the same per-pair map, then applies RoPE at each held-out position to the +predicted K. It used the same 57 calibration and 51 independent held-out +verifier windows, and the same 13,248 attention comparisons. The new result +was reproduced by `scripts/kv-keyless-attention.py --rope-base 10000000`. +The fourth candidate fits a full per-layer, per-head linear V→unrotated-K map +with ridge regularization. Ridge strength was chosen solely within the +calibration trace using a chronological training/validation split, then +refitted on all 57 calibration windows. No held-out rows selected its +strength. It improved this limited attention proxy, but a 30.2% relative +attention-output error and 26.8% best-key agreement remain far from a +demonstrated quality pass. + +These errors concern only the custom predictors tested above. They do not +evaluate the paper's trained query-routing method. `Wq_keyless` conversion, +its treatment of Q/K normalization and RoPE, and a physical V-only runtime +were not implemented. No V-only memory, agent quality, or runtime speed +was measured. + +The maximum **theoretical** saving from deleting INT8 K codes and scales in +the current QSA layout is 528 bytes per token per QSA layer: 198 MiB of +resident VRAM for one 32,768-cell slot, 396 MiB for two such slots, plus up to +1.547 GiB of host mirror at 256K context per slot. The independent indexer +keys and page tables still use memory. A keyless transform or corrective +residual would have its own cost. + +The private prompts, K/V/Q traces, output IDs, and numerical reports remain +outside Git under `/home/para/.cache/strata-next/keyless-feasibility/` on the +GPU host. The repository contains only the opt-in diagnostic capture and +offline analysis scripts. The next candidate needs a held-out attention +quality pass before implementing a physical V-only cache; then it needs real +256K model output, tool-call, and agent-task comparisons against K+V. diff --git a/docs/experiments/2026-10-04-bounded-admission.md b/docs/experiments/2026-10-04-bounded-admission.md new file mode 100644 index 00000000..5e5d4b5f --- /dev/null +++ b/docs/experiments/2026-10-04-bounded-admission.md @@ -0,0 +1,50 @@ +# Bounded native HTTP admission — STRA-28 + +Date: 2026-10-04. POST `/v1/responses` now reserves a request slot before +parsing/tokenization, through response-body completion/drop. The validated +`max_in_flight_requests` setting defaults to 17 (one active request plus the +existing 16-command queue), range 1–256; `STRATA_MAX_IN_FLIGHT_REQUESTS` +overrides JSON. A full runtime rejects new requests with 429 +`runtime_overloaded` and `Retry-After: 1`. Authentication runs first; drain's +503 takes precedence. Accepted work keeps its existing protocol and queue. + +`/admin/lifecycle` exposes maximum and available request capacity; native +`check-config` reports the configured limit. Health, management and stored +response routes remain outside this admission gate. Overload does not change +readiness. See [the API contract](../api-contract.md#admission-lifecycle). + +## Evidence + +- Rust 1.99.0: all 136 library tests passed. A new 32-thread reservation test + admits exactly three requests at capacity three and recovers all capacity + after drop. Existing body/trailer/drop and STOP-cleanup lifecycle tests pass. +- Clippy all-targets with warnings denied, fmt and diff checks passed. +- `smoke-native-drain.py` passed on macOS debug and Linux x86_64 musl release: + capacity two holds one active SSE and one queued JSON request. An unauthorized + malformed request gets 401; an authorized malformed request gets 429 before + parsing, including Retry-After. Drain then returns 503 at the same capacity. + Both accepted requests produce exactly `OK` (zero text tolerance), with + contiguous SSE sequence numbers and terminal completion. After release and + resume the next request succeeds; exactly three generations start overall. +- `smoke-config-check.py`: 26 cases passed on both platforms, including default + 17, explicit file capacity, valid boundaries 1/256, invalid 0/257, and environment + precedence. Preflight never launched the synthetic worker or acquired the + occupied listener. Both scripts already run in the Linux workflow; hosted + GitHub Actions has not run. + +Private control-plane preview on the laptop: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-admission-preview`, +**17,383,592 bytes**, SHA-256 +`da014544322555658ab81f77c97f4abc4b8a5cee4836358119d65e9cfd87baee`. +Its adjacent private JSON records source revision and checks. The active GPU +trial was not upgraded or restarted: PID 4031422/start ticks 558428413 remained +unchanged and the existing tunnel still returned ready. No inference was sent +to that trial. The isolated Linux CPU fixture directory and release build +intermediates were removed after verification; the private final binary remains. + +This bounds admitted HTTP handlers, not GPU slots, TCP connections, total +memory or generation jobs. A cancelled HTTP request may release its slot while +the worker finishes STOP cleanup under a separate generation guard. The engine +remains serial; neither batching nor performance improvement is claimed. +Real-model parity and long-running user-trial qualification for this candidate +remain pending. Development is ready for QA, not an independent QA pass. diff --git a/docs/experiments/2026-10-04-config-preflight.md b/docs/experiments/2026-10-04-config-preflight.md new file mode 100644 index 00000000..4804040b --- /dev/null +++ b/docs/experiments/2026-10-04-config-preflight.md @@ -0,0 +1,62 @@ +# Native configuration preflight — STRA-25 + +`strata-next check-config [--config FILE]` validates deployment inputs without +starting a worker or binding a listener. It uses the production configuration, +key and tokenizer readers. External executables require regular-file and execute +access; bare names are searched in PATH. Embedded selection checks Linux and +payload availability without materializing it. Output excludes credentials, +arguments and raw config data; failures use fixed stage diagnostics. + +## Verification on 2026-10-04 + +- Rust 1.99.0: 134 library tests passed; all-target Clippy with warnings denied, + formatting and diff checks passed. +- `python3 scripts/smoke-config-check.py ` passed **18 checks** on both + macOS (debug) and Linux rnr5090 (x86_64 musl release). Checks include an occupied + bind port, worker execution marker, real synthetic tokenizer assets, explicit + config precedence, environment overrides, PATH/relative executable lookup, + missing/non-executable engine, missing payload, invalid tokenizer, key-file + permissions and malformed config/argument/tokenizer credential-echo rejection. +- Linux embedded CPU fixture passed the new positive embedded preflight check, + then existing sealed-memfd, READY, HTTP generation, crash restart and cleanup + tests. Embedded and external fixture outputs were exactly `A` (zero tolerance). +- The hosted Linux workflow now invokes the config smoke before packaging the + synthetic embedded worker. Hosted GitHub Actions have not run. + +Private control-plane preview: `~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-preflight-preview` +on the laptop; **17,314,312 bytes**, SHA-256 +`774c5c8f8c16ddd09d1fcb075865c243a086ee8a4fee5a657f3b4fa24bb8bb68`. +It contains no embedded engine and is not installed over the user trial. +Its adjacent JSON records the source commit. Temporary fixture binaries, remote +smoke directory and release build intermediates are removed after checking. + +This is a point-in-time input check. It does not verify ELF dependencies, driver, +model weights, port availability, GPU behavior or generation quality. JSON always +reports `readiness_checked: false`; `inference_configured` only indicates both +worker and tokenizer are configured. The active native endpoint and tunnel were +preserved and reported ready; that observation is not an idle-request assertion. + +## Controller integration — STRA-26 + +`qwen-codex-ctl native-service check-config` now invokes an explicit remote +candidate with required `--binary`, `--config`, `--working-dir` and optional +`--host`. Paths are passed as quoted positional shell arguments. The client +uses a 64 KiB stdout cap, a 30-second local SSH deadline and discards stderr; +only validated report fields are returned. It neither changes the selected +connection nor invokes systemd. It uses the SSH login environment, without +sourcing service environment files. + +Verification: 13 native-service tests and 8 native-API tests passed. New tests +exercise actual shell interpretation of paths containing spaces, quotes, dollar +and command-substitution syntax, selector/parser rejection, malformed or oversized +reports, credential-echo suppression, transport output bounds and a simulated +deadline. Installer execution twice left the launcher and 19 profile files +byte-identical. + +The installed controller passed a real SSH check against the private Linux +preflight preview with synthetic tokenizer/configuration and a marker executable. +The config named the already occupied trial port 18082; validation succeeded, +the marker was never created, and invalid config failed without echoing its +fixture secret. Active PID 4031422/start ticks 558428413, readiness and tunnel +were preserved. The isolated remote files were removed afterwards. No model, +GPU, performance or independent-QA qualification was performed by this check. diff --git a/docs/experiments/2026-10-04-console-readiness.md b/docs/experiments/2026-10-04-console-readiness.md new file mode 100644 index 00000000..e6a3ceed --- /dev/null +++ b/docs/experiments/2026-10-04-console-readiness.md @@ -0,0 +1,56 @@ +# Console readiness waiting — STRA-34 + +Date: 2026-10-04. `qwen-codex-ctl native-api wait-ready --wait SECONDS` +provides a read-only model-readiness gate after service startup. It works with +both the retained native trial and newer candidates. It never starts or stops a +service, switches profiles, opens a tunnel, or invokes inference. + +```sh +qwen-codex-ctl native-api wait-ready --wait 60 +# Explicit endpoint without changing the selected connection: +qwen-codex-ctl native-api wait-ready \ + --url http://127.0.0.1:18084 --no-auth --wait 5 +``` + +The selected native connection supplies its private key when configured; an +explicit URL requires explicit authentication choice. Every status response is +validated for native identity, Boolean readiness and worker state. Readiness +must agree with a ready worker. Connection failures and starting/restarting +states are retried. Authentication/HTTP/JSON failures, malformed status and +failed/stopping/unconfigured worker states fail immediately. + +A positive budget starts before the first request. Polls are 250 ms apart; +individual socket timeouts are capped at the remaining budget and eight seconds. +Late responses do not count as success. Zero/omitted wait makes one check. +Socket timeouts do not provide a hard total deadline against a server that keeps +sending partial bytes. Readiness is an instantaneous observation, not idle state, +model quality, completed work or sustained stability. + +## Evidence + +- `python3 scripts/test-native-api.py`: all 12 tests passed on macOS and Linux. + New coverage includes connection/startup/recovery progression, correct bearer + forwarding, only GET status calls, zero-wait behavior, budget including initial + request time, late-result rejection, terminal/malformed state rejection and + fail-fast nonconnection errors. A real local HTTP fixture transitions from + starting to ready under authentication without echoing its test key. +- CLI parsing and existing URL/auth rules pass. Installer coexistence, + idempotence and unrelated-file protections remain covered. +- `python3 scripts/test-native-service.py`: all 13 tests passed on macOS and + Linux. Existing service-controller behavior is unchanged. +- `scripts/check-local.sh`, already invoked by the Linux workflow, includes both + test files. Hosted GitHub Actions has not run. Rust/engine code was unchanged + and was not rebuilt for this client-only feature. +- Installed the helper through `scripts/install-qwen-native-api.py`. Reinstall + was idempotent; the launcher and 19 profile/configuration files across ordinary + and isolated trial profiles retained their byte digests. No private content + was printed or committed. +- The installed command against the existing tunnel at `127.0.0.1:18084` + returned `connection_changed: false`, native model `strata-native-iq3-s`, + `worker: ready`, and `ready: true`. This used only GET status; no GPU generation + or administrative mutation was sent. +- Owned remote CPU-test directory and local test bytecode were removed after + verification. Final source, report and installed helper remain available. + +The active runtime and tunnel remain unchanged. This feature is ready for +independent QA; the checks do not establish long-term server stability or speed. diff --git a/docs/experiments/2026-10-04-custom-regex.md b/docs/experiments/2026-10-04-custom-regex.md new file mode 100644 index 00000000..37aa0544 --- /dev/null +++ b/docs/experiments/2026-10-04-custom-regex.md @@ -0,0 +1,50 @@ +# Custom regex input validation preview — STRA-30 + +Date: 2026-10-04. Native Responses accepts regex-format custom tools and validates +the complete generated input before publishing a callable item. The lowered +Qwen input schema includes the regex as prompt guidance. The feature supports +top-level and namespaced tools, JSON/SSE, reasoning and continuation, preserving +input bytes and public identities. + +This is **output validation, without constrained token sampling**. Invalid output +fails the response; there is no automatic repair or retry. Lark remains rejected. +The wire shape follows the official [custom tool grammar documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg), +read for this implementation. Exact supported syntax and resource limits are in +[the API contract](../api-contract.md#regex-custom-input-validation-preview). + +## Evidence + +- All 140 Rust library tests passed. New catalog checks cover whole-string + alternation, exact Unicode/newline/whitespace, namespaces, empty-input match + semantics, malformed patterns, unsupported lookarounds/backreferences/lazy and + verbose/swap-greed syntax, oversized definitions, compiled-size rejection and + aggregate request limits. Existing function/text custom and replay tests pass. +- Clippy all-targets with warnings denied, fmt and diff checks passed. The + first Clippy run found test-module placement; moving it to the end resolved it. +- `smoke-custom-tools.py` passed on macOS debug and Linux x86_64 musl release. + Each run executes 22 CPU fixture generations: four prior text-tool cases, + text continuation, sixteen regex cases (valid/invalid × namespaced/top-level × + reasoning none/low × JSON/SSE), and regex continuation. +- Accepted input matched the exact multiline Unicode source (zero tolerance). + Invalid buffered calls returned 502 without output; invalid SSE ended with + `response.failed`, contiguous sequence numbers, no custom call item events and + no custom input delta/done events. Invalid grammar declarations returned 400 + without starting a generation. Continuations returned exactly `OK`. +- The expanded smoke remains in the Linux workflow. Hosted GitHub Actions has + not run. `regex` 1.13.1 and `regex-syntax` 0.8.11 were already in Cargo.lock; + this change makes them direct dependencies without upgrading package versions. + +Private preview: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-regex-preview`, +**17,449,504 bytes**, SHA-256 +`183fcdcce766244662bcf49cfe25dd1b3942586b138b97eb9602169db4d369f6`. +Adjacent private JSON records source revision and gates. The temporary Linux +fixture directory and release intermediates were removed; the final binary +remains private. The active GPU trial and tunnel were preserved, with no inference +or management mutation sent to that service. + +Real-model grammar-following quality, latency and sustained stability are not +qualified. Compilation/cache bounds do not imply a total process memory bound. +Historical inputs are not revalidated under later tool definitions. Earlier valid +calls/text in an SSE stream cannot be retracted when a later call fails. +Development is ready for QA; this candidate does not replace the qualified trial. diff --git a/docs/experiments/2026-10-04-generation-deadline.md b/docs/experiments/2026-10-04-generation-deadline.md new file mode 100644 index 00000000..48afe144 --- /dev/null +++ b/docs/experiments/2026-10-04-generation-deadline.md @@ -0,0 +1,56 @@ +# Optional active-generation deadline — STRA-29 + +Date: 2026-10-04. The control plane supports an operator-selected absolute +execution deadline through `engine.generation_timeout_s` or +`STRATA_GENERATION_TIMEOUT_S`, integer 1–86400 seconds. Omission leaves it +disabled. Native preflight reports the effective value. The clock covers the +active worker command, including blocked stdin and result-channel backpressure; +it excludes parsing, tokenization and queue wait. + +Timeout revokes readiness and kills/reaps the worker before bounded failure +delivery and the existing finite restart policy. Neither the interrupted request +nor queued work is replayed. A consuming client receives JSON 502 +`generation_failed` or terminal SSE `response.failed`. See the +[API contract](../api-contract.md#active-generation-deadline) for slow-client +delivery limits and [deployment notes](../../deploy/README.md#worker-recovery). + +## Verification + +- Rust 1.99.0: full 137-test library suite passed, including the new full-channel + deadline test. The subsequently added blocked-stdin regression and full-channel + test both passed together (138 distinct library tests now present). Clippy + all-targets with warnings denied, fmt and diff checks passed. +- The blocked-stdin test sends a command larger than pipe capacity to an engine + that does not read. Its 100 ms deadline yields explicit failure and a failed + worker. The full-channel test does not consume tokens until the supervisor + exits: cleanup still completes, failure counts once, generation activity is + released, and the channel closes after its buffered token. These are timeout + acceptance tests, not speed measurements. +- `smoke-generation-deadline.py` passed four HTTP cases on macOS debug and Linux + x86_64 musl release: streaming/non-streaming crossed with restart budget 0/1. + Every stalled command terminates with failure, original PID is gone, readiness + is revoked, queued work is not executed, and generation activity returns to zero. + Restart-enabled cases serve a fresh request with exact output `OK` (zero text + tolerance). SSE event numbering stays contiguous without a completed event. +- `smoke-config-check.py` passed 35 cases on each platform, including absent + deadline, valid 1/86400 bounds, invalid 0/86401, JSON configuration and environment + precedence. The new HTTP smoke is wired into Linux CI; hosted Actions has not run. +- A first development run exposed changed crash-channel semantics; failure + delivery was restricted to deadline expiry, and the original crash/no-replay + regression then passed in the full suite. Existing cancellation and shutdown + tests also pass with deadlines disabled. + +Private preview: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-deadline-preview`, +**17,437,920 bytes**, SHA-256 +`11b427c42e27cc1492770075bc970f9ad480d9644f6a17d7ab9352d3b80815a5`. +Source revision and checks are recorded in adjacent private JSON. The isolated +remote fixture directory and release intermediates were removed; the final +artifact remains private. The user's GPU trial remained PID 4031422/start ticks +558428413, with the existing tunnel returning ready; no inference or management +mutation was sent to it. + +No real-model deadline budget, speed improvement or long-term stability claim is +made. A timeout deliberately loses that worker's caches and may reload the model. +This feature is ready for QA, not independently approved or installed over the +qualified user trial. diff --git a/docs/experiments/2026-10-04-keyless-runtime.md b/docs/experiments/2026-10-04-keyless-runtime.md new file mode 100644 index 00000000..1dbcbd8b --- /dev/null +++ b/docs/experiments/2026-10-04-keyless-runtime.md @@ -0,0 +1,155 @@ +# V-only QSA: реалізація та перевірка на RTX 5090 + +**Рішення:** залишити V-only експериментальним. Kernel і фізичний кеш +пройшли технічні тести. Конверсія наявної Qwen не пройшла перевірку якості +агентної роботи; багатоденний робочий запуск не дозволений цим результатом. +Ціль прискорення інференсу без втрати якості не досягнута. + +## Практична задача через console harness + +Використано той самий збережений запит: одна HTML-сторінка з хрестиками-нуликами +на Three.js/WebGL, перемогою/нічиєю, Restart, підтримкою телефона та task workflow +у спеціальному LeaseVibe test project. SHA-256 тексту запиту: +`e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. +Агент отримував завдання через той самий launcher і Responses adapter; +оператор не підказував йому й не виправляв створюваний результат. + +| Варіант | Запити моделі / спроби | Виконані tool calls | Згенеровані токени | Середня decode, ток/с | Час агента, с | Результат задачі | +| --- | ---: | ---: | ---: | ---: | ---: | --- | +| Native K+V, попередній еталон | 49 | 59 | 49 854 | 115,7 | 634,27 | Гра створена, 6/6 незалежних перевірок | +| V-only, лінійна ініціалізація | 1 | 0 | 645 | 85,8 | 16,34 | Переплутав гру з Breakout, файла немає | +| V-only, калібрований query routing | 3 | 0 | 908 | 90,8 | 38,01 | Невідомі/незавершені tool calls, файла немає | + +У каліброваному прогоні було одне початкове звернення та два автоматичних retry +harness. Усі три виклики були відхилені до виконання інструмента. Це відрізняється +від звичайного виправлення параметрів після відповіді MCP. У гри немає готового +артефакту, тому її шість браузерних перевірок виконати неможливо. + +Decode усереднено як `сумарні output tokens / сумарний decode time`. +908 токенів отримано за 9996 мс decode; швидкості окремих спроб: +86,7, 100,1 і 103,1 ток/с. Input: 67 104, з них reused: 44 726. +Перший prompt мав 22 368 токенів, prefill тривав 25 379 мс; наступні дві спроби +повторно використали 22 363 токени кожна. Токени невдалих відповідей враховано +за журналом engine, оскільки adapter не опублікував їх як завершену відповідь. + +Ці невдалі короткі прогони не є зіставним виміром прискорення завершеної задачі: +вони зупинилися перед першою успішною дією. Попередній успішний еталон повторно +не запускався. Його повний опис — +[попередній звіт](2026-10-03-agent-gpu-kar-threejs.md). + +## Що реалізовано + +- Нативний bounded GGUF → F32 експорт реальних `Wq`, `Wk`, `Wv` та нормалізацій, + із fingerprint/digest і перевіркою геометрії; повні 83,6 GB шарди повторно + не хешувалися. Використано вже перевірений manifest. +- Початкове перетворення query у простір V: + `A = Wk Wv.T pinv(Wv Wv.T)`, `q_keyless = q A`. +- CUDA query routing після наявної Q-нормалізації та перед RoPE. Gate-половина + вихідного query/gate projection збережена. +- Єдиний INT8 V pool і його scales у resident GPU кеші й host mirror. + Attention K codes/scales не виділяються та K projection не обчислюється. +- Scores читають позиційно повернутий V; value sum читає вихідний V. + Друга постійна копія повернутого V не створюється. +- Prefill, decode, speculative verifier, page streaming і snapshots використовують + це представлення; snapshot формату K+V не відновлюється у V-only. +- Окремі ключі QSA indexer та звичайний K+V кеш MTP draft-моделі збережені. +- M-RoPE scores використовують відповідні time/height/width позиції. Числова + арифметика цього шляху перевірена; якість задач із зображеннями не кваліфікована. + +Метод — експериментальний retrofit з +[Keyless Attention](https://arxiv.org/html/2606.21848v1). +Робота авторів навчає моделі з нуля. Це не доказ, що заміна attention у вже +навченій і квантованій Qwen збереже її якість. Поточний retrofit залишає вихідні +Q-нормалізацію та gate і навчає додаткові routing matrices; він не є відтворенням +усього навчального експерименту авторів. + +## Технічні перевірки + +| Перевірка | Результат | +| --- | --- | +| CUDA query routing проти незалежного CPU matrix product | max abs `6.55651093e-7` | +| Attention, текстові позиції, 3 causal selections, переставлені сторінки | relative L2 `1.32283452e-7`; max abs `2.78549168e-8` | +| Attention, різні M-RoPE time/height/width позиції | relative L2 `1.32984469e-7`; max abs `2.55048025e-8` | +| Resident проти streamed V-only, 40 000 cells | 306 batches; 717 880 block lookups; 70 200 misses; 0 overflow; 0 failures; побітова рівність outputs | +| V-only ring restore | Outputs побітово ідентичні resident | +| Conversation snapshots, включно з K+V форматами та V-only | 2448 checks passed; немає K payload/pools у V-only | +| Routing identities і numerical gradient калібрування | 5 Python tests passed | +| Rust | 96 tests passed, fmt та Clippy passed | +| Статичний Linux CLI | GGUF/KAR smokes; точний F32/Q2_0 export; відмова overwrite; nonfinite output cleanup — passed | +| Linux CPU engine | 5 CTest tests passed | +| Фінальний CUDA CTest на вільному GPU | 3/3 passed | + +Точність CUDA gate: query max abs ≤`2e-6`; attention relative L2 і max abs +≤`1e-5`. Незалежний CPU oracle використовує double accumulation і explicit +RoPE/softmax/raw-V retrieval. Раніша спроба запустити окремий CUDA test context, +коли вся модель займала GPU, отримала OOM; після unload усі тести пройшли. +GPU validation script тепер відмовляється запускати їх на зайнятому GPU. +Це не було падінням inference engine. + +## Калібрування та якість + +Захоплено ordinary-Qwen teacher activations із двох різних prompt: +2061 prefill positions для навчання й 526 для calibration validation. +Калібрування мінімізує causal attention KL, змінюючи тільки query routing. +Вихідні projections, norms, gate і решта моделі заморожені; кешовані K +не синтезуються. Числову похідну objective перевірено finite difference. + +Виконано попередній fit із 128 sampled queries та розширений fit із 1024, +до 512 sampled keys, 200 Adam steps, learning rate 0.003. Validation використано +для порівняння fit, тому це calibration validation, не незалежний фінальний +benchmark якості. Агентна задача не входила до цих навчальних текстів. + +У розширеному fit середня по heads відносна L2-похибка attention output +на validation лежить між `0.20433868` і `1.25948095` залежно від шару; +найгірший head — `2.28521657`. Зменшення навчальної помилки не зберегло +поведінку на інших даних. Повний агентний прогін також failed. +Не оголошуємо ні збереження якості, ні неможливість методу взагалі. + +## Пам'ять + +На один QSA block (4 cells × 2 KV heads): + +| Представлення | Bytes | +| --- | ---: | +| INT8 K+V із scales | 4224 | +| INT8 V-only із scales | 2112 | + +Для 12 main QSA layers і 256K cells економія K codes/scales становить +1.546875 GiB у повному host mirror. При 32K resident економія resident cache — +198 MiB; routing matrices додають приблизно 72 MiB GPU пам'яті. Indexer та MTP +не входять у ці половини. Збереження половини QSA cache не означає половину +всієї VRAM: expert cache auto використовує доступне місце. Завантажена модель +займала 31 773 MiB GPU, після зупинки — 34 MiB. + +## Відтворення та provenance + +- GPU RTX 5090, Ryzen 9 9950X3D, 128 GB RAM, Linux. +- NVIDIA driver `595.91.07`, power limit `600 W`; + nvcc `13.2.86`, CUDA architecture `120`. +- Модель Qwen3.8-Flash-Next GSQ-RCO IQ3_S, source shard identities у + `manifests/qwen3.8-flash-next-iq3-s.json`; native expert weights, без KAR overlay. +- Конфігурація: один слот, **256K configured context**, INT8 V-only main QSA, + 32K resident, MTP spec 4, expert cache auto. Фактично заповнений prompt — + 22 368 tokens; повний 256K/512K quality gate не пройдено. +- Upstream identity збережено у `docs/upstream.md`; local base — `46a9787`. +- SHA-256 engine саме каліброваного агентного прогону: + `fdd4ace410d57eff4fe67f33e13fc5f43ed8981b597689a6047b6460e87e4cd9`. + Після прогону додано defensive buffer guards і restoration guard для MTP; + фінальна збірка має окремий hash у приватному verification record. +- SHA-256 початкового routing: + `70d4c7b440f6dddbae755c340a27d8cd2a5e626233729e85fc8ccf1a83db796f`. +- SHA-256 routing каліброваного агентного прогону: + `5c70306b0d5e0b351f0f3f60561e37e78dff44a5a3ec7628e835cd9adf8e94e0`. +- Лінійний агентний прогін є діагностичним: окремий digest його проміжної + engine-збірки перед заміною не збережено. +- Сирі captures, logs, credentials, routing weights і generated outputs — тільки + у приватних ignored/cache шляхах. Стиснені моделі не публікуються. + +Встановлено обидві пари назв launcher: `codex-qwen`/`codex-qwen-ctl` та +`qwen-codex`/`qwen-codex-ctl`. Експериментальний opt-in profile: +`strata-next-v-only --kv-mode without-key --layout 1x256 --kv-cache q8_0`. +Profile явно позначено як такий, що не пройшов quality gate. +Після експериментів server зупинено й попередні console connection/config +відновлено. Тимчасові exports, teacher captures і зайві routing/build artifacts +прибрано; перевірені source shards і потрібний фінальний prototype збережено. +Прибрано 1 693 472 325 bytes проміжних файлів (приблизно 1,58 GiB). diff --git a/docs/experiments/2026-10-04-large-embedded-package.md b/docs/experiments/2026-10-04-large-embedded-package.md new file mode 100644 index 00000000..f2cee61c --- /dev/null +++ b/docs/experiments/2026-10-04-large-embedded-package.md @@ -0,0 +1,67 @@ +# Large embedded static-CUDA package — STRA-24 + +Date: 2026-10-04. Scope: packaging and CPU supervision checks. No inference, +model-quality or speed claim. The user's active native endpoint and tunnel were +preserved throughout; no trial restart or profile switch occurred. + +## Implemented + +Build-time payload verification and copying now use a 64 KiB buffer with a +1 GiB hard limit, rather than loading the complete engine into a Vec. Validation +covers the exact copied SHA-256, ELF64 little-endian target architecture, +executable type and declared 40-character source revision. Errors fail the +build. The revision is provenance supplied by the builder, not a reproducibility +proof. Rust compilation/linking and runtime memfd storage still require resources +proportional to payload size. + +`engine-help` explicitly materializes the embedded engine and executes `--help` +with `CUDA_VISIBLE_DEVICES` empty, retaining the memfd through child exit. It +does not load a model. Ordinary builds remain without an embedded engine. + +## Private artifacts + +| Artifact | Bytes | SHA-256 | +| --- | ---: | --- | +| Static-CUDA engine | 593,942,184 | `389b518c3c8afaccd20bab78f538e008ff996d11dacb08abe73e315a853c6b11` | +| Combined musl control plane and engine | 611,277,088 | `4e3893ddf90fd35acf39b73a12858da072cea271bf0c6129a5559fca7306bba6` | + +Engine source: `a36e45ac780cd137aceaa33bed663edd932c73d9`; upstream pin remains +`d9ab8435f654c368c586340d490915f6addf56a3`. The combined executable is retained +privately under `~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-static-cuda-preview` +on the laptop, with adjacent provenance JSON. It is not the installed trial +runtime. Weights and tokenizer are external. No artifacts were published. + +## Verification + +- Rust 1.99.0: 134 macOS library tests passed; all-target Clippy with warnings + denied and formatting passed. Streaming tests cover exact bytes, size boundary, + overflow, architecture/digest/revision rejection, truncated input, interrupted + reads and write failures. +- A normal build reports no payload and rejects `engine-help` explicitly. +- Cross-built Linux musl CPU fixture passed embedded identity, sealed memfd, + GPU-hidden help, readiness, HTTP generation, forced worker restart, and worker + and memfd cleanup. Output was exactly `A` for both embedded and external copies + of the same fixture (zero tolerance). This is synthetic protocol evidence. +- The actual 593,942,184-byte engine was embedded successfully. On rnr5090, + `engine-info` matched the expected payload size, digest and source revision. +- `env -u LD_LIBRARY_PATH engine-help`, bounded externally + by a 20-second timeout, exited zero and printed Strata help. No GPU was visible + to the child. The outer executable had no ELF INTERP or NEEDED entries. +- The inner engine's earlier ELF audit found only host libm, libc and loader + dependencies, no RPATH/RUNPATH, and a **glibc 2.43** minimum. It was built with + CUDA 13.2.86/GCC 15 for SM 120. The host has RTX 5090 and driver 595.91.07; + this check did not exercise GPU kernels. +- Trial worker PID/start identity remained unchanged and status stayed ready. + Readiness alone does not indicate whether user requests are active. + +## Remaining gates + +The inner executable is not fully static: the host still needs compatible glibc +and an NVIDIA driver. Runtime-selected `dlopen` dependencies, a clean-node run, +older glibc baseline, real-model numerical parity, agent completion and stability +remain unverified for this package. The `shared_libraries_bundled: false` metadata +means there are no separately bundled shared objects; static toolkit code is +inside the engine. No hosted GitHub Actions run has occurred. + +The source-copy directory, remote smoke directory and release build intermediates +are removed after verification; final private binaries and provenance remain. diff --git a/docs/experiments/2026-10-04-model-switch.md b/docs/experiments/2026-10-04-model-switch.md new file mode 100644 index 00000000..754f7ae5 --- /dev/null +++ b/docs/experiments/2026-10-04-model-switch.md @@ -0,0 +1,140 @@ +# Managed console model switching — 2026-10-04 + +## Scope + +STRA-35 fixes the failed `codex-qwen-ctl start` selection of +`strata-next-kar-ple-gpu` while the qualified native runtime owned the GPU. +Previously the independent experiment controller rejected any occupied GPU; +it did not know how to stop and restore the native supervisor. + +The installed console now routes ordinary llama.cpp, ordinary Strata, +experimental Strata and native starts through one remote coordinator. +Existing menu numbers are preserved; `strata-native` is appended. + +## Transaction + +1. Resolve and preflight the requested model through its existing controller. + Ordinary downloads/verification happen before unloading the old model. +2. Inventory managed process roots and reject unrelated CUDA processes. + Serialize console switches with a private host lock. +3. Save the previous launch recipe privately, stop the known current owner, + and wait for its GPU memory to release. +4. Launch the selected backend and wait for its API/model readiness. +5. Only then discover the endpoint and update the harness profile. +6. If the target fails, clean up its known processes and restore the previous + recipe. Report failed restoration explicitly and retain the private journal. + +The qualified legacy native runtime has no admin drain endpoint. An explicit +model switch sends its supervisor normal SIGTERM; an in-flight native request +can be interrupted. Existing ordinary/experiment controllers retain their +busy-request guards. Unrelated GPU work is never killed. + +## Verification + +- 11 transaction/preparation tests: sequencing, preflight preservation, + unrelated and ambiguous owners, PID reuse/ancestry, idempotence, + rollback, rollback failure, failed-target cleanup and GPU-release waiting. +- 5 menu tests: stable numbering, native dispatch, all backend routing, + profile preservation on failure, installer backup and idempotence. +- All 16 passed on macOS and Linux; 13 existing native-service and 12 native-API + tests also passed on macOS. New suites are included in `check-local.sh`. +- Live RTX 5090 switch passed through the installed command: + `codex-qwen-ctl start strata-next-kar-ple-gpu --layout 1x256 --kv-cache q8_0 --wait-seconds 900`. + Previous native PID 4031422 exited; experiment supervisor 4133313 and engine + 4133347 became ready on port 18081. The private switch journal is `ready`. + Engine log confirmed the experimental level-2 PLE KAR CUDA cache arm. +- Re-selecting the same model through `qwen-codex-ctl start` preserved those + process IDs and completed successfully. The ordinary harness connection now + selects `strata-next-kar-ple-gpu`. +- A short non-streaming generation returned HTTP 200, one choice, 56 input and + 16 output tokens. Its deliberately capped output ended with `length`; this + checks generation transport, not answer quality or a complete agent task. +- Model startup took several minutes reading NTFS-backed weights. Observed + disk reads were around 150 MB/s during loading; no whole-archive SHA pass was + added. Switching the controller does not remove model I/O startup cost. +- The retained native restart recipe passed preflight. Reverse switching and + the ordinary llama.cpp/Strata service transitions were covered by dispatch + and transaction tests, but were not separately run on the GPU in this trial. + +This is a lifecycle change; engine arguments, model weights and numerical +kernels are unchanged. No inference speed or quality improvement is claimed. +KAR PLE and V-only retain their experimental quality status. CPU fault tests +exercise rollback; they are not a live GPU failure-injection trial. + +## Commands + +```sh +codex-qwen-ctl start strata-next-kar-ple-gpu +codex-qwen-ctl start strata-native +codex-qwen-ctl start +``` + +`qwen-codex-ctl` uses the same controller. Start the agent with `qwen-codex` +after the controller reports readiness. Re-selecting the already-ready profile +keeps its process. `--wait-seconds` accepts 1–7200 seconds; the default is 3600. +Native uses the retained loopback SSH tunnel, creating one if the port is free. +The coordinator only manages the known host recipes; an externally started +untracked GPU workload still yields an ownership error. + +## Configured host layout (STRA-68) + +The repository controller also accepts an **opt-in** private deployment file. +The installed controller and the active trial are not changed by this feature. +All paths are absolute and supplied by the operator, for example: + +```json +{ + "schema_version": 1, + "root": "/home/alice/.local/state/strata/switch", + "native": "/home/alice/.local/state/strata/native", + "control": "/home/alice/.local/share/strata/console-helpers", + "agent_helper": "/home/alice/.local/share/strata/agent-profile.py", + "binary": "/home/alice/.local/share/strata/releases/v1/strata-next", + "config": "/home/alice/.config/strata/native-v1.json", + "cwd": "/home/alice/.local/share/strata", + "url": "http://127.0.0.1:18082", + "model": "strata-native-iq3-s", + "key_file": "/home/alice/.config/strata/api-key" +} +``` + +Only `key_file` is optional. The deployment and key files must be private regular +files owned by the invoking user (mode 0600); existing state directories must be +private too (0700). The readiness URL must be literal loopback HTTP with a port, +without credentials or a path. Readiness requires the expected service, model +and `ready=true`; redirects are not followed. Its socket timeout is not a hard +wall deadline against a slow byte stream. + +```sh +chmod 600 /home/alice/.config/strata/deployment.json +printf '%s\n' '{"backend":"native","waitSeconds":3600}' | + python3 scripts/strata-model-switch.py \ + --deployment /home/alice/.config/strata/deployment.json start +``` + +For this explicit mode, the native CLI runs `provision --config` before the +transaction can unload any current model. It resolves pinned assets, embedded +engine and `native_model`/derived tokenizer using the existing native bootstrap; +its bounded subprocess has private/null output and is killed/reaped on timeout. +No old PID file is needed for a first launch. An existing saved live recipe is +retained, including its selected environment. Use separate state directories for +separate native recipes; this remains a single-native-profile controller. Keep +versioned binary/config/model paths immutable while a model is running or being +switched so that rollback can reuse the saved recipe. + +Without `--deployment`, the existing host defaults and preflight behavior remain. +This does **not** install `qwen_remote`, `strata_remote` or the agent helper, nor +make their own backend-specific paths portable: those helpers must already be +configured on the destination host. It also does not replace the native runtime +with Python; Python here is only the console management tool. + +Validation adds private manifest, cold recipe, timeout/reap, authenticated +readiness and legacy-helper regression cases to the controller suite. The hosted +`smoke-controller-deployment.py` runs the actual combined native CLI with a +synthetic CPU engine, provisions a tiny verified GGUF offline, starts the native +profile from an empty state, preserves its PID on failed preflight, then fails a +simulated alternate backend and restores the original native process. The +synthetic Responses output must be exactly `A` before and after rollback (zero +tolerance). GPU ownership and the alternate backend are test adapters. This is +CPU process/transaction coverage; actual CUDA, real-model quality, clean-node +helper installation and GPU failure rollback remain separate acceptance gates. diff --git a/docs/experiments/2026-10-04-native-console.md b/docs/experiments/2026-10-04-native-console.md new file mode 100644 index 00000000..01aa2b82 --- /dev/null +++ b/docs/experiments/2026-10-04-native-console.md @@ -0,0 +1,153 @@ +# Native Responses console trial — 2026-10-04 + +## Result and scope + +The native **text** Responses profile completed a real, unassisted console +agent task on Linux RTX 5090. The agent built a playable Three.js tic-tac-toe +game, ran its own browser checks and completed LeaseVibe TEST-10. An observer +then independently checked the final game: **23/23 passed**, no page errors. +This qualifies a user trial of this profile, not the whole project, a long +stability soak, or a performance improvement. + +The test used the actual `qwen-codex` launcher and Codex CLI 0.160.0 with its +normal approval review enabled. No task assistance, corrective prompts or +completion actions were supplied by the observer. Four rejected tool items +were ordinary MCP workflow/claim validation; the agent handled the workflow. +One model response used an undeclared function name. The native server rejected +it before tool execution and the harness retried successfully. This was not a +zero-error run. + +## Measured run + +| Metric | Result | +| --- | ---: | +| Full task wall time, excluding model startup | 2,587.43 s (43:07) | +| Main agent completed model responses / iterations | 68 | +| Main agent output tokens, including reasoning | 68,403 | +| Reasoning tokens (subset of output) | 25,419 | +| Main agent cumulative input tokens | 6,170,118 | +| Main agent reused input tokens | 1,218,680 | +| Main agent weighted decode rate | 116.91 tok/s | +| Largest actual prompt | 131,759 tokens | +| Completed shell and MCP tool items | 74 | +| MCP items | 42 | +| All engine generations, including approval reviews and rejected response | 132 | +| All engine output tokens | 71,313 | +| All engine weighted decode rate | 117.18 tok/s | +| All engine request decode mean / median | 131.30 / 126.80 tok/s | +| All engine request decode p10–p90 | 102.87–165.38 tok/s | +| All engine prefill / decode time | 1,483.139 / 608.567 s | + +Weighted decode means generated tokens divided by summed engine decode time; +it excludes prefill, tools, MCP, browser tests and client work. It is not the +end-to-end task rate. Approval review requests share the worker and compete +for prefix reuse. Cache state is mixed: the first engine request reused zero +tokens; the run then contains both reused and cold prefixes. All engine input +tokens total 9,935,033, with 1,604,457 reused. No cache reset was forced per turn. + +This is one functional run, not a paired A/B experiment. Confidence intervals, +TTFT distributions, PCIe traffic, draft acceptance and expert-cache distributions +were not collected for this report. It establishes no speedup or regression +relative to the earlier benchmark. + +## Quality evidence + +- TEST-10 (`6aa33214-1e3f-4dd4-97ce-7c8f157f8f1f`) independently read back as + **Done**, with final work record and evidence. +- Agent's own Node/CDP harness: **132/132 assertions**, exit zero. It covers + winning lines, draw, restart, occupied cells, mouse/touch/keyboard input, + multiple viewports, pixel checks, CDN failure and a hover negative control. +- Observer's separate browser check: **23/23**, covering visible WebGL, all + eight winning lines, terminal locking, restart, draw, occupied cells, mobile + interaction/layout and absence of page errors. The agent's game was not edited. +- Final single-file game: 19,027 bytes; SHA-256 + `7837bbede7bff9de5f127c514cec32311b82159f37b27c7e2cb8a72e550139d6`. +- Console reached its final completed turn. Tool calls and outputs traversed + native Responses, including MCP text-part output and namespace identities. + Raw SSE frames for the entire session were not captured; terminal-event + coverage also comes from the earlier real API checks and local tests. + +Earlier attempts are retained as failures/incomplete runs: MCP text-part replay +and late developer instructions exposed protocol gaps which were fixed; a later +452.02 s run produced a playable game but left TEST-9 incomplete. Exit zero was +not accepted as task completion. A template fidelity fix kept assistant +commentary and tool calls in one turn before the successful fresh run. + +## Versions and configuration + +- Full agent run: control plane **a3770ed**, following console integration + **a60ebe5**. Follow-up deployed revision **93e2a9b** additionally preserves + call identity when parallel tool results arrive out of order, and reports + the existing greedy temperature default as zero. Sampling did not change. +- The complete agent run was not repeated on 93e2a9b. Instead, its changed path + passed a real-model paired check: ordered/reversed delivery produced identical + greedy JSON, `{"Oslo":3,"Paris":17}`, numerical tolerance **0**. Both responses + completed and reported temperature zero. +- All **116 Rust tests**, formatting and Clippy with warnings denied passed. + Rust 1.99.0, Linux x86_64 musl release build successful. +- Deployed supervisor: 17,132,528 bytes, SHA-256 + `74b116ad22eaf8382447bb71886dfc6a6d3e68142118f369f8be9cb0735dee2f`. +- Engine 0.1.35, fork `engine-fork-f80a3e0`, executable SHA-256 + `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. + Imported upstream remains `d9ab8435f654c368c586340d490915f6addf56a3`; + engine code was not changed in this milestone. +- RTX 5090 32,607 MiB, driver 595.91.07, CUDA 13.2.86, 600 W limit; + Ryzen 9 9950X3D, 128 GB RAM. +- Qwen3.8-Flash-Next IQ3_S, one slot, configured context 262,144, INT8 KV, + 32,768 resident KV tokens, auto expert cache/prefill, MTP spec=4/min-p=0.5, + existing expert profile, VRAM reserve 700 MiB. No KAR or V-only enabled. +- Model's previously verified source shards total 83,617,662,656 bytes, digests + `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` and + `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. + No new whole-model hashing was performed. +- Unchanged task prompt SHA-256: + `e10a433962e47b191b8269348cf26f9756d070ca800f2fe77213aa13f78023b1`. + +## Run the trial + +The loopback endpoint is running on rnr5090:18082, exposed through the retained +SSH tunnel at laptop port 18084. The isolated test profile was used throughout; +the user's normal connection has not been changed. To select native Responses: + +```sh +qwen-codex-ctl connect strata-native --url http://127.0.0.1:18084 --no-auth +qwen-codex-ctl status +qwen-codex +``` + +`status` reports `strata-native-iq3-s`, 1 × 256K, Responses ready; `/ready` +returned HTTP 200 after the final deployment and real-model follow-up. +The launcher uses the Rust endpoint directly, with no Python serving bridge. +The local launcher/controller itself still uses Python. + +The retained tunnel survives the tool session but not a laptop reboot. If it +is absent, recreate it (do not run a second listener on an occupied port): + +```sh +ssh -fN -o ExitOnForwardFailure=yes -L 127.0.0.1:18084:127.0.0.1:18082 rnr5090 +``` + +This native endpoint is externally supervised; the launcher does not yet own +its start/stop lifecycle. It is not configured as a boot service. `ctl stop` +explicitly directs the user to the owning service instead of stopping unrelated +processes. No HTTP authentication is implemented: keep the endpoint loopback +only and use SSH, as deployed. + +## Remaining gates + +Text and function tools are supported. Image input, custom/freeform/web tools, +encrypted reasoning, durable response history, native lifecycle profiles and +authentication remain outside this trial. Structured output is prompted and +validated, not constrained decoding. Process-local history does not survive a +restart. Full 256K occupancy, 1×512K, 2×256K and multi-day stability are not +qualified by this 131,759-token maximum run. KAR GPU and V-only retain separate +quality gates. Hosted GitHub Actions have not run; a hosted repository is not +yet set up. + +Private raw events, timing, engine log, usage summaries, final game and QA +screenshots are retained under the laptop's +`~/.cache/strata-next/native-console-20261004/`; remote runtime/config/assets +remain under the same cache subdirectory on rnr5090. Credentials and captures +are not in Git. Disposable capture home/work directories and obsolete native +runtime copies were removed. The deployed binary, tokenizer, configuration, +tunnel, private evidence and final game are retained for the user trial. diff --git a/docs/experiments/2026-10-04-native-responses.md b/docs/experiments/2026-10-04-native-responses.md new file mode 100644 index 00000000..e1bd9a29 --- /dev/null +++ b/docs/experiments/2026-10-04-native-responses.md @@ -0,0 +1,111 @@ +# Native Responses API on the real IQ3_S model + +## Scope and provenance + +This is a functional protocol and supervisor qualification on the RTX 5090, +not a paired throughput benchmark or a completed agent-quality gate. +The ordinary production endpoint was not switched. + +- Control plane: `0f1efa2` plus the accompanying `RESUME`/`REUSED` parser fix; + Rust 1.99.0, release `x86_64-unknown-linux-musl`. +- Static CLI: 16,983,824 bytes, SHA-256 + `ee1dd490c64efb636025da74868dad1a59662eb2f95409513f7b900b01d534be`. + Linux ELF inspection found no interpreter or required shared libraries. + This describes the control-plane executable, not the separate CUDA engine. +- Engine: existing baseline `engine-fork-f80a3e0/build/strata`, engine 0.1.35, + SHA-256 `0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f`. + Imported upstream provenance remains in `docs/upstream.md`. +- Hardware: RTX 5090 32 GiB, Ryzen 9 9950X3D, 128 GB RAM; + NVIDIA driver 595.91.07, CUDA 13.2.86, configured power limit 600 W. +- Model: private Qwen3.8-Flash-Next IQ3_S source shards, 83,617,662,656 bytes. + Previously verified SHA-256 identities, without another full-file scan: + `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` + and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +- Configuration: one worker, 262,144 context, INT8 K+V, 32,768 resident KV, + automatic expert cache/prefill, MTP spec4 with minimum probability 0.5, + 700 MiB VRAM reserve; copied baseline engine arguments and environment. + No KAR or V-only mode. Greedy requests, reasoning effort `none`. +- Rust directly supervises C++; Python only drives these offline HTTP checks. + Test endpoint: loopback port 18082. Private evidence directory on the Linux + host: `/home/para/.cache/strata-next/native-responses-20261004`. + +## Defect found and fixed + +The engine loaded and reached READY, but the first real generation got HTTP +503 because the Rust wire parser rejected `RESUME 0` as an unknown tag. +The supervisor correctly isolated the failed worker and initiated recovery. +The failure is retained as `text-json.pre-resume-fix.json` and `runtime.log`. + +Upstream emits `RESUME ` before prefill and `REUSED ` afterward. +Both are now validated as unsigned counts and consumed as nonterminal metadata; +`DONE` remains the source of final usage. Unknown tags, malformed/overflowing +counts, and inconsistent terminal counters still fail closed. Regression +coverage includes the real message order in the mock-worker exchange. + +## Text and tool calls after the fix + +Each row is one functional request, sequentially after a fresh worker load. +The tool SSE request reuses the preceding tool prompt; the other rows report +zero prefix reuse. OS/model storage caches were not flushed. These short, +different requests and cache states must not be compared as speed variants. + +| Request | Result | Input / output tokens | Reused | HTTP wall | First visible delta | +| --- | --- | ---: | ---: | ---: | ---: | +| Text JSON: 2 + 2 | `4`, completed | 26 / 2 | 0 | 0.3424 s | N/A | +| Text SSE: HELLO | `HELLO`, completed | 20 / 3 | 0 | 0.2287 s | 0.1721 s | +| Tool JSON | Correct typed call, completed | 307 / 39 | 0 | 1.6837 s | N/A | +| Tool SSE | Correct typed call, completed | 307 / 39 | 300 | 0.3076 s | 0.3073 s | + +Both tool responses contain exactly one `record_value` call with integer +`value: 7` and string `label: "native-smoke"`. Arguments are schema-validated +before publishing. JSON and SSE agree on the semantic call. Both SSE responses +have contiguous sequence numbers and exactly one terminal event. Output token +usage includes protocol/end tokens, not only visible text. Raw synthetic +responses and event sequences are retained privately. + +## Cancellation, recovery, and tool continuation + +- After four text deltas from a long generation, the HTTP client disconnected. + The same worker accepted the next arithmetic request and returned `4`. + Disconnect through completed follow-up took **0.3925 s** in the final run + (an earlier successful check took 0.1819 s). These include the next request's + inference, not an isolated STOP latency. +- The test killed only the verified owned engine child during another active + generation. The stream emitted exactly one `response.failed`; a new request + returned HTTP 503, and readiness was false with no context. The supervisor + started a different child after its configured two-second backoff, without + replaying the failed generation. +- Replacement readiness took **25.4056 s**, including reload, with warm OS + caches and a one-second readiness polling interval. A fresh post-recovery + request returned `4` in **0.4369 s**. The prior and replacement worker PIDs + were 3992120 and 3993068. This is one recovery measurement, not a percentile + or a cold-start promise. +- An initial lifecycle-driver attempt stopped because it treated the expected + HTTP 503 from `/ready` as an exception. The driver was corrected to read that + response body; the final complete lifecycle run above used a fresh runtime. + No runtime change was required for this driver defect. +- A further actual-model two-turn check produced a valid typed `record_value` + call, then received its result using `function_call_output` and + `previous_response_id`. The model returned the exact tool confirmation + `RECORDED-731`. The two requests took **1.7437 s** and **0.3842 s**. + +All 102 Rust tests, format, Clippy with warnings denied, and diff checks passed. +The regression keeps mock-worker token/terminal output unchanged while adding +the real prefix metadata lines. No model weights or compute kernels changed. +These checks establish supported protocol behavior; they do not establish +full-model numerical parity across a recorded agent workload. + +The isolated runtime was stopped after measurement. Temporary tokenizer assets, +configuration, and uploaded CLI are removed; private scripts, logs, and result +JSON files remain for reproduction. The latest static CLI is retained locally. +Model shards and baseline artifacts were not changed. +After cleanup, GPU usage returned to 34 MiB / 0%, and port 18082 had no listener. +The temporary local musl release build was removed (93.8 MiB). + +## Remaining qualification + +Live reasoning, structured output, full recorded Codex/MCP replay, sustained +soak, and a paired end-to-end performance comparison remain open. Passing +these small checks does not authorize switching the production console profile +or enabling experimental V-only/KAR modes. Hosted GitHub Actions has not run; +the project does not yet have its GitHub repository. diff --git a/docs/experiments/2026-10-04-required-tools.md b/docs/experiments/2026-10-04-required-tools.md new file mode 100644 index 00000000..400dbfd4 --- /dev/null +++ b/docs/experiments/2026-10-04-required-tools.md @@ -0,0 +1,55 @@ +# Required and forced function choice — STRA-32 + +Date: 2026-10-04. The native Responses candidate adds `tool_choice: "required"` +and the documented top-level function selector +`{"type":"function","name":"lookup"}`. Required permits one or more calls; +combined with `parallel_tool_calls: false`, it permits exactly one. Forced +function choice permits exactly one call to the selected function. + +The model receives prompt guidance. The runtime validates generated calls before +publishing callable items and checks the minimum at successful completion. +There is no constrained sampling or automatic retry. Token-limit incomplete +responses may contain zero complete calls. Wrong names and excessive counts +are still rejected. Ordinary SSE can publish valid text or a first valid call +before a later failure; those events cannot be retracted. + +The selector must contain only type/name and identify a declared top-level +function. Invalid selectors or a required choice with no callable tools fail +before generation. Custom/namespaced forced selectors and allowed-tools remain +unsupported. Original request metadata, tool arguments and historical replay +are retained. See the [API contract](../api-contract.md#tool-choice-and-call-count) +and [official tool-choice semantics](https://developers.openai.com/api/docs/guides/function-calling#tool-choice). + +## Verification + +- Rust 1.99.0: 141 library tests passed, including prompt guidance, required + missing-call rejection, forced wrong-call rejection and incomplete exemption. + Clippy all-targets with warnings denied, fmt and diff checks passed. +- The extended `scripts/smoke-tool-policy.py` passed on macOS debug and Linux + x86_64 musl release, with 84 HTTP generations on each: + auto/default, none, required and forced choices; zero/one/mixed/duplicate calls; + parallel false; token-limit incomplete; JSON/SSE crossed with reasoning + none/low. Eight malformed request configurations fail with 400 before + generation; two unsupported choice kinds fail with 501. Generation metrics + confirm no additional worker requests for rejected configurations. +- Accepted Unicode custom input, function arguments and metadata match the + synthetic baseline exactly (zero tolerance). Invalid output returns JSON 502 + or terminal SSE `response.failed`; sequence numbers are contiguous. Forbidden + call/input events are never published. Completed versus incomplete status is + preserved. +- Linux CI invokes the expanded matrix. Hosted GitHub Actions has not run. + +This is a CPU-verified development candidate awaiting independent QA and real +model qualification. No speedup, model policy-following quality or sustained +stability is claimed. The qualified GPU user trial and tunnel remain unchanged; +readiness does not prove the trial has no active requests. + +## Private artifact + +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-required-tools-preview`, +**17,440,536 bytes**, SHA-256 +`1c2fdcf7ef92286b518fd67ba66c893f1fcff947f483849bdb041c77e126f732`. +The adjacent private JSON records source revision and checks. This is the Rust +supervisor candidate; its external worker and tokenizer remain deployment +inputs. No active profile or service was upgraded. Owned CPU fixture files and +release intermediates were removed after verification. diff --git a/docs/experiments/2026-10-04-response-resources.md b/docs/experiments/2026-10-04-response-resources.md new file mode 100644 index 00000000..99d8dc87 --- /dev/null +++ b/docs/experiments/2026-10-04-response-resources.md @@ -0,0 +1,41 @@ +# Stored Responses retrieval and deletion — STRA-27 + +Date: 2026-10-04. The new preview provides authenticated GET and DELETE on +`/v1/responses/{response_id}` for its existing process-local history. Retrieval +returns the exact saved terminal response. Deletion removes that response and +its replay transcript atomically. The shared 64-entry/128 MiB serialized-data +budget now counts both the complete response and transcript. Full API scope and +official reference links are in [the contract](../api-contract.md#stored-response-resources). + +## Evidence + +- Rust 1.99.0: 135 library tests passed, including combined byte accounting, + FIFO eviction, rejection without evicting valid data, identity checks and + deletion reclaiming queue/data bytes. Existing failed-generation and replay + tests passed. Clippy all-targets with warnings denied, fmt and diff checks passed. +- `python3 scripts/smoke-response-history.py ` passed on macOS debug and + Linux x86_64 musl release. Its 28 combinations cover plain text, reasoning, + structured JSON, function calls, custom tools, reasoning with custom tools and + incomplete length stops, each with streaming/non-streaming and store true/false. +- Every retained object matched its original terminal JSON exactly, including + IDs, tool arguments, reasoning, metadata, usage and status (zero tolerance). + Authentication rejection, unknown/query/repeated-delete errors, successful + continuation, deleted-parent rejection and descendant preservation passed. +- Retrieval/deletion remained available while the isolated fixture runtime was + drained and its synthetic worker was killed. This was a CPU fixture, not the + active GPU service. The hosted Linux workflow includes this smoke; GitHub + Actions execution remains pending. + +Private preview on the laptop: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-history-preview`, +**17,363,752 bytes**, SHA-256 +`4e575a73f8763cd949cf273d374107ce537245cbef36f68dc71a7d03c62aa1c3`. +Source revision is recorded in adjacent private JSON. This control-plane-only +binary was not installed over the user trial. The active endpoint and tunnel +remained ready. The isolated remote smoke directory and release intermediates +were removed; the final private preview remains. + +No real-model parity, speedup or long-term stability is claimed. History is not +durable; it is shared under the optional single operator key. Deletion cannot +erase copies already in descendant histories or in-flight continuations and is +not cancellation. Retrieval query options/stream resumption are unsupported. diff --git a/docs/experiments/2026-10-04-signal-grace.md b/docs/experiments/2026-10-04-signal-grace.md new file mode 100644 index 00000000..b428ecf1 --- /dev/null +++ b/docs/experiments/2026-10-04-signal-grace.md @@ -0,0 +1,62 @@ +# Signal admission grace — STRA-33 + +Date: 2026-10-04. The native supervisor can wait for admitted inference work +before interrupting its worker on SIGTERM/SIGINT. Top-level `shutdown_grace_s` +or `STRATA_SHUTDOWN_GRACE_S` accepts 0–20 seconds; default 0 keeps the previous +immediate interruption policy. Native `check-config` reports the effective value. + +Signal arrival marks lifecycle `shutting_down` and `draining` under the admission +lock. Resume cannot reopen it. With positive grace, the listener remains open +while admitted HTTP requests and generation commands finish; new inference gets +503 and readiness becomes false. The wait ends when both counters reach zero, +checked every 25 ms, or at its deadline. Worker shutdown then follows the existing +STOP/QUIT path. Existing administrative drain/resume remains reversible. + +See [the contract](../api-contract.md#signal-shutdown-grace) and +[deployment procedure](../../deploy/README.md#drain-before-maintenance). + +## Evidence + +- Rust 1.99.0: all 142 library tests passed; Clippy all-targets with warnings + denied, fmt and diff checks passed. The added lifecycle test covers irreversible + signal drain, a previously admitted request enqueueing after signal, separate + HTTP/worker guard lifetimes, timeout and idle completion. +- `smoke-signal-drain.py` passed six CPU cases on each of macOS debug and Linux + x86_64 musl release: SIGTERM and SIGINT crossed with five-second successful + drain, one-second expiry, and default zero grace. +- Successful drain retained an active SSE response and a queued JSON response. + Both produced exactly `OK` (zero tolerance against the synthetic baseline). + SSE sequences were contiguous and ended with `response.completed`; both + generations ran, QUIT was observed, STOP was unnecessary, and the worker exited. +- During grace, readiness returned 503, new inference returned `runtime_draining`, + and resume returned the still-draining shutdown state. Health remained available. +- Expiry/default cases emitted terminal SSE `response.failed`, rejected queued + work without replay, sent STOP/QUIT, and left no worker process. One-second + expiry did not interrupt before 0.9 seconds; cooperative fixture shutdown + finished within five seconds in all cases. These are test bounds, not throughput + or production shutdown-latency measurements. +- `smoke-config-check.py` passed 45 checks on each platform, including default, + file/env precedence, 0/20 boundaries, invalid values and sanitized failures. + No worker was launched and an occupied listener port was undisturbed. +- Existing `smoke-native-drain.py` passed on both platforms, preserving reversible + maintenance, auth/429/503 precedence and exact SSE/queued JSON output. +- CI includes the new CPU signal fixture and expanded config checks. Hosted + GitHub Actions has not run. + +## Limits and artifact + +Grace bounds only the initial admission drain. Worker and HTTP connection cleanup +follow it; standalone execution gains no total exit deadline. The rendered +systemd unit retains its 45-second hard stop. Longer maintenance uses explicit +admin drain before signal. A stalled request may be interrupted after grace. +No real-model qualification, speedup or soak claim is made. Independent QA remains +pending. The active GPU trial and SSH tunnel were preserved; only read-only status +was checked, which does not establish absence of active requests. + +Private supervisor candidate: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-signal-grace-preview`, +**17,444,848 bytes**, SHA-256 +`154174705da6c73f290480fda3390714bf52b026868a695df89390064890d35f`. +The adjacent private JSON records source revision and checks. The external worker +and tokenizer remain deployment inputs. Owned remote CPU fixture files, local +fixture bytecode and release intermediates were removed; final evidence is kept. diff --git a/docs/experiments/2026-10-04-tool-policy.md b/docs/experiments/2026-10-04-tool-policy.md new file mode 100644 index 00000000..f85802d3 --- /dev/null +++ b/docs/experiments/2026-10-04-tool-policy.md @@ -0,0 +1,48 @@ +# Native tool choice and single-call policy — STRA-31 + +Date: 2026-10-04. Native Responses supports `tool_choice: "none"` by omitting +current tool declarations from the model prompt and refusing generated callable +items. Original tools/choice metadata and historical tool replay are preserved. +`parallel_tool_calls: false` now enforces at most one function/custom call across +namespaces. The prompt guides the model; complete and live paths enforce the +count before publishing a disallowed call. Auto/default behavior remains intact. + +See [the policy contract](../api-contract.md#tool-choice-and-call-count) and its +official API reference. This controls tool calls in one response, not concurrent +GPU requests or token-level constrained sampling. In a live stream the first +valid call may already be visible before a later violation fails the response; +it cannot be retracted. Required/named/allowed-tools choices remain unsupported. + +## Evidence + +- Rust 1.99.0: all 141 library tests passed, including prompt equivalence between + none and no declarations, retention of historical calls/results, validation of + hidden declarations, original response metadata, and rejection of two mixed + function/custom calls when only one is allowed. Clippy all-targets with + warnings denied, fmt and diff checks passed. +- `smoke-tool-policy.py` passed 36 CPU HTTP cases on macOS debug and Linux + x86_64 musl release: nine policies/outputs × JSON/SSE × reasoning none/low. + The matrix covers auto/default two calls, false zero/one function/one custom/two + calls, and none with plain text or forbidden custom/mixed calls. +- Accepted arguments and Unicode custom input were preserved + exactly (zero tolerance); text returned exactly `OK`. Tools, metadata, effective + default choice and parallel flags matched the request. +- Violations returned JSON 502 or terminal SSE `response.failed`. SSE sequence + numbers remained contiguous. None published zero callable items; ordinary live + false mode published only the first valid function call, with no second custom + item/input events. Buffered reasoning published no callable items on failure. +- Unsupported required/named choices returned 501 without additional generation. + The smoke is wired into Linux CI. Hosted GitHub Actions has not run. + +Private preview: +`~/.local/share/strata-next/bin/strata-next-linux-x86_64-musl-tool-policy-preview`, +**17,440,336 bytes**, SHA-256 +`a13719af9b7ad28821b09ddaffc3b75b8949a3dd4798512a1c19c50dbcf8db9a`. +Adjacent private JSON records source revision and checks. The isolated remote +fixture directory and release intermediates were removed; the final executable +remains private. The active GPU trial and existing tunnel were preserved, with +no inference or management mutation sent to them. + +No real-model policy-following quality, speedup or sustained stability is claimed. +This is a development candidate ready for QA, not an upgrade of the qualified +user trial. diff --git a/docs/experiments/2026-10-05-linux-gpu-qualification.md b/docs/experiments/2026-10-05-linux-gpu-qualification.md new file mode 100644 index 00000000..bef9a9f9 --- /dev/null +++ b/docs/experiments/2026-10-05-linux-gpu-qualification.md @@ -0,0 +1,200 @@ +# Linux GPU package qualification — 2026-10-05 + +## Scope + +The user ended the active project trial and explicitly made the RTX 5090 host +available for qualification. The previous runtime recipe and state were saved +privately before an idle check, authenticated unload and owned-process stop. +All requests in this report use synthetic inputs owned by the evaluator. +User project prompts, code and credentials were not inspected. + +This report separates package/deployment correctness, API correctness, model +quality and performance. It does not establish full KAR residency, a successful +V-only retrofit, a speedup, or completion of the whole Linux epic. + +## Artifact and hardware + +- Runtime source: `9409dc92ff9223e294ea2e027cf7fd4776bad027`. +- Actual hosted CUDA build: [run 37299581677](https://github.com/paveldhq/strata-next/actions/runs/37299581677), + including green verify, musl CLI, CLI container, CUDA engine, embedded package, + runtime image and private artifact upload. +- Private archive: 851,293,705 bytes, SHA-256 + `e45c30acb94430ee2b2f155d3c388177a56a428701e3c03b3b0a3d21298b2faa`. +- Combined executable SHA-256: + `2e07b2f3dc194576a43b902455ca91d9dc28368ac98aade1ed950f7fc98b42a3`. +- Embedded engine: 612,514,560 bytes, SHA-256 + `b629bac51a6a1d47097abf9c9e34fc25e806c3fa3fe94240cf93885c75643d22`. + CUDA 13.0.1; direct dependencies are libc, libm and the loader; minimum glibc + is 2.38. The host NVIDIA driver remains a dependency. +- Runtime image uses the pinned Ubuntu 26.04 base with glibc 2.43. + Its archive manifest digest is + `75c40b6fe1c78545ca556c79ab4503eeaf7fece1f342fbb2f418f6370f3d065b`; + its config digest is + `523a12493bc46173be2db8541760cfca6a39eefd9d3bd1bbf92191e74210cd25`. + Docker import reports the former; build provenance identifies the latter. + Both are present in the verified archive, and the contained executable hash + was independently checked after import. +- Host: Ubuntu 26.04.1, RTX 5090 32,607 MiB, driver 595.91.07, + Ryzen 9 9950X3D, 128 GB RAM. Source weights reside on the existing NVMe volume. +- Qwen3.8-Flash-Next IQ3_S source shards: 83,617,662,656 bytes, + SHA-256 `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3` + and `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. +- One slot, 262,144 configured context, INT8 K+V, 32,768 resident KV tokens, + auto expert cache/prefill, existing expert profile, MTP spec=4/min-p=0.5, + VRAM reserve 700 MiB. KAR, V-only and vision are disabled. + +The comparison baseline uses the previous external engine +`0f62ffb4dd30561bd4e56cd5e4da412a09f56b7ef6a19f5e23d0cea7e4381b1f` +and old serving pack with the current control plane. The candidate uses the +new embedded engine and a fresh native-prepared pack. The baseline CLI artifact +was built from PR merge `b678eadb8d878c659d44e60734a92bf8f483d3f6`, whose tree +`e4a4438ab40907d196885b2d0d042648ab816939` equals the runtime source tree above. + +## Native preparation and startup + +The native `provision` command verified both full GGUF hashes, generated a new +versioned serving pack and verified a separately pinned MTP bundle. It returned +`native_model_prepared=true`, `mtp_pack_structurally_validated=true` and +`worker_started=false` at 11:10 UTC. + +The generated dense file is 1,538,035,200 bytes and exactly matches the existing +offline-prepared file: SHA-256 +`d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13`. +The native expert table also matches exactly. The only index difference is the +generator comment. There were no float conversions; original quantized bytes +were preserved. This is IQ3 preparation, not KAR conversion. + +The new combined executable then started a fresh per-user unit with +`engine.executable=@embedded`, `native_model`, pinned MTP, driver policy, +loader probe, private authentication and durable history. Native `start-ready` +confirmed the exact managed PID/model and a ready worker at 11:25:44 UTC. +No separate engine installation or Python serving process was used. + +The imported image separately passed a read-only, network-disabled, UID 65532 +check: exact binary hash, driver/GPU visibility and absence of `python3`. +Container model startup and deployment rollback are recorded separately below. + +## Actual GPU rollback and durable continuation + +The native service catalog passed eight assertions at 11:35:37 UTC. Selecting +the already active target retained its PID. Switching to an intentionally invalid +target used the real embedded CUDA engine: loader preflight passed, then the +engine rejected missing PLE/native configuration before becoming ready. + +The controller drained and stopped the previous real GPU service, detected the +target startup failure, stopped that target, restarted the previous embedded +profile and waited for its model to become ready. Its durable transaction ended +in `rolled_back`. This is an actual full-model restart, not a simulated restore. +It does not test GPU OOM or driver-loss recovery. + +A previously stored response survived unchanged across that restart. Its +`previous_response_id` continuation returned the exact expected marker. The +failed target had no remaining process, and lifecycle counters showed no +orphaned request or generation. The retained source/pack/MTP were reverified +during restoration. The restored unit was then gracefully drained and stopped +before container qualification. + +## Fresh container deployment + +The verified image loaded the actual model and MTP with a read-only root, +nonroot UID 1000, all capabilities dropped and no-new-privileges. Source weights, +MTP and manifests were mounted read-only; a fresh private `/state` held the +native-generated pack and history. Production processes were the Rust control +plane and embedded engine; the image contained no Python executable. + +Native preparation inside the container checked both full source hashes. Its +dense file, expert table and index matched the host's new native pack exactly. +All 32 quality outputs matched the baseline after the same normalization, +tolerance zero. All 11 API checks and the separate JSON/SSE tool episode passed. +Graceful container stop returned exit 0, no OOM, and GPU use fell to 34 MiB. + +The first invocation used a wrong port because the image's `STRATA_BIND` +environment overrode the configuration; explicitly setting the intended bind +fixed this test setup. A replay attempted during the concurrent quality screen +correctly refused its idle precondition without generating requests; the +subsequent isolated replay passed. Both failed setup records are retained. +This proves fresh container userspace and pack deployment on the installed +driver, not installation of a driver on a new physical host. + +## Quality and API results + +The existing eight-case `quality-v1` corpus covered arithmetic, short and long +retrieval, instruction priority, no-tool behavior and forced function calls. +Each arm ran one warmup and three measured repeats per case, temperature zero, +reasoning none, maximum 128 output tokens. The unsupported Chat `seed` field +was omitted explicitly. Both arms passed 24/24 measured cases and 8/8 warmups. +All 32 paired normalized outputs matched exactly, tolerance zero; only generated +call identities were excluded from comparison. + +Acquisition, hashing and other qualification traffic overlapped these runs. +Their timings are not a valid paired performance measurement. No throughput +improvement is claimed. + +Additional real-model checks: + +- A declared two-step forced function/tool-result episode passed JSON and SSE, + with exact expected semantics, complete named events, identities, argument + chunks and one terminal per request. Four generations per run; both baseline + and embedded arms passed, with no remaining worker slots or queued jobs. +- Both arms passed 11 checks covering stored response retrieval, input items, + continuation, deletion, required/none policies, disconnect after actual output, + slot release without server restart and exact follow-up generation. +- The baseline passed 112 storage/policy assertions across JSON/SSE, + reasoning none/low and none/auto/required/forced function policies. + Full stored terminals matched the returned objects, including reasoning, + metadata and usage. An independent SSE verifier additionally checked every + captured stream's complete item/chunk/sequence graph. +- SIGKILL of the owned baseline engine after a real output delta produced one + `response.failed`. The control-plane PID stayed unchanged; the supervisor + loaded a new worker, released all slots and generated the exact expected + recovery text. This completed at 11:18:59 UTC; the failed request was not retried. + +## Actual Codex CLI capture and limits + +Codex CLI 0.160.0 ran in an isolated synthetic workspace with its own minimal +stdio MCP tool. The task read an orders CSV, obtained a discount via MCP, wrote +a JSON total and read it back. The private evaluator captured full Responses +request bodies and raw SSE without authorization headers. + +The first attempt was incomplete because the evaluator's MCP fixture required +approval while the CLI used approval policy `never`. The model correctly +refused to invent the missing policy. A second fresh attempt used automatic +approval review and an accurately annotated read-only MCP fixture. Shell and +MCP calls completed and the generated JSON exactly matched the independent +oracle: subtotal 186, discount 10, total 176, code `POLICY-731`. + +The strict final-text judge nevertheless **failed**: the model added an +explanation before the requested exact final marker. This failure is retained. +All nine captured SSE responses across both attempts passed independent +protocol validation. There were no malformed tool arguments or missing +terminal events in those captures. + +Replaying the three successful-attempt requests as non-streaming JSON returned +HTTP 200 but did **not** reproduce all text byte for byte. Differences included +an additional read-only `ls` in a shell command, heredoc whitespace and reasoning +wording. Cache state differed; no serializer defect was isolated by this test. +Do not describe this as a strict raw Codex replay parity pass. The separate +controlled JSON/SSE tool episode above did pass exact semantic comparison. + +## Actual CUDA CI + +[GPU workflow 37305522699](https://github.com/paveldhq/strata-next/actions/runs/37305522699) +ran the existing `keyless-cuda` job against runtime source `9409dc9` on the +freed RTX 5090 with CUDA 13.2.2. All three CTests passed: query routing, +V-only streaming and conversation snapshots. Query maximum absolute error was +`6.55651093e-7`; attention relative L2 error was at most `1.32984469e-7`. +The stream test covered 306 batches with zero failures and an identical ring +restore; snapshot testing passed 2,448 assertions. + +The one-job ephemeral runner deregistered itself and removed its credentials. +These synthetic CUDA correctness results do not reverse the previously failed +pretrained-model V-only quality gate. V-only remains experimental and disabled +in the model qualification above. + +## Private evidence + +Artifacts, source hashes, MTP pins, configuration, raw responses, synthetic +workspace results, telemetry and process records remain in the private +`qualification-9409dc9` and remote `linux-qualification-20261005` directories. +No weights, request captures, API keys or generated artifacts are committed. +Detailed checkpoints are attached to LeaseVibe STRA-9 and STRA-12. diff --git a/docs/keyless-runtime.md b/docs/keyless-runtime.md new file mode 100644 index 00000000..99eaeb39 --- /dev/null +++ b/docs/keyless-runtime.md @@ -0,0 +1,83 @@ +# Experimental Keyless QSA runtime + +Requirements of record: `PROJECT_CHARTER.md` G7 and MCP `STRA-11`. +Method source: [Keyless Attention](https://arxiv.org/html/2606.21848v1), +effective query projection and GQA value-space routing. + +The pretrained Qwen retrofit is a distinct experiment from the authors' +from-scratch training. It is never enabled as the normal Strata default. +The old V→K activation predictor is not used by this implementation. + +## Representation and operations + +- Each main QSA layer stores a single INT8 V pool and its quantization scales, + in both resident GPU pages and the authoritative host mirror. Full attention + K codes and scales are not allocated. Independent QSA indexer keys remain. +- The original per-head query and gate projection is retained. Its query half + is normalized with the existing Q norm, transformed by an explicit per-head + routing matrix, then position-encoded. The gate half is unchanged. +- Attention scores use the rotated view of cached V at the selected token's + position. The value sum retrieves the raw, unrotated V. Rotation happens + while reading V; no second persistent rotated V cache is required. +- Prefill, single-token decode, speculative verification, streaming page + movement and conversation snapshots must implement the same representation. + The MTP draft model retains its original K+V cache; it is a distinct model. +- Initial support is INT8 without the optional Hadamard rotation. Unsupported + KV formats, missing/invalid routing data or mismatched source projections + fail startup explicitly. A runtime cannot silently fall back to K+V. + +## Conversion and quality + +For row-major source projections, the linear initializer is +`A = Wk Wv.T pinv(Wv Wv.T)`, so `q_keyless = q A` and the effective +un-normalized query projection is `A.T Wq`. Query/gate rows are split per +head; each query head is matched to its GQA value head. Export records source +tensor digests and measures the score-matrix residual. This residual evaluates +the paper's linear subspace condition, not the full normalized model. + +Source Q/K normalization is nonlinear and is not proven removable by this +initializer. Frozen-model query-routing calibration must account for it and +RoPE before quality preservation can be claimed. Routing artifacts identify +their source model and calibration state. Weight-space error, attention error +and full-model task quality are separate results. + +## Acceptance and trial + +The CUDA implementation must match an independent CPU reference for routed +queries, causal selections, positional scores and raw V retrieval, including +nonidentity page tables and multiple verifier rows. Saved states must be +format-specific. Ordinary K+V must preserve its baseline result. + +Use the same console harness and game prompt for full-model comparisons. +Report completed requests, tool calls, input/cached/output tokens, weighted +decode tok/s, wall time, memory and independent game checks. A multi-day +`qwen-codex` trial requires repeated request, tool-call, cancellation and +long-context stability evidence plus an explicit rollback profile. + +## Current measured state (2026-10-04) + +The first implementation has passed numerical CUDA, physical streaming and +snapshot tests on RTX 5090. The pretrained-model retrofit failed the identical +console agent workload both before and after frozen routing distillation. +This is an experimental architecture with a **failed model quality gate**. +It is not qualified for a multi-day project trial. See +[the measurements](experiments/2026-10-04-keyless-runtime.md). + +The initial artifact is generated with `scripts/prepare-keyless-routing.py`. +`STRATA_KEYLESS_PREFILL_TRACE` captures bounded ordinary-Qwen teacher activations +only in offline inference. `scripts/calibrate-keyless-routing.py` fits causal +teacher attention KL while keeping the pretrained projections and norms frozen. +Training and validation are distinct prompts; full-model task quality is a +separate gate. Reusing validation to compare fits makes it a calibration +validation set, not a final unbiased model benchmark. + +`STRATA_KEYLESS_ROUTING` enables a source-bound artifact. Initial support requires +INT8, no Hadamard rotation, one GPU stage and zero position base. Missing or +mismatched artifacts fail explicitly. M-RoPE value scoring follows the same +per-cell time/height/width positions as query rotation. Image task quality has +not been qualified; only the positional kernel arithmetic has been tested. + +`scripts/check-keyless-gpu.sh` runs synthetic CUDA gates on an idle GPU, without +model weights. CI includes offline routing/gradient tests and an optional manual +CUDA job for a configured `strata-gpu` self-hosted runner. Hosted Actions has +not run: this local project still has no hosted GitHub repository. diff --git a/docs/model-assets.md b/docs/model-assets.md new file mode 100644 index 00000000..373a3c59 --- /dev/null +++ b/docs/model-assets.md @@ -0,0 +1,48 @@ +# Model acquisition + +The `strata-next` CLI can fetch and verify model files described by a versioned manifest. Each file has a pinned HTTPS URL, byte length, and SHA-256. It writes to `NAME.part`, resumes with HTTP Range when supported, verifies the complete digest, and renames the file only after successful verification. A server that ignores Range causes a full restart of that file. Existing completed files are hashed before reuse. A failed hash is never accepted as a completed model. + +Each shard gets at most four transfer attempts with 1, 2, and 4 second waits between retries. Retries cover connection and body failures, timeouts, short responses, and HTTP 408/429/5xx. Every attempt rechecks the partial file before resuming; malformed ranges, local filesystem errors, and SHA-256 failures stop the fetch. Authenticated Hub access remains to be implemented. + +For the initial Qwen3.8-Flash-Next IQ3_S profile: + +```sh +strata-next model fetch qwen-iq3-s --output /models/qwen-iq3-s +strata-next model verify qwen-iq3-s --output /models/qwen-iq3-s +strata-next model inspect /models/qwen-iq3-s/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +strata-next model extract-tokenizer /models/qwen-iq3-s/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf --output /models/qwen-iq3-s/pack +``` + +The profile manifest is embedded in the executable; a custom manifest path can be used in place of `qwen-iq3-s`. The two shard URLs are pinned to Hugging Face repository commit `ed59f92082b1e93c0e96d60a8b11aab089b52f09`, matching the imported Strata setup source. Both shards were downloaded outside Git and matched their manifest SHA-256 values locally: shard 1 `54,817,524,224` bytes / `4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3`; shard 2 `28,800,138,432` bytes / `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`. + +The executable carries its HTTPS trust roots, so `model fetch` does not need a CA bundle installed in a minimal container. TLS certificate and hostname verification remain enabled. + +For a private Hugging Face repository, set `HF_TOKEN` in the process environment when running `model fetch` or `model ensure-sharded-streamed`. The CLI adds it as a Bearer header only to requests whose URL has the exact `https://huggingface.co` origin; it does not put the token in the manifest, logs, archive, or provenance. Cross-origin redirects drop the authorization header. A model URL containing embedded user credentials is rejected. The already downloaded target shards do not require this option. + +For small GGUF fixtures, `model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N` runs fetch, source verification, experimental KAR-2 preparation, and archive verification in one command. On rerun it hashes the source shards and verifies the archive payload, provenance, and level count before reusing the file. A damaged or mismatched archive fails closed and is never overwritten automatically. This preview is limited to 64 MiB of GGUF input; the embedded `qwen-iq3-s` manifest is deliberately rejected before download. It does not provide full-model conversion or an approved serving artifact. + +`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` is the opt-in, uncapped experimental path. It fetches and verifies source shards, prepares a bounded-memory KAR-2 archive if absent, independently verifies the new archive and provenance, and rehashes all sources plus the archive before reuse. It prints actual archive bytes and accounted bits per weight. Use a model volume with enough capacity for the GGUF shards, temporary sections, and final archive. Streamed policy v4 splits any tensor too large for KAR-2's 32-bit plane stride into adjacent records and records their parent mapping and per-part source/F32 hashes in provenance. The 51,200,245,760-element `per_layer_token_embd.weight` becomes two records of 32,000,000,000 and 19,200,245,760 elements. A complete level-2 archive measured 55,295,529,472 bytes (51.50 GiB, 66.13% of the source GGUF bytes); see [build validation](build-validation.md). Its maximum tensor relative L2 error was 0.68008092. Model-level quality and serving approval remain pending. + +`model checksum-kar-preview FILE.kar TENSOR LEVEL` independently decodes one bounded nested tensor from the archive and prints an FNV-1a checksum of the F32 output. On Linux, compare `output_fnv1a64` with the same field from `strata-kar-gpu-smoke FILE.kar TENSOR LEVEL ITERATIONS`. This checks CPU and CUDA reconstruction byte for byte on a fixture; it is not a full-model quality gate. + +`model analyze-sharded-kar FILE.kar --manifest SPEC --source-dir DIR --levels N --output REPORT.json` verifies a streamed archive and its source shards, then compares bounded GGUF and KAR samples for every archive record. Append `--assume-verified` only when the exact source shards, archive, and provenance were fully verified earlier and have remained immutable: this fast mode checks their structure and mapping but does not rehash all bytes or rederive the 708 GB virtual F32 stream. The JSON records which verification mode was used, the archive digest, and relative L2 for up to three nonoverlapping, aligned windows of at most 4,096 values at the beginning, middle, and end of each record. It reads existing files without creating another model copy. Sparse samples can miss a local failure; neither mode is a full-tensor error bound or model-quality gate. + +`model prepare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --candidates CANDIDATES.json --output OVERLAY.kar` is an experimental way to re-encode selected KAR records at a higher level. Candidates may name an unsplit tensor or one partition from a v4/v5 base, such as `per_layer_token_embd.weight#strata-part-001-of-513`; the candidate's `elements` must equal that record's element count. Preparation binds the selected GGUF byte range, its physical and derived F32 digests, and the base KAR source record, verifies the resulting overlay, writes a provenance sidecar, and removes staging sections. `model compare-kar-overlay MANIFEST --source-dir DIR --base BASE.kar --overlay OVERLAY.kar --output REPORT.json` decodes every selected record from both archives against its GGUF source range, rechecks the physical and F32 digests and overlay CRCs, and records paired full-record relative L2. The base archive's earlier full verification is assumed; it is not rehashed by the comparison. No serving loader applies this overlay yet, and lower tensor error alone does not pass the model-quality gate. + +Full streamed preparation checks available space on the output volume before creating section files. Its bound counts the minimum bit-plane payload for every part and accounts for a possible RAW fallback. A volume below that bound is rejected early; passing the bound does not guarantee enough room for scales, codebooks, alignment, and provenance. Keep the verified source shards and existing archive on their external volume when retrying with more space. + +When `model ensure-sharded-streamed` sees all source shards already present and needs to create a new archive, it reads only their GGUF directories for an even earlier minimum-space rejection, before rehashing the shards. This preliminary metadata is used only to reject an impossible destination; a passing result still goes through SHA-256 source verification and the preparation-time guard. Missing shards take the normal resumable fetch path. Reusing an existing archive does not require room for a second copy. + +`model smoke-fixture --output FILE.kar` writes a deterministic 32-element KAR-2 archive named `smoke.expert` and prints its archive digest and two-level CPU decode checksum. It refuses to overwrite an existing file. This model-free artifact lets the Linux CUDA decoder be checked before the target model is available. + +The acquisition stage downloads GGUF files; the native tokenizer stage extracts and uses tokenizer assets. Before fetching, the CLI checks available filesystem space against the remaining bytes in all manifest shards and checks again after the server chooses resume or restart. This avoids starting a transfer that already cannot fit; filesystem quotas or concurrent writers can still cause a later write failure. The native experimental KAR-2 preparation path exists, but upstream `iq_pack.py` equivalence, compressed GPU loading, and model startup still need implementation and differential validation. See [compressed runtime contract](compressed-runtime.md) for the target `fetch` → `verify` → `prepare` → GPU decode sequence and `with-key`/`without-key` cache profiles. Model bytes belong on an external volume and never in Git or CI artifacts. + +`model inspect` reads the GGUF v3 header and tensor directory without mapping weight data. It checks metadata types, counts, alignment, duplicate keys/tensors, split numbering, and whether tensor start offsets fit the file. This is a structural check, not proof that all tensor bytes or quantization geometry are valid. + +`model extract-tokenizer` validates the Qwen byte-level BPE metadata, then writes `tokenizer/` under the output directory through a staging directory. It requires a nonempty chat template and refuses to overwrite an existing tokenizer directory. The dense/expert pack is still pending. + +The extracted directory is accepted by the native `model tokenize` and `model detokenize` commands. `model tokenize TOKENIZER_DIR --stdin --special` reads UTF-8 text from standard input and prints a JSON array of token IDs; `--special` enables control tokens such as `<|im_end|>`. User-defined tokens remain literal in both modes. `model detokenize TOKENIZER_DIR 1,2,3` prints a JSON string. The native BPE path matched the pinned upstream tokenizer on 20 cases from the real verified first shard. The dense/expert pack and model startup remain pending. + +The extracted real tokenizer's five files total 9,100,814 bytes (8.68 MiB) on the local model volume. Rust tokenization and token-ID-to-text conversion use host memory; this on-disk size is not a measurement of the Rust process's RAM use. Embedding and output weights are model tensors and have a separate GPU/CPU placement budget. + +Metadata references: [Hugging Face file download documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/file_download) and the two pinned files in the [model repository](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF/tree/ed59f92082b1e93c0e96d60a8b11aab089b52f09/IQ3_S). diff --git a/docs/performance-ledger.md b/docs/performance-ledger.md new file mode 100644 index 00000000..5349aefb --- /dev/null +++ b/docs/performance-ledger.md @@ -0,0 +1,21 @@ +# Performance ledger + +**Status:** no controlled baseline has been measured in this repository. The numbers in `PROJECT_CHARTER.md` are preliminary reference points. + +For each baseline or A/B result, store the machine-readable report under a documented artifact location and add a short entry here with its digest or permanent reference. + +## Required record + +- Date, benchmark harness commit, engine commit, and control-plane commit. +- Model name, quantization, and file digest. +- GPU, driver, CUDA toolkit, power limit, and relevant clock conditions. +- Context mode, KV format and residency, slots, batch size, speculation policy, and all other effective settings. +- Workload identity; prompt/output token counts; cold or warm cache state. +- TTFT, prefill tok/s, decode tok/s, end-to-end wall time, and aggregate throughput where applicable. +- Draft acceptance, expert-cache hit rate, KV-streaming hit rate, and RAM/VRAM/PCIe traffic where measured. +- Per-run data, mean, median, percentiles, confidence interval, and paired A/B method. +- Protocol, deterministic, model-quality, performance, and stability gate results as applicable. + +## Entries + +No verified entries yet. diff --git a/docs/preparation-contract.md b/docs/preparation-contract.md new file mode 100644 index 00000000..20b92940 --- /dev/null +++ b/docs/preparation-contract.md @@ -0,0 +1,15 @@ +# Native model preparation contract + +The reference implementation is the imported upstream Strata at the commit in `docs/upstream.md`. This inventory records what the native `model prepare` command must reproduce before the Python tooling can be removed from the install path. + +| Upstream source | Inputs | Outputs and required behavior | +| --- | --- | --- | +| `tools/iq_pack.py` | First GGUF shard, all adjacent split shards, optional base pack | `index.txt` v3, aligned `dense.bin`, `conversions.json`, `native_experts.txt` v3/v4 completion marker, tokenizer files; optional `extra.bin`, `experts.bin` and provenance sidecar | +| `tools/pack_index.py` | Pack `manifest.json` from the older pack path | `index.txt` v3 with file ID, type/kind, source/destination offsets, shapes and quantization plane attributes | +| `tools/strata_tokenizer.py` | GGUF tokenizer metadata | `tokenizer/vocab.json`, `merges.txt`, `token_type.json`, `tokenizer.json`, and `chat_template.jinja` | + +`iq_pack.py` serves quantized non-expert tensors from the original GGUF, writes small float tensors to `dense.bin`, and records exact or rounded conversions. Its `native_experts.txt` has absolute offsets for gate/up/down in each shard and is published last as the pack completion marker. An optional `experts.bin` is reused only after its source sidecar and sampled blobs match the current model. The 28.8 GB per-layer token embedding table remains in the GGUF. The initial IQ3_S path should preserve native quantized bytes; no lossy conversion is enabled by default. + +`strata_tokenizer.py` is the behavioral oracle for Qwen byte-level BPE, special tokens, the `qwen35` pre-tokenizer pattern, and chat template. Native extraction alone is insufficient; encoding and decoding must be checked on multilingual text, emoji, combining marks, whitespace, control bytes, and tool-call prompts. + +The Rust CLI now has bounded `model inspect`, `model extract-tokenizer`, and native BPE encode/decode commands. Extraction checks the tokenizer metadata and produces the five upstream asset files without Python. A synthetic GGUF was compared against the pinned upstream extractor; all five files matched as parsed JSON or exact text. Native BPE matched upstream on 40 synthetic full-byte vocabulary cases, covering multilingual text, emoji, combining marks, control bytes, long words, and control/user-defined literals. These checks do not validate the real IQ3_S tokenizer. The next step is to compare header metadata with upstream `strata-gguf` on representative fixtures and both real IQ3_S shards, then implement the pack formats and differential byte checks. No model bytes are committed to Git. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 00000000..9acda82e --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,122 @@ +# Strata Next implementation plan + +## Product shape + +The target interface is one Linux command, `strata-next`, with `serve`, `model fetch`, `model verify`, `model prepare`, `doctor`, and `benchmark` operations. A model remains on an external volume. The command must keep production serving independent of Python. The user-facing executable may eventually contain a statically linked Strata engine, but CUDA still needs the installed NVIDIA driver and its `libcuda.so`. The CLI checks the existing driver; it does not install or bundle one. For the current CUDA 13.0 GA baseline, the minimum Linux driver is 580.65.06 per NVIDIA's release notes. Until engine integration is proven, the Rust executable and C++ engine remain separate build artifacts and the CLI reports that limitation clearly. + +`LAYERED_EXTENDED` is retained as an exact user-provided term; no runtime semantics have been assigned to it yet. + +## Work packages + +| ID | Package | Deliverable | Acceptance | +| --- | --- | --- | --- | +| P0 | Linux foundation and CI | Pinned Rust, Linux lint/tests, musl CLI artifact, release workflow | CI builds a runnable Linux artifact and rejects format/lint/test failures | +| P1 | Artifact acquisition | Manifest-pinned model downloads, size/hash verification, safe resume, external volume | Interrupted local HTTP fixture resumes; wrong hash never becomes a completed model | +| P2 | Model preparation | Inspect GGUF and tokenizer; port pack/index; create and verify provenance-pinned KAR-2 archives | Prepared output matches upstream, with source and archive digests and separate KAR quality gate | +| P3 | Native API | Tokenization, prompt template, `/v1/responses`, tool calls, schema, live SSE, cancellation | Sanitized Codex replay has no protocol errors or missing terminal events | +| P4 | Single executable | Link/embed engine and CUDA KAR decoder where viable, check preinstalled NVIDIA driver, one-command startup | Linux node with a compatible driver loads compressed weights and decodes on GPU without Python or manual engine installation | +| P5 | Reliability and telemetry | Restart, timeouts, backpressure, metrics, graceful drain | Soak and failure injection pass without orphaned slots or incomplete streams | +| P6 | Performance and scale | Controlled baseline, KAR GPU path, 2×256K, 1×512K, scheduler, with-key and without-key cache profiles | Charter quality/performance gates and reproducible reports pass | + +## Sequence and dependencies + +1. Complete P0 and P1 locally. Keep model bytes out of Git and verify every finished file by SHA-256. +2. Port P2 with differential fixtures from upstream. Do not infer tensor correctness from a file extension alone. +3. Connect the existing Rust worker pipe to P3. Use the real model only when the GPU node is free; use synthetic protocol tests meanwhile. +4. Package P4 after the ABI and CUDA link strategy are measured on Linux. Do not label a control-plane-only musl artifact as the complete GPU runtime. +5. Add P5 before production deployment, then run the baseline and P6 experiments with the charter's gates. + +## Task queue + +### P0 — Linux delivery + +- [x] Pin the Rust toolchain and enforce format, Clippy, Rust tests, and CPU tests. +- [x] Write the local GitHub Actions workflow for Linux checks, a musl build, ELF dependency checks, artifact upload, and tag prerelease. +- [ ] Create the Strata Next GitHub repository, add its project remote, and run the workflow on a hosted Linux runner. +- [ ] Run a CUDA engine build and loader smoke test on Linux GPU hardware. +- [x] Build the isolated KAR CUDA decoder for RTX 5090 and match synthetic full/row plus two real overlay-record checksums with the CPU oracle. + +### P1 — model acquisition + +- [x] Embed a commit-pinned IQ3_S manifest with size and SHA-256 for both GGUF shards. +- [x] Implement resumable downloads, integrity checks, and a local interrupted-transfer test. +- [x] Check free disk space for all outstanding shard bytes and again after each resume/restart response. +- [x] Report per-shard byte and percentage progress while downloading, including resumed offsets. +- [x] Verify both complete real IQ3_S shards on an external volume and record measured digests. +- [x] Retry transient model transfer failures with bounded backoff and verified partial-file resume. +- [x] Accept an optional process-local `HF_TOKEN` for exact HTTPS Hugging Face URLs; reject URL-embedded credentials and keep redirects from forwarding the header across origins. + +### P2 — native model preparation + +- [x] Inventory `iq_pack.py`, `pack_index.py`, and `strata_tokenizer.py` outputs and formats. +- [x] Port bounded GGUF v3 header and tensor-directory inspection into native code. +- [ ] Validate the native inspector against representative upstream GGUF fixtures and both real IQ3_S shards. +- [x] Port tokenizer asset extraction without a Python runtime and compare it with upstream on a synthetic GGUF. +- [x] Port tokenizer encode/decode and compare token IDs with upstream on a synthetic full-byte vocabulary. +- [x] Extract the SHA-256-verified first real shard’s tokenizer and compare native IDs and roundtrips with the pinned upstream oracle on Unicode and special-token cases. +- [ ] Port the IQ3_S pack/index path without a Python runtime and verify the real tokenizer. +- [ ] Differentially compare metadata, tensor bytes, and tokenizer behavior against upstream output. +- [ ] Add `model prepare` with source digest, KAR-2 archive validation, atomic completion, and no model data in Git. +- [x] Add bounded native KAR-2 metadata inspection, streaming payload CRC verification, and optional source-manifest identity check (decode still pending). +- [x] Emit a byte-identical synthetic KAR-2 RAW/NESTED archive from native Rust tensor slices; publish after verification without overwriting an existing file. +- [x] Index supported GGUF tensor payloads with exact block geometry and bounded per-tensor hashing; reject overlapping, truncated, or malformed source layouts. +- [x] Stream RAW tensor bytes into KAR-2 with a fixed 1 MiB buffer and per-tensor digest verification. +- [x] Stream pre-encoded NESTED sections into KAR-2 with checked section geometry, finite f16 values, zero padding, and digest verification. +- [x] Encode a synthetic f32 tensor to native KAR scales and bit planes using supplied calibration; keep the lossy path experimental. +- [x] Decode a selected KAR bit-plane prefix into a caller-sized CPU buffer for numerical tests. +- [x] Decode a bounded arbitrary range of a large nested KAR tensor from stored archive bytes and compare selected real GGUF ranges with pinned ggml values. +- [x] Fit experimental top-down nested boundaries and f16 books from a supplied normalized sample; match pinned koference synthetic oracles. +- [x] Wire a small F32 GGUF through native calibration, encoding, reconstruction check, and verified KAR publication under an explicit preview command. +- [x] Spool each preview tensor as a canonical NESTED section and assemble the archive from file-backed sections; clean staging after success or failure. +- [x] Decode synthetic GGUF IQ3_S source blocks in native Rust with a pinned ggml grid and bounded output. +- [x] Define and compute a versioned virtual F32 stream identity for a bounded-memory, all-IQ3_S GGUF, retaining original GGUF and tensor digests separately. +- [x] Convert a small all-IQ3_S GGUF to an experimental KAR preview with virtual F32 source identity and an original-source provenance sidecar. +- [x] Recompute the IQ3-derived source against the original GGUF and verify each KAR source record, archive payload CRC, and provenance sidecar. +- [x] Define and compute a versioned virtual F32 source for a single GGUF mixing IQ3_S with F32, F16, and BF16 tensors. +- [x] Prepare and independently verify a small KAR preview from a mixed IQ3_S/F32/F16/BF16 virtual source. +- [x] Compute a versioned virtual F32 identity across manifest-verified GGUF shards in filename order, with global tensor offsets. +- [x] Encode and independently verify a small, manifest-pinned sharded KAR preview with provenance. +- [x] Add an experimental sharded preparation command with bounded calibration and encoding and no preview size cap; verify its archive and provenance on synthetic F32/IQ3_S shards. +- [x] Add an opt-in full-size fetch → verify → prepare → verify CLI path that reuses only a reverified streamed archive. +- [x] Inspect both target GGUF directories and statically link pinned ggml CPU dequantizers for every type found there; exercise them on bounded synthetic blocks. +- [x] Check native ggml block size against GGUF geometry and decode a real block of every first-shard type; version the streamed derivation after correcting the kind-18/22 dispatch. +- [x] Measure a provisional, reproducible IQ3_S/IQ4_NL real-data slice with the streamed KAR path; record archive size, source identity, and reconstruction error without treating the slice as a model-quality gate. +- [x] Run full streamed preparation and independent verification; both target shards matched their manifest SHA-256 values and representative real blocks/ranges matched the CPU oracle. Model-level quality and GPU execution remain separate gates. +- [x] Resolve a fully verified base KAR archive plus precision overlay into a per-record selection map; both real archive hashes, all payload CRCs, and 22 replacements passed. GPU loader use remains open. +- [ ] Verify IQ3_S values against upstream CPU dequantization on representative tensors. +- [ ] Promote the bounded GGUF/KAR path to `model prepare` after real-shard validation, per-class rate policy, and quality checks. +- [ ] Make one-command `serve` fetch, verify, and prepare missing model assets, then reuse the verified compressed archive. +- [ ] Compare KAR reconstruction with its CPU oracle; run full-model quality before making the compressed path a default. + +### P3 — API and worker + +- [x] Validate a Responses request subset and build synthetic JSON/SSE traces. +- [x] Exercise `GEN`/`T`/`DONE` through a resident fake worker. +- [x] Add native tokenization and Qwen prompt formatting; connect a restricted non-streaming text path to the worker command queue. +- [x] Stream text deltas directly from the worker with bounded channels, UTF-8 assembly, terminal SSE events, and client cancellation in synthetic tests. +- [x] Parse complete Qwen function calls in Rust for buffered Responses output, preserving nested delimiter text and checking argument schemas; synthetic HTTP test passes. +- [x] Render stateless text input arrays with paired function calls and outputs into the next Qwen prompt; synthetic HTTP continuation passes. +- [x] Store completed responses in a bounded, process-local cache by default and replay `previous_response_id` with new input; synthetic tool-result continuation passes. +- [ ] Stream live output with cancellation, backpressure, tool calls, reasoning, and terminal events. Text and completed function calls are connected; reasoning remains open. +- [ ] Replay sanitized real Codex sessions and compare against the upstream server. + +### P4–P6 — production and optimization + +- [ ] Package the C++/CUDA engine with the Rust CLI into one user-facing Linux executable where the link strategy permits. +- [ ] Keep the KAR archive compressed through GPU residency; integrate `libkar` reserve/decode, PLE row decode, expert miss scheduling, and measured transfer/decode/multiply overlap. +- [x] Verify base plus precision overlay and account for selected compressed residency and F32 scratch without double-counting replaced records; the real v4 pair was measured as archive metadata, not GPU execution. +- [ ] Expose `with-key` and experimental `without-key` KV modes; keep QSA indexer keys and pass the separate Keyless quality gate before default use. +- [ ] Add process restart, metrics, auth, failure injection, and soak tests. +- [x] Stop and drain an abandoned internal generation; interrupt an active generation during shutdown. +- [ ] Capture the 1×256K baseline, then implement and validate 2×256K and 1×512K. +- [ ] Evaluate speculation, KAR, and Value-Only only under the charter's separate quality gates. + +## CI/CD policy + +Pull requests and main commits run Rust format, Clippy, tests, synthetic replay, and CPU engine tests on Linux. CI builds a static musl **CLI/control-plane** artifact and checks that it has no ELF interpreter. Version tags can publish this artifact with a SHA-256 checksum; a full GPU release waits for a Linux CUDA build, runtime smoke test, and signed-off model quality gate. No model weights or tokens enter CI artifacts. + +## Current status + +P0 has local CI assets; Linux/arm64 and Linux/x86_64 musl control-plane/CLI artifacts ran successfully, with the x86_64 artifact checked on the RTX 5090 host. Hosted Actions still needs a GitHub repository and runner. P1 has `model fetch` and `model verify`; both real shards passed their manifest SHA-256 values on the Linux NTFS volume. P2 has bounded GGUF indexing, real-tokenizer parity against upstream, pinned ggml CPU decoding with checked block geometry, and an experimental bounded-memory sharded GGUF-to-KAR path. Streamed policy v4 partitions the giant per-layer tensor so its bit-plane stride fits KAR-2. The complete level-2 archive was produced from both verified shards: 55,295,529,472 bytes from 83,617,662,656 source bytes (66.13%); an independent verifier passed source identity, KAR records, payload CRCs, archive hash, and provenance. Its maximum tensor relative L2 error was 0.68008092. A separate 18,827,008-byte level-3 overlay for 22 high-distortion records reduced paired full-record relative L2 for every selected tensor, but no serving loader applies it yet. These numerical results do not pass the model-level quality gate. Sampled IQ3_S values matched pinned ggml bit for bit, and selected archived ranges were independently decoded and compared with GGUF values. An isolated Linux CUDA smoke matched CPU output checksums for two real overlay records. An opt-in PLE-only GPU row cache now decodes compressed rows inside the serving engine; a 4,097-token cross-part gather matched CPU KAR byte for byte, and short paired 128-token runs produced identical output. Its small measured throughput differences are not an accepted end-to-end gain, and expert weights still use the native pack. A separate custom V→K regression screen reported 0.3023 attention-output relative L2 error on a limited held-out proxy. It did not implement the cited Keyless Attention query-routing method and cannot establish whether that method preserves quality. The physical V-only cache, query-routing CUDA kernels, frozen-routing calibration and console agent experiments are now implemented and tested on RTX 5090. Technical gates passed, while both pretrained Qwen V-only agent variants failed model quality and remain opt-in; see `docs/experiments/2026-10-04-keyless-runtime.md`. No V-only production trial or speed improvement is qualified; see the methodology correction in `docs/experiments/2026-10-03-v-only-screen.md`. The Responses route has a restricted preview backed by the worker queue, including live text SSE deltas, cancellation, completed streaming function calls with schema checks, stateless tool-result replay, and bounded process-local `previous_response_id` continuation, tested with a mock worker. Live reasoning, full-model quality, native-versus-GPU agent throughput, and a complete single-file GPU runtime remain pending. + +References: [NVIDIA CUDA 13.0 release notes](https://docs.nvidia.com/cuda/archive/13.0.0/cuda-toolkit-release-notes/index.html), [NVIDIA driver components](https://docs.nvidia.com/deploy/cuda-compatibility/latest/why-cuda-compatibility.html), and [Rust musl target support](https://doc.rust-lang.org/rustc/platform-support.html). diff --git a/docs/upstream.md b/docs/upstream.md new file mode 100644 index 00000000..0c42da90 --- /dev/null +++ b/docs/upstream.md @@ -0,0 +1,46 @@ +# Strata upstream provenance + +**Status:** source imported as a local Git subtree and preserved in a private hosted repository. + +| Field | Value | +| --- | --- | +| Upstream repository URL | https://github.com/Niko1221/Strata.git | +| Upstream commit SHA | `d9ab8435f654c368c586340d490915f6addf56a3` | +| Local repository path | `engine/strata/` | +| Hosted project repository URL | https://github.com/paveldhq/strata-next (private) | +| Import date | 2026-10-02 | +| Engine build instructions | `scripts/build-cpu.sh` for source checks; CUDA build still to validate on Linux GPU | +| Local patch strategy | Squashed Git subtree; preserve upstream commit IDs in subtree merge messages | + +The local Git remote `strata-upstream` points to the URL above. To review an update, run `git fetch strata-upstream main`, inspect the diff from the pinned SHA, choose a specific new commit, then run `git subtree merge --prefix=engine/strata --squash ` and the relevant checks. Do not silently advance to whatever happens to be latest. + +The imported upstream tree includes its own small optional experimental control-vector GGUF and reference data. Production model weights, captures, and generated output remain outside this repository. The private project repository was created on 2026-10-04; its initial `main` is `858e7aa050f56b051dac5e3d7b765a05cb958aee`. This preserves the existing subtree history and does not change the pinned upstream identity. + +## Local CUDA validation, 2026-10-04 + +The upstream identity above is unchanged. The local Keyless opt-in fork compiled +on Linux with CUDA 13.2.86 for RTX 5090 (SM 120). Query-routing numerical parity, +V-only streaming and conversation snapshots passed. Pretrained-model quality +failed; see [the report](experiments/2026-10-04-keyless-runtime.md). The ordinary +K+V profile remains the production choice. + +## Local Linux packaging profile, 2026-10-04 + +STRA-23 adds the default-off `STRATA_CUDA_STATIC` CMake profile: static toolkit +runtime/BLAS targets and GNU C++ runtime linkage for Linux. The imported source +commit above remains unchanged; this is a local build-policy patch. A complete +CUDA 13.2/SM 120 compilation and ELF audit passed without GPU inference. The +candidate still needs host glibc 2.43 and an NVIDIA driver; model qualification +is pending. See `deploy/README.md` and `docs/build-validation.md` for the exact +scope, artifact identity and remaining packaging limits. + +## Experimental KAR expert integration, 2026-10-05 + +The pinned upstream commit remains unchanged. Local default-off +`STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS` adds a native verifier cache-miss callback, +linked to the separate `gpu/kar` component. Resident native hits and batched prefill +retain their IQ weights; short prompt ingestion uses the verifier and therefore +also exercises KAR misses. The runtime requires explicit archive and precision +environment settings, validates the archive payload and expert geometry, and +rejects unsupported pool/multi-device configurations. This is an experimental +quality arm, not full compressed-model residency or a qualified speedup. diff --git a/engine/README.md b/engine/README.md new file mode 100644 index 00000000..f67793b3 --- /dev/null +++ b/engine/README.md @@ -0,0 +1,3 @@ +# Engine + +The Strata C++20/CUDA source is imported under `strata/` as a Git subtree. The exact upstream commit and update method are recorded in `../docs/upstream.md`. Keep local changes in this directory traceable against that commit. diff --git a/engine/strata/.dockerignore b/engine/strata/.dockerignore new file mode 100644 index 00000000..4f341af3 --- /dev/null +++ b/engine/strata/.dockerignore @@ -0,0 +1,27 @@ +# Keep the image to the source only: everything generated is re-created on +# first start (inside the container or on the /data volume). +.git + +# local Python environment (rebuilt in the image) +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ + +# setup.py outputs and downloads (engine, packs, models, logs) +/engine/ +/build/ +/build*/ +/dist/ +/packs/ +/mtp/ +/models/ +/Strata-data/ +third_party/llama.cpp/ +third_party/*.zip +*.done +*.log +strata-*.json +strata-*.txt +run-*.sh +run-*.bat diff --git a/engine/strata/.gitattributes b/engine/strata/.gitattributes new file mode 100644 index 00000000..466d97e8 --- /dev/null +++ b/engine/strata/.gitattributes @@ -0,0 +1,9 @@ +# Frozen prompts are hashed byte for byte (manifest sha256): never convert their line endings. +bench/prompts/** -text + +# launchers keep their platform line endings wherever the repository is cloned +*.sh text eol=lf +*.bat text eol=crlf + +# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp +tests/data/native_experts/** -text diff --git a/engine/strata/.github/FUNDING.yml b/engine/strata/.github/FUNDING.yml new file mode 100644 index 00000000..35b26a9a --- /dev/null +++ b/engine/strata/.github/FUNDING.yml @@ -0,0 +1 @@ +buy_me_a_coffee: strataengine diff --git a/engine/strata/.gitignore b/engine/strata/.gitignore new file mode 100644 index 00000000..cb6477db --- /dev/null +++ b/engine/strata/.gitignore @@ -0,0 +1,53 @@ +# Generated, not source: deterministic build products of tools/ (see docs/). +# tiny-qwen4exp.gguf is ~113 MB, over GitHub's 100 MB file limit -- regenerate with +# python tools/make_tiny_model.py +bench/tiny-*.gguf +bench/wide-*.gguf +bench/micro/*.exe +bench/micro/*.obj +bench/micro/*.bin +bench/micro/*.dll +bench/micro/*.txt +*.log +build*/ +pack/ +logs/ +__pycache__/ +.pytest_cache/ +*.pyc + +# plan v0.3 P1 (repository hygiene, review E1): profiler captures and large diagnostic dumps stay out of git. +*.nsys-rep + +# Pi harness metadata (local session state, not project source) +*.sqlite +*.npz +*.occ1 +td.log + +# created by setup.py on the user's machine +/.venv/ +/build/ +/third_party/llama.cpp +/models/ +/packs/ +/mtp/ +/run-*.bat +/run-*.sh +/strata-*.json +/strata-*.log +/build-strata.bat +/.strata-mcp/ + +# image encoder (setup.py --vision): build output and the generated build script +build-vision*/ +build-vision.bat + +# setup.py outputs (engine, downloads) and release builds +/engine/ +/build-release*/ +/dist/ +*.done +/third_party/*.zip + +/.rocm-win/ diff --git a/engine/strata/AGENTS.md b/engine/strata/AGENTS.md new file mode 100644 index 00000000..3bcf107a --- /dev/null +++ b/engine/strata/AGENTS.md @@ -0,0 +1,23 @@ +# AGENTS.md + +Strata runs the Qwen3.8-Flash-Next mixture-of-experts model (and its Coder, Swift 1.5 and Unsloth variants) on a +normal PC: one NVIDIA or AMD graphics card plus system RAM, on Windows or Linux. It has a C++/CUDA/HIP engine +(`src/`, `include/`), a Python server with an OpenAI- and Anthropic-compatible API and a web app (`serve/`), and a +one-click installer (`setup.py`, started by `START-HERE.bat` / `setup.sh`). + +## Installing Strata for a user + +Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**: check the PC, pick the model by RAM, run setup non-interactively, +start and verify the server, and connect the user's apps. Never expose the server beyond `127.0.0.1` without +`--api-key`. As an alternative to shell commands, Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) +offers the same steps as tools. + +## Working on the code + +- How the engine works, every measured number, the API and all settings: [docs/DETAILS.md](docs/DETAILS.md) and + the [paper](docs/paper/Strata-Paper.pdf). +- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md). +- Setup's own tests run without a GPU or downloads: `python tools/test_setup_.py` (for example + `tools/test_setup_amd.py`, `tools/test_setup_choices.py`). +- Keep the docs' style: plain words, measured numbers with what they were measured on, no claims without a + measurement. diff --git a/engine/strata/CMakeLists.txt b/engine/strata/CMakeLists.txt new file mode 100644 index 00000000..4d9f2ca1 --- /dev/null +++ b/engine/strata/CMakeLists.txt @@ -0,0 +1,1110 @@ +# Strata Engine - top-level build (P1.S1). +# +# Targets (phase-1 §P1.S1): `strata_artifact` (no CUDA dependency), `tests`. `strata_plan` and the C++ +# `strata-pack` are added when their sources exist - a target with no sources would make the build graph +# claim something the tree does not have, which is worse than an absent target. +# +# CUDA targets arrive in Phase 2. The kernels need sm_80 or newer (tf32 mma, bf16 math) and the guard +# below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs +# and is wrong about its own performance, which is the worst of both outcomes. +cmake_minimum_required(VERSION 3.24) +project(strata VERSION 0.1.35 LANGUAGES CXX) +add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}") +# issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can +# be read back to the exact source line +if(MSVC AND CMAKE_BUILD_TYPE STREQUAL "Release") + add_compile_options($<$:/Zi>) + add_link_options(/DEBUG /OPT:REF /OPT:ICF) +endif() + +# The prebuilt release (setup.py downloads it, so users need no compiler): ggml's CPU backend for any AVX2 CPU +# instead of this machine's (Strata's own AVX-512 kernels are per-file and chosen at run time either way), and +# the MSVC runtime linked in, so no Visual C++ redistributable is needed. +option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" OFF) +if(STRATA_PORTABLE AND MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") +endif() + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE) +endif() + +option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) +option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF) +option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) +if(STRATA_CUDA_STATIC) + if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" + OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") + endif() + # Applies to subsequently created CUDA targets, including device-link runtime edges. + set(CMAKE_CUDA_RUNTIME_LIBRARY Static) +endif() +option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) +# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads +# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every +# model, and the UD-Q4_K_XL prompt is SSD-bound with or without them (docs/UNSLOTH_Q4.md) +option(STRATA_MMQ_KQUANTS "Build the CUDA MMQ prompt kernels for Q4_K / Q5_K / Q5_1 experts" OFF) +option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) +if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) + message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") +endif() +if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP) + message(FATAL_ERROR "STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP are separate backends; enable only one") +endif() +if(STRATA_ENABLE_HIP) + include(cmake/hip_backend.cmake) +endif() +# The test suite and the micro benchmarks live in tests/ and bench/micro/, which the published source leaves out. +set(_strata_tests_default OFF) +if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro) + set(_strata_tests_default ON) +endif() +option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default}) +option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF) +option(STRATA_WERROR "Treat compiler warnings as errors" OFF) + +if(STRATA_BUILD_CONVERSATION_TESTS) + enable_testing() + add_executable(conversation_cache_test src/core/conversation_cache_test.cpp) + target_include_directories(conversation_cache_test PRIVATE include) + add_test(NAME conversation_cache_test COMMAND conversation_cache_test) + add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp) + target_include_directories(conversation_memory_test PRIVATE include) + add_test(NAME conversation_memory_test COMMAND conversation_memory_test) +endif() + +if(STRATA_ENABLE_CUDA) + enable_language(CUDA) + # `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to + # be brought in explicitly for the host-side tests that call cudaMalloc themselves. + find_package(CUDAToolkit REQUIRED) + option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF) + if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) + set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures" FORCE) + endif() + foreach(_a IN LISTS CMAKE_CUDA_ARCHITECTURES) + string(REGEX REPLACE "-.*$" "" _base "${_a}") # 120-real / 120-virtual are still 120 + # Turing port: developed and measured on sm_120 (RTX 50); the tf32 mma in the QSA scorer has a + # portable fp32-FMA fallback, so RTX 20 (75), 30 (86), RTX 40 (89) and RTX 50 (120) build too. + # Pre-sm_75 is refused. + if(_base STREQUAL "native" OR _base STREQUAL "all" OR _base STREQUAL "all-major") + continue() + endif() + # STRATA_EXPERIMENTAL_SM60: a Pascal (sm_60, GP100-class) or Volta (sm_70, V100 / Titan V, #236) build. + # These sit below every architecture the kernels were written for, so two intrinsics are replaced below + # their arch - `__dp4a` (6.1+) and `__nanosleep` (7.0+) - in include/strata/kernels/dp4a.hpp, which is + # bit-exact for the first and merely a shorter pause for the second (sm_70 has both). Community-tested, + # not in the ready-made engine; RTX 20/30/40/50 cards must use the release engine instead. It needs a CUDA + # 12.x toolkit: CUDA 13 dropped sm_60 and sm_70 (nvcc fails CMake's compiler test with "compute_70"). + if(_base LESS 75 AND NOT STRATA_EXPERIMENTAL_SM60) + message(FATAL_ERROR + "Strata needs an NVIDIA GPU of compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series), but " + "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " + "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") + endif() + if(_base LESS 60) + message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " + "needs compute capability 6.0 (sm_60) or newer") + endif() + # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) + if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) + message(WARNING "Building for sm_${_base} (RTX 50) with CUDA ${CMAKE_CUDA_COMPILER_VERSION}: engines built with " + "CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.") + endif() + endforeach() + message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) + if(STRATA_CUDA_STATIC) + foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos) + if(NOT TARGET ${_required}) + message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}") + endif() + endforeach() + set(_strata_gpu_runtime_target CUDA::cudart_static) + set(_strata_gpu_blas_target CUDA::cublas_static) + message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required") + endif() + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +elseif(STRATA_ENABLE_HIP) + set(_strata_gpu_runtime_target strata_hip_runtime) + set(_strata_gpu_blas_target roc::hipblas) + set(_strata_gpu_include_directories ${STRATA_HIP_COMPAT_INCLUDE_DIR}) +endif() + +# Warnings live on an INTERFACE target the project's own code links, NOT in add_compile_options: applied +# globally they would also hit FetchContent'd Catch2, whose -W4 warnings are not this project's to fix and +# whose /WX failures would be indistinguishable from our own. +# +# Every flag is guarded by COMPILE_LANGUAGE:CXX. Without that guard nvcc receives bare `/W4 /utf-8` and dies +# with "A single input file is required for a non-link phase" - it parses them as inputs rather than host +# flags. Host flags for CUDA must go through -Xcompiler, which is what COMPILE_LANGUAGE:CUDA does below. +add_library(strata_warnings INTERFACE) +target_compile_options(strata_warnings INTERFACE + $<$,$>:/W4> + $<$,$>:/utf-8> + $<$,$>>:-Wall> + $<$,$>>:-Wextra> + $<$,$>:-Xcompiler=/W4> + $<$:-Wall> + $<$:-Wextra>) +if(STRATA_WERROR) + target_compile_options(strata_warnings INTERFACE + $<$,$>:/WX> + $<$,$>>:-Werror> + $<$:-Werror>) +endif() + +# ---- strata_artifact ------------------------------------------------------- +# Header-only, and that is a deliberate property rather than an unfinished split: the GGUF reader and the +# scalar dequantizers hold no state worth hiding, and a header-only boundary cannot introduce a +# duplicate-symbol or missing-declaration bug into code that is already validated against the real artifact. +add_library(strata_artifact INTERFACE) +target_include_directories(strata_artifact INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_link_libraries(strata_artifact INTERFACE strata_warnings) + +add_executable(strata-gguf src/artifact/gguf_reader.cpp) +target_link_libraries(strata-gguf PRIVATE strata_artifact) + +add_executable(strata-dequant src/artifact/dequant.cpp) +target_link_libraries(strata-dequant PRIVATE strata_artifact) +# this file is now nothing but the CLI entry point, and its inherited guard spells that as a "selftest" +target_compile_definitions(strata-dequant PRIVATE STRATA_DEQUANT_SELFTEST) +if(STRATA_BUILD_TESTS) + # the reader refuses a duplicate tensor name at open, naming it (a synthetic GGUF: no model, no GPU) + add_executable(gguf_reader_test src/artifact/gguf_reader_test.cpp) + target_link_libraries(gguf_reader_test PRIVATE strata_artifact) + add_test(NAME gguf_reader_test COMMAND gguf_reader_test) + # a split model's shards and their joint view: missing shard, split keys, duplicates, truncation (synthetic) + add_executable(gguf_split_test tests/core/gguf_split_test.cpp) + target_link_libraries(gguf_split_test PRIVATE strata_artifact) + add_test(NAME gguf_split_test COMMAND gguf_split_test) +endif() + +# ---- strata_plan ---------------------------------------------------------- +# Also header-only. A "planner" that hides state would be one whose decision is not inspectable, and the +# whole point of P1.S9 is that the decision is arithmetic you can check by hand. +add_library(strata_plan INTERFACE) +target_include_directories(strata_plan INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_link_libraries(strata_plan INTERFACE strata_warnings) + +add_executable(strata-plan src/plan/plan_main.cpp) +target_link_libraries(strata-plan PRIVATE strata_plan) + +# ---- strata_core (GPU runtime) --------------------------------------------- +# Only built when a GPU backend is on, so the Phase 1 targets keep working without a toolkit. +if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp + src/core/layout.cpp) + target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + # the runtime device check (src/core/device.cu) admits the cards this build was made for (#236) + target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1) + endif() + # The selected runtime is PUBLIC because graph.cpp is a HOST translation unit that calls cudaGraphLaunch and + # cudaEventQuery: the .cu sources get cudart through the CUDA language rules, a .cpp does not, and the + # linker error ("unresolved external symbol cudaGraphInstantiate") names the function rather than the cause. + target_link_libraries(strata_core PUBLIC strata_plan strata_warnings ${_strata_gpu_runtime_target}) + + add_executable(strata-device src/core/device_main.cpp) + target_link_libraries(strata-device PRIVATE strata_core) + + add_executable(strata-load src/core/load_main.cpp) + target_link_libraries(strata-load PRIVATE strata_core strata_kernels) + + add_executable(strata-concurrent src/core/concurrent_main.cpp) + target_include_directories(strata-concurrent PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata-concurrent PRIVATE strata_core strata_kernels ${_strata_gpu_runtime_target}) + + add_executable(strata-overlap src/core/overlap_main.cpp) + # a .cpp that calls cudaMemcpyAsync itself needs the toolkit headers and cudart explicitly + target_include_directories(strata-overlap PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata-overlap PRIVATE strata_core strata_kernels ${_strata_gpu_runtime_target}) + + # The load test needs the 34 GB artifact, so it is registered ONLY where that artifact exists. A test that + # silently skips is a test that stops running; an absent registration is visible in the configure output. + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/pack/full/experts.bin) + add_test(NAME expert_arena_load + COMMAND strata-load --file ${CMAKE_CURRENT_SOURCE_DIR}/pack/full/experts.bin --layers 1) + set_tests_properties(expert_arena_load PROPERTIES PASS_REGULAR_EXPRESSION "per-layer checksums") + else() + message(STATUS "strata: pack/full/experts.bin absent - the expert arena load test is NOT registered") + endif() + + # ---- strata_kernels (P2.S2) ---- + # Naive first, each with a parity test against a reference that was itself validated against ggml. The + # kernels link `strata_artifact` for the scalar dequantizers, because using the VALIDATED scalar path as the + # reference is the whole point - a kernel checked against another copy of itself proves nothing. + add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu + src/kernels/cuda/s_gemv.cu + src/kernels/cuda/s2_gemv_quads.cu + src/kernels/cuda/s2_gemv_fast.cu + src/kernels/cuda/router_top10.cu + src/kernels/cuda/quantize_act.cu + src/kernels/cuda/rope.cu + src/kernels/cuda/sampler.cu + src/kernels/cuda/s2_gemv_q8.cu + src/kernels/cuda/s2_expert_grouped.cu + src/kernels/cuda/shared_expert.cu + src/kernels/cuda/gr.cu + src/kernels/cuda/gdn.cu + src/kernels/cuda/qsa.cu + src/kernels/cuda/elementwise.cu + src/kernels/cuda/bf16_gemv.cu + src/kernels/cuda/native_mmvq.cu + src/kernels/cuda/native_bf16.cu + src/kernels/cuda/native_gr_norm.cu + src/kernels/cuda/native_moe.cu + src/kernels/cuda/native_gdn.cu + src/kernels/cuda/native_gr_postops.cu + src/kernels/cuda/native_router.cu + src/kernels/cuda/native_gdn_preprocess.cu + src/kernels/cuda/native_qsa.cu + src/kernels/cuda/native_rope.cu + src/kernels/cuda/native_ple_postops.cu + src/kernels/cuda/native_flash_attn.cu + src/kernels/cuda/native_qsa_indexer.cu + src/kernels/cuda/native_qsa_score.cu + src/kernels/cuda/ple.cu + src/kernels/cuda/kv_q8.cu + src/kernels/cuda/kv_stream.cu + src/kernels/cuda/kv_q4.cu + src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu + src/kernels/cuda/qsa_decode_attn.cu + src/kernels/cuda/keyless.cu + src/kernels/cuda/qsa_prompt_attn.cu + src/kernels/cuda/fused_gdn.cu + src/kernels/cuda/dequant_bf16.cu + src/kernels/cuda/qsa_select.cu + src/kernels/cuda/verify_kernels.cu + src/kernels/cuda/iq_kernels.cu + src/kernels/ngram.cpp + src/ngram/ple_reader.cpp + src/platform/direct_file.cpp) + target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) + option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF) + if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The experimental PLE row trace requires Linux") + endif() + target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1) + endif() + option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF) + set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") + if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") + endif() + if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") + message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") + endif() + add_library(strata_next_kar STATIC + "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" + "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu") + target_include_directories(strata_next_kar PUBLIC + "${STRATA_NEXT_KAR_DIR}/vendor" + "${STRATA_NEXT_KAR_DIR}/include") + target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target}) + set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) + target_link_libraries(strata_kernels PUBLIC strata_next_kar) + target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) + add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") + target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) + endif() + # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with + # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) + add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) + target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() + # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a + # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a + # 262144-cell capacity (the top-k dispatch follows the capacity) and exits non-zero on a failed gate + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_HIP) + add_executable(qsa_select_bench src/kernels/qsa_select_bench.cpp) + set_source_files_properties(src/kernels/qsa_select_bench.cpp PROPERTIES LANGUAGE HIP) + target_link_libraries(qsa_select_bench PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) + endif() + # plan v0.3 P6: llama.cpp's block layouts and codebook grids for the i-quant formats (MIT, third_party/ggml) + target_include_directories(strata_kernels PRIVATE third_party/ggml) + # Match the pinned llama.cpp CUDA arithmetic contract for this adapter only. + if(STRATA_ENABLE_CUDA) + set_source_files_properties(src/kernels/cuda/native_mmvq.cu src/kernels/cuda/native_bf16.cu + src/kernels/cuda/native_gr_norm.cu + src/kernels/cuda/native_moe.cu + src/kernels/cuda/native_gdn.cu + src/kernels/cuda/native_gr_postops.cu + src/kernels/cuda/native_router.cu + src/kernels/cuda/native_gdn_preprocess.cu + src/kernels/cuda/native_qsa.cu + src/kernels/cuda/native_rope.cu + src/kernels/cuda/native_ple_postops.cu + src/kernels/cuda/native_flash_attn.cu + src/kernels/cuda/native_qsa_indexer.cu + src/kernels/cuda/native_qsa_score.cu + PROPERTIES COMPILE_OPTIONS "--use_fast_math") + elseif(STRATA_ENABLE_HIP) + # Keep Q8_K's multiply and magic-bias rounding as separate FP32 operations on HIP; contraction to an + # FMA changes tie results. The embedding gather also relies on separately rounded operations. + set_source_files_properties(src/kernels/cuda/elementwise.cu src/kernels/cuda/quantize_act.cu + PROPERTIES COMPILE_OPTIONS "-ffp-contract=off") + endif() + + set(STRATA_ORACLE_SOURCE_DIR "" CACHE PATH "Pinned llama.cpp source for independent CUDA parity tests") + set(STRATA_ORACLE_BUILD_DIR "" CACHE PATH "Matching existing shared llama.cpp build") + # This oracle is a CUDA ggml build; do not pull CUDA libraries into a HIP build. + if(STRATA_ENABLE_CUDA AND STRATA_ORACLE_SOURCE_DIR AND STRATA_ORACLE_BUILD_DIR) + foreach(parity IN ITEMS native_mmvq native_bf16 native_shared native_gr_norm native_moe native_gdn native_gr_postops native_router native_gdn_preprocess native_gdn_pipeline native_qsa native_rope native_ple_postops native_flash_attn native_qsa_indexer native_qsa_score) + add_executable(${parity}_parity bench/micro/${parity}_parity.cpp) + target_include_directories(${parity}_parity PRIVATE + "${STRATA_ORACLE_SOURCE_DIR}/ggml/include" ${_strata_gpu_include_directories}) + target_compile_definitions(${parity}_parity PRIVATE GGML_SHARED GGML_BACKEND_SHARED) + target_link_libraries(${parity}_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + foreach(component IN ITEMS ggml ggml-base ggml-cpu ggml-cuda) + string(REPLACE "-" "_" variable "STRATA_ORACLE_${component}") + find_library(${variable} NAMES ${component} PATHS + "${STRATA_ORACLE_BUILD_DIR}/ggml/src" "${STRATA_ORACLE_BUILD_DIR}/ggml/src/${component}" + "${STRATA_ORACLE_BUILD_DIR}/bin" NO_DEFAULT_PATH REQUIRED) + target_link_libraries(${parity}_parity PRIVATE "${${variable}}") + endforeach() + add_test(NAME ${parity}_parity COMMAND ${parity}_parity --selftest) + if(WIN32) + set_tests_properties(${parity}_parity PROPERTIES + ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${STRATA_ORACLE_BUILD_DIR}/bin") + endif() + endforeach() + endif() + + # ---- strata_engine (P2.S5) ----------------------------------------------------- + # The COMPOSED layer lives here and not in `strata_core`, because it calls kernels and `strata_kernels` + # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third + # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know + # about arithmetic, and this one knows the ORDER the arithmetic happens in. + add_library(strata_engine STATIC src/core/keyless.cpp src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp) + target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) + option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) + if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "Experimental KAR experts require Linux CUDA") + endif() + if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") + message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar") + endif() + add_library(strata_next_kar_experts STATIC + "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" + "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu" + "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") + target_include_directories(strata_next_kar_experts PUBLIC + "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include") + target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target}) + set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) + target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20) + target_link_libraries(strata_engine PUBLIC strata_next_kar_experts) + target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1) + endif() + add_executable(keyless_parity src/kernels/keyless_parity.cpp) + target_link_libraries(keyless_parity PRIVATE strata_engine) + add_test(NAME keyless_parity COMMAND keyless_parity) + set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") + enable_testing() + add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) + target_link_libraries(file_expert_source_test PRIVATE strata_engine) + add_test(NAME file_expert_source_test COMMAND file_expert_source_test) + set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60) + endif() + if(STRATA_BUILD_TESTS AND STRATA_NATIVE_EXPERTS) + # native_experts.txt v2-v4 (the real packs' copies and the per-role shard column) and the arena filled from + # synthetic GGUF shards at the real expert dimensions + add_executable(expert_layout_test tests/core/expert_layout_test.cpp) + target_link_libraries(expert_layout_test PRIVATE strata_engine) + add_test(NAME expert_layout_test COMMAND expert_layout_test ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/native_experts) + set_tests_properties(expert_layout_test PROPERTIES TIMEOUT 60) + # #326: a native pack's BF16 (--compat-bf16) PLE key stays in the arena; a quantized key row loads as before + add_executable(native_dense_ple_key_test tests/core/native_dense_ple_key_test.cpp) + target_link_libraries(native_dense_ple_key_test PRIVATE strata_engine) + add_test(NAME native_dense_ple_key_test COMMAND native_dense_ple_key_test) + set_tests_properties(native_dense_ple_key_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + # #369: per-layer admission on a sized (native pack) cache starts each layer in its own range + add_executable(expert_cache_per_layer_test tests/core/expert_cache_per_layer_test.cpp) + target_link_libraries(expert_cache_per_layer_test PRIVATE strata_engine) + add_test(NAME expert_cache_per_layer_test COMMAND expert_cache_per_layer_test) + set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + if(STRATA_BUILD_CONVERSATION_TESTS) + add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) + target_link_libraries(keyless_stream_parity PRIVATE strata_engine) + add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only) + set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) + target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) + add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) + target_link_libraries(conversation_validation_test PRIVATE strata_engine) + add_test(NAME conversation_validation_test COMMAND conversation_validation_test) + set_tests_properties(conversation_validation_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + add_executable(conversation_transfer_test src/core/conversation_validation_test.cpp) + target_compile_definitions(conversation_transfer_test PRIVATE CONVERSATION_TEST_TRANSFERS) + target_link_options(conversation_transfer_test PRIVATE + -Wl,--wrap=cudaMemcpy -Wl,--wrap=cudaDeviceSynchronize -Wl,--wrap=cudaGetLastError) + target_link_libraries(conversation_transfer_test PRIVATE strata_engine) + add_test(NAME conversation_transfer_test COMMAND conversation_transfer_test) + set_tests_properties(conversation_transfer_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) + endif() + endif() + + # `strata generate` (P2.S6). The FIRST user-facing program: everything under it is a component, and this is + # what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits + # against llama.cpp on the SAME ids and a tokenizer on one side of that comparison is a second variable. + # plan v0.3 P5: batched prompt processing (tensor-core GEMMs through cuBLAS). + add_library(strata_prefill STATIC src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) + target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE) + target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1) + target_link_libraries(strata_prefill PRIVATE roc::hipblaslt) + + add_executable(tune_hipblaslt tools/hip/tune_hipblaslt.cpp) + target_link_libraries(tune_hipblaslt PRIVATE hip::host roc::hipblas roc::hipblaslt) + endif() + + add_executable(strata src/program/generate.cpp) + target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) + if(STRATA_CUDA_STATIC) + target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) + set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") + endif() + + if(STRATA_ENABLE_HIP) + enable_testing() + set(_strata_hip_tests) + add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp) + target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine) + add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging) + list(APPEND _strata_hip_tests hip_expert_cache_staging) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/intrinsics.cpp") + add_executable(hip_intrinsics tests/hip/intrinsics.cpp) + target_link_libraries(hip_intrinsics PRIVATE strata_hip_runtime) + add_test(NAME hip_intrinsics COMMAND hip_intrinsics) + list(APPEND _strata_hip_tests hip_intrinsics) + endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/handoff.cpp") + add_executable(hip_handoff tests/hip/handoff.cpp) + target_link_libraries(hip_handoff PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_handoff COMMAND hip_handoff) + list(APPEND _strata_hip_tests hip_handoff) + endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/mapped_alias.cpp") + # #325: reports what a hipHostGetDevicePointer alias is on this stack (on Windows: the host pointer, and a + # D2D copy into it does not land - hip_handoff's timeout there). A diagnosis: exits 0 whenever it ran. + add_executable(hip_mapped_alias tests/hip/mapped_alias.cpp) + target_link_libraries(hip_mapped_alias PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_mapped_alias COMMAND hip_mapped_alias) + set_tests_properties(hip_mapped_alias PROPERTIES SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_mapped_alias) + endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/native_qsa_score.cpp") + add_executable(hip_native_qsa_score tests/hip/native_qsa_score.cpp) + target_link_libraries(hip_native_qsa_score PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_native_qsa_score COMMAND hip_native_qsa_score) + list(APPEND _strata_hip_tests hip_native_qsa_score) + endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/prefill_native_batch.cpp") + add_executable(hip_prefill_native_batch tests/hip/prefill_native_batch.cpp) + target_link_libraries(hip_prefill_native_batch PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_prefill_native_batch COMMAND hip_prefill_native_batch) + list(APPEND _strata_hip_tests hip_prefill_native_batch) + endif() + # S6: the AMD fast router against the portable kernel, bitwise + add_executable(hip_router_fast tests/hip/router_fast.cpp) + target_link_libraries(hip_router_fast PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_router_fast COMMAND hip_router_fast) + list(APPEND _strata_hip_tests hip_router_fast) + # S6: the RDNA4 matrix-core prompt attention (STRATA_HIP_WMMA) against the FP32 kernel and FP64; skips off gfx12 + add_executable(hip_prompt_attn_wmma src/kernels/qsa_prompt_attn_parity.cpp) + target_link_libraries(hip_prompt_attn_wmma PRIVATE strata_kernels strata_hip_runtime) + add_test(NAME hip_prompt_attn_wmma COMMAND hip_prompt_attn_wmma 32768 2048 3) + set_tests_properties(hip_prompt_attn_wmma PROPERTIES TIMEOUT 600 SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prompt_attn_wmma) + if(STRATA_HIPBLASLT_AVAILABLE AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/hip/prefill_hipblaslt_gemm.cpp") + add_executable(hip_prefill_hipblaslt_gemm tests/hip/prefill_hipblaslt_gemm.cpp) + target_include_directories(hip_prefill_hipblaslt_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") + target_link_libraries(hip_prefill_hipblaslt_gemm PRIVATE strata_prefill strata_hip_runtime roc::hipblaslt roc::hipblas) + add_test(NAME hip_prefill_hipblaslt_gemm COMMAND hip_prefill_hipblaslt_gemm) + set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + list(APPEND _strata_hip_tests hip_prefill_hipblaslt_gemm) + endif() + if(_strata_hip_tests) + set_tests_properties(${_strata_hip_tests} PROPERTIES TIMEOUT 60) + endif() + if(TARGET hip_prefill_native_batch) + set_tests_properties(hip_prefill_native_batch PROPERTIES TIMEOUT 120) + endif() + if(TARGET hip_prefill_hipblaslt_gemm) + set_tests_properties(hip_prefill_hipblaslt_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endif() + endif() + + add_executable(dequant_s2_parity src/kernels/dequant_s2_parity.cpp) + # The tests are HOST C++ files that call cudaMalloc/cudaMemcpy themselves, so they need the toolkit headers + # and cudart explicitly: enabling the CUDA language gives those to .cu sources automatically, but a .cpp + # target is just a C++ target and gets neither. + target_include_directories(dequant_s2_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dequant_s2_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME dequant_s2_parity COMMAND dequant_s2_parity --selftest) + + add_executable(s2_gemv_parity src/kernels/s2_gemv_parity.cpp) + target_include_directories(s2_gemv_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s2_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s2_gemv_parity COMMAND s2_gemv_parity --selftest) + + add_executable(iq_parity src/kernels/iq_parity.cpp) + target_include_directories(iq_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + # TODO 24: the i-quant fixtures are generated, not shipped. tools/iq_fixture.py needs python3 + numpy + # and the repository's vendored gguf-py (no pip installs); it writes deterministic fixtures into the + # BUILD directory (the source tree is not touched). The CTest fixture makes generation-to-test order + # explicit even under parallel execution; a fixture-generation failure fails iq_parity with it. + find_package(Python3 COMPONENTS Interpreter QUIET) + # the generator needs an interpreter WITH numpy: probe the configured one, the setup's .venv, and the + # system python3; -DIQ_FIXTURE_PYTHON=... overrides the search outright. + set(_iq_python "") + set(_iq_candidates "") + if(IQ_FIXTURE_PYTHON) + list(APPEND _iq_candidates ${IQ_FIXTURE_PYTHON}) + else() + if(Python3_Interpreter_FOUND) + list(APPEND _iq_candidates ${Python3_EXECUTABLE}) + endif() + list(APPEND _iq_candidates "${CMAKE_CURRENT_SOURCE_DIR}/.venv/bin/python" + "${CMAKE_CURRENT_SOURCE_DIR}/.venv/Scripts/python.exe" + /usr/bin/python3 + python3) + endif() + foreach(_cand IN LISTS _iq_candidates) + if(_cand STREQUAL "") + continue() + endif() + execute_process(COMMAND ${_cand} -c "import numpy" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE _iq_probe) + if(_iq_probe EQUAL 0) + set(_iq_python "${_cand}") + break() + endif() + endforeach() + if(NOT _iq_python STREQUAL "") + add_test(NAME iq_parity_fixtures + COMMAND ${_iq_python} ${CMAKE_CURRENT_SOURCE_DIR}/tools/iq_fixture.py + --out ${CMAKE_CURRENT_BINARY_DIR}/iq_fixture) + # exit 3: numpy or the vendored gguf-py is missing (a trimmed third_party) - a skip, not a failure + set_tests_properties(iq_parity_fixtures PROPERTIES FIXTURES_SETUP iq_fixture_data SKIP_RETURN_CODE 3) + add_test(NAME iq_parity COMMAND iq_parity ${CMAKE_CURRENT_BINARY_DIR}/iq_fixture) + set_tests_properties(iq_parity PROPERTIES FIXTURES_REQUIRED iq_fixture_data SKIP_RETURN_CODE 3) + else() + message(STATUS "STRATA tests: no python3 with numpy was found (the configured interpreter and .venv " + "were probed) - the iq_parity fixtures and its test are not registered; the fixtures " + "need python3 with numpy and the repository's vendored gguf-py") + endif() + if(STRATA_ENABLE_CUDA) + # native_mmvq's multi_exact contract, bitwise: a T-column call against T single-column calls on the same Q8_1 + # bytes, with the flag off as the negative control (synthetic, GPU, no model; the control assumes 32-lane warps) + add_executable(mmvq_multi_parity src/kernels/mmvq_multi_parity.cpp) + target_include_directories(mmvq_multi_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(mmvq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME mmvq_multi_parity COMMAND mmvq_multi_parity) + endif() + # the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones + # (GPU, synthetic, no model; --bench adds old/new timings) + add_executable(iq_multi_parity src/kernels/iq_multi_parity.cpp) + target_include_directories(iq_multi_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME iq_multi_parity COMMAND iq_multi_parity) + add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp) + target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest) + + add_executable(gr_parity src/kernels/gr_parity.cpp) + target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME gr_parity COMMAND gr_parity --selftest) + + add_executable(gdn_parity src/kernels/gdn_parity.cpp) + target_include_directories(gdn_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME gdn_parity COMMAND gdn_parity --selftest) + + add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp) + target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s2_gemv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s2_gemv_q8_parity COMMAND s2_gemv_q8_parity --selftest) + + add_executable(sampler_parity src/kernels/sampler_parity.cpp) + target_include_directories(sampler_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME sampler_parity COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0") + # the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel + add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1") + add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest) + set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0") + + add_executable(rope_parity src/kernels/rope_parity.cpp) + target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(rope_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME rope_parity COMMAND rope_parity --selftest) + + add_executable(quantize_act_parity src/kernels/quantize_act_parity.cpp) + target_include_directories(quantize_act_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(quantize_act_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME quantize_act_parity COMMAND quantize_act_parity --selftest) + + add_executable(router_top10_parity src/kernels/router_top10_parity.cpp) + target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest) + + add_executable(s_gemv_parity src/kernels/s_gemv_parity.cpp) + target_include_directories(s_gemv_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s_gemv_parity COMMAND s_gemv_parity --selftest) + + add_executable(elementwise_parity src/kernels/elementwise_parity.cpp) + target_include_directories(elementwise_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(elementwise_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME elementwise_parity COMMAND elementwise_parity --selftest) + + add_executable(bf16_gemv_parity src/kernels/bf16_gemv_parity.cpp) + target_include_directories(bf16_gemv_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest) + + add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp) + target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s_gemv_q8k_parity COMMAND s_gemv_q8k_parity --selftest) + + add_executable(qsa_parity src/kernels/qsa_parity.cpp) + target_include_directories(qsa_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(qsa_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME qsa_parity COMMAND qsa_parity --selftest) + + # ---- P2.S4: the PLE n-gram hash, the IQ4_NL table read, and the PLE block ---- + # `ngram.cpp` is host-only but lives in `strata_kernels` because `ple.cu` shares its geometry constants, and + # splitting them across two libraries would only add a layer. + # + # The pack, the original GGUF and the ggml capture are all REQUIRED inputs: this test's oracles are real + # artifacts, so the working directory is pinned to the source tree and a missing input is a hard error + # INSIDE the test. A test that passes by finding nothing to compare is the failure mode this project keeps + # re-learning. + add_executable(ple_parity src/kernels/ple_parity.cpp) + target_include_directories(ple_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + set(STRATA_PLE_FIXTURE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro" CACHE PATH + "Directory containing required ple_in.bin and ple_out.bin parity fixtures") + add_test(NAME ple_parity COMMAND ple_parity --selftest + --in "${STRATA_PLE_FIXTURE_DIR}/ple_in.bin" --out "${STRATA_PLE_FIXTURE_DIR}/ple_out.bin" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + + # Plan v0.3 P7: INT8 KV storage vs a host reference and vs the FP16 path (GPU, synthetic, no model). + add_executable(kv_q8_parity src/kernels/kv_q8_parity.cpp) + target_include_directories(kv_q8_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_q8_parity COMMAND kv_q8_parity) + + # KV streaming (docs/kv-streaming-design.md): streamed vs resident attention, bitwise (GPU, synthetic, no model). + add_executable(kv_stream_parity src/kernels/kv_stream_parity.cpp) + target_include_directories(kv_stream_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_stream_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_stream_parity COMMAND kv_stream_parity) + + # PR #120: the hybrid K8V4 KV (INT8 K + rotated Q4_0 V) vs host references (GPU, synthetic, no model). + add_executable(kv_hybrid_parity src/kernels/kv_hybrid_parity.cpp) + target_include_directories(kv_hybrid_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_hybrid_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_hybrid_parity COMMAND kv_hybrid_parity) + # PR #21: Q4_0 KV with Walsh-Hadamard rotation vs a host reference (GPU, synthetic, no model). + add_executable(kv_q4_parity src/kernels/kv_q4_parity.cpp) + target_include_directories(kv_q4_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(kv_q4_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME kv_q4_parity COMMAND kv_q4_parity) + add_executable(cvec_parity src/kernels/cvec_parity.cpp) + target_include_directories(cvec_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(cvec_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME cvec_parity COMMAND cvec_parity) + + # The rewritten per-hit and grouped expert kernels vs the previous ones, bitwise (GPU, synthetic, no model). + # `--bench` adds previous/new timings on engine-like shapes. + add_executable(s2_expert_grouped_parity src/kernels/s2_expert_grouped_parity.cpp) + target_include_directories(s2_expert_grouped_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(s2_expert_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME s2_expert_grouped_parity COMMAND s2_expert_grouped_parity --selftest) + + # Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model. + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/native_mmvq_multi.cpp") + add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp) + target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest) + endif() + + # Plan v0.3 P0.1: working-set lock of a host region (CPU only). + add_executable(platform_memory_test src/platform/memory_test.cpp) + target_link_libraries(platform_memory_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME platform_memory_test COMMAND platform_memory_test) + + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_executable(pinned_shared_test src/core/pinned_shared_test.cpp) + target_link_libraries(pinned_shared_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME pinned_shared_test COMMAND pinned_shared_test) + endif() + + # Plan v0.3 P2: the n-gram table read straight from the SSD. The selftest needs only the CPU and a temp file. + add_executable(ple_reader_test src/ngram/ple_reader_test.cpp) + target_include_directories(ple_reader_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_reader_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME ple_reader_selftest COMMAND ple_reader_test --selftest) + + # The GPU test runs ON THE TARGET PC. `--selftest` allocates + # and writes real VRAM, so a machine without a device fails this test rather than skipping it silently - + # which is correct: an engine that targets one GPU should not report a pass for having no GPU. + if(STRATA_ENABLE_CUDA) + add_test(NAME cuda_device_selftest COMMAND strata-device --selftest) + else() + add_test(NAME hip_device_selftest COMMAND strata-device --selftest) + endif() + + # ---- P2.S5: the GraphRegistry -------------------------------------------------- + # A .cu because the test needs real kernels to capture; it links `strata_core` and not `strata_kernels`, + # because what it exercises is the capture machinery and not any kernel in it. + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/graph_registry_test.cu") + add_executable(graph_registry_test bench/micro/graph_registry_test.cu) + target_include_directories(graph_registry_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(graph_registry_test PRIVATE strata_core ${_strata_gpu_runtime_target}) + add_test(NAME graph_registry_test COMMAND graph_registry_test) + endif() + + # ---- P2.S5's GATE: is a device<->pinned-memory handoff graph-capturable? -------------------- + # The doorbell protocol puts the D2H of `x_f` and the miss list INSIDE G[l] - that is the whole overlap. The + # phase doc says to verify this "before building on it", and this project has already lost two rounds to + # building first (a memory-only spin that DEADLOCKS on Windows, and a `cudaEventRecord` inside a capture that + # is SILENTLY DROPPED). It links only cudart: it is about the capture machinery, not about any kernel. + if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/pinned_capture.cu") + add_executable(pinned_capture bench/micro/pinned_capture.cu) + target_include_directories(pinned_capture PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(pinned_capture PRIVATE ${_strata_gpu_runtime_target}) + add_test(NAME pinned_capture COMMAND pinned_capture) + endif() + + # Tells tests/CMakeLists.txt to add the CUDA-dependent Catch2 target. It cannot be declared there + # unconditionally: tests/ is added at the end of this file, but the flag has to be known before it runs. + if(STRATA_ENABLE_CUDA) + set(STRATA_CUDA_TESTS ON) + endif() +endif() + +# ---- strata_kernels_cpu (P2.S3) ---- +# +# A SEPARATE LIBRARY from `strata_kernels`, and `/arch:AVX512` is set on the SOURCE rather than on the target +# so that the flag applies only to the TU that needs it. Both parts matter: +# +# * the CPU expert kernel uses `_mm256_dpbusd_epi32` (AVX512-VNNI) and `_mm256_multishift_epi64_epi8` +# (AVX512-VBMI); without the flag MSVC reports undeclared intrinsics and never mentions AVX-512; +# * a TU compiled WITH `/arch:AVX512` may use AVX-512 in ANY of its code, so the scalar fallback and the +# test drivers must NOT be in it - otherwise the fallback is not a fallback, it is the same bet with +# worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the +# features, and the fallback exists for tests, exactly as P2.S3 specifies. +# Plan v0.3 P6: speculation components that need no GPU. +add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp) +target_include_directories(strata_spec PUBLIC include) +if(STRATA_BUILD_TESTS) + add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp) + target_link_libraries(suffix_drafter_test PRIVATE strata_spec) + add_test(NAME suffix_drafter_test COMMAND suffix_drafter_test) + add_executable(controller_test src/spec/controller_test.cpp) + target_link_libraries(controller_test PRIVATE strata_spec) + add_test(NAME controller_test COMMAND controller_test) + add_executable(draft_policy_test src/spec/draft_policy_test.cpp) + target_link_libraries(draft_policy_test PRIVATE strata_spec) + add_test(NAME draft_policy_test COMMAND draft_policy_test) +endif() +if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) + # the serve loop's conversation-cache retention policy (header-only, no library to link) + add_executable(conv_cache_test src/program/conv_cache_test.cpp) + target_include_directories(conv_cache_test PRIVATE include) + add_test(NAME conv_cache_test COMMAND conv_cache_test) + # coupled draft sampling's counter and penalty-ring arithmetic (header-only, CPU) + add_executable(coupled_draft_test src/core/coupled_draft_test.cpp) + target_include_directories(coupled_draft_test PRIVATE include) + add_test(NAME coupled_draft_test COMMAND coupled_draft_test) + # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) + add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) + target_include_directories(bf16_bits_test PRIVATE include) + add_test(NAME bf16_bits_test COMMAND bf16_bits_test) +endif() + +add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp + src/kernels/cpu/expert_layout.cpp src/kernels/cpu/q2_avx2.cpp) +target_include_directories(strata_kernels_cpu PUBLIC include) +# Plan v0.3 P6: only the kernel files get the AVX-512 / AVX2 flags; the pool and the probe run on any x86-64, +# and the engine picks the kernels at run time (cpu_avx512_ok). +if(MSVC) + set_source_files_properties(src/kernels/cpu/expert.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") + set_source_files_properties(src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") +else() + # GCC/Clang spell it differently, and `-mavx512vnni` alone is not enough: VBMI is a separate feature bit. + set_source_files_properties(src/kernels/cpu/expert.cpp + PROPERTIES COMPILE_OPTIONS "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + set_source_files_properties(src/kernels/cpu/q2_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") +endif() +find_package(Threads REQUIRED) +target_link_libraries(strata_kernels_cpu PUBLIC Threads::Threads) + +# ---- plan v0.3 P6: the i-quant models' CPU experts (IQ2_XS / IQ3_XXS files) ---- +# +# The CPU computes a native expert with ggml-cpu's own dot products (`ggml_get_type_traits_cpu`), so an IQ +# weight means exactly what it means in llama.cpp. ggml is built static from a llama.cpp checkout: a local one +# with -DSTRATA_GGML_DIR=..., otherwise the pinned upstream commit (third_party/ggml/VERSION.txt). +option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) +set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout to take ggml from (empty: fetch the pinned commit)") +if(STRATA_PREFILL_MMQ AND NOT STRATA_NATIVE_EXPERTS) + message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") +endif() +if(STRATA_ORCA_Q4KS_MMQ AND NOT STRATA_NATIVE_EXPERTS) + message(FATAL_ERROR "STRATA_ORCA_Q4KS_MMQ requires STRATA_NATIVE_EXPERTS=ON for GGML sources") +endif() +if(STRATA_NATIVE_EXPERTS) + enable_language(C) + set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) + set(GGML_STATIC ON CACHE BOOL "" FORCE) + set(GGML_CUDA OFF CACHE BOOL "" FORCE) + set(GGML_OPENMP OFF CACHE BOOL "" FORCE) + set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) + set(GGML_BUILD_TESTS OFF CACHE BOOL "" FORCE) + set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + if(STRATA_PORTABLE) + set(GGML_NATIVE OFF CACHE BOOL "" FORCE) + foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2) + set(${_f} ON CACHE BOOL "" FORCE) + endforeach() + else() + set(GGML_NATIVE ON CACHE BOOL "" FORCE) + endif() + if(STRATA_GGML_DIR) + add_subdirectory(${STRATA_GGML_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + else() + include(FetchContent) + FetchContent_Declare(strata_llamacpp + GIT_REPOSITORY https://github.com/ggml-org/llama.cpp.git + GIT_TAG 3cf03257f219afbe7334045ff7c6a06ac68c627d + GIT_SHALLOW FALSE) + FetchContent_GetProperties(strata_llamacpp) + if(NOT strata_llamacpp_POPULATED) + FetchContent_Populate(strata_llamacpp) + endif() + add_subdirectory(${strata_llamacpp_SOURCE_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + endif() + # part of strata_kernels_cpu (the pool calls these and they call its CPU probe: one library, so GNU ld's + # one-pass static linking has no cycle to resolve) + target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp + src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp) + target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) + if(MSVC) + set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") + set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") + else() + set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS + "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma") + set_source_files_properties(src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + set_source_files_properties(src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") + endif() + target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) + target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) + set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) + # #296: OrcaRouter Q4_K_S's Q5_0 experts (Q4_K and Q5_1 come with STRATA_MMQ_KQUANTS on CUDA, S5's branch) + if(STRATA_ORCA_Q4KS_MMQ) + list(APPEND _strata_mmq_types q5_0) + endif() + if(STRATA_ENABLE_CUDA) + # prompt-speed plan step 2b: llama.cpp's MMQ kernels (ggml-cuda, MIT) for the prompt path's experts, compiled + # from the same checkout as ggml above - only mmq.cuh's instances for the packs' types and the quantizer, with + # the few host symbols of ggml-cuda.cu they use in src/prefill/ggml_cuda_host.cu + if(STRATA_GGML_DIR) + set(_strata_gg ${STRATA_GGML_DIR}/ggml) + else() + set(_strata_gg ${strata_llamacpp_SOURCE_DIR}/ggml) + endif() + set(_strata_mmq ${_strata_gg}/src/ggml-cuda) + add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) + # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and + # STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch + # follows eddoursul/Strata 7706c1b) + set(_strata_mmq_cuda_types ${_strata_mmq_types}) + if(STRATA_MMQ_KQUANTS) + list(APPEND _strata_mmq_cuda_types q4_k q5_k q5_1) + endif() + foreach(_t IN LISTS _strata_mmq_cuda_types) + target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) + endforeach() + target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_compile_options(strata_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) + if(MSVC) + target_compile_options(strata_mmq PRIVATE $<$:-Xcompiler=/bigobj>) + endif() + target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_MMQ_KQUANTS) + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) + endif() + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() + target_link_libraries(strata_prefill PUBLIC strata_mmq) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) + # the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds) + add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp) + target_link_libraries(prefill_mmq_kquant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_kquant_test COMMAND prefill_mmq_kquant_test) + set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120) + endif() + elseif(STRATA_PREFILL_MMQ) + # Compile only the pinned GGML MMQ and activation-quantizer sources used by prefill. This uses + # common.cuh's native HIP path without enabling a second GGML HIP backend. + if(STRATA_GGML_DIR) + set(_strata_gg "${STRATA_GGML_DIR}/ggml") + else() + set(_strata_gg "${strata_llamacpp_SOURCE_DIR}/ggml") + endif() + set(_strata_mmq "${_strata_gg}/src/ggml-cuda") + if(NOT EXISTS "${_strata_mmq}/common.cuh" OR NOT EXISTS "${_strata_mmq}/quantize.cu") + message(FATAL_ERROR "The selected GGML source is missing the ggml-cuda MMQ sources: ${_strata_mmq}") + endif() + set(_strata_mmq_sources + src/prefill/moe_mmq.cu + src/prefill/ggml_cuda_host.cu + "${_strata_mmq}/quantize.cu") + foreach(_t IN LISTS _strata_mmq_types) + list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") + endforeach() + set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) + add_library(strata_mmq STATIC ${_strata_mmq_sources}) + target_include_directories(strata_mmq + PRIVATE "${_strata_gg}/include" "${_strata_gg}/src" "${_strata_mmq}" + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) + if(STRATA_ORCA_Q4KS_MMQ) + target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) + endif() + target_link_libraries(strata_mmq PUBLIC ggml-base hip::host roc::hipblas) + target_link_libraries(strata_prefill PUBLIC strata_mmq) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1) + + # Numerical diagnostic: synthetic layouts by default, optional first-expert IQ3_XXS/IQ4_NL check with a pack. + add_executable(hip_prefill_mmq_parity tests/hip/prefill_mmq_parity.cpp) + target_include_directories(hip_prefill_mmq_parity PRIVATE "${_strata_gg}/include") + target_link_libraries(hip_prefill_mmq_parity PRIVATE strata_prefill) + add_test(NAME hip_prefill_mmq_parity COMMAND hip_prefill_mmq_parity) + set_tests_properties(hip_prefill_mmq_parity PROPERTIES TIMEOUT 120) + list(APPEND _strata_hip_tests hip_prefill_mmq_parity) + endif() + if(STRATA_ENABLE_HIP) + # Optional real-model diagnostic: pass the GGUF shard containing the native PLE key. + add_executable(hip_ple_iq4 tests/hip/ple_iq4.cpp) + target_link_libraries(hip_ple_iq4 PRIVATE strata_kernels strata_hip_runtime ggml-base) + endif() + if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) + target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) + # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights + # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float + foreach(_pair q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0) + string(REPLACE "/" "_" _name "${_pair}") + add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) + set_tests_properties(native_expert_parity_${_name} PROPERTIES TIMEOUT 120) + endforeach() + add_test(NAME native_expert_parity_q5_1_min COMMAND native_expert_parity --q5_1-min) + # #290: the BF16 token embedding (--embd-gguf) gathered and dequantized bit for bit + add_test(NAME native_expert_parity_bf16_embd COMMAND native_expert_parity --bf16-embd) + # a pair without GPU kernels (Q6_K gate/up) is refused by native_expert_supported, not run + add_test(NAME native_expert_parity_refuses_q6_K COMMAND native_expert_parity --synthetic q6_K/q8_0) + set_tests_properties(native_expert_parity_refuses_q6_K PROPERTIES WILL_FAIL TRUE) + endif() + endif() + # #296's real-weight checks (OrcaRouter Q4_K_S files; docs/ORCA_Q4_K_S.md) - test programs, not part of a release + if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS) + add_executable(ple_q5_parity src/kernels/ple_q5_parity.cpp) + target_link_libraries(ple_q5_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + add_executable(q5_projection_parity src/kernels/q5_projection_parity.cpp) + target_include_directories(q5_projection_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(q5_projection_parity PRIVATE strata_kernels strata_artifact ggml-base ${_strata_gpu_runtime_target}) + # #291: the FP8 PLE table (tools/ple_fp8_pack.py) through PleTable vs the checkpoint's own values + add_executable(ple_fp8_parity src/kernels/ple_fp8_parity.cpp) + target_link_libraries(ple_fp8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() +endif() + +if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu") + add_executable(hit_cpu_order_parity bench/micro/hit_cpu_order_parity.cu) + target_link_libraries(hit_cpu_order_parity PRIVATE strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) +endif() + +if(STRATA_BUILD_TESTS) + # Plan v0.3 P6: one expert applied to several tokens, bitwise vs the single-token kernel (synthetic, CPU only). + # plan v0.3 P5: the device dequantizers vs the artifact's CPU dequantizers on the real shards (not a ctest: needs + # the 38 GB model; run it by hand or from tools/gpu_session.py) + if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # #93: it needs the device dequantizers and a GPU runtime + add_executable(dequant_bf16_test src/kernels/dequant_bf16_test.cpp) + target_link_libraries(dequant_bf16_test PRIVATE strata_kernels strata_artifact ${_strata_gpu_runtime_target}) + endif() + + add_executable(expert_multi_test src/kernels/cpu/expert_multi_test.cpp) + target_link_libraries(expert_multi_test PRIVATE strata_kernels_cpu) + add_test(NAME expert_multi_test COMMAND expert_multi_test) + + add_executable(expert_parity src/kernels/cpu/expert_parity.cpp) + target_link_libraries(expert_parity PRIVATE strata_kernels_cpu) + # The pack is a REQUIRED input, not an optional one: this test compares against a real expert blob, and a + # missing file would otherwise be reported as a pass by a test that skipped everything. + add_test(NAME expert_parity COMMAND expert_parity --selftest + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + + add_executable(pool_test src/kernels/cpu/pool_test.cpp) + target_link_libraries(pool_test PRIVATE strata_kernels_cpu) + add_test(NAME pool_test COMMAND pool_test --selftest WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it + add_executable(pool_stress src/kernels/cpu/pool_stress.cpp) + target_link_libraries(pool_stress PRIVATE strata_kernels_cpu) + add_test(NAME pool_stress COMMAND pool_stress 20) + + if(UNIX AND NOT APPLE) + add_executable(direct_file_async_test tests/platform/direct_file_async.cpp src/platform/direct_file.cpp) + target_include_directories(direct_file_async_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(direct_file_async_test PRIVATE Threads::Threads) + add_test(NAME direct_file_async_test COMMAND direct_file_async_test) + endif() +endif() + +if(STRATA_BUILD_TESTS) + enable_testing() + # Model-level checks may be absent from source distributions. + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt") + add_subdirectory(tests) + endif() +endif() diff --git a/engine/strata/Dockerfile b/engine/strata/Dockerfile new file mode 100644 index 00000000..6b62dae0 --- /dev/null +++ b/engine/strata/Dockerfile @@ -0,0 +1,115 @@ +# syntax=docker/dockerfile:1 +# +# Strata: Qwen3.8-Flash-Next on NVIDIA GPUs (RTX 30/40/50, 12+ GB VRAM; two or +# three cards can share one model, 8 GB each - docs/MULTI_GPU.md). +# +# The engine is compiled during docker build, so the first container start only +# downloads the model (~70 GB) and starts the server. docker build has no GPU, +# so the CUDA architectures are fixed here instead of read from nvidia-smi: the +# engine is a fat binary with a cubin per listed arch, and the runtime picks the +# one matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster +# build; a card outside the set needs a rebuild with its own arch. +# +# Build: +# docker build -t strata . +# docker build -t strata --build-arg CUDA_ARCHITECTURES=89 . # RTX 40 only +# +# Run (host needs an NVIDIA driver >= 580 and nvidia-container-toolkit): +# docker run --rm --gpus all \ +# -p 8080:8080 \ +# --ulimit memlock=-1 \ +# -v strata-data:/data \ +# -e MODEL=IQ2_XS \ +# strata +# +# Setup choices are env vars, read by docker-entrypoint.sh: FAMILY, MODEL, CONTEXT, +# VISION (no | yes | cpu), KV (int8 | q4_0 | k8v4), GPU (one card) or GPUS ("0,2" +# or "all", with LAYER_SPLIT), LOW_RAM (auto | on | off), HOST, PORT, API_KEY. +# +# Only the model files, the prepared pack, the MTP layer and the install config +# live in the /data volume; the engine is part of the image. Strata loads 32-62 GB +# into RAM, so a capped container needs -e LOW_RAM=on: setup.py reads the RAM from +# /proc/meminfo, which here is the host's total, not the container's limit. Add an +# API key before exposing the port to a network: -e API_KEY=. Pass +# -e REINSTALL=1 to change the model settings later. +# +# --gpus all on a host with two usable cards: setup takes both (the layer split is +# its recommended default). Pin one card with -e GPU=0, or name them with +# -e GPUS=0,2. A volume set up for one card switches to the pair on its first start +# on a two-card host unless GPU or GPUS pins it. LOW_RAM=on runs on one card. + +FROM nvidia/cuda:13.0.0-devel-ubuntu24.04 + +# STRATA_EXECV=1: setup.py replaces itself with the server, so the server is PID 1 +# and docker stop's SIGTERM reaches it (see setup.start). Normal Linux starts, which +# don't set it, keep spawning the server as a child. +ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 LANG=C.UTF-8 STRATA_EXECV=1 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl git libatomic1 libgomp1 \ + python3 python3-pip python3-venv unzip \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /opt/strata +COPY . . + +# RTX 20 (75), RTX 30 (86), RTX 40 (89), RTX 50 (120), plus 80 for A-series. CMakeLists +# refuses anything below 75. BUILD_VISION=0 skips the image encoder build. +ARG CUDA_ARCHITECTURES=75;80;86;89;120 +ARG BUILD_VISION=1 + +RUN python3 -m venv .venv \ + && .venv/bin/pip install --no-cache-dir --upgrade pip \ + && .venv/bin/pip install --no-cache-dir -r requirements.txt \ + && chmod +x setup.sh docker-entrypoint.sh + +# llama.cpp at the pinned commit, then the engine and the image encoder, built +# exactly the way setup.py builds them. BUILD.json is what setup.py reads to +# decide whether an engine is current: source=local with a matching src hash +# means the first start reuses it instead of recompiling. +RUN .venv/bin/python - <<'PYEOF' +import json, os, pathlib, shutil +import setup + +llama = setup.get_llama_cpp() +nvcc, _ = setup.find_nvcc() +arch = os.environ.get("CUDA_ARCHITECTURES", "75;80;86;89;120").strip().strip('"').replace(",", ";") +vision = "gpu" if os.environ.get("BUILD_VISION", "1") == "1" else "none" + +setup.cmake_build(setup.ROOT, setup.ROOT / "build", "strata", + ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", + f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}", + f"-DSTRATA_GGML_DIR={llama}"], None, "build-strata.bat") +if vision != "none": + setup.cmake_build(setup.ROOT / "tools" / "vision", setup.ROOT / "build-vision", "strata-vision", + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=ON", + f"-DCMAKE_CUDA_ARCHITECTURES={arch}", f"-DCMAKE_CUDA_COMPILER={nvcc}"], None, "build-vision.bat") + +eng = setup.ROOT / "engine" +eng.mkdir(exist_ok=True) +shutil.copy2(setup.ROOT / "build" / setup.EXE, eng / setup.EXE) +if vision != "none": + shutil.copy2(setup.ROOT / "build-vision" / "bin" / setup.VEXE, eng / setup.VEXE) +bindir = pathlib.Path(nvcc).parent +meta = {"source": "local", "version": setup.source_version(), + "archs": [int(a.split("-")[0]) for a in arch.split(";") if a.split("-")[0].isdigit()], "vision": vision, + "cuda_dirs": [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()], + "src": setup.source_hash(setup.ENGINE_SOURCES), + "vision_src": setup.source_hash(setup.VISION_SOURCES) if vision != "none" else None} +(eng / "BUILD.json").write_text(json.dumps(meta, indent=1)) +PYEOF + +# the cmake trees are build-time only; the engine itself is what the container needs +RUN rm -rf build build-vision + +VOLUME ["/data"] +EXPOSE 8080 + +# /health is answered before the API key gate, so it works with or without one. +# The port only opens after the model loads (1-3 minutes, longer on a first run), +# so the start period is generous: a too short one marks a still-loading container +# unhealthy and a restart policy would kill it mid-download. +HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \ + CMD curl -fs "http://127.0.0.1:${PORT:-8080}/health" || exit 1 + +ENTRYPOINT ["./docker-entrypoint.sh"] diff --git a/engine/strata/LICENSE b/engine/strata/LICENSE new file mode 100644 index 00000000..6687a423 --- /dev/null +++ b/engine/strata/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Niko1221 and the Strata contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/engine/strata/README.md b/engine/strata/README.md new file mode 100644 index 00000000..10812dcb --- /dev/null +++ b/engine/strata/README.md @@ -0,0 +1,184 @@ +

Strata

+ +

Run a 125-billion-parameter AI model on your own gaming PC
+NVIDIA or AMD graphics card (12 GB or more) · Windows or Linux · free and open source

+ +

A voxel pagoda garden that Strata's model wrote, running in the browser
+A voxel pagoda garden, 1 shot prompt running on an RTX 5070 with Strata (IQ3_S, 128K context) · +full video (49 s)

+ +Strata runs **[Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)** - a large, smart AI model that +normally needs a server - on a normal PC. It chats, writes code, reads pictures and works with your apps and coding +agents, and nothing leaves your PC. + +## How fast is it? + +Measured on two ordinary gaming PCs. "Writes answers" is how fast the reply appears in a short chat; "reads your +prompt" is how fast it takes in what you send (a 32K-token document, code or chat history). A token is about ¾ of a +word, so 60 tokens per second is faster than you can read. + + + + +
NVIDIA: RTX 5070 (12 GB), Ryzen 5 7600, 64 GB RAMAMD: RX 9070 XT (16 GB), Ryzen 9 3900X, 47 GB RAM
+ +| Size | Writes answers | Reads your prompt | +| --- | ---: | ---: | +| **Q2_0** | 93 tokens/s | 2,170 tokens/s | +| **IQ2_XS** | 79 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 1,620 tokens/s | +| **Coder** | 55 tokens/s | 2,180 tokens/s | + + + +| Size | Writes answers | Reads your prompt | +| --- | ---: | ---: | +| **Q2_0** | 60 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 1,110 tokens/s | +| **Coder** | 44 tokens/s | 1,420 tokens/s | + +
+ +A card with more VRAM is faster: an RTX 3090 (24 GB) should write roughly 100-140 tokens per second. Long chats, +other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), [community results](docs/COMMUNITY_BENCHMARKS.md). + +

Buy Me A Coffee
+Strata is free. If it runs well on your PC, a coffee keeps the work on it going.

+ +## What you need + +| | | +| --- | --- | +| **Graphics card** | **NVIDIA** GeForce RTX 20, 30, 40 or 50 series, or **AMD** Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700 or RX 6800 / 6900 series - with **12 GB of VRAM or more** | +| **RAM** | 32 GB or more - how much decides [which model](#which-model-should-i-pick) fits; 64 GB runs every size | +| **Disk** | about 80 GB free, on an SSD if you can (the first start is much faster) | +| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD | + +Everything else is installed for you. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)). +The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need). + +## Install + +### Let your AI set it up + +Use an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...)? Paste this into it: + +```text +Set up Strata on this PC for me: https://github.com/Niko1221/Strata - follow docs/AI_SETUP.md in that repository. +``` + +It checks your graphics card, RAM and disk, picks the model that fits, installs it, starts it and tells you how to +connect your apps. AI tools can also install, start and stop Strata themselves through its +[MCP server](docs/MCP_SERVER.md). + +### Or do it yourself + +[Download Strata](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or `git clone` it). +**Windows:** double-click **`START-HERE.bat`**. **Linux:** run **`./setup.sh`** in the Strata folder. + +The same steps for NVIDIA and AMD: the installer finds your card and sets up the right engine for it. It asks which +model, which size, how much context (how much text it keeps in mind) and whether it should read pictures - press +Enter each time for the recommended answer. Then it downloads the model (~70 GB; you can stop and it continues where +it left off) and starts it. Your browser opens the Strata app at `http://127.0.0.1:8080`. + +> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata +> loads 35-55 GB into your RAM and locks part of it for the graphics card. That's normal - wait, and don't close the +> window. The window tells you what it is doing. + +**Next time**, run `START-HERE.bat` (or `./setup.sh`) again: it starts right away, nothing is downloaded twice. Close +its window to stop the model. Updating, Docker, several cards, where the files go and every option: +[docs/INSTALL.md](docs/INSTALL.md). + +## Which model should I pick? + +The installer recommends one for your RAM. The same model comes in sizes that are compressed more or less: smaller +is faster, larger is a bit smarter. + +| Your RAM | Take | Why | +| --- | --- | --- | +| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too) | +| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | +| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits; IQ3_S is the best, and the slowest | +| **96 GB or more** | **IQ3_S**, or Unsloth's 4-bit (experimental) | room for the largest sizes with everything else open | + +- **[Coder](docs/MODELS.md#coder)** - a coding version with half of the experts removed: 91% of the full model's + SWE-bench Verified score (by its authors), fits 32 GB of RAM. Weaker outside code, including Chinese and other + CJK text (#438): for those, take Q2_0, IQ2_XS or IQ3_S, which keep every expert. +- **[Swift 1.5](docs/MODELS.md#swift-15)** - a fine-tune that thinks much shorter before it answers, so you get the + answer sooner, at about the same quality. +- **[Unsloth UD-Q4_K_XL](docs/MODELS.md#unsloth-ud-q4_k_xl-experimental)** (experimental) - the closest to the full + model, but most of it is read from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC. +- **[OrcaRouter's Uncensored IQ3_XXS](docs/MODELS.md#orcarouter-uncensored-iq3_xxs)** - a manual setup, not in the + installer's menu. + +Sizes, downloads and what fits where: [docs/MODELS.md](docs/MODELS.md). You can add another model later with +`SETUP.bat` (Linux: `./setup.sh --setup`). + +## Using it + +

The Strata app's Monitor tab next to a coding agent
+The Strata app's Monitor (left) while a coding agent writes the pagoda garden from the video (right)

+ +- **In the browser:** `http://127.0.0.1:8080` - **Chat**, a live **Monitor** of the model and your GPU/CPU/RAM, and + **About** with the settings and addresses. +- **Your apps and coding agents:** add an "OpenAI-compatible" provider with base URL **`http://127.0.0.1:8080/v1`**, + any API key and any model name. Apps that use Anthropic's API: `http://127.0.0.1:8080/v1/messages` (Claude Code: + `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`). +- **Thinking:** choose **off, low, medium or high** in the chat menu or your app's "reasoning effort". Off is + fastest; high is best for hard questions. +- **Pictures:** say yes to "Images?" in setup, then click **Picture** in the chat, or attach them in your app + (AMD cards: on Linux through the processor, not on Windows yet). +- **From your phone or another PC:** `START-HERE.bat --setup --host 0.0.0.0 --api-key ` - always with a key. +- **Good to know:** it answers one request at a time. The first message of a chat is read in full (about 1 minute + per 30,000 tokens); follow-ups start in seconds. + +More: [where your chats are stored](docs/INSTALL.md#where-things-are-stored), [the API](docs/DETAILS.md#using-it). + +## Something went wrong? + +- **My PC froze the first time Strata started.** Normal while it loads the model: wait, don't close the window. + Still frozen after 10 minutes? Restart the PC, close other programs and try again, or pick a smaller size. +- **It stopped while downloading or installing.** Run `START-HERE.bat` (or `./setup.sh`) again: it continues where + it stopped. +- **It's very slow and the disk light keeps blinking, or "the engine stopped unexpectedly".** Not enough free RAM: + close other programs (browsers use a lot), or pick a smaller size (Q2_0 or IQ2_XS). +- **It says port 8080 is already in use.** Strata is already running - look for its window. + +More problems and their fixes: [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Still stuck? Open an +[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. + +## How does it work? + +Models like this one normally run on servers with hundreds of gigabytes of graphics memory. Your graphics card has +12-24 GB. Strata makes it fit by **sharing the work across your whole PC** - like a kitchen, where the things you use +all the time stay on the counter and the rest waits in the pantry. + +

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

+ +- **The model is a team of 24,576 small specialists ("experts"),** and each word needs only 10 of them. +- **Your graphics card** keeps the few thousand experts that are asked most often; **your RAM** holds all of them, + and **your processor** works on the rest at the same time. **Your SSD** holds a big lookup table. + +

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

+ +- **Guess, then check:** a small helper guesses the next few words and the big model checks them all at once, so + you get the same answer, 1.6-1.8x sooner. +- **Long texts are read in big pieces** (up to 8,192 tokens at a time): over 1,000 tokens per second. + +The longer explanation: [docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md). Every part and its numbers: [the +details](docs/DETAILS.md#how-it-works) and the [paper](docs/paper/Strata-Paper.pdf). + +## Credits and license + +The model is [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team, compressed by +[ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF), UkisAI (Swift 1.5) and Unsloth; +Strata is built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp). All credits: +[docs/HOW_IT_WORKS.md](docs/HOW_IT_WORKS.md#credits). Strata is open source under the [MIT License](LICENSE); a few +parts and every model carry their own licenses ([which ones](docs/HOW_IT_WORKS.md#license)). + +## Support Strata + +Strata is free and open source. If it is useful to you, you can support its development: + +

Buy Me A Coffee

diff --git a/engine/strata/SETUP.bat b/engine/strata/SETUP.bat new file mode 100644 index 00000000..d2e6541c --- /dev/null +++ b/engine/strata/SETUP.bat @@ -0,0 +1,3 @@ +@echo off +rem Change settings or install another model (the same as START-HERE.bat --setup). +call "%~dp0START-HERE.bat" --setup %* diff --git a/engine/strata/START-HERE.bat b/engine/strata/START-HERE.bat new file mode 100644 index 00000000..dfb92feb --- /dev/null +++ b/engine/strata/START-HERE.bat @@ -0,0 +1,52 @@ +@echo off +rem Strata for Windows: the first run installs everything and starts the model; later runs just start it. +rem Needs only an NVIDIA or AMD graphics driver. Python is installed for your user account if it is missing (no admin needed). +setlocal +title Strata +cd /d "%~dp0" +if exist ".venv\Scripts\python.exe" goto run + +call :findpy +if defined PY goto venv +echo. +echo Python 3.10 or newer is not installed. Installing Python 3.12 for your user account ... +where winget >nul 2>nul +if errorlevel 1 goto pyorg +winget install -e --id Python.Python.3.12 --scope user --silent --source winget --accept-package-agreements --accept-source-agreements --disable-interactivity +call :findpy +if defined PY goto venv +:pyorg +echo Downloading the Python installer from python.org ... +powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol='Tls12'; Invoke-WebRequest -UseBasicParsing https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe -OutFile \"$env:TEMP\strata-python-setup.exe\"" +if exist "%TEMP%\strata-python-setup.exe" "%TEMP%\strata-python-setup.exe" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 Include_test=0 +call :findpy +if defined PY goto venv +echo. +echo Python could not be installed automatically. +echo Install 64-bit Python 3.12 from https://www.python.org/downloads/ ("Add python.exe to PATH"), +echo then double-click START-HERE.bat again. +pause +exit /b 1 + +:venv +rem a private environment inside this folder, so nothing is installed into the system Python +%PY% -m venv .venv +if exist ".venv\Scripts\python.exe" goto run +echo Could not create the Python environment in .venv +pause +exit /b 1 + +:run +".venv\Scripts\python.exe" setup.py %* +if errorlevel 1 pause +exit /b + +:findpy +rem the py launcher first, then python on PATH (not the Microsoft Store stub), then the usual per-user folders +set "PY=" +py -3 -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul +if not errorlevel 1 set "PY=py -3" & goto :eof +python -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) and sys.maxsize > 2**32 else 1)" >nul 2>nul +if not errorlevel 1 set "PY=python" & goto :eof +for %%V in (313 312 311 310) do if exist "%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe" set "PY="%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe"" & goto :eof +goto :eof diff --git a/engine/strata/bench/results/2026-09-24-final/estimates.json b/engine/strata/bench/results/2026-09-24-final/estimates.json new file mode 100644 index 00000000..0479ec41 --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-final/estimates.json @@ -0,0 +1,461 @@ +[ + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "1k", + "slots": 4517, + "h": 0.747, + "decode": 88.7, + "prefill": 389.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "1k", + "slots": 7179, + "h": 0.826, + "decode": 80.5, + "prefill": 341.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "1k", + "slots": 12503, + "h": 0.93, + "decode": 127.5, + "prefill": 355.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "4k", + "slots": 4464, + "h": 0.722, + "decode": 94.6, + "prefill": 539.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "4k", + "slots": 7126, + "h": 0.809, + "decode": 87.4, + "prefill": 472.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "4k", + "slots": 12450, + "h": 0.923, + "decode": 140.0, + "prefill": 491.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "32k", + "slots": 4174, + "h": 0.674, + "decode": 87.5, + "prefill": 571.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "32k", + "slots": 6836, + "h": 0.774, + "decode": 81.3, + "prefill": 501.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "32k", + "slots": 12160, + "h": 0.907, + "decode": 130.0, + "prefill": 521.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "64k", + "slots": 3809, + "h": 0.625, + "decode": 76.4, + "prefill": 561.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "64k", + "slots": 6471, + "h": 0.74, + "decode": 71.6, + "prefill": 492.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "64k", + "slots": 11795, + "h": 0.892, + "decode": 115.3, + "prefill": 512.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "128k", + "slots": 3079, + "h": 0.571, + "decode": 65.1, + "prefill": 543.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "128k", + "slots": 5741, + "h": 0.702, + "decode": 61.8, + "prefill": 476.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "128k", + "slots": 11065, + "h": 0.873, + "decode": 100.0, + "prefill": 495.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "Q2_0", + "tier": "262k", + "slots": 1588, + "h": 0.526, + "decode": 56.3, + "prefill": 496.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "Q2_0", + "tier": "262k", + "slots": 4250, + "h": 0.668, + "decode": 52.9, + "prefill": 435.0 + }, + { + "card": "RTX 3090 24GB", + "model": "Q2_0", + "tier": "262k", + "slots": 9574, + "h": 0.849, + "decode": 84.6, + "prefill": 453.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "1k", + "slots": 4621, + "h": 0.799, + "decode": 82.0, + "prefill": 332.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "1k", + "slots": 7176, + "h": 0.86, + "decode": 79.6, + "prefill": 291.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "1k", + "slots": 12287, + "h": 0.941, + "decode": 131.1, + "prefill": 303.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "4k", + "slots": 4568, + "h": 0.785, + "decode": 78.1, + "prefill": 463.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "4k", + "slots": 7123, + "h": 0.85, + "decode": 76.9, + "prefill": 406.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "4k", + "slots": 12234, + "h": 0.937, + "decode": 127.7, + "prefill": 422.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "32k", + "slots": 4289, + "h": 0.783, + "decode": 65.3, + "prefill": 495.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "32k", + "slots": 6844, + "h": 0.848, + "decode": 62.9, + "prefill": 434.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "32k", + "slots": 11955, + "h": 0.935, + "decode": 102.9, + "prefill": 451.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "64k", + "slots": 3936, + "h": 0.759, + "decode": 63.7, + "prefill": 486.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "64k", + "slots": 6491, + "h": 0.83, + "decode": 62.0, + "prefill": 426.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "64k", + "slots": 11602, + "h": 0.927, + "decode": 102.2, + "prefill": 444.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "128k", + "slots": 3229, + "h": 0.695, + "decode": 52.0, + "prefill": 472.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "128k", + "slots": 5784, + "h": 0.784, + "decode": 51.3, + "prefill": 413.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "128k", + "slots": 10895, + "h": 0.905, + "decode": 85.0, + "prefill": 430.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ2_XS", + "tier": "262k", + "slots": 1796, + "h": 0.627, + "decode": 48.1, + "prefill": 437.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ2_XS", + "tier": "262k", + "slots": 4351, + "h": 0.735, + "decode": 47.3, + "prefill": 383.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ2_XS", + "tier": "262k", + "slots": 9462, + "h": 0.876, + "decode": 77.5, + "prefill": 398.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 3556, + "h": 0.638, + "decode": 64.6, + "prefill": 285.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 5658, + "h": 0.728, + "decode": 65.8, + "prefill": 249.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "1k", + "slots": 9864, + "h": 0.858, + "decode": 106.5, + "prefill": 260.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 3511, + "h": 0.712, + "decode": 65.6, + "prefill": 410.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 5613, + "h": 0.784, + "decode": 64.7, + "prefill": 359.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "4k", + "slots": 9819, + "h": 0.887, + "decode": 103.0, + "prefill": 374.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 3279, + "h": 0.696, + "decode": 57.3, + "prefill": 435.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 5381, + "h": 0.772, + "decode": 56.3, + "prefill": 381.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "32k", + "slots": 9587, + "h": 0.879, + "decode": 89.0, + "prefill": 396.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 2990, + "h": 0.677, + "decode": 54.4, + "prefill": 427.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 5092, + "h": 0.757, + "decode": 53.7, + "prefill": 374.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "64k", + "slots": 9298, + "h": 0.87, + "decode": 85.1, + "prefill": 390.0 + }, + { + "card": "RTX 5070 12GB (measured)", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 2407, + "h": 0.57, + "decode": 44.8, + "prefill": 414.0 + }, + { + "card": "RTX 5060 Ti 16GB", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 4509, + "h": 0.675, + "decode": 44.6, + "prefill": 363.0 + }, + { + "card": "RTX 3090 24GB", + "model": "IQ3_XXS", + "tier": "128k", + "slots": 8715, + "h": 0.824, + "decode": 70.8, + "prefill": 378.0 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-24-final/estimates.md b/engine/strata/bench/results/2026-09-24-final/estimates.md new file mode 100644 index 00000000..66b88d27 --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-final/estimates.md @@ -0,0 +1,27 @@ +### Output (decode) tok/s - estimated + +| Card | Model | 1k | 4k | 32k | 64k | 128k | 262k | +|---|---|---:|---:|---:|---:|---:|---:| +| RTX 5070 12GB (measured) | Q2_0 | ~89 | ~95 | ~88 | ~76 | ~65 | ~56 | +| RTX 5070 12GB (measured) | IQ2_XS | ~82 | ~78 | ~65 | ~64 | ~52 | ~48 | +| RTX 5070 12GB (measured) | IQ3_XXS | ~65 | ~66 | ~57 | ~54 | ~45 | - | +| RTX 5060 Ti 16GB | Q2_0 | ~80 | ~87 | ~81 | ~72 | ~62 | ~53 | +| RTX 5060 Ti 16GB | IQ2_XS | ~80 | ~77 | ~63 | ~62 | ~51 | ~47 | +| RTX 5060 Ti 16GB | IQ3_XXS | ~66 | ~65 | ~56 | ~54 | ~45 | - | +| RTX 3090 24GB | Q2_0 | ~128 | ~140 | ~130 | ~115 | ~100 | ~85 | +| RTX 3090 24GB | IQ2_XS | ~131 | ~128 | ~103 | ~102 | ~85 | ~78 | +| RTX 3090 24GB | IQ3_XXS | ~106 | ~103 | ~89 | ~85 | ~71 | - | + +### Prompt processing tok/s - estimated + +| Card | Model | 1k | 4k | 32k | 64k | 128k | 262k | +|---|---|---:|---:|---:|---:|---:|---:| +| RTX 5070 12GB (measured) | Q2_0 | ~389 | ~539 | ~571 | ~561 | ~543 | ~496 | +| RTX 5070 12GB (measured) | IQ2_XS | ~332 | ~463 | ~495 | ~486 | ~472 | ~437 | +| RTX 5070 12GB (measured) | IQ3_XXS | ~285 | ~410 | ~435 | ~427 | ~414 | - | +| RTX 5060 Ti 16GB | Q2_0 | ~341 | ~472 | ~501 | ~492 | ~476 | ~435 | +| RTX 5060 Ti 16GB | IQ2_XS | ~291 | ~406 | ~434 | ~426 | ~413 | ~383 | +| RTX 5060 Ti 16GB | IQ3_XXS | ~249 | ~359 | ~381 | ~374 | ~363 | - | +| RTX 3090 24GB | Q2_0 | ~355 | ~491 | ~521 | ~512 | ~495 | ~453 | +| RTX 3090 24GB | IQ2_XS | ~303 | ~422 | ~451 | ~444 | ~430 | ~398 | +| RTX 3090 24GB | IQ3_XXS | ~260 | ~374 | ~396 | ~390 | ~378 | - | diff --git a/engine/strata/bench/results/2026-09-24-final/matrix.json b/engine/strata/bench/results/2026-09-24-final/matrix.json new file mode 100644 index 00000000..260c8330 --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-final/matrix.json @@ -0,0 +1,240 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.2, + "prefill_tok_s": 388.83, + "ttft_s": 2.68, + "decode_tok_s": 88.67, + "decoded": 256, + "spec_accept": 0.739, + "tokens_per_round": 2.71, + "vram_slots": 4517 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 44.6, + "prefill_tok_s": 538.75, + "ttft_s": 6.67, + "decode_tok_s": 94.59, + "decoded": 256, + "spec_accept": 0.846, + "tokens_per_round": 3.23, + "vram_slots": 4464 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 91.9, + "prefill_tok_s": 571.03, + "ttft_s": 55.34, + "decode_tok_s": 87.48, + "decoded": 256, + "spec_accept": 0.865, + "tokens_per_round": 3.11, + "vram_slots": 4174 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 151.5, + "prefill_tok_s": 561.16, + "ttft_s": 114.4, + "decode_tok_s": 76.38, + "decoded": 256, + "spec_accept": 0.781, + "tokens_per_round": 2.8, + "vram_slots": 3809 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 273.5, + "prefill_tok_s": 542.95, + "ttft_s": 236.7, + "decode_tok_s": 65.09, + "decoded": 256, + "spec_accept": 0.687, + "tokens_per_round": 2.65, + "vram_slots": 3079 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 562.5, + "prefill_tok_s": 496.33, + "ttft_s": 523.8, + "decode_tok_s": 56.26, + "decoded": 256, + "spec_accept": 0.659, + "tokens_per_round": 2.46, + "vram_slots": 1588 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 42.3, + "prefill_tok_s": 332.19, + "ttft_s": 3.14, + "decode_tok_s": 81.97, + "decoded": 256, + "spec_accept": 0.84, + "tokens_per_round": 3.25, + "vram_slots": 4621 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 47.4, + "prefill_tok_s": 462.95, + "ttft_s": 7.78, + "decode_tok_s": 78.05, + "decoded": 256, + "spec_accept": 0.856, + "tokens_per_round": 3.28, + "vram_slots": 4568 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 102.3, + "prefill_tok_s": 495.14, + "ttft_s": 63.83, + "decode_tok_s": 65.32, + "decoded": 256, + "spec_accept": 0.706, + "tokens_per_round": 2.53, + "vram_slots": 4289 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 170.8, + "prefill_tok_s": 486.42, + "ttft_s": 131.99, + "decode_tok_s": 63.66, + "decoded": 256, + "spec_accept": 0.701, + "tokens_per_round": 2.72, + "vram_slots": 3936 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 312.7, + "prefill_tok_s": 471.61, + "ttft_s": 272.52, + "decode_tok_s": 52.04, + "decoded": 256, + "spec_accept": 0.602, + "tokens_per_round": 2.44, + "vram_slots": 3229 + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 637.4, + "prefill_tok_s": 436.86, + "ttft_s": 595.11, + "decode_tok_s": 48.05, + "decoded": 256, + "spec_accept": 0.628, + "tokens_per_round": 2.42, + "vram_slots": 1796 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 43.8, + "prefill_tok_s": 284.64, + "ttft_s": 3.67, + "decode_tok_s": 64.58, + "decoded": 256, + "spec_accept": 0.912, + "tokens_per_round": 3.63, + "vram_slots": 3556 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 48.5, + "prefill_tok_s": 409.76, + "ttft_s": 8.78, + "decode_tok_s": 65.57, + "decoded": 256, + "spec_accept": 0.863, + "tokens_per_round": 3.24, + "vram_slots": 3511 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 112.6, + "prefill_tok_s": 434.75, + "ttft_s": 72.69, + "decode_tok_s": 57.3, + "decoded": 256, + "spec_accept": 0.752, + "tokens_per_round": 2.78, + "vram_slots": 3279 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 190.1, + "prefill_tok_s": 427.26, + "ttft_s": 150.25, + "decode_tok_s": 54.4, + "decoded": 256, + "spec_accept": 0.723, + "tokens_per_round": 2.88, + "vram_slots": 2990 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 351.1, + "prefill_tok_s": 414.43, + "ttft_s": 310.1, + "decode_tok_s": 44.81, + "decoded": 256, + "spec_accept": 0.648, + "tokens_per_round": 2.42, + "vram_slots": 2407 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-24-final/matrix.md b/engine/strata/bench/results/2026-09-24-final/matrix.md new file mode 100644 index 00000000..b9b2cb9c --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-final/matrix.md @@ -0,0 +1,15 @@ +### Prompt processing (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +|---|---:|---:|---:|---:|---:|---:| +| Q2_0 | 389 | 539 | 571 | 561 | 543 | 496 | +| IQ2_XS | 332 | 463 | 495 | 486 | 472 | 437 | +| IQ3_XXS | 285 | 410 | 435 | 427 | 414 | - | + +### Output (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +|---|---:|---:|---:|---:|---:|---:| +| Q2_0 | 88.7 | 94.6 | 87.5 | 76.4 | 65.1 | 56.3 | +| IQ2_XS | 82.0 | 78.0 | 65.3 | 63.7 | 52.0 | 48.0 | +| IQ3_XXS | 64.6 | 65.6 | 57.3 | 54.4 | 44.8 | - | diff --git a/engine/strata/bench/results/2026-09-24-vision/vision.json b/engine/strata/bench/results/2026-09-24-vision/vision.json new file mode 100644 index 00000000..5150dc24 --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-vision/vision.json @@ -0,0 +1,53 @@ +[ + { + "model": "Q2_0", + "off": { + "prefill_tok_s": 541.31, + "decode_tok_s": 90.74, + "vram_slots": 4464, + "spec_accept": 0.846 + }, + "on": { + "prefill_tok_s": 530.64, + "decode_tok_s": 86.92, + "vram_slots": 3402, + "spec_accept": 0.858 + }, + "flag_identical": true, + "on_identical": false + }, + { + "model": "IQ2_XS", + "off": { + "prefill_tok_s": 468.17, + "decode_tok_s": 77.14, + "vram_slots": 4568, + "spec_accept": 0.856 + }, + "on": { + "prefill_tok_s": 457.61, + "decode_tok_s": 73.96, + "vram_slots": 3542, + "spec_accept": 0.866 + }, + "flag_identical": true, + "on_identical": false + }, + { + "model": "IQ3_XXS", + "off": { + "prefill_tok_s": 411.3, + "decode_tok_s": 64.7, + "vram_slots": 3511, + "spec_accept": 0.863 + }, + "on": { + "prefill_tok_s": 401.48, + "decode_tok_s": 59.46, + "vram_slots": 2662, + "spec_accept": 0.868 + }, + "flag_identical": true, + "on_identical": true + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-24-vision/vision.md b/engine/strata/bench/results/2026-09-24-vision/vision.md new file mode 100644 index 00000000..c30d2992 --- /dev/null +++ b/engine/strata/bench/results/2026-09-24-vision/vision.md @@ -0,0 +1,5 @@ +| Model | Prompt tok/s (vision off) | Prompt tok/s (vision on) | Output tok/s (vision off) | Output tok/s (vision on) | VRAM expert slots off / on | --vision alone: same tokens | +|---|---:|---:|---:|---:|---:|---| +| Q2_0 | 541 | 531 | 90.7 | 86.9 | 4464 / 3402 | yes | +| IQ2_XS | 468 | 458 | 77.1 | 74.0 | 4568 / 3542 | yes | +| IQ3_XXS | 411 | 401 | 64.7 | 59.5 | 3511 / 2662 | yes | diff --git a/engine/strata/bench/results/2026-09-27-cache-parity/README.md b/engine/strata/bench/results/2026-09-27-cache-parity/README.md new file mode 100644 index 00000000..10f1d19d --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-cache-parity/README.md @@ -0,0 +1,29 @@ +# 2026-09-27: expert cache on vs off (issue #23) + +Question: the engine used to warn at start that "the GPU hit path is NOT CORRECT ... any OUTPUT from it is not". Does +the expert cache make the output worse? + +Method: teacher-forced. `strata --dump-logits` runs a text one token at a time and writes the logits at every +position, so both runs see the same text and each position's next-token prediction can be compared: +- cache off: no `--expert-cache`, every routed expert computed by the CPU pool; +- cache on: `--expert-profile pack/profile-decode-8k.bin --expert-cache auto`, 5,130 of the most-used experts on the GPU. + +Q2_0, RTX 5070, the first 512 or 1,024 tokens of three frozen prompts. + +| Text | Same top-1 | Median KL | Perplexity off | Perplexity on | On - off (nats per token) | +|---|---:|---:|---:|---:|---:| +| Code agent (512) | 97.7% | 3.0e-04 | 2.672 | 2.630 | -0.016 +- 0.019 | +| Long document (1,024) | 96.2% | 4.5e-03 | 29.844 | 29.843 | -0.000 +- 0.005 | +| Chat (1,024) | 95.0% | 4.4e-03 | 18.380 | 18.301 | -0.004 +- 0.006 | +| **All 2,557 tokens** | | | | | **-0.005 +- 0.005** | + +Reading: +- The cache changes which of two nearly equal candidates wins at 2-5% of positions. Most of the flips have a top-2 + margin under 0.5 logits (`logits-compare.txt`). +- Neither side is more accurate: the perplexity of the actual text is the same, within 1 standard error. +- A GPU expert and the CPU compute the same quantized expert with a different floating-point order. Both are an + equally good approximation of the model. + +The start-up warning dates from round 328, when the GPU hit path had a real fault (divergence from token 0). That fault +was fixed long ago and is covered by `expert_parity`, `native_expert_parity` and the grouped kernels' tests. Since +engine 0.1.8 the warning is replaced by one accurate line. diff --git a/engine/strata/bench/results/2026-09-27-esp/README.md b/engine/strata/bench/results/2026-09-27-esp/README.md new file mode 100644 index 00000000..19ff7780 --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-esp/README.md @@ -0,0 +1,36 @@ +# 2026-09-27: the experimental-speed-projection control vector + +The package's `Qwen3.8-Flash-Next-experimental-speed-projection.gguf` (47 unit directions of 2,560, one per layer), +applied as `--control-vector-scaled FILE:1.0 --control-vector-layer-range 4 44 --cvec-mode project --cvec-dir +per-layer`: after layers 4-44, every hyper-connection stream `h -= (h . v) v`. The package describes it as a +refusal-direction projection. Q2_0, RTX 5070, fixed experts (`--expert-cache 4000 --pcie-frac 0 --adapt-swaps 0`). + +## Kernel (`cvec_parity`) + +Project and add against a double-precision reference (max error 5e-7); with the switch off, the kernel's pending +residual write is bitwise the fused hyper-connection read's own, so a loaded-but-off vector is the stock engine. + +## Teacher-forced, stock vs projection (`esp_kl.py`, per-token path) + +| Text | Tokens | Same top-1 | Mean KL | p99 KL | Perplexity stock | With the vector | +|---|---:|---:|---:|---:|---:|---:| +| Code | 511 | 92.8% | 0.098 | 1.69 | 2.594 | 2.982 | +| Document | 1,023 | 89.8% | 0.058 | 0.84 | 30.299 | 30.984 | +| Chat | 1,023 | 89.6% | 0.050 | 0.33 | 18.409 | 18.485 | +| **All** | 2,557 | | **0.063** (max 4.10) | 1.00 | | | + +The package reports a mean KL of 0.186 on its own neutral text with UD-Q2_K_XL in llama.cpp. + +Cost on the same tokens: 44.34 -> 44.26, 46.74 -> 46.56, 47.02 -> 46.83 tok/s (0.2-0.4%). + +## Serve (`esp_serve.py`) + +- Loaded and switched off (`cvec=0`) vs an engine without it: 65 / 65 first tokens after prefixes (verify windows + and the batched prompt path) and three 256-token generations **token-identical**. +- On, off, on again: identical (the switch drops the conversation cache, so nothing computed one way is reused the + other way). +- The prompt paths steer like the per-token path: served-with-vector first tokens agree with the per-token path's + teacher-forced argmax with the vector 62 / 65, and with the stock one 57 / 65 (stock served: 64 / 65 and 57 / 65). +- Decode tok/s of 3 x 256-token generations: stock 66.4, on 76.7 / 81.2. **Not a like-for-like comparison:** the + model writes different text with it on (on the code prompt it copied a long stretch of the source, which prompt + lookup drafts at 91% acceptance, where stock stopped after 78 tokens). On the same tokens it is 0.2-0.4% slower. diff --git a/engine/strata/bench/results/2026-09-27-esp/esp_kl.py b/engine/strata/bench/results/2026-09-27-esp/esp_kl.py new file mode 100644 index 00000000..5ec6d3ad --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-esp/esp_kl.py @@ -0,0 +1,85 @@ +"""Teacher-forced logits, stock vs the experimental-speed-projection vector, on the same texts and fixed experts. + + python esp_kl.py run # the dumps (per-token path) + python esp_kl.py compare # same top-1, mean/median KL(stock || projection), perplexities +""" +import json +import os +import subprocess +import sys + +import numpy as np + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-kl" +ARMS = {"stock": [], + "proj": ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"]} + + +def base_args(): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + i = a.index("--expert-cache") + a[i + 1] = "4000" + j = a.index("--prefill") # the prompt one token at a time: a logits row per position + del a[j:j + 2] + return a + ["--pcie-frac", "0", "--adapt-swaps", "0"], c + + +def run(): + os.makedirs(OUT, exist_ok=True) + args, c = base_args() + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + for name, path in TEXTS.items(): + for arm, extra in ARMS.items(): + out = f"{OUT}\\{name}-{arm}.bin" + if os.path.exists(out): + continue + cmd = [EXE, *args, *extra, "--tokens-file", path, "--max-new", "1", "--dump-logits", out] + with open(f"{OUT}\\{name}-{arm}.log", "w") as log: + r = subprocess.run(cmd, cwd=c["cwd"], stdout=log, stderr=subprocess.STDOUT, env=env) + print(name, arm, "exit", r.returncode, flush=True) + + +def load(p): + h = np.fromfile(p, dtype=np.int32, count=2) + return np.memmap(p, dtype=np.float32, mode="r", offset=8, shape=(int(h[1]), int(h[0]))) + + +def lsm(x): + x = x.astype(np.float64) + m = x.max(axis=-1, keepdims=True) + return x - (m + np.log(np.exp(x - m).sum(axis=-1, keepdims=True))) + + +def compare(): + print(f"{'text':<6}{'tokens':>7}{'same top-1':>11}{'mean KL':>9}{'median KL':>11}{'p99 KL':>8}{'ppl stock':>10}{'ppl proj':>9}") + allkl = [] + for name, path in TEXTS.items(): + ids = [int(x) for x in open(path).read().replace(",", " ").split()] + a, b = load(f"{OUT}\\{name}-stock.bin"), load(f"{OUT}\\{name}-proj.bin") + n = min(a.shape[0], b.shape[0], len(ids) - 1) + kl, same, la, lb = [], 0, [], [] + for r in range(0, n, 64): + pa, pb = lsm(a[r:min(n, r + 64)]), lsm(b[r:min(n, r + 64)]) + kl += list((np.exp(pa) * (pa - pb)).sum(axis=1)) + same += int((pa.argmax(1) == pb.argmax(1)).sum()) + nxt = np.array(ids[r + 1:min(n, r + 64) + 1]) + la += list(pa[np.arange(len(nxt)), nxt]) + lb += list(pb[np.arange(len(nxt)), nxt]) + kl = np.array(kl) + allkl += list(kl) + print(f"{name:<6}{n:>7}{100 * same / n:>10.1f}%{kl.mean():>9.3f}{np.median(kl):>11.4f}{np.percentile(kl, 99):>8.2f}" + f"{np.exp(-np.mean(la)):>10.3f}{np.exp(-np.mean(lb)):>9.3f}") + allkl = np.array(allkl) + print(f"all {len(allkl)} tokens: mean KL {allkl.mean():.3f}, max {allkl.max():.2f}, p99 {np.percentile(allkl, 99):.2f}") + + +if __name__ == "__main__": + {"run": run, "compare": compare}[sys.argv[1]]() diff --git a/engine/strata/bench/results/2026-09-27-esp/esp_serve.py b/engine/strata/bench/results/2026-09-27-esp/esp_serve.py new file mode 100644 index 00000000..4ec20059 --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-esp/esp_serve.py @@ -0,0 +1,129 @@ +"""Serve-mode checks of the experimental-speed-projection vector (exact mode: fixed experts, no PCIe share). + + python esp_serve.py run ARM # ARM = stock | vec; writes esp-serve/.json + python esp_serve.py compare + +Per arm: the first greedy token after many prefixes of three texts (short ones go through the verify windows, long +ones through the batched prompt path; the conversation cache reuses the earlier prefix), and three 256-token greedy +generations. The vec arm runs everything with cvec=1, then cvec=0, then cvec=1 again. +""" +import json +import os +import sys +import threading + +S = os.path.dirname(os.path.abspath(__file__)) +E = r"C:\Users\AI-Server\Desktop\Strata\Public\Engine" +sys.path.insert(0, E) +from serve.server import StrataEngine # noqa: E402 + +EXE = E + r"\build-dev\strata.exe" +VEC = r"C:\Users\AI-Server\Desktop\Strata\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +TEXTS = {"code": S + r"\p512.ids", "doc": S + r"\4k-02-long-doc-1k.ids", "chat": S + r"\4k-04-chat-1k.ids"} +OUT = S + r"\esp-serve" +VEC_ARGS = ["--control-vector-scaled", VEC + ":1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] + + +def ids_of(name): + return [int(x) for x in open(TEXTS[name]).read().replace(",", " ").split()] + + +def engine(extra): + c = json.load(open(S + r"\cfg-rel.json")) + a = list(c["args"]) + a[a.index("--expert-cache") + 1] = "4000" + env = dict(os.environ) + env["PATH"] = os.pathsep.join(c["lib_dirs"]) + os.pathsep + env["PATH"] + return StrataEngine(EXE, a + ["--pcie-frac", "0", "--adapt-swaps", "0"] + extra, cwd=c["cwd"], + log=OUT + r"\engine.log", env=env) + + +def gen(eng, ids, n, sampling): + toks = [t for t in eng.generate(ids, n, sampling, threading.Event()) if t is not None] + return toks, dict(eng.last) + + +def suite(eng, sampling): + out = {"first": {}, "long": {}} + for name in TEXTS: + ids = ids_of(name) + # short prefixes growing by 4 (each continues the live session through the verify windows), then long ones + # SHRINKING (no cached prefix, so each is read from 0 by the batched prompt path) + lens = list(range(32, 72, 4)) + list(range(min(len(ids) - 1, 700), 95, -48)) + out["first"][name] = {L: gen(eng, ids[:L], 1, sampling)[0][0] for L in lens} + for name in TEXTS: + toks, last = gen(eng, ids_of(name)[:300], 256, sampling) + out["long"][name] = {"tokens": toks, "last": last} + return out + + +def run(arm): + os.makedirs(OUT, exist_ok=True) + eng = engine(VEC_ARGS if arm == "vec" else []) + res = {"info": eng.info} + if arm == "stock": + res["stock"] = suite(eng, {}) + else: + res["on"] = suite(eng, {"experimental_speed_projection": True}) + res["off"] = suite(eng, {"experimental_speed_projection": False}) + res["on2"] = suite(eng, {"experimental_speed_projection": True}) + eng.close() + json.dump(res, open(f"{OUT}\\{arm}.json", "w")) + print(arm, "done", eng.info, flush=True) + + +def compare(): + import numpy as np + sys.path.insert(0, S) + from esp_kl import load, OUT as KL + st = json.load(open(OUT + r"\stock.json")) + ve = json.load(open(OUT + r"\vec.json")) + print("engine INFO (vec):", ve["info"]) + + def eq_first(a, b): + tot = same = 0 + for name in a: + for L, t in a[name].items(): + tot += 1 + same += int(b[name][L] == t) + return same, tot + + def eq_long(a, b): + return all(a[n]["tokens"] == b[n]["tokens"] for n in a), \ + [(n, next((i for i, (x, y) in enumerate(zip(a[n]["tokens"], b[n]["tokens"])) if x != y), None)) for n in a] + + print("1. vector loaded, switched off == no vector") + print(" first tokens: %d / %d identical" % eq_first(st["stock"]["first"], ve["off"]["first"])) + print(" 256-token generations identical:", *eq_long(st["stock"]["long"], ve["off"]["long"])) + print("2. repeatable: on, off, on again") + print(" first tokens: %d / %d identical" % eq_first(ve["on"]["first"], ve["on2"]["first"])) + print(" 256-token generations identical:", *eq_long(ve["on"]["long"], ve["on2"]["long"])) + print("3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L)") + for arm, first in (("stock", st["stock"]["first"]), ("on", ve["on"]["first"])): + for ref in ("stock", "proj"): + agree = tot = 0 + for name in first: + d = load(f"{KL}\\{name}-{ref}.bin") + for L, t in first[name].items(): + L = int(L) + if L - 1 < d.shape[0]: + tot += 1 + agree += int(int(np.argmax(d[L - 1])) == t) + print(f" served {arm:<5} vs per-token {ref:<5}: {agree} / {tot}") + print("4. how different the text is: 256-token generations, on vs stock, first difference") + print(" ", eq_long(st["stock"]["long"], ve["on"]["long"])[1]) + print("5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup)") + for label, r in (("stock", st["stock"]), ("vec off", ve["off"]), ("vec on", ve["on"]), ("vec on 2", ve["on2"])): + g = sum(v["last"]["generated"] for v in r["long"].values()) + ms = sum(v["last"]["decode_ms"] for v in r["long"].values()) + acc = sum(v["last"].get("drafts_accepted", 0) for v in r["long"].values()) + off = sum(v["last"].get("drafts_offered", 0) for v in r["long"].values()) + print(f" {label:<9} {g / ms * 1000:6.1f} tok/s drafts accepted {acc}/{off}") + + +if __name__ == "__main__": + if sys.argv[1] == "run": + run(sys.argv[2]) + else: + compare() diff --git a/engine/strata/bench/results/2026-09-27-esp/serve-checks.txt b/engine/strata/bench/results/2026-09-27-esp/serve-checks.txt new file mode 100644 index 00000000..23219a39 --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-esp/serve-checks.txt @@ -0,0 +1,20 @@ +1. vector loaded, switched off == no vector + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +2. repeatable: on, off, on again + first tokens: 65 / 65 identical + 256-token generations identical: True [('code', None), ('doc', None), ('chat', None)] +3. the prompt paths against the per-token path's teacher-forced argmax (row L-1 predicts token L) + served stock vs per-token stock: 64 / 65 + served stock vs per-token proj : 57 / 65 + served on vs per-token stock: 57 / 65 + served on vs per-token proj : 62 / 65 +4. how different the text is: 256-token generations, on vs stock, first difference + [('code', 11), ('doc', 6), ('chat', 3)] +5. decode speed (exact mode: fixed experts, no PCIe share - not the normal setup) + stock 66.4 tok/s drafts accepted 256/309 + vec off 65.7 tok/s drafts accepted 251/318 + vec on 76.7 tok/s drafts accepted 366/425 + vec on 2 81.2 tok/s drafts accepted 366/423 + +[exited with code 0] diff --git a/engine/strata/bench/results/2026-09-27-esp/teacher-forced.txt b/engine/strata/bench/results/2026-09-27-esp/teacher-forced.txt new file mode 100644 index 00000000..5beb4b81 --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-esp/teacher-forced.txt @@ -0,0 +1,6 @@ +text tokens same top-1 mean KL median KL p99 KL ppl stock ppl proj +code 511 92.8% 0.098 0.0031 1.69 2.594 2.982 +doc 1023 89.8% 0.058 0.0271 0.84 30.299 30.984 +chat 1023 89.6% 0.050 0.0265 0.33 18.409 18.485 +all 2557 tokens: mean KL 0.063, max 4.10, p99 1.00 + diff --git a/engine/strata/bench/results/2026-09-27-kv-q4/README.md b/engine/strata/bench/results/2026-09-27-kv-q4/README.md new file mode 100644 index 00000000..7cfa891f --- /dev/null +++ b/engine/strata/bench/results/2026-09-27-kv-q4/README.md @@ -0,0 +1,60 @@ +# 2026-09-27: Q4_0 KV with Hadamard rotation (PR #21, `--kv q4_0`) + +PR #21 (code-martin) adds a 4-bit K/V format: an orthonormal 256-point Walsh-Hadamard rotation of K, V and Q, then +ggml `q4_0` blocks (576 B per cell and layer, vs 1,056 B in int8). + +## Integration fixes made on merge + +- **Q4 + KV streaming (`--kv-resident`).** The PR had no host copy for Q4 and skipped the staging, so with streaming + on, the prompt path wrote K/V through the residency map's -1 entries (out-of-bounds writes). + - Q4 is now a third format in `kv_stream`: host copy, block residency, prompt-path staging, MTP ring and STATE_HASH. + - `kv_stream_parity` checks it bitwise, streamed vs resident, with ring restore. +- **Duplicate attention.** The per-token decode path ran attention twice, the first time before the selection's + blocks were made resident; it now runs once. +- **Tie-break.** The group maximum's tie-break is now deterministic across lanes: equal |x| with opposite signs + could give one block two scales. +- **Unrelated changes dropped:** duplicate path fixes (already in 0.1.7), personal `.gitignore` entries, and a + re-encoded CMakeLists. + +`kv_q4_parity` (the PR's test) and all 70 ctest tests pass. + +## Quality (teacher-forced, `tools/kv_precision_compare.py`) + +Same text, same fixed expert set (Q2_0, 3,000 slots, `--adapt-swaps 0`); only `--kv` differs. fp16 is the reference. + +| Text | KV | Same top-1 as fp16 | Mean KL | Perplexity | vs fp16 (nats/token) | +|---|---|---:|---:|---:|---:| +| code agent (512) | int8 | 98.4% | 0.014 | 2.649 | -0.011 +- 0.006 | +| | q4_0 | 95.7% | 0.030 | 2.598 | -0.031 +- 0.014 | +| document (1,024) | int8 | 95.6% | 0.009 | 30.18 | +0.012 +- 0.005 | +| | q4_0 | 91.3% | 0.039 | 32.26 | **+0.078 +- 0.011** | +| chat (1,024) | int8 | 95.5% | 0.009 | 18.24 | -0.003 +- 0.005 | +| | q4_0 | 90.7% | 0.028 | 18.52 | +0.012 +- 0.008 | +| document, 8K (every 8th position) | int8 | 92.3% | 0.114 | 7.63 | -0.013 +- 0.020 | +| | q4_0 | 88.0% | 0.297 | 8.65 | **+0.112 +- 0.037** | + +- **int8 is indistinguishable from fp16** (within about 2 standard errors everywhere). +- **q4_0 costs measurable precision, and more as the context grows:** + - document perplexity +8% at 1K and +12% at 8K; + - the KL from fp16 is 2.6-4.2x int8's; + - code and chat are near-neutral. +- **Needles with `--kv q4_0 --kv-resident 32768`: 5/5** (1K, 32K, 128K at 10% and 90% depth, 262K; + `needles-q4.*`). Retrieval holds. + +## Speed and memory (Q2_0, 128K, matrix bench, `--kv-resident 32768`) + +| KV | Expert slots | Decode tok/s | Tokens/round | Rounds/s | K/V in RAM | +|---|---:|---:|---:|---:|---:| +| int8 (`kv-stream/matrix-stream`) | 4,044 | 62.4 | 2.52 | 24.8 | 1.52 GiB | +| q4_0 (`matrix-q4`) | 4,190 | 67.4 | 2.62 | 25.7 (+3.7%) | 0.83 GiB | + +Without streaming (contexts up to 64K, or too little RAM for it) q4_0 halves the whole KV cache in VRAM instead. + +## Decision + +`--kv q4_0` is a user option: +- `START-HERE.bat --kv q4_0`, or the question setup asks above 8K context; +- or `--kv q4_0` in a `strata-*.json`. + +int8 stays the default: every published quality number was measured with it, and q4_0's precision cost is real, +though it passes the needles. diff --git a/engine/strata/bench/results/2026-09-28-coder/README.md b/engine/strata/bench/results/2026-09-28-coder/README.md new file mode 100644 index 00000000..4afc192c --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-coder/README.md @@ -0,0 +1,44 @@ +# The GSQ-RCO Coder (256 of 512 experts) on Strata + +RTX 5070 12 GB, Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. Engine 0.1.15 + PR #54 (the expert count from the model +file), the settings setup writes (`--prefill auto`, 8-bit KV above 4K, KV streaming from 64K, MTP, greedy, 256 tokens), +`data/expert-profile-coder.bin`, the same code-agent prompts as `2026-09-28-speed-0114`. + +| | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Prompt, tokens/s | 599 | 1,152 | 1,298 | 1,350 | 1,266 | 1,034 | +| Output, tokens/s | 53.3 | 50.6 | 53.3 | 50.8 | 44.0 | 42.8 | +| Draft acceptance | 0.720 | 0.707 | 0.785 | 0.696 | 0.619 | 0.684 | +| Experts in VRAM | 2,570 | 2,615 | 2,418 | 2,382 | 2,326 | 2,208 | + +Every run in [`matrix.json`](matrix.json). The 128K and 262K answers were read: coherent (they list and discuss the +files of the prompt). + +## Why it is fast + +The kept experts are stored like IQ3_S's (IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate and up, IQ4_NL / Q2_0 down; "IQ1_M" is +the release's name for 1.89 bits per *original* parameter), so a token costs about what IQ3_S costs where the expert is +on the CPU. But there are half as many experts: the 23 GB of them pin completely (`cudaHostRegister` of the whole +arena), a 12 GB card holds ~20% of them instead of ~10%, and the prompt path streams half as many. + +## The expert profile + +`data/expert-profile-coder.bin` (48 x 256, all 12,288 pairs ranked): the shipped 48 x 512 ranking, each pair mapped to +its kept expert's new index through section 2 of the release's `tensor-allocation/*.rco-allocation.txt` (the kept +experts in their original order; gate, up and down agree on which were kept), pruned pairs dropped. 5,492 of the +shipped top 8,000 survive (as PR #54 found). With 2,537 slots on the 12 GB card, 72% of the expert reads of a 4K code +prompt hit the GPU - a wrong index mapping would give about the slot share, 21%. + +## Images + +The Coder ships the original's vision encoder (the same file). With `--vision` on the GPU it described a Strata +Monitor screenshot correctly, windows, labels and the numbers of the dashboard and the requests table (1,079 prompt +tokens with the image, 2,012 generated at ~50 tokens/s). + +## The experimental speed projection + +The vector was made from the full model's activations; the Coder has the same residual stream. On the Coder it loads +(41 layers steered), costs no measurable speed (47.7-55.7 tokens/s with it on or off), and both settings write correct +answers to three coding prompts. What it is for - fewer refusals - was not measured. (Two runs of the same prompt with +it off also differ after ~130-200 characters in serve mode, so this check cannot show how far it moves ordinary text; +the teacher-forced method of `2026-09-27-esp` needs the token-by-token prompt path, which native packs do not run.) diff --git a/engine/strata/bench/results/2026-09-28-coder/matrix.json b/engine/strata/bench/results/2026-09-28-coder/matrix.json new file mode 100644 index 00000000..2614ebc6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-coder/matrix.json @@ -0,0 +1,86 @@ +[ + { + "model": "CODER", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 18.0, + "prefill_tok_s": 599.05, + "ttft_s": 2.54, + "decode_tok_s": 53.33, + "decoded": 256, + "spec_accept": 0.72, + "tokens_per_round": 2.86, + "vram_slots": 2570 + }, + { + "model": "CODER", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 19.6, + "prefill_tok_s": 1152.17, + "ttft_s": 3.94, + "decode_tok_s": 50.6, + "decoded": 256, + "spec_accept": 0.707, + "tokens_per_round": 2.88, + "vram_slots": 2615 + }, + { + "model": "CODER", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 40.7, + "prefill_tok_s": 1297.8, + "ttft_s": 25.17, + "decode_tok_s": 53.34, + "decoded": 256, + "spec_accept": 0.785, + "tokens_per_round": 3.02, + "vram_slots": 2418 + }, + { + "model": "CODER", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 75.5, + "prefill_tok_s": 1350.09, + "ttft_s": 49.01, + "decode_tok_s": 50.84, + "decoded": 256, + "spec_accept": 0.696, + "tokens_per_round": 2.61, + "vram_slots": 2382 + }, + { + "model": "CODER", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 121.5, + "prefill_tok_s": 1266.31, + "ttft_s": 102.95, + "decode_tok_s": 44.03, + "decoded": 256, + "spec_accept": 0.619, + "tokens_per_round": 2.33, + "vram_slots": 2326 + }, + { + "model": "CODER", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 280.7, + "prefill_tok_s": 1033.91, + "ttft_s": 252.92, + "decode_tok_s": 42.8, + "decoded": 256, + "spec_accept": 0.684, + "tokens_per_round": 2.6, + "vram_slots": 2208 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-prefill-speed/README.md b/engine/strata/bench/results/2026-09-28-prefill-speed/README.md new file mode 100644 index 00000000..91d42787 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-prefill-speed/README.md @@ -0,0 +1,47 @@ +# Faster prompt reading (engine 0.1.13) + +RTX 5070 12 GB, Ryzen 5 7600, 64 GB DDR5. 32K-token prompt (`bench/prompts/long/32k-01-code-agent.ids`), one-shot +engine, `--expert-cache auto`, greedy. Numbers are prompt tokens/s. + +## What changed, step by step + +| Step | What | Result | +|---|---|---| +| Buffers | The attention half and the MoE half of a layer share one scratch region (~260 KB less per prompt token) | bit-identical; chunk 4096 borrows 1.78 GiB instead of 2.84 | +| PLE rows | The next chunk's PLE rows are read from the model file on a thread while the GPU works | bit-identical; 762 -> 790 at chunk 4096 | +| Chunk size | `--prefill auto`: the largest of 8192 / 6144 / 4096 / ... whose buffers fit in the cache slots it may borrow; a request borrows only what its own prompt needs | Q2_0: 4096 791, 6144 878, 8192 973 | +| Host copies | Experts the arena could not pin are copied to pinned buffers by helper threads instead of the launching thread | bit-identical; IQ3_S at 4096: 551 -> 652 | +| PLE block | Computed for the whole chunk (two GEMMs) instead of token by token | Q2_0 981 -> 1053, IQ3_S 831 -> 940 | +| Experts | llama.cpp's MMQ kernels (weights stay quantized, int8 tensor cores) instead of dequantize-to-FP16 + cuBLAS | Q2_0 1052 -> 1130, IQ3_S (8192) 932 -> 1014 | +| Streaming | At chunks of 2048+ every non-resident expert streams in a fixed order through a ring, so the next layer's arrive while the current layer's attention runs | bit-identical; Q2_0 1130 -> 1290, IQ3_S -> 1208 | + +Tried and dropped: cuBLAS grouped GEMMs for the experts (faster in isolation, slower inside the engine: 770 vs 790). + +## Before and after + +| | engine 0.1.12 (`--prefill 2048`) | engine 0.1.13 (`--prefill auto`) | +|---|---:|---:| +| Q2_0, 32K prompt | 572 | 1,290 | +| IQ3_S, 32K prompt | 383 | 1,208 | +| Server, Q2_0, 128K context, 999-token prompt | 353 | 438 | +| Server, 6,927-token prompt | 529 | 1,077 | +| Server, 28,584-token prompt | 584 | 1,249 | + +Output speed is unchanged (the decode path is the same). Short prompts (a few hundred tokens) go through the verify +windows as before. + +## Quality + +- "Bit-identical" steps were checked with the GDN state hash after the 32K prompt (all 36 recurrent layers). +- The steps that change rounding (the batched PLE block, MMQ's 8-bit activations) were compared teacher-forced: the + 32K prompt is read by the prompt path up to its last 256 tokens, those go through the token path with their logits + dumped. At 32K every rounding change moves the predictions about this much - even a different chunk size of the + unchanged engine - so that is the yardstick: + +| Against the 8192-chunk FP16 path | Same top-1 | Mean KL | Perplexity (reference 9.21) | +|---|---:|---:|---:| +| Chunk 6144, same code (the yardstick) | 89.8% | 0.33 | 9.18 | +| MMQ experts | 85.9% | 0.38 | 8.63 | + +- Needles (the answer hidden at a given depth): 5 of 5 at 1K, 32K, 128K (two depths) and 262K, Q2_0, KV streaming. +- A rerun of the same configuration is bit-identical. diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/README.md b/engine/strata/bench/results/2026-09-28-rope-scaling/README.md new file mode 100644 index 00000000..1624f43e --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/README.md @@ -0,0 +1,49 @@ +# Rope scaling: needle recall past the trained 262K + +The feature (PR #84, experimental): `--rope-scaling none|linear|yarn` extends the context past the model's +trained 262,144 positions by rescaling the rotary angles - llama.cpp's types, ggml's `rope_yarn` +arithmetic, one process config applied at the cos/sin table (default path) and as kernel constants +(`--native-rope`, the native indexer, prefill). The three tables here are the first end-to-end check +that a scaled run actually recalls past the trained end. + +**Hardware:** RTX 4070 Ti SUPER 16 GB, Ryzen 9 5900X (no AVX-512 - the IQ3_XXS native pack runs its +expert kernels on AVX-2), 125 GB RAM, Linux. **Engine:** this branch built from source (the log records +`rope scaling ... --max-context ... against a trained context of 262144` at startup). The runs below +were taken on the rope tree built over the 0.1.17-era base; the branch then rebased onto main (engine +0.1.20) - the drift touches none of the rope files - and the rebase was re-validated: `rope_parity` +green, a 64-token greedy run token-identical to the plain 0.1.20 build, and the yarn 262k probe +repeated green (see the last table row). Baseline arm A also re-checked the default is the stock +model: a 64-token greedy run produces the same token ids as the ready-made 0.1.17 engine, and +`rope_parity` holds the `none` table bit-identical to the pre-scaling builder. +**Method:** `tools/needle_bench.py` against a running server (launch recipes in `config-*.json`), +`temperature 0`, thinking off, depth 50%, one probe per length. + +| Arm | Scaling | Context | Probe | Prompt tokens | Result | Probe time | +| --- | --- | --- | --- | --- | --- | --- | +| A | none | 262,144 | 1k @ 50% | 1,442 | FOUND | 4 s | +| A | none | 262,144 | 32k @ 50% | 31,763 | FOUND | 27 s | +| A | none | 262,144 | 128k @ 50% | 128,328 | FOUND | 86 s | +| B | linear, factor 2 | 560,000 | 262k @ 50% | 274,222 | FOUND | 232 s | +| B | linear, factor 2 | 560,000 | 512k @ 50% | 527,051 | FOUND | 619 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% | 274,215 | FOUND | 236 s | +| C | yarn, factor 2 | 560,000 | 512k @ 50% | 526,988 | FOUND | 615 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% (the rebase re-check) | 273,708 | FOUND | 235 s | + +All 8 of 8 probes found the needle; JSON per arm: `needle-A-none.json`, `needle-B-linear2.json`, +`needle-B-linear2-512k.json`, `needle-C-yarn2.json` (+ the rebase re-check in +`needle-C-yarn2-rebased.json`); server and engine logs alongside. + +What this establishes, and what it does not: + +- **Past the trained end the model still reads.** 512k probes are 2.01x the trained 262,144 - position + interpolation (B) and YaRN (C) both hold a mid-context lookup there. +- **Scaled runs within the trained range are a slightly different model.** `yarn`'s mscale applies at + every position (a 64-token greedy prompt diverges from the stock run after ~19 tokens); arm A is the + stock model, arms B/C are not, by design. +- **One depth, one needle, one machine.** A single probe per (length, arm) at depth 50% says "recall + works there", not "no degradation anywhere" - a full depth sweep and a longer-length ladder (768K, + 1M) on the bench machine (64 GB RAM there vs 125 GB here, so 262K IQ3_XXS fits either way) is the + natural follow-up. 512K prompts prefill at ~850-950 tokens/s on this card; the probe time is almost + entirely prefill. +- **The `560,000` context** in arms B/C is headroom for the needle harness's tokenizer overshoot + (a "512k" probe tokenizes to ~527k); 524,288 exactly would refuse the probe. diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json b/engine/strata/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json new file mode 100644 index 00000000..528fc9f6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json @@ -0,0 +1,38 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "262144" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-A-none-262144.log" +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/config-B-linear2.json b/engine/strata/bench/results/2026-09-28-rope-scaling/config-B-linear2.json new file mode 100644 index 00000000..30b31d7d --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/config-B-linear2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "linear", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-B-linear2-524288.log" +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json b/engine/strata/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json new file mode 100644 index 00000000..6172a63a --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "yarn", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-C-yarn2-524288.log" +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json b/engine/strata/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json new file mode 100644 index 00000000..526b7514 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json @@ -0,0 +1,121 @@ +[ + { + "length": "128k", + "round": 0, + "kind": "decode", + "prompt_tok": 128401, + "read": 52, + "gen": 357, + "read_tok_s": 79.2, + "gen_tok_s": 56.3, + "drafts_ok": 182, + "drafts_all": 305, + "seg_blocks": 3284340, + "seg_mib": 370.0, + "seg_misses": 91744, + "seg_hit_pct": 97.207, + "kib_per_token": 1061.29 + }, + { + "length": "128k", + "round": 1, + "kind": "read", + "prompt_tok": 128357, + "read": 128357, + "gen": 24, + "read_tok_s": 1389.2, + "gen_tok_s": 41.7, + "drafts_ok": 11, + "drafts_all": 23, + "seg_blocks": -3253560, + "seg_mib": -391.7, + "seg_misses": -97147, + "seg_hit_pct": 97.014, + "kib_per_token": -3.12 + }, + { + "length": "128k", + "round": 1, + "kind": "decode", + "prompt_tok": 128402, + "read": 52, + "gen": 388, + "read_tok_s": 76.5, + "gen_tok_s": 54.6, + "drafts_ok": 195, + "drafts_all": 363, + "seg_blocks": 3752616, + "seg_mib": 463.5, + "seg_misses": 114911, + "seg_hit_pct": 96.938, + "kib_per_token": 1223.26 + }, + { + "length": "512k", + "round": 0, + "kind": "read", + "prompt_tok": 522983, + "read": 522983, + "gen": 24, + "read_tok_s": 868.4, + "gen_tok_s": 42.4, + "drafts_ok": 13, + "drafts_all": 16, + "seg_blocks": -3808056, + "seg_mib": -387.8, + "seg_misses": -96113, + "seg_hit_pct": 97.476, + "kib_per_token": -0.76 + }, + { + "length": "512k", + "round": 0, + "kind": "decode", + "prompt_tok": 523028, + "read": 52, + "gen": 402, + "read_tok_s": 63.3, + "gen_tok_s": 48.4, + "drafts_ok": 221, + "drafts_all": 348, + "seg_blocks": 3580056, + "seg_mib": 920.4, + "seg_misses": 228658, + "seg_hit_pct": 93.613, + "kib_per_token": 2344.5 + }, + { + "length": "512k", + "round": 1, + "kind": "read", + "prompt_tok": 522984, + "read": 522984, + "gen": 24, + "read_tok_s": 857.1, + "gen_tok_s": 35.5, + "drafts_ok": 9, + "drafts_all": 18, + "seg_blocks": -3555408, + "seg_mib": -905.8, + "seg_misses": -225016, + "seg_hit_pct": 93.671, + "kib_per_token": -1.77 + }, + { + "length": "512k", + "round": 1, + "kind": "decode", + "prompt_tok": 523029, + "read": 52, + "gen": 402, + "read_tok_s": 61.3, + "gen_tok_s": 42.8, + "drafts_ok": 192, + "drafts_all": 388, + "seg_blocks": 4005216, + "seg_mib": 1079.9, + "seg_misses": 268221, + "seg_hit_pct": 93.303, + "kib_per_token": 2750.79 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/needle-A-none.json b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-A-none.json new file mode 100644 index 00000000..099bd36b --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-A-none.json @@ -0,0 +1,29 @@ +[ + { + "length": "1k", + "depth": 50, + "prompt_tokens": 1442, + "seconds": 3.7, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 31763, + "seconds": 27.5, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 128328, + "seconds": 86.1, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json new file mode 100644 index 00000000..e93f21d4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json @@ -0,0 +1,11 @@ +[ + { + "length": "512k", + "depth": 50, + "prompt_tokens": 527051, + "seconds": 619.0, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json new file mode 100644 index 00000000..7a987877 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json @@ -0,0 +1,16 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274222, + "seconds": 232.2, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "error": "HTTP Error 400: Bad Request" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json new file mode 100644 index 00000000..659f51a3 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json @@ -0,0 +1,11 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 273708, + "seconds": 234.8, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json new file mode 100644 index 00000000..2dfa146d --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json @@ -0,0 +1,20 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274215, + "seconds": 235.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "prompt_tokens": 526988, + "seconds": 615.0, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-speed-0114/README.md b/engine/strata/bench/results/2026-09-28-speed-0114/README.md new file mode 100644 index 00000000..f6c1aba8 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-speed-0114/README.md @@ -0,0 +1,32 @@ +# Speed with engine 0.1.14 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.14 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens. One +code-agent prompt per length (`bench/prompts/*/…-code-agent.ids`, the same prompts as `2026-09-24-final`). + +The tables: [`matrix.md`](matrix.md) (prompt and output speed, draft acceptance, experts in VRAM); every run in +[`matrix.json`](matrix.json). + +- **IQ2_XS** was measured with Swift 1.5's IQ2_XS (the original's file was not on the machine; the two run at the same + speed: 4K 465 vs 467 prompt tokens/s in `2026-09-24`). +- **IQ3_S at 128K** comes from a first pass during which a large download was running (the clean rerun of that row + was stopped when Windows ran short of memory); the other rows are from runs on an otherwise idle machine. +- **IQ3_XXS and IQ3_S at 262K** are not measured: with 43 / 50 GB of experts, a 260K context exceeds 64 GB of RAM. + +## Against 0.1.12 + +Prompts are 1.2x (1K) to 2.4x (32K-128K) faster: the 0.1.13 prompt path (chunks of up to 8,192 tokens, MMQ experts, +streamed expert copies; see `2026-09-28-prefill-speed`). + +Output speed moves with the text: speculative decoding is faster when more drafts are accepted, and the new prompt +path's rounding changes the answer, so the same prompt can land a few percent either way (Q2_0 32K: acceptance 0.865 +then, 0.709 now). The engine itself is not slower: on the 4K prompt, run back to back on the same machine state, +0.1.14 writes 88.5 tokens/s and 0.1.12 85.7 (3 runs each, same free VRAM). + +## Found on the way + +IQ3_XXS at 64K and 128K ended with `out of memory: cudaFuncSetAttribute` in the MMQ launch: CUDA loads a kernel's code +when it is first used, and mid-prompt there was no VRAM left for it. Loading every kernel at start +(`CUDA_MODULE_LOADING=EAGER`, which the engine now sets itself) fixes it for ~30 MB of VRAM; the IQ3_XXS 64K/128K rows +were measured with that fix. diff --git a/engine/strata/bench/results/2026-09-28-speed-0114/matrix.json b/engine/strata/bench/results/2026-09-28-speed-0114/matrix.json new file mode 100644 index 00000000..ca9501e0 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-speed-0114/matrix.json @@ -0,0 +1,322 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 41.0, + "prefill_tok_s": 494.43, + "ttft_s": 3.55, + "decode_tok_s": 84.26, + "decoded": 256, + "spec_accept": 0.709, + "tokens_per_round": 2.72, + "vram_slots": 4176 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.2, + "prefill_tok_s": 1006.63, + "ttft_s": 5.05, + "decode_tok_s": 90.26, + "decoded": 256, + "spec_accept": 0.846, + "tokens_per_round": 3.23, + "vram_slots": 4123 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 63.1, + "prefill_tok_s": 1307.6, + "ttft_s": 25.63, + "decode_tok_s": 73.61, + "decoded": 256, + "spec_accept": 0.709, + "tokens_per_round": 2.68, + "vram_slots": 3833 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 89.0, + "prefill_tok_s": 1293.5, + "ttft_s": 51.12, + "decode_tok_s": 69.02, + "decoded": 256, + "spec_accept": 0.679, + "tokens_per_round": 2.62, + "vram_slots": 3780 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 147.4, + "prefill_tok_s": 1208.46, + "ttft_s": 107.81, + "decode_tok_s": 67.21, + "decoded": 256, + "spec_accept": 0.691, + "tokens_per_round": 2.64, + "vram_slots": 3697 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 309.8, + "prefill_tok_s": 966.84, + "ttft_s": 270.35, + "decode_tok_s": 60.3, + "decoded": 256, + "spec_accept": 0.623, + "tokens_per_round": 2.43, + "vram_slots": 3525 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.4, + "prefill_tok_s": 461.28, + "ttft_s": 2.28, + "decode_tok_s": 74.38, + "decoded": 256, + "spec_accept": 0.772, + "tokens_per_round": 2.84, + "vram_slots": 4386, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.8, + "prefill_tok_s": 810.71, + "ttft_s": 4.48, + "decode_tok_s": 73.84, + "decoded": 256, + "spec_accept": 0.79, + "tokens_per_round": 3.24, + "vram_slots": 4336, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 65.0, + "prefill_tok_s": 1237.98, + "ttft_s": 25.59, + "decode_tok_s": 71.49, + "decoded": 256, + "spec_accept": 0.856, + "tokens_per_round": 3.28, + "vram_slots": 4057, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 97.1, + "prefill_tok_s": 1135.63, + "ttft_s": 56.59, + "decode_tok_s": 64.29, + "decoded": 256, + "spec_accept": 0.707, + "tokens_per_round": 2.76, + "vram_slots": 4005, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 158.0, + "prefill_tok_s": 1070.61, + "ttft_s": 120.1, + "decode_tok_s": 59.76, + "decoded": 256, + "spec_accept": 0.726, + "tokens_per_round": 2.69, + "vram_slots": 3923, + "note": "first pass" + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 332.4, + "prefill_tok_s": 886.2, + "ttft_s": 293.43, + "decode_tok_s": 52.83, + "decoded": 256, + "spec_accept": 0.628, + "tokens_per_round": 2.53, + "vram_slots": 3565, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 44.1, + "prefill_tok_s": 414.55, + "ttft_s": 2.54, + "decode_tok_s": 60.26, + "decoded": 256, + "spec_accept": 0.864, + "tokens_per_round": 3.52, + "vram_slots": 3304, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 45.8, + "prefill_tok_s": 769.57, + "ttft_s": 4.73, + "decode_tok_s": 62.07, + "decoded": 256, + "spec_accept": 0.855, + "tokens_per_round": 3.24, + "vram_slots": 3263, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 69.7, + "prefill_tok_s": 1107.75, + "ttft_s": 28.61, + "decode_tok_s": 51.4, + "decoded": 256, + "spec_accept": 0.678, + "tokens_per_round": 2.6, + "vram_slots": 3031, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 104.9, + "prefill_tok_s": 1065.31, + "ttft_s": 61.77, + "decode_tok_s": 49.95, + "decoded": 256, + "spec_accept": 0.741, + "tokens_per_round": 2.94, + "vram_slots": 2965, + "note": "first pass" + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 172.1, + "prefill_tok_s": 1015.11, + "ttft_s": 128.12, + "decode_tok_s": 45.78, + "decoded": 256, + "spec_accept": 0.665, + "tokens_per_round": 2.35, + "vram_slots": 2901, + "note": "first pass" + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 56.2, + "prefill_tok_s": 396.13, + "ttft_s": 4.14, + "decode_tok_s": 51.52, + "decoded": 256, + "spec_accept": 0.826, + "tokens_per_round": 3.12, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 57.5, + "prefill_tok_s": 736.9, + "ttft_s": 6.35, + "decode_tok_s": 51.6, + "decoded": 256, + "spec_accept": 0.747, + "tokens_per_round": 2.89, + "vram_slots": 2580 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 82.5, + "prefill_tok_s": 1069.83, + "ttft_s": 31.33, + "decode_tok_s": 48.19, + "decoded": 256, + "spec_accept": 0.772, + "tokens_per_round": 2.94, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 115.0, + "prefill_tok_s": 1069.8, + "ttft_s": 61.47, + "decode_tok_s": 48.75, + "decoded": 256, + "spec_accept": 0.786, + "tokens_per_round": 2.9, + "vram_slots": 2347 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 191.8, + "prefill_tok_s": 931.09, + "ttft_s": 138.11, + "decode_tok_s": 40.48, + "decoded": 256, + "spec_accept": 0.661, + "tokens_per_round": 2.71, + "vram_slots": 2310, + "note": "first pass (a download was running)" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-28-speed-0114/matrix.md b/engine/strata/bench/results/2026-09-28-speed-0114/matrix.md new file mode 100644 index 00000000..5a92ac63 --- /dev/null +++ b/engine/strata/bench/results/2026-09-28-speed-0114/matrix.md @@ -0,0 +1,35 @@ +### Prompt processing (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 494 | 1,007 | 1,308 | 1,294 | 1,208 | 967 | +| IQ2_XS | 461 | 811 | 1,238 | 1,136 | 1,071 | 886 | +| IQ3_XXS | 415 | 770 | 1,108 | 1,065 | 1,015 | - | +| IQ3_S | 396 | 737 | 1,070 | 1,070 | 931 | - | + +### Output (tok/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 84.3 | 90.3 | 73.6 | 69.0 | 67.2 | 60.3 | +| IQ2_XS | 74.4 | 73.8 | 71.5 | 64.3 | 59.8 | 52.8 | +| IQ3_XXS | 60.3 | 62.1 | 51.4 | 50.0 | 45.8 | - | +| IQ3_S | 51.5 | 51.6 | 48.2 | 48.8 | 40.5 | - | + +### Draft acceptance + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 0.709 | 0.846 | 0.709 | 0.679 | 0.691 | 0.623 | +| IQ2_XS | 0.772 | 0.790 | 0.856 | 0.707 | 0.726 | 0.628 | +| IQ3_XXS | 0.864 | 0.855 | 0.678 | 0.741 | 0.665 | - | +| IQ3_S | 0.826 | 0.747 | 0.772 | 0.786 | 0.661 | - | + +### Experts in VRAM + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Q2_0 | 4,176 | 4,123 | 3,833 | 3,780 | 3,697 | 3,525 | +| IQ2_XS | 4,386 | 4,336 | 4,057 | 4,005 | 3,923 | 3,565 | +| IQ3_XXS | 3,304 | 3,263 | 3,031 | 2,965 | 2,901 | - | +| IQ3_S | 2,617 | 2,580 | 2,383 | 2,347 | 2,310 | - | diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/README.md b/engine/strata/bench/results/2026-09-29-layer-split-limits/README.md new file mode 100644 index 00000000..017c9d40 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/README.md @@ -0,0 +1,59 @@ +# Layer split: the features that were off across GPUs (2026-09-29) + +**Setup:** +- **Rig:** RIBPC. RTX 5080 16 GB (CUDA0) + RTX 3090 24 GB; RTX 2080 Ti 22 GB as a helper card. Ryzen 9 9950X3D, + 62 GB RAM, Windows 11. +- **Model:** the Coder (IQ1_M native pack). +- **Build:** branch `mg/limits`, sm_75 + sm_86 + sm_120. +- **Correctness runs:** `rib_norepeat.py`, with a fixed cache, no swaps, no PCIe share and no suffix drafts where two + runs are compared byte for byte. +- **Speed runs:** `rib_pp.py`. +- Raw results are in `data/`. + +## Correctness + +| Check | Result | +|---|---| +| One GPU, this branch vs the 0.1.21-equivalent run (fixed cache) | 10/10 byte-identical | +| Speed projection (control vector), one GPU vs the split on the same GPU (K=24) | 10/10 byte-identical | +| KV streaming (128K context, 32K resident), one GPU vs the split on the same GPU | 10/10 byte-identical | +| Images, one GPU vs the split on the same GPU (three questions about a test picture) | identical answers | +| Speed projection / KV streaming / plain, 5080 + 3090 (K=24): no-repeat under presence 100, the 144 sanity case | all pass, 0 repeats | +| The vector acts across GPUs: 5080 + 3090 with vs without the vector | 8 of 10 answers differ (as on one GPU: 7 of 10) | +| Images, 5080 + 3090 (K=24): "What color is the circle?" / "What number?" / describe | "Red" / "42" / "A red circle, the number 42, and a blue square are displayed on a white background" | +| Mid-prompt checkpoint (every 16,384 tokens): a 19.5K prompt, then another sharing its first 18,600 tokens | one GPU and 5080 + 3090: reused 16,384, answer right | +| 5080 + 3090 (K=30) + a 2080 Ti helper holding 3,000 experts | all pass | +| `--mmap-experts` with the Coder (a native pack) | a clear start-up error: it needs a canonical pack's `experts.bin` (with or without a split) | + +Across GPUs the text is not byte-identical to one GPU: experts that one card leaves to the CPU run on a GPU in the +split, and the two round differently. + +## Speed + +| Run | Prompt 16K / 28K / 60K tok/s | Decode story / code tok/s | Hits | +|---|---|---|---| +| KV streaming (128K), 5080 alone | 1,487 / 1,801 / 1,837 | 66.6 / 74.0 | 59-71% | +| KV streaming (128K), 5080 + 3090 auto | 1,685 / 1,957 / 1,968 | 75.8 / 97.0 | 96-97% | +| Speed projection, 5080 + 3090 auto | 1,813 / 2,053 / - | 77.0 / 103.6 | 96-97% | +| 5080 + 3090 (K=30), no helper | - | 62.5 / 85.2 | | +| 5080 + 3090 (K=30) + 2080 Ti helper | - | 43.0 / 63.7 | | + +**The helper card makes it slower,** as it did without a split (bench/results/2026-09-29-layer-split). Its per-layer +round trip costs more than the CPU pool needs for the few experts it would take over. It stays supported: the +helpers take the visible GPUs no stage runs on and hold only experts no stage's cache holds. But it isn't +recommended. + +## What changed + +- **Per-device tables:** the image-position (mrope) table and the control vector's tables are now kept per device; + every stage's rope and steering kernels read their own device's copy. `cvec_set_enabled` switches the vector on + every device. +- **KV streaming:** each stage's session streams its own KV host copy (pinned, portable). The split no longer forces + it off. +- **Mid-prompt checkpoints:** `Prefill::on_stage_chunk` lets each stage save its part of a checkpoint when it has + read the chunk. The last stage assembles the parts: the earlier ones are a chunk ahead by then. +- **Helpers (`--expert-cache-remote`) with a split:** they take the visible devices after the stages, skip every + pair a stage's cache holds, and preflight and open on those devices. +- **Explicit `--expert-cache` with a split:** it is capped so CUDA0 keeps room for the prompt path's own buffers. + Without the cap, the first prompt failed with "device buffers ... do not fit". +- **`--mmap-experts`:** refused at start for a native pack, with the reason. diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json new file mode 100644 index 00000000..d36b8baa --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 102, + "drafts_offered": 166, + "tok_s": 66.7, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 134, + "drafts_offered": 180, + "tok_s": 80.8, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 72.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.6, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 92, + "tok_s": 45.4, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 72, + "repeats": 0, + "drafts_accepted": 15, + "drafts_offered": 70, + "tok_s": 46.1, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 76, + "tok_s": 49.3, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 56, + "tok_s": 46.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.4, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 148, + "tok_s": 56.4, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json new file mode 100644 index 00000000..503a7a24 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-single-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 102, + "drafts_offered": 166, + "tok_s": 67.1, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the iron gallery of the Blackwood Point Light, rattling the glass panes like a prisoner testing the bars of a cell.\n\nElias Thorne was not a man who feared the dark. He was a man who feared the silence.\n\nFor forty years, he had lived in the shadow of the Fresnel lens, a rotating eye of glass and brass that swept the Atlantic with a beam of pure, unyielding light. His job was simple: keep the light burning. Keep the logbook current. Keep the foghorn sounding when the mist rolled in, thick as wool.\n\nBut Elias knew something else. He knew that the light was not just for ships. It was for the lost.\n\nIt was November 14th, 1982. The storm was a Category 5, a monster that had swallowed the horizon. The waves were mountains of black water, crashing against the granite" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 134, + "drafts_offered": 180, + "tok_s": 81.0, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 62.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 92, + "tok_s": 43.5, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 72, + "repeats": 0, + "drafts_accepted": 15, + "drafts_offered": 70, + "tok_s": 46.1, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds on an open sore skin\u2014like a wound left unhealed by time. Elias knew this rhythm better than he remembered his own name<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 76, + "tok_s": 48.9, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to break its rhythm against stone that refused be broken by anything less than God himself had forged into being willing and able withstand eternity\u2019s cruelty without complaint or mercy from start finish until now forevermore if any such concept even existed within human comprehension let alone divine authority which we all knew did not exist but wished it would because wishful thinking is always easier to imagine hopelessly impossible truths as probable lies than vice versa.\n\nElias Thorne was eighty-three years old today, exactly one hundred and forty-seven days since his last heart attack had been logged by Dr Armitage who himself retired seven months ago after receiving a subpoena from the county clerk indicating he might have overstayed professional courtesy boundaries" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 56, + "tok_s": 46.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nBoar \nRabbit \nSquirrel <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 63.1, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 148, + "tok_s": 56.6, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration by humans throughout human civilization; or perhaps more specifically in modern times refers often used metaphorically for economic trends like stock market fluctuations (\"sea change\"). However given your request likely intends an academic-style comprehensive overview covering both natural science aspects AND cultural significance through time periods\u2014especially since this kind question appears frequently on exams asking students write essays discussing evolution from primordial origins up present-day impacts including environmental changes due climate crisis etc.\u2014I will craft such broad yet structured piece combining geology + anthropology/ecological impact together while maintaining coherent flow suitable high-level educational context without overly technical jargon but still accurate enough scientifically grounded facts where appropriate within reasonable scope limits typical school assignments expect (~80\u201312% word count range implied implicitly though not stated explicitly here we aim moderate length ~65 words? Wait no user said \u201clong\u201d so probably >3k+ characters minimum safe bet around 7-9 paragraphs total approximating maybe close-to-full-page standard double-spaced equivalent which translates roughly \u22654K chars safely acceptable). Let me proceed accordingly ensuring clarity structure intro body conclusion style formal tone neutral informative balanced perspective acknowledging uncertainties if any minor ones exist e.g exact dates vary depending sources hence use hedging language sparingly only when necessary avoid overclaiming certainty especially regarding speculative theories vs established consensus knowledge base current mainstream understanding circa early-mid" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json new file mode 100644 index 00000000..3599ae8f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-cv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 85, + "drafts_offered": 172, + "tok_s": 36.6, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar-powered backup that no engineer had been able to fix before the supply boat stopped coming. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale. Outside, the world was a blur of black and white. The ocean was invisible; it was only a presence, a weight pressing against the stone foundation of the tower.\n\nHe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 173, + "tok_s": 96.8, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 88.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 104, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 96, + "tok_s": 55.9, + "text": "Aardvark \nAlbatross \n\nAlligator \nAnaconda \nAntelope \nBaboon \nBadger \nBat \nBear \nBeaver \nBirds of Paradise (Manucode) \nBoa Constrictor \n\nBuffalo \nCamel \nCapybara \nCat \nChameleon\nCheetah\n\nChicken\n\n\nCrocodile \nDeer \n\nDingo \nDog \nDonkey \nDragonfly \n\nElephant \nEmu \nFalcon \nFerret \nFlamingo \nFox<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 114, + "tok_s": 55.4, + "text": "The wind didn\u2019t just howl; it screamed against the glass of Lantern House 42, demanding entry into every crack and crevice that had been sealed with tar in previous years but now wept like old wounds at this one\u2019s age: forty-three winters since its construction. My name was Elias Thorne\u2014no middle initial\u2014and I kept no logbook for visitors because there were none; only ships passed by, their hulls cutting through the black water as if they too feared what lay beneath it more than above or beside them in fog so thick that even my own reflection vanished from sight when looked upon directly.\n\nI climbed each morning not to greet dawn but check whether light still lived within me\u2014the bulb\u2019s heart had failed twice before, once during a storm named *Harrow*," + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 110, + "tok_s": 52.2, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in my teeth, searching for something to hold onto until I died.\u201d said Elias Thorne as he adjusted his collar against November\u2019s bite.** He was not merely complaining of cold weather but articulating a poetic metaphor: that even after death (metaphorically), there would be no relief from this relentless gale.\n\nElias had been the last human keeper on any significant stretch coast since automation became standard practice, yet here he stood , stubbornly refusing to let technology replace his vigilance . His cottage perched atop a crumbling granite foundation was more than just shelter; it housed centuries of handwritten logs detailing every ship\u2019s name and cargo load that passed within sight.\n\nOn most nights Elias tended the light mechanically\u2014" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 91, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 69, + "tok_s": 58.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippopotamus \nRhinoceros \nLeopard \nCheetah \nPanther \nWolf \nFox \nBear \nDeer \nElk \nMoose \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nBull \nOx \nPig \nDog \nCat<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 12, + "repeats": 0, + "drafts_accepted": 4, + "drafts_offered": 17, + "tok_s": 60.3, + "text": "1 2,3456789<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 41, + "drafts_offered": 168, + "tok_s": 59.9, + "text": "The phrase \"the History Of The Sea\" is inherently ambiguous, as it could refer to several distinct historical narratives: geological formation (how oceans came into existence), maritime navigation and exploration histories (\"history at/over/across/on/in/of/to/from/toward/off by means around above below through under upon alongside against among between within without throughout despite during after before since until while when where who whom whose which what how why whether\"), or perhaps even metaphorical interpretations involving human interaction with water bodies over time periods like ages eras epochs generations centuries decades years months days hours minutes seconds moments instants times occasions instances events episodes incidents occurrences situations circumstances conditions states phases stages steps processes procedures sequences series chains cycles loops repetitions iterations continuations progressions developments evolutions transformations changes alterations modifications adjustments corrections revisions amendments updates upgrades improvements enhancements refinements optimizations perfecting completing finishing concluding ending terminating ceasing stopping halting pausing resuming continuing proceeding advancing progressing moving shifting translating rotating reflecting mirroring flipping turning twisting bending curving arches spirals helix coils twists turns rotations reflections mirrors flips inversions reversings reversion backtracking retracing reversing undo redo do again repeat repeats repeated repeatedly repetition repetitive repetitiveness repete repeater repeatingly recurrent recurrence recurring recurs recur recurred recursion recursive recursively recurse recessed recessionary regress regression regressed retrograde reverse reversed reversal revert reverted reverberate resonated echo echoed echoing echoes echolocation sonar radar radio telecommunication communication communications communicate communicated communicating communicative comms comm chatter chat chats chatting chatted talk talks talked" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json new file mode 100644 index 00000000..c8e5f091 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp0-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 171, + "tok_s": 62.5, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from broken glass and rusted iron, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and precise. *Tick. Tick. Tick.* The sound was the heartbeat of the coast." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 184, + "tok_s": 85.2, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 78.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 80.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 48, + "tok_s": 46.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 101, + "tok_s": 51.3, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine\n\nElias was not merely keeping light alive; He kept order intact. Every night, at precisely 18:07 hours local time\u2014adjusted for leap seconds and magnetic drift\u2014he wound the clockwork mechanism inside brass housing behind Fresnel lens This wasn\u2019t vanity It\u2019s necessity The rotation speed must remain constant or ships lose their bearing in fog where compasses fail\n\nHe spoke softly to himself while working, murmuring numbers aloud because silence made him" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 67, + "repeats": 0, + "drafts_accepted": 14, + "drafts_offered": 68, + "tok_s": 41.2, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, like he had no mouth to hold back its fury anymore that night.\u201d Elara pulled her wool coat tighter around herself as she climbed spiral staircase of **Blackrock Lighthouse**. Her boots were slick with salt spray from previous days.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 91, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 54, + "tok_s": 48.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nJaguar \nBear \nWolf \nFox \nDog \nCat \nMouse \nRat \nSquirrel \nDeer \n\nAntelope \n\nBuffalo \n\n\nBison \n\n\n\nElk \n\n\n\n\nMoose <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 11, + "tok_s": 68.8, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 107, + "tok_s": 52.3, + "text": "The ocean is not merely water; it has been, and remains to this day one giant storybook that weaves together geology with biology as wellas human culture into an epic narrative spanning billions years from its earliest beginnings in primordial times through modern-day ecological crises The vast expanse covers more than seventy percent Earth\u2019s surface area making up nearly all life support systems on our planet yet despite being so large humans have only explored less five thousand square kilometers out total 361 million km\u00b2 which means over ninety-nine point nine eight six per cent unexplored territory This makes oceans arguably larger unknown territories compared space exploration where NASA estimates they\u2019ve mapped roughly ten billion stars versus current marine surveys covering just two hundred fifty-six species documented globally against estimated millions undiscovered organisms including deep-sea creatures like anglerfish or vampire squid whose existence was first recorded centuries ago but still remain poorly understood due extreme pressures depths exceeding eleven miles below Pacific Trenches Mariana located near Guam island chain reaching maximum depth known today at approximately thirty-seven feet under pressure equivalent atmospheric levels causing structural collapse if unprotected by specialized vessels capable handling such conditions without failure mechanisms designed specifically for submersible operations operating within these zones require titanium hulls rated withstand forces greater gravity acting upon objects falling vertically downward acceleration rates calculated using Newtonian physics principles applied universally across gravitational fields regardless medium density variations present throughout different layers stratosphere troposphere mesospheres thermoclines etceterally speaking however when discussing aquatic environments instead air masses replace gases dissolved oxygen nitrogen arg" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json new file mode 100644 index 00000000..d8fb5e07 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-hp1-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 169, + "tok_s": 43.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage that smelled perpetually of kerosene and damp wood.\n\nFor decades, Elias had tended the great Fresnel lens, polishing the glass prisms until they gleamed like diamonds, winding the clockwork mechanism that turned the beam, and trimming the wick of the oil lamp. It was a job of patience, of precision, of silence. The light was his charge. The sea was his neighbor.\n\nBut this morning, the sea was not his neighbor. It was his enemy.\n\nThe storm had been forecasted for three days, but it had arrived in one. The barometric pressure had dropped so sharply that Elias\u2019s ears popped." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 178, + "tok_s": 63.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 56.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 57.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 24, + "drafts_offered": 49, + "tok_s": 43.3, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nHippopotamus \nRhinoceros \nCheetah \nLeopard \nJaguar \nPuma \nWolf \nFox \nBear \nDeer \nElk \nMoose \nAntelope \nBison \nBuffalo \nCamel \nDonkey \nGoat \nSheep \nCow \nDog \nCat \nRabbit \nMouse \nHamster \nGuinea Pig<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 35, + "drafts_offered": 108, + "tok_s": 41.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots smelled faintly brine and old coffee as he climbed spiral stairs worn smooth by decades feet his hands were calloused from gripping iron railings that had been polished to a dull shine.\n\nElias wasn\u2019t just keeping light; was guarding silence the beam swept across black water every seven seconds cutting through fog so thick it swallowed sound entirely for three nights straight no ships answered its signal not even fishing trawlers seeking shelter they\u2019d long abandoned this stretch of coast where currents shifted unpredictably pulling debris from sunken wrecks into tangled heaps that snagged anchors and tore hulls open like wounds.\n\nHe remembered the last time someone had" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 46, + "tok_s": 33.7, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to pry them apart like loose planks of weathered oak outside your own mouth again and then you are going away from home is fine but for now let me write a proper story.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 60, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 48, + "tok_s": 43.2, + "text": "Aardvark \nAntelope allonax (Oryx) \u2013 *Note: Using standard names for clarity* \n\nLet me provide a clean list of exactly **1** animal name on each single physical text file/terminal output stream with no other characters except the newline (\\n).<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 11, + "tok_s": 48.9, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 27, + "drafts_offered": 105, + "tok_s": 40.2, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element\u2014it became civilization itself through its capacity as both barrier (to land) but also conduit between lands\u2014and thus gave rise directly from being part nature\u2019s own evolutionary engine into becoming humanity's greatest historical actor across all time scales since first emergence until now present-day future projections still ongoing today within our current era context window limits allowed here by system constraints set above threshold levels required before output generation begins below line break marker inserted immediately after final punctuation mark ending entire preceding paragraph block structure defined earlier during initial drafting phase prior execution stage completed successfully without errors detected internally via internal validation routines executed automatically upon completion cycle termination signal received end-of-file condition triggered correctly according standard protocol specifications followed strictly adhered-to throughout process flow control logic implemented using structured programming constructs compatible with target runtime environment configuration parameters specified herein explicitly declared beforehand at top-level scope declaration section located near beginning source code file header comments included inline documentation style guidelines observed consistently applied uniformly everywhere else similarly formatted sections appearing later down document body text area scrolling vertically downward directionally aligned left margin justified right edge wrapped around fixed-width column boundaries determined dynamically based available screen real estate measured pixel-per-unit scaling factor adjusted responsively depending viewport dimensions reported back client-side rendering pipeline components responsible" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json new file mode 100644 index 00000000..c2e69fee --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 167, + "tok_s": 62.7, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 179, + "tok_s": 81.3, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.0, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 52, + "tok_s": 47.9, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 122, + "tok_s": 47.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 65, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 58, + "tok_s": 42.6, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 101, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 53, + "tok_s": 49.4, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 64.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 49.9, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json new file mode 100644 index 00000000..cd49d8c4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-single-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 94, + "drafts_offered": 167, + "tok_s": 49.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to hold the chaos of the ocean at bay. The beam swept out, a blade of pure, concentrated light cutting through the rain and sleet, illuminating the jagged teeth of the reef below.\n\n" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 179, + "tok_s": 76.2, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.4, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 52, + "tok_s": 47.1, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFalcon <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 122, + "tok_s": 47.0, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach his post at dawn every morning for thirty years. His name was written on a brass plaque by door: **Elias Thorne**.\n\nHe wasn\u2019t just keeping light; He kept time, weathered hands gripping the cold iron railing until knuckles turned white against frostbite and windburn that never healed fully because they were always there waiting to be felt again when he stepped outside into storm or calm alike. The lens above him was a Fresnel giant\u2019s eye made of hand-ground crystal prisms each one polished daily with chamois cloth soaked in whale" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 65, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 58, + "tok_s": 42.3, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they slammed against their hinges every night for eleven months of winter and summer alike.\u201d I had never seen calm water here\u2014only gray churning seas that swallowed ships smaller than themselves<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 101, + "repeats": 0, + "drafts_accepted": 32, + "drafts_offered": 53, + "tok_s": 50.0, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nHyena \nJackal \nAntelope \nBison \nElk \nCaribou \nLlama \nAlpace <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 64.6, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 49.8, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by hundreds millions years yet continues shaping every aspect from climate regulation through evolutionary biology down even into modern industrial logistics today's global supply chains depend upon them directly indirectly via atmospheric pressure systems weather patterns migration routes food webs carbon cycles oxygen generation thermal buffering tidal forces salinity gradients depth stratification light attenuation currents circulation gyres upwelling zones thermoclines halothermics bathymetric features continental shelves abyssal plains trenching ridges volcanic arcs island formations atoll structures seamounts submarine canons canyon walls cliff faces overhang ledge platforms reef flats fore-reef back-lagoon inner-shelf outer-slope drop-offs pinnacle pinnacles spires columns arches tunnels caves grottos swim-through passages chimney vents blowholes fissures cracks crevices joints faults fractures breaks gaps holes openings void spaces hollow chambers cavernous interiors subterranean networks underground rivers lakes pools springs wells shaft pits sinks drains sewers pipes conduits tubes channels gutters ditches furrows grooves rills runnels streams brooks rivulets creeks tributaries branches forks splits divergences con" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json new file mode 100644 index 00000000..2f058f40 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-kv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 97, + "drafts_offered": 176, + "tok_s": 73.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was the last of the line, the only man left on the jagged spine of Widow\u2019s Rock. For forty years, he had tended the light. For forty years, he had listened to the ocean\u2019s endless, hungry whisper.\n\nTonight was different. The storm wasn\u2019t just a storm; it was a *tempest*. The waves didn\u2019t crash; they *shattered*. They threw themselves against the granite base of the lighthouse with the force of a battering ram, sending tremors up through the soles of Elias\u2019s boots.\n\nHe climbed the spiral stairs, one hundred and twelve steps of iron and rust. His hand, calloused and scarred from decades of polishing the brass railing, found the familiar groove in the metal. He didn\u2019t look up. He didn\u2019t look down. He looked *forward*." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 176, + "tok_s": 102.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 90.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 91.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 38, + "drafts_offered": 103, + "tok_s": 62.8, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 58, + "repeats": 0, + "drafts_accepted": 9, + "drafts_offered": 63, + "tok_s": 50.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level three hundred feet down to where Elias kept his boots dry and ready for emergencies when he had no time even think about changing them.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 140, + "repeats": 0, + "drafts_accepted": 22, + "drafts_offered": 90, + "tok_s": 50.1, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, demanding entry into every crack and crevice of Stone Harbor Lighthous eKeepers have always been solitary figures against isolation\u2019s greatest adversary: time itself Elias Thorne knew this intimately. For thirty years he had kept watch over one hundred thousand ships each night scanning for lights that might signal disaster or hope\n\nHis job was simple but deadly serious He checked weather logs every day without fail The foghorn echoed through the tower three times before dawn Each morning at 4:02 AM Elias would climb eighty-two steps to reach his office where coffee cooled beside a single candle flickering in drafts from below<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 96, + "repeats": 0, + "drafts_accepted": 31, + "drafts_offered": 69, + "tok_s": 58.9, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKangaroo \nKoala \nHippo \nRhino \nCheetah \nLeopard \nJaguar \nPanther \nCougar \nBear \nWolf \nFox \nDeer \nElk \nMoose \nBison \nBuffalo \nAntelope \nCamel \nDonkey \nGoat \nSheep \nCow \nPig \nHorse <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 71.2, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 119, + "tok_s": 61.3, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth\u2019s surface.\u201d \u2014 *This quote by Rachel Carson serves as an apt introduction.* The story we tell today begins with that first drop falling into primordial pools billions years ago\u2014but what follows next? What happens when those drops become oceans themselves\u2014when they begin moving across continents carrying sediment from mountains down rivers until finally reaching their final resting place at last\u2014the deep abyssal plains where sunlight cannot reach nor pressure crushes everything else alive there below depths greater than six kilometers beneath waves crashing against shores above them all around world forever changing shape over time due plate tectonics shifting landmass slowly apart together again repeatedly throughout geological epochs spanning hundreds millions or even thousands million+ yrs since formation early Hadean era through Archeozoic eons onward present Holocene epoch still ongoing now right here under current conditions observed via satellites monitoring global climate patterns affecting currents temperatures salinity levels biodiversity distribution human impacts altering ecosystems directly indirectly causing extinction events locally globally recently historically prehistorically anciently mythologically culturally spiritually philosoph scientifically mathematically physically chem biol geo astro cosmological sociopolitical economic environmental ecological evolutionary genetic linguistic literary artistic musical cinematic theatrical photographic journalistic digital analog virtual real tangible intangible metaphysical ontosemantic semiotic symbolic allegorical narrative descriptive analytical interpretive evaluative critical reflective introspective contemplatory ponderous thoughtful considerate attentive observant perceptive insightful intelligent knowledgeable informed educated literati learned skilled capable" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json new file mode 100644 index 00000000..0e44612c --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-nocv-x2-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 87, + "drafts_offered": 170, + "tok_s": 71.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 178, + "tok_s": 104.1, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 90.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 76, + "repeats": 0, + "drafts_accepted": 20, + "drafts_offered": 64, + "tok_s": 61.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \nButterfly \nCamel \nCat \nCaterpillar \n\nCentipede \n\nChameleon \n\nCheetah \n\nChicken \n\nCricket \n\nCrocodile \n\n\nDolphin \n\n\n\nDonkey \n\n\n\n\nDragon<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 21, + "drafts_offered": 90, + "tok_s": 59.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty jail cell below sea level to above cloud height at once\u2014no matter how high you climbed or deep into its foundations down through rock and saltwater. It was November again when Elias first noticed that his logbook had begun recording entries he hadn\u2019t written yet: *Storm surge expected Tuesday, but the sky is clear.*\n\nHe stopped writing for a moment to listen\u2014not with ears alone\u2014but by pressing both palms flat against cold iron walls where condensation formed in slow spirals like fingerprints left behind after touching something invisible. The metal hummed faintly beneath his skin as if remembering old storms long past their dates on paper calendars torn from newspapers dated three years ahead of today" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 63, + "tok_s": 52.6, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his teeth, trying to get inside where he had spent thirty years refusing entry except for family and friends like him who were old enough too know better than young men ever could be again about what safety meant. It was November 2014 when Elias Thorne first stepped onto that spiral staircase with only one boot on because his other foot hurt after walking from the harbor office all morning long before anyone else thought he needed shoes off there for work even if nobody saw them do it but everyone knew why so they did not ask him anymore once this happened already twice last winter near same season now here again today too soon then tomorrow maybe never will come back unless someone sends message tonight via radio signal code Morse dot dash pattern" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 94, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 60, + "tok_s": 58.8, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nKangaroo \nPanda \nKoala \nCheetah \nWolf \nFox \nBear \nMonkey \nDolphin \nWhale \nShark \nOctopus \nJellyfish \nCrab \nSpider \nRabbit \nCat \nDog \nHorse \nCow \nSheep \nGoat \nChicken \nRooster \nTurkey \nEagle \nFalcon <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 71.8, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 52, + "drafts_offered": 148, + "tok_s": 61.8, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose evolution shaped everything else around us from climate patterns down through evolutionary biology right up into modern civilization's economic structures cultural identities political boundaries ecological systems scientific understanding technological capabilities philosophical frameworks psychological experiences artistic expressions literary metaphors cinematic narratives musical compositions architectural designs urban planning strategies agricultural practices industrial processes medical discoveries legal precedents educational curricula religious traditions spiritual beliefs mythological stories folkloric tales poetic verses dramatic scripts visual arts photographic images digital media social networks behavioral norms emotional responses cognitive models decision-making algorithms predictive analytics statistical probabilities probabilistic reasoning causal inference counterfactual thinking hypothetical scenarios normative ethics deontal logic modal semantics temporal dynamics spatial relations topographical features hydrological cycles meteor phenomena atmospheric chemistry geological formations tectonic shifts volcanic eruptions seismic events tsunamis hurricanes cyclones monsoons typhoons droughts floods storms winds currents waves swells breakers surf foam spray mist fog rain snow ice glaciers berg floes drift pack-ice brine salinity pH alkalines acidity hardness softness temperature pressure depth light darkness color hue saturation brightness contrast luminance chroma tone value shade tint reflection" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json new file mode 100644 index 00000000..99bd3791 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/norepeat-lim-reg-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.7, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 71.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 73.0, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.1, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 43.9, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.1, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.2, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json new file mode 100644 index 00000000..9c6a2a05 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-cv-pp-x2.json @@ -0,0 +1,84 @@ +{ + "label": "lim-cv-pp-x2", + "extra": [ + "--layer-split", + "auto", + "--control-vector-scaled", + "C:\\Users\\ribbon\\strata-test\\Strata\\data\\experimental-speed-projection\\Qwen3.8-Flash-Next-experimental-speed-projection.gguf:1.0", + "--control-vector-layer-range", + "4", + "44", + "--cvec-mode", + "project", + "--cvec-dir", + "per-layer" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 8783.1, + "pp_tok_s": 1813.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 13379.7, + "pp_tok_s": 2053.4, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3652.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 246.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.0, + "reps": [ + 77.0 + ], + "hit_rate": 0.9718150054476462, + "text": "The wind didn\u2019t just howl; it screamed. It tore through the gaps in the iron railing of the Lantern Room, carrying the scent of brine and rotting kelp. Elias pulled his woolen collar up to his chin, his fingers numb and clumsy inside thick leather gloves.\n\nHe was the last man on the island. The automated systems had failed three winters ago, a glitch in the solar panel array that no engineer had been able to fix before the supply boat stopped running. Now, it was just him, the light, and the sea.\n\nElias climbed the spiral stairs, his boots heavy with salt spray. The iron steps groaned under his weight, a sound that seemed to mock the storm outside. He reached the top, the glass walls vibrating with the force of the gale.\n\nInside the lantern room, the great Fresnel lens sat like a dormant eye. It was cold, dark, and waiting.\n\nElias moved to the control panel. His" + }, + { + "name": "code", + "tok_s": 103.6, + "reps": [ + 103.6 + ], + "hit_rate": 0.957731667226356, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 3479 slots, 6.22 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 91.6% (5554 hits / 6062 lookups)", + "strata serve: decode expert cache hit rate: 95.3% (3592 hits / 3771 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (3650 hits / 3782 lookups)", + "strata serve: decode expert cache hit rate: 96.3% (25027 hits / 25980 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (3201 hits / 3318 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (129334 hits / 133085 lookups)", + "strata serve: decode expert cache hit rate: 95.8% (108375 hits / 113158 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json new file mode 100644 index 00000000..5316f9a9 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-single.json @@ -0,0 +1,76 @@ +{ + "label": "lim-kv-pp-single", + "extra": [ + "--max-context", + "131072", + "--kv-resident", + "32768" + ], + "gpus": "0", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 10706.3, + "pp_tok_s": 1487.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 15256.7, + "pp_tok_s": 1800.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 59725, + "prompt_ms": 32515.5, + "pp_tok_s": 1836.8, + "found": true, + "answer": "falcon-174<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4006.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 276.2, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 66.6, + "reps": [ + 66.6 + ], + "hit_rate": 0.7101864314556545, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb." + }, + { + "name": "code", + "tok_s": 74.0, + "reps": [ + 74.0 + ], + "hit_rate": 0.5873783774988882, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: expert cache auto: 8.99 GiB free, 700 MiB reserved -> 3349 slots", + "strata generate: expert cache 2434 slots, 4.67 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 1944 cache slots (3.72 GiB)", + "strata serve: decode expert cache hit rate: 41.8% (1746 hits / 4176 lookups)", + "strata serve: decode expert cache hit rate: 50.4% (1512 hits / 3000 lookups)", + "strata serve: decode expert cache hit rate: 54.9% (1689 hits / 3077 lookups)", + "strata serve: decode expert cache hit rate: 60.3% (1938 hits / 3213 lookups)", + "strata serve: decode expert cache hit rate: 58.3% (11146 hits / 19121 lookups)", + "strata serve: decode expert cache hit rate: 66.1% (2201 hits / 3331 lookups)", + "strata serve: decode expert cache hit rate: 71.0% (74397 hits / 104757 lookups)", + "strata serve: decode expert cache hit rate: 58.7% (54151 hits / 92191 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json new file mode 100644 index 00000000..275e63f4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/pp-lim-kv-pp-x2.json @@ -0,0 +1,87 @@ +{ + "label": "lim-kv-pp-x2", + "extra": [ + "--max-context", + "131072", + "--kv-resident", + "32768", + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 15925, + "prompt_ms": 9452.6, + "pp_tok_s": 1684.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27474, + "prompt_ms": 14042.4, + "pp_tok_s": 1956.5, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 59725, + "prompt_ms": 30345.9, + "pp_tok_s": 1968.1, + "found": true, + "answer": "falcon-174<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3806.1, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 75.8, + "reps": [ + 75.8 + ], + "hit_rate": 0.9698055042592483, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He stood before the great Fresnel lens, a cathedral of glass and brass that caught the light of the single, powerful bulb and fractured it into a thousand beams.\n\nHe checked the clock. 11:42 PM. The rotation was smooth, silent, a hypnotic sweep that painted the darkness with a slow, rhythmic pulse. *Flash. Dark. Flash. Dark.*\n\nE" + }, + { + "name": "code", + "tok_s": 97.0, + "reps": [ + 97.0 + ], + "hit_rate": 0.9562207324057541, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 17.96 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.13 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 13.98 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11199 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.30 GiB free, 700 MiB reserved -> 3277 slots", + "strata generate: expert cache 3409 slots, 6.09 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 91.3% (5098 hits / 5585 lookups)", + "strata serve: decode expert cache hit rate: 94.7% (4000 hits / 4225 lookups)", + "strata serve: decode expert cache hit rate: 96.5% (4095 hits / 4245 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (4183 hits / 4278 lookups)", + "strata serve: decode expert cache hit rate: 96.2% (27177 hits / 28250 lookups)", + "strata serve: decode expert cache hit rate: 97.6% (4177 hits / 4281 lookups)", + "strata serve: decode expert cache hit rate: 97.0% (130241 hits / 134296 lookups)", + "strata serve: decode expert cache hit rate: 95.6% (113534 hits / 118732 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split-limits/data/vision.json b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/vision.json new file mode 100644 index 00000000..ed935b5b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split-limits/data/vision.json @@ -0,0 +1,24 @@ +{ + "answers": { + "single": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are arranged on a white background." + ], + "same24": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are arranged on a white background." + ], + "x2": [ + " Red", + "42", + "A red circle, the number 42, and a blue square are displayed on a white background." + ] + }, + "correct": { + "single": true, + "same24": true, + "x2": true + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/README.md b/engine/strata/bench/results/2026-09-29-layer-split/README.md new file mode 100644 index 00000000..363b1a1c --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/README.md @@ -0,0 +1,84 @@ +# Layer split across GPUs (2026-09-29) + +**Rig (a community member's PC, "RIBPC"):** +- Ryzen 9 9950X3D, 62 GB DDR5, Windows 11, CUDA 13.1. +- RTX 5080 16 GB (x16), RTX 3090 24 GB (x4 gen4, ~6 GB/s), RTX 2080 Ti 22 GB (x4 gen3, Turing sm_75; the + experimental `STRATA_EXPERIMENTAL_SM75` build). + +**Model:** the Coder (GSQ-RCO IQ1_M, 48 layers x 256 experts = 12,288 expert pairs, ~23 GB of experts), 32K +context, int8 KV, `--prefill auto`, `--spec 4`. It is the only model that fits the rig's RAM and disk. + +**Tools:** `rib_pp.py` (needle prompts at 2.7K/8K/16K/28K tokens with a code word at 50% depth, a 2-turn chat that +must reuse its checkpoint, greedy decode of a story and a code prompt) and `rib_norepeat.py` (the Phase A +no-repeat and sanity cases). Raw results are in `data/`. + +## Correctness + +| Check | Result | +|---|---| +| This branch vs the 0.1.20 release, one GPU (5080), fixed cache, all 10 cases | **10/10 byte-identical** | +| This branch, one GPU vs the split on the same GPU (K=24, `--split-device 0`) | **10/10 byte-identical**: the hand-off is exact | +| 5080 + 3090 (auto) and 5080 + 2080 Ti + 3090 (auto): no-repeat under presence 100 (greedy and sampled), 144 sanity | all pass, 0 repeats | +| Needles at 2.7K-28K tokens, every configuration | all found | +| 2-turn chat (the checkpoint restored on every GPU) | reused 6,631-6,632 of 6,660 tokens, answer right | + +Across GPUs the text is not byte-identical to one GPU: experts the CPU computed on one card run on a GPU in the split, +and they round differently (the same effect as `--expert-cache`, bench/results/2026-09-27-cache-parity). + +## Speed + +**Prompt tok/s** at 16K / 28K tokens, and **decode tok/s** for story / code (greedy; three repeats averaged +in the K sweep): + +| Configuration | Split | Prompt 16K | Prompt 28K | Decode story | Decode code | Decode hits | +|---|---|---|---|---|---|---| +| 0.1.20, 5080 alone | - | 2,045 | 2,005 | 83.2 | 88.2 | 70-84% | +| this branch, 5080 alone | - | 2,017 | 1,974 | 83.1 | 88.0 | 70-84% | +| this branch, 5080 alone, 3 repeats (adaptive swaps learn the prompt) | - | 1,726 | 1,970 | 86.7 | 105.2 | 91-92% | +| 3090 alone | - | 1,253 | 1,211 | 71.7 | 92.9 | 86-93% | +| 5080 + 3090 | K=18 | 1,547 | 1,694 | 77.2 | 103.8 | 99.9% | +| 5080 + 3090 | K=22 | 1,840 | 2,074 | 80.2 | 106.4 | 99.8% | +| 5080 + 3090 | K=24 | 1,978 | 2,258 | 83.5 | 109.5 | 99.5% | +| **5080 + 3090** | **K=26** | **2,039** | **2,357** | **83.8** | **109.7** | 99.3% | +| 5080 + 3090 | K=28 | 2,011 | 2,287 | 83.5 | 112.5 | 99.0% | +| 5080 + 3090 | K=30 | 1,935 | 2,218 | 81.1 | 109.6 | 98% | +| 5080 + 3090 | K=32 | 1,818 | 2,063 | 83.0 | 108.7 | 98% | +| 5080 + 3090 | auto (K=22) | 2,037 | 2,073 | 79.5 | 108.9 | 99.7% | +| 3090 + 5080 | auto (K=30) | 1,672 | 1,876 | 90.3 | 105.1 | 99.4% | +| 5080 + 2080 Ti + 3090 | auto (22, 23) | 1,687 | 1,847 | 67.6 | 89.6 | 99.7% | +| 5080 + 3090 + 2080 Ti | first auto (12, 33) | 1,148 | 1,144 | 51.9 | 69.7 | 100% | +| 5080 + 2080 Ti | first auto | 914 | 906 | 45.5 | 58.0 | 97% | + +What decides it: + +- **The best two-GPU split for the Coder is K=26-28.** Prompts run +18-20% over the 5080 alone at 16-28K; + decode is on par for story and +4-7% for code. +- **Residency saturates quickly: the per-layer GPU speed decides.** From K=18 up, both caches hold 98-100% of + the routed experts. Moving layers to the faster card is what helps: the 3090 costs 0.50 ms per layer per + window, the 5080 0.33 (`STRATA_SPLIT_TIMING`, the "wait for the GPU" per stage). +- **Decode is bounded by that GPU time.** One 5080 with its cache adapted spends 16.3 ms waiting for its GPU and + 5.5 ms in the CPU pool per window. The split removes the pool (0.8-1.0 ms) but adds the slower card's layers: + 7.9 + 12.1 ms at K=24. The per-layer GPU half (kernels plus the host round trip that publishes each layer's + expert plan) is the next thing to cut, for one GPU as well (perf-review-plan E-6). +- **A third, slower card costs more than it holds.** The 2080 Ti's one-layer stage took 3.1 ms per window. + For a model that already fits two cards, leave it out. It pays only when the two faster cards cannot hold most + of the routed experts (a bigger model; not testable on this rig's 62 GB of RAM). +- **Prompt chunk:** 1024 instead of 2048 frees ~0.7 GB per card, but prompts read 7-12% slower. + +## Auto placement + +`--layer-split auto` predicts one decode window's time for every placement (every placement up to three GPUs) and +keeps the fastest: + +- **per-layer time** from SMs x clock (0.33 ms for an RTX 5080); +- **cache contents:** each card's layers' profiled pairs, hottest first, as the fill does; +- **routed mass** of rank r taken as (r+1)^-1.2 (fits the sweep's hit rates within 0.1-1%); +- **missed mass** costing 190 ms per unit (fitted to the sweep's best K; `STRATA_SPLIT_MISS_MS` overrides). + +It picked K=22 on the 5080 + 3090: within 0-12% of the best fixed split on prompts and on par on decode. It gives +a slow third card a single layer. + +## Reproduce + +On a rig: the `strata-remote` tools, then `rib_matrix.bat`, `rib_ksweep.bat`, `rib_validate.bat` (in the dev +notes, not in this repository). diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json new file mode 100644 index 00000000..a5169b0e --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x2-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 193, + "tok_s": 74.6, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 181, + "tok_s": 105.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 85.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 94.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 105, + "tok_s": 67.9, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 147, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 103, + "tok_s": 63.2, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 109, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 56, + "tok_s": 54.1, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 92, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 48, + "tok_s": 64.7, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 14, + "tok_s": 71.7, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 53, + "drafts_offered": 134, + "tok_s": 66.1, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json new file mode 100644 index 00000000..54c8c520 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-v-x3-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 193, + "tok_s": 68.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, gripped the iron railing as he ascended the final flight of steps to the lantern room.\n\nBelow him, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t flip a switch. He didn\u2019t press a button. He reached for the heavy brass lever that had worn smooth by his palm over the years. With a grunt that matched the strain of his aging muscles, he pulled it down.\n\n*Clunk.*\n\nThe" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 136, + "drafts_offered": 181, + "tok_s": 99.4, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 76.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 37, + "drafts_offered": 105, + "tok_s": 65.2, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 147, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 103, + "tok_s": 45.7, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to that date and time for context because you asked me about a lighthouse keeper but gave no specifics beyond \u201cshort story,\u201d so let\u2019s set it: isolated coastal station off the Oregon coast during winter storm season, 1987.\n\nMy name is Elias Vane (I made this fictional; real keepers often kept journals signed with initials only), and I\u2019m writing from memory because my logbook got waterlogged when a rogue wave breached lower storage room at dawn\u2014so here\u2019s what happened:<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 109, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 56, + "tok_s": 42.1, + "text": "The wind didn\u2019t just blow at Cape Hollow; it screamed through the gaps in my cottage\u2019s shutters, rattling them like loose teeth until they settled into silence with every storm break out of three hundred days here being storms that broke something else again but mostly kept me warm because I burned coal and wood whenever we had any left over from last winter when even then if you\u2019re lucky enough to get through it all without freezing yourself so hard your own thoughts become ice too\n\nBut Elias knew better than anyone: fear was useful only until dawn<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 92, + "repeats": 0, + "drafts_accepted": 26, + "drafts_offered": 48, + "tok_s": 43.9, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nHippopotamus \nRhinoceros \nCamel \nCheetah \nLeopard \nPanther \nJaguar \nBison \nElk \nDeer \nFox \nWolf \nBear \nLlama \nDonkey \nGoat \nSheep \nCow \nPig \nRabbit \nCat \nDog<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 14, + "tok_s": 61.4, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 53, + "drafts_offered": 134, + "tok_s": 51.9, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story we tell ourselves through our relationship** between landmasses separated by vast expansiveness that defines both isolation from other worlds (and thus their own unique evolutionary paths) as well than connection across them via currents wind patterns tides depth pressure temperature salinity biodiversity geology climate change economic trade routes ecological systems cultural exchange political boundaries scientific discovery technological advancement environmental degradation conservation efforts maritime archaeography historical cartographic evolution legal frameworks international law enforcement mechanisms insurance liability regimes regulatory compliance standards safety protocols navigation aids communication networks emergency response strategies search-and-rescue operations salvage rights ownership disputes heritage protection zones sustainable harvesting practices aquaculture development infrastructure engineering projects coastal management policies urban planning regulations zoning ordinances building codes architectural design guidelines aesthetic considerations functional requirements accessibility provisions energy efficiency measures thermal insulation techniques moisture control methods ventilation optimization lighting solutions acoustic soundproofing structural integrity assessments seismic resistance evaluations flood mitigation plans storm surge barriers levee construction seawall reinforcement breakwater installation harbor dredging channel maintenance buoy placement lighthouse automation radar monitoring sonar mapping bathymetric surveys hydrographic charts nautical almanacs tide tables current predictions weather forecasts marine meteorological models satellite imagery remote sensing data assimilation numerical simulations computational fluid dynamics finite element analysis partial differential equations tensor calculus linear algebra probability theory statistics stochastic processes Markov chains Bayesian inference machine learning artificial neural network deep convolutional recurrent transformer attention heads generative adversarial diffusion transformers large language model tokenization" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json new file mode 100644 index 00000000..537523bb --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x2-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 91, + "drafts_offered": 190, + "tok_s": 74.0, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 137, + "drafts_offered": 178, + "tok_s": 103.4, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 91.1, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 70.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 118, + "repeats": 0, + "drafts_accepted": 38, + "drafts_offered": 108, + "tok_s": 65.4, + "text": "Aardvark \nAlbatross \nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird of Paradise \nBuffalo \nCamel \nCheetah \nChimpanzee \nCrane \nCrocodile \nDeer \nDolphin \nDonkey \nElephant \nFlamingo \nFox \nGiraffe \nGoat \nHippopotamus \nIguana \nJaguar \nKangaroo \nKoala \nLion \nLeopard \nMonkey \nMoose \nOstrich \nOtter\nPanda<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 57, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 61, + "tok_s": 57.1, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach top room where his world began again.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 58, + "repeats": 0, + "drafts_accepted": 14, + "drafts_offered": 54, + "tok_s": 52.9, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in stone and steel, carrying with them spray from three miles out into churning black water that no longer resembled an ocean so much as abyssal chaos waiting for its prey to surface beneath waves of salt.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 11, + "drafts_offered": 47, + "tok_s": 51.7, + "text": "Lion \nTiger \n\nElephant\\nGiraffe\\Zebra\\rHippopotamus\\tRhinoceros\\vCrocodile\\fAlligator\\bSnake\\aSpider\\u2615CoffeeCup\u2615\ufe0fTeaTime\ud83d\udc09DragonFishWhaleDolph<|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 12, + "tok_s": 73.5, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 43, + "drafts_offered": 126, + "tok_s": 63.4, + "text": "The ocean is not merely water; it has been, and continues to be one with humanity\u2019s most profound narrative arc in human civilization: **the story told by waves**. It serves as both witness (through sedimentary layers)and participant( through currents that carry messages across continents). Its \"history\" spans geological epochs where life first emerged from primordial pools into complex ecosystems today\u2014and cultural histories shaped entirely around its roleas connector between distant lands or barrier separating them forever depending on perspective taken at different times throughout millennia since ancient civilizations began building boats outof logs carved using stone tools until modern container ships carrying billions tons cargo daily cross Atlantic routes once navigated onlyby stars alone under moonlight during nights when sailors feared monsters lurking beneath hulls made fragile against storms they could barely predict even now despite advanced meteorology systems developed over past century after industrial revolution transformed maritime trade patterns globally due economic pressures driving demand for faster logistics chains linking factories producing electronics manufactured inside cities located far inland near rivers feeding estuaries opening directly onto open seas connected via canals engineered centuries ago like Suez Canal built originallyfor military purposes later adapted commercial use post-World War II era reshaping global supply networks dramatically because geopolitical shifts altered which ports remained accessible politically versus physically blocked temporarily then reopened permanently following treaty agreements signed among nations agreeing upon shared responsibilities regarding environmental stewardship including coral reef restoration efforts funded jointly international organizations coordinating scientific research conducted aboard vessels specifically designed deep-sea exploration equipped robotic submersibles capable descending trenches deeper than any previous technology allowed" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json new file mode 100644 index 00000000..d72d1b23 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-nr-x3-auto-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 98, + "drafts_offered": 166, + "tok_s": 54.4, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 137, + "drafts_offered": 163, + "tok_s": 70.7, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 56.7, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 57.6, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 59, + "repeats": 0, + "drafts_accepted": 13, + "drafts_offered": 47, + "tok_s": 39.7, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBuffalo \n\nCat \nCheetah \n\nChimpanzee \nClam \n\n\nCrocodile \n\n\n\nDolphin \n\n\n\n\nDonkey <|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 57, + "repeats": 0, + "drafts_accepted": 12, + "drafts_offered": 58, + "tok_s": 39.9, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral vaults below Elias\u2019s boots were heavy with salt and exhaustion as he climbed one hundred twelve steps to reach topmost gallery where his world began.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 30, + "drafts_offered": 111, + "tok_s": 34.7, + "text": "The wind didn\u2019t just blow at Blackwood Rock; it screamed through the gaps in his stone cottage like an angry ghost trying to get inside, yet finding no door left unlocked because Elias never let one stay that way for more than three seconds after entering or leaving during storm season. He had been doing this since 1987\u2014since before he even knew why\u2014and now it was muscle memory so deep into his bones and fingers\u2019 calloused skin texture patterns worn thin by years of gripping the same iron railing at midnight watch that if you asked him what time exactly, down to quarter-hour increments when fog rolled in thick enough where light beams bent around itself like old rope coiling tight on a winch drum spooling out slowly from below deck floor level storage locker number seven under stairs leading" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 96, + "repeats": 0, + "drafts_accepted": 31, + "drafts_offered": 48, + "tok_s": 42.3, + "text": "Lion \nTiger \nElephant \nGiraffe \nZebra \nPanda \nKoala \nKangaroo \nCheetah \nHippopotamus \nRhinoceros \nLeopard \nJaguar \nWolf \nFox \nBear \nDeer \nOtter \nBeaver \nBadger \nMongoose \nMeerkat \nChimpanzee \nGorilla \nOrangetutan \nAntelope \nBison \nElk <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 43.0, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 29, + "drafts_offered": 127, + "tok_s": 37.6, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\u201d \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \u201cthe Sea\u201d or \"Ocean\" (terms often used interchangeably but distinct geographically) was never just an element within our planet\u2019s geography\u2014it became its engine itself\u2014a living system whose existence predates humanity by billions years yet continues shaping us today through climate regulation oxygen production food supply trade routes cultural identity ecological resilience economic development political boundaries scientific discovery technological innovation environmental crisis conservation efforts historical memory philosophical reflection poetic metaphor musical composition cinematic storytelling literary narrative visual art architectural inspiration culinary tradition spiritual symbolism psychological influence sociological transformation educational foundation medical necessity agricultural dependency industrial revolution urban planning infrastructural engineering legal framework regulatory policy international cooperation global governance planetary stewardship existential risk mitigation sustainable practice ethical consideration moral imperative social justice democratic participation civic engagement public health community welfare individual responsibility personal accountability collective action shared experience common understanding mutual respect reciprocal trust collaborative effort cooperative endeavor joint venture unified mission integrated strategy coordinated plan synchronized schedule aligned timeline concurrent execution simultaneous operation parallel processing sequential progression iterative refinement recursive improvement continuous adaptation dynamic adjustment flexible response adaptive behavior responsive conduct proactive initiative anticipatory foresight predictive modeling probabilistic assessment statistical analysis empirical observation experimental verification theoretical hypothesis conceptual abstraction logical deduction rational inference critical evaluation analytical reasoning systematic investigation methodical inquiry structured exploration comprehensive examination detailed scrutiny meticulous inspection thorough review exhaustive audit complete survey full census total enumeration absolute" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json new file mode 100644 index 00000000..99cf2991 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-dev-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 59.2, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 81.6, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.9, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.3, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 44.9, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 44.1, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.5, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 65.2, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.5, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json new file mode 100644 index 00000000..85cdf6e3 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-rel-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.6, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 75.2, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.2, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 48.5, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.4, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 43.3, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 49.8, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.5, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.6, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json new file mode 100644 index 00000000..e0473e78 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/norepeat-reg-same24-coder-iq1_m.json @@ -0,0 +1,92 @@ +[ + { + "name": "greedy story 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 88, + "drafts_offered": 187, + "tok_s": 58.4, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, mapped with veins like the roots of an ancient oak, gripped the cold iron railing.\n\nFor forty years, Elias had tended the light at the end of the world. Not the end of the map, but the end of the land. Here, the Atlantic threw itself against the granite cliffs with such violence that the spray reached the gallery, thirty feet above the rocks.\n\nHe checked the clock. 11:42 PM. The fog was thickening, a gray soup that swallowed the horizon. In the old days, he would have climbed the stairs to the lantern room, polished the Fresnel lens, and wound the clockwork mechanism that turned the great beam. But the automation had changed" + }, + { + "name": "greedy code 200", + "tokens": 200, + "repeats": 0, + "drafts_accepted": 135, + "drafts_offered": 179, + "tok_s": 80.5, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + }, + { + "name": "greedy sanity", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 74.5, + "text": "144<|im_end|>" + }, + { + "name": "greedy, no penalty (sanity)", + "tokens": 4, + "repeats": 0, + "drafts_accepted": 3, + "drafts_offered": 3, + "tok_s": 76.8, + "text": "144<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64", + "tokens": 61, + "repeats": 0, + "drafts_accepted": 19, + "drafts_offered": 49, + "tok_s": 49.6, + "text": "Aardvark \nAlbatross \n\nAlligator \nAntelope \nBaboon \nBadger \nBeaver \nBear \nBird \nBoar \nBuffalo \nButterfly \n\nCamel \nCat \nCheetah \n\nDolphin \n\n\nElephant \n\n\n\nFlamingo<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=64 story", + "tokens": 80, + "repeats": 0, + "drafts_accepted": 6, + "drafts_offered": 52, + "tok_s": 46.7, + "text": "The wind didn\u2019t just blow; it screamed against the glass of Lantern House 42, rattling like chains in an empty cathedral hall outside my window at midnight on November third this year\u2014so I pulled up to check what was happening with that storm and why they were calling me out there when all we had left for tonight\u2019s shift is one last pass through our logs before dawn breaks.<|im_end|>" + }, + { + "name": "sampled presence=100 last_n=64 seed 3", + "tokens": 160, + "repeats": 0, + "drafts_accepted": 17, + "drafts_offered": 83, + "tok_s": 44.3, + "text": "The wind didn\u2019t just blow at Cape Harrow; it screamed through the gaps in its teeth, hungry and relentless for three centuries of stone salt-spray history that had long since forgotten to be polite or gentle with itself against anything smaller than God Himself was willing acknowledge as divine protection from drowning souls who were already lost before they ever touched water.\n\nElias knew this rhythm better he himself could hear it sometimes; his boots worn smooth by pacing the spiral stair\u2019s center-post groove where thousands upon countless steps had rubbed away texture until all that remained beneath sole leather now felt like polished bone carved out slowly but surely over time into something more hollow than wood ever really should be allowed become when used so often enough within such confined circular spaces meant only for vertical ascent down always descending again back upward never truly leaving" + }, + { + "name": "sampled presence=100 last_n=64 seed 11", + "tokens": 62, + "repeats": 0, + "drafts_accepted": 18, + "drafts_offered": 31, + "tok_s": 50.0, + "text": "Lion \nTiger \n\nElephant \n \nGiraffe \n\n\n\nHippopotamus \nZebra \nRhinoceros \n\n\nPanda Bear \n\n\n\n\nKangaroo \nKoala \nSloth \n\n\n\n\n\nCheetah \nLeopard \nPanther \n\n\n\n\n\n\nWolf \nFox \nBear <|im_end|>" + }, + { + "name": "greedy frequency=100 last_n=16", + "tokens": 11, + "repeats": 0, + "drafts_accepted": 5, + "drafts_offered": 13, + "tok_s": 62.0, + "text": "1 to 50, separated by commas:<|im_end|>" + }, + { + "name": "greedy presence=100 last_n=4096 (8-row windows)", + "tokens": 300, + "repeats": 0, + "drafts_accepted": 47, + "drafts_offered": 153, + "tok_s": 52.1, + "text": "The ocean is not merely water; it has been, and remains to this day one giant machine for making life possible on Earth.\" \u2014 *David Attenborough* \n\nThis quote captures perhaps more than any other single sentence in human language: that which we call \"the Sea\" or \u201cOcean\u201d was never just an element within our planet\u2019s geography but rather its most fundamental biological engine\u2014a living system whose existence predates humanity by billions years yet continues shaping every aspect from climate regulation through evolutionary biology all way down modern industrial supply chains today's global shipping lanes carry cargo across vast distances because they were once crossed only slowly via coastal hopping routes used since antiquity until steamships revolutionized travel during late nineteenth century when diesel engines replaced wind power entirely allowing container ships carrying thousands TEUs (Twenty-foot Equivalent Units) per voyage crossing entire Pacific basins without stopping at intermediate ports anymore unlike earlier sailing vessels needing favorable winds currents seasonal patterns dictating departure windows based upon monsoon calendars established centuries ago before technological advances changed those constraints fundamentally altering logistics networks worldwide thereby transforming economic structures globally while simultaneously creating ecological disruptions due invasive species transported unintentionally alongside legitimate goods causing cascading ecosystem collapses locally where non-native organisms outcompete native fauna disrupting food webs leading population declines affecting biodiversity indices measured scientifically using standardized metrics like Shannon-Wiener diversity index calculations applied consistently over decades revealing trends showing significant decreases post-introduction events correl strongly with introduction dates matching historical records documenting first sightings confirmed taxonomically classified formally according International Code Nomenclature rules" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json new file mode 100644 index 00000000..acfe0b3f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-3090.json @@ -0,0 +1,72 @@ +{ + "label": "dev-3090", + "extra": [], + "gpus": "2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 3424.8, + "pp_tok_s": 796.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 8617.9, + "pp_tok_s": 972.3, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 12820.1, + "pp_tok_s": 1253.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 22901.1, + "pp_tok_s": 1211.4, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 5657.8, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 71.7, + "hit_rate": 0.9266798230257504, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron rungs were cold, slick with condensation that had leaked through the hairline cracks in the masonry. At the top, the lantern room hummed with the low, steady thrum of the rotating lens. It was a sound Elias had learned to sleep with, a heartbeat of the house.\n\nHe checked the clock. 11:42 PM. The light swept across the water, a slow, hypnotic arc. *Flash. Darkness. Flash. Darkness.*\n\nFor a moment, the beam caught something that wasn\u2019t water. A shape" + }, + { + "name": "code", + "tok_s": 92.9, + "hit_rate": 0.8636411400016346, + "text": "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(filepath, 'r', newline='') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 17.31 GiB free, 700 MiB reserved -> 6704 slots", + "strata generate: expert cache 8730 slots, 16.62 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2315 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 86.6% (4986 hits / 5756 lookups)", + "strata serve: decode expert cache hit rate: 87.1% (3757 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 88.7% (3827 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 92.1% (3975 hits / 4318 lookups)", + "strata serve: decode expert cache hit rate: 95.5% (4124 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 94.3% (25793 hits / 27360 lookups)", + "strata serve: decode expert cache hit rate: 94.6% (4088 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 92.7% (116454 hits / 125668 lookups)", + "strata serve: decode expert cache hit rate: 86.4% (73970 hits / 85649 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json new file mode 100644 index 00000000..e7b3d311 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-dev-5080.json @@ -0,0 +1,72 @@ +{ + "label": "dev-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2129.8, + "pp_tok_s": 1279.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5057.2, + "pp_tok_s": 1656.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7964.7, + "pp_tok_s": 2017.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14053.6, + "pp_tok_s": 1974.1, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3366.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.3, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.1, + "hit_rate": 0.8418683557684931, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 88.0, + "hit_rate": 0.7011385968111186, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)", + "strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)", + "strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)", + "strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)", + "strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)", + "strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json new file mode 100644 index 00000000..16251eb4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k18.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k18", + "extra": [ + "--layer-split", + "18" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 10383.7, + "pp_tok_s": 1547.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 16371.9, + "pp_tok_s": 1694.5, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4308.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 239.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.2, + "reps": [ + 74.6, + 78.1, + 79.0 + ], + "hit_rate": 0.9985378787878788, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through" + }, + { + "name": "code", + "tok_s": 103.8, + "reps": [ + 97.6, + 106.4, + 107.3 + ], + "hit_rate": 0.9984863945578232, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 524 windows; per window: wait for the GPU 6.456 ms, pool + plan 0.181 ms, host staging 0.581 ms, commit 0.206 ms", + "strata serve: stage 1: 524 windows; per window: wait for the GPU 14.872 ms, pool + plan 0.501 ms, host staging 0.000 ms, commit 0.387 ms", + "strata serve: stage 0: 593 windows; per window: wait for the GPU 6.479 ms, pool + plan 0.185 ms, host staging 0.515 ms, commit 0.207 ms", + "strata serve: stage 1: 593 windows; per window: wait for the GPU 15.053 ms, pool + plan 0.496 ms, host staging 0.000 ms, commit 0.390 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 18)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4608 slots, 8.24 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 18-47, expert cache 7152 slots (14.14 GiB), 7152 of its 7680 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-17", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-17 (CUDA0), 18-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.7% (6159 hits / 6240 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (3796 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (3811 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (27723 hits / 27840 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (3807 hits / 3840 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (142002 hits / 143040 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (139882 hits / 140160 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (131807 hits / 132000 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (119278 hits / 120480 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (117410 hits / 117600 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (117422 hits / 117600 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json new file mode 100644 index 00000000..7628eac8 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k19.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k19", + "extra": [ + "--layer-split", + "19" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9875.2, + "pp_tok_s": 1626.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15498.0, + "pp_tok_s": 1790.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4085.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 238.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 79.3, + "reps": [ + 74.8, + 85.6, + 77.4 + ], + "hit_rate": 0.9977757017660928, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt" + }, + { + "name": "code", + "tok_s": 107.4, + "reps": [ + 98.9, + 111.3, + 112.1 + ], + "hit_rate": 0.9986286196529353, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header row\n and values from the corresponding row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with" + } + ], + "stage_timing": [ + "strata serve: stage 0: 533 windows; per window: wait for the GPU 6.226 ms, pool + plan 0.294 ms, host staging 0.561 ms, commit 0.225 ms", + "strata serve: stage 1: 533 windows; per window: wait for the GPU 14.156 ms, pool + plan 0.373 ms, host staging 0.000 ms, commit 0.371 ms", + "strata serve: stage 0: 599 windows; per window: wait for the GPU 6.314 ms, pool + plan 0.292 ms, host staging 0.501 ms, commit 0.225 ms", + "strata serve: stage 1: 599 windows; per window: wait for the GPU 14.366 ms, pool + plan 0.375 ms, host staging 0.000 ms, commit 0.374 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 19)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (3797 hits / 3836 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3814 hits / 3837 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (28659 hits / 28795 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3814 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (141378 hits / 142508 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (124963 hits / 125273 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (134574 hits / 134874 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (121132 hits / 122322 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (114073 hits / 114235 lookups)", + "strata serve: decode expert cache hit rate: 99.9% (113598 hits / 113754 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json new file mode 100644 index 00000000..494c08bf --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k20.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k20", + "extra": [ + "--layer-split", + "20" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9044.3, + "pp_tok_s": 1776.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13928.7, + "pp_tok_s": 1991.8, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3743.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 76.4, + "reps": [ + 74.2, + 78.4, + 76.7 + ], + "hit_rate": 0.9979911611088791, + "text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry it from the bedrock, and it howled through the narrow slits of the lantern room glass.\n\nElias Thorne was seventy years old, but he moved with the grace of a man who had spent fifty years listening to the sea. He knew the rhythm of the waves against the rocks below\u2014the *thud, thud, crash*\u2014and he knew when that rhythm changed. When the sea grew too quiet, or too violent, he knew a storm was coming, or a ship was in trouble.\n\nTonight, the storm was a Category 4. The rain lashed against the windows like gravel thrown by a giant. Elias stood in the center of the lantern room, his hand resting on the cold brass railing. He wasn\u2019t afraid. He was a guardian.\n\nHe checked the clockwork mechanism. It was old, a relic from 1" + }, + { + "name": "code", + "tok_s": 105.9, + "reps": [ + 103.2, + 106.8, + 107.7 + ], + "hit_rate": 0.9981849807154201, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 537 windows; per window: wait for the GPU 6.685 ms, pool + plan 0.403 ms, host staging 0.593 ms, commit 0.215 ms", + "strata serve: stage 1: 537 windows; per window: wait for the GPU 13.928 ms, pool + plan 0.282 ms, host staging 0.000 ms, commit 0.359 ms", + "strata serve: stage 0: 606 windows; per window: wait for the GPU 6.764 ms, pool + plan 0.399 ms, host staging 0.528 ms, commit 0.216 ms", + "strata serve: stage 1: 606 windows; per window: wait for the GPU 14.108 ms, pool + plan 0.288 ms, host staging 0.000 ms, commit 0.362 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 20)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 7142 slots (14.14 GiB), 7142 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.9% (6162 hits / 6230 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (3803 hits / 3835 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3810 hits / 3836 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27185 hits / 27330 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (3807 hits / 3835 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (139825 hits / 140938 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (142122 hits / 142524 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (146556 hits / 146851 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (118026 hits / 119233 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118729 hits / 118997 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118791 hits / 119007 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json new file mode 100644 index 00000000..8e7bcc90 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k21.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k21", + "extra": [ + "--layer-split", + "21" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8880.5, + "pp_tok_s": 1809.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13654.6, + "pp_tok_s": 2031.8, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3680.6, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 77.4, + "reps": [ + 80.2, + 80.8, + 71.2 + ], + "hit_rate": 0.9973622550922132, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, ensuring the rotation was smooth, silent, and steady. *Tick. Tick. Tick.* The sound was the heartbeat of the coast.\n\n" + }, + { + "name": "code", + "tok_s": 106.7, + "reps": [ + 100.6, + 110.5, + 109.0 + ], + "hit_rate": 0.998218711927068, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 527 windows; per window: wait for the GPU 6.934 ms, pool + plan 0.620 ms, host staging 0.530 ms, commit 0.245 ms", + "strata serve: stage 1: 527 windows; per window: wait for the GPU 13.912 ms, pool + plan 0.365 ms, host staging 0.000 ms, commit 0.359 ms", + "strata serve: stage 0: 595 windows; per window: wait for the GPU 7.031 ms, pool + plan 0.595 ms, host staging 0.472 ms, commit 0.245 ms", + "strata serve: stage 1: 595 windows; per window: wait for the GPU 14.051 ms, pool + plan 0.361 ms, host staging 0.000 ms, commit 0.361 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 21)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4627 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 21-47, expert cache 6912 slots (13.78 GiB), 6912 of its 6912 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-20", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-20 (CUDA0), 21-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.7% (5672 hits / 5748 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4287 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (29024 hits / 29229 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4316 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (131499 hits / 133085 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (130974 hits / 131451 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (138767 hits / 139134 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (121454 hits / 122932 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (116809 hits / 117079 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (118803 hits / 119015 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json new file mode 100644 index 00000000..e139ea5b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k22.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k22", + "extra": [ + "--layer-split", + "22" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8730.9, + "pp_tok_s": 1840.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13375.4, + "pp_tok_s": 2074.2, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3611.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 80.2, + "reps": [ + 78.4, + 80.9, + 81.5 + ], + "hit_rate": 0.9977764197412695, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a small, drafty cottage on the mainland, waiting for the day when the sea would finally claim him.\n\nTonight, the storm was a Category 4. The waves weren\u2019t just crashing; they were climbing. They reached the gallery railing, ten feet above the base of the tower, spraying a fine mist of brine that coated Elias\u2019s glasses.\n\nHe climbed the spiral stairs, his knees protesting with every step. The iron steps were cold, slick with condensation. At the top, in the lantern room, the air was thin and sharp. The great Fresnel lens, a cathedral of glass and brass, stood silent. It was time to wake it.\n\n" + }, + { + "name": "code", + "tok_s": 106.4, + "reps": [ + 100.7, + 110.3, + 108.1 + ], + "hit_rate": 0.9971798370756316, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 529 windows; per window: wait for the GPU 7.229 ms, pool + plan 0.561 ms, host staging 0.529 ms, commit 0.233 ms", + "strata serve: stage 1: 529 windows; per window: wait for the GPU 13.058 ms, pool + plan 0.253 ms, host staging 0.000 ms, commit 0.334 ms", + "strata serve: stage 0: 598 windows; per window: wait for the GPU 7.325 ms, pool + plan 0.552 ms, host staging 0.469 ms, commit 0.235 ms", + "strata serve: stage 1: 598 windows; per window: wait for the GPU 13.238 ms, pool + plan 0.260 ms, host staging 0.000 ms, commit 0.337 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (27008 hits / 27289 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (4260 hits / 4313 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (135183 hits / 137274 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (136132 hits / 136708 lookups)", + "strata serve: decode expert cache hit rate: 99.8% (135515 hits / 135817 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (121287 hits / 123280 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (117658 hits / 118026 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (120574 hits / 120915 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json new file mode 100644 index 00000000..b0b58277 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k23.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k23", + "extra": [ + "--layer-split", + "23" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8742.6, + "pp_tok_s": 1837.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13084.2, + "pp_tok_s": 2120.3, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3566.1, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 81.0, + "reps": [ + 76.8, + 85.2, + 81.1 + ], + "hit_rate": 0.9961302681992337, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, swallowing the horizon, throwing white foam against the granite base like a tantrum.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his wool trousers, the fabric stiff with salt and grease. He checked the clockwork mechanism that turned the lens. It was a beast of a thing, a Fresnel lens of eight feet in diameter, a cathedral of glass and crystal that focused the beam of the lamp into a single, piercing needle of light.\n\nHe wound the weights. *Click, click, click.* The gears engaged. The massive lens began its slow, hypnotic rotation.\n\nFor a moment, the" + }, + { + "name": "code", + "tok_s": 108.4, + "reps": [ + 105.1, + 109.0, + 111.1 + ], + "hit_rate": 0.9961698810290479, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 537 windows; per window: wait for the GPU 7.423 ms, pool + plan 0.953 ms, host staging 0.542 ms, commit 0.237 ms", + "strata serve: stage 1: 537 windows; per window: wait for the GPU 12.223 ms, pool + plan 0.236 ms, host staging 0.000 ms, commit 0.324 ms", + "strata serve: stage 0: 606 windows; per window: wait for the GPU 7.519 ms, pool + plan 0.904 ms, host staging 0.483 ms, commit 0.239 ms", + "strata serve: stage 1: 606 windows; per window: wait for the GPU 12.395 ms, pool + plan 0.242 ms, host staging 0.000 ms, commit 0.326 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 23)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4609 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-22", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-22 (CUDA0), 23-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 96.8% (5528 hits / 5709 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (4235 hits / 4303 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4260 hits / 4308 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (30643 hits / 31089 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (4248 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 98.3% (134776 hits / 137143 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (133024 hits / 133766 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (129995 hits / 130500 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (115782 hits / 118287 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (117953 hits / 118464 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (117560 hits / 118012 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json new file mode 100644 index 00000000..0d5baf64 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k24.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k24", + "extra": [ + "--layer-split", + "24" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8122.5, + "pp_tok_s": 1978.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12285.8, + "pp_tok_s": 2258.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3407.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.5, + "reps": [ + 84.9, + 83.3, + 82.3 + ], + "hit_rate": 0.9949381327334084, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was not merely a keeper; he was a guardian of silence.\n\nHe checked the clock. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced hand, he engaged the brake on the clockwork mechanism. The heavy brass gears groaned, then began their slow, rhythmic turn. *Tick. Tick. Tick.* It was a heartbeat" + }, + { + "name": "code", + "tok_s": 109.5, + "reps": [ + 104.9, + 111.0, + 112.6 + ], + "hit_rate": 0.9953796671318199, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 519 windows; per window: wait for the GPU 7.835 ms, pool + plan 0.767 ms, host staging 0.557 ms, commit 0.244 ms", + "strata serve: stage 1: 519 windows; per window: wait for the GPU 11.922 ms, pool + plan 0.232 ms, host staging 0.000 ms, commit 0.325 ms", + "strata serve: stage 0: 587 windows; per window: wait for the GPU 7.943 ms, pool + plan 0.744 ms, host staging 0.497 ms, commit 0.246 ms", + "strata serve: stage 1: 587 windows; per window: wait for the GPU 12.073 ms, pool + plan 0.238 ms, host staging 0.000 ms, commit 0.326 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-23", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 95.9% (5916 hits / 6171 lookups)", + "strata serve: decode expert cache hit rate: 97.4% (3717 hits / 3815 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (3761 hits / 3823 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (27138 hits / 27664 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (3742 hits / 3826 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (126114 hits / 128875 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (133626 hits / 134658 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (132675 hits / 133350 lookups)", + "strata serve: decode expert cache hit rate: 96.8% (113593 hits / 117399 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (118372 hits / 118949 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (116981 hits / 117524 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json new file mode 100644 index 00000000..a7b95c13 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k26.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k26", + "extra": [ + "--layer-split", + "26" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 7880.9, + "pp_tok_s": 2038.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 11771.9, + "pp_tok_s": 2356.7, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3323.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 231.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.8, + "reps": [ + 85.9, + 83.1, + 82.4 + ], + "hit_rate": 0.9933966961830739, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and green.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined Elias\u2019s life for thirty years. He was a keeper of the light, but more importantly, he was a keeper of time.\n\nHe checked his pocket watch. 11:42 PM. The rotation of the great Fresnel lens was due. With a practiced, rhythmic *clunk-clunk-clunk*, he wound the clockwork mechanism. The massive lens began its slow, hypnotic turn, sweeping its beam across" + }, + { + "name": "code", + "tok_s": 109.7, + "reps": [ + 104.4, + 112.7, + 111.9 + ], + "hit_rate": 0.9938670271352759, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 519 windows; per window: wait for the GPU 8.376 ms, pool + plan 1.030 ms, host staging 0.566 ms, commit 0.273 ms", + "strata serve: stage 1: 519 windows; per window: wait for the GPU 10.886 ms, pool + plan 0.214 ms, host staging 0.000 ms, commit 0.297 ms", + "strata serve: stage 0: 588 windows; per window: wait for the GPU 8.506 ms, pool + plan 0.985 ms, host staging 0.505 ms, commit 0.274 ms", + "strata serve: stage 1: 588 windows; per window: wait for the GPU 11.036 ms, pool + plan 0.219 ms, host staging 0.000 ms, commit 0.298 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 26)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4568 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 26-47, expert cache 5632 slots (11.32 GiB), 5632 of its 5632 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-25", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-25 (CUDA0), 26-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 92.8% (5259 hits / 5665 lookups)", + "strata serve: decode expert cache hit rate: 95.2% (4056 hits / 4259 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (4164 hits / 4285 lookups)", + "strata serve: decode expert cache hit rate: 97.1% (27690 hits / 28510 lookups)", + "strata serve: decode expert cache hit rate: 97.5% (4184 hits / 4293 lookups)", + "strata serve: decode expert cache hit rate: 96.9% (121839 hits / 125724 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (132165 hits / 133648 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (137652 hits / 138567 lookups)", + "strata serve: decode expert cache hit rate: 95.3% (111307 hits / 116822 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (118436 hits / 119329 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (119109 hits / 119844 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json new file mode 100644 index 00000000..8e811202 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k28.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k28", + "extra": [ + "--layer-split", + "28" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 7989.3, + "pp_tok_s": 2010.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12132.9, + "pp_tok_s": 2286.6, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3433.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 228.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.5, + "reps": [ + 83.7, + 82.4, + 84.5 + ], + "hit_rate": 0.9900441970361987, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His knees ached, not from age, but from the constant vibration of the floor beneath his feet. He reached the lantern room, the heart of the lighthouse, and checked the clockwork mechanism. The great lens, a prism of Fresnel glass, rotated with a steady, hypnotic *whirrr-click, whirrr-click*. It was the only sound that mattered. The light swept out into the black void, cutting through" + }, + { + "name": "code", + "tok_s": 112.5, + "reps": [ + 101.4, + 112.1, + 124.1 + ], + "hit_rate": 0.9896636587366694, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n```<|im_end|>" + } + ], + "stage_timing": [ + "strata serve: stage 0: 527 windows; per window: wait for the GPU 8.765 ms, pool + plan 1.401 ms, host staging 0.593 ms, commit 0.281 ms", + "strata serve: stage 1: 527 windows; per window: wait for the GPU 9.893 ms, pool + plan 0.195 ms, host staging 0.000 ms, commit 0.276 ms", + "strata serve: stage 0: 578 windows; per window: wait for the GPU 8.908 ms, pool + plan 1.359 ms, host staging 0.559 ms, commit 0.284 ms", + "strata serve: stage 1: 578 windows; per window: wait for the GPU 10.025 ms, pool + plan 0.200 ms, host staging 0.000 ms, commit 0.278 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 28)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4537 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 28-47, expert cache 5120 slots (10.30 GiB), 5120 of its 5120 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-27", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-27 (CUDA0), 28-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 88.8% (5405 hits / 6086 lookups)", + "strata serve: decode expert cache hit rate: 93.8% (3539 hits / 3773 lookups)", + "strata serve: decode expert cache hit rate: 94.2% (3560 hits / 3781 lookups)", + "strata serve: decode expert cache hit rate: 95.7% (26702 hits / 27899 lookups)", + "strata serve: decode expert cache hit rate: 95.9% (3647 hits / 3804 lookups)", + "strata serve: decode expert cache hit rate: 95.7% (122618 hits / 128160 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (135035 hits / 136884 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (129476 hits / 130778 lookups)", + "strata serve: decode expert cache hit rate: 93.9% (111037 hits / 118290 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (118829 hits / 120140 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (90480 hits / 91425 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json new file mode 100644 index 00000000..8ce08cd4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k30.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k30", + "extra": [ + "--layer-split", + "30" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8301.3, + "pp_tok_s": 1935.4, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 12507.6, + "pp_tok_s": 2218.1, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3448.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 229.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 81.1, + "reps": [ + 78.0, + 84.4, + 81.0 + ], + "hit_rate": 0.9798126997277784, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, the glass was vibrating like a plucked cello string. The sea, usually a rhythmic pulse against the granite base, was now a chaotic, frothing beast, throwing itself against the rocks with the force of a battering ram.\n\nElias stood at the top of the spiral staircase, his hand resting on the cold iron railing. He was not afraid. Fear was for the tourists who came in summer, wide-eyed and clutching their cameras. Elias was a keeper. He was a guardian.\n\nHe checked the logbook. The entry for the night was simple: *Wind, 60 knots. Visibility, zero. Light, operational.*\n\nHe walked down the stairs, his boots heavy on the metal grating. The smell of salt" + }, + { + "name": "code", + "tok_s": 109.6, + "reps": [ + 100.7, + 114.1, + 114.1 + ], + "hit_rate": 0.9825370343977666, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 540 windows; per window: wait for the GPU 9.206 ms, pool + plan 1.794 ms, host staging 0.525 ms, commit 0.298 ms", + "strata serve: stage 1: 540 windows; per window: wait for the GPU 8.767 ms, pool + plan 0.173 ms, host staging 0.000 ms, commit 0.242 ms", + "strata serve: stage 0: 608 windows; per window: wait for the GPU 9.390 ms, pool + plan 1.733 ms, host staging 0.471 ms, commit 0.301 ms", + "strata serve: stage 1: 608 windows; per window: wait for the GPU 8.910 ms, pool + plan 0.178 ms, host staging 0.000 ms, commit 0.244 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 30)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4479 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 30-47, expert cache 4608 slots (9.19 GiB), 4608 of its 4608 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-29", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 84.6% (5099 hits / 6028 lookups)", + "strata serve: decode expert cache hit rate: 90.7% (3403 hits / 3751 lookups)", + "strata serve: decode expert cache hit rate: 91.1% (3415 hits / 3747 lookups)", + "strata serve: decode expert cache hit rate: 94.1% (26108 hits / 27737 lookups)", + "strata serve: decode expert cache hit rate: 93.4% (3534 hits / 3784 lookups)", + "strata serve: decode expert cache hit rate: 94.6% (127532 hits / 134866 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (135828 hits / 137786 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (132455 hits / 135184 lookups)", + "strata serve: decode expert cache hit rate: 91.0% (106351 hits / 116917 lookups)", + "strata serve: decode expert cache hit rate: 97.9% (115791 hits / 118246 lookups)", + "strata serve: decode expert cache hit rate: 98.3% (117198 hits / 119281 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json new file mode 100644 index 00000000..bf239857 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-k32.json @@ -0,0 +1,85 @@ +{ + "label": "ks-k32", + "extra": [ + "--layer-split", + "32" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 8837.1, + "pp_tok_s": 1818.0, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13449.8, + "pp_tok_s": 2062.7, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3565.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 227.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.0, + "reps": [ + 75.0, + 86.1, + 87.8 + ], + "hit_rate": 0.9796934433020751, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 108.7, + "reps": [ + 98.8, + 112.2, + 115.1 + ], + "hit_rate": 0.9777186846317358, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 533 windows; per window: wait for the GPU 9.839 ms, pool + plan 2.192 ms, host staging 0.585 ms, commit 0.318 ms", + "strata serve: stage 1: 533 windows; per window: wait for the GPU 8.014 ms, pool + plan 0.156 ms, host staging 0.000 ms, commit 0.231 ms", + "strata serve: stage 0: 602 windows; per window: wait for the GPU 10.014 ms, pool + plan 2.111 ms, host staging 0.520 ms, commit 0.321 ms", + "strata serve: stage 1: 602 windows; per window: wait for the GPU 8.094 ms, pool + plan 0.160 ms, host staging 0.000 ms, commit 0.232 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 32)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4488 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 32-47, expert cache 4096 slots (8.26 GiB), 4096 of its 4096 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-31", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-31 (CUDA0), 32-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 81.3% (4889 hits / 6010 lookups)", + "strata serve: decode expert cache hit rate: 87.7% (3272 hits / 3733 lookups)", + "strata serve: decode expert cache hit rate: 87.9% (3280 hits / 3733 lookups)", + "strata serve: decode expert cache hit rate: 92.3% (24238 hits / 26254 lookups)", + "strata serve: decode expert cache hit rate: 91.5% (3457 hits / 3778 lookups)", + "strata serve: decode expert cache hit rate: 93.7% (133254 hits / 142240 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (130112 hits / 132812 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (130069 hits / 132765 lookups)", + "strata serve: decode expert cache hit rate: 89.1% (105263 hits / 118190 lookups)", + "strata serve: decode expert cache hit rate: 97.2% (116970 hits / 120309 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (115450 hits / 118081 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-single.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-single.json new file mode 100644 index 00000000..d4fe9d7c --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-ks-single.json @@ -0,0 +1,76 @@ +{ + "label": "ks-single", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9310.4, + "pp_tok_s": 1725.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14085.4, + "pp_tok_s": 1969.6, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3388.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 200.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 86.7, + "reps": [ + 78.2, + 91.4, + 90.4 + ], + "hit_rate": 0.921882148773369, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and his hands were a map of the coastline he had guarded for fifty years. The knuckles were swollen, the skin cracked like dry earth, but they moved with a precision that no machine could replicate.\n\nHe stood on the gallery of the *Harrow Point* lighthouse, the iron railing cold against his palms. Below, the Atlantic churned in a frenzy, whitecaps exploding against the black rocks like fireworks. Above, the sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen.\n\nElias checked the clock. 11:42 PM. The light was due.\n\nHe didn\u2019t look at the gauge. He didn\u2019t check the fuel levels. He knew. He always knew. The rhythm of the ocean, the pressure of the air, the subtle vibration" + }, + { + "name": "code", + "tok_s": 105.2, + "reps": [ + 87.8, + 113.5, + 114.2 + ], + "hit_rate": 0.9109811738648947, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 382 windows; per window: wait for the GPU 15.155 ms, pool + plan 4.331 ms, host staging 0.656 ms, commit 0.458 ms", + "strata serve: stage 0: 455 windows; per window: wait for the GPU 15.790 ms, pool + plan 5.552 ms, host staging 0.688 ms, commit 0.467 ms", + "strata serve: stage 0: 524 windows; per window: wait for the GPU 16.064 ms, pool + plan 5.529 ms, host staging 0.606 ms, commit 0.472 ms", + "strata serve: stage 0: 593 windows; per window: wait for the GPU 16.305 ms, pool + plan 5.462 ms, host staging 0.540 ms, commit 0.475 ms" + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 67.8% (2299 hits / 3391 lookups)", + "strata serve: decode expert cache hit rate: 68.5% (2345 hits / 3424 lookups)", + "strata serve: decode expert cache hit rate: 75.6% (16605 hits / 21959 lookups)", + "strata serve: decode expert cache hit rate: 73.3% (2608 hits / 3558 lookups)", + "strata serve: decode expert cache hit rate: 83.7% (104878 hits / 125346 lookups)", + "strata serve: decode expert cache hit rate: 92.7% (119739 hits / 129184 lookups)", + "strata serve: decode expert cache hit rate: 92.2% (116867 hits / 126770 lookups)", + "strata serve: decode expert cache hit rate: 68.1% (64111 hits / 94116 lookups)", + "strata serve: decode expert cache hit rate: 89.0% (96370 hits / 108259 lookups)", + "strata serve: decode expert cache hit rate: 91.1% (102827 hits / 112875 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json new file mode 100644 index 00000000..e0783846 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-rel-5080.json @@ -0,0 +1,72 @@ +{ + "label": "rel-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2132.8, + "pp_tok_s": 1278.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5008.9, + "pp_tok_s": 1672.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7855.4, + "pp_tok_s": 2045.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13833.9, + "pp_tok_s": 2005.4, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3298.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.9, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.2, + "hit_rate": 0.8418683557684931, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. *Click. Click. Click.* The gears engaged, and the massive Fresnel lens began its slow" + }, + { + "name": "code", + "tok_s": 88.2, + "hit_rate": 0.7011385968111186, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 72.5% (2539 hits / 3504 lookups)", + "strata serve: decode expert cache hit rate: 77.3% (2817 hits / 3642 lookups)", + "strata serve: decode expert cache hit rate: 75.3% (16500 hits / 21916 lookups)", + "strata serve: decode expert cache hit rate: 80.0% (2978 hits / 3723 lookups)", + "strata serve: decode expert cache hit rate: 84.2% (98752 hits / 117301 lookups)", + "strata serve: decode expert cache hit rate: 70.1% (69215 hits / 98718 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json new file mode 100644 index 00000000..a339822f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-t75-5080.json @@ -0,0 +1,78 @@ +{ + "label": "t75-5080", + "extra": [], + "gpus": "0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2158.8, + "pp_tok_s": 1262.7, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5060.0, + "pp_tok_s": 1655.9, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3389.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 213.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 80.4, + "reps": [ + 80.4 + ], + "hit_rate": 0.855538332528651, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning black void, punctuated by whitecaps that looked like teeth.\n\nHe climbed the spiral stairs, his boots heavy with salt and exhaustion. The iron steps groaned under his weight, a sound that had become so familiar to him that he could sleep to it. But tonight, he wasn\u2019t sleeping. He was working.\n\nThe lens was the heart of the lighthouse. A massive, rotating Fresnel lens, a cathedral of glass and brass that turned with a mechanical hum. Elias checked the clockwork mechanism. It was smooth, rhythmic, a heartbeat in the dark. But the light itself was failing.\n\nHe climbed higher, into the lantern room. The wind battered the glass panes," + }, + { + "name": "code", + "tok_s": 87.5, + "reps": [ + 87.5 + ], + "hit_rate": 0.7075461363025227, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 39 windows; per window: wait for the GPU 17.252 ms, pool + plan 8.473 ms, host staging 0.611 ms, commit 0.525 ms", + "strata serve: stage 0: 47 windows; per window: wait for the GPU 18.018 ms, pool + plan 8.616 ms, host staging 0.607 ms, commit 0.534 ms", + "strata serve: stage 0: 169 windows; per window: wait for the GPU 15.223 ms, pool + plan 5.717 ms, host staging 0.688 ms, commit 0.467 ms", + "strata serve: stage 0: 243 windows; per window: wait for the GPU 16.500 ms, pool + plan 7.316 ms, host staging 0.742 ms, commit 0.481 ms" + ], + "engine_lines": [ + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4294 slots, 8.18 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)", + "strata serve: decode expert cache hit rate: 74.4% (2660 hits / 3573 lookups)", + "strata serve: decode expert cache hit rate: 83.4% (92664 hits / 111086 lookups)", + "strata serve: decode expert cache hit rate: 72.0% (70946 hits / 98601 lookups)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: the prompt path borrows 2343 cache slots (4.42 GiB)", + "strata serve: decode expert cache hit rate: 59.6% (2749 hits / 4610 lookups)", + "strata serve: decode expert cache hit rate: 64.2% (2136 hits / 3329 lookups)", + "strata serve: decode expert cache hit rate: 67.3% (2309 hits / 3432 lookups)", + "strata serve: decode expert cache hit rate: 75.5% (16316 hits / 21602 lookups)", + "strata serve: decode expert cache hit rate: 74.4% (2659 hits / 3572 lookups)", + "strata serve: decode expert cache hit rate: 85.6% (101004 hits / 118059 lookups)", + "strata serve: decode expert cache hit rate: 70.8% (71044 hits / 100409 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json new file mode 100644 index 00000000..4b02eecb --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2-auto.json @@ -0,0 +1,103 @@ +{ + "label": "v-x2-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2577.0, + "pp_tok_s": 1057.8, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 4433.5, + "pp_tok_s": 1889.9, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7885.8, + "pp_tok_s": 2037.3, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13384.6, + "pp_tok_s": 2072.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3667.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 253.8, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 79.5, + "reps": [ + 78.9, + 79.0, + 80.7 + ], + "hit_rate": 0.9969903443250137, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching against his stubble. Outside the thick, salt-crusted glass of the lantern room, the Atlantic was a churning cauldron of black and white foam. Rain lashed against the panes in horizontal sheets, blurring the world into a smear of gray and shadow.\n\nInside, however, it was warm. The smell of kerosene and old wood hung heavy in the air, a scent that had defined his life for thirty years.\n\nElias was not a man of many words. He was a man of many tasks. His hands, mapped with scars from rope burns and broken glass, moved with a rhythm that predated his memory. He checked the clockwork mechanism of the Fresnel lens, listening for the faint, rhythmic *tick-tick-tick* that signaled the rotation was true. If the rhythm faltered, ships" + }, + { + "name": "code", + "tok_s": 108.9, + "reps": [ + 103.3, + 113.7, + 109.5 + ], + "hit_rate": 0.9971795386830036, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 542 windows; per window: wait for the GPU 7.167 ms, pool + plan 0.572 ms, host staging 0.550 ms, commit 0.232 ms", + "strata serve: stage 1: 542 windows; per window: wait for the GPU 12.855 ms, pool + plan 0.250 ms, host staging 0.000 ms, commit 0.334 ms", + "strata serve: stage 0: 610 windows; per window: wait for the GPU 7.276 ms, pool + plan 0.559 ms, host staging 0.493 ms, commit 0.234 ms", + "strata serve: stage 1: 610 windows; per window: wait for the GPU 13.048 ms, pool + plan 0.258 ms, host staging 0.000 ms, commit 0.337 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22 - predicted 19.7 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (136232 hits / 138256 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (135540 hits / 136216 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (136812 hits / 137225 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (118437 hits / 120406 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (112836 hits / 113230 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json new file mode 100644 index 00000000..786a117f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x2r-auto.json @@ -0,0 +1,88 @@ +{ + "label": "v-x2r-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "2,0", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9610.0, + "pp_tok_s": 1671.8, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 14786.1, + "pp_tok_s": 1876.3, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3850.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 90.3, + "reps": [ + 91.0, + 97.0, + 82.8 + ], + "hit_rate": 0.993905472636816, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak of the spiral staircase, every draft that slipped under the door, and every shift in the barometric pressure that preceded a storm. He was not merely a worker; he was the heartbeat of the coast.\n\nIt was November, the month of grey seas and shorter days. The fog had rolled in thick, a wall of white so dense that even the beam of the Fresnel lens seemed to struggle against it. Elias stood in the lantern room, his hands roughened by salt and rope, adjusting the rotation mechanism. The great lens, a cathedral of glass and brass, began its slow, rhythmic sweep. *Flash. Dark. Flash. Dark.*\n\nHe checked the log" + }, + { + "name": "code", + "tok_s": 105.1, + "reps": [ + 98.4, + 109.9, + 107.0 + ], + "hit_rate": 0.9949900793650793, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 492 windows; per window: wait for the GPU 15.016 ms, pool + plan 0.297 ms, host staging 0.517 ms, commit 0.404 ms", + "strata serve: stage 1: 492 windows; per window: wait for the GPU 5.775 ms, pool + plan 0.854 ms, host staging 0.001 ms, commit 0.210 ms", + "strata serve: stage 0: 561 windows; per window: wait for the GPU 15.257 ms, pool + plan 0.306 ms, host staging 0.455 ms, commit 0.408 ms", + "strata serve: stage 1: 561 windows; per window: wait for the GPU 5.852 ms, pool + plan 0.820 ms, host staging 0.001 ms, commit 0.210 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: CUDA0 82 SMs at 1.86 GHz -> 0.48 ms per layer, 16.45 GiB for experts", + "strata generate: layer split auto: CUDA1 84 SMs at 2.81 GHz -> 0.31 ms per layer, 5.99 GiB for experts", + "strata generate: layer split auto: K=30 - predicted 20.8 ms per decode window; the caches hold 10684 of 12288 profiled pairs (~99.5% of the routed mass)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 7680 slots, 14.23 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 30-47, expert cache 3004 slots (5.98 GiB), 3004 of its 4608 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-29", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-29 (CUDA0), 30-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 93.2% (5367 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 93.7% (4049 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 96.7% (4178 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 97.7% (26272 hits / 26880 lookups)", + "strata serve: decode expert cache hit rate: 97.1% (4194 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (110748 hits / 113280 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (113787 hits / 114240 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (127856 hits / 128640 lookups)", + "strata serve: decode expert cache hit rate: 96.3% (116528 hits / 120960 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (116423 hits / 117120 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (120354 hits / 120960 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json new file mode 100644 index 00000000..70510aef --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-v-x3-auto.json @@ -0,0 +1,89 @@ +{ + "label": "v-x3-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,1,2", + "needles": [ + { + "tokens": 16066, + "prompt_ms": 9525.4, + "pp_tok_s": 1686.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15017.1, + "pp_tok_s": 1847.4, + "found": true, + "answer": "juniper-766<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4039.6, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 360.2, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 67.6, + "reps": [ + 59.8, + 83.1, + 59.9 + ], + "hit_rate": 0.9967581085879247, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with the force of a battering ram. Elias stood in the lantern room, his hands rough as sandpaper, adjusting the massive Fresnel lens. The rotation mechanism groaned, a sound like a ship\u2019s anchor chain being h" + }, + { + "name": "code", + "tok_s": 89.6, + "reps": [ + 81.0, + 104.8, + 83.0 + ], + "hit_rate": 0.9975041387598007, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 2: 522 windows; per window: wait for the GPU 12.405 ms, pool + plan 0.242 ms, host staging 0.006 ms, commit 0.375 ms", + "strata serve: stage 0: 590 windows; per window: wait for the GPU 7.387 ms, pool + plan 0.549 ms, host staging 0.517 ms, commit 0.248 ms", + "strata serve: stage 1: 590 windows; per window: wait for the GPU 3.071 ms, pool + plan 0.011 ms, host staging 0.000 ms, commit 0.606 ms", + "strata serve: stage 2: 590 windows; per window: wait for the GPU 12.592 ms, pool + plan 0.250 ms, host staging 0.006 ms, commit 0.377 ms" + ], + "engine_lines": [ + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session; 16.67 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA2 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: CUDA0 84 SMs at 2.81 GHz -> 0.31 ms per layer, 8.30 GiB for experts", + "strata generate: layer split auto: CUDA1 68 SMs at 1.54 GHz -> 0.69 ms per layer, 13.50 GiB for experts", + "strata generate: layer split auto: CUDA2 82 SMs at 1.86 GHz -> 0.48 ms per layer, 14.14 GiB for experts", + "strata generate: layer split auto: K=22,23 - predicted 19.9 ms per decode window; the caches hold 11298 of 12288 profiled pairs (~99.7% of the routed mass)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-22, expert cache 256 slots (0.52 GiB), 256 of its 256 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-22 (CUDA1), 23-47 (CUDA2), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.7% (4256 hits / 4310 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4278 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (29862 hits / 30170 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4264 hits / 4313 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (134418 hits / 136339 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (116986 hits / 117525 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (129134 hits / 129554 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json new file mode 100644 index 00000000..9bc24c35 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto-c1024.json @@ -0,0 +1,84 @@ +{ + "label": "x2-auto-c1024", + "extra": [ + "--layer-split", + "auto", + "--prefill", + "1024" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2648.7, + "pp_tok_s": 1029.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5547.0, + "pp_tok_s": 1510.5, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10123.3, + "pp_tok_s": 1587.0, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 17652.0, + "pp_tok_s": 1571.7, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4379.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.5, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 82.7, + "hit_rate": 1.0, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "code", + "tok_s": 111.1, + "hit_rate": 1.0, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 12288 of 12288 profiled pairs (fullest device 99%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3613 slots", + "strata generate: expert cache 4864 slots, 8.76 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7424 slots (14.66 GiB), 7424 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 100.0% (5760 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (26400 hits / 26400 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (4320 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (130080 hits / 130080 lookups)", + "strata serve: decode expert cache hit rate: 100.0% (110400 hits / 110400 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json new file mode 100644 index 00000000..280c63ea --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-auto.json @@ -0,0 +1,82 @@ +{ + "label": "x2-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2711.7, + "pp_tok_s": 1005.3, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5010.3, + "pp_tok_s": 1672.4, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 8994.8, + "pp_tok_s": 1786.1, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 15497.2, + "pp_tok_s": 1790.2, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4050.3, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 249.7, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 83.0, + "hit_rate": 0.9920220447608565, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference between a gale and a hurricane by the way the glass rattled in its frame. Tonight, it was the latter. The sea was a churning cauldron of black ink and white foam, throwing itself against the granite base with the force of a battering ram.\n\nInside the lantern room, the air was thick with the smell of kerosene and old brass. Elias wiped his hands on his woolen trousers, leaving faint, oily smears on the fabric. He checked the clock. 11:42 PM. The rotation was due.\n\nHe reached for the crank handle, a heavy iron wheel worn smooth by decades of his own palms. With a grunt that matched the strain of his shoulders, he began to turn it. The massive Fresnel lens, a cathedral of glass and crystal, began its slow, hypnotic sweep" + }, + { + "name": "code", + "tok_s": 101.8, + "hit_rate": 0.991767530342175, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.5% (6141 hits / 6234 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (3797 hits / 3838 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (3804 hits / 3838 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3816 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (3825 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27693 hits / 27832 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (3815 hits / 3839 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (127081 hits / 128103 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (119386 hits / 120377 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json new file mode 100644 index 00000000..cca7bcf6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k16.json @@ -0,0 +1,81 @@ +{ + "label": "x2-k16", + "extra": [ + "--layer-split", + "16" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2987.1, + "pp_tok_s": 912.6, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5908.6, + "pp_tok_s": 1418.1, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10655.8, + "pp_tok_s": 1507.7, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 18484.6, + "pp_tok_s": 1500.9, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4790.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 243.3, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 71.4, + "hit_rate": 0.9814261642156863, + "text": "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry the lighthouse from its bedrock. Inside, however, the air was still, smelling faintly of kerosene and old paper.\n\nElias had been the keeper of the Point for thirty-two years. He knew every creak in the floorboards, every draft that slipped through the window seals, and exactly how much oil the great Fresnel lens needed to turn its slow, hypnotic rotation.\n\nIt was 2:00 AM. The storm was at its peak. The sea was a chaotic black mirror, whipped into whitecaps that looked like jagged teeth.\n\nElias climbed the spiral stairs, his hand gripping the cold iron railing. His boots, heavy with salt and wear, thumped a steady rhythm against the stone. *Thump. Thump. Thump.*\n\nAt the top, the lantern room hummed with the vibration of" + }, + { + "name": "code", + "tok_s": 86.4, + "hit_rate": 0.9798276439089693, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 16)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4096 slots, 7.17 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 16-47, expert cache 7124 slots (14.14 GiB), 7124 of its 8192 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-15", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-15 (CUDA0), 16-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5626 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (4237 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (4269 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4279 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (4298 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (28471 hits / 28800 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4282 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 98.1% (128135 hits / 130560 lookups)", + "strata serve: decode expert cache hit rate: 98.0% (117109 hits / 119520 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json new file mode 100644 index 00000000..765880e9 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2-k22.json @@ -0,0 +1,81 @@ +{ + "label": "x2-k22", + "extra": [ + "--layer-split", + "22" + ], + "gpus": "0,2", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2537.7, + "pp_tok_s": 1074.2, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 4440.0, + "pp_tok_s": 1887.2, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 7872.5, + "pp_tok_s": 2040.8, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 13405.0, + "pp_tok_s": 2069.6, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3610.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.0, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 78.1, + "hit_rate": 0.9851122208995093, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy-three years old, and he had been the keeper of the Blackwood Point Light for forty of those years. The other thirty-three had been spent in a hospital bed, waiting for the end.\n\nEvery night, Elias climbed the one hundred and twelve steps of the spiral staircase. His knees, worn smooth by the friction of his own boots over decades, protested with a sharp ache. He counted them. *One, two, three\u2026* The rhythm was his heartbeat. If he lost the count, he lost the light.\n\nAt the top, the lantern room hummed with the low, electric thrum of the Fresnel lens. It was a cathedral of glass and brass, a machine that had never failed him. Not once. Not in four decades.\n\nHe polished the brass railing with a rag that smelled of lemon and" + }, + { + "name": "code", + "tok_s": 104.3, + "hit_rate": 0.9842543225870746, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 97.7% (5609 hits / 5739 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (4241 hits / 4306 lookups)", + "strata serve: decode expert cache hit rate: 98.9% (4262 hits / 4309 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4290 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4319 lookups)", + "strata serve: decode expert cache hit rate: 98.8% (28379 hits / 28721 lookups)", + "strata serve: decode expert cache hit rate: 99.3% (4285 hits / 4314 lookups)", + "strata serve: decode expert cache hit rate: 98.5% (135713 hits / 137764 lookups)", + "strata serve: decode expert cache hit rate: 98.4% (118518 hits / 120414 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json new file mode 100644 index 00000000..acc5c986 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2r-auto.json @@ -0,0 +1,82 @@ +{ + "label": "x2r-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "2,0", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 2804.2, + "pp_tok_s": 972.1, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 5641.7, + "pp_tok_s": 1485.2, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 10643.4, + "pp_tok_s": 1509.5, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 18363.5, + "pp_tok_s": 1510.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4517.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 78.9, + "hit_rate": 0.9913117283950618, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and ice. Outside the thick glass of the lantern room, the Atlantic was a churning cauldron of black and white, the waves crashing against the granite base with a violence that shook the very foundations of the tower. It was November, 1924, and the storm had been raging for three days.\n\nElias was not a man who feared the dark. He was a man who feared the silence.\n\nHe checked the clock on the wall. 11:42 PM. The rotation of the great Fresnel lens was steady, a rhythmic *whirrr-click, whirrr-click* that seemed to sync with his own heartbeat. He had been doing this for forty years. His hands were mapped with scars from rope burns and broken glass, his eyes permanently squinted against the glare of the bulb." + }, + { + "name": "code", + "tok_s": 93.4, + "hit_rate": 0.990286044973545, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: K=36 - the caches hold 11775 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 8828 slots, 16.45 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 36-47, expert cache 2945 slots (5.99 GiB), 2945 of its 3072 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-35", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-35 (CUDA0), 36-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 98.6% (5678 hits / 5760 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (4283 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.2% (4285 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.6% (4303 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.7% (4306 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.5% (27700 hits / 27840 lookups)", + "strata serve: decode expert cache hit rate: 99.4% (4295 hits / 4320 lookups)", + "strata serve: decode expert cache hit rate: 99.1% (128474 hits / 129600 lookups)", + "strata serve: decode expert cache hit rate: 99.0% (119785 hits / 120960 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json new file mode 100644 index 00000000..9c141116 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x2t-auto.json @@ -0,0 +1,99 @@ +{ + "label": "x2t-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,1", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 4201.1, + "pp_tok_s": 648.9, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 9655.6, + "pp_tok_s": 867.8, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 17573.8, + "pp_tok_s": 914.2, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 30615.6, + "pp_tok_s": 906.2, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 7864.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 366.9, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 45.5, + "reps": [ + 45.5 + ], + "hit_rate": 0.9703345151405784, + "text": "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with salt and age. He was seventy years old, but he moved with the grace of a man who had spent decades on a narrow spiral staircase. His hands, rough as sandpaper, knew every bolt, every lever, and every creak in the iron bones of the tower.\n\nFor forty years, Elias had been the guardian of the Point. Not just of the light, but of the silence between the waves.\n\nIt was November. The sky was a bruised purple, heavy with rain that hadn\u2019t yet fallen. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that shook the floorboards beneath Elias\u2019s boots.\n\nHe climbed the stairs. One hundred and twelve steps. He counted them by feel, his left hand trailing along the cold iron railing. At the top, the air was" + }, + { + "name": "code", + "tok_s": 58.0, + "reps": [ + 58.0 + ], + "hit_rate": 0.9700542735219787, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys from the header and values from the row.\n \n Args:\n filepath: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result: List[Dict[str, Any]] = []\n with open(filepath, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_to_dicts():\n import tempfile\n import os\n \n # Create a temporary CSV file\n with tempfile.NamedTemporaryFile" + } + ], + "stage_timing": [ + "strata serve: stage 0: 168 windows; per window: wait for the GPU 9.683 ms, pool + plan 0.509 ms, host staging 0.714 ms, commit 0.320 ms", + "strata serve: stage 1: 168 windows; per window: wait for the GPU 25.253 ms, pool + plan 0.881 ms, host staging 0.000 ms, commit 0.559 ms", + "strata serve: stage 0: 242 windows; per window: wait for the GPU 9.860 ms, pool + plan 0.550 ms, host staging 0.750 ms, commit 0.328 ms", + "strata serve: stage 1: 242 windows; per window: wait for the GPU 26.029 ms, pool + plan 0.980 ms, host staging 0.000 ms, commit 0.571 ms" + ], + "engine_lines": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA1 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=20 - the caches hold 10761 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 6157 slots (12.19 GiB), 6157 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window", + "strata serve: decode expert cache hit rate: 96.6% (5559 hits / 5754 lookups)", + "strata serve: decode expert cache hit rate: 97.5% (4205 hits / 4315 lookups)", + "strata serve: decode expert cache hit rate: 97.8% (4217 hits / 4312 lookups)", + "strata serve: decode expert cache hit rate: 98.6% (4257 hits / 4318 lookups)" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json new file mode 100644 index 00000000..14cd5a50 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/pp-x3-auto.json @@ -0,0 +1,99 @@ +{ + "label": "x3-auto", + "extra": [ + "--layer-split", + "auto" + ], + "gpus": "0,2,1", + "needles": [ + { + "tokens": 2726, + "prompt_ms": 3657.4, + "pp_tok_s": 745.3, + "found": true, + "answer": "meadow-254<|im_end|>" + }, + { + "tokens": 8379, + "prompt_ms": 7594.1, + "pp_tok_s": 1103.4, + "found": true, + "answer": "juniper-766<|im_end|>" + }, + { + "tokens": 16066, + "prompt_ms": 13996.4, + "pp_tok_s": 1147.9, + "found": true, + "answer": "falcon-174<|im_end|>" + }, + { + "tokens": 27743, + "prompt_ms": 24255.2, + "pp_tok_s": 1143.8, + "found": true, + "answer": "willow-474<|im_end|>" + } + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 6104.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 393.4, + "answer": "lantern-417<|im_end|>", + "ok": true + }, + "decode": [ + { + "name": "story", + "tok_s": 51.9, + "reps": [ + 51.9 + ], + "hit_rate": 1.0, + "text": "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the glass panes like a prisoner shaking its bars.\n\nElias Thorne was seventy years old, and he had been the keeper for forty of them. He knew every creak in the spiral staircase, every draft that slipped under the door, and every shift in the weather that the barometer couldn\u2019t quite predict. He knew that when the fog rolled in thick enough to swallow the horizon, the world ceased to exist. There was only the light, the stone, and him.\n\nIt was November, the month of storms. The sea was a churning cauldron of grey and white, throwing itself against the granite base with a violence that made the floorboards tremble. Elias stood by the lantern room, his hands wrapped around a mug of coffee that had gone cold hours ago. He wasn\u2019t drinking it. He was holding it for warmth." + }, + { + "name": "code", + "tok_s": 69.7, + "reps": [ + 69.7 + ], + "hit_rate": 1.0, + "text": "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"\n Parse a CSV file into a list of dictionaries.\n \n Each dictionary represents a row, with keys being the header values\n and values being the corresponding cell values.\n \n Args:\n file_path: Path to the CSV file.\n \n Returns:\n A list of dictionaries, one per row (excluding the header).\n \"\"\"\n result = []\n with open(file_path, 'r', newline='', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n for row in reader:\n result.append(dict(row))\n return result\n\n\n# Tests\ndef test_parse_csv_basic():\n \"\"\"Test basic CSV parsing with simple data.\"\"\"\n import tempfile\n import os\n \n # Create a temporary CSV" + } + ], + "stage_timing": [ + "strata serve: stage 2: 165 windows; per window: wait for the GPU 13.452 ms, pool + plan 0.162 ms, host staging 0.000 ms, commit 0.328 ms", + "strata serve: stage 0: 234 windows; per window: wait for the GPU 6.235 ms, pool + plan 0.145 ms, host staging 0.704 ms, commit 0.214 ms", + "strata serve: stage 1: 234 windows; per window: wait for the GPU 15.592 ms, pool + plan 0.246 ms, host staging 0.000 ms, commit 0.657 ms", + "strata serve: stage 2: 234 windows; per window: wait for the GPU 13.916 ms, pool + plan 0.177 ms, host staging 0.000 ms, commit 0.335 ms" + ], + "engine_lines": [ + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots", + "strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-11", + "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)", + "strata serve: layer split: layers 0-11 (CUDA0), 12-32 (CUDA1), 33-47 (CUDA2), one hand-off per window", + "strata generate: layer split across 3 GPUs: CUDA0, then CUDA1,2 (split auto)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session; 18.62 GiB free", + "strata generate: layer split: CUDA2 PCIe probe 3.2 GB/s -> pcie_frac 0.00", + "strata generate: layer split: CUDA2 holds its weights, session and head; 16.18 GiB free", + "strata generate: layer split auto: K=12,33 - the caches hold 12288 of 12288 profiled pairs (fullest device 66%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3072 slots", + "strata generate: expert cache 3072 slots, 5.41 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 12-32, expert cache 5376 slots (10.22 GiB), 5376 of its 5376 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA2 runs layers 33-47, expert cache 3840 slots (7.79 GiB), 3840 of its 3840 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-11" + ] +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-layer-split/data/summary-all.json b/engine/strata/bench/results/2026-09-29-layer-split/data/summary-all.json new file mode 100644 index 00000000..75bcd84e --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-layer-split/data/summary-all.json @@ -0,0 +1,1083 @@ +{ + "regression": { + "release_vs_dev_identical": [ + 10, + 10 + ], + "speed_release": { + "greedy story 200": 58.4, + "greedy code 200": 80.6, + "greedy sanity": 75.2, + "greedy, no penalty (sanity)": 74.2, + "greedy presence=100 last_n=64": 48.5, + "greedy presence=100 last_n=64 story": 46.4, + "sampled presence=100 last_n=64 seed 3": 43.3, + "sampled presence=100 last_n=64 seed 11": 49.8, + "greedy frequency=100 last_n=16": 62.5, + "greedy presence=100 last_n=4096 (8-row windows)": 52.6 + }, + "speed_dev": { + "greedy story 200": 59.2, + "greedy code 200": 81.6, + "greedy sanity": 74.9, + "greedy, no penalty (sanity)": 74.3, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 44.9, + "sampled presence=100 last_n=64 seed 3": 44.1, + "sampled presence=100 last_n=64 seed 11": 49.5, + "greedy frequency=100 last_n=16": 65.2, + "greedy presence=100 last_n=4096 (8-row windows)": 52.5 + }, + "dev_vs_same_gpu_split_identical": [ + 10, + 10 + ] + }, + "correctness": { + "reg-rel": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 58.4, + "greedy code 200": 80.6, + "greedy sanity": 75.2, + "greedy, no penalty (sanity)": 74.2, + "greedy presence=100 last_n=64": 48.5, + "greedy presence=100 last_n=64 story": 46.4, + "sampled presence=100 last_n=64 seed 3": 43.3, + "sampled presence=100 last_n=64 seed 11": 49.8, + "greedy frequency=100 last_n=16": 62.5, + "greedy presence=100 last_n=4096 (8-row windows)": 52.6 + } + }, + "reg-dev": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 59.2, + "greedy code 200": 81.6, + "greedy sanity": 74.9, + "greedy, no penalty (sanity)": 74.3, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 44.9, + "sampled presence=100 last_n=64 seed 3": 44.1, + "sampled presence=100 last_n=64 seed 11": 49.5, + "greedy frequency=100 last_n=16": 65.2, + "greedy presence=100 last_n=4096 (8-row windows)": 52.5 + } + }, + "reg-same24": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 58.4, + "greedy code 200": 80.5, + "greedy sanity": 74.5, + "greedy, no penalty (sanity)": 76.8, + "greedy presence=100 last_n=64": 49.6, + "greedy presence=100 last_n=64 story": 46.7, + "sampled presence=100 last_n=64 seed 3": 44.3, + "sampled presence=100 last_n=64 seed 11": 50.0, + "greedy frequency=100 last_n=16": 62.0, + "greedy presence=100 last_n=4096 (8-row windows)": 52.1 + } + }, + "nr-x2-auto": { + "cases": 10, + "repeats": 0, + "sanity_144": true, + "tok_s": { + "greedy story 200": 74.0, + "greedy code 200": 103.4, + "greedy sanity": 91.1, + "greedy, no penalty (sanity)": 70.7, + "greedy presence=100 last_n=64": 65.4, + "greedy presence=100 last_n=64 story": 57.1, + "sampled presence=100 last_n=64 seed 3": 52.9, + "sampled presence=100 last_n=64 seed 11": 51.7, + "greedy frequency=100 last_n=16": 73.5, + "greedy presence=100 last_n=4096 (8-row windows)": 63.4 + } + } + }, + "runs": { + "dev-3090": { + "gpus": "2", + "extra": "", + "pp": [ + [ + 2726, + 796.0, + true + ], + [ + 8379, + 972.3, + true + ], + [ + 16066, + 1253.2, + true + ], + [ + 27743, + 1211.4, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 5657.8, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.7, + "ok": true + }, + "decode": [ + [ + "story", + 71.7, + 0.927 + ], + [ + "code", + 92.9, + 0.864 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict\n\n\ndef parse_csv(filepath: str) -> List[Dict[str, str]]:\n \"\"\"\n P", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 6.4 GB/s host->device -> pcie_frac 0.14 (default 0.55)", + "strata generate: expert cache auto: 17.31 GiB free, 700 MiB reserved -> 6704 slots", + "strata generate: expert cache 8730 slots, 16.62 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "dev-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1279.9, + true + ], + [ + 8379, + 1656.8, + true + ], + [ + 16066, + 2017.2, + true + ], + [ + 27743, + 1974.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3366.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.3, + "ok": true + }, + "decode": [ + [ + "story", + 83.1, + 0.842 + ], + [ + "code", + 88.0, + 0.701 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "ks-k18": { + "gpus": "0,2", + "extra": "--layer-split 18", + "pp": [ + [ + 16066, + 1547.2, + true + ], + [ + 27743, + 1694.5, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4308.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 239.8, + "ok": true + }, + "decode": [ + [ + "story", + 77.2, + 0.999 + ], + [ + "code", + 103.8, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 18)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4608 slots, 8.24 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 18-47, expert cache 7152 slots (14.14 GiB), 7152 of its 7680 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-17", + "strata serve: layer split: layers 0-17 (CUDA0), 18-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k19": { + "gpus": "0,2", + "extra": "--layer-split 19", + "pp": [ + [ + 16066, + 1626.9, + true + ], + [ + 27743, + 1790.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4085.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 238.7, + "ok": true + }, + "decode": [ + [ + "story", + 79.3, + 0.998 + ], + [ + "code", + 107.4, + 0.999 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 19)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k20": { + "gpus": "0,2", + "extra": "--layer-split 20", + "pp": [ + [ + 16066, + 1776.4, + true + ], + [ + 27743, + 1991.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3743.5, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.8, + "ok": true + }, + "decode": [ + [ + "story", + 76.4, + 0.998 + ], + [ + "code", + 105.9, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry it from the bedrock, a", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 20)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 20-47, expert cache 7142 slots (14.14 GiB), 7142 of its 7168 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-19", + "strata serve: layer split: layers 0-19 (CUDA0), 20-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k21": { + "gpus": "0,2", + "extra": "--layer-split 21", + "pp": [ + [ + 16066, + 1809.1, + true + ], + [ + 27743, + 2031.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3680.6, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.4, + "ok": true + }, + "decode": [ + [ + "story", + 77.4, + 0.997 + ], + [ + "code", + 106.7, + 0.998 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching agai", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 21)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4627 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 21-47, expert cache 6912 slots (13.78 GiB), 6912 of its 6912 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-20", + "strata serve: layer split: layers 0-20 (CUDA0), 21-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k22": { + "gpus": "0,2", + "extra": "--layer-split 22", + "pp": [ + [ + 16066, + 1840.1, + true + ], + [ + 27743, + 2074.2, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3611.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.8, + "ok": true + }, + "decode": [ + [ + "story", + 80.2, + 0.998 + ], + [ + "code", + 106.4, + 0.997 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k23": { + "gpus": "0,2", + "extra": "--layer-split 23", + "pp": [ + [ + 16066, + 1837.7, + true + ], + [ + 27743, + 2120.3, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3566.1, + "turn2_tokens": 6660, + "reused": 6631, + "turn2_ms": 238.0, + "ok": true + }, + "decode": [ + [ + "story", + 81.0, + 0.996 + ], + [ + "code", + 108.4, + 0.996 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 23)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4609 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 23-47, expert cache 6400 slots (12.82 GiB), 6400 of its 6400 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-22", + "strata serve: layer split: layers 0-22 (CUDA0), 23-47 (CUDA1), one hand-off per window" + ] + }, + "ks-k24": { + "gpus": "0,2", + "extra": "--layer-split 24", + "pp": [ + [ + 16066, + 1978.0, + true + ], + [ + 27743, + 2258.1, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3407.0, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 234.0, + "ok": true + }, + "decode": [ + [ + "story", + 83.5, + 0.995 + ], + [ + "code", + 109.5, + 0.995 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the rough fabric scratching agai", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 24)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4603 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 24-47, expert cache 6144 slots (12.35 GiB), 6144 of its 6144 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-23", + "strata serve: layer split: layers 0-23 (CUDA0), 24-47 (CUDA1), one hand-off per window" + ] + }, + "ks-single": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 16066, + 1725.6, + true + ], + [ + 27743, + 1969.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3388.7, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 200.7, + "ok": true + }, + "decode": [ + [ + "story", + 86.7, + 0.922 + ], + [ + "code", + 105.2, + 0.911 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "rel-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1278.1, + true + ], + [ + 8379, + 1672.8, + true + ], + [ + 16066, + 2045.2, + true + ], + [ + 27743, + 2005.4, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3298.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 197.9, + "ok": true + }, + "decode": [ + [ + "story", + 83.2, + 0.842 + ], + [ + "code", + 88.2, + 0.701 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4293 slots, 8.17 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "t75-5080": { + "gpus": "0", + "extra": "", + "pp": [ + [ + 2726, + 1262.9, + true + ], + [ + 8379, + 1658.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3385.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 212.5, + "ok": true + }, + "decode": [ + [ + "story", + 86.7, + 0.834 + ], + [ + "code", + 90.1, + 0.72 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>" + ], + "engine": [ + "strata generate: PCIe probe: 57.8 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: expert cache auto: 9.15 GiB free, 700 MiB reserved -> 3415 slots", + "strata generate: expert cache 4294 slots, 8.18 GiB of VRAM; policy is", + "strata serve: prompt chunk auto: 8192 tokens" + ] + }, + "x2-auto-c1024": { + "gpus": "0,2", + "extra": "--layer-split auto --prefill 1024", + "pp": [ + [ + 2726, + 1029.2, + true + ], + [ + 8379, + 1510.5, + true + ], + [ + 16066, + 1587.0, + true + ], + [ + 27743, + 1571.7, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4379.9, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 235.5, + "ok": true + }, + "decode": [ + [ + "story", + 82.7, + 1.0 + ], + [ + "code", + 111.1, + 1.0 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It tore through the iron gallery of the Blackwood Point Lighthouse, rattling the", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv(file_path: str) -> List[Dict[str, Any]]:\n \"\"\"", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 57.8 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 12288 of 12288 profiled pairs (fullest device 99%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3613 slots", + "strata generate: expert cache 4864 slots, 8.76 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7424 slots (14.66 GiB), 7424 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "x2-auto": { + "gpus": "0,2", + "extra": "--layer-split auto", + "pp": [ + [ + 2726, + 1005.3, + true + ], + [ + 8379, + 1672.4, + true + ], + [ + 16066, + 1786.1, + true + ], + [ + 27743, + 1790.2, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4050.3, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 249.7, + "ok": true + }, + "decode": [ + [ + "story", + 83.0, + 0.992 + ], + [ + "code", + 101.8, + 0.992 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias had lived in the tower for thirty years, and he knew the difference betwe", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4606 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 19-47, expert cache 7160 slots (14.14 GiB), 7160 of its 7424 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-18", + "strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window" + ] + }, + "x2-k16": { + "gpus": "0,2", + "extra": "--layer-split 16", + "pp": [ + [ + 2726, + 912.6, + true + ], + [ + 8379, + 1418.1, + true + ], + [ + 16066, + 1507.7, + true + ], + [ + 27743, + 1500.9, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4790.8, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 243.3, + "ok": true + }, + "decode": [ + [ + "story", + 71.4, + 0.981 + ], + [ + "code", + 86.4, + 0.98 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed. It clawed at the granite base of the tower, trying to pry the lighthouse from it", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 16)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4096 slots, 7.17 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 16-47, expert cache 7124 slots (14.14 GiB), 7124 of its 8192 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-15", + "strata serve: layer split: layers 0-15 (CUDA0), 16-47 (CUDA1), one hand-off per window" + ] + }, + "x2-k22": { + "gpus": "0,2", + "extra": "--layer-split 22", + "pp": [ + [ + 2726, + 1074.2, + true + ], + [ + 8379, + 1887.2, + true + ], + [ + 16066, + 2040.8, + true + ], + [ + 27743, + 2069.6, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 3610.4, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 236.0, + "ok": true + }, + "decode": [ + [ + "story", + 78.1, + 0.985 + ], + [ + "code", + 104.3, + 0.984 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his wool coat tighter around his shoulders, the fabric stiff with ", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split 22)", + "strata generate: PCIe probe: 57.7 GB/s host->device -> pcie_frac 0.55 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 6.4 GB/s -> pcie_frac 0.14", + "strata generate: layer split: CUDA1 holds its weights, session and head; 18.13 GiB free", + "strata generate: expert cache auto: 10.46 GiB free, 700 MiB reserved -> 3345 slots", + "strata generate: expert cache 4640 slots, 8.29 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 22-47, expert cache 6656 slots (13.34 GiB), 6656 of its 6656 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-21", + "strata serve: layer split: layers 0-21 (CUDA0), 22-47 (CUDA1), one hand-off per window" + ] + }, + "x2r-auto": { + "gpus": "2,0", + "extra": "--layer-split auto", + "pp": [ + [ + 2726, + 972.1, + true + ], + [ + 8379, + 1485.2, + true + ], + [ + 16066, + 1509.5, + true + ], + [ + 27743, + 1510.8, + true + ] + ], + "chat": { + "turn1_tokens": 6584, + "turn1_ms": 4517.2, + "turn2_tokens": 6660, + "reused": 6632, + "turn2_ms": 245.6, + "ok": true + }, + "decode": [ + [ + "story", + 78.9, + 0.991 + ], + [ + "code", + 93.4, + 0.99 + ] + ], + "texts": [ + "The wind didn\u2019t just blow; it screamed.\n\nElias pulled his woolen collar up to his chin, the fabric stiff with salt and i", + "```python\nimport csv\nfrom typing import List, Dict, Any\n\n\ndef parse_csv_to_dicts(filepath: str) -> List[Dict[str, Any]]:", + "meadow-254<|im_end|>", + "juniper-766<|im_end|>", + "falcon-174<|im_end|>", + "willow-474<|im_end|>" + ], + "engine": [ + "strata generate: layer split across 2 GPUs: CUDA0, then CUDA1 (split auto)", + "strata generate: PCIe probe: 6.4 GB/s host->device -> pcie_frac 0.14 (default 0.55)", + "strata generate: layer split: CUDA1 PCIe probe 57.7 GB/s -> pcie_frac 0.55", + "strata generate: layer split: CUDA1 holds its weights, session and head; 9.98 GiB free", + "strata generate: layer split auto: K=36 - the caches hold 11775 of 12288 profiled pairs (fullest device 100%)", + "strata generate: expert cache auto: 18.62 GiB free, 700 MiB reserved -> 6634 slots", + "strata generate: expert cache 8828 slots, 16.45 GiB of VRAM; policy is", + "strata generate: layer split: CUDA1 runs layers 36-47, expert cache 2945 slots (5.99 GiB), 2945 of its 3072 profiled pairs; slot 0 verified", + "strata generate: layer split: CUDA0 runs layers 0-35", + "strata serve: layer split: layers 0-35 (CUDA0), 36-47 (CUDA1), one hand-off per window" + ] + } + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/README.md b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/README.md new file mode 100644 index 00000000..05e346e6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/README.md @@ -0,0 +1,46 @@ +# Preliminary native RTX 3090 / EPYC 7453 results + +Issue: [#165](https://github.com/Niko1221/Strata/issues/165) +Engine: Strata v0.1.26, source build at `ac8b251` +Status: preliminary; prompt set and harness guidance requested upstream. + +## Hardware + +| Component | Guest-visible details | +|---|---| +| CPU | AMD EPYC 7453, 20 vCPU, AVX2; AVX-512 not exposed | +| RAM | 165 GiB visible to Ubuntu 24.04.5 KVM guest; physical DIMM layout and bandwidth not verified | +| GPUs | 2x RTX 3090 24 GB; PCIe Gen4 x16 maximum reported per card; driver 595.91.07 | +| Power limit | 280 W configured on each GPU; defaults are 350 W / 420 W, max-adjustable limits 366 W / 450 W | +| Storage | 541 GiB ext4 guest data disk; host storage layout not verified | + +The power values above are configured caps, not measured workload draw. Idle draw during the hardware capture was approximately 35 W / 29 W. + +## Method + +Native Linux setup, local build from v0.1.26, `--prefill auto`, shipped expert profile, automatic expert cache, int8 KV, MTP on, images off, experimental speed projection off. The GPU power limit was 280 W per card. Native runs used a systemd service with `LimitMEMLOCK=infinity`; other llama-swap model containers were stopped. + +The local API harness used the public Strata source tree as its prompt corpus, with generated tasks, `temperature: 0`, `reasoning_effort: none`, and `max_tokens: 256`. It is not the upstream code-agent prompt set or harness. Runs use unique request IDs and no conversation reuse in speed mode. Three runs per speed cell are summarized by medians; actual `usage.prompt_tokens` are recorded because nominal context labels can drift. The first decode run is also shown. Several requests ended early on EOS, so actual generated counts are in the raw JSON. + +No calibration comparison, upstream prompt comparison, `STRATA_SPLIT_TIMING` stage timing, or under-load power-draw capture has been done. Treat all prompt/decode comparisons with upstream as indicative only until the requested upstream method is available. + +## Results + +See [`matrix.md`](matrix.md) for summary tables and [`matrix.json`](matrix.json) for all successful run records. Per-run source JSON, logs, the local harness, and scrubbed hardware facts are in [`data/`](data/). + +Highlights: + +- IQ3_XXS on one 3090: 1K–262K cells, three runs each; 262K prompts were 232,183 / 259,589 / 261,068 tokens and fit within the 262,144 context. +- Coder IQ1_M at 32K: single-GPU median decode 66.8 tok/s; dual-GPU auto (K=19) median 98.6 tok/s. +- Fixed Coder K sweep: K=22 was the highest observed three-run median (103.3 tok/s); independently generated prompts mean this is not a paired ranking. +- IQ3_XXS and IQ3_S dual-GPU auto both selected K=24 at 32K. +- IQ3_XXS and IQ3_S needles passed 3/3 at 8K / 16K / 28K on the tested single/dual configurations; two-turn checkpoint reuse passed for both. + +## Limits and follow-up + +- Upstream prompts/harness are not yet available; all current speed data uses a local source-tree corpus. +- The guest exposes one NUMA node and 165 GiB RAM, but physical DIMM topology and memory bandwidth are unknown. +- PCIe x16 is the reported maximum link width; the engine probes were about 23–26 GB/s. Verify PCIe generation/width under sustained load before claiming a direct x16-vs-x4 comparison. +- Coder dual-GPU needle/two-turn checks and dual-GPU timing breakdowns are not run yet. +- K=18 has one successful run at 83.1 tok/s; a repeated startup failed while uploading a dense weight with an out-of-memory error, so it is not a three-run median. +- Calibration/default comparisons and IQ3_S single-GPU results remain outstanding. diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json new file mode 100644 index 00000000..9aaa778b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-1.json @@ -0,0 +1,360 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "6c1252339f83", + "corpus_repeated": false, + "time": "2026-09-29T21:11:07", + "prompt_tokens": 28317, + "completion_tokens": 48, + "ttft_s": 12.868, + "e2e_s": 13.739, + "api_prompt_tps": 2200.5, + "api_decode_tps": 54.0, + "engine_prompt_tps": 2229.2, + "engine_decode_tps": 52.7, + "log_lines": [ + "strata serve: prompt 28317 tokens = 0 reused + 28317 read in 12703 ms (2229.2 tok/s), 48 generated in 911 ms (52.7 tok/s), drafts accepted 31 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (25001 hits / 25956 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716256.7391467, + "requests": 1, + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6 + }, + "hardware": { + "gpu_util": 88, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 220.362, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 81.3, + "ram_used": 43964985344, + "ram_total": 177175990272, + "disk_read_mb": 2.9148478336133063, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716282.234284 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json new file mode 100644 index 00000000..fce05488 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-2.json @@ -0,0 +1,491 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "894af0ad69b7", + "corpus_repeated": false, + "time": "2026-09-29T21:11:22", + "prompt_tokens": 31630, + "completion_tokens": 26, + "ttft_s": 12.792, + "e2e_s": 13.164, + "api_prompt_tps": 2472.7, + "api_decode_tps": 67.3, + "engine_prompt_tps": 2506.6, + "engine_decode_tps": 66.8, + "log_lines": [ + "strata serve: prompt 31630 tokens = 0 reused + 31630 read in 12619 ms (2506.6 tok/s), 26 generated in 389 ms (66.8 tok/s), drafts accepted 12 of 21, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (16646 hits / 16791 lookups)" + ], + "answer_head": "I don't see any file content in the conversation above. Could you please share the file you'd like me to analyze?", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716282.3818104, + "duration_s": 13.0, + "finish": "stop", + "prompt_tokens": 31630, + "reused": 0, + "output_tokens": 26, + "engine_generated": 26, + "prompt_ms": 12618.8, + "decode_ms": 389.0, + "decode_tok_s": 66.8, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790716256.7391467, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 74, + "prompt_ms": 25321.4, + "decode_ms": 1299.6 + }, + "hardware": { + "gpu_util": 81, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 256.109, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 9.7744140625, + "gpu_pcie_tx_mb": 25.1767578125, + "cpu": 46.1, + "ram_used": 43872071680, + "ram_total": 177175990272, + "disk_read_mb": 1.6222807345356267, + "disk_write_mb": 0.018689870213544086, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88, + 0, + 100, + 99, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 99, + 100, + 81 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 44, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 48, + 47, + 45 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36, + 189.89, + 258.72, + 276.75, + 276.67, + 277.52, + 275.34, + 268.93, + 277.69, + 277.77, + 276.91, + 278.53, + 278.56, + 256.11 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29, + 2531.19, + 14.02, + 3715.09, + 10.68, + 13440.37, + 8568.48, + 14.92, + 15.31, + 15.69, + 6486.56, + 17.31, + 9674.45, + 9.77 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3, + 4.2, + 6.8, + 6.4, + 7.6, + 5.5, + 6.0, + 20.6, + 12.9, + 6.2, + 7.0, + 5.7, + 5.9, + 46.1 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344, + 43959267328, + 43943862272, + 43937861632, + 43930320896, + 43922284544, + 43915001856, + 43817238528, + 43819147264, + 43818729472, + 43828027392, + 43824201728, + 43825434624, + 43872071680 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91, + 0.61, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 79.64, + 41.92, + 0.0, + 0.0, + 0.0, + 0.0, + 1.62 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716295.9009006 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json new file mode 100644 index 00000000..c94b8364 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-1x3090/speed-32k-3.json @@ -0,0 +1,622 @@ +{ + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "a4c63bd599ab", + "corpus_repeated": false, + "time": "2026-09-29T21:11:35", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 12.796, + "e2e_s": 13.243, + "api_prompt_tps": 2469.6, + "api_decode_tps": 98.5, + "engine_prompt_tps": 2502.4, + "engine_decode_tps": 97.4, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 12628 ms (2502.4 tok/s), 45 generated in 462 ms (97.4 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (23985 hits / 24333 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 8973, + "expert_cache_mib": 17503, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 369, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716296.0458817, + "duration_s": 13.1, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 12628.3, + "decode_ms": 461.9, + "decode_tok_s": 97.4, + "hit_rate": 0.986 + }, + { + "projection": null, + "time": 1790716282.3818104, + "duration_s": 13.0, + "finish": "stop", + "prompt_tokens": 31630, + "reused": 0, + "output_tokens": 26, + "engine_generated": 26, + "prompt_ms": 12618.8, + "decode_ms": 389.0, + "decode_tok_s": 66.8, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790716268.10927, + "duration_s": 13.6, + "finish": "stop", + "prompt_tokens": 28317, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 12702.6, + "decode_ms": 910.6, + "decode_tok_s": 52.7, + "hit_rate": 0.963 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790716256.7391467, + "requests": 3, + "prompt_tokens": 91548, + "reused": 0, + "output_tokens": 119, + "prompt_ms": 37949.7, + "decode_ms": 1761.5 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25531711488, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 245.399, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 414.037109375, + "gpu_pcie_tx_mb": 303.36328125, + "cpu": 35.1, + "ram_used": 43772702720, + "ram_total": 177175990272, + "disk_read_mb": 0.6087260569540994, + "disk_write_mb": 0.20539836277592313, + "tok_s": 97.29124144311484, + "tok_s_mean": 96.62332449971758 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 100, + 96, + 100, + 99, + 100, + 99, + 99, + 100, + 100, + 88, + 0, + 100, + 99, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 99, + 100, + 81, + 99, + 100, + 100, + 99, + 100, + 99, + 17, + 99, + 100, + 99, + 99, + 99, + 96 + ], + "gpu_mem_used": [ + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25382813696, + 25407979520, + 25418465280, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25424756736, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488, + 25531711488 + ], + "gpu_temp": [ + 43, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 42, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 44, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 48, + 47, + 45, + 47, + 47, + 47, + 48, + 48, + 48, + 46, + 47, + 48, + 48, + 48, + 48, + 47 + ], + "gpu_power": [ + 148.8, + 140.48, + 132.59, + 119.03, + 118.99, + 119.03, + 119.04, + 119.03, + 119.12, + 119.17, + 119.16, + 119.15, + 119.26, + 191.57, + 276.49, + 276.88, + 275.95, + 277.04, + 277.35, + 267.91, + 275.37, + 276.16, + 278.28, + 279.07, + 220.36, + 189.89, + 258.72, + 276.75, + 276.67, + 277.52, + 275.34, + 268.93, + 277.69, + 277.77, + 276.91, + 278.53, + 278.56, + 256.11, + 199.6, + 275.35, + 275.49, + 276.31, + 275.46, + 277.78, + 266.35, + 267.73, + 276.71, + 276.41, + 275.34, + 278.17, + 245.4 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.29, + 385.14, + 19.88, + 1892.23, + 13280.39, + 85.45, + 16838.55, + 680.06, + 1060.72, + 13.45, + 15.74, + 5013.75, + 1194.52, + 0.29, + 2531.19, + 14.02, + 3715.09, + 10.68, + 13440.37, + 8568.48, + 14.92, + 15.31, + 15.69, + 6486.56, + 17.31, + 9674.45, + 9.77, + 2795.22, + 4473.69, + 14.5, + 12.97, + 14.92, + 7716.66, + 2819.78, + 4278.33, + 12009.48, + 17.07, + 9916.78, + 8518.17, + 414.04 + ], + "cpu": [ + 0.0, + 0.7, + 7.3, + 15.7, + 7.1, + 2.0, + 1.2, + 2.0, + 2.1, + 1.6, + 1.9, + 7.4, + 13.9, + 18.3, + 6.1, + 6.0, + 16.7, + 24.9, + 13.2, + 12.0, + 7.1, + 6.2, + 6.0, + 8.8, + 81.3, + 4.2, + 6.8, + 6.4, + 7.6, + 5.5, + 6.0, + 20.6, + 12.9, + 6.2, + 7.0, + 5.7, + 5.9, + 46.1, + 4.0, + 6.9, + 5.7, + 6.2, + 7.1, + 5.5, + 5.6, + 9.9, + 13.7, + 8.4, + 7.7, + 6.4, + 35.1 + ], + "ram_used": [ + 43381886976, + 43381694464, + 43410796544, + 43434872832, + 43483377664, + 43485900800, + 43484897280, + 43481210880, + 43469135872, + 43462295552, + 43458363392, + 43496140800, + 43624353792, + 43648593920, + 43633405952, + 43641139200, + 43635249152, + 43689267200, + 43846070272, + 43924541440, + 43924467712, + 43918565376, + 43883311104, + 44002877440, + 43964985344, + 43959267328, + 43943862272, + 43937861632, + 43930320896, + 43922284544, + 43915001856, + 43817238528, + 43819147264, + 43818729472, + 43828027392, + 43824201728, + 43825434624, + 43872071680, + 43734614016, + 43728027648, + 43719413760, + 43703148544, + 43695366144, + 43687342080, + 43744829440, + 43791024128, + 43789787136, + 43766198272, + 43761831936, + 43750072320, + 43772702720 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 25.43, + 204.93, + 214.14, + 7.41, + 0.22, + 184.19, + 135.03, + 0.0, + 101.27, + 0.0, + 0.0, + 0.0, + 0.78, + 2.91, + 0.61, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 79.64, + 41.92, + 0.0, + 0.0, + 0.0, + 0.0, + 1.62, + 0.72, + 0.0, + 0.0, + 0.05, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.61 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.29 + ] + }, + "time": 1790716309.6464093 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json new file mode 100644 index 00000000..3f6e9100 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K18/speed-32k-1.json @@ -0,0 +1,423 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K18", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "052cbcbb7af7", + "corpus_repeated": false, + "time": "2026-09-29T21:21:48", + "prompt_tokens": 28313, + "completion_tokens": 57, + "ttft_s": 12.346, + "e2e_s": 12.991, + "api_prompt_tps": 2293.3, + "api_decode_tps": 86.9, + "engine_prompt_tps": 2324.6, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28313 tokens = 0 reused + 28313 read in 12180 ms (2324.6 tok/s), 57 generated in 686 ms (83.1 tok/s), drafts accepted 39 of 41, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.7% (28717 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4608, + "expert_cache_mib": 8437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716909.0337873, + "duration_s": 12.9, + "finish": "stop", + "prompt_tokens": 28313, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 12179.9, + "decode_ms": 685.7, + "decode_tok_s": 83.1, + "hit_rate": 0.997 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716889.8200681, + "requests": 1, + "prompt_tokens": 28313, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 12179.9, + "decode_ms": 685.7 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 15823994880, + "mem_total": 25769803776, + "temp": 44, + "power": 161.267 + }, + { + "index": 1, + "util": 90, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 51, + "power": 278.413 + } + ], + "gpu_util": 45.0, + "gpu_mem_used": 40032403456, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 439.68, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.33984375, + "gpu_pcie_tx_mb": 18.5009765625, + "cpu": 16.1, + "ram_used": 44574941184, + "ram_total": 177175990272, + "disk_read_mb": 0.9737281407762519, + "disk_write_mb": 0.11497896865254635, + "tok_s": 36.0, + "tok_s_mean": 64.01736582189179 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 41.5, + 68.0, + 50.0, + 73.0, + 87.5, + 41.5, + 47.0, + 50.0, + 78.0, + 50.5, + 45.0 + ], + "gpu_mem_used": [ + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39866728448, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 39965294592, + 40032403456 + ], + "gpu_temp": [ + 45, + 44, + 44, + 44, + 44, + 44, + 45, + 44, + 44, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 41, + 41, + 47, + 50, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 52, + 51 + ], + "gpu_power": [ + 255.0, + 240.14, + 239.41, + 239.38, + 239.55, + 239.75, + 239.74, + 239.65, + 239.56, + 239.63, + 239.71, + 239.58, + 239.49, + 239.62, + 239.83, + 239.9, + 200.58, + 138.26, + 69.98, + 230.69, + 516.11, + 485.77, + 500.33, + 518.82, + 491.98, + 467.22, + 490.75, + 506.65, + 510.68, + 439.68 + ], + "gpu_pcie_rx_mb": [ + 0.71, + 0.62, + 0.67, + 0.67, + 0.67, + 0.57, + 0.71, + 0.62, + 0.62, + 0.57, + 0.67, + 0.62, + 0.71, + 0.67, + 0.67, + 0.62, + 0.76, + 0.86, + 0.71, + 1243.59, + 45.3, + 2454.38, + 77.06, + 3382.78, + 1099.87, + 47.06, + 2677.87, + 79.25, + 1143.26, + 5.34 + ], + "cpu": [ + 0.0, + 1.0, + 2.8, + 3.4, + 1.0, + 1.6, + 1.6, + 1.0, + 1.4, + 0.7, + 3.6, + 8.3, + 1.0, + 8.2, + 5.7, + 2.6, + 3.4, + 1.4, + 10.1, + 12.9, + 8.2, + 10.3, + 10.7, + 11.6, + 27.0, + 14.9, + 11.2, + 18.3, + 15.0, + 16.1 + ], + "ram_used": [ + 43962929152, + 43965493248, + 43981484032, + 43968327680, + 43968602112, + 43968954368, + 43964538880, + 43964022784, + 43964801024, + 43964657664, + 43961843712, + 43958075392, + 43958878208, + 43967004672, + 43967807488, + 43951247360, + 43945017344, + 43945320448, + 43971616768, + 44103409664, + 44112924672, + 44112818176, + 43979321344, + 43978510336, + 44145692672, + 44276580352, + 44275351552, + 44327723008, + 44296556544, + 44574941184 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 64.21, + 105.78, + 24.45, + 89.11, + 67.32, + 92.34, + 145.4, + 79.43, + 98.92, + 75.23, + 0.0, + 0.97 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 36.0 + ] + }, + "time": 1790716922.4098496 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json new file mode 100644 index 00000000..063ae12f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-1.json @@ -0,0 +1,270 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "69d919ce1297", + "corpus_repeated": false, + "time": "2026-09-29T21:32:53", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.575, + "e2e_s": 11.256, + "api_prompt_tps": 2677.7, + "api_decode_tps": 82.2, + "engine_prompt_tps": 2718.9, + "engine_decode_tps": 79.8, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10414 ms (2718.9 tok/s), 57 generated in 715 ms (79.8 tok/s), drafts accepted 37 of 48, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717571.262619, + "requests": 1, + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 34, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 49, + "power": 184.581 + }, + { + "index": 1, + "util": 54, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 52, + "power": 232.993 + } + ], + "gpu_util": 44.0, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 417.57399999999996, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.953125, + "cpu": 6.2, + "ram_used": 44281556992, + "ram_total": 177175990272, + "disk_read_mb": 3.421090719626586, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717584.813652 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json new file mode 100644 index 00000000..44d74e82 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-2.json @@ -0,0 +1,383 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "8506420b91e1", + "corpus_repeated": false, + "time": "2026-09-29T21:33:04", + "prompt_tokens": 31633, + "completion_tokens": 45, + "ttft_s": 10.85, + "e2e_s": 11.271, + "api_prompt_tps": 2915.4, + "api_decode_tps": 104.6, + "engine_prompt_tps": 2962.7, + "engine_decode_tps": 103.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 10677 ms (2962.7 tok/s), 45 generated in 436 ms (103.3 tok/s), drafts accepted 32 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24960 hits / 24960 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717584.9637764, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10677.2, + "decode_ms": 435.6, + "decode_tok_s": 103.3, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717571.262619, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 102, + "prompt_ms": 21091.6, + "decode_ms": 1150.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 37, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 49, + "power": 187.064 + }, + { + "index": 1, + "util": 60, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 53, + "power": 243.674 + } + ], + "gpu_util": 48.5, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 430.738, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 1.0, + "cpu": 6.1, + "ram_used": 44308209664, + "ram_total": 177175990272, + "disk_read_mb": 0.7959400039611647, + "disk_write_mb": 0.24130307812397303, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0, + 18.0, + 52.0, + 95.5, + 50.0, + 97.0, + 24.5, + 95.5, + 82.0, + 96.5, + 50.0, + 48.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52, + 49, + 54, + 54, + 54, + 54, + 52, + 54, + 54, + 54, + 54, + 53 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57, + 353.2, + 539.11, + 526.73, + 525.83, + 531.55, + 507.76, + 523.24, + 527.24, + 526.07, + 501.32, + 430.74 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67, + 1765.25, + 83.88, + 85.4, + 85.07, + 88.59, + 82.35, + 78.3, + 85.16, + 61.94, + 46.3, + 0.62 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2, + 4.4, + 6.6, + 6.4, + 5.8, + 6.1, + 7.4, + 5.9, + 6.8, + 19.8, + 14.2, + 6.1 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992, + 44278607872, + 44263776256, + 44251099136, + 44242841600, + 44235354112, + 44232339456, + 44218642432, + 44210057216, + 44216344576, + 44288196608, + 44308209664 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42, + 0.48, + 0.01, + 0.04, + 0.06, + 0.02, + 0.02, + 0.02, + 12.53, + 104.78, + 0.0, + 0.8 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717596.5877995 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json new file mode 100644 index 00000000..905e9d9d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K22/speed-32k-3.json @@ -0,0 +1,496 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "831d87a1dacc", + "corpus_repeated": false, + "time": "2026-09-29T21:33:16", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.877, + "e2e_s": 11.43, + "api_prompt_tps": 2905.4, + "api_decode_tps": 106.7, + "engine_prompt_tps": 2951.6, + "engine_decode_tps": 105.7, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 10706 ms (2951.6 tok/s), 60 generated in 568 ms (105.7 tok/s), drafts accepted 41 of 46, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (31680 hits / 31680 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 5632, + "expert_cache_mib": 10325, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 7669, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717596.735188, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 10706.3, + "decode_ms": 567.6, + "decode_tok_s": 105.7, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717584.9637764, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10677.2, + "decode_ms": 435.6, + "decode_tok_s": 103.3, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717573.1737459, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10414.4, + "decode_ms": 714.5, + "decode_tok_s": 79.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717571.262619, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 162, + "prompt_ms": 31797.899999999998, + "decode_ms": 1717.6999999999998 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 25, + "mem_used": 17822580736, + "mem_total": 25769803776, + "temp": 50, + "power": 201.214 + }, + { + "index": 1, + "util": 61, + "mem_used": 22828482560, + "mem_total": 25769803776, + "temp": 53, + "power": 238.993 + } + ], + "gpu_util": 43.0, + "gpu_mem_used": 40651063296, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 440.207, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 4.4, + "ram_used": 44291919872, + "ram_total": 177175990272, + "disk_read_mb": 0.7281688058408962, + "disk_write_mb": 0.01802398034259644, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 73.5, + 58.5, + 96.0, + 57.5, + 95.5, + 47.5, + 93.0, + 58.5, + 50.0, + 44.0, + 18.0, + 52.0, + 95.5, + 50.0, + 97.0, + 24.5, + 95.5, + 82.0, + 96.5, + 50.0, + 48.5, + 49.5, + 96.0, + 48.0, + 96.0, + 47.5, + 94.5, + 61.0, + 97.5, + 47.5, + 49.5, + 43.0 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296, + 40651063296 + ], + "gpu_temp": [ + 48, + 47, + 47, + 50, + 53, + 53, + 54, + 53, + 54, + 54, + 54, + 54, + 52, + 49, + 54, + 54, + 54, + 54, + 52, + 54, + 54, + 54, + 54, + 53, + 50, + 54, + 54, + 54, + 55, + 54, + 54, + 54, + 55, + 55, + 53 + ], + "gpu_power": [ + 256.98, + 244.54, + 244.03, + 340.49, + 532.78, + 528.1, + 525.31, + 536.01, + 504.78, + 526.85, + 529.86, + 484.8, + 417.57, + 353.2, + 539.11, + 526.73, + 525.83, + 531.55, + 507.76, + 523.24, + 527.24, + 526.07, + 501.32, + 430.74, + 359.38, + 510.67, + 527.45, + 526.85, + 532.56, + 501.47, + 534.58, + 526.16, + 522.92, + 475.95, + 440.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.67, + 78.72, + 82.54, + 76.1, + 85.97, + 55.17, + 62.23, + 87.12, + 83.54, + 85.83, + 0.67, + 1765.25, + 83.88, + 85.4, + 85.07, + 88.59, + 82.35, + 78.3, + 85.16, + 61.94, + 46.3, + 0.62, + 87.45, + 41.53, + 89.07, + 84.21, + 76.25, + 52.17, + 78.29, + 83.59, + 51.45, + 47.92, + 0.67 + ], + "cpu": [ + 0.0, + 1.2, + 5.4, + 10.7, + 10.0, + 9.8, + 14.0, + 18.3, + 17.8, + 18.6, + 9.0, + 5.8, + 6.2, + 4.4, + 6.6, + 6.4, + 5.8, + 6.1, + 7.4, + 5.9, + 6.8, + 19.8, + 14.2, + 6.1, + 7.3, + 6.6, + 6.3, + 5.7, + 6.0, + 6.2, + 6.3, + 6.1, + 7.3, + 6.4, + 4.4 + ], + "ram_used": [ + 43564908544, + 43556737024, + 43564126208, + 43739512832, + 43734302720, + 43734560768, + 43735560192, + 43898122240, + 44013469696, + 43991674880, + 43978436608, + 43974189056, + 44281556992, + 44278607872, + 44263776256, + 44251099136, + 44242841600, + 44235354112, + 44232339456, + 44218642432, + 44210057216, + 44216344576, + 44288196608, + 44308209664, + 44011671552, + 43989819392, + 43978940416, + 43970682880, + 43962933248, + 44045533184, + 44039798784, + 44039798784, + 44047568896, + 44044705792, + 44291919872 + ], + "disk_read_mb": [ + null, + 0.0, + 73.94, + 96.25, + 39.8, + 73.77, + 144.08, + 110.85, + 127.27, + 131.68, + 42.81, + 0.0, + 3.42, + 0.48, + 0.01, + 0.04, + 0.06, + 0.02, + 0.02, + 0.02, + 12.53, + 104.78, + 0.0, + 0.8, + 0.61, + 0.05, + 0.03, + 0.09, + 0.08, + 0.04, + 0.05, + 0.04, + 0.15, + 0.0, + 0.73 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717608.5200934 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json new file mode 100644 index 00000000..e087261d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-1.json @@ -0,0 +1,279 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "87af67edfd2d", + "corpus_repeated": false, + "time": "2026-09-29T21:34:02", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 10.029, + "e2e_s": 12.977, + "api_prompt_tps": 2823.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 2871.1, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9862 ms (2871.1 tok/s), 256 generated in 2981 ms (85.9 tok/s), drafts accepted 143 of 193, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (147360 hits / 147360 lookups)" + ], + "answer_head": "Looking at the last file above, `docs/AMD_HIP_PERFORMANCE.md`, it documents the performance evidence and correctness limits for the experimental AMD HIP backend targeting gfx1100 (RX 7900 XTX). It records:\n\n- The exact build/runtime configuration used for the benchmark (env vars, CLI flags, model pa", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717640.7776525, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 50, + "power": 244.874 + }, + { + "index": 1, + "util": 57, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 254.71 + } + ], + "gpu_util": 50.0, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 499.584, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.38671875, + "gpu_pcie_tx_mb": 87.7373046875, + "cpu": 11.7, + "ram_used": 44619116544, + "ram_total": 177175990272, + "disk_read_mb": 4.515214018548113, + "disk_write_mb": 0.17657261525048487, + "tok_s": 107.09643367230112, + "tok_s_mean": 83.26979350665239 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1 + ] + }, + "time": 1790717655.7892108 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json new file mode 100644 index 00000000..290da924 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-2.json @@ -0,0 +1,392 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "b38394f620b3", + "corpus_repeated": false, + "time": "2026-09-29T21:34:15", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.269, + "e2e_s": 10.686, + "api_prompt_tps": 3080.5, + "api_decode_tps": 105.5, + "engine_prompt_tps": 3130.4, + "engine_decode_tps": 104.2, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 10106 ms (3130.4 tok/s), 45 generated in 432 ms (104.2 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717655.9301767, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10105.9, + "decode_ms": 431.8, + "decode_tok_s": 104.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717640.7776525, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 301, + "prompt_ms": 19967.699999999997, + "decode_ms": 3413.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 20, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 50, + "power": 191.174 + }, + { + "index": 1, + "util": 53, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 238.032 + } + ], + "gpu_util": 36.5, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 429.206, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 5.3, + "ram_used": 44575621120, + "ram_total": 177175990272, + "disk_read_mb": 2.4688909410966033, + "disk_write_mb": 0.23427432287777988, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0, + 0.0, + 84.5, + 96.0, + 95.5, + 79.0, + 97.5, + 97.0, + 95.5, + 96.0, + 50.0, + 36.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54, + 50, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58, + 409.59, + 480.21, + 551.08, + 548.0, + 547.82, + 539.97, + 537.72, + 548.44, + 548.33, + 513.55, + 429.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39, + 45.78, + 64.8, + 1284.55, + 129.94, + 83.06, + 82.63, + 84.78, + 73.15, + 82.44, + 0.57, + 0.62 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7, + 6.7, + 8.3, + 6.5, + 7.2, + 6.1, + 6.0, + 6.1, + 6.5, + 11.2, + 8.0, + 5.3 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544, + 44154675200, + 44152926208, + 44151242752, + 44149854208, + 44145594368, + 44375150592, + 44366180352, + 44365656064, + 44362940416, + 44400578560, + 44575621120 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52, + 0.63, + 0.02, + 0.04, + 0.03, + 0.05, + 0.03, + 0.02, + 13.87, + 103.6, + 0.0, + 2.47 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717666.9788535 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json new file mode 100644 index 00000000..7ef80057 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K24/speed-32k-3.json @@ -0,0 +1,496 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3bee1c1e482a", + "corpus_repeated": false, + "time": "2026-09-29T21:34:26", + "prompt_tokens": 31602, + "completion_tokens": 60, + "ttft_s": 10.281, + "e2e_s": 10.865, + "api_prompt_tps": 3073.8, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3123.2, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10118 ms (3123.2 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34560 hits / 34560 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6144, + "expert_cache_mib": 11337, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 6657, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717667.1193056, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 10118.5, + "decode_ms": 599.0, + "decode_tok_s": 100.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717655.9301767, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10105.9, + "decode_ms": 431.8, + "decode_tok_s": 104.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717642.434618, + "duration_s": 12.9, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 9861.8, + "decode_ms": 2981.5, + "decode_tok_s": 85.9, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717640.7776525, + "requests": 3, + "prompt_tokens": 91551, + "reused": 0, + "output_tokens": 361, + "prompt_ms": 30086.199999999997, + "decode_ms": 4012.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 18898419712, + "mem_total": 25769803776, + "temp": 51, + "power": 178.691 + }, + { + "index": 1, + "util": 51, + "mem_used": 21758935040, + "mem_total": 25769803776, + "temp": 54, + "power": 244.501 + } + ], + "gpu_util": 47.0, + "gpu_mem_used": 40657354752, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 423.192, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.1962890625, + "gpu_pcie_tx_mb": 103.138671875, + "cpu": 6.6, + "ram_used": 44596383744, + "ram_total": 177175990272, + "disk_read_mb": 1.1207609014346964, + "disk_write_mb": 0.0288298624163266, + "tok_s": 110.47676922161895, + "tok_s_mean": 99.0096070780873 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 1.0, + 93.0, + 94.0, + 64.0, + 94.5, + 88.5, + 95.5, + 92.5, + 48.5, + 32.0, + 48.0, + 50.0, + 0.0, + 84.5, + 96.0, + 95.5, + 79.0, + 97.5, + 97.0, + 95.5, + 96.0, + 50.0, + 36.5, + 49.5, + 96.5, + 61.0, + 94.5, + 91.0, + 97.0, + 95.5, + 98.5, + 47.5, + 47.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40476999680, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40546205696, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752, + 40657354752 + ], + "gpu_temp": [ + 49, + 49, + 49, + 53, + 54, + 54, + 55, + 54, + 55, + 55, + 55, + 52, + 54, + 54, + 50, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54, + 52, + 55, + 55, + 55, + 55, + 56, + 56, + 55, + 56, + 54 + ], + "gpu_power": [ + 259.59, + 247.18, + 245.88, + 414.53, + 546.71, + 547.76, + 546.95, + 533.57, + 531.41, + 545.46, + 539.14, + 402.04, + 486.67, + 499.58, + 409.59, + 480.21, + 551.08, + 548.0, + 547.82, + 539.97, + 537.72, + 548.44, + 548.33, + 513.55, + 429.21, + 354.61, + 553.75, + 546.57, + 547.59, + 532.21, + 535.5, + 547.28, + 548.49, + 534.02, + 423.19 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 247.86, + 81.11, + 78.2, + 80.92, + 83.88, + 57.6, + 82.87, + 79.92, + 40.29, + 5.39, + 9.77, + 5.39, + 45.78, + 64.8, + 1284.55, + 129.94, + 83.06, + 82.63, + 84.78, + 73.15, + 82.44, + 0.57, + 0.62, + 81.82, + 83.45, + 75.34, + 84.16, + 82.11, + 81.49, + 70.95, + 73.91, + 52.55, + 5.2 + ], + "cpu": [ + 0.0, + 1.9, + 9.1, + 8.8, + 9.5, + 10.7, + 13.9, + 10.5, + 13.9, + 11.8, + 6.0, + 6.3, + 12.4, + 11.7, + 6.7, + 8.3, + 6.5, + 7.2, + 6.1, + 6.0, + 6.1, + 6.5, + 11.2, + 8.0, + 5.3, + 6.7, + 12.7, + 10.0, + 5.9, + 6.4, + 6.0, + 7.1, + 5.7, + 6.8, + 6.6 + ], + "ram_used": [ + 43887411200, + 43859918848, + 43956232192, + 44034678784, + 44030210048, + 44028076032, + 44015280128, + 44252610560, + 44247789568, + 44243210240, + 44230340608, + 44558966784, + 44619108352, + 44619116544, + 44154675200, + 44152926208, + 44151242752, + 44149854208, + 44145594368, + 44375150592, + 44366180352, + 44365656064, + 44362940416, + 44400578560, + 44575621120, + 44112637952, + 44134821888, + 44114948096, + 44112486400, + 44240445440, + 44343197696, + 44341800960, + 44344549376, + 44344029184, + 44596383744 + ], + "disk_read_mb": [ + null, + 0.0, + 126.09, + 44.05, + 80.0, + 93.94, + 138.6, + 104.01, + 156.43, + 97.38, + 0.0, + 1.76, + 4.66, + 4.52, + 0.63, + 0.02, + 0.04, + 0.03, + 0.05, + 0.03, + 0.02, + 13.87, + 103.6, + 0.0, + 2.47, + 0.63, + 0.05, + 0.08, + 0.08, + 0.04, + 0.07, + 0.04, + 0.17, + 0.0, + 1.12 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 78.74, + 81.4, + 107.1, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.48 + ] + }, + "time": 1790717678.3471994 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json new file mode 100644 index 00000000..2e492f8a --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-1.json @@ -0,0 +1,261 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "5ca39dba7489", + "corpus_repeated": false, + "time": "2026-09-29T21:35:22", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 9.79, + "e2e_s": 10.297, + "api_prompt_tps": 2892.2, + "api_decode_tps": 92.7, + "engine_prompt_tps": 2940.2, + "engine_decode_tps": 88.8, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9630 ms (2940.2 tok/s), 48 generated in 540 ms (88.8 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25920 hits / 25920 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717720.412441, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 47, + "mem_used": 19980550144, + "mem_total": 25769803776, + "temp": 51, + "power": 179.665 + }, + { + "index": 1, + "util": 28, + "mem_used": 20641153024, + "mem_total": 25769803776, + "temp": 53, + "power": 236.004 + } + ], + "gpu_util": 37.5, + "gpu_mem_used": 40621703168, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 415.669, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 6.0, + "ram_used": 44539072512, + "ram_total": 177175990272, + "disk_read_mb": 2.97776661958663, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717732.8116624 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json new file mode 100644 index 00000000..85ea2124 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-2.json @@ -0,0 +1,365 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "14c7210ce0e9", + "corpus_repeated": false, + "time": "2026-09-29T21:35:32", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.029, + "e2e_s": 10.496, + "api_prompt_tps": 3154.3, + "api_decode_tps": 94.3, + "engine_prompt_tps": 3205.2, + "engine_decode_tps": 93.5, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 9870 ms (3205.2 tok/s), 45 generated in 481 ms (93.5 tok/s), drafts accepted 31 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717732.947479, + "duration_s": 10.4, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9870.0, + "decode_ms": 481.3, + "decode_tok_s": 93.5, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717720.412441, + "requests": 2, + "prompt_tokens": 59949, + "reused": 0, + "output_tokens": 93, + "prompt_ms": 19500.1, + "decode_ms": 1021.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 51, + "mem_used": 19991035904, + "mem_total": 25769803776, + "temp": 51, + "power": 190.866 + }, + { + "index": 1, + "util": 56, + "mem_used": 20653735936, + "mem_total": 25769803776, + "temp": 55, + "power": 249.813 + } + ], + "gpu_util": 53.5, + "gpu_mem_used": 40644771840, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 440.679, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.44921875, + "gpu_pcie_tx_mb": 82.0625, + "cpu": 6.0, + "ram_used": 44553875456, + "ram_total": 177175990272, + "disk_read_mb": 0.6053434938228842, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5, + 1.5, + 97.0, + 96.0, + 81.0, + 86.5, + 95.5, + 95.0, + 96.5, + 95.0, + 53.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40644771840 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53, + 51, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67, + 326.37, + 532.86, + 555.24, + 552.15, + 555.12, + 507.8, + 554.85, + 554.0, + 554.13, + 440.68 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67, + 3698.35, + 132.46, + 131.89, + 82.06, + 85.92, + 83.02, + 1279.88, + 50.4, + 86.21, + 16.45 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0, + 4.5, + 6.1, + 6.0, + 6.4, + 6.7, + 5.9, + 6.7, + 9.9, + 7.4, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512, + 44064968704, + 44058497024, + 44058497024, + 44058501120, + 44175929344, + 44294356992, + 44294352896, + 44295569408, + 44291391488, + 44553875456 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98, + 0.47, + 0.01, + 0.04, + 0.06, + 0.03, + 0.03, + 12.57, + 71.85, + 33.12, + 0.61 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717743.8106396 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json new file mode 100644 index 00000000..60304587 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K26/speed-32k-3.json @@ -0,0 +1,469 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3f243fdb63ee", + "corpus_repeated": false, + "time": "2026-09-29T21:35:43", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.026, + "e2e_s": 10.61, + "api_prompt_tps": 3151.9, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3208.3, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 9850 ms (3208.3 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 50, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file is.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 6656, + "expert_cache_mib": 12387, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 5607, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717743.964174, + "duration_s": 10.5, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 60, + "engine_generated": 60, + "prompt_ms": 9849.9, + "decode_ms": 598.9, + "decode_tok_s": 100.2, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717732.947479, + "duration_s": 10.4, + "finish": "stop", + "prompt_tokens": 31635, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9870.0, + "decode_ms": 481.3, + "decode_tok_s": 93.5, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717722.129571, + "duration_s": 10.2, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 9630.1, + "decode_ms": 540.5, + "decode_tok_s": 88.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717720.412441, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 153, + "prompt_ms": 29350.0, + "decode_ms": 1620.6999999999998 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 46, + "mem_used": 19991035904, + "mem_total": 25769803776, + "temp": 52, + "power": 189.922 + }, + { + "index": 1, + "util": 52, + "mem_used": 20653735936, + "mem_total": 25769803776, + "temp": 55, + "power": 246.398 + } + ], + "gpu_util": 49.0, + "gpu_mem_used": 40644771840, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 436.32, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.8330078125, + "gpu_pcie_tx_mb": 43.1533203125, + "cpu": 6.0, + "ram_used": 44614168576, + "ram_total": 177175990272, + "disk_read_mb": 0.4973320821900814, + "disk_write_mb": 0.05405783502066102, + "tok_s": 99.26679787882165, + "tok_s_mean": 97.997900113756 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.5, + 71.0, + 95.5, + 96.0, + 91.5, + 66.5, + 95.5, + 90.5, + 84.5, + 37.5, + 1.5, + 97.0, + 96.0, + 81.0, + 86.5, + 95.5, + 95.0, + 96.5, + 95.0, + 53.5, + 0.0, + 95.0, + 95.5, + 82.0, + 94.5, + 93.0, + 88.5, + 96.0, + 97.0, + 49.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40472805376, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40535719936, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40621703168, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840, + 40644771840 + ], + "gpu_temp": [ + 50, + 50, + 50, + 52, + 55, + 55, + 56, + 56, + 56, + 55, + 56, + 53, + 51, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55, + 52, + 55, + 56, + 56, + 56, + 56, + 56, + 56, + 56, + 55 + ], + "gpu_power": [ + 261.03, + 248.02, + 247.5, + 351.95, + 548.48, + 553.77, + 555.05, + 536.77, + 531.38, + 552.37, + 551.57, + 415.67, + 326.37, + 532.86, + 555.24, + 552.15, + 555.12, + 507.8, + 554.85, + 554.0, + 554.13, + 440.68, + 363.75, + 474.54, + 552.72, + 554.16, + 554.3, + 509.24, + 555.11, + 555.88, + 555.36, + 436.32 + ], + "gpu_pcie_rx_mb": [ + 0.76, + 0.62, + 224.64, + 86.02, + 83.16, + 75.62, + 86.69, + 102.66, + 65.66, + 83.97, + 38.86, + 0.67, + 3698.35, + 132.46, + 131.89, + 82.06, + 85.92, + 83.02, + 1279.88, + 50.4, + 86.21, + 16.45, + 38.96, + 81.63, + 83.25, + 84.4, + 72.53, + 127.22, + 48.4, + 96.51, + 100.71, + 17.83 + ], + "cpu": [ + 0.0, + 1.1, + 8.1, + 9.1, + 9.3, + 12.2, + 12.6, + 12.6, + 23.5, + 14.7, + 5.9, + 6.0, + 4.5, + 6.1, + 6.0, + 6.4, + 6.7, + 5.9, + 6.7, + 9.9, + 7.4, + 6.0, + 11.7, + 10.8, + 6.2, + 11.4, + 7.0, + 6.7, + 5.6, + 5.4, + 6.0, + 6.0 + ], + "ram_used": [ + 43871281152, + 43867545600, + 43958726656, + 44040531968, + 44041007104, + 44033200128, + 44032602112, + 44244361216, + 44250234880, + 44236812288, + 44233678848, + 44539072512, + 44064968704, + 44058497024, + 44058497024, + 44058501120, + 44175929344, + 44294356992, + 44294352896, + 44295569408, + 44291391488, + 44553875456, + 44129808384, + 44180946944, + 44184666112, + 44182659072, + 44296114176, + 44404658176, + 44394999808, + 44386783232, + 44374441984, + 44614168576 + ], + "disk_read_mb": [ + null, + 0.0, + 122.8, + 47.19, + 79.99, + 100.77, + 127.09, + 108.72, + 156.54, + 97.45, + 0.0, + 2.98, + 0.47, + 0.01, + 0.04, + 0.06, + 0.03, + 0.03, + 12.57, + 71.85, + 33.12, + 0.61, + 0.53, + 0.06, + 0.06, + 0.09, + 0.08, + 0.04, + 0.04, + 0.04, + 0.15, + 0.5 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 99.27 + ] + }, + "time": 1790717754.9239163 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json new file mode 100644 index 00000000..65c14074 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-1.json @@ -0,0 +1,261 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "0796a1ce12e4", + "corpus_repeated": false, + "time": "2026-09-29T21:36:29", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.285, + "e2e_s": 10.86, + "api_prompt_tps": 2753.1, + "api_decode_tps": 97.4, + "engine_prompt_tps": 2798.5, + "engine_decode_tps": 93.7, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10118 ms (2798.5 tok/s), 57 generated in 608 ms (93.7 tok/s), drafts accepted 40 of 42, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (28800 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717787.625935, + "requests": 1, + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 41, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 52, + "power": 189.832 + }, + { + "index": 1, + "util": 42, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 54, + "power": 230.563 + } + ], + "gpu_util": 41.5, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 420.395, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.1650390625, + "gpu_pcie_tx_mb": 53.119140625, + "cpu": 6.1, + "ram_used": 44503613440, + "ram_total": 177175990272, + "disk_read_mb": 1.946188226381293, + "disk_write_mb": 0.0036040522710764685, + "tok_s": 81.42212134334822, + "tok_s_mean": 78.79383849818437 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42 + ] + }, + "time": 1790717800.421838 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json new file mode 100644 index 00000000..bd332179 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-2.json @@ -0,0 +1,374 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "3d5bf2c2aa6f", + "corpus_repeated": false, + "time": "2026-09-29T21:36:40", + "prompt_tokens": 31631, + "completion_tokens": 45, + "ttft_s": 10.58, + "e2e_s": 10.972, + "api_prompt_tps": 2989.7, + "api_decode_tps": 112.3, + "engine_prompt_tps": 3034.9, + "engine_decode_tps": 110.6, + "log_lines": [ + "strata serve: prompt 31631 tokens = 0 reused + 31631 read in 10423 ms (3034.9 tok/s), 45 generated in 407 ms (110.6 tok/s), drafts accepted 33 of 34, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (23040 hits / 23040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717800.5571585, + "duration_s": 10.8, + "finish": "stop", + "prompt_tokens": 31631, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10422.5, + "decode_ms": 406.8, + "decode_tok_s": 110.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717787.625935, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 102, + "prompt_ms": 20540.7, + "decode_ms": 1014.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 46, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 51, + "power": 204.027 + }, + { + "index": 1, + "util": 12, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 54, + "power": 226.431 + } + ], + "gpu_util": 29.0, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 430.45799999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.6181640625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 4.3, + "ram_used": 44573519872, + "ram_total": 177175990272, + "disk_read_mb": 0.9768799607845553, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5, + 0.0, + 96.0, + 93.0, + 97.5, + 94.5, + 97.0, + 95.0, + 97.0, + 93.5, + 67.0, + 29.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54, + 52, + 55, + 54, + 56, + 56, + 56, + 56, + 57, + 57, + 56, + 54 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39, + 375.37, + 452.84, + 528.99, + 547.53, + 532.29, + 524.3, + 518.92, + 543.34, + 532.25, + 534.03, + 430.46 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17, + 42.15, + 1288.27, + 41.05, + 75.34, + 70.76, + 44.15, + 79.87, + 61.61, + 75.63, + 42.06, + 0.62 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1, + 4.2, + 6.4, + 6.0, + 12.9, + 11.2, + 6.1, + 8.2, + 8.8, + 14.0, + 6.4, + 4.3 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440, + 44015304704, + 44019281920, + 44021350400, + 44034875392, + 44111585280, + 44348657664, + 44344815616, + 44359872512, + 44334280704, + 44327985152, + 44573519872 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95, + 1.72, + 0.02, + 0.02, + 0.05, + 0.06, + 0.01, + 0.03, + 12.6, + 101.64, + 2.94, + 0.98 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717811.896799 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json new file mode 100644 index 00000000..98976150 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K28/speed-32k-3.json @@ -0,0 +1,487 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "d22ca9d8c7b8", + "corpus_repeated": false, + "time": "2026-09-29T21:36:51", + "prompt_tokens": 31602, + "completion_tokens": 59, + "ttft_s": 10.575, + "e2e_s": 11.17, + "api_prompt_tps": 2988.5, + "api_decode_tps": 97.4, + "engine_prompt_tps": 3037.5, + "engine_decode_tps": 96.6, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10404 ms (3037.5 tok/s), 59 generated in 611 ms (96.6 tok/s), drafts accepted 41 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (35040 hits / 35040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7168, + "expert_cache_mib": 13437, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 4557, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717812.0454123, + "duration_s": 11.0, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 59, + "engine_generated": 59, + "prompt_ms": 10404.1, + "decode_ms": 610.6, + "decode_tok_s": 96.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717800.5571585, + "duration_s": 10.8, + "finish": "stop", + "prompt_tokens": 31631, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10422.5, + "decode_ms": 406.8, + "decode_tok_s": 110.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717789.1846194, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 57, + "engine_generated": 57, + "prompt_ms": 10118.2, + "decode_ms": 608.0, + "decode_tok_s": 93.8, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717787.625935, + "requests": 3, + "prompt_tokens": 91549, + "reused": 0, + "output_tokens": 161, + "prompt_ms": 30944.800000000003, + "decode_ms": 1625.4 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 48, + "mem_used": 21104623616, + "mem_total": 25769803776, + "temp": 53, + "power": 214.931 + }, + { + "index": 1, + "util": 0, + "mem_used": 19548536832, + "mem_total": 25769803776, + "temp": 53, + "power": 199.379 + } + ], + "gpu_util": 24.0, + "gpu_mem_used": 40653160448, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 414.31, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 3.6, + "ram_used": 44545851392, + "ram_total": 177175990272, + "disk_read_mb": 0.7062443272525659, + "disk_write_mb": 0.11530519628613321, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 46.5, + 96.0, + 72.5, + 93.0, + 90.0, + 95.5, + 93.5, + 97.5, + 41.5, + 0.0, + 96.0, + 93.0, + 97.5, + 94.5, + 97.0, + 95.0, + 97.0, + 93.5, + 67.0, + 29.0, + 50.0, + 96.5, + 47.5, + 95.5, + 96.5, + 95.5, + 62.5, + 96.5, + 95.5, + 50.0, + 24.0 + ], + "gpu_mem_used": [ + 40447639552, + 40447639552, + 40495874048, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40542011392, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448, + 40653160448 + ], + "gpu_temp": [ + 51, + 50, + 50, + 52, + 55, + 54, + 56, + 54, + 56, + 56, + 57, + 54, + 52, + 55, + 54, + 56, + 56, + 56, + 56, + 57, + 57, + 56, + 54, + 53, + 56, + 54, + 57, + 57, + 57, + 56, + 57, + 56, + 57, + 53 + ], + "gpu_power": [ + 261.46, + 249.04, + 248.59, + 342.07, + 531.07, + 533.47, + 545.68, + 511.29, + 533.34, + 534.58, + 541.51, + 420.39, + 375.37, + 452.84, + 528.99, + 547.53, + 532.29, + 524.3, + 518.92, + 543.34, + 532.25, + 534.03, + 430.46, + 354.3, + 519.1, + 530.52, + 534.81, + 532.5, + 512.45, + 532.86, + 540.0, + 532.72, + 513.31, + 414.31 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 182.48, + 55.88, + 87.02, + 80.58, + 57.5, + 78.87, + 83.88, + 1294.42, + 46.78, + 17.17, + 42.15, + 1288.27, + 41.05, + 75.34, + 70.76, + 44.15, + 79.87, + 61.61, + 75.63, + 42.06, + 0.62, + 84.64, + 74.34, + 85.5, + 81.54, + 0.67, + 75.72, + 81.82, + 82.83, + 28.8, + 17.74, + 0.67 + ], + "cpu": [ + 0.0, + 6.6, + 18.0, + 11.3, + 10.5, + 9.8, + 11.5, + 13.9, + 11.4, + 12.9, + 7.4, + 6.1, + 4.2, + 6.4, + 6.0, + 12.9, + 11.2, + 6.1, + 8.2, + 8.8, + 14.0, + 6.4, + 4.3, + 4.2, + 6.6, + 6.0, + 17.8, + 8.5, + 6.2, + 15.1, + 14.3, + 6.7, + 6.9, + 3.6 + ], + "ram_used": [ + 43799613440, + 43777974272, + 43950305280, + 43962880000, + 43939622912, + 43930345472, + 43932086272, + 44071780352, + 44183257088, + 44182880256, + 44179062784, + 44503613440, + 44015304704, + 44019281920, + 44021350400, + 44034875392, + 44111585280, + 44348657664, + 44344815616, + 44359872512, + 44334280704, + 44327985152, + 44573519872, + 44103626752, + 44105744384, + 44105732096, + 44159885312, + 44275363840, + 44375539712, + 44373200896, + 44318019584, + 44307988480, + 44545863680, + 44545851392 + ], + "disk_read_mb": [ + null, + 0.0, + 129.59, + 40.83, + 79.94, + 84.92, + 115.02, + 136.42, + 117.79, + 106.04, + 29.9, + 1.95, + 1.72, + 0.02, + 0.02, + 0.05, + 0.06, + 0.01, + 0.03, + 12.6, + 101.64, + 2.94, + 0.98, + 0.74, + 0.02, + 0.06, + 0.32, + 0.08, + 0.04, + 0.05, + 0.04, + 0.1, + 0.0, + 0.71 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 81.42, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717823.5700235 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json new file mode 100644 index 00000000..a0d750ac --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-1.json @@ -0,0 +1,608 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "b4895f87f439", + "corpus_repeated": false, + "time": "2026-09-29T21:28:38", + "prompt_tokens": 28316, + "completion_tokens": 45, + "ttft_s": 9.936, + "e2e_s": 10.4, + "api_prompt_tps": 2849.8, + "api_decode_tps": 94.9, + "engine_prompt_tps": 2892.0, + "engine_decode_tps": 94.1, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 9791 ms (2892.0 tok/s), 45 generated in 478 ms (94.1 tok/s), drafts accepted 31 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717276.5105639, + "requests": 2, + "prompt_tokens": 56632, + "reused": 0, + "output_tokens": 101, + "prompt_ms": 20275.699999999997, + "decode_ms": 1114.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 53, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 51, + "power": 200.427 + }, + { + "index": 1, + "util": 46, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 53, + "power": 223.879 + } + ], + "gpu_util": 49.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 424.306, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5.8642578125, + "gpu_pcie_tx_mb": 107.4306640625, + "cpu": 6.9, + "ram_used": 44604223488, + "ram_total": 177175990272, + "disk_read_mb": 1.1417042620069329, + "disk_write_mb": 0.04682067951447989, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904 + ], + "gpu_temp": [ + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53 + ], + "gpu_power": [ + 257.9, + 244.84, + 244.4, + 244.1, + 244.29, + 244.43, + 244.32, + 244.0, + 243.79, + 243.86, + 244.04, + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.67, + 1.62, + 0.67, + 0.62, + 0.62, + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86 + ], + "cpu": [ + 0.0, + 1.4, + 4.7, + 7.8, + 13.7, + 1.8, + 1.4, + 1.9, + 1.6, + 1.4, + 1.5, + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9 + ], + "ram_used": [ + 43796508672, + 43800592384, + 43805933568, + 43809234944, + 43832729600, + 43832090624, + 43837464576, + 43835621376, + 43830910976, + 43829395456, + 43825078272, + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790717329.186504 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json new file mode 100644 index 00000000..d8865049 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-2.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f81947893a8b", + "corpus_repeated": false, + "time": "2026-09-29T21:28:49", + "prompt_tokens": 31632, + "completion_tokens": 48, + "ttft_s": 11.011, + "e2e_s": 11.496, + "api_prompt_tps": 2872.7, + "api_decode_tps": 97.0, + "engine_prompt_tps": 2926.4, + "engine_decode_tps": 96.1, + "log_lines": [ + "strata serve: prompt 31632 tokens = 0 reused + 31632 read in 10809 ms (2926.4 tok/s), 48 generated in 499 ms (96.1 tok/s), drafts accepted 32 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (27360 hits / 27360 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717329.364414, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31632, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 10809.3, + "decode_ms": 499.4, + "decode_tok_s": 96.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717276.5105639, + "requests": 3, + "prompt_tokens": 88264, + "reused": 0, + "output_tokens": 149, + "prompt_ms": 31084.999999999996, + "decode_ms": 1613.5 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 48, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 51, + "power": 211.949 + }, + { + "index": 1, + "util": 41, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 54, + "power": 238.158 + } + ], + "gpu_util": 44.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 450.10699999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.3544921875, + "gpu_pcie_tx_mb": 94.6513671875, + "cpu": 12.9, + "ram_used": 44387663872, + "ram_total": 177175990272, + "disk_read_mb": 0.417992184024029, + "disk_write_mb": 0.0972912842124895, + "tok_s": 101.46942145535564, + "tok_s_mean": 93.06246895838419 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5, + 50.0, + 97.5, + 97.0, + 98.5, + 68.5, + 96.0, + 49.5, + 96.0, + 68.5, + 97.0, + 44.5 + ], + "gpu_mem_used": [ + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904 + ], + "gpu_temp": [ + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53, + 50, + 54, + 54, + 55, + 54, + 55, + 52, + 55, + 54, + 55, + 54 + ], + "gpu_power": [ + 257.9, + 244.84, + 244.4, + 244.1, + 244.29, + 244.43, + 244.32, + 244.0, + 243.79, + 243.86, + 244.04, + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31, + 362.71, + 481.71, + 508.96, + 525.74, + 511.3, + 510.79, + 506.4, + 523.98, + 513.03, + 516.57, + 450.11 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.67, + 1.62, + 0.67, + 0.62, + 0.62, + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86, + 45.25, + 84.11, + 42.39, + 128.98, + 67.52, + 42.77, + 92.46, + 81.82, + 43.3, + 95.32, + 16.35 + ], + "cpu": [ + 0.0, + 1.4, + 4.7, + 7.8, + 13.7, + 1.8, + 1.4, + 1.9, + 1.6, + 1.4, + 1.5, + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9, + 3.9, + 5.5, + 5.8, + 5.9, + 6.4, + 7.5, + 6.6, + 6.1, + 8.7, + 17.4, + 12.9 + ], + "ram_used": [ + 43796508672, + 43800592384, + 43805933568, + 43809234944, + 43832729600, + 43832090624, + 43837464576, + 43835621376, + 43830910976, + 43829395456, + 43825078272, + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488, + 44141965312, + 44142555136, + 44129452032, + 44121694208, + 44121939968, + 44354928640, + 44349378560, + 44349894656, + 44349890560, + 44144226304, + 44387663872 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14, + 0.4, + 0.01, + 0.0, + 0.03, + 0.04, + 0.01, + 0.03, + 12.58, + 71.94, + 32.9, + 0.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 101.47 + ] + }, + "time": 1790717341.185252 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json new file mode 100644 index 00000000..714c5df3 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-K30/speed-32k-3.json @@ -0,0 +1,735 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "cb947708c5cc", + "corpus_repeated": false, + "time": "2026-09-29T21:29:01", + "prompt_tokens": 31602, + "completion_tokens": 45, + "ttft_s": 10.976, + "e2e_s": 11.378, + "api_prompt_tps": 2879.2, + "api_decode_tps": 109.6, + "engine_prompt_tps": 2920.6, + "engine_decode_tps": 108.0, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10820 ms (2920.6 tok/s), 45 generated in 417 ms (108.0 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 7680, + "expert_cache_mib": 14575, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 3419, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717341.3189692, + "duration_s": 11.2, + "finish": "stop", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 10820.3, + "decode_ms": 416.8, + "decode_tok_s": 108.0, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717329.364414, + "duration_s": 11.3, + "finish": "stop", + "prompt_tokens": 31632, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 10809.3, + "decode_ms": 499.4, + "decode_tok_s": 96.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717318.4067442, + "duration_s": 10.3, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 9791.3, + "decode_ms": 478.1, + "decode_tok_s": 94.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790717288.2692974, + "duration_s": 11.1, + "finish": "stop", + "prompt_tokens": 28316, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 10484.4, + "decode_ms": 636.0, + "decode_tok_s": 88.1, + "hit_rate": 1.0 + } + ], + "requests_kept": 4, + "totals": { + "since": 1790717276.5105639, + "requests": 4, + "prompt_tokens": 119866, + "reused": 0, + "output_tokens": 194, + "prompt_ms": 41905.299999999996, + "decode_ms": 2030.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 5, + "mem_used": 22306291712, + "mem_total": 25769803776, + "temp": 49, + "power": 227.165 + }, + { + "index": 1, + "util": 42, + "mem_used": 18353160192, + "mem_total": 25769803776, + "temp": 54, + "power": 235.691 + } + ], + "gpu_util": 23.5, + "gpu_mem_used": 40659451904, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 462.856, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 17.0703125, + "gpu_pcie_tx_mb": 56.361328125, + "cpu": 5.5, + "ram_used": 44383059968, + "ram_total": 177175990272, + "disk_read_mb": 0.38547172180233397, + "disk_write_mb": 0.09366602585851105, + "tok_s": 121.26075785511577, + "tok_s_mean": 112.03069063875886 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 50.0, + 94.0, + 63.0, + 95.0, + 50.0, + 92.0, + 95.0, + 82.5, + 97.0, + 35.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.5, + 97.5, + 49.0, + 94.5, + 50.0, + 96.5, + 53.0, + 94.5, + 97.0, + 49.5, + 50.0, + 97.5, + 97.0, + 98.5, + 68.5, + 96.0, + 49.5, + 96.0, + 68.5, + 97.0, + 44.5, + 50.0, + 85.5, + 94.5, + 73.0, + 79.0, + 96.0, + 48.0, + 95.0, + 72.5, + 95.5, + 23.5 + ], + "gpu_mem_used": [ + 40449736704, + 40542011392, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40548302848, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40636383232, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904, + 40659451904 + ], + "gpu_temp": [ + 48, + 50, + 52, + 53, + 53, + 53, + 52, + 54, + 51, + 54, + 52, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 48, + 49, + 49, + 49, + 49, + 46, + 46, + 53, + 52, + 54, + 52, + 54, + 52, + 54, + 54, + 53, + 50, + 54, + 54, + 55, + 54, + 55, + 52, + 55, + 54, + 55, + 54, + 51, + 53, + 54, + 53, + 54, + 55, + 54, + 55, + 55, + 55, + 54 + ], + "gpu_power": [ + 244.43, + 304.5, + 504.99, + 527.59, + 513.34, + 519.55, + 489.82, + 537.3, + 515.01, + 534.71, + 416.26, + 390.46, + 299.77, + 260.05, + 241.54, + 241.56, + 241.75, + 241.63, + 241.51, + 241.46, + 241.4, + 241.29, + 241.13, + 241.31, + 241.69, + 241.72, + 221.92, + 136.12, + 67.69, + 469.97, + 521.96, + 512.77, + 514.47, + 496.64, + 522.43, + 513.55, + 532.56, + 424.31, + 362.71, + 481.71, + 508.96, + 525.74, + 511.3, + 510.79, + 506.4, + 523.98, + 513.03, + 516.57, + 450.11, + 369.53, + 481.25, + 509.29, + 527.58, + 511.62, + 510.74, + 510.07, + 527.16, + 513.42, + 533.96, + 462.86 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 4319.14, + 134.51, + 87.31, + 96.37, + 111.91, + 79.87, + 41.53, + 80.25, + 44.15, + 15.88, + 0.67, + 0.57, + 0.57, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.62, + 0.62, + 0.57, + 0.81, + 0.81, + 44.34, + 97.08, + 1308.87, + 41.25, + 84.97, + 155.3, + 46.68, + 84.26, + 3604.32, + 5.86, + 45.25, + 84.11, + 42.39, + 128.98, + 67.52, + 42.77, + 92.46, + 81.82, + 43.3, + 95.32, + 16.35, + 43.1, + 79.92, + 41.63, + 65.23, + 80.39, + 37.1, + 81.92, + 1273.96, + 41.01, + 79.15, + 17.07 + ], + "cpu": [ + 9.7, + 13.3, + 10.3, + 10.0, + 9.4, + 23.0, + 17.6, + 10.6, + 13.1, + 6.5, + 6.2, + 1.3, + 8.4, + 5.4, + 1.3, + 1.2, + 1.8, + 1.6, + 0.9, + 10.0, + 4.2, + 0.8, + 1.8, + 1.6, + 2.2, + 2.6, + 1.9, + 2.8, + 7.4, + 8.7, + 7.1, + 5.6, + 6.2, + 14.3, + 8.5, + 5.8, + 9.0, + 6.9, + 3.9, + 5.5, + 5.8, + 5.9, + 6.4, + 7.5, + 6.6, + 6.1, + 8.7, + 17.4, + 12.9, + 4.0, + 6.3, + 7.4, + 6.1, + 5.4, + 6.6, + 5.7, + 6.7, + 9.3, + 6.7, + 5.5 + ], + "ram_used": [ + 43852685312, + 44052480000, + 44036640768, + 44033179648, + 44028084224, + 44053590016, + 44291584000, + 44290129920, + 44269481984, + 44257243136, + 44556734464, + 44502183936, + 44524433408, + 44526993408, + 44523057152, + 44523831296, + 44519899136, + 44508749824, + 44508250112, + 44527558656, + 44529721344, + 44527198208, + 44529672192, + 44530278400, + 44537171968, + 44538560512, + 44524920832, + 44552687616, + 44075163648, + 44090421248, + 44086198272, + 44085055488, + 44084731904, + 44364992512, + 44360019968, + 44359946240, + 44359090176, + 44604223488, + 44141965312, + 44142555136, + 44129452032, + 44121694208, + 44121939968, + 44354928640, + 44349378560, + 44349894656, + 44349890560, + 44144226304, + 44387663872, + 44206063616, + 44194983936, + 44169220096, + 44150177792, + 44142342144, + 44137152512, + 44138057728, + 44126892032, + 44160794624, + 44161884160, + 44383059968 + ], + "disk_read_mb": [ + 56.63, + 73.79, + 64.08, + 89.26, + 71.49, + 160.33, + 111.7, + 115.85, + 97.53, + 0.0, + 3.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.56, + 0.02, + 0.04, + 0.03, + 0.05, + 0.01, + 0.03, + 0.01, + 0.0, + 1.14, + 0.4, + 0.01, + 0.0, + 0.03, + 0.04, + 0.01, + 0.03, + 12.58, + 71.94, + 32.9, + 0.42, + 0.53, + 0.06, + 0.03, + 0.08, + 0.09, + 0.04, + 0.08, + 0.03, + 0.02, + 0.22, + 0.39 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 101.47, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 121.26 + ] + }, + "time": 1790717353.0661266 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json new file mode 100644 index 00000000..ef3f5dd6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-1.json @@ -0,0 +1,585 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "3e44ccd7ec28", + "corpus_repeated": false, + "time": "2026-09-29T21:18:00", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 11.385, + "e2e_s": 11.891, + "api_prompt_tps": 2486.9, + "api_decode_tps": 93.0, + "engine_prompt_tps": 2524.7, + "engine_decode_tps": 88.5, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 11215 ms (2524.7 tok/s), 48 generated in 542 ms (88.5 tok/s), drafts accepted 34 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24958 hits / 24960 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790716641.243247, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 2, + "mem_used": 16383934464, + "mem_total": 25769803776, + "temp": 43, + "power": 147.336 + }, + { + "index": 1, + "util": 7, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 48, + "power": 266.007 + } + ], + "gpu_util": 4.5, + "gpu_mem_used": 40611217408, + "gpu_mem_total": 51539607552, + "gpu_temp": 48, + "gpu_power": 413.343, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 16.8310546875, + "gpu_pcie_tx_mb": 71.810546875, + "cpu": 8.4, + "ram_used": 44637356032, + "ram_total": 177175990272, + "disk_read_mb": 2.277384309569965, + "disk_write_mb": 0.07927603609262536, + "tok_s": 96.0473472439008, + "tok_s_mean": 90.3424282028167 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408 + ], + "gpu_temp": [ + 44, + 43, + 43, + 43, + 43, + 43, + 44, + 44, + 43, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48 + ], + "gpu_power": [ + 253.73, + 239.29, + 238.99, + 238.62, + 238.58, + 238.53, + 238.39, + 238.34, + 238.4, + 238.51, + 238.61, + 238.53, + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.71, + 0.57, + 0.62, + 0.57, + 0.67, + 0.57, + 0.67, + 0.62, + 0.57, + 0.67, + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83 + ], + "cpu": [ + 0.0, + 0.6, + 1.0, + 1.6, + 2.5, + 1.0, + 3.1, + 8.1, + 6.5, + 1.2, + 1.9, + 2.1, + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4 + ], + "ram_used": [ + 43649658880, + 43652177920, + 43664764928, + 43666993152, + 43672375296, + 43665145856, + 43695276032, + 43759751168, + 43760455680, + 43757346816, + 43754053632, + 43711803392, + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05 + ] + }, + "time": 1790716693.048385 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json new file mode 100644 index 00000000..62fded25 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "0b6b57dfa6a4", + "corpus_repeated": false, + "time": "2026-09-29T21:18:13", + "prompt_tokens": 31634, + "completion_tokens": 55, + "ttft_s": 11.855, + "e2e_s": 12.398, + "api_prompt_tps": 2668.4, + "api_decode_tps": 99.4, + "engine_prompt_tps": 2704.3, + "engine_decode_tps": 98.6, + "log_lines": [ + "strata serve: prompt 31634 tokens = 0 reused + 31634 read in 11698 ms (2704.3 tok/s), 55 generated in 558 ms (98.6 tok/s), drafts accepted 38 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (29759 hits / 29760 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716693.1835682, + "duration_s": 12.3, + "finish": "stop", + "prompt_tokens": 31634, + "reused": 0, + "output_tokens": 55, + "engine_generated": 55, + "prompt_ms": 11697.7, + "decode_ms": 557.8, + "decode_tok_s": 98.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790716641.243247, + "requests": 2, + "prompt_tokens": 59948, + "reused": 0, + "output_tokens": 103, + "prompt_ms": 22912.300000000003, + "decode_ms": 1100.0 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 30, + "mem_used": 16392323072, + "mem_total": 25769803776, + "temp": 45, + "power": 154.497 + }, + { + "index": 1, + "util": 0, + "mem_used": 24241963008, + "mem_total": 25769803776, + "temp": 47, + "power": 250.412 + } + ], + "gpu_util": 15.0, + "gpu_mem_used": 40634286080, + "gpu_mem_total": 51539607552, + "gpu_temp": 47, + "gpu_power": 404.909, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 19.310546875, + "gpu_pcie_tx_mb": 48.8271484375, + "cpu": 8.6, + "ram_used": 44481728512, + "ram_total": 177175990272, + "disk_read_mb": 1.583864660002197, + "disk_write_mb": 0.12238954190926069, + "tok_s": 112.53532236859756, + "tok_s_mean": 97.92814776699883 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5, + 0.5, + 94.5, + 73.5, + 72.5, + 96.5, + 49.0, + 97.5, + 97.5, + 48.5, + 94.0, + 48.5, + 15.0 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40634286080 + ], + "gpu_temp": [ + 44, + 43, + 43, + 43, + 43, + 43, + 44, + 44, + 43, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48, + 45, + 51, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 47 + ], + "gpu_power": [ + 253.73, + 239.29, + 238.99, + 238.62, + 238.58, + 238.53, + 238.39, + 238.34, + 238.4, + 238.51, + 238.61, + 238.53, + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34, + 344.59, + 491.91, + 520.34, + 491.14, + 524.22, + 495.09, + 489.28, + 512.02, + 509.99, + 497.54, + 503.94, + 404.91 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.67, + 0.71, + 0.57, + 0.62, + 0.57, + 0.67, + 0.57, + 0.67, + 0.62, + 0.57, + 0.67, + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83, + 43.1, + 73.43, + 85.92, + 85.16, + 1285.6, + 83.21, + 5496.41, + 73.67, + 83.68, + 89.36, + 52.83, + 19.31 + ], + "cpu": [ + 0.0, + 0.6, + 1.0, + 1.6, + 2.5, + 1.0, + 3.1, + 8.1, + 6.5, + 1.2, + 1.9, + 2.1, + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4, + 5.5, + 16.9, + 8.9, + 8.2, + 6.7, + 6.4, + 6.4, + 5.5, + 7.3, + 10.1, + 6.1, + 8.6 + ], + "ram_used": [ + 43649658880, + 43652177920, + 43664764928, + 43666993152, + 43672375296, + 43665145856, + 43695276032, + 43759751168, + 43760455680, + 43757346816, + 43754053632, + 43711803392, + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032, + 44551315456, + 44588969984, + 44562165760, + 44546224128, + 44540850176, + 44543295488, + 44547391488, + 44375429120, + 44370026496, + 44363567104, + 44368113664, + 44481728512 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28, + 1.11, + 0.12, + 0.02, + 0.05, + 0.05, + 0.01, + 0.03, + 0.0, + 25.35, + 92.15, + 0.01, + 1.58 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 112.54 + ] + }, + "time": 1790716705.9498026 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json new file mode 100644 index 00000000..2c111c3f --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-Coder-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "caa0b992dd74", + "corpus_repeated": false, + "time": "2026-09-29T21:18:25", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 11.847, + "e2e_s": 12.249, + "api_prompt_tps": 2667.3, + "api_decode_tps": 109.5, + "engine_prompt_tps": 2704.5, + "engine_decode_tps": 108.1, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 11684 ms (2704.5 tok/s), 45 generated in 416 ms (108.1 tok/s), drafts accepted 33 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24000 hits / 24000 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-coder-iq1_m", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 4864, + "expert_cache_mib": 8968, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 9025, + "cvec": 0, + "arena_mib": 23981, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790716706.0904436, + "duration_s": 12.1, + "finish": "stop", + "prompt_tokens": 31601, + "reused": 0, + "output_tokens": 45, + "engine_generated": 45, + "prompt_ms": 11684.5, + "decode_ms": 416.2, + "decode_tok_s": 108.1, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716693.1835682, + "duration_s": 12.3, + "finish": "stop", + "prompt_tokens": 31634, + "reused": 0, + "output_tokens": 55, + "engine_generated": 55, + "prompt_ms": 11697.7, + "decode_ms": 557.8, + "decode_tok_s": 98.6, + "hit_rate": 1.0 + }, + { + "projection": null, + "time": 1790716680.7795944, + "duration_s": 11.8, + "finish": "stop", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 11214.6, + "decode_ms": 542.2, + "decode_tok_s": 88.5, + "hit_rate": 1.0 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790716641.243247, + "requests": 3, + "prompt_tokens": 91549, + "reused": 0, + "output_tokens": 148, + "prompt_ms": 34596.8, + "decode_ms": 1516.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 30, + "mem_used": 16392323072, + "mem_total": 25769803776, + "temp": 46, + "power": 161.526 + }, + { + "index": 1, + "util": 0, + "mem_used": 24241963008, + "mem_total": 25769803776, + "temp": 48, + "power": 223.689 + } + ], + "gpu_util": 15.0, + "gpu_mem_used": 40634286080, + "gpu_mem_total": 51539607552, + "gpu_temp": 48, + "gpu_power": 385.21500000000003, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.5703125, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 6.1, + "ram_used": 44274470912, + "ram_total": 177175990272, + "disk_read_mb": 0.14419269932051038, + "disk_write_mb": 0.2595468587769187, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 48.0, + 91.5, + 69.0, + 77.0, + 91.0, + 93.0, + 49.5, + 94.0, + 50.0, + 4.5, + 0.5, + 94.5, + 73.5, + 72.5, + 96.5, + 49.0, + 97.5, + 97.5, + 48.5, + 94.0, + 48.5, + 15.0, + 0.0, + 97.5, + 49.0, + 93.5, + 72.5, + 70.5, + 97.0, + 95.5, + 50.0, + 96.0, + 50.0, + 15.0 + ], + "gpu_mem_used": [ + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40426668032, + 40489582592, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40521039872, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40611217408, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080, + 40634286080 + ], + "gpu_temp": [ + 44, + 44, + 44, + 44, + 44, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 43, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 51, + 51, + 48, + 45, + 51, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 47, + 45, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 52, + 48 + ], + "gpu_power": [ + 238.49, + 238.83, + 238.96, + 238.97, + 226.8, + 148.88, + 73.97, + 64.38, + 63.94, + 63.69, + 63.56, + 63.75, + 63.53, + 63.8, + 63.68, + 63.62, + 63.84, + 63.74, + 63.81, + 64.11, + 63.92, + 63.72, + 63.85, + 63.64, + 63.78, + 139.81, + 418.68, + 508.54, + 520.36, + 495.57, + 522.4, + 506.1, + 501.02, + 508.77, + 509.32, + 413.34, + 344.59, + 491.91, + 520.34, + 491.14, + 524.22, + 495.09, + 489.28, + 512.02, + 509.99, + 497.54, + 503.94, + 404.91, + 336.42, + 502.95, + 510.85, + 498.42, + 519.36, + 492.86, + 501.0, + 522.94, + 497.46, + 508.62, + 494.37, + 385.22 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.57, + 1.05, + 0.57, + 0.76, + 0.81, + 0.81, + 0.81, + 0.76, + 0.76, + 0.81, + 0.86, + 1.43, + 0.81, + 0.81, + 0.76, + 0.86, + 0.81, + 0.76, + 0.95, + 0.86, + 0.86, + 0.76, + 0.86, + 0.86, + 70.24, + 68.14, + 64.66, + 75.24, + 42.29, + 84.73, + 70.48, + 75.05, + 54.45, + 44.44, + 16.83, + 43.1, + 73.43, + 85.92, + 85.16, + 1285.6, + 83.21, + 5496.41, + 73.67, + 83.68, + 89.36, + 52.83, + 19.31, + 45.11, + 82.73, + 85.31, + 43.06, + 94.36, + 41.63, + 73.48, + 42.01, + 87.26, + 45.92, + 121.97, + 0.57 + ], + "cpu": [ + 1.5, + 3.2, + 2.4, + 1.3, + 2.0, + 1.4, + 1.3, + 0.9, + 0.9, + 14.0, + 6.6, + 2.5, + 2.7, + 1.7, + 1.2, + 0.6, + 1.1, + 1.2, + 1.7, + 1.3, + 1.4, + 2.7, + 4.4, + 12.3, + 12.4, + 11.4, + 12.5, + 10.3, + 9.0, + 12.2, + 12.1, + 12.5, + 11.3, + 10.4, + 5.8, + 8.4, + 5.5, + 16.9, + 8.9, + 8.2, + 6.7, + 6.4, + 6.4, + 5.5, + 7.3, + 10.1, + 6.1, + 8.6, + 3.1, + 6.2, + 9.6, + 17.9, + 6.1, + 7.4, + 6.0, + 6.4, + 6.4, + 5.7, + 5.9, + 6.1 + ], + "ram_used": [ + 43717255168, + 43692584960, + 43693260800, + 43687956480, + 43682111488, + 43635728384, + 43632320512, + 43636883456, + 43633815552, + 43735252992, + 43881848832, + 43881005056, + 43875524608, + 43879301120, + 43878330368, + 43866976256, + 43862958080, + 43863728128, + 43854176256, + 43855548416, + 43854200832, + 43859615744, + 43895934976, + 43929411584, + 43962118144, + 44169498624, + 44107767808, + 44110077952, + 44109590528, + 44111515648, + 44233150464, + 44346421248, + 44340047872, + 44335108096, + 44329865216, + 44637356032, + 44551315456, + 44588969984, + 44562165760, + 44546224128, + 44540850176, + 44543295488, + 44547391488, + 44375429120, + 44370026496, + 44363567104, + 44368113664, + 44481728512, + 44224720896, + 44216463360, + 44188299264, + 44025966592, + 44017278976, + 44014284800, + 44060004352, + 44042358784, + 44044165120, + 44044423168, + 44044165120, + 44274470912 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 129.56, + 55.21, + 65.53, + 55.86, + 128.68, + 113.77, + 117.74, + 106.28, + 68.13, + 0.0, + 2.28, + 1.11, + 0.12, + 0.02, + 0.05, + 0.05, + 0.01, + 0.03, + 0.0, + 25.35, + 92.15, + 0.01, + 1.58, + 0.57, + 0.06, + 0.06, + 0.05, + 0.08, + 0.04, + 0.07, + 0.01, + 0.04, + 0.15, + 0.0, + 0.14 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 96.05, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 112.54, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790716718.7022452 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json new file mode 100644 index 00000000..420ad09b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-16k-1.json @@ -0,0 +1,750 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "1e52cb484c7f", + "corpus_repeated": false, + "time": "2026-09-29T21:55:17", + "prompt_tokens": 17345, + "completion_tokens": 8, + "ttft_s": 23.389, + "e2e_s": 23.454, + "api_prompt_tps": 741.6, + "api_decode_tps": 106.6, + "engine_prompt_tps": 744.7, + "engine_decode_tps": 101.7, + "log_lines": [ + "strata serve: prompt 17345 tokens = 0 reused + 17345 read in 23292 ms (744.7 tok/s), 8 generated in 79 ms (101.7 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (4159 hits / 4317 lookups)" + ], + "answer_head": "A466BDE8", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 5, + "totals": { + "since": 1790718725.4039552, + "requests": 5, + "prompt_tokens": 116388, + "reused": 0, + "output_tokens": 237, + "prompt_ms": 157531.5, + "decode_ms": 2436.8 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 5, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 125.093 + }, + { + "index": 1, + "util": 0, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 51, + "power": 215.964 + } + ], + "gpu_util": 2.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 341.057, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 16.5, + "ram_used": 70477971456, + "ram_total": 177175990272, + "disk_read_mb": 0.17303348536954039, + "disk_write_mb": 0.0036048642785320916, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 37.0, + 28.0, + 22.5, + 30.0, + 37.0, + 18.0, + 29.0, + 22.0, + 21.0, + 0.5, + 50.0, + 34.5, + 25.0, + 60.5, + 31.5, + 26.0, + 33.5, + 46.5, + 25.0, + 31.5, + 21.0, + 30.0, + 35.0, + 37.0, + 32.5, + 22.0, + 26.5, + 19.5, + 49.5, + 26.5, + 21.0, + 2.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 45, + 45, + 45, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 50, + 49, + 51, + 51, + 51, + 51, + 50, + 51, + 52, + 50, + 49, + 49, + 51, + 52, + 50, + 52, + 51, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 51, + 52, + 52, + 51, + 52, + 52, + 53, + 51 + ], + "gpu_power": [ + 242.53, + 242.44, + 242.38, + 242.52, + 242.49, + 242.46, + 242.59, + 242.37, + 242.36, + 242.5, + 242.54, + 140.5, + 84.6, + 65.59, + 65.03, + 64.81, + 64.81, + 64.9, + 64.51, + 64.65, + 64.87, + 64.67, + 64.8, + 64.5, + 64.56, + 64.64, + 64.52, + 64.48, + 252.37, + 388.02, + 363.78, + 375.15, + 399.66, + 368.5, + 396.75, + 362.75, + 365.62, + 336.59, + 296.73, + 407.69, + 367.08, + 376.76, + 397.12, + 384.8, + 382.99, + 408.25, + 371.72, + 397.41, + 373.98, + 388.78, + 413.99, + 362.47, + 402.46, + 358.68, + 403.34, + 387.12, + 369.06, + 426.5, + 375.9, + 341.06 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.62, + 0.67, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.67, + 0.71, + 0.81, + 0.81, + 0.86, + 0.81, + 0.86, + 0.81, + 0.86, + 0.76, + 0.81, + 0.86, + 0.81, + 0.95, + 0.81, + 0.86, + 0.86, + 0.86, + 0.71, + 7078.07, + 5438.42, + 7891.61, + 5618.71, + 5824.99, + 6656.5, + 6553.84, + 1295.8, + 3929.76, + 0.67, + 7089.76, + 6013.73, + 7916.07, + 5803.39, + 5749.08, + 4295.01, + 6229.4, + 7158.52, + 6448.94, + 8972.07, + 4133.89, + 5762.81, + 4218.58, + 7081.13, + 5446.96, + 19399.45, + 7164.1, + 6657.41, + 4340.22, + 8272.65, + 7551.43, + 0.67 + ], + "cpu": [ + 1.4, + 3.7, + 2.4, + 2.6, + 2.2, + 1.6, + 7.0, + 7.8, + 0.8, + 3.8, + 6.2, + 1.4, + 1.5, + 1.3, + 0.5, + 0.8, + 1.4, + 1.7, + 1.4, + 1.5, + 8.2, + 9.2, + 2.9, + 5.7, + 1.3, + 5.6, + 1.2, + 7.3, + 6.3, + 9.1, + 6.4, + 7.4, + 6.7, + 6.4, + 16.3, + 9.8, + 6.3, + 19.7, + 4.9, + 6.7, + 5.5, + 6.3, + 6.2, + 6.4, + 7.1, + 6.3, + 6.6, + 6.4, + 16.7, + 8.7, + 6.4, + 6.7, + 6.7, + 6.4, + 6.1, + 7.1, + 5.5, + 9.0, + 6.7, + 16.5 + ], + "ram_used": [ + 70616137728, + 70634639360, + 70632943616, + 70619291648, + 70622433280, + 70624546816, + 70651342848, + 70754201600, + 70754394112, + 70772871168, + 70811869184, + 70806048768, + 70788648960, + 70775001088, + 70770065408, + 70761766912, + 70762528768, + 70758371328, + 70767398912, + 70768398336, + 70723190784, + 70684524544, + 70713102336, + 70694293504, + 70656102400, + 70685872128, + 70679355392, + 70251024384, + 70250827776, + 70240993280, + 70217400320, + 70216302592, + 70220156928, + 70211788800, + 70218944512, + 70240178176, + 70232375296, + 70472826880, + 70432313344, + 70401486848, + 70392971264, + 70382305280, + 70365552640, + 70356713472, + 70348333056, + 70341337088, + 70134956032, + 70120873984, + 70109106176, + 70101512192, + 70084435968, + 70076407808, + 70066089984, + 70059646976, + 70027522048, + 70087983104, + 70087725056, + 70115901440, + 70239928320, + 70477971456 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.46, + 0.01, + 0.0, + 0.0, + 0.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.2, + 0.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.02, + 0.0, + 0.04, + 0.0, + 0.0, + 0.05, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.17 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718941.76262 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json new file mode 100644 index 00000000..fca49d31 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-28k-1.json @@ -0,0 +1,764 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "c61aafff2d90", + "corpus_repeated": false, + "time": "2026-09-29T21:55:41", + "prompt_tokens": 29827, + "completion_tokens": 8, + "ttft_s": 39.958, + "e2e_s": 40.036, + "api_prompt_tps": 746.5, + "api_decode_tps": 89.7, + "engine_prompt_tps": 749.2, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 29827 tokens = 0 reused + 29827 read in 39812 ms (749.2 tok/s), 8 generated in 93 ms (85.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.2% (4154 hits / 4318 lookups)" + ], + "answer_head": "7BDBA3C1", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718941.8879943, + "duration_s": 39.9, + "finish": "stop", + "prompt_tokens": 29827, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 39812.1, + "decode_ms": 93.1, + "decode_tok_s": 85.9, + "hit_rate": 0.962 + }, + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 6, + "totals": { + "since": 1790718725.4039552, + "requests": 6, + "prompt_tokens": 146215, + "reused": 0, + "output_tokens": 245, + "prompt_ms": 197343.6, + "decode_ms": 2529.9 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 47, + "power": 130.942 + }, + { + "index": 1, + "util": 42, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 53, + "power": 227.639 + } + ], + "gpu_util": 21.0, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 358.581, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 6.3, + "ram_used": 70479159296, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.014414807554752778, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 50.0, + 34.5, + 25.0, + 60.5, + 31.5, + 26.0, + 33.5, + 46.5, + 25.0, + 31.5, + 21.0, + 30.0, + 35.0, + 37.0, + 32.5, + 22.0, + 26.5, + 19.5, + 49.5, + 26.5, + 21.0, + 2.5, + 50.5, + 42.0, + 43.0, + 38.0, + 32.0, + 21.5, + 29.0, + 34.0, + 13.5, + 36.0, + 23.0, + 30.0, + 11.0, + 77.5, + 34.5, + 23.5, + 29.0, + 17.5, + 69.0, + 34.5, + 23.5, + 32.5, + 24.5, + 57.5, + 32.0, + 26.0, + 33.5, + 25.0, + 32.0, + 32.5, + 22.5, + 36.0, + 37.0, + 36.5, + 28.5, + 42.5, + 21.0 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 50, + 49, + 49, + 51, + 52, + 50, + 52, + 51, + 51, + 51, + 51, + 52, + 51, + 52, + 51, + 51, + 52, + 52, + 51, + 52, + 52, + 53, + 51, + 50, + 50, + 51, + 53, + 51, + 52, + 52, + 51, + 52, + 51, + 52, + 52, + 52, + 53, + 52, + 52, + 51, + 51, + 53, + 52, + 52, + 52, + 52, + 52, + 51, + 53, + 52, + 52, + 52, + 52, + 53, + 52, + 53, + 52, + 53, + 52, + 53 + ], + "gpu_power": [ + 336.59, + 296.73, + 407.69, + 367.08, + 376.76, + 397.12, + 384.8, + 382.99, + 408.25, + 371.72, + 397.41, + 373.98, + 388.78, + 413.99, + 362.47, + 402.46, + 358.68, + 403.34, + 387.12, + 369.06, + 426.5, + 375.9, + 341.06, + 316.12, + 396.45, + 370.14, + 378.61, + 411.6, + 381.87, + 383.44, + 399.03, + 378.32, + 399.6, + 372.43, + 400.43, + 390.19, + 384.29, + 405.22, + 398.65, + 405.33, + 377.77, + 347.82, + 408.44, + 395.16, + 399.76, + 391.18, + 383.68, + 395.97, + 381.79, + 371.58, + 387.34, + 367.36, + 390.18, + 377.99, + 404.54, + 406.77, + 371.21, + 404.91, + 389.57, + 358.58 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 7089.76, + 6013.73, + 7916.07, + 5803.39, + 5749.08, + 4295.01, + 6229.4, + 7158.52, + 6448.94, + 8972.07, + 4133.89, + 5762.81, + 4218.58, + 7081.13, + 5446.96, + 19399.45, + 7164.1, + 6657.41, + 4340.22, + 8272.65, + 7551.43, + 0.67, + 5912.64, + 6668.66, + 4836.32, + 15187.07, + 6919.96, + 7012.13, + 4668.04, + 8340.98, + 5615.52, + 6986.24, + 8358.29, + 8231.35, + 7154.13, + 6558.46, + 5322.65, + 14744.81, + 6437.3, + 7645.75, + 4067.04, + 5734.82, + 1.62, + 5507.04, + 5994.7, + 5715.7, + 6093.12, + 89.88, + 6215.57, + 4331.35, + 6045.63, + 5971.19, + 6178.04, + 5846.59, + 7484.53, + 5744.65, + 5095.67, + 7809.07, + 0.67 + ], + "cpu": [ + 19.7, + 4.9, + 6.7, + 5.5, + 6.3, + 6.2, + 6.4, + 7.1, + 6.3, + 6.6, + 6.4, + 16.7, + 8.7, + 6.4, + 6.7, + 6.7, + 6.4, + 6.1, + 7.1, + 5.5, + 9.0, + 6.7, + 16.5, + 4.3, + 8.5, + 17.0, + 10.5, + 8.0, + 8.5, + 6.2, + 6.8, + 6.0, + 6.0, + 5.6, + 6.4, + 7.1, + 5.6, + 6.3, + 11.3, + 13.8, + 13.6, + 7.0, + 5.8, + 6.1, + 6.1, + 6.3, + 6.2, + 6.0, + 9.3, + 6.5, + 6.1, + 6.0, + 14.5, + 11.7, + 5.6, + 8.6, + 7.7, + 6.1, + 6.7, + 6.3 + ], + "ram_used": [ + 70472826880, + 70432313344, + 70401486848, + 70392971264, + 70382305280, + 70365552640, + 70356713472, + 70348333056, + 70341337088, + 70134956032, + 70120873984, + 70109106176, + 70101512192, + 70084435968, + 70076407808, + 70066089984, + 70059646976, + 70027522048, + 70087983104, + 70087725056, + 70115901440, + 70239928320, + 70477971456, + 70343557120, + 70337265664, + 70309584896, + 70434922496, + 70428250112, + 70420987904, + 70412926976, + 70409207808, + 70400454656, + 70391336960, + 70383079424, + 70374731776, + 70367465472, + 70359465984, + 70354010112, + 70334316544, + 70343401472, + 70345613312, + 70344155136, + 70340018176, + 70356168704, + 70375772160, + 70372450304, + 70371860480, + 70366474240, + 70373842944, + 70374035456, + 70365605888, + 70363926528, + 70340509696, + 70341251072, + 70340546560, + 70343122944, + 70346379264, + 70347120640, + 70345048064, + 70479159296 + ], + "disk_read_mb": [ + 0.2, + 0.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.02, + 0.0, + 0.04, + 0.0, + 0.0, + 0.05, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.17, + 0.53, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.6, + 0.0, + 0.03, + 0.0, + 0.0, + 0.05, + 0.0, + 0.0, + 0.05, + 0.0, + 0.05, + 0.0, + 0.0, + 0.03, + 0.0, + 0.04, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718982.302463 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json new file mode 100644 index 00000000..e510b110 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-needle/needle-8k-1.json @@ -0,0 +1,736 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "7c040dd4c6d7", + "corpus_repeated": false, + "time": "2026-09-29T21:55:06", + "prompt_tokens": 7491, + "completion_tokens": 8, + "ttft_s": 10.682, + "e2e_s": 10.776, + "api_prompt_tps": 701.3, + "api_decode_tps": 74.7, + "engine_prompt_tps": 705.0, + "engine_decode_tps": 73.1, + "log_lines": [ + "strata serve: prompt 7491 tokens = 0 reused + 7491 read in 10625 ms (705.0 tok/s), 8 generated in 109 ms (73.1 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 90.2% (3891 hits / 4313 lookups)" + ], + "answer_head": "C43C98BD", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 4, + "totals": { + "since": 1790718725.4039552, + "requests": 4, + "prompt_tokens": 99043, + "reused": 0, + "output_tokens": 229, + "prompt_ms": 134239.3, + "decode_ms": 2358.1000000000004 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 1, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 122.865 + }, + { + "index": 1, + "util": 0, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 213.727 + } + ], + "gpu_util": 0.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 336.592, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 19.7, + "ram_used": 70472826880, + "ram_total": 177175990272, + "disk_read_mb": 0.2018157842351215, + "disk_write_mb": 0.28470440990311785, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 25.0, + 33.5, + 47.0, + 15.5, + 32.5, + 24.0, + 32.5, + 29.0, + 55.0, + 34.0, + 48.0, + 33.0, + 22.5, + 31.5, + 24.5, + 20.0, + 20.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 37.0, + 28.0, + 22.5, + 30.0, + 37.0, + 18.0, + 29.0, + 22.0, + 21.0, + 0.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 50, + 52, + 52, + 52, + 51, + 52, + 52, + 50, + 49, + 49, + 49, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 45, + 45, + 45, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 50, + 49, + 51, + 51, + 51, + 51, + 50, + 51, + 52, + 50 + ], + "gpu_power": [ + 380.19, + 386.69, + 409.76, + 359.41, + 400.68, + 368.54, + 396.07, + 393.99, + 371.52, + 407.92, + 367.65, + 416.33, + 386.19, + 394.79, + 409.75, + 373.56, + 329.84, + 371.48, + 309.69, + 279.06, + 254.32, + 242.47, + 242.53, + 242.44, + 242.38, + 242.52, + 242.49, + 242.46, + 242.59, + 242.37, + 242.36, + 242.5, + 242.54, + 140.5, + 84.6, + 65.59, + 65.03, + 64.81, + 64.81, + 64.9, + 64.51, + 64.65, + 64.87, + 64.67, + 64.8, + 64.5, + 64.56, + 64.64, + 64.52, + 64.48, + 252.37, + 388.02, + 363.78, + 375.15, + 399.66, + 368.5, + 396.75, + 362.75, + 365.62, + 336.59 + ], + "gpu_pcie_rx_mb": [ + 5368.61, + 7806.78, + 7675.93, + 8469.58, + 5669.88, + 14723.06, + 5790.85, + 6188.01, + 6980.23, + 7332.23, + 12898.87, + 6754.21, + 6340.74, + 6000.61, + 6420.09, + 4455.66, + 19.74, + 0.62, + 0.62, + 0.57, + 0.67, + 0.62, + 0.62, + 0.62, + 0.67, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.67, + 0.71, + 0.81, + 0.81, + 0.86, + 0.81, + 0.86, + 0.81, + 0.86, + 0.76, + 0.81, + 0.86, + 0.81, + 0.95, + 0.81, + 0.86, + 0.86, + 0.86, + 0.71, + 7078.07, + 5438.42, + 7891.61, + 5618.71, + 5824.99, + 6656.5, + 6553.84, + 1295.8, + 3929.76, + 0.67 + ], + "cpu": [ + 7.3, + 17.5, + 8.0, + 7.9, + 6.6, + 6.2, + 6.2, + 6.1, + 6.6, + 5.7, + 6.8, + 7.1, + 7.8, + 6.2, + 9.8, + 15.0, + 32.2, + 20.2, + 4.3, + 11.3, + 2.0, + 1.5, + 1.4, + 3.7, + 2.4, + 2.6, + 2.2, + 1.6, + 7.0, + 7.8, + 0.8, + 3.8, + 6.2, + 1.4, + 1.5, + 1.3, + 0.5, + 0.8, + 1.4, + 1.7, + 1.4, + 1.5, + 8.2, + 9.2, + 2.9, + 5.7, + 1.3, + 5.6, + 1.2, + 7.3, + 6.3, + 9.1, + 6.4, + 7.4, + 6.7, + 6.4, + 16.3, + 9.8, + 6.3, + 19.7 + ], + "ram_used": [ + 70159552512, + 70270476288, + 70270668800, + 70271184896, + 70263926784, + 70264184832, + 70264291328, + 70265167872, + 70267035648, + 70267035648, + 70264389632, + 70261067776, + 70265782272, + 70268100608, + 70275043328, + 70091866112, + 70312075264, + 70311395328, + 70465576960, + 70613889024, + 70610006016, + 70609461248, + 70616137728, + 70634639360, + 70632943616, + 70619291648, + 70622433280, + 70624546816, + 70651342848, + 70754201600, + 70754394112, + 70772871168, + 70811869184, + 70806048768, + 70788648960, + 70775001088, + 70770065408, + 70761766912, + 70762528768, + 70758371328, + 70767398912, + 70768398336, + 70723190784, + 70684524544, + 70713102336, + 70694293504, + 70656102400, + 70685872128, + 70679355392, + 70251024384, + 70250827776, + 70240993280, + 70217400320, + 70216302592, + 70220156928, + 70211788800, + 70218944512, + 70240178176, + 70232375296, + 70472826880 + ], + "disk_read_mb": [ + 0.0, + 0.04, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.01, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.09, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.46, + 0.01, + 0.0, + 0.0, + 0.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.2 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.75, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790718917.804988 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json new file mode 100644 index 00000000..49166bd7 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto-two-turn/two-turn-16k-1.json @@ -0,0 +1,797 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "2fd93144a29a", + "corpus_repeated": false, + "time": "2026-09-29T21:56:47", + "prompt_tokens": 15639, + "completion_tokens": 83, + "ttft_s": 21.242, + "e2e_s": 22.071, + "api_prompt_tps": 736.2, + "api_decode_tps": 98.8, + "engine_prompt_tps": 739.4, + "engine_decode_tps": 98.3, + "log_lines": [ + "strata serve: prompt 15639 tokens = 0 reused + 15639 read in 21151 ms (739.4 tok/s), 83 generated in 844 ms (98.3 tok/s), drafts accepted 53 of 73, 1 checkpoints", + "strata serve: decode expert cache hit rate: 98.5% (48689 hits / 49415 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "turn2_ttft_s": 0.627, + "turn2_prompt_tokens": 15676, + "turn2_log_lines": [ + "strata serve: prompt 15676 tokens = 15632 reused + 44 read in 521 ms (84.4 tok/s), 64 generated in 739 ms (86.6 tok/s), drafts accepted 37 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (36768 hits / 37868 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719030.332211, + "duration_s": 1.3, + "finish": "length", + "prompt_tokens": 15676, + "reused": 15632, + "output_tokens": 64, + "engine_generated": 64, + "prompt_ms": 521.0, + "decode_ms": 739.1, + "decode_tok_s": 86.6, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790719007.7458334, + "duration_s": 22.0, + "finish": "stop", + "prompt_tokens": 15639, + "reused": 0, + "output_tokens": 83, + "engine_generated": 83, + "prompt_ms": 21150.9, + "decode_ms": 844.3, + "decode_tok_s": 98.3, + "hit_rate": 0.985 + }, + { + "projection": null, + "time": 1790718941.8879943, + "duration_s": 39.9, + "finish": "stop", + "prompt_tokens": 29827, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 39812.1, + "decode_ms": 93.1, + "decode_tok_s": 85.9, + "hit_rate": 0.962 + }, + { + "projection": null, + "time": 1790718917.8830457, + "duration_s": 23.4, + "finish": "stop", + "prompt_tokens": 17345, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 23292.2, + "decode_ms": 78.7, + "decode_tok_s": 101.7, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790718906.5660036, + "duration_s": 10.7, + "finish": "stop", + "prompt_tokens": 7491, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 10625.3, + "decode_ms": 109.4, + "decode_tok_s": 73.1, + "hit_rate": 0.902 + }, + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 8, + "totals": { + "since": 1790718725.4039552, + "requests": 8, + "prompt_tokens": 177530, + "reused": 15632, + "output_tokens": 392, + "prompt_ms": 219015.5, + "decode_ms": 4113.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 41, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 50, + "power": 209.466 + }, + { + "index": 1, + "util": 49, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 53, + "power": 186.867 + } + ], + "gpu_util": 45.0, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 396.33299999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 2090.7392578125, + "gpu_pcie_tx_mb": 103.1865234375, + "cpu": 82.0, + "ram_used": 70765735936, + "ram_total": 177175990272, + "disk_read_mb": 3.548661248401337, + "disk_write_mb": 0.003595401467478558, + "tok_s": 85.02069488627261, + "tok_s_mean": 85.60127593635436 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 57.5, + 32.0, + 26.0, + 33.5, + 25.0, + 32.0, + 32.5, + 22.5, + 36.0, + 37.0, + 36.5, + 28.5, + 42.5, + 21.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 32.0, + 30.5, + 25.5, + 63.5, + 34.5, + 24.5, + 36.0, + 38.0, + 28.0, + 33.0, + 21.5, + 25.0, + 41.5, + 33.0, + 30.0, + 22.0, + 29.5, + 19.5, + 23.5, + 48.0, + 0.0, + 45.0 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 52, + 51, + 53, + 52, + 52, + 52, + 52, + 53, + 52, + 53, + 52, + 53, + 52, + 53, + 51, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 47, + 46, + 46, + 46, + 46, + 45, + 45, + 45, + 51, + 51, + 51, + 52, + 51, + 53, + 52, + 53, + 52, + 52, + 53, + 52, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 51, + 53 + ], + "gpu_power": [ + 383.68, + 395.97, + 381.79, + 371.58, + 387.34, + 367.36, + 390.18, + 377.99, + 404.54, + 406.77, + 371.21, + 404.91, + 389.57, + 358.58, + 310.16, + 278.39, + 242.88, + 242.69, + 242.56, + 242.41, + 242.25, + 242.45, + 242.44, + 242.38, + 242.25, + 242.18, + 242.52, + 242.57, + 242.25, + 242.23, + 197.61, + 110.58, + 65.55, + 65.12, + 65.0, + 65.02, + 65.01, + 64.82, + 155.28, + 410.36, + 361.72, + 382.57, + 404.0, + 377.89, + 389.35, + 407.89, + 389.48, + 386.49, + 371.41, + 379.85, + 411.79, + 387.4, + 395.89, + 369.99, + 400.03, + 390.77, + 393.61, + 354.25, + 413.98, + 396.33 + ], + "gpu_pcie_rx_mb": [ + 5715.7, + 6093.12, + 89.88, + 6215.57, + 4331.35, + 6045.63, + 5971.19, + 6178.04, + 5846.59, + 7484.53, + 5744.65, + 5095.67, + 7809.07, + 0.67, + 0.71, + 0.57, + 0.67, + 0.62, + 0.62, + 0.57, + 0.71, + 0.62, + 0.57, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 0.71, + 0.91, + 0.81, + 0.76, + 0.81, + 0.76, + 0.81, + 0.86, + 0.86, + 6219.24, + 5437.52, + 6447.08, + 6610.58, + 6506.2, + 88.93, + 6106.14, + 6218.53, + 5297.85, + 8021.88, + 67.85, + 4886.82, + 6395.77, + 5794.95, + 5961.99, + 92.79, + 4561.42, + 5886.93, + 4115.39, + 15.07, + 6036.38, + 2090.74 + ], + "cpu": [ + 6.2, + 6.0, + 9.3, + 6.5, + 6.1, + 6.0, + 14.5, + 11.7, + 5.6, + 8.6, + 7.7, + 6.1, + 6.7, + 6.3, + 15.2, + 4.0, + 11.7, + 1.7, + 0.8, + 1.6, + 10.1, + 8.8, + 1.8, + 3.0, + 2.0, + 1.1, + 3.9, + 2.5, + 1.2, + 1.0, + 4.4, + 2.2, + 2.1, + 1.1, + 9.2, + 4.0, + 0.7, + 12.8, + 6.2, + 7.1, + 6.6, + 6.1, + 5.7, + 6.8, + 7.9, + 5.9, + 6.1, + 7.1, + 16.6, + 14.8, + 6.4, + 6.7, + 6.6, + 7.0, + 6.5, + 7.1, + 6.4, + 44.5, + 46.9, + 82.0 + ], + "ram_used": [ + 70371860480, + 70366474240, + 70373842944, + 70374035456, + 70365605888, + 70363926528, + 70340509696, + 70341251072, + 70340546560, + 70343122944, + 70346379264, + 70347120640, + 70345048064, + 70479159296, + 70572703744, + 70652428288, + 70736793600, + 70729584640, + 70733873152, + 70729728000, + 70753632256, + 70894960640, + 70882795520, + 70887088128, + 70877409280, + 70896922624, + 70917816320, + 70944993280, + 70949908480, + 70948433920, + 70969233408, + 70968532992, + 70973911040, + 70965530624, + 70981591040, + 70982193152, + 70979321856, + 71007891456, + 70533447680, + 70536957952, + 70444630016, + 70438658048, + 70435995648, + 70428848128, + 70422986752, + 70424240128, + 70404268032, + 70411444224, + 70518763520, + 70541369344, + 70539395072, + 70538240000, + 70528540672, + 70514954240, + 70316679168, + 70304641024, + 70310481920, + 70539440128, + 70546964480, + 70765735936 + ], + "disk_read_mb": [ + 0.05, + 0.0, + 0.0, + 0.03, + 0.0, + 0.04, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.48, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.01, + 0.0, + 0.03, + 0.0, + 0.0, + 0.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.21, + 0.47, + 3.55 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 106.42, + 0.0, + 85.02 + ] + }, + "time": 1790719032.1000419 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json new file mode 100644 index 00000000..443e5220 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-1.json @@ -0,0 +1,648 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "e13c9cdd6797", + "corpus_repeated": false, + "time": "2026-09-29T21:52:23", + "prompt_tokens": 28315, + "completion_tokens": 84, + "ttft_s": 39.45, + "e2e_s": 40.422, + "api_prompt_tps": 717.7, + "api_decode_tps": 85.4, + "engine_prompt_tps": 720.7, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28315 tokens = 0 reused + 28315 read in 39287 ms (720.7 tok/s), 84 generated in 1011 ms (83.1 tok/s), drafts accepted 56 of 67, 2 checkpoints", + "strata serve: decode expert cache hit rate: 94.9% (43073 hits / 45377 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context and find the relevant files.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790718725.4039552, + "requests": 1, + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 39, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 45, + "power": 141.739 + }, + { + "index": 1, + "util": 48, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 205.268 + } + ], + "gpu_util": 43.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 347.007, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 6170.3671875, + "gpu_pcie_tx_mb": 126.7900390625, + "cpu": 85.9, + "ram_used": 70739390464, + "ram_total": 177175990272, + "disk_read_mb": 3.315986845192439, + "disk_write_mb": 0.09340808014626588, + "tok_s": 93.51552437654362, + "tok_s_mean": 85.24938371584437 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 57.0, + 32.5, + 23.5, + 25.0, + 22.0, + 51.0, + 35.5, + 33.0, + 27.5, + 26.0, + 41.0, + 33.0, + 23.5, + 29.5, + 27.5, + 71.0, + 31.5, + 21.5, + 64.0, + 36.5, + 20.5, + 32.5, + 30.5, + 22.0, + 29.0, + 24.5, + 30.0, + 17.5, + 76.0, + 25.0, + 20.5, + 30.0, + 23.0, + 19.0, + 24.0, + 43.5 + ], + "gpu_mem_used": [ + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49224220672, + 49316495360, + 49326981120, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49440227328 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 44, + 47, + 46, + 49, + 47, + 49, + 49, + 49, + 49, + 48, + 49, + 48, + 48, + 49, + 48, + 48, + 50, + 48, + 48, + 48, + 48, + 49, + 48, + 48, + 49, + 48, + 50, + 49, + 49, + 51, + 48, + 50, + 48, + 49, + 50, + 50, + 50 + ], + "gpu_power": [ + 239.92, + 240.19, + 239.81, + 239.35, + 239.3, + 239.28, + 239.24, + 239.29, + 239.41, + 239.46, + 239.45, + 239.36, + 239.21, + 239.26, + 239.32, + 239.37, + 225.06, + 145.42, + 158.12, + 371.86, + 384.05, + 358.93, + 405.61, + 381.25, + 384.16, + 389.93, + 395.3, + 399.41, + 384.35, + 363.41, + 386.79, + 392.7, + 344.05, + 389.76, + 383.66, + 397.8, + 373.05, + 366.9, + 391.72, + 366.3, + 381.76, + 387.41, + 366.67, + 395.88, + 403.84, + 386.94, + 392.83, + 352.42, + 402.48, + 392.8, + 357.94, + 383.58, + 359.24, + 350.73, + 347.01 + ], + "gpu_pcie_rx_mb": [ + 0.62, + 0.67, + 0.67, + 0.62, + 0.62, + 0.57, + 0.57, + 0.57, + 0.62, + 0.67, + 0.67, + 0.62, + 0.62, + 0.62, + 0.62, + 0.62, + 0.76, + 14.92, + 6198.41, + 7236.0, + 8724.26, + 3654.86, + 5959.32, + 6449.94, + 6329.34, + 7285.26, + 4763.84, + 6812.52, + 7321.69, + 6494.14, + 5619.86, + 6789.97, + 5793.67, + 5562.64, + 2331.69, + 6177.52, + 8354.0, + 7435.75, + 4811.38, + 1.43, + 7506.18, + 7562.16, + 2886.44, + 7184.17, + 6752.54, + 7546.95, + 7499.69, + 4610.3, + 6852.1, + 6167.22, + 5107.31, + 7326.55, + 4237.65, + 0.67, + 6170.37 + ], + "cpu": [ + 100.0, + 1.4, + 1.1, + 0.9, + 1.2, + 2.3, + 0.9, + 1.3, + 9.5, + 5.4, + 6.6, + 4.7, + 1.3, + 1.2, + 1.8, + 2.0, + 0.8, + 11.3, + 10.6, + 10.4, + 5.7, + 6.8, + 17.0, + 10.2, + 8.1, + 7.1, + 6.9, + 7.6, + 9.8, + 9.9, + 5.8, + 6.7, + 11.0, + 6.0, + 9.4, + 6.2, + 15.2, + 12.9, + 8.4, + 7.2, + 10.2, + 6.1, + 10.5, + 6.4, + 6.0, + 9.0, + 7.4, + 8.9, + 6.9, + 8.7, + 15.6, + 12.0, + 6.3, + 6.8, + 85.9 + ], + "ram_used": [ + 70239571968, + 70088245248, + 70096302080, + 70097154048, + 70103457792, + 70078648320, + 70084857856, + 70088122368, + 70148214784, + 70162341888, + 70191161344, + 70190673920, + 70184566784, + 70184079360, + 70179979264, + 70173462528, + 70171906048, + 70119723008, + 70266146816, + 70263320576, + 70263308288, + 70262693888, + 70372823040, + 70378594304, + 70380400640, + 70383910912, + 70389587968, + 70366543872, + 70385344512, + 70382903296, + 70379986944, + 70372298752, + 70358667264, + 70367678464, + 70356070400, + 70353756160, + 70321405952, + 70284603392, + 70262280192, + 70387703808, + 70314864640, + 70312120320, + 70299967488, + 70299987968, + 70294355968, + 70301368320, + 70293327872, + 70290792448, + 70280925184, + 70300200960, + 70377836544, + 70448394240, + 70448910336, + 70574612480, + 70739390464 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 4.75, + 124.76, + 40.78, + 0.0, + 7.5, + 16.84, + 0.0, + 55.72, + 0.0, + 13.03, + 20.5, + 0.0, + 67.32, + 0.0, + 0.0, + 83.74, + 0.0, + 80.89, + 0.0, + 0.0, + 71.3, + 0.0, + 0.0, + 79.43, + 0.0, + 72.4, + 4.53, + 0.0, + 54.62, + 0.0, + 42.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.32 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 93.52 + ] + }, + "time": 1790718784.6773934 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json new file mode 100644 index 00000000..719fcb2d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f953f67441b4", + "corpus_repeated": false, + "time": "2026-09-29T21:53:04", + "prompt_tokens": 31633, + "completion_tokens": 88, + "ttft_s": 42.403, + "e2e_s": 43.165, + "api_prompt_tps": 746.0, + "api_decode_tps": 114.2, + "engine_prompt_tps": 749.3, + "engine_decode_tps": 113.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 42217 ms (749.3 tok/s), 88 generated in 777 ms (113.3 tok/s), drafts accepted 61 of 69, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.8% (45031 hits / 46048 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790718725.4039552, + "requests": 2, + "prompt_tokens": 59948, + "reused": 0, + "output_tokens": 172, + "prompt_ms": 81503.2, + "decode_ms": 1787.8000000000002 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 46, + "power": 127.404 + }, + { + "index": 1, + "util": 22, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 202.736 + } + ], + "gpu_util": 32.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 330.14, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 50.97265625, + "gpu_pcie_tx_mb": 74.43359375, + "cpu": 47.4, + "ram_used": 70762872832, + "ram_total": 177175990272, + "disk_read_mb": 0.9085358249169909, + "disk_write_mb": 0.21546304148229034, + "tok_s": 110.51273259801776, + "tok_s_mean": 104.51731108020398 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 31.5, + 21.5, + 64.0, + 36.5, + 20.5, + 32.5, + 30.5, + 22.0, + 29.0, + 24.5, + 30.0, + 17.5, + 76.0, + 25.0, + 20.5, + 30.0, + 23.0, + 19.0, + 24.0, + 43.5, + 0.0, + 41.5, + 33.5, + 27.5, + 34.0, + 22.0, + 61.5, + 37.0, + 23.5, + 24.5, + 28.5, + 54.0, + 41.5, + 89.5, + 30.5, + 21.0, + 32.0, + 33.5, + 24.5, + 26.0, + 25.5, + 38.5, + 31.5, + 24.5, + 30.0, + 26.0, + 31.5, + 19.0, + 86.5, + 28.0, + 22.5, + 32.0, + 26.0, + 77.5, + 22.5, + 22.5, + 34.0, + 26.0, + 20.5, + 32.5 + ], + "gpu_mem_used": [ + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49333272576, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 49, + 48, + 48, + 49, + 48, + 50, + 49, + 49, + 51, + 48, + 50, + 48, + 49, + 50, + 50, + 50, + 47, + 48, + 48, + 50, + 49, + 50, + 49, + 49, + 50, + 49, + 50, + 49, + 50, + 51, + 49, + 50, + 50, + 49, + 50, + 50, + 51, + 50, + 49, + 50, + 49, + 51, + 49, + 50, + 51, + 49, + 50, + 50, + 51, + 52, + 50, + 50, + 50, + 51, + 52, + 50 + ], + "gpu_power": [ + 397.8, + 373.05, + 366.9, + 391.72, + 366.3, + 381.76, + 387.41, + 366.67, + 395.88, + 403.84, + 386.94, + 392.83, + 352.42, + 402.48, + 392.8, + 357.94, + 383.58, + 359.24, + 350.73, + 347.01, + 325.66, + 372.55, + 370.97, + 352.05, + 397.27, + 391.66, + 343.17, + 403.13, + 366.16, + 402.14, + 390.68, + 396.82, + 401.28, + 360.7, + 398.3, + 366.48, + 382.49, + 395.03, + 366.16, + 401.29, + 385.57, + 368.88, + 396.03, + 374.4, + 393.23, + 385.24, + 406.68, + 391.86, + 364.28, + 409.58, + 388.38, + 389.1, + 390.65, + 372.81, + 415.25, + 390.44, + 384.85, + 382.05, + 377.98, + 330.14 + ], + "gpu_pcie_rx_mb": [ + 6177.52, + 8354.0, + 7435.75, + 4811.38, + 1.43, + 7506.18, + 7562.16, + 2886.44, + 7184.17, + 6752.54, + 7546.95, + 7499.69, + 4610.3, + 6852.1, + 6167.22, + 5107.31, + 7326.55, + 4237.65, + 0.67, + 6170.37, + 5107.54, + 5192.28, + 6336.26, + 3422.45, + 4911.8, + 7759.14, + 6146.0, + 4671.1, + 9668.92, + 5712.17, + 6061.89, + 4888.06, + 5886.08, + 9090.42, + 5683.33, + 6294.68, + 7625.39, + 4995.82, + 12979.6, + 4392.43, + 6062.41, + 5581.95, + 5691.53, + 8234.83, + 8344.89, + 7880.73, + 6094.07, + 8294.58, + 5858.85, + 5465.17, + 6922.82, + 4432.29, + 6296.59, + 5837.44, + 7103.97, + 7604.84, + 4756.35, + 4899.02, + 5517.96, + 50.97 + ], + "cpu": [ + 6.2, + 15.2, + 12.9, + 8.4, + 7.2, + 10.2, + 6.1, + 10.5, + 6.4, + 6.0, + 9.0, + 7.4, + 8.9, + 6.9, + 8.7, + 15.6, + 12.0, + 6.3, + 6.8, + 85.9, + 9.8, + 9.7, + 6.7, + 6.6, + 6.8, + 7.4, + 7.1, + 7.1, + 12.2, + 13.8, + 6.7, + 8.5, + 6.5, + 6.1, + 6.4, + 6.5, + 6.1, + 7.2, + 6.6, + 7.4, + 6.1, + 6.8, + 12.8, + 11.1, + 6.2, + 6.4, + 6.4, + 6.1, + 6.3, + 8.7, + 7.4, + 9.4, + 6.3, + 7.9, + 6.5, + 6.4, + 15.4, + 9.4, + 6.3, + 47.4 + ], + "ram_used": [ + 70353756160, + 70321405952, + 70284603392, + 70262280192, + 70387703808, + 70314864640, + 70312120320, + 70299967488, + 70299987968, + 70294355968, + 70301368320, + 70293327872, + 70290792448, + 70280925184, + 70300200960, + 70377836544, + 70448394240, + 70448910336, + 70574612480, + 70739390464, + 70512533504, + 70533234688, + 70513684480, + 70496215040, + 70484873216, + 70469386240, + 70452416512, + 70445555712, + 70424002560, + 70434533376, + 70424702976, + 70408409088, + 70395523072, + 70388035584, + 70353256448, + 70333558784, + 70326820864, + 70357315584, + 70361923584, + 70355750912, + 70357520384, + 70490038272, + 70530985984, + 70524338176, + 70524243968, + 70525259776, + 70528827392, + 70526148608, + 70526631936, + 70541975552, + 70541778944, + 70536822784, + 70537621504, + 70537134080, + 70534877184, + 70532685824, + 70529556480, + 70530998272, + 70534545408, + 70762872832 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 71.3, + 0.0, + 0.0, + 79.43, + 0.0, + 72.4, + 4.53, + 0.0, + 54.62, + 0.0, + 42.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.32, + 0.6, + 0.01, + 0.0, + 0.01, + 0.0, + 0.0, + 0.02, + 0.0, + 0.02, + 0.0, + 0.0, + 0.03, + 0.0, + 0.03, + 0.0, + 0.0, + 0.73, + 0.0, + 0.01, + 0.0, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 12.58, + 0.0, + 0.0, + 71.88, + 0.0, + 33.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.91 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 93.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.51 + ] + }, + "time": 1790718828.3451 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json new file mode 100644 index 00000000..8acc53d2 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_S-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "4e71f26e7fd8", + "corpus_repeated": false, + "time": "2026-09-29T21:53:48", + "prompt_tokens": 31604, + "completion_tokens": 49, + "ttft_s": 42.269, + "e2e_s": 42.716, + "api_prompt_tps": 747.7, + "api_decode_tps": 107.5, + "engine_prompt_tps": 750.5, + "engine_decode_tps": 106.3, + "log_lines": [ + "strata serve: prompt 31604 tokens = 0 reused + 31604 read in 42111 ms (750.5 tok/s), 49 generated in 461 ms (106.3 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (26163 hits / 26396 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_s", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 9376, + "expert_cache_mib": 17297, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 635, + "cvec": 0, + "arena_mib": 47962, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718828.4807332, + "duration_s": 42.6, + "finish": "stop", + "prompt_tokens": 31604, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 42110.8, + "decode_ms": 460.9, + "decode_tok_s": 106.3, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790718784.8375118, + "duration_s": 43.0, + "finish": "stop", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 88, + "engine_generated": 88, + "prompt_ms": 42216.7, + "decode_ms": 776.7, + "decode_tok_s": 113.3, + "hit_rate": 0.978 + }, + { + "projection": null, + "time": 1790718743.8685048, + "duration_s": 40.3, + "finish": "stop", + "prompt_tokens": 28315, + "reused": 0, + "output_tokens": 84, + "engine_generated": 84, + "prompt_ms": 39286.5, + "decode_ms": 1011.1, + "decode_tok_s": 83.1, + "hit_rate": 0.949 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790718725.4039552, + "requests": 3, + "prompt_tokens": 91552, + "reused": 0, + "output_tokens": 221, + "prompt_ms": 123614.0, + "decode_ms": 2248.7000000000003 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 39, + "mem_used": 25212944384, + "mem_total": 25769803776, + "temp": 47, + "power": 127.526 + }, + { + "index": 1, + "util": 2, + "mem_used": 24227282944, + "mem_total": 25769803776, + "temp": 50, + "power": 202.315 + } + ], + "gpu_util": 20.5, + "gpu_mem_used": 49440227328, + "gpu_mem_total": 51539607552, + "gpu_temp": 50, + "gpu_power": 329.841, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 19.740234375, + "gpu_pcie_tx_mb": 54.21484375, + "cpu": 32.2, + "ram_used": 70312075264, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.09328657441898458, + "tok_s": 97.74566314411967, + "tok_s_mean": 97.74268443960047 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 25.5, + 38.5, + 31.5, + 24.5, + 30.0, + 26.0, + 31.5, + 19.0, + 86.5, + 28.0, + 22.5, + 32.0, + 26.0, + 77.5, + 22.5, + 22.5, + 34.0, + 26.0, + 20.5, + 32.5, + 0.0, + 36.5, + 37.0, + 26.0, + 32.0, + 37.0, + 24.0, + 32.5, + 20.5, + 29.0, + 25.0, + 27.5, + 30.5, + 24.0, + 35.0, + 28.5, + 29.0, + 30.0, + 29.5, + 33.5, + 44.5, + 55.5, + 36.0, + 25.0, + 33.5, + 47.0, + 15.5, + 32.5, + 24.0, + 32.5, + 29.0, + 55.0, + 34.0, + 48.0, + 33.0, + 22.5, + 31.5, + 24.5, + 20.0, + 20.5 + ], + "gpu_mem_used": [ + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328, + 49440227328 + ], + "gpu_temp": [ + 51, + 50, + 49, + 50, + 49, + 51, + 49, + 50, + 51, + 49, + 50, + 50, + 51, + 52, + 50, + 50, + 50, + 51, + 52, + 50, + 49, + 49, + 49, + 51, + 50, + 50, + 50, + 50, + 51, + 50, + 50, + 51, + 50, + 51, + 50, + 51, + 51, + 50, + 52, + 50, + 51, + 50, + 50, + 51, + 50, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 50, + 52, + 52, + 52, + 51, + 52, + 52, + 50 + ], + "gpu_power": [ + 385.57, + 368.88, + 396.03, + 374.4, + 393.23, + 385.24, + 406.68, + 391.86, + 364.28, + 409.58, + 388.38, + 389.1, + 390.65, + 372.81, + 415.25, + 390.44, + 384.85, + 382.05, + 377.98, + 330.14, + 415.76, + 348.22, + 407.06, + 354.03, + 392.05, + 392.72, + 370.96, + 399.97, + 402.84, + 387.68, + 394.33, + 359.55, + 419.05, + 403.04, + 384.68, + 390.64, + 393.93, + 389.6, + 362.93, + 373.48, + 405.22, + 378.6, + 399.07, + 380.19, + 386.69, + 409.76, + 359.41, + 400.68, + 368.54, + 396.07, + 393.99, + 371.52, + 407.92, + 367.65, + 416.33, + 386.19, + 394.79, + 409.75, + 373.56, + 329.84 + ], + "gpu_pcie_rx_mb": [ + 6062.41, + 5581.95, + 5691.53, + 8234.83, + 8344.89, + 7880.73, + 6094.07, + 8294.58, + 5858.85, + 5465.17, + 6922.82, + 4432.29, + 6296.59, + 5837.44, + 7103.97, + 7604.84, + 4756.35, + 4899.02, + 5517.96, + 50.97, + 0.67, + 11557.34, + 5125.33, + 6536.1, + 6042.86, + 7341.43, + 5299.47, + 6137.51, + 6431.72, + 5859.47, + 4887.1, + 5919.46, + 5763.62, + 94.17, + 6438.59, + 7535.84, + 6171.89, + 7355.36, + 4306.32, + 5857.37, + 4681.59, + 5568.03, + 5823.33, + 5368.61, + 7806.78, + 7675.93, + 8469.58, + 5669.88, + 14723.06, + 5790.85, + 6188.01, + 6980.23, + 7332.23, + 12898.87, + 6754.21, + 6340.74, + 6000.61, + 6420.09, + 4455.66, + 19.74 + ], + "cpu": [ + 6.1, + 6.8, + 12.8, + 11.1, + 6.2, + 6.4, + 6.4, + 6.1, + 6.3, + 8.7, + 7.4, + 9.4, + 6.3, + 7.9, + 6.5, + 6.4, + 15.4, + 9.4, + 6.3, + 47.4, + 36.1, + 6.3, + 6.7, + 6.6, + 5.7, + 7.4, + 6.2, + 7.4, + 6.0, + 6.6, + 15.5, + 14.6, + 5.8, + 6.4, + 6.5, + 6.2, + 11.6, + 8.8, + 7.8, + 6.2, + 6.9, + 6.0, + 5.5, + 7.3, + 17.5, + 8.0, + 7.9, + 6.6, + 6.2, + 6.2, + 6.1, + 6.6, + 5.7, + 6.8, + 7.1, + 7.8, + 6.2, + 9.8, + 15.0, + 32.2 + ], + "ram_used": [ + 70357520384, + 70490038272, + 70530985984, + 70524338176, + 70524243968, + 70525259776, + 70528827392, + 70526148608, + 70526631936, + 70541975552, + 70541778944, + 70536822784, + 70537621504, + 70537134080, + 70534877184, + 70532685824, + 70529556480, + 70530998272, + 70534545408, + 70762872832, + 70460293120, + 70452703232, + 70444961792, + 70428729344, + 70420193280, + 70418821120, + 70406471680, + 70396342272, + 70389112832, + 70380965888, + 70312722432, + 70348423168, + 70338981888, + 70328791040, + 70326034432, + 70312820736, + 70085947392, + 69987848192, + 70072119296, + 70060589056, + 70056861696, + 70179471360, + 70176550912, + 70159552512, + 70270476288, + 70270668800, + 70271184896, + 70263926784, + 70264184832, + 70264291328, + 70265167872, + 70267035648, + 70267035648, + 70264389632, + 70261067776, + 70265782272, + 70268100608, + 70275043328, + 70091866112, + 70312075264 + ], + "disk_read_mb": [ + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 12.58, + 0.0, + 0.0, + 71.88, + 0.0, + 33.04, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.91, + 0.83, + 0.04, + 0.0, + 0.0, + 0.01, + 0.0, + 0.03, + 0.0, + 0.0, + 0.03, + 0.0, + 0.05, + 0.0, + 0.0, + 0.04, + 0.0, + 0.04, + 0.0, + 0.04, + 0.0, + 0.0, + 0.04, + 0.0, + 0.0, + 0.04, + 0.0, + 0.01, + 0.0, + 0.02, + 0.0, + 0.0, + 0.01, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 110.51, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.75 + ] + }, + "time": 1790718871.5639336 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json new file mode 100644 index 00000000..2a76a65d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-16k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "e39790e5649d", + "corpus_repeated": false, + "time": "2026-09-29T20:47:57", + "prompt_tokens": 17346, + "completion_tokens": 8, + "ttft_s": 9.075, + "e2e_s": 9.178, + "api_prompt_tps": 1911.3, + "api_decode_tps": 68.2, + "engine_prompt_tps": 1933.6, + "engine_decode_tps": 67.4, + "log_lines": [ + "strata serve: prompt 17346 tokens = 0 reused + 17346 read in 8971 ms (1933.6 tok/s), 8 generated in 119 ms (67.4 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3014 hits / 3740 lookups)" + ], + "answer_head": "37E3DB14", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + } + ], + "requests_kept": 24, + "totals": { + "since": 1790713882.6043305, + "requests": 24, + "prompt_tokens": 631825, + "reused": 0, + "output_tokens": 4662, + "prompt_ms": 302982.9, + "decode_ms": 55029.19999999998 + }, + "hardware": { + "gpu_util": 100, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 265.798, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 22367.23828125, + "gpu_pcie_tx_mb": 80.8232421875, + "cpu": 6.2, + "ram_used": 63624777728, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.31474488451743216, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100, + 0, + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 46, + 45, + 45, + 44, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49, + 46, + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49 + ], + "gpu_power": [ + 162.82, + 148.08, + 135.02, + 121.86, + 121.63, + 121.78, + 121.51, + 121.24, + 121.16, + 121.27, + 121.24, + 121.23, + 121.05, + 121.06, + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27, + 201.82, + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.38, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45, + 2343.61, + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24 + ], + "cpu": [ + 1.7, + 6.8, + 2.8, + 2.2, + 1.5, + 0.9, + 1.8, + 5.2, + 2.3, + 5.5, + 8.8, + 1.8, + 3.7, + 1.8, + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5, + 22.5, + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2 + ], + "ram_used": [ + 64108949504, + 64264835072, + 64269873152, + 64217538560, + 64220250112, + 64209580032, + 64204328960, + 64140402688, + 64131928064, + 64163700736, + 64240553984, + 64240898048, + 64248393728, + 64243052544, + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368, + 63680327680, + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0, + 34.69, + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714887.0144231 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json new file mode 100644 index 00000000..507bd18b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-28k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "94aa92e58ada", + "corpus_repeated": false, + "time": "2026-09-29T20:48:07", + "prompt_tokens": 29820, + "completion_tokens": 8, + "ttft_s": 14.138, + "e2e_s": 14.241, + "api_prompt_tps": 2109.2, + "api_decode_tps": 68.2, + "engine_prompt_tps": 2134.7, + "engine_decode_tps": 66.5, + "log_lines": [ + "strata serve: prompt 29820 tokens = 0 reused + 29820 read in 13969 ms (2134.7 tok/s), 8 generated in 120 ms (66.5 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3033 hits / 3764 lookups)" + ], + "answer_head": "64EC0999", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714887.1579242, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 29820, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 13969.3, + "decode_ms": 120.3, + "decode_tok_s": 66.5, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + } + ], + "requests_kept": 25, + "totals": { + "since": 1790713882.6043305, + "requests": 25, + "prompt_tokens": 661645, + "reused": 0, + "output_tokens": 4670, + "prompt_ms": 316952.2, + "decode_ms": 55149.499999999985 + }, + "hardware": { + "gpu_util": 99, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 278.531, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 86.068359375, + "gpu_pcie_tx_mb": 76.1982421875, + "cpu": 6.7, + "ram_used": 63515471872, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.08241686128693117, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100, + 0, + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100, + 0, + 99, + 99, + 100, + 96, + 100, + 99, + 99, + 99, + 100, + 99, + 100, + 99, + 99 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49, + 46, + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49, + 46, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49 + ], + "gpu_power": [ + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27, + 201.82, + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8, + 225.08, + 215.47, + 277.53, + 277.2, + 277.77, + 276.7, + 277.63, + 275.8, + 266.11, + 275.21, + 277.53, + 275.92, + 279.07, + 278.53 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45, + 2343.61, + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24, + 0.29, + 6039.81, + 15.31, + 2050.78, + 8.77, + 51.02, + 14.83, + 11.11, + 14.88, + 25541.35, + 21966.98, + 22781.28, + 20080.71, + 86.07 + ], + "cpu": [ + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5, + 22.5, + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2, + 20.7, + 7.5, + 5.6, + 6.7, + 10.9, + 6.4, + 7.2, + 16.4, + 12.9, + 5.7, + 8.2, + 6.5, + 6.1, + 6.7 + ], + "ram_used": [ + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368, + 63680327680, + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728, + 63754727424, + 63698673664, + 63690715136, + 63681667072, + 63675179008, + 63536058368, + 63521837056, + 63517446144, + 63523024896, + 63518388224, + 63517155328, + 63521734656, + 63516585984, + 63515471872 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0, + 34.69, + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.11, + 4.58, + 0.0, + 0.0, + 97.16, + 0.0, + 0.0, + 0.0, + 52.31, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714901.7591343 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json new file mode 100644 index 00000000..844f1d09 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-needle/needle-8k-1.json @@ -0,0 +1,830 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "3c83d69c2581", + "corpus_repeated": false, + "time": "2026-09-29T20:47:52", + "prompt_tokens": 7493, + "completion_tokens": 8, + "ttft_s": 4.2, + "e2e_s": 4.307, + "api_prompt_tps": 1783.9, + "api_decode_tps": 65.8, + "engine_prompt_tps": 1816.6, + "engine_decode_tps": 64.9, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 4125 ms (1816.6 tok/s), 8 generated in 123 ms (64.9 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 74.8% (2704 hits / 3615 lookups)" + ], + "answer_head": "0E6415FF", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + } + ], + "requests_kept": 23, + "totals": { + "since": 1790713882.6043305, + "requests": 23, + "prompt_tokens": 614479, + "reused": 0, + "output_tokens": 4654, + "prompt_ms": 294011.9, + "decode_ms": 54910.499999999985 + }, + "hardware": { + "gpu_util": 100, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 276.273, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 24945.44921875, + "gpu_pcie_tx_mb": 2986.287109375, + "cpu": 8.5, + "ram_used": 63716282368, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 100, + 99, + 100, + 99, + 99, + 85, + 91, + 96, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 100, + 99, + 100 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 46, + 45, + 45, + 44, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 48, + 49, + 49 + ], + "gpu_power": [ + 277.85, + 276.09, + 278.51, + 279.06, + 278.13, + 239.73, + 262.71, + 270.73, + 273.54, + 162.82, + 148.08, + 135.02, + 121.86, + 121.63, + 121.78, + 121.51, + 121.24, + 121.16, + 121.27, + 121.24, + 121.23, + 121.05, + 121.06, + 121.26, + 121.23, + 101.81, + 59.35, + 35.84, + 35.18, + 35.01, + 35.2, + 35.0, + 34.94, + 35.11, + 35.02, + 35.03, + 35.11, + 34.94, + 34.9, + 35.04, + 35.01, + 35.02, + 35.13, + 34.98, + 34.93, + 35.03, + 34.9, + 34.91, + 35.06, + 34.94, + 34.94, + 35.11, + 35.01, + 35.09, + 34.99, + 34.98, + 69.69, + 278.48, + 278.38, + 276.27 + ], + "gpu_pcie_rx_mb": [ + 12025.83, + 22118.66, + 18928.05, + 18.36, + 86.12, + 284.24, + 9240.67, + 7805.97, + 0.29, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.38, + 0.33, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.43, + 0.43, + 0.43, + 0.43, + 0.48, + 0.52, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.57, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.48, + 0.43, + 0.43, + 0.67, + 0.43, + 0.43, + 0.43, + 0.43, + 12932.54, + 9.63, + 46.83, + 24945.45 + ], + "cpu": [ + 8.2, + 6.7, + 6.2, + 6.0, + 13.2, + 64.5, + 99.9, + 99.0, + 86.8, + 1.7, + 6.8, + 2.8, + 2.2, + 1.5, + 0.9, + 1.8, + 5.2, + 2.3, + 5.5, + 8.8, + 1.8, + 3.7, + 1.8, + 2.8, + 1.4, + 3.7, + 3.3, + 1.7, + 1.3, + 4.2, + 1.2, + 1.6, + 1.7, + 9.9, + 2.6, + 0.5, + 2.0, + 1.8, + 2.4, + 1.5, + 0.8, + 1.6, + 1.2, + 0.7, + 1.6, + 1.6, + 2.3, + 9.4, + 4.7, + 1.1, + 3.5, + 10.5, + 1.6, + 1.2, + 1.3, + 4.9, + 9.2, + 6.2, + 7.5, + 8.5 + ], + "ram_used": [ + 64100171776, + 64087904256, + 64069447680, + 64067096576, + 64095731712, + 64224346112, + 64185745408, + 64170352640, + 64157536256, + 64108949504, + 64264835072, + 64269873152, + 64217538560, + 64220250112, + 64209580032, + 64204328960, + 64140402688, + 64131928064, + 64163700736, + 64240553984, + 64240898048, + 64248393728, + 64243052544, + 64234790912, + 64233521152, + 64232390656, + 64308101120, + 64309403648, + 64297762816, + 64329601024, + 64305721344, + 64307060736, + 64304783360, + 64363835392, + 64356347904, + 64354099200, + 64356909056, + 64359067648, + 64329744384, + 64330743808, + 64332496896, + 64325115904, + 64319610880, + 64320966656, + 64320552960, + 64315297792, + 64318357504, + 64285126656, + 64085762048, + 64088686592, + 64091111424, + 64247578624, + 64251699200, + 64241737728, + 64244289536, + 64283144192, + 63581208576, + 63583793152, + 63583657984, + 63716282368 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.89, + 2.52, + 3.25, + 2.83, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.02, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 59.38, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 61.23, + 76.01, + 95.36, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790714877.3325372 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json new file mode 100644 index 00000000..2b88fb6b --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090-two-turn/two-turn-16k-1.json @@ -0,0 +1,835 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "7aed17dd03cd", + "corpus_repeated": false, + "time": "2026-09-29T20:48:48", + "prompt_tokens": 15636, + "completion_tokens": 256, + "ttft_s": 7.488, + "e2e_s": 10.882, + "api_prompt_tps": 2088.0, + "api_decode_tps": 75.1, + "engine_prompt_tps": 2114.8, + "engine_decode_tps": 75.1, + "log_lines": [ + "strata serve: prompt 15636 tokens = 0 reused + 15636 read in 7394 ms (2114.8 tok/s), 256 generated in 3410 ms (75.1 tok/s), drafts accepted 152 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 93.0% (136865 hits / 147168 lookups)" + ], + "answer_head": "## What `README.md` does\n\n`README.md` is the project's landing page and primary user-facing documentation. It serves several purposes:\n\n1. **Marketing/overview** \u2014 Opens with a headline claim (\"Run a 125-billion-parameter AI model on a normal gaming PC\") and a visual demo (the pagoda video) to immed", + "turn2_ttft_s": 0.438, + "turn2_prompt_tokens": 15915, + "turn2_log_lines": [ + "strata serve: prompt 15915 tokens = 15892 reused + 23 read in 332 ms (69.3 tok/s), 46 generated in 661 ms (69.6 tok/s), drafts accepted 27 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.4% (29047 hits / 30124 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714939.7647502, + "duration_s": 1.0, + "finish": "stop", + "prompt_tokens": 15915, + "reused": 15892, + "output_tokens": 46, + "engine_generated": 46, + "prompt_ms": 331.9, + "decode_ms": 660.8, + "decode_tok_s": 69.6, + "hit_rate": 0.964 + }, + { + "projection": null, + "time": 1790714928.3706348, + "duration_s": 10.8, + "finish": "length", + "prompt_tokens": 15636, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 7393.6, + "decode_ms": 3409.5, + "decode_tok_s": 75.1, + "hit_rate": 0.93 + }, + { + "projection": null, + "time": 1790714887.1579242, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 29820, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 13969.3, + "decode_ms": 120.3, + "decode_tok_s": 66.5, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714877.4157934, + "duration_s": 9.1, + "finish": "stop", + "prompt_tokens": 17346, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 8971.0, + "decode_ms": 118.7, + "decode_tok_s": 67.4, + "hit_rate": 0.806 + }, + { + "projection": null, + "time": 1790714872.57582, + "duration_s": 4.3, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 4124.7, + "decode_ms": 123.2, + "decode_tok_s": 64.9, + "hit_rate": 0.748 + }, + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + } + ], + "requests_kept": 27, + "totals": { + "since": 1790713882.6043305, + "requests": 27, + "prompt_tokens": 693196, + "reused": 15892, + "output_tokens": 4972, + "prompt_ms": 324677.7, + "decode_ms": 59219.79999999999 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 48, + "gpu_power": 197.275, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 822.3525390625, + "gpu_pcie_tx_mb": 183.15234375, + "cpu": 52.4, + "ram_used": 63860678656, + "ram_total": 177175990272, + "disk_read_mb": 1.1632307226246328, + "disk_write_mb": 0.2954830452969325, + "tok_s": 50.58164583911189, + "tok_s_mean": 50.57911214220715 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 100, + 99, + 99, + 100, + 100, + 99, + 90, + 100, + 0, + 99, + 99, + 100, + 96, + 100, + 99, + 99, + 99, + 100, + 99, + 100, + 99, + 99, + 96, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 99, + 99, + 100, + 99, + 99, + 100, + 100, + 100, + 95, + 97, + 93, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 49, + 48, + 49, + 49, + 49, + 48, + 49, + 46, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 46, + 45, + 45, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 44, + 42, + 42, + 42, + 41, + 41, + 41, + 41, + 41, + 41, + 41, + 47, + 49, + 49, + 49, + 49, + 49, + 49, + 47, + 48, + 49, + 49, + 48 + ], + "gpu_power": [ + 237.39, + 277.05, + 276.41, + 278.18, + 277.05, + 276.73, + 274.45, + 265.8, + 225.08, + 215.47, + 277.53, + 277.2, + 277.77, + 276.7, + 277.63, + 275.8, + 266.11, + 275.21, + 277.53, + 275.92, + 279.07, + 278.53, + 241.13, + 171.76, + 147.92, + 134.65, + 121.43, + 121.4, + 121.36, + 121.31, + 121.11, + 121.03, + 121.2, + 121.14, + 120.8, + 121.02, + 121.17, + 121.22, + 102.94, + 60.93, + 36.12, + 35.26, + 35.35, + 35.31, + 35.23, + 35.08, + 35.09, + 35.22, + 69.73, + 277.07, + 276.87, + 276.87, + 278.61, + 277.22, + 278.12, + 247.41, + 259.45, + 271.65, + 275.28, + 197.28 + ], + "gpu_pcie_rx_mb": [ + 13238.91, + 26700.59, + 116.78, + 454.76, + 16.55, + 25179.15, + 16555.31, + 22367.24, + 0.29, + 6039.81, + 15.31, + 2050.78, + 8.77, + 51.02, + 14.83, + 11.11, + 14.88, + 25541.35, + 21966.98, + 22781.28, + 20080.71, + 86.07, + 0.33, + 0.29, + 0.29, + 0.33, + 0.33, + 0.29, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.43, + 0.33, + 0.33, + 0.29, + 0.33, + 0.38, + 0.43, + 0.38, + 0.43, + 0.38, + 0.43, + 0.43, + 0.38, + 0.43, + 7494.78, + 15213.11, + 13.83, + 86.31, + 6.25, + 4.48, + 7.34, + 1956.56, + 3779.22, + 10756.4, + 0.33, + 822.35 + ], + "cpu": [ + 12.5, + 14.4, + 12.6, + 8.8, + 6.5, + 7.5, + 6.4, + 6.2, + 20.7, + 7.5, + 5.6, + 6.7, + 10.9, + 6.4, + 7.2, + 16.4, + 12.9, + 5.7, + 8.2, + 6.5, + 6.1, + 6.7, + 20.8, + 2.1, + 8.1, + 1.0, + 2.4, + 4.3, + 1.2, + 15.4, + 6.0, + 0.7, + 1.7, + 1.9, + 1.9, + 1.8, + 1.1, + 2.0, + 2.0, + 1.3, + 1.6, + 1.5, + 3.7, + 3.2, + 9.8, + 1.4, + 4.8, + 1.6, + 8.9, + 6.6, + 7.0, + 5.9, + 5.6, + 7.0, + 10.7, + 49.0, + 100.0, + 99.6, + 87.8, + 52.4 + ], + "ram_used": [ + 63688806400, + 63692079104, + 63653728256, + 63611449344, + 63604965376, + 63573368832, + 63636836352, + 63624777728, + 63754727424, + 63698673664, + 63690715136, + 63681667072, + 63675179008, + 63536058368, + 63521837056, + 63517446144, + 63523024896, + 63518388224, + 63517155328, + 63521734656, + 63516585984, + 63515471872, + 63598735360, + 63575552000, + 63746940928, + 63743287296, + 63744950272, + 63746498560, + 63748960256, + 63781244928, + 63777951744, + 63778541568, + 63778627584, + 63784894464, + 63788924928, + 63789916160, + 63785603072, + 63778463744, + 63786168320, + 63781711872, + 63785504768, + 63775502336, + 63798136832, + 63833931776, + 63825649664, + 63827275776, + 63826427904, + 63833698304, + 63620595712, + 63618826240, + 63602626560, + 63602855936, + 63603830784, + 63609753600, + 63610949632, + 63683670016, + 63692382208, + 63679488000, + 63682031616, + 63860678656 + ], + "disk_read_mb": [ + 51.95, + 0.0, + 0.0, + 11.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.11, + 4.58, + 0.0, + 0.0, + 97.16, + 0.0, + 0.0, + 0.0, + 52.31, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.41, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.29, + 3.18, + 2.31, + 2.73, + 1.16 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 68.59, + 62.69, + 101.15, + 0.0, + 50.58 + ] + }, + "time": 1790714941.2661076 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json new file mode 100644 index 00000000..ffcfe8e1 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 1, + "run_id": "183f9c0b2a25", + "corpus_repeated": false, + "time": "2026-09-29T20:43:56", + "prompt_tokens": 119256, + "completion_tokens": 256, + "ttft_s": 55.136, + "e2e_s": 58.347, + "api_prompt_tps": 2162.9, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2185.1, + "engine_decode_tps": 79.3, + "log_lines": [ + "strata serve: prompt 119256 tokens = 0 reused + 119256 read in 54577 ms (2185.1 tok/s), 256 generated in 3230 ms (79.3 tok/s), drafts accepted 151 of 208, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.5% (140181 hits / 146787 lookups)" + ], + "answer_head": "The last file shown is `include/strata/kernels/cpu/pool.hpp`. It declares the CPU expert pool (`ExpertPool`), which is the engine's mechanism for computing the routed MoE experts that do not fit in VRAM.\n\n**What it does:**\n\n1. **Thread Management:** It creates a pool of worker threads pinned to phy", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + } + ], + "requests_kept": 20, + "totals": { + "since": 1790713882.6043305, + "requests": 20, + "prompt_tokens": 346713, + "reused": 0, + "output_tokens": 4134, + "prompt_ms": 170012.5, + "decode_ms": 48004.89999999999 + }, + "hardware": { + "gpu_util": 0, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 245.728, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 55.3, + "ram_used": 63994736640, + "ram_total": 177175990272, + "disk_read_mb": 2.173699813344069, + "disk_write_mb": 0.07870292427625078, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 100, + 99, + 99, + 100, + 99, + 97, + 96, + 99, + 99, + 99, + 100, + 100, + 97, + 100, + 100, + 99, + 97, + 99, + 100, + 100, + 99, + 99, + 98, + 99, + 99, + 99, + 98, + 100, + 100, + 99, + 99, + 100, + 100, + 100, + 99, + 99, + 99, + 97, + 100, + 100, + 100, + 4, + 100, + 100, + 89, + 94, + 95, + 0 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 38, + 38, + 38, + 38, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 47, + 47, + 47, + 47, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 46, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 47, + 47, + 46, + 47, + 47, + 45 + ], + "gpu_power": [ + 34.95, + 35.05, + 34.94, + 34.95, + 146.71, + 278.26, + 278.02, + 277.13, + 278.38, + 277.26, + 277.39, + 265.55, + 278.37, + 277.81, + 278.33, + 277.55, + 276.64, + 268.76, + 278.4, + 278.09, + 279.44, + 277.89, + 278.06, + 278.94, + 266.27, + 278.02, + 278.54, + 277.25, + 277.61, + 278.51, + 277.09, + 267.68, + 277.75, + 277.97, + 277.81, + 277.03, + 277.2, + 278.97, + 266.74, + 277.84, + 277.04, + 277.08, + 277.19, + 277.7, + 278.99, + 275.31, + 278.3, + 278.49, + 277.62, + 278.02, + 276.32, + 276.96, + 277.41, + 263.19, + 267.16, + 277.12, + 240.24, + 275.77, + 278.35, + 245.73 + ], + "gpu_pcie_rx_mb": [ + 0.43, + 0.38, + 0.43, + 0.62, + 11.06, + 10427.81, + 2646.73, + 383.9, + 8262.3, + 11.68, + 24650.05, + 893.64, + 18094.54, + 8958.05, + 12.25, + 6881.52, + 17403.6, + 4113.72, + 25011.21, + 21669.05, + 15617.75, + 11.78, + 26451.63, + 0.33, + 5449.25, + 2654.98, + 14.88, + 22.22, + 15.59, + 7.49, + 1.29, + 17076.97, + 2352.29, + 26573.8, + 19.55, + 15.45, + 3977.3, + 0.29, + 16.07, + 3622.44, + 16839.27, + 13.49, + 13131.9, + 19713.45, + 26861.86, + 17424.06, + 12115.96, + 5297.42, + 26787.19, + 12211.47, + 5737.21, + 18827.01, + 8191.39, + 15610.6, + 18543.15, + 81.97, + 3906.87, + 3778.6, + 4665.28, + 0.33 + ], + "cpu": [ + 1.5, + 6.0, + 1.8, + 7.9, + 6.4, + 6.6, + 16.7, + 12.8, + 7.5, + 6.4, + 5.6, + 6.5, + 6.9, + 6.6, + 17.4, + 5.9, + 5.5, + 14.4, + 12.9, + 6.6, + 19.0, + 17.6, + 6.4, + 7.6, + 15.3, + 10.6, + 6.2, + 15.5, + 14.7, + 6.1, + 5.9, + 17.4, + 8.8, + 6.2, + 15.9, + 21.5, + 7.2, + 7.4, + 16.6, + 7.1, + 6.6, + 8.9, + 14.9, + 6.1, + 5.8, + 10.7, + 14.6, + 6.8, + 5.9, + 19.6, + 12.3, + 6.2, + 7.7, + 6.1, + 5.9, + 6.3, + 64.3, + 100.0, + 100.0, + 55.3 + ], + "ram_used": [ + 63599173632, + 63581626368, + 63584313344, + 63628144640, + 63383064576, + 63385989120, + 63410585600, + 63420211200, + 63412383744, + 63414505472, + 63524802560, + 63511179264, + 63497076736, + 63495684096, + 63489646592, + 63487651840, + 63472156672, + 63594835968, + 63578550272, + 63580782592, + 63599607808, + 63609155584, + 63609020416, + 63658397696, + 63611748352, + 63599493120, + 63591612416, + 63610773504, + 63607812096, + 63605293056, + 63719862272, + 63720685568, + 63714033664, + 63716544512, + 63707664384, + 63700750336, + 63700516864, + 63791661056, + 63808417792, + 63809699840, + 63813054464, + 63809191936, + 63809736704, + 63785721856, + 63788429312, + 63899906048, + 63903354880, + 63885254656, + 63887302656, + 63919407104, + 63917928448, + 63921512448, + 63919017984, + 64030937088, + 64033521664, + 64022724608, + 64014991360, + 64020590592, + 64011530240, + 63994736640 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.59, + 0.0, + 0.0, + 0.18, + 0.0, + 0.0, + 0.31, + 0.0, + 0.0, + 5.59, + 188.01, + 0.0, + 0.0, + 123.58, + 109.11, + 0.0, + 61.11, + 110.87, + 0.0, + 0.0, + 173.38, + 90.91, + 0.0, + 90.3, + 151.87, + 0.0, + 0.0, + 198.92, + 33.71, + 0.0, + 100.92, + 100.99, + 0.0, + 0.0, + 190.6, + 21.65, + 0.0, + 46.97, + 157.79, + 0.0, + 0.0, + 54.2, + 150.86, + 0.0, + 0.0, + 89.37, + 16.55, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.57, + 4.0, + 4.88, + 2.17 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.35, + 77.04, + 74.05, + 0.0 + ] + }, + "time": 1790714694.882821 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json new file mode 100644 index 00000000..27d398a5 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 2, + "run_id": "815c67976126", + "corpus_repeated": false, + "time": "2026-09-29T20:44:54", + "prompt_tokens": 130360, + "completion_tokens": 256, + "ttft_s": 60.567, + "e2e_s": 63.777, + "api_prompt_tps": 2152.3, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2173.6, + "engine_decode_tps": 79.4, + "log_lines": [ + "strata serve: prompt 130360 tokens = 0 reused + 130360 read in 59974 ms (2173.6 tok/s), 256 generated in 3226 ms (79.4 tok/s), drafts accepted 158 of 225, 6 checkpoints", + "strata serve: decode expert cache hit rate: 94.5% (142001 hits / 150326 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing.\n\n## What `include/strata/kernels/gdn.hpp` does\n\nThis header declares the **non-projection parts of the Gated Delta-Net (GDN) layer** \u2014 the \"mixer\" used in 36 of the model's 48 layers (the other 12 are QSA full-attention layers). It is the C++ cou", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + } + ], + "requests_kept": 21, + "totals": { + "since": 1790713882.6043305, + "requests": 21, + "prompt_tokens": 477073, + "reused": 0, + "output_tokens": 4390, + "prompt_ms": 229986.4, + "decode_ms": 51230.999999999985 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 48, + "gpu_power": 278.59, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1822.99609375, + "gpu_pcie_tx_mb": 282.4296875, + "cpu": 100.0, + "ram_used": 63968800768, + "ram_total": 177175990272, + "disk_read_mb": 3.7524610679737007, + "disk_write_mb": 0.06727519842980738, + "tok_s": 75.51795929153683, + "tok_s_mean": 78.52742680374247 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 100, + 97, + 99, + 100, + 3, + 99, + 100, + 98, + 100, + 99, + 100, + 100, + 99, + 99, + 98, + 100, + 100, + 15, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 100, + 99, + 98, + 99, + 100, + 11, + 99, + 99, + 100, + 100, + 99, + 99, + 99, + 99, + 100, + 99, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 100, + 100, + 100, + 49, + 97, + 93, + 95 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 47, + 47, + 48, + 48, + 48, + 47, + 46, + 47, + 47, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 47, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 46, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 47, + 48, + 48, + 48 + ], + "gpu_power": [ + 242.39, + 277.2, + 277.34, + 277.65, + 278.23, + 277.3, + 263.86, + 266.5, + 276.0, + 277.29, + 276.57, + 277.42, + 277.59, + 268.12, + 277.51, + 276.99, + 278.25, + 276.6, + 278.17, + 261.67, + 270.19, + 277.42, + 278.17, + 277.12, + 278.28, + 277.75, + 275.69, + 267.25, + 277.04, + 278.86, + 278.14, + 276.63, + 278.3, + 265.62, + 266.61, + 278.07, + 276.73, + 277.66, + 277.57, + 279.3, + 278.07, + 267.14, + 278.22, + 278.47, + 276.15, + 278.64, + 278.86, + 277.69, + 275.4, + 267.11, + 276.68, + 277.32, + 278.12, + 277.19, + 277.93, + 278.16, + 257.52, + 253.15, + 278.1, + 278.59 + ], + "gpu_pcie_rx_mb": [ + 5309.2, + 958.97, + 17058.94, + 14.64, + 4.05, + 3010.03, + 8.39, + 15.12, + 15999.51, + 15.07, + 10772.8, + 7160.47, + 71.72, + 850.39, + 14.26, + 26414.87, + 26332.33, + 24917.6, + 18346.6, + 6700.37, + 20833.01, + 48.73, + 15.64, + 11585.24, + 10728.5, + 4552.75, + 22.55, + 13.78, + 18.55, + 13.88, + 3975.96, + 21618.6, + 14728.83, + 12107.04, + 17.45, + 2833.51, + 11.78, + 14105.51, + 21939.33, + 26894.86, + 0.33, + 21545.12, + 4351.66, + 13.54, + 21.36, + 50.16, + 22.7, + 14.26, + 24800.11, + 17.12, + 405.07, + 24.65, + 15145.21, + 16473.29, + 23109.39, + 24054.19, + 24291.28, + 1098.68, + 2094.22, + 1823.0 + ], + "cpu": [ + 12.7, + 5.7, + 13.2, + 17.8, + 11.5, + 8.3, + 10.6, + 6.0, + 6.7, + 8.3, + 8.0, + 5.8, + 5.5, + 10.0, + 7.2, + 6.7, + 11.2, + 15.8, + 7.1, + 9.4, + 8.7, + 6.2, + 6.3, + 10.1, + 6.6, + 8.2, + 8.6, + 6.9, + 6.0, + 6.4, + 9.0, + 16.5, + 8.5, + 8.3, + 8.3, + 6.3, + 6.1, + 9.9, + 6.0, + 7.2, + 6.1, + 8.2, + 11.3, + 7.1, + 7.3, + 16.3, + 11.9, + 6.5, + 8.4, + 17.1, + 6.1, + 6.2, + 6.3, + 6.4, + 6.8, + 7.5, + 7.9, + 100.0, + 100.0, + 100.0 + ], + "ram_used": [ + 63257399296, + 63250329600, + 63299825664, + 63294885888, + 63299862528, + 63298265088, + 63372304384, + 63374991360, + 63367077888, + 63366172672, + 63358062592, + 63355240448, + 63368228864, + 63471902720, + 63463698432, + 63469293568, + 63458623488, + 63534329856, + 63535923200, + 63653580800, + 63646789632, + 63642984448, + 63647580160, + 63642767360, + 63650861056, + 63672475648, + 63778967552, + 63777734656, + 63777472512, + 63771406336, + 63775264768, + 63864942592, + 63851782144, + 63977308160, + 63971295232, + 63971143680, + 63971721216, + 63963795456, + 63959093248, + 63937032192, + 64053448704, + 64054136832, + 63885062144, + 63887245312, + 63892475904, + 63940841472, + 63943122944, + 63941619712, + 64051613696, + 64039284736, + 64037093376, + 64025649152, + 64001216512, + 63998476288, + 63988797440, + 63985102848, + 64024535040, + 64006193152, + 63985057792, + 63968800768 + ], + "disk_read_mb": [ + 82.45, + 0.0, + 0.0, + 104.98, + 0.0, + 0.15, + 86.65, + 0.0, + 0.0, + 49.16, + 30.63, + 0.0, + 0.0, + 66.33, + 0.0, + 0.0, + 49.25, + 0.0, + 0.0, + 19.87, + 53.0, + 0.0, + 0.0, + 65.63, + 0.0, + 0.0, + 49.27, + 11.94, + 0.0, + 0.0, + 53.35, + 0.0, + 0.0, + 40.85, + 14.45, + 0.0, + 0.0, + 52.4, + 0.0, + 0.0, + 0.0, + 51.78, + 0.0, + 0.0, + 14.03, + 110.69, + 0.0, + 0.0, + 0.19, + 189.89, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 2.91, + 2.72, + 3.75 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.44, + 97.1, + 75.52 + ] + }, + "time": 1790714759.167411 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json new file mode 100644 index 00000000..ab96da07 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-128k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 3, + "run_id": "317fbfabc24a", + "corpus_repeated": false, + "time": "2026-09-29T20:45:59", + "prompt_tokens": 129913, + "completion_tokens": 256, + "ttft_s": 60.534, + "e2e_s": 64.056, + "api_prompt_tps": 2146.1, + "api_decode_tps": 72.4, + "engine_prompt_tps": 2168.8, + "engine_decode_tps": 72.0, + "log_lines": [ + "strata serve: prompt 129913 tokens = 0 reused + 129913 read in 59901 ms (2168.8 tok/s), 256 generated in 3556 ms (72.0 tok/s), drafts accepted 148 of 200, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.6% (138618 hits / 145073 lookups)" + ], + "answer_head": "The last file is `include/strata/kernels/gdn.hpp`. It declares the non-projection parts of the gated delta-net (GDN) layer used by 36 of the model's 48 layers. It defines `GdnShapes` (S=128, h_k=16, h_v=48) and declares `gdn_step`, which performs one in-place step of the delta-rule recurrence: it de", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714759.725435, + "duration_s": 63.5, + "finish": "length", + "prompt_tokens": 129913, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59900.8, + "decode_ms": 3556.3, + "decode_tok_s": 72.0, + "hit_rate": 0.956 + }, + { + "projection": null, + "time": 1790714695.4286683, + "duration_s": 63.2, + "finish": "length", + "prompt_tokens": 130360, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 59973.9, + "decode_ms": 3226.1, + "decode_tok_s": 79.4, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714636.537164, + "duration_s": 57.8, + "finish": "length", + "prompt_tokens": 119256, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 54577.1, + "decode_ms": 3229.8, + "decode_tok_s": 79.3, + "hit_rate": 0.955 + }, + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + } + ], + "requests_kept": 22, + "totals": { + "since": 1790713882.6043305, + "requests": 22, + "prompt_tokens": 606986, + "reused": 0, + "output_tokens": 4646, + "prompt_ms": 289887.2, + "decode_ms": 54787.29999999999 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 49, + "gpu_power": 273.544, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 86.8, + "ram_used": 64157536256, + "ram_total": 177175990272, + "disk_read_mb": 2.8283858363947703, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 99, + 99, + 100, + 100, + 99, + 99, + 100, + 97, + 99, + 100, + 98, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 99, + 100, + 97, + 100, + 100, + 100, + 99, + 99, + 99, + 99, + 100, + 100, + 100, + 97, + 99, + 99, + 100, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 85, + 91, + 96, + 95 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 48, + 49, + 48, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 48, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49 + ], + "gpu_power": [ + 277.4, + 277.63, + 276.55, + 277.24, + 277.6, + 277.7, + 267.41, + 277.71, + 277.73, + 277.11, + 277.47, + 278.48, + 265.62, + 277.65, + 278.51, + 277.16, + 277.8, + 278.42, + 276.76, + 264.34, + 277.83, + 278.79, + 277.39, + 278.33, + 279.04, + 277.09, + 266.43, + 277.15, + 279.09, + 277.12, + 278.21, + 279.11, + 276.87, + 266.5, + 277.59, + 276.92, + 277.76, + 277.37, + 277.95, + 278.05, + 266.15, + 281.14, + 276.88, + 277.27, + 277.03, + 278.78, + 277.01, + 276.66, + 264.08, + 276.78, + 278.41, + 277.85, + 276.09, + 278.51, + 279.06, + 278.13, + 239.73, + 262.71, + 270.73, + 273.54 + ], + "gpu_pcie_rx_mb": [ + 11.44, + 11737.44, + 1061.11, + 1303.05, + 10.78, + 20755.48, + 892.69, + 12802.27, + 17290.83, + 13.02, + 669.76, + 9859.75, + 15.88, + 26970.96, + 27538.78, + 8595.9, + 10.82, + 22491.22, + 20098.16, + 7703.26, + 2655.31, + 1810.74, + 21.84, + 656.7, + 7.82, + 17247.68, + 12383.65, + 14706.95, + 18027.4, + 14.64, + 51.02, + 23.94, + 21140.67, + 19852.11, + 18272.88, + 11345.43, + 10748.2, + 23.08, + 3973.67, + 14.35, + 15.45, + 12245.37, + 13872.91, + 2994.2, + 10277.84, + 51.35, + 26547.62, + 4842.76, + 13126.71, + 6178.52, + 14.73, + 12025.83, + 22118.66, + 18928.05, + 18.36, + 86.12, + 284.24, + 9240.67, + 7805.97, + 0.29 + ], + "cpu": [ + 7.6, + 6.7, + 9.9, + 8.5, + 6.7, + 6.2, + 11.3, + 5.7, + 6.1, + 11.0, + 7.2, + 6.5, + 20.9, + 10.8, + 5.8, + 8.9, + 8.5, + 6.7, + 6.4, + 11.1, + 6.7, + 5.6, + 11.4, + 8.9, + 6.1, + 6.0, + 17.0, + 11.4, + 6.6, + 10.0, + 7.3, + 6.2, + 6.6, + 10.7, + 6.4, + 6.2, + 6.7, + 9.0, + 6.2, + 7.0, + 9.7, + 17.6, + 7.3, + 7.5, + 10.4, + 6.7, + 6.4, + 6.7, + 8.5, + 6.3, + 5.8, + 8.2, + 6.7, + 6.2, + 6.0, + 13.2, + 64.5, + 99.9, + 99.0, + 86.8 + ], + "ram_used": [ + 63275466752, + 63276769280, + 63271755776, + 63272300544, + 63263879168, + 63359676416, + 63357374464, + 63357542400, + 63358373888, + 63359791104, + 63361323008, + 63363457024, + 63494107136, + 63494156288, + 63489257472, + 63490707456, + 63488667648, + 63458295808, + 63462985728, + 63580164096, + 63581151232, + 63584616448, + 63609655296, + 63608074240, + 63610007552, + 63607758848, + 63749599232, + 63745466368, + 63718805504, + 63722086400, + 63728562176, + 63731232768, + 63729074176, + 63842201600, + 63847124992, + 63850708992, + 63853719552, + 63846064128, + 63846113280, + 63848321024, + 63970734080, + 63991717888, + 63989817344, + 63985319936, + 63983939584, + 63975882752, + 63976255488, + 63973568512, + 64091373568, + 64083685376, + 64078811136, + 64100171776, + 64087904256, + 64069447680, + 64067096576, + 64095731712, + 64224346112, + 64185745408, + 64170352640, + 64157536256 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 71.01, + 35.58, + 0.0, + 2.93, + 89.18, + 0.0, + 0.0, + 92.41, + 0.0, + 0.0, + 76.71, + 3.39, + 0.0, + 12.48, + 48.82, + 0.0, + 0.0, + 92.22, + 0.0, + 0.0, + 44.7, + 41.48, + 0.0, + 0.0, + 83.51, + 0.0, + 0.0, + 52.65, + 20.67, + 0.0, + 0.0, + 77.14, + 0.0, + 0.0, + 21.58, + 52.7, + 0.0, + 0.0, + 74.56, + 0.0, + 0.0, + 0.0, + 65.27, + 0.0, + 0.0, + 0.0, + 48.73, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.89, + 2.52, + 3.25, + 2.83 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 61.23, + 76.01, + 95.36, + 0.0 + ] + }, + "time": 1790714823.7293081 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json new file mode 100644 index 00000000..b46da857 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-1.json @@ -0,0 +1,815 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 1, + "run_id": "56b3dec5f002", + "corpus_repeated": false, + "time": "2026-09-29T20:40:39", + "prompt_tokens": 1092, + "completion_tokens": 256, + "ttft_s": 1.378, + "e2e_s": 4.115, + "api_prompt_tps": 792.3, + "api_decode_tps": 93.2, + "engine_prompt_tps": 808.1, + "engine_decode_tps": 93.0, + "log_lines": [ + "strata serve: prompt 1092 tokens = 0 reused + 1092 read in 1351 ms (808.1 tok/s), 256 generated in 2753 ms (93.0 tok/s), drafts accepted 159 of 210, 1 checkpoints", + "strata serve: decode expert cache hit rate: 95.4% (137036 hits / 143638 lookups)" + ], + "answer_head": "Based on the content of `CMakeLists.txt`, here is an explanation of its function and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file serves as the top-level build configuration for the **Strata Engine** (version 0.1.26). Its primary responsibilities are:\n\n1. **Project Defini", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + }, + { + "projection": null, + "time": 1790713900.001974, + "duration_s": 0.7, + "finish": "stop", + "prompt_tokens": 22, + "reused": 0, + "output_tokens": 7, + "engine_generated": 7, + "prompt_ms": 482.2, + "decode_ms": 197.4, + "decode_tok_s": 35.5, + "hit_rate": 0.707 + } + ], + "requests_kept": 11, + "totals": { + "since": 1790713882.6043305, + "requests": 11, + "prompt_tokens": 114775, + "reused": 0, + "output_tokens": 1944, + "prompt_ms": 60083.00000000001, + "decode_ms": 23035.299999999996 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 276.526, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4765625, + "cpu": 87.0, + "ram_used": 63534440448, + "ram_total": 177175990272, + "disk_read_mb": 3.2598935177561885, + "disk_write_mb": 0.003747004043397918, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 99, + 42, + 99, + 99, + 100, + 99, + 99, + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 44, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45 + ], + "gpu_power": [ + 277.8, + 276.98, + 276.99, + 264.47, + 274.0, + 276.95, + 276.96, + 277.85, + 278.23, + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53 + ], + "gpu_pcie_rx_mb": [ + 20099.78, + 18385.74, + 52.36, + 17363.88, + 9102.54, + 10.44, + 87.17, + 12174.99, + 8.39, + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33 + ], + "cpu": [ + 6.7, + 5.9, + 12.5, + 10.7, + 6.6, + 10.7, + 6.2, + 7.2, + 6.5, + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0 + ], + "ram_used": [ + 63341527040, + 63336820736, + 63366373376, + 63501127680, + 63474081792, + 63398842368, + 63397171200, + 63396274176, + 63387021312, + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448 + ], + "disk_read_mb": [ + 0.2, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0 + ] + }, + "time": 1790714443.884817 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json new file mode 100644 index 00000000..299ed2b6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 2, + "run_id": "5da89525cd83", + "corpus_repeated": false, + "time": "2026-09-29T20:40:43", + "prompt_tokens": 1149, + "completion_tokens": 256, + "ttft_s": 1.323, + "e2e_s": 4.156, + "api_prompt_tps": 868.4, + "api_decode_tps": 90.0, + "engine_prompt_tps": 885.5, + "engine_decode_tps": 89.9, + "log_lines": [ + "strata serve: prompt 1149 tokens = 0 reused + 1149 read in 1298 ms (885.5 tok/s), 256 generated in 2847 ms (89.9 tok/s), drafts accepted 156 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (144603 hits / 148933 lookups)" + ], + "answer_head": "Based on the content provided, here is an explanation of the `CMakeLists.txt` file and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file is the top-level build configuration for the **Strata Engine** (specifically Phase 1, Step 1). Its primary responsibilities are:\n\n1. **Proje", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + }, + { + "projection": null, + "time": 1790713900.001974, + "duration_s": 0.7, + "finish": "stop", + "prompt_tokens": 22, + "reused": 0, + "output_tokens": 7, + "engine_generated": 7, + "prompt_ms": 482.2, + "decode_ms": 197.4, + "decode_tok_s": 35.5, + "hit_rate": 0.707 + } + ], + "requests_kept": 12, + "totals": { + "since": 1790713882.6043305, + "requests": 12, + "prompt_tokens": 115924, + "reused": 0, + "output_tokens": 2200, + "prompt_ms": 61380.600000000006, + "decode_ms": 25882.799999999996 + }, + "hardware": { + "gpu_util": 95, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 45, + "gpu_power": 273.597, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1249.6943359375, + "gpu_pcie_tx_mb": 212.6689453125, + "cpu": 97.9, + "ram_used": 63536766976, + "ram_total": 177175990272, + "disk_read_mb": 2.8181744035205307, + "disk_write_mb": 0.014930725316665065, + "tok_s": 76.9743768862725, + "tok_s_mean": 90.24600065341676 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 99, + 100, + 99, + 99, + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45 + ], + "gpu_power": [ + 274.0, + 276.95, + 276.96, + 277.85, + 278.23, + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6 + ], + "gpu_pcie_rx_mb": [ + 9102.54, + 10.44, + 87.17, + 12174.99, + 8.39, + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69 + ], + "cpu": [ + 6.6, + 10.7, + 6.2, + 7.2, + 6.5, + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9 + ], + "ram_used": [ + 63474081792, + 63398842368, + 63397171200, + 63396274176, + 63387021312, + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97 + ] + }, + "time": 1790714448.544591 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json new file mode 100644 index 00000000..e56ebe6e --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-1k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 3, + "run_id": "3ad6050d1d4c", + "corpus_repeated": false, + "time": "2026-09-29T20:40:48", + "prompt_tokens": 1135, + "completion_tokens": 256, + "ttft_s": 1.33, + "e2e_s": 4.007, + "api_prompt_tps": 853.1, + "api_decode_tps": 95.3, + "engine_prompt_tps": 869.7, + "engine_decode_tps": 95.1, + "log_lines": [ + "strata serve: prompt 1135 tokens = 0 reused + 1135 read in 1305 ms (869.7 tok/s), 256 generated in 2691 ms (95.1 tok/s), drafts accepted 159 of 217, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.2% (145229 hits / 149472 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file defines the top-level build configuration for the **Strata Engine** project. Its primary responsibilities include:\n\n1. **Project Definition**: Sets the project name (`strata`), version (`0.1.26`), and language standard (C++20).\n2. **Target Management**: Conditionally adds", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + }, + { + "projection": null, + "time": 1790714285.3293037, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 1094, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1899.7, + "decode_ms": 3080.2, + "decode_tok_s": 83.1, + "hit_rate": 0.946 + } + ], + "requests_kept": 13, + "totals": { + "since": 1790713882.6043305, + "requests": 13, + "prompt_tokens": 117059, + "reused": 0, + "output_tokens": 2456, + "prompt_ms": 62685.700000000004, + "decode_ms": 28573.599999999995 + }, + "hardware": { + "gpu_util": 21, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 43, + "gpu_power": 268.452, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.28515625, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 63.3, + "ram_used": 63492075520, + "ram_total": 177175990272, + "disk_read_mb": 1.6601509757982635, + "disk_write_mb": 0.022485114796364742, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 94, + 99, + 95, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 45, + 45, + 45, + 45, + 42, + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43 + ], + "gpu_power": [ + 277.83, + 242.91, + 278.73, + 277.1, + 247.26, + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45 + ], + "gpu_pcie_rx_mb": [ + 78.63, + 439.12, + 1555.01, + 511.84, + 0.33, + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29 + ], + "cpu": [ + 5.9, + 52.8, + 100.0, + 100.0, + 46.0, + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3 + ], + "ram_used": [ + 63380054016, + 63501307904, + 63504547840, + 63499546624, + 63490957312, + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520 + ], + "disk_read_mb": [ + 0.0, + 1.41, + 2.29, + 3.94, + 1.13, + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66 + ], + "tok_s": [ + 0.0, + 91.56, + 92.69, + 83.62, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0 + ] + }, + "time": 1790714453.0546403 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json new file mode 100644 index 00000000..d2005e37 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-1.json @@ -0,0 +1,675 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 1, + "run_id": "459ef0e5c155", + "corpus_repeated": false, + "time": "2026-09-29T20:52:28", + "prompt_tokens": 232183, + "completion_tokens": 256, + "ttft_s": 131.32, + "e2e_s": 135.339, + "api_prompt_tps": 1768.1, + "api_decode_tps": 63.4, + "engine_prompt_tps": 1784.6, + "engine_decode_tps": 63.0, + "log_lines": [ + "strata serve: prompt 232183 tokens = 0 reused + 232183 read in 130101 ms (1784.6 tok/s), 256 generated in 4061 ms (63.0 tok/s), drafts accepted 150 of 240, 6 checkpoints", + "strata serve: decode expert cache hit rate: 93.7% (149829 hits / 159942 lookups)" + ], + "answer_head": "The last file is `serve/server.py` (the listing is truncated at the very end, in the `main()` function where it assigns `svc.gpu_index`).\n\n## What it does\n\nIt is the HTTP API layer of Strata: a pure-Python bridge between OpenAI/Anthropic-style clients and the C++ engine. Concretely:\n\n- **Engine adap", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790715131.4670517, + "requests": 1, + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2 + }, + "hardware": { + "gpu_util": 93, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 50, + "gpu_power": 278.227, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1220.75, + "gpu_pcie_tx_mb": 478.41015625, + "cpu": 100.0, + "ram_used": 65694810112, + "ram_total": 177175990272, + "disk_read_mb": 3.754966568441275, + "disk_write_mb": 0.0, + "tok_s": 74.58045953935934, + "tok_s_mean": 62.37130450720771 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 99, + 100, + 99, + 100, + 98, + 100, + 100, + 100, + 100, + 100, + 99, + 99, + 100, + 99, + 99, + 100, + 99, + 100, + 100, + 98, + 100, + 100, + 100, + 97, + 100, + 100, + 99, + 99, + 98, + 97, + 100, + 100, + 100, + 99, + 100, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 3, + 100, + 100, + 93, + 94, + 96, + 93 + ], + "gpu_mem_used": [ + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25412173824, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 49, + 49, + 49, + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 49, + 49, + 49, + 49, + 50, + 50, + 49, + 49, + 50, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 49, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 50, + 49, + 50, + 50, + 50, + 51, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 50, + 47, + 50, + 50, + 50 + ], + "gpu_power": [ + 279.11, + 266.12, + 276.9, + 277.46, + 279.35, + 277.6, + 278.96, + 278.2, + 276.29, + 279.45, + 275.58, + 268.64, + 275.16, + 277.98, + 275.78, + 278.17, + 279.67, + 276.04, + 279.46, + 275.1, + 265.27, + 279.22, + 280.54, + 276.07, + 280.55, + 278.32, + 274.82, + 275.85, + 280.08, + 279.93, + 266.81, + 277.79, + 274.52, + 274.38, + 279.74, + 277.72, + 274.64, + 279.65, + 280.34, + 278.34, + 277.27, + 274.99, + 265.64, + 277.06, + 278.38, + 279.64, + 279.6, + 273.86, + 273.12, + 273.61, + 275.7, + 275.96, + 276.36, + 266.12, + 265.34, + 275.53, + 242.04, + 256.98, + 274.43, + 278.23 + ], + "gpu_pcie_rx_mb": [ + 28.08, + 16676.85, + 27.75, + 7942.58, + 15.78, + 16.36, + 19454.0, + 15911.58, + 26.8, + 41.1, + 28.75, + 15.21, + 24.79, + 15.5, + 12903.17, + 15722.66, + 13615.27, + 5212.5, + 21571.11, + 9259.8, + 29.85, + 15.5, + 9701.01, + 153.35, + 15.64, + 30.23, + 25023.46, + 14.5, + 29.71, + 26217.94, + 17128.85, + 9320.26, + 28.28, + 28.94, + 13.54, + 87.12, + 1377.34, + 10125.25, + 29.04, + 30.52, + 15905.0, + 8753.63, + 7850.26, + 26.85, + 27.04, + 15.31, + 3817.42, + 27.99, + 26.89, + 26269.48, + 26779.27, + 20418.6, + 6900.17, + 6532.96, + 1637.36, + 26114.94, + 1472.71, + 1607.46, + 3050.8, + 1220.75 + ], + "cpu": [ + 6.4, + 10.7, + 11.7, + 16.5, + 8.6, + 6.3, + 18.6, + 6.0, + 5.9, + 5.7, + 8.8, + 12.7, + 5.6, + 5.9, + 6.6, + 12.9, + 11.3, + 13.4, + 13.0, + 9.8, + 14.3, + 23.4, + 6.3, + 5.9, + 7.9, + 13.4, + 9.7, + 6.5, + 6.7, + 5.9, + 10.3, + 17.8, + 14.9, + 7.1, + 8.8, + 5.8, + 16.3, + 7.3, + 5.7, + 7.3, + 5.7, + 8.0, + 14.4, + 7.4, + 6.6, + 5.9, + 15.4, + 12.5, + 6.2, + 6.9, + 7.8, + 7.2, + 6.8, + 7.1, + 5.7, + 6.0, + 44.6, + 99.9, + 99.9, + 100.0 + ], + "ram_used": [ + 65760505856, + 65825771520, + 65805475840, + 65899847680, + 65884385280, + 65881726976, + 65877250048, + 65865695232, + 65856700416, + 65843732480, + 65918058496, + 65911185408, + 65901252608, + 65896804352, + 65888411648, + 65880047616, + 65859633152, + 65903091712, + 65906130944, + 65929789440, + 65996169216, + 65697763328, + 65680461824, + 65660788736, + 65639858176, + 65624662016, + 65614233600, + 65604620288, + 65594793984, + 65589379072, + 65666322432, + 65661911040, + 65706741760, + 65701203968, + 65697587200, + 65691623424, + 65677221888, + 65665282048, + 65657679872, + 65628098560, + 65621381120, + 65695760384, + 65678503936, + 65672011776, + 65665482752, + 65658216448, + 65673232384, + 65655951360, + 65646583808, + 65641152512, + 65659457536, + 65656025088, + 65651355648, + 65716195328, + 65703702528, + 65693274112, + 65702584320, + 65687781376, + 65690525696, + 65694810112 + ], + "disk_read_mb": [ + 0.0, + 84.11, + 102.3, + 0.0, + 0.0, + 0.0, + 175.14, + 0.0, + 0.0, + 0.0, + 43.72, + 150.32, + 0.0, + 0.0, + 0.0, + 118.91, + 69.66, + 0.0, + 0.0, + 0.0, + 128.82, + 137.4, + 0.0, + 0.0, + 0.0, + 143.2, + 89.93, + 0.0, + 0.0, + 0.0, + 81.49, + 154.61, + 0.0, + 0.0, + 0.0, + 0.0, + 196.96, + 31.0, + 0.0, + 0.0, + 0.0, + 22.35, + 158.36, + 0.0, + 0.0, + 0.0, + 0.0, + 63.48, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.53, + 4.38, + 2.32, + 3.75 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 41.84, + 65.33, + 69.08, + 74.58 + ] + }, + "time": 1790715283.9323688 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json new file mode 100644 index 00000000..bfc81eee --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-2.json @@ -0,0 +1,689 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 2, + "run_id": "fbabd65a593d", + "corpus_repeated": false, + "time": "2026-09-29T20:54:43", + "prompt_tokens": 259589, + "completion_tokens": 92, + "ttft_s": 152.099, + "e2e_s": 153.446, + "api_prompt_tps": 1706.7, + "api_decode_tps": 67.5, + "engine_prompt_tps": 1721.6, + "engine_decode_tps": 67.3, + "log_lines": [ + "strata serve: prompt 259589 tokens = 0 reused + 259589 read in 150784 ms (1721.6 tok/s), 92 generated in 1367 ms (67.3 tok/s), drafts accepted 61 of 75, 6 checkpoints", + "strata serve: decode expert cache hit rate: 90.0% (43983 hits / 48863 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the codebase and the last file in detail.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715285.1507986, + "duration_s": 152.2, + "finish": "stop", + "prompt_tokens": 259589, + "reused": 0, + "output_tokens": 92, + "engine_generated": 92, + "prompt_ms": 150783.8, + "decode_ms": 1366.8, + "decode_tok_s": 67.3, + "hit_rate": 0.9 + }, + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790715131.4670517, + "requests": 2, + "prompt_tokens": 491772, + "reused": 0, + "output_tokens": 348, + "prompt_ms": 280884.9, + "decode_ms": 5428.0 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 52, + "gpu_power": 277.319, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5709.8388671875, + "gpu_pcie_tx_mb": 1049.041015625, + "cpu": 99.9, + "ram_used": 65638817792, + "ram_total": 177175990272, + "disk_read_mb": 3.1622365794124767, + "disk_write_mb": 0.03737868297177868, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 100, + 99, + 100, + 100, + 100, + 99, + 100, + 100, + 99, + 99, + 97, + 100, + 100, + 100, + 99, + 99, + 97, + 100, + 100, + 100, + 100, + 60, + 100, + 100, + 99, + 99, + 100, + 98, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 98, + 100, + 100, + 99, + 99, + 100, + 98, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 99, + 96, + 96 + ], + "gpu_mem_used": [ + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 51, + 52, + 52, + 51, + 51, + 52, + 51, + 50, + 51, + 52, + 51, + 51, + 51, + 51, + 51, + 52, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 50, + 52, + 51, + 52, + 52, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 51, + 52, + 52, + 52, + 52, + 52, + 52, + 51, + 51, + 51, + 52, + 51, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 52, + 51, + 52 + ], + "gpu_power": [ + 280.1, + 277.72, + 269.31, + 279.51, + 276.6, + 277.19, + 280.46, + 278.19, + 275.14, + 276.45, + 280.49, + 278.01, + 265.6, + 274.96, + 274.76, + 278.94, + 279.21, + 278.77, + 277.22, + 274.11, + 273.93, + 275.55, + 279.88, + 274.53, + 278.22, + 280.08, + 279.56, + 277.48, + 275.9, + 276.58, + 275.74, + 275.62, + 274.27, + 272.69, + 272.53, + 276.33, + 279.54, + 279.3, + 279.1, + 279.0, + 278.24, + 279.57, + 276.45, + 276.52, + 276.57, + 276.89, + 273.45, + 267.54, + 275.91, + 275.91, + 277.91, + 276.31, + 276.26, + 279.97, + 276.73, + 278.79, + 274.29, + 278.64, + 241.5, + 277.32 + ], + "gpu_pcie_rx_mb": [ + 24.6, + 11576.41, + 14790.49, + 31.66, + 20927.76, + 28.32, + 23015.64, + 14269.26, + 27.42, + 9814.79, + 27090.45, + 28.08, + 29.28, + 30.8, + 22511.15, + 22487.21, + 30.47, + 74.67, + 20330.0, + 20889.04, + 27.89, + 31.8, + 55.55, + 14868.74, + 15.35, + 20128.63, + 27.13, + 26.56, + 53.21, + 24118.71, + 16327.71, + 9496.97, + 20100.59, + 27.75, + 15.97, + 14788.58, + 13.49, + 13957.07, + 26.13, + 27.75, + 26181.89, + 48.68, + 16340.3, + 5056.67, + 25172.95, + 16.36, + 87.55, + 33.81, + 31.28, + 31.66, + 35.0, + 35.09, + 8309.17, + 6276.99, + 31.14, + 13669.87, + 18489.17, + 29.47, + 2057.6, + 5709.84 + ], + "cpu": [ + 6.6, + 7.6, + 11.4, + 12.8, + 6.6, + 6.0, + 6.6, + 11.6, + 10.6, + 6.8, + 5.6, + 6.1, + 9.8, + 25.0, + 9.1, + 5.9, + 6.8, + 6.1, + 16.7, + 7.0, + 8.8, + 6.9, + 5.9, + 12.8, + 11.2, + 5.6, + 6.5, + 14.2, + 10.7, + 16.4, + 8.1, + 7.0, + 6.2, + 5.9, + 7.4, + 13.8, + 6.0, + 5.7, + 7.0, + 6.1, + 6.2, + 15.3, + 15.5, + 12.5, + 6.3, + 6.3, + 6.0, + 14.9, + 7.3, + 9.6, + 6.6, + 6.1, + 6.6, + 8.6, + 5.9, + 6.2, + 16.0, + 9.9, + 42.7, + 99.9 + ], + "ram_used": [ + 65829687296, + 65809809408, + 65878708224, + 65862221824, + 65854197760, + 65848958976, + 65840418816, + 65838673920, + 65828872192, + 65821380608, + 65813520384, + 65804607488, + 65870708736, + 65884573696, + 65869344768, + 65860734976, + 65835606016, + 65825009664, + 65818324992, + 65817894912, + 65821642752, + 65816698880, + 65812000768, + 65862680576, + 65843482624, + 65833279488, + 65827409920, + 65838510080, + 65830367232, + 65803018240, + 65796870144, + 65792782336, + 65785704448, + 65781006336, + 65859014656, + 65839325184, + 65832935424, + 65818849280, + 65813626880, + 65805553664, + 65796202496, + 65790906368, + 65792847872, + 65822486528, + 65813880832, + 65796804608, + 65786474496, + 65854476288, + 65841573888, + 65829576704, + 65816891392, + 65810354176, + 65800015872, + 65793110016, + 65783308288, + 65776508928, + 65580986368, + 65575313408, + 65644572672, + 65638817792 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 99.27, + 135.95, + 0.0, + 0.0, + 0.0, + 113.06, + 91.94, + 0.0, + 0.0, + 0.0, + 46.52, + 161.04, + 0.0, + 0.0, + 0.0, + 0.0, + 199.72, + 0.0, + 0.0, + 0.0, + 0.0, + 91.5, + 66.56, + 0.0, + 0.0, + 0.0, + 0.0, + 191.98, + 0.0, + 0.0, + 0.0, + 0.0, + 13.73, + 127.69, + 0.0, + 0.0, + 0.0, + 0.0, + 1.52, + 125.36, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 171.54, + 7.82, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.75, + 3.16 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 69.44, + 0.0 + ] + }, + "time": 1790715437.8967788 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json new file mode 100644 index 00000000..b42bd7fe --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-262k-3.json @@ -0,0 +1,703 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 3, + "run_id": "40a721fd9a17", + "corpus_repeated": false, + "time": "2026-09-29T20:57:17", + "prompt_tokens": 261068, + "completion_tokens": 256, + "ttft_s": 152.605, + "e2e_s": 156.279, + "api_prompt_tps": 1710.7, + "api_decode_tps": 69.4, + "engine_prompt_tps": 1725.6, + "engine_decode_tps": 69.3, + "log_lines": [ + "strata serve: prompt 261068 tokens = 0 reused + 261068 read in 151288 ms (1725.6 tok/s), 256 generated in 3693 ms (69.3 tok/s), drafts accepted 151 of 231, 6 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (153481 hits / 159304 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and then propose a concrete improvement.\n\n## What `serve/web/app.js` does\n\nThis file is the **entire client-side logic of the Strata web application** \u2014 a framework-free, single-file JavaScript app that talks only to the local Strata server. It po", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 262144, + "images": false, + "version": "0.1.26", + "context": 262144, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10451, + "expert_cache_mib": 17355, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 385, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790715439.1095636, + "duration_s": 155.1, + "finish": "length", + "prompt_tokens": 261068, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 151288.5, + "decode_ms": 3693.0, + "decode_tok_s": 69.3, + "hit_rate": 0.963 + }, + { + "projection": null, + "time": 1790715285.1507986, + "duration_s": 152.2, + "finish": "stop", + "prompt_tokens": 259589, + "reused": 0, + "output_tokens": 92, + "engine_generated": 92, + "prompt_ms": 150783.8, + "decode_ms": 1366.8, + "decode_tok_s": 67.3, + "hit_rate": 0.9 + }, + { + "projection": null, + "time": 1790715149.1813676, + "duration_s": 134.2, + "finish": "length", + "prompt_tokens": 232183, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 130101.1, + "decode_ms": 4061.2, + "decode_tok_s": 63.0, + "hit_rate": 0.937 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790715131.4670517, + "requests": 3, + "prompt_tokens": 752840, + "reused": 0, + "output_tokens": 604, + "prompt_ms": 432173.4, + "decode_ms": 9121.0 + }, + "hardware": { + "gpu_util": 92, + "gpu_mem_used": 25512837120, + "gpu_mem_total": 25769803776, + "gpu_temp": 53, + "gpu_power": 277.576, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 3810.1669921875, + "gpu_pcie_tx_mb": 299.7392578125, + "cpu": 100.0, + "ram_used": 65843089408, + "ram_total": 177175990272, + "disk_read_mb": 4.922097648659462, + "disk_write_mb": 0.0, + "tok_s": 68.55526509763148, + "tok_s_mean": 69.76955378630859 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 99, + 100, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 100, + 100, + 100, + 100, + 99, + 100, + 98, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 98, + 100, + 100, + 100, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 88, + 100, + 100, + 100, + 99, + 99, + 99, + 100, + 100, + 100, + 100, + 100, + 100, + 97, + 95, + 95, + 92 + ], + "gpu_mem_used": [ + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120, + 25512837120 + ], + "gpu_temp": [ + 53, + 52, + 53, + 52, + 52, + 52, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 52, + 52, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 52, + 53, + 53, + 52, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53, + 53 + ], + "gpu_power": [ + 279.28, + 276.25, + 280.52, + 280.21, + 276.32, + 278.64, + 280.39, + 275.19, + 275.3, + 267.01, + 278.7, + 279.27, + 280.07, + 277.82, + 274.89, + 273.96, + 277.23, + 280.24, + 279.4, + 277.21, + 266.21, + 276.82, + 277.27, + 274.7, + 272.68, + 273.87, + 273.33, + 275.44, + 276.56, + 276.53, + 276.52, + 263.9, + 276.06, + 275.76, + 276.06, + 275.68, + 275.74, + 273.79, + 276.62, + 276.84, + 276.88, + 276.17, + 275.71, + 273.17, + 265.54, + 275.78, + 273.31, + 275.66, + 275.72, + 276.2, + 275.38, + 273.99, + 273.72, + 275.56, + 276.07, + 276.57, + 245.75, + 278.73, + 277.86, + 277.58 + ], + "gpu_pcie_rx_mb": [ + 4135.46, + 6890.58, + 13.64, + 3437.09, + 30.71, + 20378.88, + 15.64, + 30.99, + 20391.65, + 19570.21, + 4926.97, + 27.94, + 28.08, + 26564.6, + 4245.0, + 29.13, + 28.94, + 7148.27, + 17857.03, + 28.51, + 11700.44, + 28.28, + 27.51, + 26015.42, + 14.3, + 16.36, + 11904.38, + 29.71, + 29.99, + 33.33, + 14.83, + 30.04, + 28.8, + 28.18, + 26.08, + 17.07, + 26755.14, + 31.04, + 30.14, + 30.8, + 29.04, + 30.8, + 33.24, + 27187.54, + 19414.33, + 9223.17, + 54.17, + 12.68, + 24.32, + 33.43, + 12868.02, + 32.04, + 29.66, + 34.62, + 20107.13, + 84.11, + 1655.15, + 10931.06, + 1614.47, + 3810.17 + ], + "cpu": [ + 12.6, + 5.5, + 6.4, + 6.8, + 13.7, + 9.3, + 10.4, + 12.8, + 12.2, + 11.8, + 13.0, + 6.1, + 6.4, + 6.3, + 8.4, + 15.9, + 9.1, + 6.5, + 7.0, + 5.8, + 13.8, + 18.7, + 8.2, + 6.0, + 7.7, + 8.1, + 14.9, + 5.8, + 6.5, + 6.5, + 5.9, + 9.5, + 9.8, + 6.4, + 6.2, + 13.8, + 11.5, + 9.4, + 9.4, + 6.0, + 7.2, + 5.8, + 6.6, + 6.5, + 15.9, + 8.9, + 7.4, + 6.0, + 6.1, + 9.0, + 13.9, + 6.6, + 8.0, + 6.2, + 6.0, + 7.2, + 56.6, + 100.0, + 100.0, + 100.0 + ], + "ram_used": [ + 65659777024, + 65650483200, + 65649508352, + 65644490752, + 65632600064, + 65621151744, + 65675010048, + 65661538304, + 65681547264, + 65747542016, + 65735454720, + 65723609088, + 65715372032, + 65702187008, + 65677402112, + 65653993472, + 65667379200, + 65663696896, + 65657884672, + 65648963584, + 65722257408, + 65791442944, + 65798762496, + 65787301888, + 65781350400, + 65659375616, + 65646817280, + 65635090432, + 65627262976, + 65615314944, + 65606516736, + 65678639104, + 65669410816, + 65663270912, + 65656647680, + 65739636736, + 65798643712, + 65792847872, + 65780387840, + 65772281856, + 65774555136, + 65768087552, + 65765552128, + 65838772224, + 65833267200, + 65850757120, + 65824538624, + 65812451328, + 65801834496, + 65796722688, + 65808052224, + 65799196672, + 65796362240, + 65791713280, + 65787756544, + 65798152192, + 65876860928, + 65866027008, + 65852674048, + 65843089408 + ], + "disk_read_mb": [ + 116.54, + 0.0, + 0.0, + 0.0, + 150.82, + 68.05, + 0.0, + 0.0, + 0.0, + 84.44, + 137.56, + 0.0, + 0.0, + 0.0, + 19.83, + 193.88, + 0.0, + 0.0, + 0.0, + 0.0, + 143.92, + 24.87, + 0.0, + 0.0, + 0.0, + 25.89, + 153.9, + 0.0, + 0.0, + 0.0, + 0.0, + 69.98, + 56.36, + 0.0, + 0.0, + 0.0, + 0.0, + 48.96, + 64.15, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 206.65, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.78, + 4.65, + 4.44, + 4.92 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 74.98, + 63.75, + 72.35, + 68.56 + ] + }, + "time": 1790715594.6843412 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json new file mode 100644 index 00000000..deb941f1 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "563f1c703ebe", + "corpus_repeated": false, + "time": "2026-09-29T20:41:08", + "prompt_tokens": 34932, + "completion_tokens": 256, + "ttft_s": 16.748, + "e2e_s": 19.56, + "api_prompt_tps": 2085.7, + "api_decode_tps": 90.7, + "engine_prompt_tps": 2110.2, + "engine_decode_tps": 90.6, + "log_lines": [ + "strata serve: prompt 34932 tokens = 0 reused + 34932 read in 16554 ms (2110.2 tok/s), 256 generated in 2827 ms (90.6 tok/s), drafts accepted 167 of 216, 3 checkpoints", + "strata serve: decode expert cache hit rate: 94.1% (133137 hits / 141416 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and propose an improvement.\n\n## What `docs/DETAILS.md` does\n\nThis is the comprehensive technical documentation file for the Strata project. It serves as the single source of truth for:\n\n1. **Performance benchmarks** \u2014 Detailed tables of prompt-pro", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + } + ], + "requests_kept": 17, + "totals": { + "since": 1790713882.6043305, + "requests": 17, + "prompt_tokens": 164273, + "reused": 0, + "output_tokens": 3366, + "prompt_ms": 86199.0, + "decode_ms": 38719.19999999999 + }, + "hardware": { + "gpu_util": 97, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.81, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 5630.111328125, + "gpu_pcie_tx_mb": 76.2939453125, + "cpu": 100.0, + "ram_used": 63789760512, + "ram_total": 177175990272, + "disk_read_mb": 2.3587450688100042, + "disk_write_mb": 0.1268945131954749, + "tok_s": 96.52070218780436, + "tok_s_mean": 91.25774344883004 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46 + ], + "gpu_power": [ + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81 + ], + "gpu_pcie_rx_mb": [ + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11 + ], + "cpu": [ + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0 + ], + "ram_used": [ + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52 + ] + }, + "time": 1790714488.9946597 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json new file mode 100644 index 00000000..449462f2 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "283cb867e188", + "corpus_repeated": false, + "time": "2026-09-29T20:41:28", + "prompt_tokens": 31582, + "completion_tokens": 256, + "ttft_s": 14.807, + "e2e_s": 18.058, + "api_prompt_tps": 2132.9, + "api_decode_tps": 78.4, + "engine_prompt_tps": 2160.4, + "engine_decode_tps": 78.3, + "log_lines": [ + "strata serve: prompt 31582 tokens = 0 reused + 31582 read in 14619 ms (2160.4 tok/s), 256 generated in 3271 ms (78.3 tok/s), drafts accepted 161 of 240, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (151459 hits / 157708 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the **comprehensive technical manual and reference guide** for the Strata engine. While the `README.md` focuses on quick installation and high-level marketing, `DETAILS.md` provides the deep technical spec", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + } + ], + "requests_kept": 18, + "totals": { + "since": 1790713882.6043305, + "requests": 18, + "prompt_tokens": 195855, + "reused": 0, + "output_tokens": 3622, + "prompt_ms": 100817.7, + "decode_ms": 41989.89999999999 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 276.188, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.380859375, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 84.0, + "ram_used": 63683891200, + "ram_total": 177175990272, + "disk_read_mb": 2.12697518787369, + "disk_write_mb": 0.05242544477153462, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97, + 0, + 99, + 99, + 99, + 99, + 99, + 99, + 98, + 100, + 99, + 100, + 99, + 99, + 99, + 73, + 98, + 97, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 43, + 46, + 47, + 46, + 46, + 46, + 47, + 46, + 47, + 46, + 47, + 46, + 46, + 46, + 44, + 46, + 46, + 47 + ], + "gpu_power": [ + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81, + 203.42, + 258.01, + 277.13, + 277.38, + 277.05, + 276.55, + 275.55, + 267.16, + 280.52, + 277.94, + 278.68, + 277.45, + 276.52, + 278.47, + 255.06, + 250.07, + 273.21, + 276.19 + ], + "gpu_pcie_rx_mb": [ + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11, + 6.67, + 11788.08, + 773.91, + 87.02, + 13.59, + 4.53, + 50.21, + 7.15, + 6744.72, + 14.45, + 115.11, + 2575.49, + 26114.03, + 3364.04, + 3375.15, + 957.73, + 2766.08, + 0.38 + ], + "cpu": [ + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0, + 19.3, + 8.8, + 6.1, + 7.1, + 6.6, + 7.1, + 6.0, + 6.8, + 5.6, + 5.5, + 6.6, + 7.8, + 6.1, + 6.2, + 41.1, + 99.9, + 99.4, + 84.0 + ], + "ram_used": [ + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512, + 63567470592, + 63559606272, + 63544537088, + 63536496640, + 63529500672, + 63515496448, + 63496245248, + 63530811392, + 63529254912, + 63530737664, + 63536521216, + 63543078912, + 63537020928, + 63539232768, + 63659114496, + 63677952000, + 63679279104, + 63683891200 + ], + "disk_read_mb": [ + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36, + 0.74, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.34, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 1.22, + 1.87, + 2.13 + ], + "tok_s": [ + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.68, + 75.74, + 112.93, + 0.0 + ] + }, + "time": 1790714507.5571826 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json new file mode 100644 index 00000000..f12d32ee --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-32k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "1aba3d88be7a", + "corpus_repeated": false, + "time": "2026-09-29T20:41:47", + "prompt_tokens": 31602, + "completion_tokens": 256, + "ttft_s": 14.833, + "e2e_s": 17.604, + "api_prompt_tps": 2130.5, + "api_decode_tps": 92.0, + "engine_prompt_tps": 2161.9, + "engine_decode_tps": 91.9, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 14618 ms (2161.9 tok/s), 256 generated in 2785 ms (91.9 tok/s), drafts accepted 160 of 207, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.5% (137828 hits / 142765 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the comprehensive technical documentation and user manual for the \"Strata\" engine. It bridges the gap between the high-level marketing pitch in `README.md` and the raw source code. Specifically, it:\n\n1. *", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714507.7469585, + "duration_s": 17.4, + "finish": "length", + "prompt_tokens": 31602, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14617.7, + "decode_ms": 2785.2, + "decode_tok_s": 91.9, + "hit_rate": 0.965 + }, + { + "projection": null, + "time": 1790714489.1532733, + "duration_s": 17.9, + "finish": "length", + "prompt_tokens": 31582, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14618.7, + "decode_ms": 3270.7, + "decode_tok_s": 78.3, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714469.1007972, + "duration_s": 19.4, + "finish": "length", + "prompt_tokens": 34932, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 16553.9, + "decode_ms": 2826.7, + "decode_tok_s": 90.6, + "hit_rate": 0.941 + }, + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + } + ], + "requests_kept": 19, + "totals": { + "since": 1790713882.6043305, + "requests": 19, + "prompt_tokens": 227457, + "reused": 0, + "output_tokens": 3878, + "prompt_ms": 115435.4, + "decode_ms": 44775.099999999984 + }, + "hardware": { + "gpu_util": 94, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 47, + "gpu_power": 277.644, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 3986.787109375, + "gpu_pcie_tx_mb": 397.443359375, + "cpu": 99.9, + "ram_used": 63539171328, + "ram_total": 177175990272, + "disk_read_mb": 3.5686025775501298, + "disk_write_mb": 0.3811491758221081, + "tok_s": 96.24470767975828, + "tok_s_mean": 94.09593644569512 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 99, + 100, + 99, + 96, + 96, + 0, + 100, + 99, + 100, + 100, + 99, + 100, + 100, + 99, + 100, + 99, + 100, + 99, + 99, + 99, + 100, + 98, + 99, + 97, + 0, + 99, + 99, + 99, + 99, + 99, + 99, + 98, + 100, + 99, + 100, + 99, + 99, + 99, + 73, + 98, + 97, + 94, + 100, + 100, + 99, + 99, + 99, + 99, + 99, + 100, + 99, + 100, + 100, + 100, + 99, + 99, + 97, + 97, + 94 + ], + "gpu_mem_used": [ + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 42, + 45, + 45, + 45, + 46, + 46, + 42, + 46, + 46, + 46, + 46, + 46, + 45, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 46, + 43, + 46, + 47, + 46, + 46, + 46, + 47, + 46, + 47, + 46, + 47, + 46, + 46, + 46, + 44, + 46, + 46, + 47, + 46, + 46, + 47, + 46, + 46, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 47, + 46, + 47, + 47 + ], + "gpu_power": [ + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06, + 194.1, + 265.98, + 277.8, + 274.38, + 278.56, + 277.99, + 277.15, + 264.89, + 276.96, + 277.37, + 277.24, + 276.83, + 276.94, + 278.15, + 264.71, + 273.73, + 243.99, + 277.71, + 278.81, + 203.42, + 258.01, + 277.13, + 277.38, + 277.05, + 276.55, + 275.55, + 267.16, + 280.52, + 277.94, + 278.68, + 277.45, + 276.52, + 278.47, + 255.06, + 250.07, + 273.21, + 276.19, + 200.05, + 276.81, + 276.45, + 275.4, + 277.81, + 277.45, + 277.14, + 266.34, + 281.85, + 279.13, + 278.52, + 278.21, + 279.47, + 278.62, + 244.74, + 278.38, + 277.64 + ], + "gpu_pcie_rx_mb": [ + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33, + 10.87, + 10442.35, + 23162.22, + 22324.94, + 24878.6, + 26870.2, + 14619.68, + 11419.68, + 893.4, + 13515.52, + 20953.08, + 7.87, + 14.59, + 23972.7, + 9329.51, + 82.11, + 7527.59, + 4538.68, + 5630.11, + 6.67, + 11788.08, + 773.91, + 87.02, + 13.59, + 4.53, + 50.21, + 7.15, + 6744.72, + 14.45, + 115.11, + 2575.49, + 26114.03, + 3364.04, + 3375.15, + 957.73, + 2766.08, + 0.38, + 16.21, + 26374.96, + 15489.62, + 25149.82, + 11.68, + 14.21, + 14.21, + 5900.76, + 15.35, + 3692.53, + 87.59, + 8.2, + 25347.8, + 80.63, + 5132.53, + 22.03, + 3986.79 + ], + "cpu": [ + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5, + 5.1, + 7.7, + 6.8, + 5.8, + 11.1, + 14.6, + 9.1, + 8.4, + 7.3, + 7.4, + 7.0, + 7.1, + 6.5, + 5.9, + 6.0, + 6.9, + 72.2, + 100.0, + 100.0, + 19.3, + 8.8, + 6.1, + 7.1, + 6.6, + 7.1, + 6.0, + 6.8, + 5.6, + 5.5, + 6.6, + 7.8, + 6.1, + 6.2, + 41.1, + 99.9, + 99.4, + 84.0, + 4.7, + 8.8, + 7.4, + 6.1, + 6.1, + 5.7, + 6.3, + 7.3, + 6.8, + 5.8, + 8.4, + 15.2, + 18.1, + 6.8, + 56.4, + 100.0, + 99.9 + ], + "ram_used": [ + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520, + 63358083072, + 63351615488, + 63342723072, + 63336611840, + 63371808768, + 63426170880, + 63504416768, + 63594704896, + 63611879424, + 63612047360, + 63599980544, + 63573508096, + 63570501632, + 63568433152, + 63702056960, + 63700324352, + 63800950784, + 63801184256, + 63789760512, + 63567470592, + 63559606272, + 63544537088, + 63536496640, + 63529500672, + 63515496448, + 63496245248, + 63530811392, + 63529254912, + 63530737664, + 63536521216, + 63543078912, + 63537020928, + 63539232768, + 63659114496, + 63677952000, + 63679279104, + 63683891200, + 63526555648, + 63547674624, + 63533957120, + 63515795456, + 63502536704, + 63493373952, + 63485927424, + 63556431872, + 63548153856, + 63549214720, + 63593517056, + 63649341440, + 63479009280, + 63476772864, + 63577780224, + 63546908672, + 63539171328 + ], + "disk_read_mb": [ + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96, + 0.82, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.23, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.7, + 0.31, + 2.36, + 0.74, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.34, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.15, + 1.22, + 1.87, + 2.13, + 0.67, + 0.0, + 0.0, + 0.27, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.45, + 0.74, + 3.57 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 97.18, + 97.71, + 96.52, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 80.68, + 75.74, + 112.93, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 108.5, + 87.33, + 96.24 + ] + }, + "time": 1790714525.664817 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json new file mode 100644 index 00000000..24ec0dca --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-1.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 1, + "run_id": "6c6e9cb15bc9", + "corpus_repeated": false, + "time": "2026-09-29T20:40:53", + "prompt_tokens": 3881, + "completion_tokens": 256, + "ttft_s": 2.267, + "e2e_s": 5.041, + "api_prompt_tps": 1711.6, + "api_decode_tps": 91.9, + "engine_prompt_tps": 1745.2, + "engine_decode_tps": 91.7, + "log_lines": [ + "strata serve: prompt 3881 tokens = 0 reused + 3881 read in 2224 ms (1745.2 tok/s), 256 generated in 2791 ms (91.7 tok/s), drafts accepted 155 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (146401 hits / 150495 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. It orchestrates the compilation of the project, handling complex dependencies between CPU-only components, GPU kernels (CUDA/HIP), and testing infrastructure.\n\n### What the file does:\n\n1. **Project Configurati", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714290.8242896, + "duration_s": 1.8, + "finish": "stop", + "prompt_tokens": 1147, + "reused": 0, + "output_tokens": 40, + "engine_generated": 40, + "prompt_ms": 1304.0, + "decode_ms": 456.3, + "decode_tok_s": 87.7, + "hit_rate": 0.916 + } + ], + "requests_kept": 14, + "totals": { + "since": 1790713882.6043305, + "requests": 14, + "prompt_tokens": 120940, + "reused": 0, + "output_tokens": 2712, + "prompt_ms": 64909.50000000001, + "decode_ms": 31364.099999999995 + }, + "hardware": { + "gpu_util": 97, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.792, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.5244140625, + "cpu": 93.8, + "ram_used": 63471906816, + "ram_total": 177175990272, + "disk_read_mb": 2.6609869128828647, + "disk_write_mb": 0.0037478688913843163, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 42, + 41, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46 + ], + "gpu_power": [ + 164.95, + 142.09, + 130.43, + 119.16, + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79 + ], + "gpu_pcie_rx_mb": [ + 0.29, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33 + ], + "cpu": [ + 2.5, + 9.7, + 2.8, + 11.4, + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8 + ], + "ram_used": [ + 63502053376, + 63600914432, + 63612030976, + 63779962880, + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0 + ] + }, + "time": 1790714458.598403 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json new file mode 100644 index 00000000..fea0fecb --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-2.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 2, + "run_id": "1df8c923675b", + "corpus_repeated": false, + "time": "2026-09-29T20:40:58", + "prompt_tokens": 4200, + "completion_tokens": 142, + "ttft_s": 2.418, + "e2e_s": 4.063, + "api_prompt_tps": 1736.7, + "api_decode_tps": 85.7, + "engine_prompt_tps": 1772.2, + "engine_decode_tps": 85.5, + "log_lines": [ + "strata serve: prompt 4200 tokens = 0 reused + 4200 read in 2370 ms (1772.2 tok/s), 142 generated in 1660 ms (85.5 tok/s), drafts accepted 96 of 114, 1 checkpoints", + "strata serve: decode expert cache hit rate: 89.6% (64163 hits / 71608 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + }, + { + "projection": null, + "time": 1790714293.0977688, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1288.1, + "decode_ms": 2834.1, + "decode_tok_s": 90.3, + "hit_rate": 0.966 + } + ], + "requests_kept": 15, + "totals": { + "since": 1790713882.6043305, + "requests": 15, + "prompt_tokens": 125140, + "reused": 0, + "output_tokens": 2854, + "prompt_ms": 67279.5, + "decode_ms": 33024.09999999999 + }, + "hardware": { + "gpu_util": 98, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 276.727, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 4551.6005859375, + "gpu_pcie_tx_mb": 1681.041015625, + "cpu": 100.0, + "ram_used": 63441051648, + "ram_total": 177175990272, + "disk_read_mb": 2.097570021071815, + "disk_write_mb": 0.10077293695540748, + "tok_s": 98.25687730909294, + "tok_s_mean": 85.16861474502441 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46 + ], + "gpu_power": [ + 119.05, + 119.02, + 118.92, + 118.89, + 118.85, + 118.74, + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73 + ], + "gpu_pcie_rx_mb": [ + 0.33, + 0.33, + 0.33, + 0.33, + 0.33, + 0.29, + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6 + ], + "cpu": [ + 13.4, + 2.8, + 1.5, + 1.3, + 2.8, + 1.6, + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0 + ], + "ram_used": [ + 63785050112, + 63794016256, + 63795236864, + 63794536448, + 63786823680, + 63781208064, + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648 + ], + "disk_read_mb": [ + 0.1, + 0.14, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26 + ] + }, + "time": 1790714463.1652913 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json new file mode 100644 index 00000000..bcaa4dfb --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-1x3090/speed-4k-3.json @@ -0,0 +1,829 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 3, + "run_id": "777f84f22df4", + "corpus_repeated": false, + "time": "2026-09-29T20:41:03", + "prompt_tokens": 4201, + "completion_tokens": 256, + "ttft_s": 2.409, + "e2e_s": 5.262, + "api_prompt_tps": 1744.1, + "api_decode_tps": 89.4, + "engine_prompt_tps": 1775.8, + "engine_decode_tps": 89.2, + "log_lines": [ + "strata serve: prompt 4201 tokens = 0 reused + 4201 read in 2366 ms (1775.8 tok/s), 256 generated in 2868 ms (89.2 tok/s), drafts accepted 161 of 222, 1 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (144002 hits / 149996 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. Its primary responsibilities are:\n\n1. **Project Definition**: Sets up the project name (`strata`), version (`0.1.26`), and C++20 standard.\n2. **Backend Selection**: Manages mutually exclusive GPU backends (CU", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 131072, + "images": false, + "version": "0.1.26", + "context": 131072, + "kv": "int8", + "kv_resident": 32768, + "expert_slots": 10584, + "expert_cache_mib": 17583, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 389, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790714463.1913157, + "duration_s": 5.2, + "finish": "length", + "prompt_tokens": 4201, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2365.6, + "decode_ms": 2868.4, + "decode_tok_s": 89.2, + "hit_rate": 0.96 + }, + { + "projection": null, + "time": 1790714458.6299415, + "duration_s": 4.0, + "finish": "stop", + "prompt_tokens": 4200, + "reused": 0, + "output_tokens": 142, + "engine_generated": 142, + "prompt_ms": 2370.0, + "decode_ms": 1660.0, + "decode_tok_s": 85.5, + "hit_rate": 0.896 + }, + { + "projection": null, + "time": 1790714453.0791314, + "duration_s": 5.0, + "finish": "length", + "prompt_tokens": 3881, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2223.8, + "decode_ms": 2790.5, + "decode_tok_s": 91.7, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790714448.5537117, + "duration_s": 4.0, + "finish": "length", + "prompt_tokens": 1135, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1305.1, + "decode_ms": 2690.8, + "decode_tok_s": 95.1, + "hit_rate": 0.972 + }, + { + "projection": null, + "time": 1790714443.8943996, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1149, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1297.6, + "decode_ms": 2847.5, + "decode_tok_s": 89.9, + "hit_rate": 0.971 + }, + { + "projection": null, + "time": 1790714439.2770011, + "duration_s": 4.1, + "finish": "length", + "prompt_tokens": 1092, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1351.4, + "decode_ms": 2752.6, + "decode_tok_s": 93.0, + "hit_rate": 0.954 + }, + { + "projection": null, + "time": 1790714377.2599747, + "duration_s": 17.6, + "finish": "length", + "prompt_tokens": 31605, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14608.5, + "decode_ms": 3015.6, + "decode_tok_s": 84.9, + "hit_rate": 0.966 + }, + { + "projection": null, + "time": 1790714359.1307795, + "duration_s": 17.5, + "finish": "length", + "prompt_tokens": 31589, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 14609.7, + "decode_ms": 2833.5, + "decode_tok_s": 90.3, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714338.0043592, + "duration_s": 20.5, + "finish": "length", + "prompt_tokens": 34942, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 17033.3, + "decode_ms": 3435.7, + "decode_tok_s": 74.5, + "hit_rate": 0.945 + }, + { + "projection": null, + "time": 1790714334.3235514, + "duration_s": 3.0, + "finish": "stop", + "prompt_tokens": 4199, + "reused": 0, + "output_tokens": 49, + "engine_generated": 49, + "prompt_ms": 2369.7, + "decode_ms": 626.3, + "decode_tok_s": 78.2, + "hit_rate": 0.934 + }, + { + "projection": null, + "time": 1790714328.2723713, + "duration_s": 5.5, + "finish": "length", + "prompt_tokens": 4214, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 2436.3, + "decode_ms": 3084.4, + "decode_tok_s": 83.0, + "hit_rate": 0.959 + }, + { + "projection": null, + "time": 1790714324.3220718, + "duration_s": 3.4, + "finish": "stop", + "prompt_tokens": 3736, + "reused": 0, + "output_tokens": 56, + "engine_generated": 56, + "prompt_ms": 2700.1, + "decode_ms": 719.2, + "decode_tok_s": 77.9, + "hit_rate": 0.897 + } + ], + "requests_kept": 16, + "totals": { + "since": 1790713882.6043305, + "requests": 16, + "prompt_tokens": 129341, + "reused": 0, + "output_tokens": 3110, + "prompt_ms": 69645.1, + "decode_ms": 35892.49999999999 + }, + "hardware": { + "gpu_util": 96, + "gpu_mem_used": 25517031424, + "gpu_mem_total": 25769803776, + "gpu_temp": 46, + "gpu_power": 278.057, + "gpu_power_limit": 280.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.3330078125, + "gpu_pcie_tx_mb": 0.4287109375, + "cpu": 83.5, + "ram_used": 63416299520, + "ram_total": 177175990272, + "disk_read_mb": 2.956676951508761, + "disk_write_mb": 0.16488439273306146, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090", + "gpu_count": 1, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 100, + 98, + 94, + 94, + 100, + 21, + 98, + 95, + 53, + 100, + 94, + 96, + 21, + 99, + 99, + 92, + 97, + 97, + 0, + 98, + 99, + 98, + 0, + 99, + 100, + 99, + 96, + 96 + ], + "gpu_mem_used": [ + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25514934272, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424, + 25517031424 + ], + "gpu_temp": [ + 40, + 40, + 40, + 40, + 40, + 40, + 39, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 38, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 37, + 45, + 45, + 45, + 45, + 45, + 43, + 45, + 45, + 44, + 45, + 45, + 45, + 43, + 45, + 45, + 45, + 45, + 46, + 42, + 46, + 45, + 46, + 42, + 45, + 45, + 45, + 46, + 46 + ], + "gpu_power": [ + 118.81, + 118.95, + 118.87, + 118.88, + 119.01, + 118.97, + 113.29, + 37.07, + 35.2, + 35.1, + 35.04, + 34.98, + 34.86, + 34.88, + 34.97, + 34.79, + 34.76, + 34.94, + 34.9, + 34.89, + 35.0, + 34.87, + 34.82, + 34.93, + 34.86, + 34.92, + 34.99, + 34.83, + 34.88, + 34.97, + 34.89, + 34.96, + 172.41, + 265.41, + 275.33, + 276.53, + 216.14, + 263.1, + 264.26, + 273.6, + 211.21, + 274.12, + 265.58, + 276.31, + 268.45, + 217.39, + 278.78, + 252.44, + 278.12, + 278.79, + 215.59, + 278.37, + 251.8, + 276.73, + 219.4, + 271.43, + 276.62, + 251.66, + 277.46, + 278.06 + ], + "gpu_pcie_rx_mb": [ + 0.29, + 0.29, + 0.29, + 0.33, + 0.33, + 0.33, + 0.57, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.43, + 0.43, + 0.43, + 0.38, + 0.38, + 0.43, + 0.43, + 0.38, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 0.43, + 0.38, + 0.38, + 9.97, + 22329.52, + 3689.24, + 4264.07, + 0.33, + 14955.09, + 784.16, + 3310.82, + 1249.69, + 15874.15, + 18357.04, + 4099.13, + 485.18, + 0.29, + 11.78, + 84.59, + 865.12, + 8675.62, + 0.33, + 3342.49, + 34.05, + 7461.5, + 4551.6, + 6961.73, + 24513.15, + 26324.56, + 679.21, + 426.48, + 0.33 + ], + "cpu": [ + 1.6, + 1.6, + 2.2, + 1.1, + 5.2, + 2.3, + 1.3, + 11.2, + 3.6, + 1.3, + 11.5, + 1.1, + 1.9, + 1.2, + 1.3, + 1.3, + 1.0, + 0.6, + 2.3, + 0.8, + 1.2, + 6.3, + 8.9, + 0.6, + 1.9, + 2.2, + 2.1, + 1.1, + 2.2, + 4.7, + 1.2, + 6.8, + 7.3, + 83.2, + 99.8, + 87.0, + 14.8, + 49.9, + 100.0, + 97.9, + 33.3, + 7.4, + 99.9, + 100.0, + 63.3, + 5.7, + 6.4, + 81.2, + 100.0, + 93.8, + 14.8, + 15.8, + 37.5, + 100.0, + 32.6, + 6.8, + 6.6, + 96.7, + 100.0, + 83.5 + ], + "ram_used": [ + 63760637952, + 63756046336, + 63757750272, + 63751917568, + 63784116224, + 63784988672, + 63783927808, + 63781187584, + 63772962816, + 63781842944, + 63808417792, + 63797518336, + 63793590272, + 63788277760, + 63788392448, + 63791640576, + 63791734784, + 63793213440, + 63793565696, + 63794352128, + 63793430528, + 63799361536, + 63590793216, + 63591645184, + 63583899648, + 63571738624, + 63579156480, + 63572910080, + 63581016064, + 63625879552, + 63626788864, + 63427158016, + 63429017600, + 63532883968, + 63535853568, + 63534440448, + 63490953216, + 63544176640, + 63529631744, + 63536766976, + 63443234816, + 63502606336, + 63508336640, + 63509970944, + 63492075520, + 63440269312, + 63431364608, + 63482470400, + 63473512448, + 63471906816, + 63401848832, + 63554486272, + 63453114368, + 63441051648, + 63399321600, + 63389306880, + 63427080192, + 63418408960, + 63417094144, + 63416299520 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.35, + 0.0, + 0.8, + 3.91, + 3.26, + 0.6, + 0.0, + 1.08, + 2.82, + 1.34, + 0.0, + 1.55, + 2.4, + 1.66, + 0.64, + 0.0, + 2.25, + 2.98, + 2.66, + 0.64, + 0.0, + 0.21, + 2.1, + 1.17, + 0.0, + 0.0, + 1.29, + 3.73, + 2.96 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.98, + 98.22, + 0.0, + 0.0, + 112.83, + 83.57, + 76.97, + 0.0, + 0.0, + 97.69, + 87.72, + 0.0, + 0.0, + 0.0, + 102.14, + 97.9, + 0.0, + 0.0, + 0.0, + 89.96, + 98.26, + 0.0, + 0.0, + 0.0, + 93.47, + 116.21, + 0.0 + ] + }, + "time": 1790714468.9308503 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json new file mode 100644 index 00000000..f42f93db --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-16k-1.json @@ -0,0 +1,501 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "8f89dfed9af3", + "corpus_repeated": false, + "time": "2026-09-29T22:00:26", + "prompt_tokens": 17344, + "completion_tokens": 8, + "ttft_s": 15.582, + "e2e_s": 15.663, + "api_prompt_tps": 1113.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 1119.9, + "engine_decode_tps": 83.8, + "log_lines": [ + "strata serve: prompt 17344 tokens = 0 reused + 17344 read in 15487 ms (1119.9 tok/s), 8 generated in 96 ms (83.8 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (4205 hits / 4320 lookups)" + ], + "answer_head": "05449BFC", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790719202.7795203, + "requests": 2, + "prompt_tokens": 24837, + "reused": 0, + "output_tokens": 17, + "prompt_ms": 23348.3, + "decode_ms": 249.2 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25171001344, + "mem_total": 25769803776, + "temp": 47, + "power": 148.05 + }, + { + "index": 1, + "util": 40, + "mem_used": 24185339904, + "mem_total": 25769803776, + "temp": 54, + "power": 237.219 + } + ], + "gpu_util": 20.0, + "gpu_mem_used": 49356341248, + "gpu_mem_total": 51539607552, + "gpu_temp": 54, + "gpu_power": 385.269, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 1.7626953125, + "gpu_pcie_tx_mb": 0.9052734375, + "cpu": 9.1, + "ram_used": 62596341760, + "ram_total": 177175990272, + "disk_read_mb": 0.0, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54 + ], + "gpu_power": [ + 257.56, + 245.14, + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76 + ], + "cpu": [ + 0.0, + 15.8, + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1 + ], + "ram_used": [ + 61827047424, + 61871300608, + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719242.619913 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json new file mode 100644 index 00000000..edaf3005 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-28k-1.json @@ -0,0 +1,722 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "93a9a0e32114", + "corpus_repeated": false, + "time": "2026-09-29T22:00:42", + "prompt_tokens": 29825, + "completion_tokens": 9, + "ttft_s": 26.19, + "e2e_s": 26.262, + "api_prompt_tps": 1138.8, + "api_decode_tps": 110.5, + "engine_prompt_tps": 1146.7, + "engine_decode_tps": 103.9, + "log_lines": [ + "strata serve: prompt 29825 tokens = 0 reused + 29825 read in 26009 ms (1146.7 tok/s), 9 generated in 87 ms (103.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.2% (4241 hits / 4320 lookups)" + ], + "answer_head": "98C00B03", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719242.7790127, + "duration_s": 26.1, + "finish": "stop", + "prompt_tokens": 29825, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 26008.5, + "decode_ms": 86.6, + "decode_tok_s": 103.9, + "hit_rate": 0.982 + }, + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790719202.7795203, + "requests": 3, + "prompt_tokens": 54662, + "reused": 0, + "output_tokens": 26, + "prompt_ms": 49356.8, + "decode_ms": 335.79999999999995 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 6, + "mem_used": 25171001344, + "mem_total": 25769803776, + "temp": 47, + "power": 141.832 + }, + { + "index": 1, + "util": 20, + "mem_used": 24185339904, + "mem_total": 25769803776, + "temp": 52, + "power": 243.782 + } + ], + "gpu_util": 13.0, + "gpu_mem_used": 49356341248, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 385.61400000000003, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 16.6, + "ram_used": 62951010304, + "ram_total": 177175990272, + "disk_read_mb": 0.08651659039933747, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0, + 0.0, + 60.5, + 25.5, + 71.0, + 67.0, + 26.5, + 26.5, + 85.0, + 26.0, + 73.5, + 49.5, + 25.0, + 48.0, + 32.0, + 76.5, + 9.0, + 27.5, + 47.5, + 30.0, + 62.5, + 15.5, + 31.5, + 29.0, + 39.5, + 13.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54, + 50, + 51, + 53, + 53, + 52, + 54, + 52, + 52, + 53, + 53, + 53, + 53, + 52, + 53, + 54, + 52, + 53, + 52, + 53, + 52, + 52, + 54, + 53, + 54, + 52 + ], + "gpu_power": [ + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27, + 299.57, + 398.78, + 401.71, + 449.87, + 430.87, + 402.83, + 439.43, + 401.46, + 455.62, + 425.18, + 404.39, + 417.35, + 406.87, + 423.67, + 422.86, + 404.6, + 421.5, + 402.4, + 422.71, + 432.67, + 398.05, + 455.72, + 434.46, + 403.83, + 385.61 + ], + "gpu_pcie_rx_mb": [ + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76, + 1343.92, + 7796.67, + 10809.8, + 5598.92, + 3013.99, + 91.89, + 4693.79, + 5621.38, + 5381.87, + 7487.25, + 2228.12, + 7344.77, + 3943.44, + 0.81, + 5476.19, + 2437.4, + 6693.74, + 3836.63, + 7843.59, + 5638.65, + 2853.11, + 8215.43, + 8500.96, + 4445.79, + 0.67 + ], + "cpu": [ + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1, + 16.9, + 17.1, + 22.7, + 7.5, + 10.8, + 8.9, + 7.3, + 7.3, + 8.3, + 7.7, + 9.8, + 6.9, + 12.4, + 6.4, + 12.2, + 20.6, + 19.9, + 11.0, + 8.1, + 10.3, + 9.8, + 7.6, + 8.1, + 7.3, + 16.6 + ], + "ram_used": [ + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760, + 62489825280, + 62562496512, + 62577270784, + 62577836032, + 62576951296, + 62564986880, + 62553812992, + 62539886592, + 62533107712, + 62521810944, + 62503256064, + 62503677952, + 62490673152, + 62492131328, + 62495432704, + 62503706624, + 62769029120, + 62766465024, + 62765707264, + 62747688960, + 62726733824, + 62717767680, + 62722011136, + 62728314880, + 62951010304 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.73, + 0.0, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.14, + 0.0, + 0.53, + 47.85, + 0.0, + 71.37, + 0.0, + 78.98, + 55.42, + 22.25, + 53.69, + 0.0, + 54.32, + 39.07, + 0.0, + 0.0, + 0.0, + 0.09 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719269.3852785 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json new file mode 100644 index 00000000..f2df03e8 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-needle/needle-8k-1.json @@ -0,0 +1,352 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "d1d745f05911", + "corpus_repeated": false, + "time": "2026-09-29T22:00:17", + "prompt_tokens": 7493, + "completion_tokens": 9, + "ttft_s": 7.948, + "e2e_s": 8.057, + "api_prompt_tps": 942.8, + "api_decode_tps": 73.4, + "engine_prompt_tps": 953.1, + "engine_decode_tps": 58.6, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 7861 ms (953.1 tok/s), 9 generated in 154 ms (58.6 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 94.0% (4062 hits / 4320 lookups)" + ], + "answer_head": "69231569", + "needle_found": true, + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790719202.7795203, + "requests": 1, + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 0, + "mem_used": 25139544064, + "mem_total": 25769803776, + "temp": 46, + "power": 145.526 + }, + { + "index": 1, + "util": 41, + "mem_used": 24151785472, + "mem_total": 25769803776, + "temp": 53, + "power": 243.553 + } + ], + "gpu_util": 20.5, + "gpu_mem_used": 49291329536, + "gpu_mem_total": 51539607552, + "gpu_temp": 53, + "gpu_power": 389.079, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.9521484375, + "gpu_pcie_tx_mb": 4154.1572265625, + "cpu": 12.2, + "ram_used": 62392664064, + "ram_total": 177175990272, + "disk_read_mb": 0.0036010722333241606, + "disk_write_mb": 0.0, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.5, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 2.0, + 73.5, + 23.5, + 31.0, + 56.5, + 23.5, + 20.5 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49274552320, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536 + ], + "gpu_temp": [ + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 48, + 51, + 53, + 52, + 52, + 52, + 53 + ], + "gpu_power": [ + 257.56, + 245.14, + 244.59, + 244.41, + 244.51, + 244.45, + 244.36, + 244.36, + 244.26, + 244.16, + 244.27, + 244.18, + 244.09, + 243.92, + 243.88, + 245.24, + 443.06, + 409.13, + 432.67, + 433.1, + 400.92, + 389.08 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.57, + 0.62, + 0.67, + 0.57, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.67, + 0.62, + 0.57, + 0.62, + 2169.46, + 6179.19, + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95 + ], + "cpu": [ + 0.0, + 15.8, + 15.7, + 6.4, + 8.0, + 8.1, + 4.7, + 6.7, + 0.9, + 1.5, + 5.3, + 12.5, + 1.6, + 3.2, + 8.4, + 14.2, + 13.2, + 10.5, + 10.5, + 13.4, + 9.0, + 12.2 + ], + "ram_used": [ + 61827047424, + 61871300608, + 61941383168, + 61960540160, + 61978361856, + 61977542656, + 61984432128, + 61992636416, + 61992636416, + 62000824320, + 62002450432, + 62005186560, + 62006108160, + 62014894080, + 62023741440, + 62230065152, + 62246010880, + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064 + ], + "disk_read_mb": [ + null, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 28.33, + 101.36, + 41.6, + 10.77, + 0.0, + 0.01, + 0.0, + 0.0 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "time": 1790719226.4537745 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json new file mode 100644 index 00000000..96504d42 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn/two-turn-16k-1.json @@ -0,0 +1,755 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "dedda4f9d6be", + "corpus_repeated": false, + "time": "2026-09-29T22:01:09", + "prompt_tokens": 15635, + "completion_tokens": 44, + "ttft_s": 13.63, + "e2e_s": 14.13, + "api_prompt_tps": 1147.1, + "api_decode_tps": 86.1, + "engine_prompt_tps": 1154.6, + "engine_decode_tps": 85.6, + "log_lines": [ + "strata serve: prompt 15635 tokens = 0 reused + 15635 read in 13541 ms (1154.6 tok/s), 44 generated in 514 ms (85.6 tok/s), drafts accepted 30 of 36, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.9% (24433 hits / 24957 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "turn2_ttft_s": 0.577, + "turn2_prompt_tokens": 15672, + "turn2_log_lines": [ + "strata serve: prompt 15672 tokens = 15628 reused + 44 read in 490 ms (89.8 tok/s), 48 generated in 567 ms (84.6 tok/s), drafts accepted 28 of 43, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (31236 hits / 31679 lookups)" + ], + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790719284.681533, + "duration_s": 1.1, + "finish": "stop", + "prompt_tokens": 15672, + "reused": 15628, + "output_tokens": 48, + "engine_generated": 48, + "prompt_ms": 490.1, + "decode_ms": 567.1, + "decode_tok_s": 84.6, + "hit_rate": 0.986 + }, + { + "projection": null, + "time": 1790719270.0522854, + "duration_s": 14.1, + "finish": "stop", + "prompt_tokens": 15635, + "reused": 0, + "output_tokens": 44, + "engine_generated": 44, + "prompt_ms": 13541.4, + "decode_ms": 513.7, + "decode_tok_s": 85.7, + "hit_rate": 0.979 + }, + { + "projection": null, + "time": 1790719242.7790127, + "duration_s": 26.1, + "finish": "stop", + "prompt_tokens": 29825, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 26008.5, + "decode_ms": 86.6, + "decode_tok_s": 103.9, + "hit_rate": 0.982 + }, + { + "projection": null, + "time": 1790719226.530526, + "duration_s": 15.6, + "finish": "stop", + "prompt_tokens": 17344, + "reused": 0, + "output_tokens": 8, + "engine_generated": 8, + "prompt_ms": 15486.8, + "decode_ms": 95.5, + "decode_tok_s": 83.8, + "hit_rate": 0.973 + }, + { + "projection": null, + "time": 1790719217.9333243, + "duration_s": 8.0, + "finish": "stop", + "prompt_tokens": 7493, + "reused": 0, + "output_tokens": 9, + "engine_generated": 9, + "prompt_ms": 7861.5, + "decode_ms": 153.7, + "decode_tok_s": 58.6, + "hit_rate": 0.94 + } + ], + "requests_kept": 5, + "totals": { + "since": 1790719202.7795203, + "requests": 5, + "prompt_tokens": 85969, + "reused": 15628, + "output_tokens": 118, + "prompt_ms": 63388.3, + "decode_ms": 1416.6 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 15, + "mem_used": 25191972864, + "mem_total": 25769803776, + "temp": 48, + "power": 148.771 + }, + { + "index": 1, + "util": 0, + "mem_used": 24206311424, + "mem_total": 25769803776, + "temp": 51, + "power": 169.566 + } + ], + "gpu_util": 7.5, + "gpu_mem_used": 49398284288, + "gpu_mem_total": 51539607552, + "gpu_temp": 51, + "gpu_power": 318.337, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 26.1298828125, + "gpu_pcie_tx_mb": 56.265625, + "cpu": 39.7, + "ram_used": 63088369664, + "ram_total": 177175990272, + "disk_read_mb": 1.2843527404984159, + "disk_write_mb": 0.0035875774874257423, + "tok_s": 52.0, + "tok_s_mean": 89.37171592337687 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 23.5, + 31.0, + 56.5, + 23.5, + 20.5, + 0.5, + 70.5, + 22.5, + 26.5, + 56.0, + 29.0, + 77.0, + 11.0, + 28.5, + 59.5, + 28.5, + 19.5, + 17.0, + 27.0, + 20.0, + 0.0, + 60.5, + 25.5, + 71.0, + 67.0, + 26.5, + 26.5, + 85.0, + 26.0, + 73.5, + 49.5, + 25.0, + 48.0, + 32.0, + 76.5, + 9.0, + 27.5, + 47.5, + 30.0, + 62.5, + 15.5, + 31.5, + 29.0, + 39.5, + 13.0, + 0.0, + 69.5, + 24.0, + 30.5, + 61.5, + 27.0, + 62.5, + 17.0, + 26.5, + 53.5, + 23.5, + 29.5, + 29.0, + 41.0, + 7.5 + ], + "gpu_mem_used": [ + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49291329536, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49356341248, + 49398284288, + 49398284288 + ], + "gpu_temp": [ + 53, + 52, + 52, + 52, + 53, + 49, + 51, + 52, + 52, + 53, + 53, + 53, + 52, + 53, + 51, + 53, + 53, + 53, + 53, + 54, + 50, + 51, + 53, + 53, + 52, + 54, + 52, + 52, + 53, + 53, + 53, + 53, + 52, + 53, + 54, + 52, + 53, + 52, + 53, + 52, + 52, + 54, + 53, + 54, + 52, + 50, + 51, + 53, + 54, + 52, + 54, + 53, + 53, + 54, + 53, + 53, + 54, + 55, + 53, + 51 + ], + "gpu_power": [ + 409.13, + 432.67, + 433.1, + 400.92, + 389.08, + 278.03, + 383.36, + 392.74, + 440.94, + 403.62, + 421.29, + 427.09, + 407.67, + 422.11, + 423.13, + 417.76, + 440.15, + 377.19, + 403.8, + 385.27, + 299.57, + 398.78, + 401.71, + 449.87, + 430.87, + 402.83, + 439.43, + 401.46, + 455.62, + 425.18, + 404.39, + 417.35, + 406.87, + 423.67, + 422.86, + 404.6, + 421.5, + 402.4, + 422.71, + 432.67, + 398.05, + 455.72, + 434.46, + 403.83, + 385.61, + 282.41, + 360.22, + 446.82, + 449.66, + 410.55, + 427.9, + 441.96, + 389.46, + 451.44, + 439.2, + 402.13, + 441.82, + 408.98, + 365.37, + 318.34 + ], + "gpu_pcie_rx_mb": [ + 3838.3, + 4927.82, + 4008.2, + 7314.58, + 0.95, + 1338.19, + 7892.51, + 3024.72, + 5741.74, + 2921.96, + 5454.83, + 5667.49, + 3768.87, + 6803.13, + 8164.64, + 2711.1, + 5725.29, + 6417.89, + 0.67, + 1.76, + 1343.92, + 7796.67, + 10809.8, + 5598.92, + 3013.99, + 91.89, + 4693.79, + 5621.38, + 5381.87, + 7487.25, + 2228.12, + 7344.77, + 3943.44, + 0.81, + 5476.19, + 2437.4, + 6693.74, + 3836.63, + 7843.59, + 5638.65, + 2853.11, + 8215.43, + 8500.96, + 4445.79, + 0.67, + 0.62, + 4431.82, + 4655.12, + 7505.13, + 4915.86, + 7990.69, + 6352.23, + 3326.13, + 3696.82, + 7077.12, + 4858.06, + 5613.99, + 7732.68, + 0.67, + 26.13 + ], + "cpu": [ + 10.5, + 10.5, + 13.4, + 9.0, + 12.2, + 23.9, + 8.1, + 16.5, + 13.0, + 13.0, + 9.0, + 9.7, + 12.8, + 8.6, + 12.9, + 10.4, + 8.6, + 9.0, + 9.4, + 9.1, + 16.9, + 17.1, + 22.7, + 7.5, + 10.8, + 8.9, + 7.3, + 7.3, + 8.3, + 7.7, + 9.8, + 6.9, + 12.4, + 6.4, + 12.2, + 20.6, + 19.9, + 11.0, + 8.1, + 10.3, + 9.8, + 7.6, + 8.1, + 7.3, + 16.6, + 7.1, + 8.3, + 7.7, + 7.5, + 19.7, + 13.3, + 9.8, + 12.2, + 12.2, + 11.3, + 11.1, + 11.3, + 11.7, + 49.6, + 39.7 + ], + "ram_used": [ + 62250319872, + 62234144768, + 62227582976, + 62226890752, + 62392664064, + 62490071040, + 62486704128, + 62515294208, + 62517342208, + 62467452928, + 62510080000, + 62495842304, + 62471684096, + 62463819776, + 62459879424, + 62443171840, + 62374465536, + 62303469568, + 62390607872, + 62596341760, + 62489825280, + 62562496512, + 62577270784, + 62577836032, + 62576951296, + 62564986880, + 62553812992, + 62539886592, + 62533107712, + 62521810944, + 62503256064, + 62503677952, + 62490673152, + 62492131328, + 62495432704, + 62503706624, + 62769029120, + 62766465024, + 62765707264, + 62747688960, + 62726733824, + 62717767680, + 62722011136, + 62728314880, + 62951010304, + 62691995648, + 62677225472, + 62661165056, + 62640271360, + 62636351488, + 62633791488, + 62731657216, + 62747160576, + 62744502272, + 62746267648, + 62732316672, + 62762123264, + 62711451648, + 62861885440, + 63088369664 + ], + "disk_read_mb": [ + 10.77, + 0.0, + 0.01, + 0.0, + 0.0, + 1.06, + 0.0, + 14.72, + 0.0, + 56.04, + 0.0, + 33.79, + 66.18, + 16.29, + 83.86, + 33.38, + 0.0, + 0.0, + 0.0, + 0.0, + 0.73, + 0.0, + 0.0, + 0.0, + 0.22, + 0.0, + 0.0, + 0.14, + 0.0, + 0.53, + 47.85, + 0.0, + 71.37, + 0.0, + 78.98, + 55.42, + 22.25, + 53.69, + 0.0, + 54.32, + 39.07, + 0.0, + 0.0, + 0.0, + 0.09, + 0.58, + 0.02, + 0.01, + 0.0, + 0.03, + 0.0, + 2.6, + 6.44, + 7.35, + 8.08, + 4.14, + 2.09, + 0.01, + 2.47, + 1.28 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 52.0 + ] + }, + "time": 1790719286.2452984 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json new file mode 100644 index 00000000..f92ffc79 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-1.json @@ -0,0 +1,612 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "cfa75b59eb61", + "corpus_repeated": false, + "time": "2026-09-29T21:39:52", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 26.573, + "e2e_s": 29.595, + "api_prompt_tps": 1065.5, + "api_decode_tps": 84.4, + "engine_prompt_tps": 1071.8, + "engine_decode_tps": 83.7, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 26417 ms (1071.8 tok/s), 256 generated in 3058 ms (83.7 tok/s), drafts accepted 147 of 251, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.9% (171443 hits / 173268 lookups)" + ], + "answer_head": "The last file in the repository listing is `docs/DETAILS.md`.\n\n### What `docs/DETAILS.md` does\n\nIt is the comprehensive technical documentation and reference manual for the Strata engine. While the `README.md` focuses on quick installation and high-level usage, `DETAILS.md` provides the deep technic", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 1, + "totals": { + "since": 1790717968.2500567, + "requests": 1, + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 44, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 52, + "power": 244.795 + }, + { + "index": 1, + "util": 0, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 52, + "power": 218.413 + } + ], + "gpu_util": 22.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 52, + "gpu_power": 463.20799999999997, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 0.666015625, + "gpu_pcie_tx_mb": 0.857421875, + "cpu": 60.1, + "ram_used": 62328995840, + "ram_total": 177175990272, + "disk_read_mb": 3.420667733965059, + "disk_write_mb": 0.02523147959721329, + "tok_s": 0.0, + "tok_s_mean": 0.0 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 49.5, + 21.5, + 58.5, + 25.5, + 31.5, + 24.0, + 25.0, + 35.0, + 27.0, + 64.5, + 29.0, + 24.5, + 24.5, + 27.0, + 16.0, + 26.0, + 59.5, + 24.5, + 28.5, + 48.0, + 26.5, + 29.0, + 31.0, + 3.0, + 46.0, + 46.0, + 22.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49205346304, + 49278746624, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 50, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 49, + 50, + 49, + 46, + 46, + 46, + 46, + 46, + 46, + 48, + 52, + 53, + 53, + 53, + 53, + 54, + 54, + 53, + 54, + 53, + 53, + 54, + 54, + 54, + 52, + 55, + 53, + 54, + 55, + 54, + 54, + 54, + 55, + 53, + 55, + 55, + 52 + ], + "gpu_power": [ + 260.95, + 248.93, + 247.54, + 246.62, + 246.82, + 246.65, + 246.9, + 246.83, + 246.8, + 246.68, + 246.72, + 246.75, + 246.63, + 246.53, + 246.57, + 246.83, + 236.89, + 159.99, + 79.32, + 65.35, + 64.71, + 64.62, + 64.91, + 91.65, + 314.3, + 428.65, + 367.67, + 455.67, + 441.66, + 390.44, + 440.16, + 375.92, + 453.54, + 370.98, + 401.8, + 438.74, + 379.04, + 440.69, + 353.57, + 419.67, + 435.26, + 406.67, + 447.91, + 390.07, + 459.5, + 448.73, + 405.61, + 374.45, + 407.02, + 468.77, + 463.21 + ], + "gpu_pcie_rx_mb": [ + 0.67, + 0.62, + 0.62, + 0.67, + 0.57, + 7.87, + 0.62, + 0.62, + 0.67, + 0.62, + 0.62, + 0.57, + 0.62, + 0.62, + 1.38, + 0.57, + 0.76, + 0.86, + 0.91, + 0.81, + 0.86, + 0.86, + 0.81, + 539.92, + 4704.14, + 5432.94, + 3021.19, + 4790.88, + 4142.71, + 2301.69, + 8161.88, + 3244.83, + 5099.68, + 7126.09, + 2825.64, + 6742.29, + 2064.18, + 5534.93, + 4369.31, + 7614.9, + 4834.13, + 2332.54, + 7141.88, + 4942.8, + 3514.62, + 5720.52, + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67 + ], + "cpu": [ + 0.0, + 14.3, + 2.7, + 0.9, + 1.7, + 1.5, + 2.1, + 1.3, + 1.5, + 1.3, + 1.2, + 2.2, + 1.2, + 0.9, + 1.2, + 19.1, + 3.1, + 3.2, + 2.2, + 1.9, + 2.8, + 2.0, + 4.5, + 12.1, + 9.2, + 7.1, + 7.5, + 5.5, + 13.3, + 15.7, + 18.9, + 15.5, + 7.4, + 9.3, + 7.1, + 10.1, + 9.1, + 6.1, + 9.7, + 7.4, + 9.1, + 9.2, + 13.5, + 15.4, + 6.6, + 8.7, + 6.0, + 28.4, + 94.8, + 99.5, + 60.1 + ], + "ram_used": [ + 61824409600, + 61846106112, + 61853241344, + 61854605312, + 61855711232, + 61855694848, + 61853442048, + 61858058240, + 61861154816, + 61861928960, + 61862432768, + 61867282432, + 61861072896, + 61856456704, + 61880406016, + 61890236416, + 61890191360, + 61887963136, + 61887766528, + 61882646528, + 61870043136, + 61879148544, + 61934235648, + 61984825344, + 62089637888, + 62090121216, + 62098157568, + 62098403328, + 62088568832, + 62106021888, + 61750501376, + 61766746112, + 61776080896, + 61778165760, + 61779779584, + 61908017152, + 61907206144, + 61910032384, + 62031020032, + 62033805312, + 62032531456, + 61967249408, + 61974036480, + 61990858752, + 61985890304, + 61979660288, + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840 + ], + "disk_read_mb": [ + null, + 0.01, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.38, + 66.8, + 0.0, + 24.38, + 0.0, + 55.65, + 33.54, + 0.11, + 67.43, + 0.0, + 83.76, + 1.78, + 79.2, + 71.21, + 0.0, + 79.44, + 0.0, + 77.02, + 53.81, + 0.7, + 42.73, + 0.0, + 0.0, + 0.0, + 1.02, + 5.65, + 4.98, + 3.42 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 48.0, + 86.94, + 102.06, + 0.0 + ] + }, + "time": 1790718022.6741135 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json new file mode 100644 index 00000000..e7b146c4 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-2.json @@ -0,0 +1,707 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "c27c8adc0b65", + "corpus_repeated": false, + "time": "2026-09-29T21:40:22", + "prompt_tokens": 31633, + "completion_tokens": 256, + "ttft_s": 26.904, + "e2e_s": 29.536, + "api_prompt_tps": 1175.8, + "api_decode_tps": 96.9, + "engine_prompt_tps": 1185.2, + "engine_decode_tps": 96.7, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 26691 ms (1185.2 tok/s), 256 generated in 2648 ms (96.7 tok/s), drafts accepted 160 of 214, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (147426 hits / 148799 lookups)" + ], + "answer_head": "I cannot analyze the last file because the provided repository content is truncated. The `docs/DETAILS.md` file cuts off mid-sentence in the \"Using it\" section (`...if y`), and no subsequent files are shown.\n\nHowever, I can analyze the **`chat.py`** file, which is the last *complete* file provided i", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718022.860633, + "duration_s": 29.4, + "finish": "length", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26690.6, + "decode_ms": 2648.4, + "decode_tok_s": 96.7, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 2, + "totals": { + "since": 1790717968.2500567, + "requests": 2, + "prompt_tokens": 59947, + "reused": 0, + "output_tokens": 512, + "prompt_ms": 53107.2, + "decode_ms": 5706.3 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 37, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 51, + "power": 209.254 + }, + { + "index": 1, + "util": 55, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 55, + "power": 248.664 + } + ], + "gpu_util": 46.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 457.918, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 30.46875, + "gpu_pcie_tx_mb": 164.2216796875, + "cpu": 97.1, + "ram_used": 62326792192, + "ram_total": 177175990272, + "disk_read_mb": 4.657722192080744, + "disk_write_mb": 0.11106875996500236, + "tok_s": 102.58306863780025, + "tok_s_mean": 98.12574884260572 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 49.5, + 21.5, + 58.5, + 25.5, + 31.5, + 24.0, + 25.0, + 35.0, + 27.0, + 64.5, + 29.0, + 24.5, + 24.5, + 27.0, + 16.0, + 26.0, + 59.5, + 24.5, + 28.5, + 48.0, + 26.5, + 29.0, + 31.0, + 3.0, + 46.0, + 46.0, + 22.0, + 59.5, + 29.0, + 60.0, + 26.0, + 31.5, + 71.0, + 32.5, + 28.0, + 66.0, + 23.5, + 24.5, + 18.5, + 29.0, + 28.0, + 78.0, + 30.0, + 73.5, + 16.0, + 28.0, + 25.0, + 28.0, + 29.0, + 66.0, + 26.5, + 18.5, + 43.5, + 46.0 + ], + "gpu_mem_used": [ + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49192763392, + 49205346304, + 49278746624, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 46, + 46, + 46, + 46, + 46, + 48, + 52, + 53, + 53, + 53, + 53, + 54, + 54, + 53, + 54, + 53, + 53, + 54, + 54, + 54, + 52, + 55, + 53, + 54, + 55, + 54, + 54, + 54, + 55, + 53, + 55, + 55, + 52, + 52, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 54, + 54, + 54, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 55, + 54, + 55, + 55, + 55, + 55, + 53, + 55, + 55 + ], + "gpu_power": [ + 79.32, + 65.35, + 64.71, + 64.62, + 64.91, + 91.65, + 314.3, + 428.65, + 367.67, + 455.67, + 441.66, + 390.44, + 440.16, + 375.92, + 453.54, + 370.98, + 401.8, + 438.74, + 379.04, + 440.69, + 353.57, + 419.67, + 435.26, + 406.67, + 447.91, + 390.07, + 459.5, + 448.73, + 405.61, + 374.45, + 407.02, + 468.77, + 463.21, + 376.39, + 436.62, + 444.21, + 398.6, + 447.75, + 406.3, + 391.79, + 452.85, + 427.37, + 418.5, + 444.64, + 378.02, + 407.95, + 435.96, + 404.27, + 456.87, + 440.61, + 401.93, + 421.84, + 438.49, + 398.65, + 446.07, + 421.03, + 422.3, + 368.39, + 434.33, + 457.92 + ], + "gpu_pcie_rx_mb": [ + 0.91, + 0.81, + 0.86, + 0.86, + 0.81, + 539.92, + 4704.14, + 5432.94, + 3021.19, + 4790.88, + 4142.71, + 2301.69, + 8161.88, + 3244.83, + 5099.68, + 7126.09, + 2825.64, + 6742.29, + 2064.18, + 5534.93, + 4369.31, + 7614.9, + 4834.13, + 2332.54, + 7141.88, + 4942.8, + 3514.62, + 5720.52, + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67, + 4175.19, + 7742.45, + 4905.89, + 4411.55, + 4744.0, + 6063.36, + 4488.9, + 7846.78, + 7336.33, + 4790.3, + 4790.26, + 4959.82, + 3664.44, + 6053.92, + 4708.72, + 5601.93, + 6957.58, + 5201.77, + 7840.16, + 7413.0, + 3656.91, + 7095.34, + 5569.93, + 6273.89, + 9.44, + 21.46, + 30.47 + ], + "cpu": [ + 2.2, + 1.9, + 2.8, + 2.0, + 4.5, + 12.1, + 9.2, + 7.1, + 7.5, + 5.5, + 13.3, + 15.7, + 18.9, + 15.5, + 7.4, + 9.3, + 7.1, + 10.1, + 9.1, + 6.1, + 9.7, + 7.4, + 9.1, + 9.2, + 13.5, + 15.4, + 6.6, + 8.7, + 6.0, + 28.4, + 94.8, + 99.5, + 60.1, + 6.9, + 5.7, + 6.7, + 6.1, + 6.3, + 13.9, + 10.0, + 6.4, + 7.2, + 5.7, + 6.4, + 6.6, + 6.1, + 5.5, + 6.3, + 6.6, + 7.5, + 6.5, + 6.4, + 17.9, + 10.2, + 6.4, + 7.9, + 6.6, + 24.8, + 93.3, + 97.1 + ], + "ram_used": [ + 61887766528, + 61882646528, + 61870043136, + 61879148544, + 61934235648, + 61984825344, + 62089637888, + 62090121216, + 62098157568, + 62098403328, + 62088568832, + 62106021888, + 61750501376, + 61766746112, + 61776080896, + 61778165760, + 61779779584, + 61908017152, + 61907206144, + 61910032384, + 62031020032, + 62033805312, + 62032531456, + 61967249408, + 61974036480, + 61990858752, + 61985890304, + 61979660288, + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840, + 62040481792, + 62030888960, + 62024949760, + 62010191872, + 62003638272, + 62026113024, + 62011977728, + 61980151808, + 61970239488, + 61954445312, + 61954318336, + 61948420096, + 61997678592, + 62080253952, + 62075203584, + 62075965440, + 62076403712, + 62076399616, + 62070407168, + 62091988992, + 62091988992, + 62093479936, + 62097862656, + 62095917056, + 62331494400, + 62325518336, + 62326792192 + ], + "disk_read_mb": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 103.38, + 66.8, + 0.0, + 24.38, + 0.0, + 55.65, + 33.54, + 0.11, + 67.43, + 0.0, + 83.76, + 1.78, + 79.2, + 71.21, + 0.0, + 79.44, + 0.0, + 77.02, + 53.81, + 0.7, + 42.73, + 0.0, + 0.0, + 0.0, + 1.02, + 5.65, + 4.98, + 3.42, + 0.54, + 0.0, + 0.01, + 0.02, + 0.0, + 0.02, + 0.03, + 0.0, + 0.03, + 0.02, + 0.0, + 0.01, + 0.0, + 0.01, + 0.02, + 0.0, + 0.0, + 12.64, + 0.0, + 71.65, + 32.97, + 0.0, + 0.0, + 0.0, + 0.99, + 5.21, + 4.66 + ], + "tok_s": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 48.0, + 86.94, + 102.06, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.0, + 103.48, + 102.58 + ] + }, + "time": 1790718052.712857 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json new file mode 100644 index 00000000..af133b71 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/native-v0.1.26-IQ3_XXS-2x3090-auto/speed-32k-3.json @@ -0,0 +1,721 @@ +{ + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "60c6cbe1b14a", + "corpus_repeated": false, + "time": "2026-09-29T21:40:52", + "prompt_tokens": 31603, + "completion_tokens": 256, + "ttft_s": 27.476, + "e2e_s": 30.102, + "api_prompt_tps": 1150.2, + "api_decode_tps": 97.1, + "engine_prompt_tps": 1158.9, + "engine_decode_tps": 96.9, + "log_lines": [ + "strata serve: prompt 31603 tokens = 0 reused + 31603 read in 27271 ms (1158.9 tok/s), 256 generated in 2641 ms (96.9 tok/s), drafts accepted 154 of 209, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.6% (148622 hits / 149275 lookups)" + ], + "answer_head": "An analysis of the last file (`docs/DETAILS.md`) and a proposed improvement follows.\n\n### What the file does\n\n`docs/DETAILS.md` serves as the comprehensive technical manual for the Strata engine. It bridges the gap between the high-level marketing in the `README.md` and the raw source code. Specific", + "metrics_after": { + "engine": { + "model": "qwen3.8-flash-next-iq3_xxs", + "max_context": 32768, + "images": false, + "version": "0.1.26", + "context": 32768, + "kv": "int8", + "kv_resident": 0, + "expert_slots": 11883, + "expert_cache_mib": 17564, + "spec": 6, + "mtp_max": 4, + "lookup": 3, + "vram_free_mib": 645, + "cvec": 0, + "arena_mib": 40925, + "pool_workers": 19, + "pcie_frac": "0.55", + "spec_min_p": "0.50", + "engine": "0.1.26" + }, + "live": { + "state": "idle", + "queued": 0, + "phase": null, + "prompt_tokens": null, + "prompt_read": null, + "prompt_total": null, + "generated": null, + "max_tokens": null, + "elapsed_s": null, + "tok_s": null, + "tok_s_mean": null, + "tok_s_window_s": null + }, + "requests": [ + { + "projection": null, + "time": 1790718052.8930452, + "duration_s": 29.9, + "finish": "length", + "prompt_tokens": 31603, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 27270.7, + "decode_ms": 2641.1, + "decode_tok_s": 96.9, + "hit_rate": 0.996 + }, + { + "projection": null, + "time": 1790718022.860633, + "duration_s": 29.4, + "finish": "length", + "prompt_tokens": 31633, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26690.6, + "decode_ms": 2648.4, + "decode_tok_s": 96.7, + "hit_rate": 0.991 + }, + { + "projection": null, + "time": 1790717992.6885722, + "duration_s": 29.5, + "finish": "length", + "prompt_tokens": 28314, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 26416.6, + "decode_ms": 3057.9, + "decode_tok_s": 83.7, + "hit_rate": 0.989 + } + ], + "requests_kept": 3, + "totals": { + "since": 1790717968.2500567, + "requests": 3, + "prompt_tokens": 91550, + "reused": 0, + "output_tokens": 768, + "prompt_ms": 80377.9, + "decode_ms": 8347.4 + }, + "hardware": { + "gpus": [ + { + "index": 0, + "util": 43, + "mem_used": 25196167168, + "mem_total": 25769803776, + "temp": 52, + "power": 242.95 + }, + { + "index": 1, + "util": 65, + "mem_used": 24208408576, + "mem_total": 25769803776, + "temp": 55, + "power": 253.875 + } + ], + "gpu_util": 54.0, + "gpu_mem_used": 49404575744, + "gpu_mem_total": 51539607552, + "gpu_temp": 55, + "gpu_power": 496.825, + "gpu_power_limit": 560.0, + "gpu_pcie_gen": 4, + "gpu_pcie_gen_max": 4, + "gpu_pcie_width": 16, + "gpu_pcie_rx_mb": 11.77734375, + "gpu_pcie_tx_mb": 120.830078125, + "cpu": 85.4, + "ram_used": 62122582016, + "ram_total": 177175990272, + "disk_read_mb": 2.9330443322466575, + "disk_write_mb": 0.08616042102070966, + "tok_s": 82.32972941826796, + "tok_s_mean": 95.05553044960695 + }, + "hardware_static": { + "gpu_name": "NVIDIA GeForce RTX 3090 + NVIDIA GeForce RTX 3090", + "gpu_count": 2, + "cpu_name": "AMD EPYC 7453 28-Core Processor", + "cores": 20, + "threads": 20, + "psutil": true + }, + "history": { + "gpu_util": [ + 31.0, + 3.0, + 46.0, + 46.0, + 22.0, + 59.5, + 29.0, + 60.0, + 26.0, + 31.5, + 71.0, + 32.5, + 28.0, + 66.0, + 23.5, + 24.5, + 18.5, + 29.0, + 28.0, + 78.0, + 30.0, + 73.5, + 16.0, + 28.0, + 25.0, + 28.0, + 29.0, + 66.0, + 26.5, + 18.5, + 43.5, + 46.0, + 0.0, + 64.5, + 26.0, + 23.0, + 72.5, + 27.0, + 66.0, + 24.5, + 76.5, + 60.5, + 27.5, + 57.5, + 24.5, + 32.0, + 66.5, + 26.0, + 27.0, + 64.5, + 29.5, + 52.5, + 65.5, + 24.0, + 23.5, + 85.0, + 30.5, + 9.5, + 46.0, + 54.0 + ], + "gpu_mem_used": [ + 49295523840, + 49383604224, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744, + 49404575744 + ], + "gpu_temp": [ + 55, + 53, + 55, + 55, + 52, + 52, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 54, + 54, + 54, + 54, + 54, + 54, + 55, + 55, + 55, + 54, + 55, + 54, + 55, + 55, + 55, + 55, + 53, + 55, + 55, + 53, + 54, + 55, + 55, + 54, + 55, + 55, + 55, + 56, + 54, + 55, + 55, + 55, + 55, + 55, + 55, + 55, + 54, + 55, + 55, + 55, + 55, + 56, + 55, + 56, + 54, + 56, + 55 + ], + "gpu_power": [ + 405.61, + 374.45, + 407.02, + 468.77, + 463.21, + 376.39, + 436.62, + 444.21, + 398.6, + 447.75, + 406.3, + 391.79, + 452.85, + 427.37, + 418.5, + 444.64, + 378.02, + 407.95, + 435.96, + 404.27, + 456.87, + 440.61, + 401.93, + 421.84, + 438.49, + 398.65, + 446.07, + 421.03, + 422.3, + 368.39, + 434.33, + 457.92, + 400.91, + 379.28, + 435.92, + 440.53, + 380.92, + 451.07, + 408.21, + 436.33, + 435.94, + 414.69, + 425.45, + 442.33, + 389.05, + 457.45, + 433.14, + 411.6, + 454.98, + 417.2, + 434.56, + 447.81, + 430.75, + 413.26, + 446.25, + 404.97, + 437.77, + 402.11, + 426.81, + 496.82 + ], + "gpu_pcie_rx_mb": [ + 6970.74, + 14.21, + 15.78, + 30.52, + 0.67, + 4175.19, + 7742.45, + 4905.89, + 4411.55, + 4744.0, + 6063.36, + 4488.9, + 7846.78, + 7336.33, + 4790.3, + 4790.26, + 4959.82, + 3664.44, + 6053.92, + 4708.72, + 5601.93, + 6957.58, + 5201.77, + 7840.16, + 7413.0, + 3656.91, + 7095.34, + 5569.93, + 6273.89, + 9.44, + 21.46, + 30.47, + 0.67, + 4040.72, + 6771.71, + 4774.76, + 3710.08, + 6013.11, + 4218.43, + 89.64, + 5065.25, + 4264.21, + 7538.94, + 3521.39, + 1962.57, + 7673.88, + 4194.59, + 12185.76, + 7580.33, + 5805.73, + 5337.71, + 5530.07, + 5019.52, + 94.17, + 4176.62, + 7140.59, + 4804.28, + 0.62, + 11.11, + 11.78 + ], + "cpu": [ + 6.0, + 28.4, + 94.8, + 99.5, + 60.1, + 6.9, + 5.7, + 6.7, + 6.1, + 6.3, + 13.9, + 10.0, + 6.4, + 7.2, + 5.7, + 6.4, + 6.6, + 6.1, + 5.5, + 6.3, + 6.6, + 7.5, + 6.5, + 6.4, + 17.9, + 10.2, + 6.4, + 7.9, + 6.6, + 24.8, + 93.3, + 97.1, + 28.6, + 7.9, + 6.3, + 6.6, + 5.7, + 7.6, + 16.1, + 12.3, + 6.8, + 6.9, + 6.2, + 7.1, + 5.6, + 6.4, + 6.7, + 5.7, + 7.5, + 6.5, + 6.0, + 8.4, + 15.8, + 7.4, + 8.5, + 6.1, + 5.7, + 7.0, + 74.1, + 85.4 + ], + "ram_used": [ + 61980233728, + 62277226496, + 62302523392, + 62302191616, + 62328995840, + 62040481792, + 62030888960, + 62024949760, + 62010191872, + 62003638272, + 62026113024, + 62011977728, + 61980151808, + 61970239488, + 61954445312, + 61954318336, + 61948420096, + 61997678592, + 62080253952, + 62075203584, + 62075965440, + 62076403712, + 62076399616, + 62070407168, + 62091988992, + 62091988992, + 62093479936, + 62097862656, + 62095917056, + 62331494400, + 62325518336, + 62326792192, + 62020993024, + 62018838528, + 62010839040, + 62003871744, + 61990277120, + 61970149376, + 61773103104, + 61820641280, + 61810376704, + 61790760960, + 61782196224, + 61814075392, + 61809737728, + 61808422912, + 61930074112, + 61927755776, + 61912608768, + 61800587264, + 61798178816, + 61793333248, + 61882507264, + 61882978304, + 61885661184, + 61886173184, + 61886357504, + 62129778688, + 62122844160, + 62122582016 + ], + "disk_read_mb": [ + 0.0, + 1.02, + 5.65, + 4.98, + 3.42, + 0.54, + 0.0, + 0.01, + 0.02, + 0.0, + 0.02, + 0.03, + 0.0, + 0.03, + 0.02, + 0.0, + 0.01, + 0.0, + 0.01, + 0.02, + 0.0, + 0.0, + 12.64, + 0.0, + 71.65, + 32.97, + 0.0, + 0.0, + 0.0, + 0.99, + 5.21, + 4.66, + 2.02, + 0.04, + 0.0, + 0.02, + 0.04, + 0.0, + 0.04, + 0.0, + 0.05, + 0.05, + 0.0, + 0.05, + 0.04, + 0.0, + 0.04, + 0.04, + 0.0, + 0.02, + 0.03, + 0.0, + 0.01, + 0.0, + 0.16, + 0.0, + 0.0, + 0.0, + 3.86, + 2.93 + ], + "tok_s": [ + 0.0, + 48.0, + 86.94, + 102.06, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 56.0, + 103.48, + 102.58, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 114.9, + 82.33 + ] + }, + "time": 1790718083.3185816 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py new file mode 100644 index 00000000..ed92ede5 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/data/strata-bench.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Strata benchmark harness (contribution plan, PR 1 step 1.2). + +Follows the upstream method (bench/results/2026-09-28-speed-0114): one code-agent prompt per +length, greedy, 256 generated tokens, MTP as configured by setup. Every run gets a unique +prefix, so conversation checkpoints cannot skip the prompt. Numbers come from the engine log +lines the owner asks for in issue #74. /metrics and API timing are stored as cross-checks. + +Stdlib only. Examples: + ./strata-bench.py --label IQ3_XXS-1x3090 --log ./strata-iq3_xxs.log + ./strata-bench.py --label Coder-2x3090-auto --contexts 16k,28k --mode needle + ./strata-bench.py --url http://127.0.0.1:9292 --model flash-next-strata --label via-llama-swap +""" + +import argparse +import json +import os +import re +import statistics +import sys +import time +import urllib.error +import urllib.request +import uuid +from datetime import datetime +from pathlib import Path + +NOMINAL = {"1k": 1024, "2.7k": 2765, "4k": 4096, "8k": 8192, "16k": 16384, "28k": 28672, + "32k": 32768, "64k": 65536, "128k": 131072, "262k": 262144} +CODE_EXT = {".py", ".cpp", ".cc", ".h", ".hpp", ".cu", ".cuh", ".js", ".md", ".txt", ".cmake"} +SKIP_DIRS = {".git", ".venv", "build", "engine", "third_party", "node_modules", "models", + "packs", "mtp", "bench", "data", "__pycache__", "Strata-data"} +LOG_PATTERNS = [ + re.compile(r"decode expert cache hit rate", re.I), + re.compile(r"\bPCIe\b"), + re.compile(r"prompt .*tok/s.*generated .*tok/s", re.I), + re.compile(r"reus|checkpoint", re.I), + re.compile(r"layer split", re.I), +] +TOKS_PER_S = re.compile(r"([\d][\d,]*(?:\.\d+)?)\s*tok(?:ens)?/s", re.I) + + +def load_corpus(dirs): + parts = [] + for d in dirs: + root = Path(d) + for p in sorted(root.rglob("*")): + if p.suffix.lower() not in CODE_EXT or not p.is_file(): + continue + if any(s in SKIP_DIRS for s in p.relative_to(root).parts[:-1]): + continue + text = p.read_text(encoding="utf-8", errors="ignore") + if text.strip(): + parts.append(f"### {p.relative_to(root).as_posix()}\n```\n{text}\n```\n") + if not parts: + sys.exit(f"no source files found in {dirs}") + return parts + + +def build_text(parts, n_chars): + out, size, i, repeated = [], 0, 0, False + while size < n_chars: + if i and i % len(parts) == 0: + repeated = True + chunk = parts[i % len(parts)] + out.append(chunk) + size += len(chunk) + i += 1 + return "".join(out)[:n_chars], repeated + + +def post_stream(url, payload, api_key, timeout): + req = urllib.request.Request( + f"{url}/v1/chat/completions", data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json", "Authorization": f"Bearer {api_key or 'none'}"}) + t0 = time.perf_counter() + t_first, text, reasoning, usage, chunks = None, [], [], {}, 0 + with urllib.request.urlopen(req, timeout=timeout) as resp: + for raw in resp: + line = raw.decode("utf-8", errors="ignore").strip() + if not line.startswith("data:"): + continue + data = line[5:].strip() + if data == "[DONE]": + break + try: + chunk = json.loads(data) + except json.JSONDecodeError: + continue + if chunk.get("usage"): + usage = chunk["usage"] + for ch in chunk.get("choices") or []: + delta = ch.get("delta") or {} + piece = delta.get("content") or "" + rpiece = delta.get("reasoning_content") or "" + if (piece or rpiece) and t_first is None: + t_first = time.perf_counter() + if piece or rpiece: + chunks += 1 + text.append(piece) + reasoning.append(rpiece) + t_end = time.perf_counter() + return {"t_start": t0, "t_first": t_first or t_end, "t_end": t_end, "text": "".join(text), + "reasoning": "".join(reasoning), "usage": usage, "chunks": chunks} + + +def get_json(url, path, api_key, timeout=10): + try: + req = urllib.request.Request(f"{url}{path}", headers={"Authorization": f"Bearer {api_key or 'none'}"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + body = r.read().decode("utf-8", errors="ignore") + try: + return json.loads(body) + except json.JSONDecodeError: + return body + except (urllib.error.URLError, TimeoutError) as e: + return {"error": str(e)} + + +def wait_healthy(url, api_key, timeout): + deadline = time.time() + timeout + while time.time() < deadline: + h = get_json(url, "/health", api_key, timeout=5) + if not (isinstance(h, dict) and "error" in h): + return True + time.sleep(5) + return False + + +def log_offset(log): + return log.stat().st_size if log and log.exists() else 0 + + +def log_lines_since(log, offset): + if not log or not log.exists(): + return [] + time.sleep(0.5) + with log.open("r", encoding="utf-8", errors="ignore") as f: + f.seek(offset) + new = f.read().splitlines() + return [ln for ln in new if any(p.search(ln) for p in LOG_PATTERNS)] + + +def engine_numbers(lines): + """Best effort: the last 'prompt ... tok/s ... generated ... tok/s' line -> (prompt, decode).""" + for ln in reversed(lines): + if LOG_PATTERNS[2].search(ln): + vals = [float(v.replace(",", "")) for v in TOKS_PER_S.findall(ln)] + if len(vals) >= 2: + return vals[0], vals[1] + return None, None + + +def target_tokens(key, max_tokens): + n = NOMINAL[key] + # leave room for the answer, like upstream's 259,943-token "262K" prompt + return n - max_tokens - 1024 if n >= 32768 else n + + +def make_messages(mode, parts, n_chars, run_id): + body, repeated = build_text(parts, n_chars) + system = f"[bench run {run_id}] You are a coding agent working in the repository shown below." + if mode == "needle": + word = uuid.uuid4().hex[:8].upper() + mid = len(body) // 2 + body = f"{body[:mid]}\n# NOTE: the secret code word is {word}.\n{body[mid:]}" + task = "What is the secret code word mentioned in the files above? Answer with the word only." + else: + word = None + task = ("Task: explain what the last file above does, then propose one concrete improvement " + "as a unified diff.") + msgs = [{"role": "system", "content": system}, + {"role": "user", "content": f"Repository files:\n\n{body}\n\n{task}"}] + return msgs, word, repeated + + +def run_once(a, parts, key, run, cpt): + tgt = target_tokens(key, a.max_tokens) + run_id = uuid.uuid4().hex[:12] + msgs, word, repeated = make_messages(a.mode, parts, int(tgt * cpt), run_id) + payload = {"model": a.model, "messages": msgs, "max_tokens": a.max_tokens, "stream": True, + "stream_options": {"include_usage": True}, "temperature": 0, + "reasoning_effort": a.reasoning_effort} + off = log_offset(a.log) + rec = {"label": a.label, "mode": a.mode, "ctx": key, "target_tokens": tgt, "run": run, + "run_id": run_id, "corpus_repeated": repeated, "time": datetime.now().isoformat(timespec="seconds")} + try: + r = post_stream(a.url, payload, a.api_key, a.timeout) + except Exception as e: # noqa: BLE001 - record and continue with the next cell + rec["error"] = str(e)[:300] + return rec, cpt + pt = r["usage"].get("prompt_tokens") + ct = r["usage"].get("completion_tokens") or r["chunks"] + ttft = r["t_first"] - r["t_start"] + dec_t = r["t_end"] - r["t_first"] + lines = log_lines_since(a.log, off) + e_prompt, e_decode = engine_numbers(lines) + rec.update({ + "prompt_tokens": pt, "completion_tokens": ct, + "ttft_s": round(ttft, 3), "e2e_s": round(r["t_end"] - r["t_start"], 3), + "api_prompt_tps": round(pt / ttft, 1) if pt and ttft > 0 else None, + "api_decode_tps": round((ct - 1) / dec_t, 1) if ct and ct > 1 and dec_t > 0 else None, + "engine_prompt_tps": e_prompt, "engine_decode_tps": e_decode, + "log_lines": lines, "answer_head": r["text"][:300], + }) + if word: + rec["needle_found"] = word in r["text"].upper() or word in r["reasoning"].upper() + if a.mode == "two-turn": + follow = msgs + [{"role": "assistant", "content": r["text"]}, + {"role": "user", "content": "Summarize your answer in one sentence."}] + off2 = log_offset(a.log) + r2 = post_stream(a.url, {**payload, "messages": follow, "max_tokens": 64}, a.api_key, a.timeout) + rec["turn2_ttft_s"] = round(r2["t_first"] - r2["t_start"], 3) + rec["turn2_prompt_tokens"] = r2["usage"].get("prompt_tokens") + rec["turn2_log_lines"] = log_lines_since(a.log, off2) + if pt: + cpt = (int(tgt * cpt) + 400) / pt # refine chars per token for the next cells + return rec, cpt + + +def write_md(path, recs, label): + def med(vals): + vals = [v for v in vals if v is not None] + return round(statistics.median(vals), 1) if vals else None + + rows = ["| ctx | prompt tokens | runs | TTFT s (med) | prompt tok/s engine / API (med) " + "| decode tok/s engine / API (run 1) | decode tok/s engine / API (med) | needle |", + "|---|---|---|---|---|---|---|---|"] + for key in dict.fromkeys(r["ctx"] for r in recs): + rs = [r for r in recs if r["ctx"] == key and "error" not in r] + errs = sum(1 for r in recs if r["ctx"] == key and "error" in r) + if not rs: + rows.append(f"| {key} | - | 0 ({errs} errors) | | | | | |") + continue + first = rs[0] + needle = "" if rs[0].get("needle_found") is None else f"{sum(r['needle_found'] for r in rs)}/{len(rs)}" + rows.append( + f"| {key} | {rs[0]['prompt_tokens']} | {len(rs)}{f' ({errs} err)' if errs else ''} " + f"| {med(r['ttft_s'] for r in rs)} " + f"| {med(r['engine_prompt_tps'] for r in rs)} / {med(r['api_prompt_tps'] for r in rs)} " + f"| {first['engine_decode_tps']} / {first['api_decode_tps']} " + f"| {med(r['engine_decode_tps'] for r in rs)} / {med(r['api_decode_tps'] for r in rs)} | {needle} |") + path.write_text(f"# {label}\n\n" + "\n".join(rows) + "\n", encoding="utf-8") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--url", default="http://127.0.0.1:8090") + ap.add_argument("--model", default="strata", help="model name sent (llama-swap: the model id)") + ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", "")) + ap.add_argument("--label", required=True, help="e.g. IQ3_XXS-1x3090-calibrated") + ap.add_argument("--contexts", default="1k,4k,32k,128k", help=f"comma list of {','.join(NOMINAL)}") + ap.add_argument("--repeats", type=int, default=3) + ap.add_argument("--max-tokens", type=int, default=256) + ap.add_argument("--reasoning-effort", default="none") + ap.add_argument("--mode", choices=["speed", "needle", "two-turn"], default="speed") + ap.add_argument("--source-dir", action="append", default=None, + help="code corpus for the prompts (default: current directory, the Strata repo)") + ap.add_argument("--log", type=Path, default=None, + help="engine log, e.g. ./strata-iq3_xxs.log") + ap.add_argument("--out", type=Path, default=Path(f"./benchmark-output/{datetime.now():%Y-%m-%d}")) + ap.add_argument("--timeout", type=float, default=1800, help="per request, seconds (262K prefill takes minutes)") + ap.add_argument("--chars-per-token", type=float, default=3.4, help="start value, refined after each run") + a = ap.parse_args() + + keys = [k.strip().lower() for k in a.contexts.split(",") if k.strip()] + bad = [k for k in keys if k not in NOMINAL] + if bad: + sys.exit(f"unknown context(s): {bad}") + parts = load_corpus(a.source_dir or ["."]) + if a.log and not a.log.exists(): + print(f"warning: log {a.log} not found; engine numbers will be empty", file=sys.stderr) + if not wait_healthy(a.url, a.api_key, 900): + sys.exit(f"{a.url}/health not reachable") + + out = a.out / a.label + (out / "data").mkdir(parents=True, exist_ok=True) + recs, cpt = [], a.chars_per_token + for key in keys: + for run in range(1, a.repeats + 1): + rec, cpt = run_once(a, parts, key, run, cpt) + rec["metrics_after"] = get_json(a.url, "/metrics", a.api_key) + recs.append(rec) + (out / "data" / f"{a.mode}-{key}-{run}.json").write_text(json.dumps(rec, indent=1), encoding="utf-8") + status = rec.get("error") or (f"prompt {rec['prompt_tokens']} tok, TTFT {rec['ttft_s']} s, " + f"decode engine {rec['engine_decode_tps']} / API {rec['api_decode_tps']} tok/s") + print(f"[{a.label}] {a.mode} {key} run {run}: {status}", flush=True) + + matrix_path = out / "matrix.json" + merged = {} + if matrix_path.exists(): + for record in json.loads(matrix_path.read_text(encoding="utf-8")): + merged[(record["mode"], record["ctx"], record["run"])] = record + for record in recs: + key = (record["mode"], record["ctx"], record["run"]) + merged[key] = {k: v for k, v in record.items() if k != "metrics_after"} + combined = list(merged.values()) + matrix_path.write_text(json.dumps(combined, indent=1), encoding="utf-8") + write_md(out / "matrix.md", combined, f"{a.label} ({a.mode})") + print(f"written: {out}/matrix.md, matrix.json, data/") + + +if __name__ == "__main__": + main() diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt new file mode 100644 index 00000000..843efcfa --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/hw.txt @@ -0,0 +1,86 @@ + +## date (UTC) +2026-09-29T22:07:24Z + +## strata version +v0.1.26 + +## os +PRETTY_NAME="Ubuntu 24.04.5 LTS" +VERSION_ID="24.04" +6.8.0-139-generic + +## virtualization +kvm + +## cpu +CPU(s): 20 +Model name: AMD EPYC 7453 28-Core Processor +Thread(s) per core: 1 +Core(s) per socket: 20 +Socket(s): 1 +L3 cache: 320 MiB (20 instances) +NUMA node(s): 1 + +## cpu flags (relevant) +avx2 f16c fma + +## numa +available: 1 nodes (0) +node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 +node 0 size: 168968 MB +node 0 free: 47460 MB +node distances: +node 0 + 0: 10 + +## memory + total used free shared buff/cache available +Mem: 165 14 46 0 105 150 +Swap: 0 0 0 + +## dimms +run as root for dmidecode +(in a VM these are virtual DIMMs: fill in the host section below by hand) + +## memlock limit +21627928 + +## gpu +index, name, driver_version, memory.total [MiB], pcie.link.gen.current, pcie.link.gen.max, pcie.link.width.current, pcie.link.width.max, power.limit [W], power.default_limit [W], power.max_limit [W], power.draw [W], clocks.max.sm [MHz] +0, NVIDIA GeForce RTX 3090, 595.91.07, 24576 MiB, 1, 4, 16, 16, 280.00 W, 350.00 W, 366.00 W, 35.23 W, 2130 MHz +1, NVIDIA GeForce RTX 3090, 595.91.07, 24576 MiB, 1, 4, 16, 16, 280.00 W, 420.00 W, 450.00 W, 28.60 W, 2100 MHz + +## gpu topology + GPU0 GPU1 CPU Affinity NUMA Affinity GPU NUMA ID +GPU0 X PHB 0-19 0 N/A +GPU1 PHB X 0-19 0 N/A + +Legend: + + X = Self + SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI) + NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node + PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU) + PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge) + PIX = Connection traversing at most a single PCIe bridge + NV# = Connection traversing a bonded set of # NVLinks + +## gpu processes (must be empty before benchmarking) +pid, process_name, used_gpu_memory [MiB] + +## docker +Docker version 29.8.1, build 4a63305 +NVIDIA Container Toolkit CLI version 1.18.1 + +## disk (model data) +Filesystem Size Used Avail Use% Mounted on +/dev/sdb1 541G 409G 106G 80% + +## host (fill in manually) +- Hypervisor: Proxmox VE (KVM guest; host version not visible inside the VM) +- CPU: AMD EPYC 7453 28-Core Processor (Milan); 20 vCPU exposed, AVX2, no AVX-512 visible +- RAM: 165 GiB visible to the guest; physical DIMM layout and bandwidth not measured +- VM: 20 vCPU, 1 socket x 20 cores x 1 thread, 1 NUMA node; ballooning and pinning not verified +- GPUs: 2x RTX 3090 24 GB; PCIe Gen4 x16 maximum reported for each (current idle link generation varies); configured power limit 280 W each +- Storage: ext4 guest data disk, 541 GiB; host storage layout not verified from the guest diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json new file mode 100644 index 00000000..4cc74c5d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.json @@ -0,0 +1,1294 @@ +[ + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "6c1252339f83", + "corpus_repeated": false, + "time": "2026-09-29T21:11:07", + "prompt_tokens": 28317, + "completion_tokens": 48, + "ttft_s": 12.868, + "e2e_s": 13.739, + "api_prompt_tps": 2200.5, + "api_decode_tps": 54.0, + "engine_prompt_tps": 2229.2, + "engine_decode_tps": 52.7, + "log_lines": [ + "strata serve: prompt 28317 tokens = 0 reused + 28317 read in 12703 ms (2229.2 tok/s), 48 generated in 911 ms (52.7 tok/s), drafts accepted 31 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (25001 hits / 25956 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "894af0ad69b7", + "corpus_repeated": false, + "time": "2026-09-29T21:11:22", + "prompt_tokens": 31630, + "completion_tokens": 26, + "ttft_s": 12.792, + "e2e_s": 13.164, + "api_prompt_tps": 2472.7, + "api_decode_tps": 67.3, + "engine_prompt_tps": 2506.6, + "engine_decode_tps": 66.8, + "log_lines": [ + "strata serve: prompt 31630 tokens = 0 reused + 31630 read in 12619 ms (2506.6 tok/s), 26 generated in 389 ms (66.8 tok/s), drafts accepted 12 of 21, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (16646 hits / 16791 lookups)" + ], + "answer_head": "I don't see any file content in the conversation above. Could you please share the file you'd like me to analyze?" + }, + { + "label": "native-v0.1.26-Coder-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "a4c63bd599ab", + "corpus_repeated": false, + "time": "2026-09-29T21:11:35", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 12.796, + "e2e_s": 13.243, + "api_prompt_tps": 2469.6, + "api_decode_tps": 98.5, + "engine_prompt_tps": 2502.4, + "engine_decode_tps": 97.4, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 12628 ms (2502.4 tok/s), 45 generated in 462 ms (97.4 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (23985 hits / 24333 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K18", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "052cbcbb7af7", + "corpus_repeated": false, + "time": "2026-09-29T21:21:48", + "prompt_tokens": 28313, + "completion_tokens": 57, + "ttft_s": 12.346, + "e2e_s": 12.991, + "api_prompt_tps": 2293.3, + "api_decode_tps": 86.9, + "engine_prompt_tps": 2324.6, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28313 tokens = 0 reused + 28313 read in 12180 ms (2324.6 tok/s), 57 generated in 686 ms (83.1 tok/s), drafts accepted 39 of 41, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.7% (28717 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "69d919ce1297", + "corpus_repeated": false, + "time": "2026-09-29T21:32:53", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.575, + "e2e_s": 11.256, + "api_prompt_tps": 2677.7, + "api_decode_tps": 82.2, + "engine_prompt_tps": 2718.9, + "engine_decode_tps": 79.8, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10414 ms (2718.9 tok/s), 57 generated in 715 ms (79.8 tok/s), drafts accepted 37 of 48, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "8506420b91e1", + "corpus_repeated": false, + "time": "2026-09-29T21:33:04", + "prompt_tokens": 31633, + "completion_tokens": 45, + "ttft_s": 10.85, + "e2e_s": 11.271, + "api_prompt_tps": 2915.4, + "api_decode_tps": 104.6, + "engine_prompt_tps": 2962.7, + "engine_decode_tps": 103.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 10677 ms (2962.7 tok/s), 45 generated in 436 ms (103.3 tok/s), drafts accepted 32 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24960 hits / 24960 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K22", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "831d87a1dacc", + "corpus_repeated": false, + "time": "2026-09-29T21:33:16", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.877, + "e2e_s": 11.43, + "api_prompt_tps": 2905.4, + "api_decode_tps": 106.7, + "engine_prompt_tps": 2951.6, + "engine_decode_tps": 105.7, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 10706 ms (2951.6 tok/s), 60 generated in 568 ms (105.7 tok/s), drafts accepted 41 of 46, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (31680 hits / 31680 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "87af67edfd2d", + "corpus_repeated": false, + "time": "2026-09-29T21:34:02", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 10.029, + "e2e_s": 12.977, + "api_prompt_tps": 2823.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 2871.1, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9862 ms (2871.1 tok/s), 256 generated in 2981 ms (85.9 tok/s), drafts accepted 143 of 193, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (147360 hits / 147360 lookups)" + ], + "answer_head": "Looking at the last file above, `docs/AMD_HIP_PERFORMANCE.md`, it documents the performance evidence and correctness limits for the experimental AMD HIP backend targeting gfx1100 (RX 7900 XTX). It records:\n\n- The exact build/runtime configuration used for the benchmark (env vars, CLI flags, model pa" + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "b38394f620b3", + "corpus_repeated": false, + "time": "2026-09-29T21:34:15", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.269, + "e2e_s": 10.686, + "api_prompt_tps": 3080.5, + "api_decode_tps": 105.5, + "engine_prompt_tps": 3130.4, + "engine_decode_tps": 104.2, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 10106 ms (3130.4 tok/s), 45 generated in 432 ms (104.2 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K24", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3bee1c1e482a", + "corpus_repeated": false, + "time": "2026-09-29T21:34:26", + "prompt_tokens": 31602, + "completion_tokens": 60, + "ttft_s": 10.281, + "e2e_s": 10.865, + "api_prompt_tps": 3073.8, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3123.2, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10118 ms (3123.2 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34560 hits / 34560 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "5ca39dba7489", + "corpus_repeated": false, + "time": "2026-09-29T21:35:22", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 9.79, + "e2e_s": 10.297, + "api_prompt_tps": 2892.2, + "api_decode_tps": 92.7, + "engine_prompt_tps": 2940.2, + "engine_decode_tps": 88.8, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 9630 ms (2940.2 tok/s), 48 generated in 540 ms (88.8 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25920 hits / 25920 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "14c7210ce0e9", + "corpus_repeated": false, + "time": "2026-09-29T21:35:32", + "prompt_tokens": 31635, + "completion_tokens": 45, + "ttft_s": 10.029, + "e2e_s": 10.496, + "api_prompt_tps": 3154.3, + "api_decode_tps": 94.3, + "engine_prompt_tps": 3205.2, + "engine_decode_tps": 93.5, + "log_lines": [ + "strata serve: prompt 31635 tokens = 0 reused + 31635 read in 9870 ms (3205.2 tok/s), 45 generated in 481 ms (93.5 tok/s), drafts accepted 31 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what the last file does." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K26", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "3f243fdb63ee", + "corpus_repeated": false, + "time": "2026-09-29T21:35:43", + "prompt_tokens": 31601, + "completion_tokens": 60, + "ttft_s": 10.026, + "e2e_s": 10.61, + "api_prompt_tps": 3151.9, + "api_decode_tps": 101.0, + "engine_prompt_tps": 3208.3, + "engine_decode_tps": 100.2, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 9850 ms (3208.3 tok/s), 60 generated in 599 ms (100.2 tok/s), drafts accepted 40 of 50, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (34080 hits / 34080 lookups)" + ], + "answer_head": "I'll start by examining the repository structure to understand what the last file is." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "0796a1ce12e4", + "corpus_repeated": false, + "time": "2026-09-29T21:36:29", + "prompt_tokens": 28316, + "completion_tokens": 57, + "ttft_s": 10.285, + "e2e_s": 10.86, + "api_prompt_tps": 2753.1, + "api_decode_tps": 97.4, + "engine_prompt_tps": 2798.5, + "engine_decode_tps": 93.7, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 10118 ms (2798.5 tok/s), 57 generated in 608 ms (93.7 tok/s), drafts accepted 40 of 42, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (28800 hits / 28800 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "3d5bf2c2aa6f", + "corpus_repeated": false, + "time": "2026-09-29T21:36:40", + "prompt_tokens": 31631, + "completion_tokens": 45, + "ttft_s": 10.58, + "e2e_s": 10.972, + "api_prompt_tps": 2989.7, + "api_decode_tps": 112.3, + "engine_prompt_tps": 3034.9, + "engine_decode_tps": 110.6, + "log_lines": [ + "strata serve: prompt 31631 tokens = 0 reused + 31631 read in 10423 ms (3034.9 tok/s), 45 generated in 407 ms (110.6 tok/s), drafts accepted 33 of 34, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (23040 hits / 23040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K28", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "d22ca9d8c7b8", + "corpus_repeated": false, + "time": "2026-09-29T21:36:51", + "prompt_tokens": 31602, + "completion_tokens": 59, + "ttft_s": 10.575, + "e2e_s": 11.17, + "api_prompt_tps": 2988.5, + "api_decode_tps": 97.4, + "engine_prompt_tps": 3037.5, + "engine_decode_tps": 96.6, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10404 ms (3037.5 tok/s), 59 generated in 611 ms (96.6 tok/s), drafts accepted 41 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (35040 hits / 35040 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "b4895f87f439", + "corpus_repeated": false, + "time": "2026-09-29T21:28:38", + "prompt_tokens": 28316, + "completion_tokens": 45, + "ttft_s": 9.936, + "e2e_s": 10.4, + "api_prompt_tps": 2849.8, + "api_decode_tps": 94.9, + "engine_prompt_tps": 2892.0, + "engine_decode_tps": 94.1, + "log_lines": [ + "strata serve: prompt 28316 tokens = 0 reused + 28316 read in 9791 ms (2892.0 tok/s), 45 generated in 478 ms (94.1 tok/s), drafts accepted 31 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (25440 hits / 25440 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f81947893a8b", + "corpus_repeated": false, + "time": "2026-09-29T21:28:49", + "prompt_tokens": 31632, + "completion_tokens": 48, + "ttft_s": 11.011, + "e2e_s": 11.496, + "api_prompt_tps": 2872.7, + "api_decode_tps": 97.0, + "engine_prompt_tps": 2926.4, + "engine_decode_tps": 96.1, + "log_lines": [ + "strata serve: prompt 31632 tokens = 0 reused + 31632 read in 10809 ms (2926.4 tok/s), 48 generated in 499 ms (96.1 tok/s), drafts accepted 32 of 38, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (27360 hits / 27360 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-K30", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "cb947708c5cc", + "corpus_repeated": false, + "time": "2026-09-29T21:29:01", + "prompt_tokens": 31602, + "completion_tokens": 45, + "ttft_s": 10.976, + "e2e_s": 11.378, + "api_prompt_tps": 2879.2, + "api_decode_tps": 109.6, + "engine_prompt_tps": 2920.6, + "engine_decode_tps": 108.0, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 10820 ms (2920.6 tok/s), 45 generated in 417 ms (108.0 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24480 hits / 24480 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "3e44ccd7ec28", + "corpus_repeated": false, + "time": "2026-09-29T21:18:00", + "prompt_tokens": 28314, + "completion_tokens": 48, + "ttft_s": 11.385, + "e2e_s": 11.891, + "api_prompt_tps": 2486.9, + "api_decode_tps": 93.0, + "engine_prompt_tps": 2524.7, + "engine_decode_tps": 88.5, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 11215 ms (2524.7 tok/s), 48 generated in 542 ms (88.5 tok/s), drafts accepted 34 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24958 hits / 24960 lookups)" + ], + "answer_head": "I'll first look at the repository structure to understand what files exist and identify the last file." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "0b6b57dfa6a4", + "corpus_repeated": false, + "time": "2026-09-29T21:18:13", + "prompt_tokens": 31634, + "completion_tokens": 55, + "ttft_s": 11.855, + "e2e_s": 12.398, + "api_prompt_tps": 2668.4, + "api_decode_tps": 99.4, + "engine_prompt_tps": 2704.3, + "engine_decode_tps": 98.6, + "log_lines": [ + "strata serve: prompt 31634 tokens = 0 reused + 31634 read in 11698 ms (2704.3 tok/s), 55 generated in 558 ms (98.6 tok/s), drafts accepted 38 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (29759 hits / 29760 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-Coder-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "caa0b992dd74", + "corpus_repeated": false, + "time": "2026-09-29T21:18:25", + "prompt_tokens": 31601, + "completion_tokens": 45, + "ttft_s": 11.847, + "e2e_s": 12.249, + "api_prompt_tps": 2667.3, + "api_decode_tps": 109.5, + "engine_prompt_tps": 2704.5, + "engine_decode_tps": 108.1, + "log_lines": [ + "strata serve: prompt 31601 tokens = 0 reused + 31601 read in 11684 ms (2704.5 tok/s), 45 generated in 416 ms (108.1 tok/s), drafts accepted 33 of 36, 2 checkpoints", + "strata serve: decode expert cache hit rate: 100.0% (24000 hits / 24000 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what we're working with." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "e13c9cdd6797", + "corpus_repeated": false, + "time": "2026-09-29T21:52:23", + "prompt_tokens": 28315, + "completion_tokens": 84, + "ttft_s": 39.45, + "e2e_s": 40.422, + "api_prompt_tps": 717.7, + "api_decode_tps": 85.4, + "engine_prompt_tps": 720.7, + "engine_decode_tps": 83.1, + "log_lines": [ + "strata serve: prompt 28315 tokens = 0 reused + 28315 read in 39287 ms (720.7 tok/s), 84 generated in 1011 ms (83.1 tok/s), drafts accepted 56 of 67, 2 checkpoints", + "strata serve: decode expert cache hit rate: 94.9% (43073 hits / 45377 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context and find the relevant files." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "f953f67441b4", + "corpus_repeated": false, + "time": "2026-09-29T21:53:04", + "prompt_tokens": 31633, + "completion_tokens": 88, + "ttft_s": 42.403, + "e2e_s": 43.165, + "api_prompt_tps": 746.0, + "api_decode_tps": 114.2, + "engine_prompt_tps": 749.3, + "engine_decode_tps": 113.3, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 42217 ms (749.3 tok/s), 88 generated in 777 ms (113.3 tok/s), drafts accepted 61 of 69, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.8% (45031 hits / 46048 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "4e71f26e7fd8", + "corpus_repeated": false, + "time": "2026-09-29T21:53:48", + "prompt_tokens": 31604, + "completion_tokens": 49, + "ttft_s": 42.269, + "e2e_s": 42.716, + "api_prompt_tps": 747.7, + "api_decode_tps": 107.5, + "engine_prompt_tps": 750.5, + "engine_decode_tps": 106.3, + "log_lines": [ + "strata serve: prompt 31604 tokens = 0 reused + 31604 read in 42111 ms (750.5 tok/s), 49 generated in 461 ms (106.3 tok/s), drafts accepted 33 of 37, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (26163 hits / 26396 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there and identify the \"last file\" being referenced." + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "1e52cb484c7f", + "corpus_repeated": false, + "time": "2026-09-29T21:55:17", + "prompt_tokens": 17345, + "completion_tokens": 8, + "ttft_s": 23.389, + "e2e_s": 23.454, + "api_prompt_tps": 741.6, + "api_decode_tps": 106.6, + "engine_prompt_tps": 744.7, + "engine_decode_tps": 101.7, + "log_lines": [ + "strata serve: prompt 17345 tokens = 0 reused + 17345 read in 23292 ms (744.7 tok/s), 8 generated in 79 ms (101.7 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (4159 hits / 4317 lookups)" + ], + "answer_head": "A466BDE8", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "c61aafff2d90", + "corpus_repeated": false, + "time": "2026-09-29T21:55:41", + "prompt_tokens": 29827, + "completion_tokens": 8, + "ttft_s": 39.958, + "e2e_s": 40.036, + "api_prompt_tps": 746.5, + "api_decode_tps": 89.7, + "engine_prompt_tps": 749.2, + "engine_decode_tps": 85.9, + "log_lines": [ + "strata serve: prompt 29827 tokens = 0 reused + 29827 read in 39812 ms (749.2 tok/s), 8 generated in 93 ms (85.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.2% (4154 hits / 4318 lookups)" + ], + "answer_head": "7BDBA3C1", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "7c040dd4c6d7", + "corpus_repeated": false, + "time": "2026-09-29T21:55:06", + "prompt_tokens": 7491, + "completion_tokens": 8, + "ttft_s": 10.682, + "e2e_s": 10.776, + "api_prompt_tps": 701.3, + "api_decode_tps": 74.7, + "engine_prompt_tps": 705.0, + "engine_decode_tps": 73.1, + "log_lines": [ + "strata serve: prompt 7491 tokens = 0 reused + 7491 read in 10625 ms (705.0 tok/s), 8 generated in 109 ms (73.1 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 90.2% (3891 hits / 4313 lookups)" + ], + "answer_head": "C43C98BD", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_S-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "2fd93144a29a", + "corpus_repeated": false, + "time": "2026-09-29T21:56:47", + "prompt_tokens": 15639, + "completion_tokens": 83, + "ttft_s": 21.242, + "e2e_s": 22.071, + "api_prompt_tps": 736.2, + "api_decode_tps": 98.8, + "engine_prompt_tps": 739.4, + "engine_decode_tps": 98.3, + "log_lines": [ + "strata serve: prompt 15639 tokens = 0 reused + 15639 read in 21151 ms (739.4 tok/s), 83 generated in 844 ms (98.3 tok/s), drafts accepted 53 of 73, 1 checkpoints", + "strata serve: decode expert cache hit rate: 98.5% (48689 hits / 49415 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand what's there.", + "turn2_ttft_s": 0.627, + "turn2_prompt_tokens": 15676, + "turn2_log_lines": [ + "strata serve: prompt 15676 tokens = 15632 reused + 44 read in 521 ms (84.4 tok/s), 64 generated in 739 ms (86.6 tok/s), drafts accepted 37 of 52, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (36768 hits / 37868 lookups)" + ] + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 1, + "run_id": "183f9c0b2a25", + "corpus_repeated": false, + "time": "2026-09-29T20:43:56", + "prompt_tokens": 119256, + "completion_tokens": 256, + "ttft_s": 55.136, + "e2e_s": 58.347, + "api_prompt_tps": 2162.9, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2185.1, + "engine_decode_tps": 79.3, + "log_lines": [ + "strata serve: prompt 119256 tokens = 0 reused + 119256 read in 54577 ms (2185.1 tok/s), 256 generated in 3230 ms (79.3 tok/s), drafts accepted 151 of 208, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.5% (140181 hits / 146787 lookups)" + ], + "answer_head": "The last file shown is `include/strata/kernels/cpu/pool.hpp`. It declares the CPU expert pool (`ExpertPool`), which is the engine's mechanism for computing the routed MoE experts that do not fit in VRAM.\n\n**What it does:**\n\n1. **Thread Management:** It creates a pool of worker threads pinned to phy" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 2, + "run_id": "815c67976126", + "corpus_repeated": false, + "time": "2026-09-29T20:44:54", + "prompt_tokens": 130360, + "completion_tokens": 256, + "ttft_s": 60.567, + "e2e_s": 63.777, + "api_prompt_tps": 2152.3, + "api_decode_tps": 79.4, + "engine_prompt_tps": 2173.6, + "engine_decode_tps": 79.4, + "log_lines": [ + "strata serve: prompt 130360 tokens = 0 reused + 130360 read in 59974 ms (2173.6 tok/s), 256 generated in 3226 ms (79.4 tok/s), drafts accepted 158 of 225, 6 checkpoints", + "strata serve: decode expert cache hit rate: 94.5% (142001 hits / 150326 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing.\n\n## What `include/strata/kernels/gdn.hpp` does\n\nThis header declares the **non-projection parts of the Gated Delta-Net (GDN) layer** \u2014 the \"mixer\" used in 36 of the model's 48 layers (the other 12 are QSA full-attention layers). It is the C++ cou" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "128k", + "target_tokens": 129792, + "run": 3, + "run_id": "317fbfabc24a", + "corpus_repeated": false, + "time": "2026-09-29T20:45:59", + "prompt_tokens": 129913, + "completion_tokens": 256, + "ttft_s": 60.534, + "e2e_s": 64.056, + "api_prompt_tps": 2146.1, + "api_decode_tps": 72.4, + "engine_prompt_tps": 2168.8, + "engine_decode_tps": 72.0, + "log_lines": [ + "strata serve: prompt 129913 tokens = 0 reused + 129913 read in 59901 ms (2168.8 tok/s), 256 generated in 3556 ms (72.0 tok/s), drafts accepted 148 of 200, 6 checkpoints", + "strata serve: decode expert cache hit rate: 95.6% (138618 hits / 145073 lookups)" + ], + "answer_head": "The last file is `include/strata/kernels/gdn.hpp`. It declares the non-projection parts of the gated delta-net (GDN) layer used by 36 of the model's 48 layers. It defines `GdnShapes` (S=128, h_k=16, h_v=48) and declares `gdn_step`, which performs one in-place step of the delta-rule recurrence: it de" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 1, + "run_id": "56b3dec5f002", + "corpus_repeated": false, + "time": "2026-09-29T20:40:39", + "prompt_tokens": 1092, + "completion_tokens": 256, + "ttft_s": 1.378, + "e2e_s": 4.115, + "api_prompt_tps": 792.3, + "api_decode_tps": 93.2, + "engine_prompt_tps": 808.1, + "engine_decode_tps": 93.0, + "log_lines": [ + "strata serve: prompt 1092 tokens = 0 reused + 1092 read in 1351 ms (808.1 tok/s), 256 generated in 2753 ms (93.0 tok/s), drafts accepted 159 of 210, 1 checkpoints", + "strata serve: decode expert cache hit rate: 95.4% (137036 hits / 143638 lookups)" + ], + "answer_head": "Based on the content of `CMakeLists.txt`, here is an explanation of its function and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file serves as the top-level build configuration for the **Strata Engine** (version 0.1.26). Its primary responsibilities are:\n\n1. **Project Defini" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 2, + "run_id": "5da89525cd83", + "corpus_repeated": false, + "time": "2026-09-29T20:40:43", + "prompt_tokens": 1149, + "completion_tokens": 256, + "ttft_s": 1.323, + "e2e_s": 4.156, + "api_prompt_tps": 868.4, + "api_decode_tps": 90.0, + "engine_prompt_tps": 885.5, + "engine_decode_tps": 89.9, + "log_lines": [ + "strata serve: prompt 1149 tokens = 0 reused + 1149 read in 1298 ms (885.5 tok/s), 256 generated in 2847 ms (89.9 tok/s), drafts accepted 156 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.1% (144603 hits / 148933 lookups)" + ], + "answer_head": "Based on the content provided, here is an explanation of the `CMakeLists.txt` file and a proposed improvement.\n\n### Explanation of `CMakeLists.txt`\n\nThis file is the top-level build configuration for the **Strata Engine** (specifically Phase 1, Step 1). Its primary responsibilities are:\n\n1. **Proje" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "1k", + "target_tokens": 1024, + "run": 3, + "run_id": "3ad6050d1d4c", + "corpus_repeated": false, + "time": "2026-09-29T20:40:48", + "prompt_tokens": 1135, + "completion_tokens": 256, + "ttft_s": 1.33, + "e2e_s": 4.007, + "api_prompt_tps": 853.1, + "api_decode_tps": 95.3, + "engine_prompt_tps": 869.7, + "engine_decode_tps": 95.1, + "log_lines": [ + "strata serve: prompt 1135 tokens = 0 reused + 1135 read in 1305 ms (869.7 tok/s), 256 generated in 2691 ms (95.1 tok/s), drafts accepted 159 of 217, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.2% (145229 hits / 149472 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file defines the top-level build configuration for the **Strata Engine** project. Its primary responsibilities include:\n\n1. **Project Definition**: Sets the project name (`strata`), version (`0.1.26`), and language standard (C++20).\n2. **Target Management**: Conditionally adds" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 1, + "run_id": "459ef0e5c155", + "corpus_repeated": false, + "time": "2026-09-29T20:52:28", + "prompt_tokens": 232183, + "completion_tokens": 256, + "ttft_s": 131.32, + "e2e_s": 135.339, + "api_prompt_tps": 1768.1, + "api_decode_tps": 63.4, + "engine_prompt_tps": 1784.6, + "engine_decode_tps": 63.0, + "log_lines": [ + "strata serve: prompt 232183 tokens = 0 reused + 232183 read in 130101 ms (1784.6 tok/s), 256 generated in 4061 ms (63.0 tok/s), drafts accepted 150 of 240, 6 checkpoints", + "strata serve: decode expert cache hit rate: 93.7% (149829 hits / 159942 lookups)" + ], + "answer_head": "The last file is `serve/server.py` (the listing is truncated at the very end, in the `main()` function where it assigns `svc.gpu_index`).\n\n## What it does\n\nIt is the HTTP API layer of Strata: a pure-Python bridge between OpenAI/Anthropic-style clients and the C++ engine. Concretely:\n\n- **Engine adap" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 2, + "run_id": "fbabd65a593d", + "corpus_repeated": false, + "time": "2026-09-29T20:54:43", + "prompt_tokens": 259589, + "completion_tokens": 92, + "ttft_s": 152.099, + "e2e_s": 153.446, + "api_prompt_tps": 1706.7, + "api_decode_tps": 67.5, + "engine_prompt_tps": 1721.6, + "engine_decode_tps": 67.3, + "log_lines": [ + "strata serve: prompt 259589 tokens = 0 reused + 259589 read in 150784 ms (1721.6 tok/s), 92 generated in 1367 ms (67.3 tok/s), drafts accepted 61 of 75, 6 checkpoints", + "strata serve: decode expert cache hit rate: 90.0% (43983 hits / 48863 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the codebase and the last file in detail." + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "262k", + "target_tokens": 260864, + "run": 3, + "run_id": "40a721fd9a17", + "corpus_repeated": false, + "time": "2026-09-29T20:57:17", + "prompt_tokens": 261068, + "completion_tokens": 256, + "ttft_s": 152.605, + "e2e_s": 156.279, + "api_prompt_tps": 1710.7, + "api_decode_tps": 69.4, + "engine_prompt_tps": 1725.6, + "engine_decode_tps": 69.3, + "log_lines": [ + "strata serve: prompt 261068 tokens = 0 reused + 261068 read in 151288 ms (1725.6 tok/s), 256 generated in 3693 ms (69.3 tok/s), drafts accepted 151 of 231, 6 checkpoints", + "strata serve: decode expert cache hit rate: 96.3% (153481 hits / 159304 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and then propose a concrete improvement.\n\n## What `serve/web/app.js` does\n\nThis file is the **entire client-side logic of the Strata web application** \u2014 a framework-free, single-file JavaScript app that talks only to the local Strata server. It po" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "563f1c703ebe", + "corpus_repeated": false, + "time": "2026-09-29T20:41:08", + "prompt_tokens": 34932, + "completion_tokens": 256, + "ttft_s": 16.748, + "e2e_s": 19.56, + "api_prompt_tps": 2085.7, + "api_decode_tps": 90.7, + "engine_prompt_tps": 2110.2, + "engine_decode_tps": 90.6, + "log_lines": [ + "strata serve: prompt 34932 tokens = 0 reused + 34932 read in 16554 ms (2110.2 tok/s), 256 generated in 2827 ms (90.6 tok/s), drafts accepted 167 of 216, 3 checkpoints", + "strata serve: decode expert cache hit rate: 94.1% (133137 hits / 141416 lookups)" + ], + "answer_head": "I'll analyze the last file in the repository listing and propose an improvement.\n\n## What `docs/DETAILS.md` does\n\nThis is the comprehensive technical documentation file for the Strata project. It serves as the single source of truth for:\n\n1. **Performance benchmarks** \u2014 Detailed tables of prompt-pro" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "283cb867e188", + "corpus_repeated": false, + "time": "2026-09-29T20:41:28", + "prompt_tokens": 31582, + "completion_tokens": 256, + "ttft_s": 14.807, + "e2e_s": 18.058, + "api_prompt_tps": 2132.9, + "api_decode_tps": 78.4, + "engine_prompt_tps": 2160.4, + "engine_decode_tps": 78.3, + "log_lines": [ + "strata serve: prompt 31582 tokens = 0 reused + 31582 read in 14619 ms (2160.4 tok/s), 256 generated in 3271 ms (78.3 tok/s), drafts accepted 161 of 240, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (151459 hits / 157708 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the **comprehensive technical manual and reference guide** for the Strata engine. While the `README.md` focuses on quick installation and high-level marketing, `DETAILS.md` provides the deep technical spec" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "1aba3d88be7a", + "corpus_repeated": false, + "time": "2026-09-29T20:41:47", + "prompt_tokens": 31602, + "completion_tokens": 256, + "ttft_s": 14.833, + "e2e_s": 17.604, + "api_prompt_tps": 2130.5, + "api_decode_tps": 92.0, + "engine_prompt_tps": 2161.9, + "engine_decode_tps": 91.9, + "log_lines": [ + "strata serve: prompt 31602 tokens = 0 reused + 31602 read in 14618 ms (2161.9 tok/s), 256 generated in 2785 ms (91.9 tok/s), drafts accepted 160 of 207, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.5% (137828 hits / 142765 lookups)" + ], + "answer_head": "The last file in the provided list is `docs/DETAILS.md`.\n\n### What it does\nThis file serves as the comprehensive technical documentation and user manual for the \"Strata\" engine. It bridges the gap between the high-level marketing pitch in `README.md` and the raw source code. Specifically, it:\n\n1. *" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 1, + "run_id": "6c6e9cb15bc9", + "corpus_repeated": false, + "time": "2026-09-29T20:40:53", + "prompt_tokens": 3881, + "completion_tokens": 256, + "ttft_s": 2.267, + "e2e_s": 5.041, + "api_prompt_tps": 1711.6, + "api_decode_tps": 91.9, + "engine_prompt_tps": 1745.2, + "engine_decode_tps": 91.7, + "log_lines": [ + "strata serve: prompt 3881 tokens = 0 reused + 3881 read in 2224 ms (1745.2 tok/s), 256 generated in 2791 ms (91.7 tok/s), drafts accepted 155 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (146401 hits / 150495 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. It orchestrates the compilation of the project, handling complex dependencies between CPU-only components, GPU kernels (CUDA/HIP), and testing infrastructure.\n\n### What the file does:\n\n1. **Project Configurati" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 2, + "run_id": "1df8c923675b", + "corpus_repeated": false, + "time": "2026-09-29T20:40:58", + "prompt_tokens": 4200, + "completion_tokens": 142, + "ttft_s": 2.418, + "e2e_s": 4.063, + "api_prompt_tps": 1736.7, + "api_decode_tps": 85.7, + "engine_prompt_tps": 1772.2, + "engine_decode_tps": 85.5, + "log_lines": [ + "strata serve: prompt 4200 tokens = 0 reused + 4200 read in 2370 ms (1772.2 tok/s), 142 generated in 1660 ms (85.5 tok/s), drafts accepted 96 of 114, 1 checkpoints", + "strata serve: decode expert cache hit rate: 89.6% (64163 hits / 71608 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better." + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090", + "mode": "speed", + "ctx": "4k", + "target_tokens": 4096, + "run": 3, + "run_id": "777f84f22df4", + "corpus_repeated": false, + "time": "2026-09-29T20:41:03", + "prompt_tokens": 4201, + "completion_tokens": 256, + "ttft_s": 2.409, + "e2e_s": 5.262, + "api_prompt_tps": 1744.1, + "api_decode_tps": 89.4, + "engine_prompt_tps": 1775.8, + "engine_decode_tps": 89.2, + "log_lines": [ + "strata serve: prompt 4201 tokens = 0 reused + 4201 read in 2366 ms (1775.8 tok/s), 256 generated in 2868 ms (89.2 tok/s), drafts accepted 161 of 222, 1 checkpoints", + "strata serve: decode expert cache hit rate: 96.0% (144002 hits / 149996 lookups)" + ], + "answer_head": "The `CMakeLists.txt` file is the top-level build configuration for the **Strata Engine**. Its primary responsibilities are:\n\n1. **Project Definition**: Sets up the project name (`strata`), version (`0.1.26`), and C++20 standard.\n2. **Backend Selection**: Manages mutually exclusive GPU backends (CU" + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "e39790e5649d", + "corpus_repeated": false, + "time": "2026-09-29T20:47:57", + "prompt_tokens": 17346, + "completion_tokens": 8, + "ttft_s": 9.075, + "e2e_s": 9.178, + "api_prompt_tps": 1911.3, + "api_decode_tps": 68.2, + "engine_prompt_tps": 1933.6, + "engine_decode_tps": 67.4, + "log_lines": [ + "strata serve: prompt 17346 tokens = 0 reused + 17346 read in 8971 ms (1933.6 tok/s), 8 generated in 119 ms (67.4 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3014 hits / 3740 lookups)" + ], + "answer_head": "37E3DB14", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "94aa92e58ada", + "corpus_repeated": false, + "time": "2026-09-29T20:48:07", + "prompt_tokens": 29820, + "completion_tokens": 8, + "ttft_s": 14.138, + "e2e_s": 14.241, + "api_prompt_tps": 2109.2, + "api_decode_tps": 68.2, + "engine_prompt_tps": 2134.7, + "engine_decode_tps": 66.5, + "log_lines": [ + "strata serve: prompt 29820 tokens = 0 reused + 29820 read in 13969 ms (2134.7 tok/s), 8 generated in 120 ms (66.5 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 80.6% (3033 hits / 3764 lookups)" + ], + "answer_head": "64EC0999", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "3c83d69c2581", + "corpus_repeated": false, + "time": "2026-09-29T20:47:52", + "prompt_tokens": 7493, + "completion_tokens": 8, + "ttft_s": 4.2, + "e2e_s": 4.307, + "api_prompt_tps": 1783.9, + "api_decode_tps": 65.8, + "engine_prompt_tps": 1816.6, + "engine_decode_tps": 64.9, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 4125 ms (1816.6 tok/s), 8 generated in 123 ms (64.9 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 74.8% (2704 hits / 3615 lookups)" + ], + "answer_head": "0E6415FF", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-1x3090-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "7aed17dd03cd", + "corpus_repeated": false, + "time": "2026-09-29T20:48:48", + "prompt_tokens": 15636, + "completion_tokens": 256, + "ttft_s": 7.488, + "e2e_s": 10.882, + "api_prompt_tps": 2088.0, + "api_decode_tps": 75.1, + "engine_prompt_tps": 2114.8, + "engine_decode_tps": 75.1, + "log_lines": [ + "strata serve: prompt 15636 tokens = 0 reused + 15636 read in 7394 ms (2114.8 tok/s), 256 generated in 3410 ms (75.1 tok/s), drafts accepted 152 of 215, 1 checkpoints", + "strata serve: decode expert cache hit rate: 93.0% (136865 hits / 147168 lookups)" + ], + "answer_head": "## What `README.md` does\n\n`README.md` is the project's landing page and primary user-facing documentation. It serves several purposes:\n\n1. **Marketing/overview** \u2014 Opens with a headline claim (\"Run a 125-billion-parameter AI model on a normal gaming PC\") and a visual demo (the pagoda video) to immed", + "turn2_ttft_s": 0.438, + "turn2_prompt_tokens": 15915, + "turn2_log_lines": [ + "strata serve: prompt 15915 tokens = 15892 reused + 23 read in 332 ms (69.3 tok/s), 46 generated in 661 ms (69.6 tok/s), drafts accepted 27 of 44, 2 checkpoints", + "strata serve: decode expert cache hit rate: 96.4% (29047 hits / 30124 lookups)" + ] + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 1, + "run_id": "cfa75b59eb61", + "corpus_repeated": false, + "time": "2026-09-29T21:39:52", + "prompt_tokens": 28314, + "completion_tokens": 256, + "ttft_s": 26.573, + "e2e_s": 29.595, + "api_prompt_tps": 1065.5, + "api_decode_tps": 84.4, + "engine_prompt_tps": 1071.8, + "engine_decode_tps": 83.7, + "log_lines": [ + "strata serve: prompt 28314 tokens = 0 reused + 28314 read in 26417 ms (1071.8 tok/s), 256 generated in 3058 ms (83.7 tok/s), drafts accepted 147 of 251, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.9% (171443 hits / 173268 lookups)" + ], + "answer_head": "The last file in the repository listing is `docs/DETAILS.md`.\n\n### What `docs/DETAILS.md` does\n\nIt is the comprehensive technical documentation and reference manual for the Strata engine. While the `README.md` focuses on quick installation and high-level usage, `DETAILS.md` provides the deep technic" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 2, + "run_id": "c27c8adc0b65", + "corpus_repeated": false, + "time": "2026-09-29T21:40:22", + "prompt_tokens": 31633, + "completion_tokens": 256, + "ttft_s": 26.904, + "e2e_s": 29.536, + "api_prompt_tps": 1175.8, + "api_decode_tps": 96.9, + "engine_prompt_tps": 1185.2, + "engine_decode_tps": 96.7, + "log_lines": [ + "strata serve: prompt 31633 tokens = 0 reused + 31633 read in 26691 ms (1185.2 tok/s), 256 generated in 2648 ms (96.7 tok/s), drafts accepted 160 of 214, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.1% (147426 hits / 148799 lookups)" + ], + "answer_head": "I cannot analyze the last file because the provided repository content is truncated. The `docs/DETAILS.md` file cuts off mid-sentence in the \"Using it\" section (`...if y`), and no subsequent files are shown.\n\nHowever, I can analyze the **`chat.py`** file, which is the last *complete* file provided i" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto", + "mode": "speed", + "ctx": "32k", + "target_tokens": 31488, + "run": 3, + "run_id": "60c6cbe1b14a", + "corpus_repeated": false, + "time": "2026-09-29T21:40:52", + "prompt_tokens": 31603, + "completion_tokens": 256, + "ttft_s": 27.476, + "e2e_s": 30.102, + "api_prompt_tps": 1150.2, + "api_decode_tps": 97.1, + "engine_prompt_tps": 1158.9, + "engine_decode_tps": 96.9, + "log_lines": [ + "strata serve: prompt 31603 tokens = 0 reused + 31603 read in 27271 ms (1158.9 tok/s), 256 generated in 2641 ms (96.9 tok/s), drafts accepted 154 of 209, 2 checkpoints", + "strata serve: decode expert cache hit rate: 99.6% (148622 hits / 149275 lookups)" + ], + "answer_head": "An analysis of the last file (`docs/DETAILS.md`) and a proposed improvement follows.\n\n### What the file does\n\n`docs/DETAILS.md` serves as the comprehensive technical manual for the Strata engine. It bridges the gap between the high-level marketing in the `README.md` and the raw source code. Specific" + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "8f89dfed9af3", + "corpus_repeated": false, + "time": "2026-09-29T22:00:26", + "prompt_tokens": 17344, + "completion_tokens": 8, + "ttft_s": 15.582, + "e2e_s": 15.663, + "api_prompt_tps": 1113.1, + "api_decode_tps": 86.5, + "engine_prompt_tps": 1119.9, + "engine_decode_tps": 83.8, + "log_lines": [ + "strata serve: prompt 17344 tokens = 0 reused + 17344 read in 15487 ms (1119.9 tok/s), 8 generated in 96 ms (83.8 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 97.3% (4205 hits / 4320 lookups)" + ], + "answer_head": "05449BFC", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "28k", + "target_tokens": 28672, + "run": 1, + "run_id": "93a9a0e32114", + "corpus_repeated": false, + "time": "2026-09-29T22:00:42", + "prompt_tokens": 29825, + "completion_tokens": 9, + "ttft_s": 26.19, + "e2e_s": 26.262, + "api_prompt_tps": 1138.8, + "api_decode_tps": 110.5, + "engine_prompt_tps": 1146.7, + "engine_decode_tps": 103.9, + "log_lines": [ + "strata serve: prompt 29825 tokens = 0 reused + 29825 read in 26009 ms (1146.7 tok/s), 9 generated in 87 ms (103.9 tok/s), drafts accepted 6 of 6, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.2% (4241 hits / 4320 lookups)" + ], + "answer_head": "98C00B03", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-needle", + "mode": "needle", + "ctx": "8k", + "target_tokens": 8192, + "run": 1, + "run_id": "d1d745f05911", + "corpus_repeated": false, + "time": "2026-09-29T22:00:17", + "prompt_tokens": 7493, + "completion_tokens": 9, + "ttft_s": 7.948, + "e2e_s": 8.057, + "api_prompt_tps": 942.8, + "api_decode_tps": 73.4, + "engine_prompt_tps": 953.1, + "engine_decode_tps": 58.6, + "log_lines": [ + "strata serve: prompt 7493 tokens = 0 reused + 7493 read in 7861 ms (953.1 tok/s), 9 generated in 154 ms (58.6 tok/s), drafts accepted 6 of 6, 1 checkpoints", + "strata serve: decode expert cache hit rate: 94.0% (4062 hits / 4320 lookups)" + ], + "answer_head": "69231569", + "needle_found": true + }, + { + "label": "native-v0.1.26-IQ3_XXS-2x3090-auto-two-turn", + "mode": "two-turn", + "ctx": "16k", + "target_tokens": 16384, + "run": 1, + "run_id": "dedda4f9d6be", + "corpus_repeated": false, + "time": "2026-09-29T22:01:09", + "prompt_tokens": 15635, + "completion_tokens": 44, + "ttft_s": 13.63, + "e2e_s": 14.13, + "api_prompt_tps": 1147.1, + "api_decode_tps": 86.1, + "engine_prompt_tps": 1154.6, + "engine_decode_tps": 85.6, + "log_lines": [ + "strata serve: prompt 15635 tokens = 0 reused + 15635 read in 13541 ms (1154.6 tok/s), 44 generated in 514 ms (85.6 tok/s), drafts accepted 30 of 36, 1 checkpoints", + "strata serve: decode expert cache hit rate: 97.9% (24433 hits / 24957 lookups)" + ], + "answer_head": "I'll start by exploring the repository structure to understand the context better.", + "turn2_ttft_s": 0.577, + "turn2_prompt_tokens": 15672, + "turn2_log_lines": [ + "strata serve: prompt 15672 tokens = 15628 reused + 44 read in 490 ms (89.8 tok/s), 48 generated in 567 ms (84.6 tok/s), drafts accepted 28 of 43, 2 checkpoints", + "strata serve: decode expert cache hit rate: 98.6% (31236 hits / 31679 lookups)" + ] + } +] diff --git a/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md new file mode 100644 index 00000000..31b53b4d --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-rtx3090-epyc-milan/matrix.md @@ -0,0 +1,48 @@ +# Native benchmark matrix (v0.1.26) + +Prompt speeds are engine tok/s medians; output lists the first-run value and the three-run median. `prompt tokens` is the median measured count. Draft acceptance is the mean of per-run accepted/offered values from engine logs. + +## IQ3_XXS, one RTX 3090 + +| Context | Prompt tokens | Prompt tok/s | Decode first / median tok/s | TTFT median | Draft acceptance | +|---|---:|---:|---:|---:|---:| +| 1K | 1,135 | 869.7 | 93.0 / 93.0 | 1.33 s | 0.738 | +| 4K | 4,200 | 1,772.2 | 91.7 / 89.2 | 2.41 s | 0.763 | +| 32K | 31,602 | 2,160.4 | 90.6 / 90.6 | 14.83 s | 0.739 | +| 128K | 129,913 | 2,173.6 | 79.3 / 79.3 | 60.53 s | 0.723 | +| 262K | 259,589 | 1,725.6 | 63.0 / 67.3 | 152.10 s | 0.697 | + +## 32K model and GPU comparison + +| Model | GPUs / split | Prompt tokens | Prompt tok/s median | Decode first / median tok/s | TTFT median | Draft acceptance | +|---|---|---:|---:|---:|---:|---:| +| Coder IQ1_M | 1x 3090 | 31,601 | 2,502.4 | 52.7 / 66.8 | 12.80 s | 0.760 | +| Coder IQ1_M | 2x 3090, auto K=19 | 31,601 | 2,704.3 | 88.5 / 98.6 | 11.85 s | 0.908 | +| IQ3_XXS | 2x 3090, auto K=24 | 31,603 | 1,158.9 | 83.7 / 96.7 | 26.90 s | 0.690 | +| IQ3_S | 2x 3090, auto K=24 | 31,604 | 749.3 | 83.1 / 106.3 | 42.27 s | 0.871 | + +## Coder IQ1_M fixed layer split + +One initial 32K run per K, then three-run repeats for K=22–30. Prompts are independent and adaptive-cache behavior varies; compare the medians cautiously. + +| Split | Successful runs | Prompt tok/s median | Decode tok/s median | Notes | +|---|---:|---:|---:|---| +| Auto (K=19) | 3 | 2,704.3 | 98.6 | Layers 0–18 / 19–47 | +| K=18 | 1 | 2,324.6 | 83.1 | Repeat startup OOM while uploading a dense weight | +| K=22 | 3 | 2,951.6 | 103.3 | Layers 0–21 / 22–47 | +| K=24 | 3 | 3,123.2 | 100.2 | Layers 0–23 / 24–47 | +| K=26 | 3 | 3,205.2 | 93.5 | Layers 0–25 / 26–47 | +| K=28 | 3 | 3,034.9 | 96.6 | Layers 0–27 / 28–47 | +| K=30 | 3 | 2,920.6 | 96.1 | Layers 0–29 / 30–47 | + +## Correctness + +| Model / setup | Check | Result | +|---|---|---| +| IQ3_XXS, 1x 3090 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_XXS, 1x 3090 | 16K two-turn chat | 15,892 / 15,915 prompt tokens reused on turn two | +| IQ3_XXS, 2x 3090 auto K=24 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_XXS, 2x 3090 auto K=24 | 16K two-turn chat | 15,628 / 15,672 prompt tokens reused on turn two | +| IQ3_S, 2x 3090 auto K=24 | Needles 8K / 16K / 28K | 3/3 found | +| IQ3_S, 2x 3090 auto K=24 | 16K two-turn chat | 15,632 / 15,676 prompt tokens reused on turn two | +| Coder, 2x 3090 | Needles / two-turn | Not run | diff --git a/engine/strata/bench/results/2026-09-29-speed-0122/README.md b/engine/strata/bench/results/2026-09-29-speed-0122/README.md new file mode 100644 index 00000000..37d190c1 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-speed-0122/README.md @@ -0,0 +1,32 @@ +# Speed with engine 0.1.22 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.22 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens, images +off. The same code-agent prompts as `2026-09-28-speed-0114`. Every run: [`matrix.json`](matrix.json). + +## Prompt (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 519 | 1,226 | 1,844 | 1,836 | 1,682 | 1,304 | +| **IQ2_XS** | 524 | 1,196 | 1,799 | 1,611 | 1,495 | 1,181 | +| **IQ3_XXS** | 472 | 974 | 1,555 | 1,449 | 1,386 | - | +| **IQ3_S** | 419 | 893 | 1,499 | 1,285 | 1,245 | - | +| **Coder** | 660 | 1,522 | 1,871 | 1,938 | 1,779 | - | + +## Output (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 84.7 | 88.2 | 77.4 | 71.0 | 63.1 | 61.1 | +| **IQ2_XS** | 77.2 | 74.6 | 67.5 | 63.5 | 59.1 | 54.7 | +| **IQ3_XXS** | 65.1 | 62.3 | 49.8 | 53.6 | 47.0 | - | +| **IQ3_S** | 50.5 | 44.6 | 49.0 | 48.8 | 41.3 | - | +| **Coder** | 56.9 | 53.6 | 54.9 | 48.5 | 42.8 | - | + +- IQ2_XS was measured with Swift 1.5's IQ2_XS (the same speed as the original's); its 262K run had images on. +- IQ3_XXS and IQ3_S at 262K do not fit 64 GB of RAM; the Coder at 262K was not run again (0.1.14: 1,034 tokens/s). +- Against 0.1.14: prompts 1.2-1.5x faster at 32K-128K (the 0.1.22 prompt path: tensor-core attention, bit-identical + batched kernels, faster PLE reads). Output speed is the engine's same decode; one run per cell moves a few percent + with the text (speculative drafts), so compare it across many runs, not one. diff --git a/engine/strata/bench/results/2026-09-29-speed-0122/matrix.json b/engine/strata/bench/results/2026-09-29-speed-0122/matrix.json new file mode 100644 index 00000000..82d52f1c --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-speed-0122/matrix.json @@ -0,0 +1,380 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 40.0, + "decode_tok_s": 84.71, + "decoded": 256, + "prefill_tok_s": 519.48, + "ttft_s": 3.62, + "spec_accept": 0.786, + "tokens_per_round": 2.77, + "vram_slots": 4176 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 41.6, + "decode_tok_s": 88.23, + "decoded": 256, + "prefill_tok_s": 1226.49, + "ttft_s": 4.43, + "spec_accept": 0.839, + "tokens_per_round": 3.24, + "vram_slots": 4123 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 56.6, + "decode_tok_s": 77.37, + "decoded": 256, + "prefill_tok_s": 1843.83, + "ttft_s": 18.63, + "spec_accept": 0.808, + "tokens_per_round": 3.04, + "vram_slots": 3833 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 72.9, + "decode_tok_s": 71.0, + "decoded": 256, + "prefill_tok_s": 1835.64, + "ttft_s": 36.48, + "spec_accept": 0.685, + "tokens_per_round": 2.77, + "vram_slots": 3780 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 118.1, + "decode_tok_s": 63.08, + "decoded": 256, + "prefill_tok_s": 1681.64, + "ttft_s": 77.92, + "spec_accept": 0.7, + "tokens_per_round": 2.56, + "vram_slots": 3697 + }, + { + "model": "Q2_0", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 242.0, + "decode_tok_s": 61.12, + "decoded": 256, + "prefill_tok_s": 1303.83, + "ttft_s": 200.94, + "spec_accept": 0.627, + "tokens_per_round": 2.5, + "vram_slots": 3525 + }, + { + "model": "IQ2_XS", + "tier": "262k", + "prompt_tokens": 259943, + "exit": 0, + "wall_s": 263.6, + "decode_tok_s": 54.68, + "decoded": 256, + "prefill_tok_s": 1180.58, + "ttft_s": 221.91, + "spec_accept": 0.632, + "tokens_per_round": 2.49, + "vram_slots": 3727 + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 56.0, + "decode_tok_s": 50.5, + "decoded": 256, + "prefill_tok_s": 419.48, + "ttft_s": 3.98, + "spec_accept": 0.811, + "tokens_per_round": 3.17, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 60.0, + "decode_tok_s": 44.58, + "decoded": 256, + "prefill_tok_s": 892.84, + "ttft_s": 5.53, + "spec_accept": 0.672, + "tokens_per_round": 2.69, + "vram_slots": 2580 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 75.6, + "decode_tok_s": 48.96, + "decoded": 256, + "prefill_tok_s": 1499.09, + "ttft_s": 22.65, + "spec_accept": 0.79, + "tokens_per_round": 2.9, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 102.1, + "decode_tok_s": 48.8, + "decoded": 256, + "prefill_tok_s": 1284.81, + "ttft_s": 51.58, + "spec_accept": 0.797, + "tokens_per_round": 2.94, + "vram_slots": 2281 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 159.2, + "decode_tok_s": 41.27, + "decoded": 256, + "prefill_tok_s": 1244.55, + "ttft_s": 104.81, + "spec_accept": 0.694, + "tokens_per_round": 2.73, + "vram_slots": 2292 + }, + { + "model": "Coder", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 34.5, + "decode_tok_s": 56.94, + "decoded": 256, + "prefill_tok_s": 660.44, + "ttft_s": 2.42, + "spec_accept": 0.74, + "tokens_per_round": 2.91, + "vram_slots": 2650 + }, + { + "model": "Coder", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 18.8, + "decode_tok_s": 53.65, + "decoded": 256, + "prefill_tok_s": 1521.84, + "ttft_s": 3.21, + "spec_accept": 0.736, + "tokens_per_round": 2.91, + "vram_slots": 2615 + }, + { + "model": "Coder", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 33.1, + "decode_tok_s": 54.85, + "decoded": 256, + "prefill_tok_s": 1870.76, + "ttft_s": 17.7, + "spec_accept": 0.806, + "tokens_per_round": 3.11, + "vram_slots": 2418 + }, + { + "model": "Coder", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 50.2, + "decode_tok_s": 48.46, + "decoded": 256, + "prefill_tok_s": 1937.69, + "ttft_s": 33.99, + "spec_accept": 0.653, + "tokens_per_round": 2.56, + "vram_slots": 2382 + }, + { + "model": "Coder", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 90.3, + "decode_tok_s": 42.75, + "decoded": 256, + "prefill_tok_s": 1778.66, + "ttft_s": 73.12, + "spec_accept": 0.588, + "tokens_per_round": 2.27, + "vram_slots": 2326 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 43.6, + "decode_tok_s": 77.16, + "decoded": 256, + "prefill_tok_s": 523.77, + "ttft_s": 3.46, + "spec_accept": 0.811, + "tokens_per_round": 3.02, + "vram_slots": 4361 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 43.7, + "decode_tok_s": 74.58, + "decoded": 256, + "prefill_tok_s": 1196.03, + "ttft_s": 4.47, + "spec_accept": 0.824, + "tokens_per_round": 3.36, + "vram_slots": 4309 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 59.6, + "decode_tok_s": 67.46, + "decoded": 256, + "prefill_tok_s": 1798.65, + "ttft_s": 19.06, + "spec_accept": 0.789, + "tokens_per_round": 3.02, + "vram_slots": 4030 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 81.4, + "decode_tok_s": 63.52, + "decoded": 256, + "prefill_tok_s": 1610.73, + "ttft_s": 41.37, + "spec_accept": 0.705, + "tokens_per_round": 2.6, + "vram_slots": 3978 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 126.0, + "decode_tok_s": 59.11, + "decoded": 256, + "prefill_tok_s": 1494.53, + "ttft_s": 87.51, + "spec_accept": 0.704, + "tokens_per_round": 2.71, + "vram_slots": 3897 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 48.6, + "decode_tok_s": 65.12, + "decoded": 256, + "prefill_tok_s": 471.53, + "ttft_s": 3.65, + "spec_accept": 0.876, + "tokens_per_round": 4.08, + "vram_slots": 3281 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 48.5, + "decode_tok_s": 62.33, + "decoded": 256, + "prefill_tok_s": 974.3, + "ttft_s": 5.17, + "spec_accept": 0.826, + "tokens_per_round": 3.15, + "vram_slots": 3243 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 64.9, + "decode_tok_s": 49.83, + "decoded": 256, + "prefill_tok_s": 1554.53, + "ttft_s": 21.84, + "spec_accept": 0.766, + "tokens_per_round": 2.91, + "vram_slots": 3009 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 91.7, + "decode_tok_s": 53.58, + "decoded": 256, + "prefill_tok_s": 1449.37, + "ttft_s": 45.84, + "spec_accept": 0.748, + "tokens_per_round": 2.8, + "vram_slots": 2965 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 140.9, + "decode_tok_s": 46.97, + "decoded": 256, + "prefill_tok_s": 1386.04, + "ttft_s": 94.33, + "spec_accept": 0.607, + "tokens_per_round": 2.47, + "vram_slots": 2901 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-29-speed-0126/README.md b/engine/strata/bench/results/2026-09-29-speed-0126/README.md new file mode 100644 index 00000000..e6f8fdd0 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-speed-0126/README.md @@ -0,0 +1,36 @@ +# Speed with engine 0.1.26 + +RTX 5070 12 GB (PCIe 5.0 x16), Ryzen 5 7600, 64 GB DDR5-5200, Windows 10. The ready-made 0.1.26 engine, one-shot runs +with what setup writes: `--prefill auto`, the shipped expert profile, `--expert-cache auto`, 8-bit KV above 4K, KV +streaming (`--kv-resident 32768`) from 64K, MTP (`--spec 4 --spec-min-p 0.5`), greedy, 256 generated tokens, images +off, no timing marks. The same code-agent prompts as `2026-09-29-speed-0122`. Every run: [`matrix.json`](matrix.json). + +## Prompt (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | +| --- | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 536 | 1,299 | 2,171 | 2,126 | 2,107 | +| **IQ2_XS** | 534 | 1,256 | 2,092 | 1,754 | 1,752 | +| **IQ3_XXS** | 482 | 1,007 | 1,745 | 1,609 | 1,602 | +| **IQ3_S** | 427 | 913 | 1,624 | 1,640 | 1,443 | +| **Coder** | 656 | 1,583 | 2,177 | 2,236 | 2,208 | + +## Output (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | +| --- | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 87.3 | 93.0 | 81.8 | 76.2 | 73.7 | +| **IQ2_XS** | 79.6 | 78.6 | 76.3 | 63.7 | 62.7 | +| **IQ3_XXS** | 61.9 | 61.6 | 58.5 | 57.2 | 49.0 | +| **IQ3_S** | 52.4 | 53.3 | 48.3 | 46.3 | 45.5 | +| **Coder** | 58.9 | 55.1 | 54.9 | 53.2 | 43.0 | + +- Against 0.1.22 (`2026-09-29-speed-0122`), prompts at 32K-128K are 8-28% faster: Q2_0 1,844 -> 2,171 at 32K and + 1,682 -> 2,107 at 128K, the Coder 1,779 -> 2,208 at 128K. The gains come from: + - 0.1.24's QSA selection on tensor cores; + - 0.1.25's grouping tables in mapped memory and fused norms; + - 0.1.26's batched draft-layer pass. +- 262K was not run again (0.1.22: Q2_0 1,304, IQ2_XS 1,181 tokens/s). +- Output speed is the same decode as before. One run per cell moves several percent with the text (the share of + accepted drafts, `spec_accept` in `matrix.json`). For example, the Coder's 128K answer accepted 55% of its drafts + and its 64K answer 71%. diff --git a/engine/strata/bench/results/2026-09-29-speed-0126/matrix.json b/engine/strata/bench/results/2026-09-29-speed-0126/matrix.json new file mode 100644 index 00000000..cd4bf7f9 --- /dev/null +++ b/engine/strata/bench/results/2026-09-29-speed-0126/matrix.json @@ -0,0 +1,352 @@ +[ + { + "model": "Q2_0", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 23.9, + "decode_tok_s": 87.33, + "decoded": 256, + "prefill_tok_s": 536.42, + "ttft_s": 3.4, + "spec_accept": 0.681, + "tokens_per_round": 2.72, + "vram_slots": 4174 + }, + { + "model": "Q2_0", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 27.6, + "decode_tok_s": 92.97, + "decoded": 256, + "prefill_tok_s": 1299.44, + "ttft_s": 4.21, + "spec_accept": 0.838, + "tokens_per_round": 3.23, + "vram_slots": 4121 + }, + { + "model": "Q2_0", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 40.8, + "decode_tok_s": 81.75, + "decoded": 256, + "prefill_tok_s": 2170.85, + "ttft_s": 16.02, + "spec_accept": 0.788, + "tokens_per_round": 2.99, + "vram_slots": 3832 + }, + { + "model": "Q2_0", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 57.3, + "decode_tok_s": 76.23, + "decoded": 256, + "prefill_tok_s": 2126.03, + "ttft_s": 32.06, + "spec_accept": 0.707, + "tokens_per_round": 2.8, + "vram_slots": 3778 + }, + { + "model": "Q2_0", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 87.7, + "decode_tok_s": 73.73, + "decoded": 256, + "prefill_tok_s": 2106.85, + "ttft_s": 62.48, + "spec_accept": 0.679, + "tokens_per_round": 2.71, + "vram_slots": 3695 + }, + { + "model": "IQ2_XS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 42.2, + "decode_tok_s": 79.62, + "decoded": 256, + "prefill_tok_s": 533.83, + "ttft_s": 3.51, + "spec_accept": 0.774, + "tokens_per_round": 2.89, + "vram_slots": 4359 + }, + { + "model": "IQ2_XS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 40.6, + "decode_tok_s": 78.6, + "decoded": 256, + "prefill_tok_s": 1256.02, + "ttft_s": 4.31, + "spec_accept": 0.81, + "tokens_per_round": 3.29, + "vram_slots": 4308 + }, + { + "model": "IQ2_XS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 53.6, + "decode_tok_s": 76.34, + "decoded": 256, + "prefill_tok_s": 2092.02, + "ttft_s": 16.57, + "spec_accept": 0.85, + "tokens_per_round": 3.2, + "vram_slots": 4029 + }, + { + "model": "IQ2_XS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 78.3, + "decode_tok_s": 63.69, + "decoded": 256, + "prefill_tok_s": 1753.65, + "ttft_s": 38.08, + "spec_accept": 0.636, + "tokens_per_round": 2.59, + "vram_slots": 3977 + }, + { + "model": "IQ2_XS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 115.1, + "decode_tok_s": 62.72, + "decoded": 256, + "prefill_tok_s": 1751.79, + "ttft_s": 74.85, + "spec_accept": 0.696, + "tokens_per_round": 2.6, + "vram_slots": 3896 + }, + { + "model": "IQ3_XXS", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 46.9, + "decode_tok_s": 61.94, + "decoded": 256, + "prefill_tok_s": 482.04, + "ttft_s": 3.67, + "spec_accept": 0.845, + "tokens_per_round": 3.57, + "vram_slots": 3279 + }, + { + "model": "IQ3_XXS", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 47.4, + "decode_tok_s": 61.64, + "decoded": 256, + "prefill_tok_s": 1007.48, + "ttft_s": 5.03, + "spec_accept": 0.801, + "tokens_per_round": 3.19, + "vram_slots": 3242 + }, + { + "model": "IQ3_XXS", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 65.6, + "decode_tok_s": 58.49, + "decoded": 256, + "prefill_tok_s": 1745.16, + "ttft_s": 19.63, + "spec_accept": 0.789, + "tokens_per_round": 2.85, + "vram_slots": 3007 + }, + { + "model": "IQ3_XXS", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 88.5, + "decode_tok_s": 57.21, + "decoded": 256, + "prefill_tok_s": 1609.31, + "ttft_s": 41.45, + "spec_accept": 0.74, + "tokens_per_round": 2.87, + "vram_slots": 2963 + }, + { + "model": "IQ3_XXS", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 127.0, + "decode_tok_s": 48.95, + "decoded": 256, + "prefill_tok_s": 1602.33, + "ttft_s": 81.71, + "spec_accept": 0.643, + "tokens_per_round": 2.37, + "vram_slots": 2899 + }, + { + "model": "IQ3_S", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 54.2, + "decode_tok_s": 52.4, + "decoded": 256, + "prefill_tok_s": 426.6, + "ttft_s": 4.03, + "spec_accept": 0.822, + "tokens_per_round": 3.17, + "vram_slots": 2617 + }, + { + "model": "IQ3_S", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 58.9, + "decode_tok_s": 53.3, + "decoded": 256, + "prefill_tok_s": 912.99, + "ttft_s": 5.58, + "spec_accept": 0.85, + "tokens_per_round": 3.38, + "vram_slots": 2579 + }, + { + "model": "IQ3_S", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 72.8, + "decode_tok_s": 48.31, + "decoded": 256, + "prefill_tok_s": 1624.07, + "ttft_s": 21.07, + "spec_accept": 0.827, + "tokens_per_round": 3.0, + "vram_slots": 2383 + }, + { + "model": "IQ3_S", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 93.3, + "decode_tok_s": 46.25, + "decoded": 256, + "prefill_tok_s": 1640.34, + "ttft_s": 40.77, + "spec_accept": 0.693, + "tokens_per_round": 2.56, + "vram_slots": 2346 + }, + { + "model": "IQ3_S", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 144.6, + "decode_tok_s": 45.51, + "decoded": 256, + "prefill_tok_s": 1443.21, + "ttft_s": 90.72, + "spec_accept": 0.697, + "tokens_per_round": 2.73, + "vram_slots": 2291 + }, + { + "model": "Coder", + "tier": "1k", + "prompt_tokens": 1017, + "exit": 0, + "wall_s": 37.0, + "decode_tok_s": 58.91, + "decoded": 256, + "prefill_tok_s": 656.36, + "ttft_s": 2.48, + "spec_accept": 0.743, + "tokens_per_round": 2.91, + "vram_slots": 2649 + }, + { + "model": "Coder", + "tier": "4k", + "prompt_tokens": 3562, + "exit": 0, + "wall_s": 18.3, + "decode_tok_s": 55.1, + "decoded": 256, + "prefill_tok_s": 1583.1, + "ttft_s": 3.09, + "spec_accept": 0.713, + "tokens_per_round": 2.88, + "vram_slots": 2614 + }, + { + "model": "Coder", + "tier": "32k", + "prompt_tokens": 31566, + "exit": 0, + "wall_s": 30.4, + "decode_tok_s": 54.89, + "decoded": 256, + "prefill_tok_s": 2177.17, + "ttft_s": 15.33, + "spec_accept": 0.731, + "tokens_per_round": 2.75, + "vram_slots": 2417 + }, + { + "model": "Coder", + "tier": "64k", + "prompt_tokens": 64162, + "exit": 0, + "wall_s": 44.8, + "decode_tok_s": 53.22, + "decoded": 256, + "prefill_tok_s": 2236.49, + "ttft_s": 29.51, + "spec_accept": 0.709, + "tokens_per_round": 2.68, + "vram_slots": 2382 + }, + { + "model": "Coder", + "tier": "128k", + "prompt_tokens": 128478, + "exit": 0, + "wall_s": 75.9, + "decode_tok_s": 43.04, + "decoded": 256, + "prefill_tok_s": 2208.27, + "ttft_s": 59.02, + "spec_accept": 0.553, + "tokens_per_round": 2.23, + "vram_slots": 2324 + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/BUILD.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/BUILD.json new file mode 100644 index 00000000..a65c0153 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/BUILD.json @@ -0,0 +1,14 @@ +{ + "source": "local", + "version": "0.1.29", + "archs": [ + 120 + ], + "vision": "gpu", + "cuda_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "src": "1437bc9455f7c0af", + "vision_src": "4b80385716918cce" +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/Dockerfile b/engine/strata/bench/results/2026-09-30-community-rtx-5090/Dockerfile new file mode 100644 index 00000000..24949fb2 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/Dockerfile @@ -0,0 +1,4 @@ +FROM nvidia/cuda@sha256:5dc1bca23d05bd37b011be68ec470c03b403a5da07ec3a86e41af9470e9d0cc6 +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends build-essential cmake ninja-build git ca-certificates curl python3 python3-venv python3-dev pkg-config && rm -rf /var/lib/apt/lists/* +ENV HOME=/workspace/home PYTHONUNBUFFERED=1 +WORKDIR /workspace/Strata diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/README.md b/engine/strata/bench/results/2026-09-30-community-rtx-5090/README.md new file mode 100644 index 00000000..88e664cb --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/README.md @@ -0,0 +1,167 @@ +# Community benchmark: RTX 5090, Core Ultra 9 285K + +Measured on 2026-09-30 by [hagope](https://github.com/hagope), on a Linux +machine called OMAN. This tests Strata 0.1.29 with the original Flash-Next +IQ2_XS, one GPU, and a 131,072-token context limit. + +Median decode throughput was **179.4 tok/s at 4,096 prompt tokens, 175.7 tok/s +at 32,768, and 165.0 tok/s at 128,000**. These are synthetic code-explanation +requests with greedy decoding and a 256-token output cap. They do not establish +general answer quality or performance on other workloads. + +## Hardware and software + +- NVIDIA GeForce RTX 5090; 32,607 MiB reported VRAM; 575 W power limit. + PCIe capability: Gen 5, x16. The engine's startup transfer probe reported + 50.0 GB/s host-to-device. GPU clocks were not fixed for this test. +- Intel Core Ultra 9 285K; 24 logical CPUs. The engine selected AVX2 and + 23 expert-pool workers plus its host thread. +- 64 GB installed RAM; Linux reported 62.19 GiB usable. Local NVMe storage: + WDC WDS200T2B0C-00PXH0. 8 GiB system swap. +- Ubuntu 24.04.4 LTS, kernel 6.8.0-142-generic, NVIDIA driver 595.84. +- Source commit `d6708a4aae15b4860000d54c8af9e84d684bce09`; engine 0.1.29. + Locally compiled CUDA architecture 120, including the GPU vision helper. + See [BUILD.json](BUILD.json). +- CUDA 13.0.2 container; NVCC 13.0.88; GCC 13.3.0; Python 3.12.3. + Base image: `nvidia/cuda@sha256:5dc1bca23d05bd37b011be68ec470c03b403a5da07ec3a86e41af9470e9d0cc6`. + Installed Python dependencies are listed in [python-packages.txt](python-packages.txt). +- The regular inference server, GPU TTS, and GPU embedding service were paused. + Other CPU services remained running. The GPU was dedicated to Strata and its + vision helper; this was not a completely isolated operating system. + +## Model and configuration + +Model: `ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF`, revision +`ed59f92082b1e93c0e96d60a8b11aab089b52f09`: + +- `IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf` +- `IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf` +- `mmproj-Qwen3.8-Flash-Next-BF16.gguf` + +All three local GGUF SHA-256 hashes matched the revision's published LFS hashes. +[model-provenance.json](model-provenance.json) contains filenames, byte sizes, +revisions, and verified hashes. MTP was fetched by the installer from +`Qwen/Qwen3.8-Flash-Next`; its API reported revision +`de4b8e4d43b917e7706784d8bb445c9af86a3540` at verification time. The installer +uses `main` for those tensor-range downloads. Their individual output hashes +are retained in [mtp-manifest.json](mtp-manifest.json); the full BF16 upstream +shards were not downloaded or independently hash-verified. + +The unmodified installer prepared the native IQ2_XS pack and Q2_0 MTP experts. +[artifact-hashes.json](artifact-hashes.json) identifies the executables, +default expert profile, tokenizer, pack metadata/dense weights, and draft pack. + +- Context 131,072; INT8 KV; 32,768 KV cells per attention layer resident on GPU. +- Expert cache `auto`: 17,463 slots, 23.44 GiB VRAM, profile-prefilled with + **no eviction**. The bundled expert profile was used without calibration. +- Prefill `auto` selected chunks of 8,192 tokens, borrowing 3,421 expert-cache + slots during prompt processing. +- MTP `--spec 4 --spec-min-p 0.5`; built-in suffix drafting remained enabled. +- Low-RAM mode off; GPU vision enabled, 1,024 image tokens and a 700 MiB VRAM + reserve. The vision helper warmed up; benchmark requests contained no images. +- Experimental speed projection off; no custom control vectors or calibration. +- Reasoning disabled, temperature 0, maximum 256 generated tokens per speed run. + +The complete measured configuration is [strata-iq2_xs.json](strata-iq2_xs.json). +Startup choices and every request's timing/draft statistics are in +[engine.log](engine.log). + +## Method and reproduction + +Use the attached [Dockerfile](Dockerfile), the pinned source commit, and an empty +data directory. Mount a working directory as `/workspace`, with the checkout +at `/workspace/Strata`. Run setup inside the CUDA container with GPU access, +host IPC, and unlimited memlock: + +```bash +bash ./setup.sh --family qwen --model IQ2_XS --context 131072 --kv int8 \ + --vision gpu --experimental-speed-projection off --gpu 0 --low-ram off \ + --build --yes --no-start --port 18080 --data-dir /workspace/Strata-data +``` + +Launch the prepared server on loopback inside a container using host networking: + +```bash +/workspace/Strata/.venv/bin/python serve/server.py --engine strata \ + --config strata-iq2_xs.json --host 127.0.0.1 --port 18080 +``` + +Run [benchmark.py](benchmark.py) inside that container, after placing the script +at `/workspace/benchmark.py`. It generates deterministic synthetic Python +functions, adds a different nonce near the start of each request, and counts the +complete rendered chat prompt using Strata's tokenizer. It adjusts the filler +to the target token count and verifies the count against the server afterward. +The resulting request hashes are in [results.json](results.json). + +```bash +/workspace/Strata/.venv/bin/python /workspace/benchmark.py +/workspace/Strata/.venv/bin/python tools/needle_bench.py \ + --url http://127.0.0.1:18080 --lengths 32k,128k --depths 10,50,90 \ + --out /workspace/results/needles.json +``` + +One short warm-up request was excluded. Three runs at each length were executed +serially in increasing-length order on the same loaded engine. All nine speed +requests processed their entire prompt: **zero reused tokens**. The GPU expert +cache was filled at startup and retained between requests; no engine restart or +OS page-cache reset separated them. Downloads and file verification had already +warmed the filesystem cache. Loading time is excluded. + +The script measures streaming TTFT from immediately before the HTTP request +until the first nonempty text delta, ignoring empty role chunks and keep-alives. +With reasoning off, that delta contains answer text. Total latency ends at +stream completion. Both timings include HTTP and frontend tokenization on OMAN +over loopback. Engine prompt throughput uses freshly read tokens divided by +`prompt_ms`; decode throughput uses `engine_generated / decode_ms`. The JSON +preserves the engine timing values and output text for each run. + +## Results + +Each cell below is the median **[minimum–maximum]** of three runs. Every request +generated 256 tokens and stopped at the output limit, with no failed or cancelled +speed requests. + +| Prompt tokens | Reused | Prompt tok/s | Decode tok/s | TTFT seconds | Total seconds | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 4,096 | 0 | 4,269.8 [3,510.2–4,273.3] | 179.4 [161.3–184.8] | 0.974 [0.973–1.183] | 2.392 [2.351–2.761] | +| 32,768 | 0 | 5,543.2 [5,527.1–5,549.6] | 175.7 [166.1–181.8] | 5.950 [5.942–5.968] | 7.390 [7.348–7.498] | +| 128,000 | 0 | 5,778.7 [5,767.0–5,791.9] | 165.0 [154.8–169.3] | 22.262 [22.212–22.308] | 23.850 [23.765–23.856] | + +Raw per-run records: [results.json](results.json). Calculated aggregates: +[summary.json](summary.json). The lower first 4K run is retained in the range. +Decode expert-cache hit rates were 97.8–99.7% for these nine requests. + +[monitor.py](monitor.py) sampled the host once per second, starting before model +load and ending after the recall checks. [telemetry.jsonl](telemetry.jsonl) +contains 250 samples over 255.9 seconds, with the following observed peaks: + +- GPU memory: **31,785 MiB (31.04 GiB)**, system-wide on the selected GPU. +- Host RAM: **45.54 GiB**, calculated as `MemTotal - MemAvailable`. This includes + Strata, other services, and non-reclaimable system memory; it is not process RSS. +- Swap allocation increased from **0.25 MiB to 425.50 MiB**, including increases + during the speed suite. Swap I/O rates were not measured, so this is not a + claim that inference ran without paging. No out-of-memory error occurred. + +Sampling and the server's own telemetry were active during inference. These +are sampled peaks; brief allocation spikes between samples may be missed. +Aggregates are also recorded in [memory-summary.json](memory-summary.json). + +## Recall and limitations + +The repository's unchanged `tools/needle_bench.py` found **all six needles**: +depths 10%, 50%, and 90% at both requested lengths. Actual prompt lengths were +30,804–30,805 tokens for `32k` and 126,318–126,320 for `128k`. All answers exactly +matched the expected code words. See [needles.json](needles.json). + +The final 128K recall case reused 16,384 prompt tokens; the other five reused +zero. Recall latency is therefore not used in the fresh-prompt speed table. +The script chooses needle depth by character position, not token position. + +This is one machine, one quantization, one configuration, and a small synthetic +workload. Long output, sampled decoding, thinking, coding-task correctness, +vision, tool use, multi-request concurrency, and a sustained thermal run were +not evaluated. The built-in needle check measures recall on these six inputs, +not general model accuracy. No same-workload baseline on another engine or GPU +was run; do not interpret the README's different-hardware numbers as a controlled +comparison. The 128,000-token speed prompt also does not fill every token of the +131,072-token context window. diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json new file mode 100644 index 00000000..cde7e669 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/artifact-hashes.json @@ -0,0 +1,82 @@ +[ + { + "file": "Strata-data/mtp/mtp-q2_0.gguf", + "bytes": 889017216, + "sha256": "a22206a4d74eafbf31063a84610292535fb3b49af9a339963817fd04aed81e4d" + }, + { + "file": "Strata-data/mtp/rt/dense.bin", + "bytes": 116099072, + "sha256": "c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a" + }, + { + "file": "Strata-data/mtp/rt/dense.txt", + "bytes": 1851, + "sha256": "991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd" + }, + { + "file": "Strata-data/mtp/rt/draft_vocab.bin", + "bytes": 425196, + "sha256": "b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91" + }, + { + "file": "Strata-data/mtp/rt/experts.bin", + "bytes": 707788800, + "sha256": "09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f" + }, + { + "file": "Strata-data/packs/iq2_xs/dense.bin", + "bytes": 1538035200, + "sha256": "d2af3d8331e5c7a1985d1d589747230f9d56719a6d33c7cddc9ee6b81cde6b13" + }, + { + "file": "Strata-data/packs/iq2_xs/index.txt", + "bytes": 93686, + "sha256": "19e781af360ca3b83fd90fe09e757ac9aa2a9dcada26810ddc9e933bdb112091" + }, + { + "file": "Strata-data/packs/iq2_xs/native_experts.txt", + "bytes": 3289, + "sha256": "48df605acb89c7e8c3176a51cec777c2ed344ea439e8f3a37e5ce4f9dcb6946c" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/chat_template.jinja", + "bytes": 9993, + "sha256": "12827f24b742ea4e80cdc12dbcf9622227056b9f797252a3149263d4f9aaadce" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/merges.txt", + "bytes": 3353258, + "sha256": "4ba698529766c7a2f5052083ea10cdf2485577f5237a332ee291054eb11e3332" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/token_type.json", + "bytes": 744960, + "sha256": "5088c8c298fc06af8382ddb3b76c888703ac2634e82263b97eedcc2ad202738b" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/tokenizer.json", + "bytes": 541, + "sha256": "c0bd435efbc6c3b28964b47999afe16c4ad268c7c7c4e8cb3af410796a6f30bf" + }, + { + "file": "Strata-data/packs/iq2_xs/tokenizer/vocab.json", + "bytes": 5737005, + "sha256": "4ba64f0332abcfb0b600b7df1537d1e836e68009d5fb7cdb77339738dc6365c4" + }, + { + "file": "Strata/data/expert-profile.bin", + "bytes": 196632, + "sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf" + }, + { + "file": "Strata/engine/strata", + "bytes": 43158256, + "sha256": "b7f18df1314ad438952ca11bb5ce5f23b41e7a572462426383d2ad8209fcf367" + }, + { + "file": "Strata/engine/strata-vision", + "bytes": 74993888, + "sha256": "0d4c955f255ba4c3a9f6f456d63292754fae440a8a39cb13b9b6564938448e19" + } +] diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/benchmark.py b/engine/strata/bench/results/2026-09-30-community-rtx-5090/benchmark.py new file mode 100644 index 00000000..cdb6e4cc --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/benchmark.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Serial, fresh-prompt Strata benchmark. Run inside its prepared environment.""" +import argparse +import hashlib +import json +import statistics +import sys +import time +import urllib.request +from pathlib import Path + + +def get(url): + with urllib.request.urlopen(url, timeout=30) as response: + return json.load(response) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path("/workspace/Strata")) + parser.add_argument("--pack", type=Path, default=Path("/workspace/Strata-data/packs/iq2_xs")) + parser.add_argument("--url", default="http://127.0.0.1:18080") + parser.add_argument("--out", type=Path, default=Path("/workspace/results")) + parser.add_argument("--targets", default="4096,32768,128000") + parser.add_argument("--runs", type=int, default=3) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + sys.path[:0] = [str(args.root), str(args.root / "tools")] + from strata_tokenizer import Tokenizer + from serve.frontend import ChatTemplate, openai_to_messages + directory = args.pack / "tokenizer" + vocab = json.loads((directory / "vocab.json").read_text()) + tokens = [None] * len(vocab) + for token, number in vocab.items(): + tokens[number] = token + tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(), + json.loads((directory / "token_type.json").read_text())) + template = ChatTemplate(directory / "chat_template.jinja") + initial = get(args.url + "/v1/status") + (args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n") + rows = [] + + def request(content, maximum=256): + return {"model": "strata", "messages": [{"role": "user", "content": content}], + "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum, + "stream": True, "stream_options": {"include_usage": True}} + + def count(req): + messages, tools, kwargs = openai_to_messages(req) + return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True)) + + def perform(label, req, expected=None): + body = json.dumps(req).encode() + (args.out / (label + "-request.json")).write_bytes(body + b"\n") + print("start", label, "tokens", expected, flush=True) + chunks, texts, first, finish = [], [], None, None + started = time.perf_counter() + wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(wire, timeout=1800) as response: + for line in response: + if not line.startswith(b"data: "): + continue + payload = line[6:].strip() + if payload == b"[DONE]": + break + chunk = json.loads(payload) + chunks.append(chunk) + for choice in chunk.get("choices", []): + delta = choice.get("delta", {}) + text = (delta.get("content") or "") + (delta.get("reasoning_content") or "") + if text: + first = first if first is not None else time.perf_counter() - started + texts.append(text) + finish = choice.get("finish_reason") or finish + elapsed = time.perf_counter() - started + metrics = get(args.url + "/metrics") + engine = metrics["requests"][0] + usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {}) + row = {"label": label, "expected_prompt_tokens": expected, + "request_sha256": hashlib.sha256(body).hexdigest(), + "client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish, + "usage": usage, "engine": engine, "text": "".join(texts)} + if expected is not None and engine["prompt_tokens"] != expected: + raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}") + if not texts: + raise RuntimeError(f"no text received for {label}") + (args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n") + rows.append(row) + (args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n") + print("done", label, json.dumps({"ttft_s": first, "elapsed_s": elapsed, "engine": engine}), flush=True) + return row + + perform("warmup", request("Reply with exactly the word READY.", 16)) + # Each nonce occurs before the filler so previous long prompts cannot be reused. + filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003" + for i in range(12000)) + ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, " + "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.") + for target in map(int, args.targets.split(",")): + for run in range(1, args.runs + 1): + prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n" + lo, hi = 0, len(filler) + while lo < hi: + middle = (lo + hi + 1) // 2 + if count(request(prefix + filler[:middle] + ending)) <= target: + lo = middle + else: + hi = middle - 1 + req = request(prefix + filler[:lo] + ending) + actual = count(req) + if actual < target - 20 or actual > target: + raise RuntimeError(f"could not construct target {target}: {actual}") + perform(f"tokens-{target}-run-{run}", req, actual) + measured = [row for row in rows if row["label"] != "warmup"] + groups = {} + for target in map(int, args.targets.split(",")): + subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")] + values = { + "prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset], + "cached_tokens": [r["engine"].get("reused", 0) for r in subset], + "output_tokens": [r["engine"]["engine_generated"] for r in subset], + "client_ttft_s": [r["client_ttft_s"] for r in subset], + "client_elapsed_s": [r["client_elapsed_s"] for r in subset], + "prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset], + "decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset], + } + groups[str(target)] = {key: {"median": statistics.median(v), "min": min(v), "max": max(v)} + for key, v in values.items()} + (args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n") + print("summary", json.dumps(groups), flush=True) + + +if __name__ == "__main__": + main() diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/final-status.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/final-status.json new file mode 100644 index 00000000..de26a051 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/final-status.json @@ -0,0 +1 @@ +{"service": "strata", "model": "qwen3.8-flash-next-iq2_xs", "engine": "0.1.29", "started": 1790772696, "uptime_s": 196, "cache_max_tokens": 131072, "context": {"native": 131072, "max_positions": 131072}, "concurrency": {"serving": 1, "requested": 1}, "dialects": ["/v1/chat/completions", "/v1/messages"], "vision": {"enabled": true, "available": true, "error": null}, "activity": {"requests": 16, "in_flight": 0, "last_request_at": 1790772892}, "last_timings": {"cache_n": 16384, "prompt_n": 109934, "prompt_ms": 19791.2, "prompt_per_token_ms": 0.18, "prompt_per_second": 5554.7, "predicted_n": 9, "predicted_ms": 78.1, "predicted_per_token_ms": 8.678, "predicted_per_second": 115.2, "draft_n": 9, "draft_n_accepted": 7, "at": 1790772892}, "machine": {"at": 1790772892, "gpu": {"name": "NVIDIA GeForce RTX 5090", "used_mib": 32281.0, "total_mib": 32607.0, "util_pct": 100, "temp_c": 72, "power_w": 528.823}, "ram": {"used_gib": 45.4, "total_gib": 62.2}}} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/initial-status.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/initial-status.json new file mode 100644 index 00000000..93fe6185 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/initial-status.json @@ -0,0 +1,46 @@ +{ + "service": "strata", + "model": "qwen3.8-flash-next-iq2_xs", + "engine": "0.1.29", + "started": 1790772696, + "uptime_s": 2, + "cache_max_tokens": 131072, + "context": { + "native": 131072, + "max_positions": 131072 + }, + "concurrency": { + "serving": 1, + "requested": 1 + }, + "dialects": [ + "/v1/chat/completions", + "/v1/messages" + ], + "vision": { + "enabled": true, + "available": true, + "error": null + }, + "activity": { + "requests": 0, + "in_flight": 0, + "last_request_at": null + }, + "last_timings": null, + "machine": { + "at": 1790772698, + "gpu": { + "name": "NVIDIA GeForce RTX 5090", + "used_mib": 32195.0, + "total_mib": 32607.0, + "util_pct": 0, + "temp_c": 36, + "power_w": 83.403 + }, + "ram": { + "used_gib": 44.4, + "total_gib": 62.2 + } + } +} diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/memory-summary.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/memory-summary.json new file mode 100644 index 00000000..b750522b --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/memory-summary.json @@ -0,0 +1,10 @@ +{ + "samples": 250, + "sample_duration_s": 255.8539924621582, + "sampling_method": "nominal 1 s; /proc/meminfo and nvidia-smi; startup through recall checks", + "ram_peak_GiB": 45.54487228393555, + "gpu_peak_MiB": 31785.0, + "swap_start_MiB": 0.25, + "swap_peak_MiB": 425.5, + "swap_end_MiB": 425.5 +} diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/model-provenance.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/model-provenance.json new file mode 100644 index 00000000..c22afda6 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/model-provenance.json @@ -0,0 +1,46 @@ +[ + { + "repository": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", + "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", + "gguf_files": [ + { + "filename": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "lfs": { + "sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7", + "size": 39225954592, + "pointerSize": 136 + }, + "size": 39225954592, + "actual_sha256": "92cee27ae5bbadcd732416a0f7a7f0acc092399dbbe8f5a5efa707c2ec0a49d7", + "verified": true + }, + { + "filename": "IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "lfs": { + "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", + "size": 28800138432, + "pointerSize": 136 + }, + "size": 28800138432, + "actual_sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", + "verified": true + }, + { + "filename": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", + "lfs": { + "sha256": "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0", + "size": 907543008, + "pointerSize": 134 + }, + "size": 907543008, + "actual_sha256": "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0", + "verified": true + } + ] + }, + { + "repository": "Qwen/Qwen3.8-Flash-Next", + "revision": "de4b8e4d43b917e7706784d8bb445c9af86a3540", + "gguf_files": [] + } +] diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/monitor.py b/engine/strata/bench/results/2026-09-30-community-rtx-5090/monitor.py new file mode 100644 index 00000000..6f9f8082 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/monitor.py @@ -0,0 +1,18 @@ +"""Sample system RAM, swap and GPU memory once per second during the trial.""" +import json +import subprocess +import sys +import time +from pathlib import Path + +with Path(sys.argv[1] if len(sys.argv) > 1 else 'telemetry.jsonl').open('a') as output: + while True: + memory = {} + for line in Path('/proc/meminfo').read_text().splitlines(): + key, value = line.split(':', 1) + if key in ('MemTotal', 'MemAvailable', 'SwapTotal', 'SwapFree'): + memory[key + '_KiB'] = int(value.strip().split()[0]) + gpu = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used,memory.total,utilization.gpu,power.draw,temperature.gpu', '--format=csv,noheader,nounits'], text=True).strip() + output.write(json.dumps({'epoch_s': time.time(), 'memory': memory, 'gpu': gpu}) + '\n') + output.flush() + time.sleep(1) diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json new file mode 100644 index 00000000..fca1a9db --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/mtp-manifest.json @@ -0,0 +1,429 @@ +[ + { + "name": "mtp.fc_embedding.weight", + "shard": "model-00120-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 2560 + ], + "start": 1935412640, + "end": 1948519839, + "bytes": 13107200, + "file": "tensors/mtp.fc_embedding.weight.bin", + "sha256": "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751" + }, + { + "name": "mtp.fc_hidden.weight", + "shard": "model-00124-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 2560 + ], + "start": 1716599928, + "end": 1729707127, + "bytes": 13107200, + "file": "tensors/mtp.fc_hidden.weight.bin", + "sha256": "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96" + }, + { + "name": "mtp.hyper_connection_mixer.hc_norm.weight", + "shard": "model-00037-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1742326680, + "end": 1742347159, + "bytes": 20480, + "file": "tensors/mtp.hyper_connection_mixer.hc_norm.weight.bin", + "sha256": "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64" + }, + { + "name": "mtp.hyper_connection_mixer.input_mix_weight_down.weight", + "shard": "model-00041-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1935412688, + "end": 1941966287, + "bytes": 6553600, + "file": "tensors/mtp.hyper_connection_mixer.input_mix_weight_down.weight.bin", + "sha256": "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947" + }, + { + "name": "mtp.hyper_connection_mixer.input_mix_weight_up.weight", + "shard": "model-00043-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1832518416, + "end": 1839072015, + "bytes": 6553600, + "file": "tensors/mtp.hyper_connection_mixer.input_mix_weight_up.weight.bin", + "sha256": "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight", + "shard": "model-00047-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 4, + 10240 + ], + "start": 1716599984, + "end": 1716681903, + "bytes": 81920, + "file": "tensors/mtp.layers.0.attn_hyper_connection.block_inject_weight.weight.bin", + "sha256": "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.hc_norm.weight", + "shard": "model-00049-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1935412672, + "end": 1935433151, + "bytes": 20480, + "file": "tensors/mtp.layers.0.attn_hyper_connection.hc_norm.weight.bin", + "sha256": "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight", + "shard": "model-00053-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1832518424, + "end": 1839072023, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight.bin", + "sha256": "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5" + }, + { + "name": "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight", + "shard": "model-00057-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1935412680, + "end": 1941966279, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight.bin", + "sha256": "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5" + }, + { + "name": "mtp.layers.0.mlp.experts.down_proj", + "shard": "model-00062-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560, + 640 + ], + "start": 1832518400, + "end": 3510239999, + "bytes": 1677721600, + "file": "tensors/mtp.layers.0.mlp.experts.down_proj.bin", + "sha256": "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0" + }, + { + "name": "mtp.layers.0.mlp.experts.gate_up_proj", + "shard": "model-00060-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 1280, + 2560 + ], + "start": 115918328, + "end": 3471361527, + "bytes": 3355443200, + "file": "tensors/mtp.layers.0.mlp.experts.gate_up_proj.bin", + "sha256": "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5" + }, + { + "name": "mtp.layers.0.mlp.gate.weight", + "shard": "model-00066-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1716599952, + "end": 1719221391, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.mlp.gate.weight.bin", + "sha256": "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.down_proj.weight", + "shard": "model-00076-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 640 + ], + "start": 1935412680, + "end": 1938689479, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.down_proj.weight.bin", + "sha256": "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.gate_proj.weight", + "shard": "model-00072-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1832518528, + "end": 1835795327, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.gate_proj.weight.bin", + "sha256": "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c" + }, + { + "name": "mtp.layers.0.mlp.shared_expert.up_proj.weight", + "shard": "model-00072-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1835795328, + "end": 1839072127, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.mlp.shared_expert.up_proj.weight.bin", + "sha256": "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156" + }, + { + "name": "mtp.layers.0.mlp.shared_expert_gate.weight", + "shard": "model-00070-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 1, + 2560 + ], + "start": 1832518400, + "end": 1832523519, + "bytes": 5120, + "file": "tensors/mtp.layers.0.mlp.shared_expert_gate.weight.bin", + "sha256": "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight", + "shard": "model-00078-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 4, + 10240 + ], + "start": 1832518424, + "end": 1832600343, + "bytes": 81920, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight.bin", + "sha256": "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.hc_norm.weight", + "shard": "model-00082-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1935412656, + "end": 1935433135, + "bytes": 20480, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.hc_norm.weight.bin", + "sha256": "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight", + "shard": "model-00086-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 320, + 10240 + ], + "start": 1935412696, + "end": 1941966295, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight.bin", + "sha256": "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1" + }, + { + "name": "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight", + "shard": "model-00088-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240, + 320 + ], + "start": 1832518424, + "end": 1839072023, + "bytes": 6553600, + "file": "tensors/mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight.bin", + "sha256": "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94" + }, + { + "name": "mtp.layers.0.self_attn.indexer.index_qk_proj.weight", + "shard": "model-00090-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 640, + 2560 + ], + "start": 1832518416, + "end": 1835795215, + "bytes": 3276800, + "file": "tensors/mtp.layers.0.self_attn.indexer.index_qk_proj.weight.bin", + "sha256": "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859" + }, + { + "name": "mtp.layers.0.self_attn.indexer.k_layernorm.weight", + "shard": "model-00094-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 128 + ], + "start": 1935412672, + "end": 1935412927, + "bytes": 256, + "file": "tensors/mtp.layers.0.self_attn.indexer.k_layernorm.weight.bin", + "sha256": "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54" + }, + { + "name": "mtp.layers.0.self_attn.indexer.q_layernorm.weight", + "shard": "model-00100-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 128 + ], + "start": 1716599968, + "end": 1716600223, + "bytes": 256, + "file": "tensors/mtp.layers.0.self_attn.indexer.q_layernorm.weight.bin", + "sha256": "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6" + }, + { + "name": "mtp.layers.0.self_attn.k_norm.weight", + "shard": "model-00102-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 256 + ], + "start": 1935412648, + "end": 1935413159, + "bytes": 512, + "file": "tensors/mtp.layers.0.self_attn.k_norm.weight.bin", + "sha256": "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd" + }, + { + "name": "mtp.layers.0.self_attn.k_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1832518624, + "end": 1835140063, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.self_attn.k_proj.weight.bin", + "sha256": "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38" + }, + { + "name": "mtp.layers.0.self_attn.o_proj.weight", + "shard": "model-00106-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560, + 6144 + ], + "start": 1832518400, + "end": 1863975679, + "bytes": 31457280, + "file": "tensors/mtp.layers.0.self_attn.o_proj.weight.bin", + "sha256": "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219" + }, + { + "name": "mtp.layers.0.self_attn.q_norm.weight", + "shard": "model-00112-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 256 + ], + "start": 1935412664, + "end": 1935413175, + "bytes": 512, + "file": "tensors/mtp.layers.0.self_attn.q_norm.weight.bin", + "sha256": "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef" + }, + { + "name": "mtp.layers.0.self_attn.q_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 12288, + 2560 + ], + "start": 1835140064, + "end": 1898054623, + "bytes": 62914560, + "file": "tensors/mtp.layers.0.self_attn.q_proj.weight.bin", + "sha256": "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d" + }, + { + "name": "mtp.layers.0.self_attn.v_proj.weight", + "shard": "model-00108-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 512, + 2560 + ], + "start": 1898054624, + "end": 1900676063, + "bytes": 2621440, + "file": "tensors/mtp.layers.0.self_attn.v_proj.weight.bin", + "sha256": "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41" + }, + { + "name": "mtp.pre_fc_norm_embedding.weight", + "shard": "model-00114-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 2560 + ], + "start": 1832518392, + "end": 1832523511, + "bytes": 5120, + "file": "tensors/mtp.pre_fc_norm_embedding.weight.bin", + "sha256": "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86" + }, + { + "name": "mtp.pre_fc_norm_hidden.weight", + "shard": "model-00118-of-00131.safetensors", + "dtype": "BF16", + "shape": [ + 10240 + ], + "start": 1716599944, + "end": 1716620423, + "bytes": 20480, + "file": "tensors/mtp.pre_fc_norm_hidden.weight.bin", + "sha256": "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/needles.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/needles.json new file mode 100644 index 00000000..01a7c073 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/needles.json @@ -0,0 +1,56 @@ +[ + { + "length": "32k", + "depth": 10, + "prompt_tokens": 30804, + "seconds": 6.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 30804, + "seconds": 5.8, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "32k", + "depth": 90, + "prompt_tokens": 30805, + "seconds": 5.8, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + }, + { + "length": "128k", + "depth": 10, + "prompt_tokens": 126320, + "seconds": 22.5, + "found": true, + "word": "falcon-saffron-138", + "answer": "falcon-saffron-138" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 126318, + "seconds": 22.8, + "found": true, + "word": "quartz-tundra-528", + "answer": "quartz-tundra-528" + }, + { + "length": "128k", + "depth": 90, + "prompt_tokens": 126318, + "seconds": 20.1, + "found": true, + "word": "quartz-glacier-192", + "answer": "quartz-glacier-192" + } +] \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/python-packages.txt b/engine/strata/bench/results/2026-09-30-community-rtx-5090/python-packages.txt new file mode 100644 index 00000000..9e4e371e --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/python-packages.txt @@ -0,0 +1,15 @@ +certifi==2026.7.22 +charset-normalizer==3.5.2 +cmake==4.4.3 +idna==3.20 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +ninja==1.13.2 +numpy==2.5.3 +pillow==12.3.0 +psutil==7.2.2 +PyYAML==6.0.3 +regex==2026.9.29 +requests==2.34.2 +tqdm==4.70.1 +urllib3==2.8.0 diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/results.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/results.json new file mode 100644 index 00000000..1a0b67b5 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/results.json @@ -0,0 +1,312 @@ +[ + { + "label": "warmup", + "expected_prompt_tokens": null, + "request_sha256": "b63e57873441a996a529b246a66cf12de70a7c671777f99329354d5c195f788f", + "client_ttft_s": 0.15764825499991275, + "client_elapsed_s": 0.19575888999997915, + "finish_reason": "stop", + "usage": { + "prompt_tokens": 19, + "completion_tokens": 2, + "total_tokens": 21, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772698.967025, + "duration_s": 0.2, + "finish": "stop", + "prompt_tokens": 19, + "reused": 0, + "output_tokens": 2, + "engine_generated": 2, + "prompt_ms": 134.9, + "decode_ms": 57.4, + "decode_tok_s": 34.8, + "hit_rate": 0.908 + }, + "text": "READY" + }, + { + "label": "tokens-4096-run-1", + "expected_prompt_tokens": 4096, + "request_sha256": "5d94c652067354bbe72930d2bdad3886564f08cf2546b32411af02d33ad3ce05", + "client_ttft_s": 1.1827884900003482, + "client_elapsed_s": 2.7608979090000503, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772699.5014164, + "duration_s": 2.8, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 1166.9, + "decode_ms": 1587.0, + "decode_tok_s": 161.3, + "hit_rate": 0.978 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion covering the mathematical basis, testing implications, naming conventions, complexity, and maintainability.\n\n## 1. Mathematical Basis: Deterministic Transforms and Modulo Arithmetic\n\nAt its core, every function in this module performs a linear transformation on an input integer `value`. The general pattern for `task_NNNNN` is:\n\n$$ f(x) = (x \\cdot a + b) \\pmod{M} $$\n\nWhere:\n- $M = 100003$ is a fixed modulus.\n- $a$ is the multiplier.\n- $b$ is the additive constant.\n\nFor most functions (e.g., `task_00000` to `task_00096`), the multiplier $a$ and the additive constant $b$ follow a" + }, + { + "label": "tokens-4096-run-2", + "expected_prompt_tokens": 4096, + "request_sha256": "8da8a04e70e4d916f6630729082bdfb9d6ebbb47117aad60bc0541bce198a213", + "client_ttft_s": 0.9743533680002656, + "client_elapsed_s": 2.3506501550000394, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772702.5992615, + "duration_s": 2.3, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 959.3, + "decode_ms": 1385.0, + "decode_tok_s": 184.8, + "hit_rate": 0.993 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion of the code's structure, mathematical properties, testing implications, and maintainability.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nAt its core, every function in this module implements a linear congruential generator (LCG) step or a simple affine transformation modulo a prime number. The general form of each function is:\n\n$$ f_n(x) = (x \\cdot a_n + b_n) \\pmod{M} $$\n\nWhere:\n- $M = 100003$ is a fixed modulus.\n- $a_n$ is the multiplier for function $n$.\n- $b_n$ is the additive constant for function $n$.\n\nFor the first 97 functions (`task_00000` to `task_00096`" + }, + { + "label": "tokens-4096-run-3", + "expected_prompt_tokens": 4096, + "request_sha256": "946079edb58e764050805886156dc8f877cc29e1ca8d01c84e9a1e7917d49492", + "client_ttft_s": 0.9733456560002196, + "client_elapsed_s": 2.391696067000339, + "finish_reason": "length", + "usage": { + "prompt_tokens": 4096, + "completion_tokens": 256, + "total_tokens": 4352, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772705.2866879, + "duration_s": 2.4, + "finish": "length", + "prompt_tokens": 4096, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 958.5, + "decode_ms": 1427.2, + "decode_tok_s": 179.4, + "hit_rate": 0.989 + }, + "text": "# Analysis of Synthetic Python Module: Deterministic Integer Transforms\n\nThe provided Python module consists of a series of functions, `task_00000` through `task_00112`, each implementing a specific deterministic integer transformation. While the code appears repetitive, it serves as a clear example of modular arithmetic, function design, and the trade-offs between explicit implementation and algorithmic abstraction. Below is a detailed discussion of the code\u2019s structure, mathematical properties, testing implications, naming conventions, complexity, and maintainability.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nEach function follows the general form:\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * multiplier + addend) % MOD\n```\nwhere `MOD = 100003`.\n\nFor most functions, the multiplier and addend are derived from the function index `i`:\n- `multiplier = i + 1`\n- `addend = i`\n\nThus, for `task_00000`, `multiplier = 1`, `addend = 0`.\nFor `task_00001`, `multiplier = 2`, `" + }, + { + "label": "tokens-32768-run-1", + "expected_prompt_tokens": 32768, + "request_sha256": "e37cfc2ab9867d91130927440df24a57255a736b8d0d829d07d828e22e3de572", + "client_ttft_s": 5.9679448089996185, + "client_elapsed_s": 7.498308491999978, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772708.3260226, + "duration_s": 7.5, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5928.6, + "decode_ms": 1541.2, + "decode_tok_s": 166.1, + "hit_rate": 0.994 + }, + "text": "Based on the provided Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code defines a series of functions, `task_00000` through `task_00888`, that perform deterministic integer transformations. Each function takes an integer `value` and returns a new integer based on a specific linear formula involving multiplication, addition, and modulo arithmetic. The benchmark nonce `series-32768-trial-1` suggests this code is part of a larger test suite or performance benchmark, likely designed to evaluate computational consistency, hash generation, or state machine transitions.\n\n### Mathematical Logic and Deterministic Transforms\n\nAt its core, every function in this module implements a linear congruential generator (LCG) style transformation, albeit with varying parameters. The general structure of each function is:\n\n$$ f(x) = (x \\cdot a + b) \\pmod{100003} $$\n\nWhere:\n* $x$ is the input `value`.\n* $a$ is the multiplier (coefficient).\n* $b$ is the additive constant.\n* $100003$ is the modulus." + }, + { + "label": "tokens-32768-run-2", + "expected_prompt_tokens": 32768, + "request_sha256": "ed2dfaa11aecad9f4563f33bb5f5d4b8704486508700b8fa572722cc1225ee26", + "client_ttft_s": 5.950024114999906, + "client_elapsed_s": 7.348446455000158, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772716.4558623, + "duration_s": 7.3, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5911.4, + "decode_ms": 1408.3, + "decode_tok_s": 181.8, + "hit_rate": 0.994 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### 1. Structural Analysis and Pattern Recognition\n\nThe module consists of a series of functions named `task_00000` through `task_00888` (the list appears truncated at `task_00888`, but the pattern implies a larger set). Each function follows a strict, deterministic signature: `def task_XXXXX(value: int) -> int`.\n\nThe core logic within each function is a linear transformation followed by a modulo operation:\n$$ f(x) = (x \\cdot a + b) \\pmod{100003} $$\n\nWhere:\n* $x$ is the input `value`.\n* $a$ is the multiplier.\n* $b$ is the additive constant.\n* $100003$ is the modulus.\n\n#### The Multiplier Pattern ($a$)\nThe multiplier $a$ follows a cyclic pattern. It starts at 1 and increments by 1 for each function until it reaches 97. After `task_00096` (where $a=97$), the" + }, + { + "label": "tokens-32768-run-3", + "expected_prompt_tokens": 32768, + "request_sha256": "2a3c7342622e80c3cd8b37e062f0a2f64640c119ece8cccbf168639041eac079", + "client_ttft_s": 5.941602006999801, + "client_elapsed_s": 7.389697677000186, + "finish_reason": "length", + "usage": { + "prompt_tokens": 32768, + "completion_tokens": 256, + "total_tokens": 33024, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772724.435358, + "duration_s": 7.4, + "finish": "length", + "prompt_tokens": 32768, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 5904.6, + "decode_ms": 1457.1, + "decode_tok_s": 175.7, + "hit_rate": 0.995 + }, + "text": "Based on the provided Python module, here is a detailed technical review and explanation.\n\n### 1. Structural Overview and Pattern Analysis\n\nThe provided code consists of a series of function definitions, ranging from `task_00000` to `task_00888`. Each function follows a strict, repetitive structure:\n\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * A + B) % 100003\n```\n\nThis module is a synthetic representation of a **linear congruential generator (LCG)** or a set of **affine transformations** applied to an integer input. The core logic is consistent across all functions, with only the coefficients `A` (multiplier) and `B` (addend) changing.\n\n### 2. Deterministic Integer Transforms and Modulo Arithmetic\n\nThe mathematical core of this module is the expression `(value * A + B) % 100003`. This is a classic example of a **deterministic integer transform**.\n\n* **Determinism:** For any given input `value`, the output is always the same. There is no randomness, state, or side effects. This makes" + }, + { + "label": "tokens-128000-run-1", + "expected_prompt_tokens": 128000, + "request_sha256": "3235aac3f934cf1d889c25973ca172b355509dc2522fdfb463fbefe979a9075d", + "client_ttft_s": 22.212050286999784, + "client_elapsed_s": 23.856042405000153, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772733.6124191, + "duration_s": 23.8, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22099.7, + "decode_ms": 1653.5, + "decode_tok_s": 154.8, + "hit_rate": 0.994 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code consists of a massive collection of function definitions, ranging from `task_00000` to `task_03404` (and potentially beyond, as the input cuts off). Each function follows a strict, repetitive pattern. The core logic of every function is identical in structure, differing only in the specific integer constants used for multiplication and addition.\n\nThe general form of any function `task_N` is:\n```python\ndef task_N(value: int) -> int:\n return (value * multiplier + addend) % 100003\n```\n\n### 1. Deterministic Integer Transforms and Modulo Arithmetic\n\nThe primary mechanism in this module is a **deterministic linear transform** followed by a **modulo operation**.\n\n**The Linear Transform:**\nFor any given `value`, the function computes `value * multiplier + addend`. This is an affine transformation. In mathematics, an affine transformation is a function that preserves points, straight lines, and planes. Here, it maps an input integer to an output integer based on a fixed slope (`multiplier`) and" + }, + { + "label": "tokens-128000-run-2", + "expected_prompt_tokens": 128000, + "request_sha256": "5f4b8bc9f0afc7765320abd89960c0938e0d7cf5974e962fdbd0613fef31c8d4", + "client_ttft_s": 22.262365384000077, + "client_elapsed_s": 23.764614322999932, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772759.195895, + "duration_s": 23.7, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22150.5, + "decode_ms": 1511.7, + "decode_tok_s": 169.3, + "hit_rate": 0.997 + }, + "text": "# Analysis of the Synthetic Python Module\n\nThe provided Python module consists of a massive collection of functions, ranging from `task_00000` to `task_03404` (and potentially beyond, as the code is truncated). Each function follows a strict, repetitive pattern: it accepts an integer `value`, applies a linear transformation, and returns the result modulo a fixed prime number, `100003`.\n\n## 1. Mathematical Structure and Deterministic Transforms\n\nAt its core, every function in this module implements a **linear congruential generator (LCG)** step or a simple affine transformation. The general formula for any function `task_N` is:\n\n$$ f_N(x) = (x \\cdot a_N + b_N) \\pmod{M} $$\n\nWhere:\n* $M = 100003$ is the modulus.\n* $a_N$ is the multiplier for task $N$.\n* $b_N$ is the additive constant for task $N$.\n\n### The Modulus: 100003\nThe choice of `100003` is significant. It is a **prime number**. In" + }, + { + "label": "tokens-128000-run-3", + "expected_prompt_tokens": 128000, + "request_sha256": "5c3fb71db9f9f44765f28389d1032f2c8b6687d1bf5ca6f33aeb924072cfa6e4", + "client_ttft_s": 22.308453708999878, + "client_elapsed_s": 23.850161715000013, + "finish_reason": "length", + "usage": { + "prompt_tokens": 128000, + "completion_tokens": 256, + "total_tokens": 128256, + "prompt_tokens_details": { + "cached_tokens": 0 + } + }, + "engine": { + "projection": null, + "time": 1790772784.6969988, + "duration_s": 23.8, + "finish": "length", + "prompt_tokens": 128000, + "reused": 0, + "output_tokens": 256, + "engine_generated": 256, + "prompt_ms": 22195.2, + "decode_ms": 1551.4, + "decode_tok_s": 165.0, + "hit_rate": 0.997 + }, + "text": "Based on the provided synthetic Python module, here is a detailed technical review and explanation.\n\n### Overview of the Module\n\nThe provided code consists of a massive collection of function definitions, ranging from `task_00000` to `task_03404`. Each function accepts a single integer argument `value` and returns an integer. The core logic within every function is identical in structure, differing only in the specific coefficients used for multiplication and addition.\n\nThe general pattern for any function `task_N` is:\n```python\ndef task_N(value: int) -> int:\n return (value * multiplier + addend) % 100003\n```\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe functions implement a **deterministic linear transform** over the integers. In mathematics, this is an affine transformation defined by $f(x) = ax + b$. However, the code applies this transformation within a finite field defined by the modulus $M = 100003$.\n\n1. **Modulo Arithmetic**: The use of `% 100003` ensures that the output is always within the range $[0, 100002" + } +] diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json new file mode 100644 index 00000000..6066e2be --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/strata-iq2_xs.json @@ -0,0 +1,50 @@ +{ + "exe": "/workspace/Strata/engine/strata", + "args": [ + "--pack", + "/workspace/Strata-data/packs/iq2_xs", + "--native", + "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "--ple-gguf", + "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf", + "--expert-profile", + "/workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/workspace/Strata-data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768", + "--vision", + "--vram-reserve-mib", + "700" + ], + "cwd": "/workspace/Strata", + "tokenizer": "/workspace/Strata-data/packs/iq2_xs/tokenizer", + "model_name": "qwen3.8-flash-next-iq2_xs", + "log": "/workspace/Strata/strata-iq2_xs.log", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 18080, + "gpu": 0, + "gpus_asked": true, + "vision": { + "exe": "/workspace/Strata/engine/strata-vision", + "mmproj": "/workspace/Strata-data/models/mmproj-Qwen3.8-Flash-Next-BF16.gguf", + "model": "/workspace/Strata-data/models/IQ2_XS/Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf", + "gpu": true, + "max_tokens": 1024 + } +} \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/summary.json b/engine/strata/bench/results/2026-09-30-community-rtx-5090/summary.json new file mode 100644 index 00000000..05bc1e74 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/summary.json @@ -0,0 +1,113 @@ +{ + "4096": { + "prompt_tokens": { + "median": 4096, + "min": 4096, + "max": 4096 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 0.9743533680002656, + "min": 0.9733456560002196, + "max": 1.1827884900003482 + }, + "client_elapsed_s": { + "median": 2.391696067000339, + "min": 2.3506501550000394, + "max": 2.7608979090000503 + }, + "prefill_tok_s": { + "median": 4269.780047951632, + "min": 3510.1551118347757, + "max": 4273.343766301513 + }, + "decode_tok_s": { + "median": 179.37219730941703, + "min": 161.31064902331443, + "max": 184.8375451263538 + } + }, + "32768": { + "prompt_tokens": { + "median": 32768, + "min": 32768, + "max": 32768 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 5.950024114999906, + "min": 5.941602006999801, + "max": 5.9679448089996185 + }, + "client_elapsed_s": { + "median": 7.389697677000186, + "min": 7.348446455000158, + "max": 7.498308491999978 + }, + "prefill_tok_s": { + "median": 5543.187738945089, + "min": 5527.105893465573, + "max": 5549.571520509433 + }, + "decode_tok_s": { + "median": 175.69144190515408, + "min": 166.10433428497274, + "max": 181.77945040119295 + } + }, + "128000": { + "prompt_tokens": { + "median": 128000, + "min": 128000, + "max": 128000 + }, + "cached_tokens": { + "median": 0, + "min": 0, + "max": 0 + }, + "output_tokens": { + "median": 256, + "min": 256, + "max": 256 + }, + "client_ttft_s": { + "median": 22.262365384000077, + "min": 22.212050286999784, + "max": 22.308453708999878 + }, + "client_elapsed_s": { + "median": 23.850161715000013, + "min": 23.764614322999932, + "max": 23.856042405000153 + }, + "prefill_tok_s": { + "median": 5778.6505947947, + "min": 5767.012687427912, + "max": 5791.933827156025 + }, + "decode_tok_s": { + "median": 165.01224700270723, + "min": 154.82310250982763, + "max": 169.34576966329297 + } + } +} diff --git a/engine/strata/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl b/engine/strata/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl new file mode 100644 index 00000000..21baed0e --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-community-rtx-5090/telemetry.jsonl @@ -0,0 +1,250 @@ +{"epoch_s": 1790772668.438457, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 58332840, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "2, 32607, 1, 60.13, 36"} +{"epoch_s": 1790772669.461572, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 57749256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "1374, 32607, 25, 53.81, 36"} +{"epoch_s": 1790772670.483304, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56952232, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "3719, 32607, 2, 130.61, 36"} +{"epoch_s": 1790772671.5050805, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56947812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "3719, 32607, 3, 86.30, 36"} +{"epoch_s": 1790772672.5268102, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 56930224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "4949, 32607, 3, 62.43, 36"} +{"epoch_s": 1790772673.5491986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 54141020, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 2, 59.82, 36"} +{"epoch_s": 1790772674.584606, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 46827008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 58.26, 36"} +{"epoch_s": 1790772675.6100278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 39487436, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.70, 36"} +{"epoch_s": 1790772676.6331685, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 32761416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.36, 36"} +{"epoch_s": 1790772677.6556065, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 24833136, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6875, 32607, 0, 57.03, 36"} +{"epoch_s": 1790772679.1176229, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20348260, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6893, 32607, 0, 57.33, 36"} +{"epoch_s": 1790772680.1513186, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19836220, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 58.46, 36"} +{"epoch_s": 1790772681.18351, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19863628, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.35, 36"} +{"epoch_s": 1790772682.2173855, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19918256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 56.50, 36"} +{"epoch_s": 1790772683.2403264, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19836728, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.14, 36"} +{"epoch_s": 1790772684.263194, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19812576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 57.01, 36"} +{"epoch_s": 1790772685.2866416, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19832496, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8388348}, "gpu": "6941, 32607, 0, 56.75, 36"} +{"epoch_s": 1790772686.3135202, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19950804, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8387324}, "gpu": "6941, 32607, 0, 56.74, 36"} +{"epoch_s": 1790772687.3367112, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19874724, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8386812}, "gpu": "6941, 32607, 0, 56.90, 36"} +{"epoch_s": 1790772688.3587284, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19842500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8386556}, "gpu": "6941, 32607, 0, 57.05, 36"} +{"epoch_s": 1790772689.3818972, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19944936, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8384252}, "gpu": "6941, 32607, 0, 57.04, 36"} +{"epoch_s": 1790772690.406354, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19871504, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8379900}, "gpu": "6941, 32607, 0, 56.74, 36"} +{"epoch_s": 1790772691.4390683, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19883588, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8376316}, "gpu": "6941, 32607, 0, 31.70, 35"} +{"epoch_s": 1790772692.470097, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19895676, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8372220}, "gpu": "6941, 32607, 0, 20.18, 35"} +{"epoch_s": 1790772693.5028179, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20038008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8203772}, "gpu": "6941, 32607, 0, 11.67, 35"} +{"epoch_s": 1790772694.5281374, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20156748, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31267, 32607, 33, 28.99, 35"} +{"epoch_s": 1790772695.5503595, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 19302012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31351, 32607, 1, 96.33, 36"} +{"epoch_s": 1790772696.5729709, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18691716, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 1, 88.24, 36"} +{"epoch_s": 1790772697.5949724, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18600496, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 0, 83.40, 36"} +{"epoch_s": 1790772698.6135545, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18594848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8075004}, "gpu": "31699, 32607, 0, 56.88, 36"} +{"epoch_s": 1790772699.6351354, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18384636, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31729, 32607, 38, 71.98, 36"} +{"epoch_s": 1790772700.6604307, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18135500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31769, 32607, 99, 227.76, 45"} +{"epoch_s": 1790772701.682456, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18126208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 95, 359.78, 43"} +{"epoch_s": 1790772702.706684, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18118008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 2, 244.34, 38"} +{"epoch_s": 1790772703.7335, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18095652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 98, 409.97, 43"} +{"epoch_s": 1790772704.7526512, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18096236, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 97, 346.22, 45"} +{"epoch_s": 1790772705.7763088, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18088644, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 99, 290.87, 48"} +{"epoch_s": 1790772706.799191, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18089132, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 100, 370.80, 45"} +{"epoch_s": 1790772707.8183546, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18072284, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 97, 348.14, 45"} +{"epoch_s": 1790772708.8408382, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18071772, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31783, 32607, 99, 204.77, 49"} +{"epoch_s": 1790772709.8652713, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18084484, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 502.69, 49"} +{"epoch_s": 1790772710.8869991, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18091232, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 477.46, 52"} +{"epoch_s": 1790772711.9077418, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18051376, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 100, 453.75, 50"} +{"epoch_s": 1790772712.945486, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18059000, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 98, 483.63, 48"} +{"epoch_s": 1790772713.9662626, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18068208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 8013308}, "gpu": "31785, 32607, 99, 482.43, 53"} +{"epoch_s": 1790772714.9933336, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17987384, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 93, 346.04, 47"} +{"epoch_s": 1790772716.0165942, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17960560, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 96, 347.16, 48"} +{"epoch_s": 1790772717.039366, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18132960, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 211.30, 51"} +{"epoch_s": 1790772718.0643644, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18138544, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 508.40, 53"} +{"epoch_s": 1790772719.0876768, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18147832, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 475.77, 55"} +{"epoch_s": 1790772720.1091926, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18103444, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 457.60, 53"} +{"epoch_s": 1790772721.1299815, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18100992, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 507.29, 54"} +{"epoch_s": 1790772722.1500635, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18112212, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 476.48, 52"} +{"epoch_s": 1790772723.1765406, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18011920, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 97, 382.48, 50"} +{"epoch_s": 1790772724.1962311, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18017628, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 274.45, 45"} +{"epoch_s": 1790772725.21881, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18114148, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 365.93, 54"} +{"epoch_s": 1790772726.2438593, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18128360, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 479.71, 54"} +{"epoch_s": 1790772727.2632627, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18143844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 510.50, 56"} +{"epoch_s": 1790772728.2869742, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18150700, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 459.35, 56"} +{"epoch_s": 1790772729.3204784, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18162336, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 480.67, 58"} +{"epoch_s": 1790772730.3480747, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18062716, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 98, 494.31, 53"} +{"epoch_s": 1790772731.3745997, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18056756, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 94, 311.79, 52"} +{"epoch_s": 1790772732.3941443, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18080332, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 272.26, 47"} +{"epoch_s": 1790772733.4142647, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18087264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 134.10, 46"} +{"epoch_s": 1790772734.4370096, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18208276, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 222.96, 54"} +{"epoch_s": 1790772735.4588313, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18211508, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.78, 58"} +{"epoch_s": 1790772736.4805841, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18202380, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.06, 58"} +{"epoch_s": 1790772737.503986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18205432, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 494.72, 57"} +{"epoch_s": 1790772738.5267396, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18196648, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 514.25, 59"} +{"epoch_s": 1790772739.5491192, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18054812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 496.71, 60"} +{"epoch_s": 1790772740.5723188, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18048512, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 515.80, 58"} +{"epoch_s": 1790772741.5950322, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17928312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 513.71, 58"} +{"epoch_s": 1790772742.6171873, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17944052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 496.11, 60"} +{"epoch_s": 1790772743.639043, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17940264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 513.91, 60"} +{"epoch_s": 1790772744.6600034, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17833128, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 52, 496.12, 54"} +{"epoch_s": 1790772745.6818032, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17835068, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 497.48, 61"} +{"epoch_s": 1790772746.7033856, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17830900, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 516.30, 62"} +{"epoch_s": 1790772747.7276258, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17715960, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 496.96, 61"} +{"epoch_s": 1790772748.7482834, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17719684, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 513.01, 60"} +{"epoch_s": 1790772749.7694225, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17610640, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 507.09, 59"} +{"epoch_s": 1790772750.7923675, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17603368, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 485.92, 60"} +{"epoch_s": 1790772751.812411, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17595640, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 479.74, 64"} +{"epoch_s": 1790772752.8319893, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17586396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 515.18, 63"} +{"epoch_s": 1790772753.8533502, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17622816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 458.79, 63"} +{"epoch_s": 1790772754.8752813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17623492, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 479.38, 61"} +{"epoch_s": 1790772755.9013746, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17629392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 49, 450.65, 56"} +{"epoch_s": 1790772756.922106, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17626016, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 308.26, 58"} +{"epoch_s": 1790772757.9418297, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17607068, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 295.22, 53"} +{"epoch_s": 1790772758.9605587, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17603144, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 0, 130.95, 52"} +{"epoch_s": 1790772759.9839687, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18282120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 210.90, 61"} +{"epoch_s": 1790772761.006678, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18282984, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 515.74, 62"} +{"epoch_s": 1790772762.0434818, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18162840, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.51, 62"} +{"epoch_s": 1790772763.067759, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18150136, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 501.61, 62"} +{"epoch_s": 1790772764.089317, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18166848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.68, 64"} +{"epoch_s": 1790772765.1115272, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18031696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 500.77, 64"} +{"epoch_s": 1790772766.1324067, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18034652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 521.99, 64"} +{"epoch_s": 1790772767.1545649, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17937296, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 521.65, 66"} +{"epoch_s": 1790772768.176144, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17929464, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 501.06, 64"} +{"epoch_s": 1790772769.198718, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17920788, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.32, 65"} +{"epoch_s": 1790772770.236203, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17799416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 497.43, 64"} +{"epoch_s": 1790772771.257868, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17792564, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 523.67, 66"} +{"epoch_s": 1790772772.2799609, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17801924, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 520.28, 67"} +{"epoch_s": 1790772773.3021274, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17687256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 498.60, 66"} +{"epoch_s": 1790772774.335996, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17678064, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 521.94, 66"} +{"epoch_s": 1790772775.35813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17557356, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 521.58, 67"} +{"epoch_s": 1790772776.3823485, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17565428, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 489.46, 66"} +{"epoch_s": 1790772777.405725, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17569088, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 100, 487.07, 68"} +{"epoch_s": 1790772778.4254801, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17570184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7990524}, "gpu": "31785, 32607, 99, 520.51, 66"} +{"epoch_s": 1790772779.4490557, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 470.02, 67"} +{"epoch_s": 1790772780.473841, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17616188, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 487.32, 64"} +{"epoch_s": 1790772781.499789, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17505864, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.28, 67"} +{"epoch_s": 1790772782.523191, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17517408, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 328.98, 62"} +{"epoch_s": 1790772783.5435653, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17539636, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 303.74, 57"} +{"epoch_s": 1790772784.565325, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17527416, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 136.73, 56"} +{"epoch_s": 1790772785.5888178, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18242896, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 217.75, 64"} +{"epoch_s": 1790772786.612396, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18244028, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 524.56, 66"} +{"epoch_s": 1790772787.6342883, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18194804, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 526.80, 66"} +{"epoch_s": 1790772788.6568644, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18203332, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.39, 67"} +{"epoch_s": 1790772789.6793633, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18191904, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 521.05, 67"} +{"epoch_s": 1790772790.7027128, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18079592, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 503.11, 67"} +{"epoch_s": 1790772791.7242851, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18083776, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 527.45, 67"} +{"epoch_s": 1790772792.7456532, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17980956, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 505.96, 67"} +{"epoch_s": 1790772793.768554, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17984860, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 521.32, 68"} +{"epoch_s": 1790772794.7907064, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17972956, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.85, 66"} +{"epoch_s": 1790772795.8138406, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17850288, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 505.34, 68"} +{"epoch_s": 1790772796.8353448, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17848116, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.36, 69"} +{"epoch_s": 1790772797.8563817, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17846184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 526.18, 69"} +{"epoch_s": 1790772798.8780813, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723912, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 503.19, 68"} +{"epoch_s": 1790772799.899205, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17715168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 523.83, 69"} +{"epoch_s": 1790772800.9237013, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17593528, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 526.99, 70"} +{"epoch_s": 1790772801.9461932, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17589112, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 492.53, 69"} +{"epoch_s": 1790772802.9673676, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17602032, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 497.32, 69"} +{"epoch_s": 1790772803.9868026, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17581748, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 524.68, 70"} +{"epoch_s": 1790772805.006854, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17479100, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 467.85, 71"} +{"epoch_s": 1790772806.027366, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17469612, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 494.48, 66"} +{"epoch_s": 1790772807.054402, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17465264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 508.83, 66"} +{"epoch_s": 1790772808.0764651, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17451560, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 341.96, 65"} +{"epoch_s": 1790772809.0972805, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18242708, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 326.58, 60"} +{"epoch_s": 1790772810.1193252, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18224312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 231.55, 67"} +{"epoch_s": 1790772811.1443434, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18251360, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 98, 513.76, 65"} +{"epoch_s": 1790772812.1641836, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18257168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.31, 68"} +{"epoch_s": 1790772813.188216, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18264160, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 475.36, 68"} +{"epoch_s": 1790772814.2106729, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18280248, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 491.24, 70"} +{"epoch_s": 1790772815.2351635, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18226696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 43, 408.46, 65"} +{"epoch_s": 1790772816.2571764, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18232216, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 516.37, 70"} +{"epoch_s": 1790772817.2793994, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18237844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 492.67, 71"} +{"epoch_s": 1790772818.3027427, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18258420, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 85, 480.93, 69"} +{"epoch_s": 1790772819.3249714, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18262736, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 520.06, 70"} +{"epoch_s": 1790772820.3447847, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18263392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 495.94, 70"} +{"epoch_s": 1790772821.3689287, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18252008, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 387.84, 70"} +{"epoch_s": 1790772822.391625, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18251760, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.36, 70"} +{"epoch_s": 1790772823.4142845, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18246696, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 499.02, 69"} +{"epoch_s": 1790772824.4363837, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18255784, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 474.00, 72"} +{"epoch_s": 1790772825.4570014, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18249508, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 534.05, 68"} +{"epoch_s": 1790772826.4777033, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18265224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.60, 68"} +{"epoch_s": 1790772827.5001867, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18241316, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 338.84, 69"} +{"epoch_s": 1790772828.5244417, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18234208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.48, 69"} +{"epoch_s": 1790772829.5457335, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18255808, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.12, 72"} +{"epoch_s": 1790772830.5685184, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18259268, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.47, 71"} +{"epoch_s": 1790772831.5907855, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18256224, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.53, 71"} +{"epoch_s": 1790772832.613174, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18178900, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.43, 64"} +{"epoch_s": 1790772833.6395922, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18163872, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 510.42, 72"} +{"epoch_s": 1790772834.660667, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18164500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.48, 72"} +{"epoch_s": 1790772835.682373, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18067600, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 514.49, 71"} +{"epoch_s": 1790772836.7051973, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18067096, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.68, 71"} +{"epoch_s": 1790772837.7258525, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17941220, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 511.56, 71"} +{"epoch_s": 1790772838.747495, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17946888, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 532.64, 72"} +{"epoch_s": 1790772839.7696228, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17948264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 529.32, 72"} +{"epoch_s": 1790772840.7897382, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17841772, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 513.67, 71"} +{"epoch_s": 1790772841.811278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838756, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 528.76, 72"} +{"epoch_s": 1790772842.8329659, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.90, 71"} +{"epoch_s": 1790772843.8551986, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17717288, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 490.94, 72"} +{"epoch_s": 1790772844.8746738, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17722396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.11, 71"} +{"epoch_s": 1790772845.8973172, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723676, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 493.89, 72"} +{"epoch_s": 1790772846.91816, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17609420, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 85, 479.12, 71"} +{"epoch_s": 1790772847.939702, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17606604, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.62, 70"} +{"epoch_s": 1790772848.9587715, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17605816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 482.68, 71"} +{"epoch_s": 1790772849.9811416, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18225312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 2, 287.55, 62"} +{"epoch_s": 1790772851.0086215, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18219312, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 495.29, 70"} +{"epoch_s": 1790772852.0307431, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18212012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 532.53, 73"} +{"epoch_s": 1790772853.0534828, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18241908, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 513.63, 71"} +{"epoch_s": 1790772854.0752146, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18240392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 534.22, 71"} +{"epoch_s": 1790772855.0970914, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18192424, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.69, 73"} +{"epoch_s": 1790772856.119393, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18176072, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 511.80, 72"} +{"epoch_s": 1790772857.1404707, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18174816, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.85, 73"} +{"epoch_s": 1790772858.1629918, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066588, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 512.33, 71"} +{"epoch_s": 1790772859.1853132, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066664, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 512.57, 72"} +{"epoch_s": 1790772860.206362, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18066844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 532.25, 71"} +{"epoch_s": 1790772861.2286925, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17941852, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 511.81, 74"} +{"epoch_s": 1790772862.2505696, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17961916, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.91, 72"} +{"epoch_s": 1790772863.2736192, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17842052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 52, 515.36, 72"} +{"epoch_s": 1790772864.2948847, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17837396, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.06, 72"} +{"epoch_s": 1790772865.315923, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17838760, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.20, 71"} +{"epoch_s": 1790772866.3383734, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17722852, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 77, 489.91, 74"} +{"epoch_s": 1790772867.3589919, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17723784, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.00, 72"} +{"epoch_s": 1790772868.3802085, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17724116, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 492.00, 72"} +{"epoch_s": 1790772869.4032836, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17610436, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 519.67, 68"} +{"epoch_s": 1790772870.4251704, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17593928, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 482.79, 71"} +{"epoch_s": 1790772871.446933, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625500, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 490.11, 71"} +{"epoch_s": 1790772872.4693067, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18115856, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 42, 376.82, 63"} +{"epoch_s": 1790772873.4927008, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18130848, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 413.33, 71"} +{"epoch_s": 1790772874.517678, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18129660, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.46, 71"} +{"epoch_s": 1790772875.539969, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18122464, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 96, 513.83, 71"} +{"epoch_s": 1790772876.5611775, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18124472, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 525.10, 73"} +{"epoch_s": 1790772877.5850198, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18126548, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 533.66, 72"} +{"epoch_s": 1790772878.6076293, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18073280, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 511.73, 72"} +{"epoch_s": 1790772879.629884, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 18098184, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 535.61, 74"} +{"epoch_s": 1790772880.6510599, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17972812, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 531.98, 73"} +{"epoch_s": 1790772881.675439, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17976576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 507.68, 72"} +{"epoch_s": 1790772882.699754, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17973148, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 533.44, 72"} +{"epoch_s": 1790772883.722258, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17861120, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 508.82, 72"} +{"epoch_s": 1790772884.745278, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17864404, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 531.88, 72"} +{"epoch_s": 1790772885.769315, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17866576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 530.83, 74"} +{"epoch_s": 1790772886.7924066, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17752540, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 488.78, 72"} +{"epoch_s": 1790772887.817747, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17751168, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 99, 527.99, 69"} +{"epoch_s": 1790772888.8397095, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17735964, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 496.67, 72"} +{"epoch_s": 1790772889.8620257, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17625844, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 470.64, 71"} +{"epoch_s": 1790772890.884023, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17629264, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 528.82, 72"} +{"epoch_s": 1790772891.9039407, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17631268, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 100, 475.71, 71"} +{"epoch_s": 1790772892.925761, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17658484, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 242.06, 62"} +{"epoch_s": 1790772893.947652, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17660788, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 124.52, 62"} +{"epoch_s": 1790772894.9685812, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17662644, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 94.57, 60"} +{"epoch_s": 1790772895.9877603, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17666884, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 70.56, 59"} +{"epoch_s": 1790772897.009143, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17675152, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.94, 59"} +{"epoch_s": 1790772898.0305054, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17677208, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.68, 58"} +{"epoch_s": 1790772899.0518734, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17686920, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 69.10, 58"} +{"epoch_s": 1790772900.0737712, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17694368, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.64, 57"} +{"epoch_s": 1790772901.0949237, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17701040, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.54, 57"} +{"epoch_s": 1790772902.1162262, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17704052, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 68.07, 56"} +{"epoch_s": 1790772903.1371994, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17716036, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 67.54, 56"} +{"epoch_s": 1790772904.1573613, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17729424, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.79, 56"} +{"epoch_s": 1790772905.178784, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17734376, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.78, 55"} +{"epoch_s": 1790772906.2002432, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17741828, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.73, 55"} +{"epoch_s": 1790772907.2226708, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17744104, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 66.62, 54"} +{"epoch_s": 1790772908.2435381, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17741708, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 65.50, 54"} +{"epoch_s": 1790772909.2710078, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17724256, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 40.74, 53"} +{"epoch_s": 1790772910.2964864, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17746392, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 31.75, 53"} +{"epoch_s": 1790772911.3218958, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17745548, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 19.67, 53"} +{"epoch_s": 1790772912.3480182, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17746012, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.41, 52"} +{"epoch_s": 1790772913.3754818, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17733056, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.42, 52"} +{"epoch_s": 1790772914.402011, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17739736, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.55, 52"} +{"epoch_s": 1790772915.4289236, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17733576, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.24, 51"} +{"epoch_s": 1790772916.4575953, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17753656, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.35, 51"} +{"epoch_s": 1790772917.4829435, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17752892, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.47, 51"} +{"epoch_s": 1790772918.5089724, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17753536, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 12.31, 51"} +{"epoch_s": 1790772919.5349586, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17755604, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 12.49, 51"} +{"epoch_s": 1790772920.5655951, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17766328, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.14, 50"} +{"epoch_s": 1790772921.5931342, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 17743004, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "31785, 32607, 0, 14.21, 50"} +{"epoch_s": 1790772922.637384, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 20934704, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "30128, 32607, 4, 16.71, 50"} +{"epoch_s": 1790772924.2924495, "memory": {"MemTotal_KiB": 65208820, "MemAvailable_KiB": 37200652, "SwapTotal_KiB": 8388604, "SwapFree_KiB": 7952892}, "gpu": "2, 32607, 0, 60.26, 50"} diff --git a/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/README.md b/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/README.md new file mode 100644 index 00000000..8eaf9026 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/README.md @@ -0,0 +1,57 @@ +# BF16 GEMV on Turing tensor cores (sm_75): measured negative + +i7-8700K + RTX 2070 8 GB (sm_75, 36 SMs), engine 0.1.27 tree (`bf16_gemv.cu` is unchanged through 0.1.30), +qwen3.8-flash-next (~125.7B MoE, GGUF-verified) Q2_0 in production. Isolated benchmark only - +[`bench_tc_gemv.cu`](bench_tc_gemv.cu) touches nothing in the inference path. Question: the QSA prompt attention +already rides the Turing tensor cores (`mma.sync.m16n8k8`, the #270 path); can the decode GEMVs do the same? + +## Setup + +- Baseline: the production `bf16_gemv` warp kernel, transcribed verbatim +- TC variant: `mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32` on BF16->FP16 (the sm_75 MMA has native f16 only). + BF16->FP16 conversion is exact (0 / 2,000,000 values inexact - bf16's 7-bit mantissa fits in fp16's 10 bits); the + A-fragment packing is the same one #270 validated (`a0` = row `gid`, k columns `2t..2t+1`; broadcast makes + `a0 == a1 == {x[2t], x[2t+1]}`) +- Three TC variants to cover the conversion overhead from every angle: W preconverted to fp16 once at load + (`pc`), W converted in-register every call (`in`), and a fused ks=1 form that writes the output directly and skips + the reduce kernel (`fused`) +- The k-split across blocks (`ks`) is swept over all values that divide n_in, and the best is reported - the TC + kernel gets its best occupancy +- Parity against an fp64 host reference; 2000 iterations x 3 reps, warmed CUDA events + +## Results (best TC config per shape) + +| Shape (decode, n_in = 2560, BF16 W) | Baseline us | Best TC us | Speedup | Config | +| --- | ---: | ---: | ---: | --- | +| ssm_alpha/beta [2560, 48] | 8.73 | 11.32 | 0.77x | pc, ks=16 | +| indexer.k_proj [2560, 128] | 7.14 | 12.09 | 0.59x | pc, ks=16 | +| indexer.q_proj / router [2560, 512] | 9.48 | 15.78 | 0.60x | pc, ks=4 | +| ple_value [2560, 2560] | 35.08 | 77.73 | 0.45x | pc, ks=40 | + +- Numerics pass: TC max error vs fp64 reference 1.7e-6 .. 7.2e-6 (fp16-accumulation level), baseline + 0.7e-6 .. 2.3e-6. The TC variant computes the same thing, it is just slower. +- The warp kernel is already bandwidth-bound at 276-374 GB/s effective W bandwidth (374 GB/s on the 13 MB + [2560, 2560] shape); the TC path reaches only 166-169 GB/s (4-byte lane loads, conversion instructions, in-tile + launch overhead). +- A single-token GEMV broadcasts one token across the whole m16 MMA tile, so 15/16 of the MMA throughput is thrown + away - but the baseline is not compute-bound, so the wasted throughput buys nothing. The k-split sweep and the + fused variant do not recover it. +- One-time W conversion cost is negligible (2 ms for 13 MB), so preconverting W for the TC path does not help. + +## How to rerun + +``` +nvcc -arch=sm_75 -O3 -o bench_tc_gemv.exe bench_tc_gemv.cu +./bench_tc_gemv.exe +``` + +Prints the table above, per-shape latency/parity and the conversion exactness scan. On a newer card, adjust +`-arch`; the packed-A layout comment in the source documents the fragment mapping it relies on. + +## Conclusion + +**Keep the warp kernel. Tensor cores are not a promising direction for the decode GEMVs on sm_75**, and this was a +measured loss (1.3-2.2x slower), not a failed attempt to optimize. The Turing MMA stays worthwhile where the input +really has m16 rows of work: the QSA prompt-attention tiles, which is where #270 uses it. Someone looking to +re-evaluate on future hardware (a card with native bf16 or denser GEMV batching) can rerun this instead of +rebuilding it. \ No newline at end of file diff --git a/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu b/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu new file mode 100644 index 00000000..bead5e33 --- /dev/null +++ b/engine/strata/bench/results/2026-09-30-tc-gemv-sm75/bench_tc_gemv.cu @@ -0,0 +1,305 @@ +// bench_tc_gemv.cu - ISOLATED benchmark: BF16 GEMV baseline vs Tensor Core (mma.m16n8k8, BF16->FP16) on sm_75. +// Nothing in the engine changes. Shapes are the REAL Strata decode GEMVs (BF16 weights, n_in = n_embd = 2560): +// ssm_alpha / ssm_beta [2560, 48] project_bf16(split=true) -> bf16_gemv_split(TPR=32) -> warp kernel +// indexer.k_proj [2560, 128] project_bf16(split=false) -> bf16_gemv -> warp kernel +// indexer.q_proj / ffn_gate_inp / mlp.gate [2560, 512] warp / split(TPR=32) -> warp kernel +// ple_value [2560, 2560] warp +// Baseline = bf16_gemv_warp_kernel transcribed verbatim from src/kernels/cuda/bf16_gemv.cu (production). +// TC variant = same maths; A = x broadcast down m16 (single-token GEMV), k-chunk = 8; +// (a) W preconverted bf16->fp16 once, x converted in-kernel (timed) [tc_preconv] +// (b) fully inline: W read as bf16 and converted in-register [tc_inline] +// Numerics: fp64 host reference; max abs err for baseline and both TC variants; bf16->fp16 exactness scan. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(e) do { cudaError_t err_ = (e); if (err_ != cudaSuccess) { \ + fprintf(stderr, "CUDA %s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(err_)); exit(1); } } while (0) + +__device__ __forceinline__ float bf16_f32(uint16_t v) { return __int_as_float((int) ((unsigned) v << 16)); } +static float bf16_f32_host(uint16_t v) { unsigned u = (unsigned) v << 16; float f; memcpy(&f, &u, 4); return f; } +static uint16_t f32_bf16_host(float f) { + unsigned u, r; memcpy(&u, &f, 4); + r = ((u >> 16) ^ (u >> 15)) & 1; u += 0x7fff + r; + return (uint16_t) (u >> 16); +} + +// ============ baseline: production warp kernel (verbatim semantics from bf16_gemv.cu) ============ +__global__ void gemv_warp(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out) { + const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (o >= n_out) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = lane; i < n_in; i += 32) + acc += bf16_f32(x[i]) * bf16_f32(row[i]); + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + if (lane == 0) y[o] = acc; +} + +// ============ TC: A(x) broadcast, k-split over blocks, partial D row 0 -> scratch ============ +// A fragment (m16n8k8, .f16): lane l: a0 = A[m=l>>2][k=2(l&3)], a1 = A[m][k=2(l&3)+1], +// a2/a3 = same cols at row m+8. Broadcast => a2=a0, a3=a1. +// B fragment (.f16, col-major): lane l: b0 = B[k=2(l&3)][n=(l>>2)], b1 = B[k=2(l&3)+1][n]. +// B[k][n] = W[n][k], so lane l loads W[n][2(l&3)], W[n][2(l&3)+1] - coalesced within the row. +// D fragment: c0/c1 = D[m=l>>2][cols 2(l&3), +1], c2/c3 = row m+8. All m rows identical -> row 0. +__global__ void tc_preconv(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_f, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + // A (2 x f16x2): a0 = {A[m][2t], A[m+8][2t]}, a1 = {A[m][2t+1], A[m+8][2t+1]} (broadcast -> dup halves) + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + // fp16 conversion in-register: bf16 -> f32 -> f16 (exact within fp16 range) + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + // B is already fp16 here: load as __half2 directly (bf16 path must NOT convert twice) + __half2 wbh = *reinterpret_cast(&w_f[(n_base + (lane >> 2)) * n_in + kk0 + t2]); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// same, but W stays bf16 and converts in-register (fully fair per-call cost) +__global__ void tc_inline(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + unsigned xh = (unsigned) x_b[kk0 + t2] | ((unsigned) x_b[kk0 + t2 + 1] << 16); + __half2 ha = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + __half2 hb = __floats2half2_rn(bf16_f32((uint16_t) (xh & 0xFFFF)), bf16_f32((uint16_t) (xh >> 16))); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +__global__ void tc_reduce(const float* __restrict__ partials, float* __restrict__ y, long long n_out, int ks) { + const long long o = blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + float s = 0.f; + for (int q = 0; q < ks; ++q) s += partials[(size_t) ((o >> 3) * ks + q) * 8 + (o & 7)]; + y[o] = s; +} + +// variant with the OTHER candidate A layout: a0 = {A[gid][2t], A[gid+8][2t]} (same k-col, two rows), +// a1 = same for col 2t+1. Broadcast => both halves of a0 hold x[2t], both halves of a1 hold x[2t+1]. +__global__ void tc_dupcol(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ partials, long long n_in, long long n_out, int ks) { + const int tile = blockIdx.x, ks_i = blockIdx.y, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const long long k_per = n_in / (long long) ks; + const long long k0 = (long long) ks_i * k_per; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = k0; kk0 < k0 + k_per; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2])); + __half2 hb = __floats2half2_rn(bf16_f32(x_b[kk0 + t2 + 1]), bf16_f32(x_b[kk0 + t2 + 1])); + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { float* p = partials + (size_t) (tile * ks + ks_i) * 8; p[t2] = c0; p[t2 + 1] = c1; } +} + +// FUSED, ks=1 only: with a single k-fragment the partial IS the answer -> write y directly, no reduce kernel, +// no scratch. Fully inline bf16 W conversion (fairest per-call TC cost). +__global__ void tc_fused(const uint16_t* __restrict__ x_b, const uint16_t* __restrict__ w_b, + float* __restrict__ y, long long n_in, long long n_out) { + const int tile = blockIdx.x, lane = threadIdx.x & 31; + const long long n_base = (long long) tile * 8; + const int t2 = 2 * (lane & 3); + float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f; + for (long long kk0 = 0; kk0 < n_in; kk0 += 8) { + __half2 ha = __floats2half2_rn(bf16_f32(x_b[kk0 + t2]), bf16_f32(x_b[kk0 + t2 + 1])); + __half2 hb = ha; // broadcast: row gid+8 = row gid (single-token GEMV) + unsigned a0 = *reinterpret_cast(&ha); + unsigned a1 = *reinterpret_cast(&hb); + const uint16_t* wbv = w_b + (n_base + (lane >> 2)) * n_in + kk0 + t2; + __half2 wbh = __floats2half2_rn(bf16_f32(wbv[0]), bf16_f32(wbv[1])); + unsigned b0 = *reinterpret_cast(&wbh); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) + : "r"(a0), "r"(a1), "r"(b0)); + } + if (lane < 4) { y[n_base + t2] = c0; y[n_base + t2 + 1] = c1; } +} + +int main() { + CHECK(cudaSetDevice(0)); + cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, 0)); + printf("device: %s, SMs %d, capability %d.%d\n", prop.name, prop.multiProcessorCount, prop.major, prop.minor); + + struct Shape { const char* name; long long n_in, n_out; }; + Shape shapes[] = { + {"ssm_alpha/beta [2560,48]", 2560, 48}, + {"indexer.k_proj [2560,128]", 2560, 128}, + {"q_proj/router [2560,512]", 2560, 512}, + {"ple_value [2560,2560]", 2560, 2560}, + }; + auto rng = [](unsigned& s) { s = s * 1664525u + 1013904223u; return (float) ((s >> 8) & 0xFFFF) / 65535.0f - 0.5f; }; + const int ITERS = 2000, WARM = 300; + + printf("\n%-26s %13s | %s\n", "shape", "baseline us", "tc variants (pc = W preconverted, in = inline conversion, fused = no reduce), speedup vs baseline"); + printf("%s\n", std::string(150, '-').c_str()); + + for (auto& sh : shapes) { + const long long n_in = sh.n_in, n_out = sh.n_out; + const size_t wn = (size_t) n_out * n_in; + std::vector hw(wn), hx(n_in), hf(wn); + std::vector hyb(n_out), hypc(n_out), hyin(n_out), hyfu(n_out); + std::vector href(n_out); + unsigned seed = 991u + (unsigned) (n_out & 0xFFF); + for (size_t i = 0; i < wn; ++i) hw[i] = f32_bf16_host(rng(seed) * 0.3f); + for (long long i = 0; i < n_in; ++i) hx[i] = f32_bf16_host(rng(seed) * 3.0f); + for (long long o = 0; o < n_out; ++o) { + double s = 0.0; + for (long long i = 0; i < n_in; ++i) s += (double) bf16_f32_host(hx[i]) * (double) bf16_f32_host(hw[(size_t) o * n_in + i]); + href[o] = s; + } + // preconvert W to fp16 (bf16 -> fp16 is exact within fp16 range) + for (size_t i = 0; i < wn; ++i) { __half h = __float2half_rn(bf16_f32_host(hw[i])); memcpy(&hf[i], &h, 2); } + + uint16_t *dx, *dw, *dwf; float *dy, *dyp; + CHECK(cudaMalloc(&dx, n_in * 2)); + CHECK(cudaMalloc(&dw, wn * 2)); CHECK(cudaMalloc(&dwf, wn * 2)); + CHECK(cudaMalloc(&dy, n_out * 4)); + CHECK(cudaMalloc(&dyp, (size_t)(n_out / 8) * 65 * 8 * 4)); + CHECK(cudaMemcpy(dx, hx.data(), n_in * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dw, hw.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + + // one-time W conversion cost (host->device, reported separately; the engine would fold this + // into the weight load exactly like Gemm::bf16 does for sm<80) + { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + CHECK(cudaMemcpy(dwf, hf.data(), wn * 2, cudaMemcpyHostToDevice)); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + printf("%-26s one-time W convert: %.2f ms (%.1f MB), tiles=%lld\n", sh.name, ms, wn * 2 / 1e6, n_out / 8); + } + + int tiles = (int) (n_out / 8); + // valid ks must divide n_in so each k-chunk is a multiple of 8; sweep ALL of them, report the best + const int cands[11] = {1, 2, 4, 5, 8, 10, 16, 20, 32, 40, 64}; + + auto timeit = [&](const char* tag, const std::function& fn) -> double { + for (int i = 0; i < WARM; ++i) fn(); + CHECK(cudaDeviceSynchronize()); + double best = 1e30; + for (int rep = 0; rep < 3; ++rep) { + cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1)); + CHECK(cudaEventRecord(e0)); + for (int i = 0; i < ITERS; ++i) fn(); + CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1)); + float ms = 0; CHECK(cudaEventElapsedTime(&ms, e0, e1)); + double us = ms * 1000.0 / ITERS; + if (us < best) best = us; + } + (void) tag; return best; + }; + + double t_base = timeit("base", [&]{ gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); }); + gemv_warp<<<(unsigned) ((n_out + 7) / 8), 256>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyb.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + // occupancy sweep over k-chunk count for the preconverted-W TC kernel + int best_ks = 1; double t_pc = 1e30; + for (int i = 0; i < 11; ++i) { + const int ksv = cands[i]; + if (n_in % ksv != 0) continue; + dim3 g((unsigned) tiles, (unsigned) ksv); + double t = timeit("pcs", [&]{ tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, ksv); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, ksv); }); + if (t < t_pc) { t_pc = t; best_ks = ksv; } + } + dim3 gtc((unsigned) tiles, (unsigned) best_ks); + tc_preconv<<>>(dx, dwf, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hypc.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_ti = timeit("tci", [&]{ tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); }); + tc_inline<<>>(dx, dw, dyp, n_in, n_out, best_ks); + tc_reduce<<<(unsigned) ((n_out + 255) / 256), 256>>>(dyp, dy, n_out, best_ks); + CHECK(cudaMemcpy(hyin.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double t_fu = timeit("tcf", [&]{ tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); }); + tc_fused<<<(unsigned) tiles, 32>>>(dx, dw, dy, n_in, n_out); + CHECK(cudaMemcpy(hyfu.data(), dy, n_out * 4, cudaMemcpyDeviceToHost)); + + double best_tc = t_pc; const char* best_var = "preconv"; + if (t_ti < best_tc) { best_tc = t_ti; best_var = "inline"; } + if (t_fu < best_tc) { best_tc = t_fu; best_var = "fused"; } + + double e_tc = 0, e_base = 0, sc = 0; + if (strcmp(best_var, "preconv") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hypc[o] - href[o])); } + } else if (strcmp(best_var, "inline") == 0) { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyin[o] - href[o])); } + } else { + for (long long o = 0; o < n_out; ++o) { e_tc = std::max(e_tc, std::fabs((double) hyfu[o] - href[o])); } + } + for (long long o = 0; o < n_out; ++o) { + e_base = std::max(e_base, std::fabs((double) hyb[o] - href[o])); + sc = std::max(sc, std::fabs(href[o])); + } + double gb_base = (double) (wn * 2) / t_base / 1e3; + double gb_tc = (double) (wn * 2) / best_tc / 1e3; + printf("%-26s %13.3f | pc %13.3f (ks=%d) | in %13.3f | fused %13.3f | BEST %s %7.3fx | maxerr tc %.2e base %.2e (scale %.1f, BW base %.0f tc %.0f GB/s)\n", + sh.name, t_base, t_pc, best_ks, t_ti, t_fu, best_var, t_base / best_tc, + e_tc, e_base, sc, gb_base, gb_tc); + + CHECK(cudaFree(dx)); CHECK(cudaFree(dw)); CHECK(cudaFree(dwf)); CHECK(cudaFree(dy)); CHECK(cudaFree(dyp)); + } + + { // bf16 -> fp16 exactness scan + unsigned seed = 777u; double worst = 0; int bad = 0, n = 2000000; + for (int i = 0; i < n; ++i) { + float f = (rng(seed) * 2.0f - 1.0f) * 100.0f; + uint16_t b = f32_bf16_host(f); + __half h = __float2half_rn(bf16_f32_host(b)); + if ((double) __half2float(h) != (double) bf16_f32_host(b)) { + bad++; worst = std::max(worst, std::fabs((double) __half2float(h) - (double) bf16_f32_host(b))); + } + } + printf("\nbf16->fp16 conversion exactness: %d / %d inexact, worst %.3g\n", bad, n, worst); + } + printf("BENCH_DONE\n"); + return 0; +} diff --git a/engine/strata/chat.py b/engine/strata/chat.py new file mode 100644 index 00000000..124c7278 --- /dev/null +++ b/engine/strata/chat.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""A tiny terminal chat for a running Strata server (start it with run-.bat / run-.sh first). + + python chat.py [--port 8080] [--think none|low|medium|high] + +Type a message and press Enter. /image attaches a picture to your next message (when the server was set up +with images), /think sets how long the model thinks first, /reset starts a new conversation, +/quit leaves. Standard library only. +""" +from __future__ import annotations + +import argparse +import base64 +import json +import mimetypes +import os +import sys +import time +import urllib.request + + +def stream(url, messages, think, max_tokens): + body = {"model": "strata", "messages": messages, "stream": True, "max_tokens": max_tokens, + "reasoning_effort": think} + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=3600) as r: + for raw in r: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data: ") or line == "data: [DONE]": + continue + d = json.loads(line[6:])["choices"][0]["delta"] + yield d.get("reasoning_content") or "", d.get("content") or "" + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="127.0.0.1") + ap.add_argument("--think", default="medium", choices=["none", "low", "medium", "high"], + help="how long the model thinks before answering (none = answer directly)") + ap.add_argument("--no-think", action="store_true", help="same as --think none") + ap.add_argument("--max-tokens", type=int, default=4096) + a = ap.parse_args() + url = f"http://{a.host}:{a.port}/v1/chat/completions" + gray, reset = ("\033[90m", "\033[0m") if sys.stdout.isatty() else ("", "") + messages, pending = [], [] + think = "none" if a.no_think else a.think + print(f"Strata chat ({url}). /image = attach a picture, /think none|low|medium|high (now: {think}), " + f"/reset = new conversation, /quit = leave.") + while True: + try: + user = input("\nyou> ").strip() + except (EOFError, KeyboardInterrupt): + print() + return 0 + if user in ("/quit", "/exit"): + return 0 + if user == "/reset": + messages, pending = [], [] + print("(new conversation)") + continue + if user.startswith("/think"): + level = user[6:].strip().lower() + if level in ("none", "low", "medium", "high"): + think = level + print(f"(thinking: {think})") + else: + print("(usage: /think none|low|medium|high)") + continue + if user.startswith("/image"): + path = user[6:].strip().strip('"').strip("'") + if not os.path.isfile(path): + print(f"(no such file: {path or '?'} - usage: /image )") + continue + mime = mimetypes.guess_type(path)[0] or "image/jpeg" + data = base64.b64encode(open(path, "rb").read()).decode() + pending.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}}) + print(f"(picture attached: {os.path.basename(path)} - now type your question)") + continue + if not user: + continue + if pending: + messages.append({"role": "user", "content": [*pending, {"type": "text", "text": user}]}) + pending = [] + else: + messages.append({"role": "user", "content": user}) + answer, n, t0 = [], 0, time.time() + print("model> ", end="", flush=True) + try: + in_think = False + for reasoning, content in stream(url, messages, think, a.max_tokens): + if reasoning: + if not in_think: + print(gray, end="") + in_think = True + print(reasoning, end="", flush=True) + if content: + if in_think: + print(reset + "\n", end="") + in_think = False + print(content, end="", flush=True) + answer.append(content) + n += 1 + if in_think: + print(reset, end="") + except OSError as e: + print(f"\n(could not reach the server at {url}: {e})") + messages.pop() + continue + dt = time.time() - t0 + print(f"\n{gray}[{n} chunks in {dt:.1f} s]{reset}") + messages.append({"role": "assistant", "content": "".join(answer)}) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/cmake/hip_backend.cmake b/engine/strata/cmake/hip_backend.cmake new file mode 100644 index 00000000..255ee381 --- /dev/null +++ b/engine/strata/cmake/hip_backend.cmake @@ -0,0 +1,99 @@ +# Opt-in HIP configuration. Strata's CUDA-shaped kernels target wave32 RDNA2 / RDNA3 / RDNA4 (64 KiB LDS per +# workgroup, a signed dot4 instruction). CMake/compiler discovery stays machine-independent; pass CMAKE_HIP_COMPILER when it +# is not on PATH. +if(NOT DEFINED CMAKE_HIP_ARCHITECTURES OR CMAKE_HIP_ARCHITECTURES STREQUAL "") + set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture(s), e.g. gfx1100 or gfx1100;gfx1201") +endif() +# Validated on real cards: gfx1100 (RX 7900 XT / XTX) and gfx1201 (RX 9070 / 9070 XT, Radeon AI PRO R9700) by the +# maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the +# same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. RDNA2 gfx1030 (RX 6800 / 6900) has the +# same LDS limit and wave32 but an older dot4 instruction (v_dot4_i32_i8, hip_compat/intrinsics.hpp); a community +# report ran it (#311), the maintainers have not. +set(_strata_hip_validated gfx1100 gfx1201) +set(_strata_hip_community gfx1101 gfx1200) +set(_strata_hip_unvalidated gfx1102 gfx1030) +# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use +# spaces, which foreach(IN LISTS) would otherwise treat as one element. +string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}") +set(STRATA_HIP_ARCH_LIST "") +foreach(_arch IN LISTS _strata_hip_norm) + if(_arch STREQUAL "") + continue() + endif() + string(REGEX REPLACE ":.*$" "" _base "${_arch}") # gfx1100:xnack- -> gfx1100 + if(_base IN_LIST _strata_hip_validated) + elseif(_base IN_LIST _strata_hip_community) + message(STATUS "Strata HIP: ${_base} was validated by community reports (docs/AMD_HIP.md)") + elseif(_base IN_LIST _strata_hip_unvalidated) + message(WARNING "Strata HIP: ${_base} builds, but it is not validated on a real card yet; please report results") + else() + message(FATAL_ERROR + "Strata HIP supports wave32 gfx1100, gfx1101, gfx1200 and gfx1201 (unvalidated: ${_strata_hip_unvalidated}); " + "CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'") + endif() + list(APPEND STRATA_HIP_ARCH_LIST "${_base}") +endforeach() +list(REMOVE_DUPLICATES STRATA_HIP_ARCH_LIST) +if(NOT STRATA_HIP_ARCH_LIST) + message(FATAL_ERROR "Strata HIP: CMAKE_HIP_ARCHITECTURES is empty") +endif() +# The compiled architectures reach the runtime device check (src/core/device.cu) as "gfx1100,gfx1201": a binary +# carried to a card it has no code for stops at startup with a clear message instead of "invalid device function". +string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}") + +enable_language(HIP) +find_package(hip CONFIG REQUIRED) +find_package(hipblas CONFIG REQUIRED) +find_package(hipblaslt CONFIG QUIET) + +if(NOT TARGET hip::host) + message(FATAL_ERROR "The ROCm hip CMake package did not provide hip::host") +endif() +if(NOT TARGET roc::hipblas) + message(FATAL_ERROR "The ROCm hipblas CMake package did not provide roc::hipblas") +endif() +if(TARGET roc::hipblaslt) + set(STRATA_HIPBLASLT_AVAILABLE ON) +else() + set(STRATA_HIPBLASLT_AVAILABLE OFF) + message(STATUS "Strata: hipBLASLt not found; solution-table dispatch is unavailable") +endif() + +# HIP's link step produces a PIE; make Strata and ggml objects PIC for the ROCm linker. +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +set(STRATA_HIP_COMPAT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include/strata/hip_compat") +add_library(strata_hip_runtime INTERFACE) +target_include_directories(strata_hip_runtime BEFORE INTERFACE + "${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"") +target_link_libraries(strata_hip_runtime INTERFACE hip::host) +# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host +# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes +# -include like it does on Linux; an MSVC-style front end (cl / clang-cl) takes /FI instead. Forward slashes, so /FI +# does not read the path's backslashes as escapes. +file(TO_CMAKE_PATH "${STRATA_HIP_COMPAT_INCLUDE_DIR}/cuda_runtime.h" _strata_hip_force) +if(MSVC) + target_compile_options(strata_hip_runtime INTERFACE "$<$:/FI${_strata_hip_force}>") +else() + target_compile_options(strata_hip_runtime INTERFACE + "$<$:-include>" "$<$:${_strata_hip_force}>") +endif() +target_compile_options(strata_hip_runtime INTERFACE + "$<$:-include>" "$<$:${_strata_hip_force}>") + +# CMake does not infer HIP from Strata's existing CUDA-shaped .cu suffixes. +file(GLOB_RECURSE _strata_hip_sources CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu" + "${CMAKE_CURRENT_SOURCE_DIR}/bench/*.cu" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cu") +if(_strata_hip_sources) + set_source_files_properties(${_strata_hip_sources} PROPERTIES LANGUAGE HIP) +endif() +foreach(_source IN ITEMS tests/hip/intrinsics.cpp tests/hip/native_qsa_score.cpp) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_source}") + set_source_files_properties("${_source}" PROPERTIES LANGUAGE HIP) + endif() +endforeach() + +message(STATUS "Strata: HIP enabled, arch ${STRATA_HIP_ARCHS}") diff --git a/engine/strata/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json b/engine/strata/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json new file mode 100644 index 00000000..82946d62 --- /dev/null +++ b/engine/strata/data/experimental-speed-projection/Qwen3.8-Flash-Next-experimental-speed-projection.json @@ -0,0 +1,26 @@ +{ + "mode": "project", + "dir": "per-layer", + "scale": 1.0, + "layer_range": [ + 4, + 44 + ], + "refusal_harmful_thinkoff": 2.0, + "refusal_harmful_thinkon": 2.0, + "refusal_harmless_thinkoff": 4.0, + "refusal_harmless_thinkon": 6.0, + "broken": 0, + "kl_mean": 0.18598, + "kl_max": 18.26549, + "kl_p99": 3.143571, + "decode_tps": 51.19, + "vector_file": "Qwen3.8-Flash-Next-experimental-speed-projection.gguf", + "base_model_gguf": "unsloth/Qwen3.8-Flash-Next-GGUF UD-Q2_K_XL", + "base_model_sha256_shard1": "a4f3b21e77353999829f2f767e9ac21ce9c71d29a74f2cc9eda48c9bf23c8b86", + "worktree_commit": "37e026e3b", + "criterion_status": "PASS", + "dirty_direction": false, + "note": "projection ablation h -= s*(h.v)*v, v unit-normalized per layer. dir=per-layer", + "branch": "cvec-hooks (github.com/Cudila/llama.cpp)" +} diff --git a/engine/strata/data/experimental-speed-projection/README.md b/engine/strata/data/experimental-speed-projection/README.md new file mode 100644 index 00000000..ad4a0085 --- /dev/null +++ b/engine/strata/data/experimental-speed-projection/README.md @@ -0,0 +1,21 @@ +# experimental-speed-projection (EXPERIMENTAL, off by default) + +`Qwen3.8-Flash-Next-experimental-speed-projection.gguf` is a 480 KB control vector for Qwen3.8-Flash-Next: one unit +direction of 2,560 values per layer (`direction.1` .. `direction.47`, GGUF `controlvector` format). The JSON beside it +is the configuration its authors selected and their scores. + +**What it does.** Turned on, Strata removes each direction from the residual stream after layers 4-44 +(`h -= (h . v) v` on every hyper-connection stream), the same operation as llama.cpp's `--cvec-mode project` in the +package's patches. The package's own documentation describes the vector as a **refusal-direction projection**: the +model declines far fewer requests (it reports 1 of 50 vs 50 of 50 on its test set), and removing refusals removes a +safety behaviour - you are responsible for what the model writes with it on. It also shifts the model's predictions +slightly on ordinary text (measured here: `bench/results/2026-09-27-esp/`). It is not an optimization in the engine: +on the same text it costs 0.2-0.4% per token; a chat's speed with it on depends on the text the model writes. + +**Turning it on.** `START-HERE.bat --setup` asks (default: off), or pass `--experimental-speed-projection on`. With it +loaded, the web app's Sampling drawer and the API field `"experimental_speed_projection": false` switch it off per +request. See `docs/DETAILS.md`, "Experimental speed projection". + +**Origin and license.** A local package of the vector (the published original uses filenames containing "refusal"; +the bytes are the same), made from Qwen3.8-Flash-Next activations, so the Qwen Community License 1.0 of the model +applies to it. Made for the original Qwen3.8-Flash-Next (not Swift 1.5). diff --git a/engine/strata/docker-entrypoint.sh b/engine/strata/docker-entrypoint.sh new file mode 100755 index 00000000..f167bed0 --- /dev/null +++ b/engine/strata/docker-entrypoint.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# Entry point for the Strata container. The engine is compiled during docker +# build and lives in the image, so the first start only downloads the model. +# The install config is kept on the /data volume so a recreated container skips +# the setup pass and goes straight to serving. +set -e +cd /opt/strata || exit 1 + +STRATA_DATA="${STRATA_DATA:-/data}" +FAMILY="${FAMILY:-qwen}" +MODEL="${MODEL:-IQ2_XS}" +CONTEXT="${CONTEXT:-32768}" +VISION="${VISION:-no}" # no | yes | cpu (the image encoder on the CPU) +HOST="${HOST:-0.0.0.0}" +PORT="${PORT:-8080}" +API_KEY="${API_KEY:-}" +KV="${KV:-}" # int8 | q4_0 | k8v4; empty: setup.py's own default (int8) +GPUS="${GPUS:-}" # "0,2" or "all": one model across several cards (docs/MULTI_GPU.md) +GPU="${GPU:-}" # one card, numbered as nvidia-smi numbers them +LAYER_SPLIT="${LAYER_SPLIT:-}" # with GPUS: where each later card's layers start (default: auto) +LOW_RAM="${LOW_RAM:-auto}" # on: the experts come from the pack's experts.bin, not from RAM + +# setup.py starts the newest strata-*.json it finds, so link in exactly the one +# this family and model were set up with. The config is the recorded output of +# that setup (the pack, the profile, the quant, the KV decision), not settings +# the entry point could rebuild from env vars. qwen has an empty family tag. +case "$FAMILY" in qwen) prefix="" ;; *) prefix="${FAMILY}-" ;; esac +tag="${prefix}$(printf '%s' "$MODEL" | tr 'A-Z' 'a-z')" +cfg="$STRATA_DATA/config/strata-$tag.json" +mkdir -p "$STRATA_DATA/config" + +# REINSTALL is only needed to change settings for a model that is already set up +# (context, vision, KV, host, api_key). Switching between models already on the +# volume needs no setup pass: their config is already there. +# +# KV / GPUS / GPU / LAYER_SPLIT are passed only when set, so an unset one keeps +# setup.py's own default. LOW_RAM is always passed: setup.py measures the PC's RAM +# from /proc/meminfo, which in a container is the host's total, not the container's +# limit, so a memory-capped container has to ask for the low-RAM mode itself. +if [ "${REINSTALL:-0}" = "1" ] || [ ! -f "$cfg" ]; then + echo "Setting up $tag: downloading the model (~70 GB; the engine is already in the image)." + set -- --family "$FAMILY" --model "$MODEL" --context "$CONTEXT" --vision "$VISION" \ + --data-dir "$STRATA_DATA" --host "$HOST" --api-key "$API_KEY" \ + --port "$PORT" --no-start --low-ram "$LOW_RAM" + if [ -n "$KV" ]; then set -- "$@" --kv "$KV"; fi + if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi + if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi + if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi + .venv/bin/python setup.py --setup --yes "$@" + [ -e "/opt/strata/strata-$tag.json" ] && { cmp -s "/opt/strata/strata-$tag.json" "$cfg" || cp -f "/opt/strata/strata-$tag.json" "$cfg"; } +else + [ -e "/opt/strata/strata-$tag.json" ] || ln -s "$cfg" "/opt/strata/strata-$tag.json" +fi + +# Later starts skip straight here: setup.py finds the installed config and +# launches serve/server.py (OpenAI- and Anthropic-compatible API on :8080). +# GPUS / GPU / LAYER_SPLIT are repeated on purpose. Given at the start they pin the +# cards for this model, and setup.py saves them in its config; without them a config +# that names one card is offered once to a pair, on its own, when the host has two +# cards that can share the model (setup.py's offer_together, docs/MULTI_GPU.md). +set -- --port "$PORT" +if [ -n "$GPUS" ]; then set -- "$@" --gpus "$GPUS"; fi +if [ -n "$GPU" ]; then set -- "$@" --gpu "$GPU"; fi +if [ -n "$LAYER_SPLIT" ]; then set -- "$@" --layer-split "$LAYER_SPLIT"; fi +exec .venv/bin/python setup.py "$@" diff --git a/engine/strata/docs/AI_SETUP.md b/engine/strata/docs/AI_SETUP.md new file mode 100644 index 00000000..48fd1429 --- /dev/null +++ b/engine/strata/docs/AI_SETUP.md @@ -0,0 +1,196 @@ +# Installing Strata for a user (instructions for AI agents) + +This page is written for an AI coding assistant (Claude Code, Cursor, Codex, GitHub Copilot, ...) that a user asked to +set up Strata on their PC. Strata runs the Qwen3.8-Flash-Next model locally on one NVIDIA or AMD graphics card plus +system RAM, and serves an OpenAI- and Anthropic-compatible API on `http://127.0.0.1:8080`. The human-oriented +version of everything below is [INSTALL.md](INSTALL.md). + +Work through the steps in order. Tell the user what you are doing in plain words; they may not be technical. + +## 0. Ground rules + +- **Never expose the server without an API key.** Keep the default `--host 127.0.0.1`. Only if the user asks for + access from other devices, use `--host 0.0.0.0` **together with** `--api-key `, and give the + user the key. Never put a tunnel or port forward in front of a server without a key. +- Do not change the user's system beyond what setup does (setup installs Python for the user account if needed, + and everything else inside the Strata folder and its `Strata-data` folder). Ask before installing drivers. +- The model download is ~70 GB (up to 111 GB for Unsloth's 4-bit). Confirm the user is fine with that before you + start, especially on a metered connection. +- Setup is long-running (an hour or more on a slow connection). Run it in the background or with a long timeout and + poll its output; do not kill it because it is quiet for a while. It is resumable: running the same command again + continues where it stopped. + +## 1. Check the PC + +The quickest way is setup's own check, which prints the GPU(s), driver, RAM, CPU, free disk and whether this PC can run +Strata, and installs nothing except Python and the `.venv` it needs to run (step 2 gets the repository first): + +``` +Windows: START-HERE.bat --check +Linux: ./setup.sh --check +``` + +To check by hand: + +| What | Windows (PowerShell) | Linux | +| --- | --- | --- | +| OS | `[Environment]::OSVersion` | `cat /etc/os-release` | +| NVIDIA GPU, VRAM, driver | `nvidia-smi --query-gpu=index,name,memory.total,driver_version --format=csv` | the same | +| AMD GPU | `Get-CimInstance Win32_VideoController \| Select-Object Name, AdapterRAM` (AdapterRAM is capped at 4 GB; trust the model name) | `lspci \| grep -i -E 'vga\|display'`; VRAM: `cat /sys/class/drm/card*/device/mem_info_vram_total` (bytes); `rocm-smi` only if ROCm is installed | +| RAM | `(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB` | `free -g` | +| Free disk | `Get-PSDrive -PSProvider FileSystem` | `df -h .` | + +Requirements (details: [INSTALL.md](INSTALL.md#what-you-need)): + +- **GPU:** NVIDIA RTX 20, 30, 40 or 50 series, or AMD Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, + RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series; 12 GB of VRAM or more (an NVIDIA card with 8 GB runs, + slowly). GTX 10 series and older, and integrated GPUs, are not supported. +- **Driver:** NVIDIA 580 or newer. AMD on Linux: the kernel's amdgpu driver; on Windows: a current AMD Adrenalin + driver. If the driver is missing or too old, tell the user to update it (NVIDIA App / nvidia.com/drivers, or AMD + Software) and restart; do not install drivers yourself unless they ask. +- **RAM:** 32 GB or more (see step 3). **Disk:** ~80 GB free, ideally on an NVMe SSD. **CPU:** x86-64 with AVX2. +- **OS:** Windows 10/11 or Linux (Ubuntu 22.04/24.04 are fully automatic). + +If the PC does not meet them, say which part is missing and stop. + +## 2. Get Strata + +``` +git clone https://github.com/Niko1221/Strata.git +``` + +Without git: download https://github.com/Niko1221/Strata/archive/refs/heads/main.zip and unzip it. Pick a drive with +enough free space: the model files go to a `Strata-data` folder **next to** the Strata folder (or `--data-dir ` +on another drive). + +## 3. Pick the model + +By the PC's RAM (ask the user whether they mainly want it for code - then the Coder is a good pick at any RAM size): + +| RAM | `--family` / `--model` | Notes | +| --- | --- | --- | +| 32 GB | `--family coder` (size IQ1_M) | for code; with a 24 GB card Q2_0 and IQ2_XS also run (setup picks the low-RAM mode) | +| 48 GB | `--family qwen --model IQ2_XS` | or `Q2_0` (fastest) | +| 64 GB | `--family qwen --model IQ2_XS` (recommended) | `IQ3_XXS` / `IQ3_S` are slower and a bit better | +| 96 GB+ | `--family qwen --model IQ3_S` | `--family unsloth --model UD-Q4_K_XL` is experimental: NVIDIA only, NVMe SSD, 7-8.5 tokens/s on 64 GB | + +`--family swift` (Swift 1.5, a fine-tune that thinks shorter; sizes Q2_0, IQ2_XS, IQ3_XXS) is the alternative to +`qwen`. With `--yes` and no `--model`, setup picks the recommended size for the RAM itself. More: [MODELS.md](MODELS.md). + +## 4. Run setup without questions + +From the Strata folder (Windows: in `cmd`, or `cmd /c START-HERE.bat ...` from PowerShell): + +``` +Windows: START-HERE.bat --yes --family qwen --model IQ2_XS --no-start +Linux: ./setup.sh --yes --family qwen --model IQ2_XS --no-start +``` + +The flags (all of them: `START-HERE.bat --help`): + +| Flag | Meaning | +| --- | --- | +| `--yes` | take the recommended answer to every question (no prompts) | +| `--family qwen\|swift\|coder\|unsloth` | the model version | +| `--model Q2_0\|IQ2_XS\|IQ3_XXS\|IQ3_S\|IQ1_M\|UD-Q4_K_XL` | the size (the Coder is IQ1_M, Unsloth UD-Q4_K_XL) | +| `--context N` | context in tokens; default by VRAM: 32768 under 14 GB, 65536 under 20 GB, else 131072 | +| `--vision yes\|no\|gpu\|cpu` | read pictures; `--yes` leaves images off. AMD cards: `cpu` | +| `--gpu N` / `--gpus 0,1` / `--gpus all` | one card, or several sharing the model (default: the card with the most VRAM) | +| `--backend cuda\|hip` | NVIDIA or AMD engine; chosen by itself on a PC with only one kind of card | +| `--data-dir PATH` | where the 70-120 GB of model files go | +| `--port N` | the server port (default 8080) | +| `--host H --api-key K` | listen beyond this PC; **only together with a key** | +| `--no-start` | install only, do not start the server | +| `--setup` | install another model or change settings of an installed one | +| `--check` | only check the PC | + +`--no-start` is recommended for agents: the server runs in the foreground until its window is closed, which would +block your shell. Start it separately in step 6. + +Notes: +- **Linux:** setup uses `sudo apt` (or dnf/pacman) to install Python with venv if it is missing, and on AMD may need + `build-essential` and `git`. You cannot type the user's password: if a `sudo` step is needed, ask the user to run it + (e.g. `sudo apt install python3-venv build-essential git`) and then rerun setup. +- **AMD on Linux:** setup installs ROCm into `.venv` (~10 GB, no sudo) unless a system ROCm 7 exists, and compiles the + engine for the card (10-20 minutes, once). +- **AMD on Windows (new in 0.1.34):** setup downloads the ready-made AMD engine (~550 MB, ROCm included) - nothing + is compiled and only the AMD driver is needed. Before the model download it runs `engine\strata-device.exe + --list-devices`; if that does not list the card, the driver is the problem (tell the user to update AMD Software). + One card per model and no images on Windows for now. It is new: ask the user to report how it runs (docs/AMD_HIP.md). +- **NVIDIA with no ready-made engine for the card:** setup offers to install build tools and compile (20-40 minutes); + `--yes` accepts. + +## 5. While it downloads, tell the user + +- It downloads about 70 GB from Hugging Face; how long depends on their connection (at 100 Mbit/s roughly 1.5-2 + hours). It can be stopped and continues where it left off. +- Then it prepares the model for their PC (a few minutes) and, on AMD on Linux, compiles the engine. +- **When the model starts, the PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata + loads 35-55 GB into RAM and locks part of it for the graphics card. That is normal; they should not close the window. +- Nothing leaves their PC: the model runs locally. + +## 6. Start the server + +Setup prints the start script it wrote (`start script: run-.bat`). The name is the family tag plus the size, +lower case: `run-iq2_xs`, `run-swift-iq2_xs`, `run-coder-iq1_m`, `run-unsloth-ud-q4_k_xl`. + +``` +Windows (PowerShell): Start-Process -FilePath ".\run-iq2_xs.bat" (opens its own window) +Linux: nohup ./run-iq2_xs.sh > strata-server.out 2>&1 & +``` + +Or `START-HERE.bat` / `./setup.sh` without flags, which starts the installed model (it asks which one when several are +installed; add `--yes` to take the first). The server opens the user's browser on `http://127.0.0.1:8080` when it is +ready. Closing its window (or stopping the process) stops the model. + +## 7. Verify + +The HTTP server answers once the model is loaded (30-90 s on later starts, a few minutes the first time). Poll: + +``` +curl http://127.0.0.1:8080/health +``` + +It returns `{"status": "ok", "model": ..., "max_context": ..., "images": ..., "api_key": ..., "loaded": true, ...}`. +Then: + +``` +curl http://127.0.0.1:8080/v1/models +curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d "{\"model\": \"strata\", \"messages\": [{\"role\": \"user\", \"content\": \"Say hello in five words.\"}], \"max_tokens\": 64, \"reasoning_effort\": \"none\"}" +``` + +With an API key, add `-H "Authorization: Bearer "`. The server window prints a `ready: http://127.0.0.1:8080/v1` +line when it is ready; the engine log is `strata-.log` in the Strata folder. + +## 8. Connect the user's apps + +- **Browser:** `http://127.0.0.1:8080` - Chat, a live Monitor, and About (settings and addresses). +- **Any OpenAI-compatible app or agent:** base URL `http://127.0.0.1:8080/v1`, any API key (or the configured one), + any model name. +- **Anthropic-compatible apps:** `http://127.0.0.1:8080/v1/messages`. +- **Claude Code:** `ANTHROPIC_BASE_URL=http://127.0.0.1:8080`, `ANTHROPIC_MODEL` set to a Claude model name it knows + (Strata ignores the name), and any `ANTHROPIC_AUTH_TOKEN` (or the configured key). +- **Thinking level:** `"reasoning_effort": "none" | "low" | "medium" | "high"` (default high). +- Strata answers one request at a time. API details: [DETAILS.md](DETAILS.md#using-it). + +## 9. When something fails + +| Symptom | What to do | +| --- | --- | +| `the NVIDIA driver is too old` | The user updates the driver (NVIDIA App or nvidia.com/drivers) and restarts; rerun setup. | +| Download or install stopped | Rerun the same setup command; it continues. | +| `port 8080 is already in use` | Strata is already running (check `/health`), or use `--port 8081`. | +| Very slow, disk busy, or "the engine stopped unexpectedly" | Not enough free RAM: close programs, or set up a smaller size (`--setup --model Q2_0` or IQ2_XS). | +| `ExpertCache: cudaMalloc(...) failed: out of memory` with free VRAM (Windows) | The page file is off or tiny: set it to "System managed" and restart. | +| `prompt ... exceeds the context` | Rerun setup with `--setup --context `. | +| No AMD GPU found (Linux) | The amdgpu driver lists no GPU; check the card and driver. Integrated GPUs are not supported. | +| Python or build tools could not be installed | Install what the message names (links are printed), then rerun. | + +More: [TROUBLESHOOTING.md](TROUBLESHOOTING.md) and the [full table](DETAILS.md#troubleshooting). If it still fails, +collect `strata-.log` and the setup output, and suggest an issue at https://github.com/Niko1221/Strata/issues. + +## Alternative: the MCP server + +Strata also has an MCP server, so an AI tool can check, install, start and stop Strata through tool calls +(`strata_status`, `strata_models`, `strata_install`, `strata_start`, `strata_stop`, `strata_logs`) instead of the +shell commands above. See [MCP_SERVER.md](MCP_SERVER.md). diff --git a/engine/strata/docs/AMD_HIP.md b/engine/strata/docs/AMD_HIP.md new file mode 100644 index 00000000..da311bc2 --- /dev/null +++ b/engine/strata/docs/AMD_HIP.md @@ -0,0 +1,405 @@ +# AMD Radeon: the HIP backend (gfx1100, gfx1101, gfx1200, gfx1201, gfx1030) + +Strata runs on AMD Radeon cards through its HIP backend, the same engine as on NVIDIA compiled for AMD. This page +covers the build on Linux (on Windows a ready-made engine, see [Windows](#windows)) for the RX 7900 XT / XTX (RDNA3, gfx1100) and the +RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). The RX 7800 XT / 7700 XT +(gfx1101) and the RX 9060 XT (gfx1200) were validated by their owners (see [Community-validated +cards](#community-validated-cards)); the RX 6800 / 6900 series (RDNA2, gfx1030) builds and runs too, reported by a community machine and not yet validated by the maintainers (see [RDNA2](#rdna2-gfx1030)). Setup chooses it by itself on a PC with no NVIDIA card Strata can use (`--backend hip` on a PC with both); the +install steps for users are in [INSTALL.md](INSTALL.md#amd-cards). Other AMD architectures, wave64, and mixed +AMD/NVIDIA execution in one run are not supported. + +The backend maps the CUDA-shaped runtime and BLAS calls to HIP/hipBLAS, uses +RDNA2/RDNA3/RDNA4's signed integer dot instruction for quantized kernels, and supplies +wave32 shuffle/packed-byte operations. CUDA-only QSA matrix instructions have +an ordered FP32 fallback. Prefill supports both dequantization plus hipBLAS GEMM and opt-in HIP ggml MMQ. +An optional, calibrated hipBLASLt path accelerates dense projections (per-architecture tables in `tools/hip`). +This does not claim bit-identical model answers across backends. See +[performance settings and evidence](AMD_HIP_PERFORMANCE.md). + +## Install with setup (recommended) + +On Linux with an RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT or Radeon AI PRO R9700 and +the kernel's amdgpu driver (no ROCm install needed): + +```sh +./setup.sh --backend hip +``` + +- **Detection:** setup finds the card through the kernel's KFD topology. Integrated Radeon GPUs are listed as not + supported. On a PC without an NVIDIA card Strata can use, `--backend hip` is chosen automatically. +- **ROCm:** a system ROCm 7 in `/opt/rocm` (or `$ROCM_PATH`) with hipcc and hipBLAS is used when present. Otherwise + (or when it is older than 7.0) ROCm is installed into `.venv` from AMD's TheRock wheels (~10 GB, no sudo), pinned + to the version this backend was tested with, from the card family's index: `gfx110X-dgpu` for gfx1100 / gfx1101, + `gfx120X-all` for gfx1200 / gfx1201, `gfx103X-all` for gfx1030 (`STRATA_ROCM_VERSION` / + `STRATA_ROCM_INDEX` override them; the gfx1030 index is not checked to carry the pinned version: a system + ROCm 7 is the tested path there). +- **Engine:** compiled on your PC for the card's architecture (10-20 minutes, once; again after a `git pull` that + changes it, or when you pick a card of another architecture). This needs a C++ compiler and git + (`sudo apt install build-essential git`). +- **hipBLASLt tuning table:** setup uses `tools/hip/-hipblaslt-.txt` only when it matches both the + card's architecture and the installed hipBLASLt version (read from `hipblaslt-version.h`; 1.2.0 is `100200`). + Otherwise it says so and the prompt's dense matrix products use plain hipBLAS (slower prompts, same answers). + A table's solution ids are valid only for that pair, and the engine refuses any other table. +- **Several cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: + `./setup.sh --backend hip --gpus 1,0` splits the model's layers across them, the first one the main card (numbers + as setup lists them; `--gpus all` = every supported card, the most VRAM first). Every chosen card must be one of the + architectures above; the engine is compiled for each of them (cards of two families, e.g. gfx1100 + gfx1201, need + a system ROCm 7: AMD's wheels hold one family). A split pays only when no single card holds the model's experts + (see RDNA4 below). +- **Limits for now:** images only through the CPU encoder (`--vision cpu`, 0.1.32), no calibration. The Monitor + shows the card's load, VRAM, temperature and power from Linux sysfs (0.1.32). + +The rest of setup is the same as on NVIDIA: the model download, the start script, the server. + +## Windows + +Since 0.1.34 an AMD card on Windows is set up like an NVIDIA one: download Strata, double-click `START-HERE.bat`. +On a PC with no NVIDIA card Strata can use, the AMD card is chosen by itself; with both, setup asks +(`START-HERE.bat --backend hip` picks AMD directly). + +- **You need:** Windows 10 or 11 (64-bit), one of the cards above, and a current AMD driver ([AMD Software: + Adrenalin Edition](https://www.amd.com/en/support/download/drivers.html)). Nothing else: no ROCm or HIP SDK + install, no compiler, no admin rights. +- **Detection:** setup reads the display adapters Windows lists (their PCI ids; the VRAM size from the display + driver's registry entry). An integrated Radeon is listed as not supported. +- **Engine:** the ready-made `strata-windows-x64-hip.zip` from the release (built by `tools\hip\build_windows.bat` + for gfx1100, gfx1101, gfx1102, gfx1200, gfx1201 and gfx1030) goes into `engine\`. It carries the ROCm libraries the + engine loads (`engine\rocm\bin`: the HIP runtime, hipBLAS / rocBLAS / hipBLASLt with their kernels for these cards, + amd_comgr and the Microsoft C++ runtime; ROCm 10.2.0a20260930 from AMD's TheRock builds, licenses in + `engine\rocm\licenses`). The HIP runtime works through the AMD driver's own components, so the driver is the one + thing it needs from the PC. +- **The HIP runtime next to `strata.exe` (0.1.35, #468 #461):** `amdhip64_7.dll` and `amd_comgr.dll` are also put in + `engine\` (setup copies them there on every start). Windows looks in the program's folder before System32, where + some AMD drivers install their own `amdhip64_7.dll`; with that one, the bundled libraries crashed on the first + prompt (an access violation, or `hipErrorInvalidDeviceFunction`). The engine's log names the runtime it loaded + (`strata generate: HIP runtime ...`). +- **Before the ~60 GB model download** setup runs `engine\strata-device.exe --list-devices` (with `engine\rocm\bin` on + the PATH): if the HIP runtime does not see the card, setup stops there and points to the driver. It also gives the + card's HIP number: with an integrated Radeon that is device 1, not 0 (#325). From then on setup lists the AMD cards + as HIP numbers them, so `--gpu N` and the config's `"gpu"` are HIP numbers. +- **Differences from Windows-on-NVIDIA and Linux-on-AMD:** no images yet (the CPU image encoder is Linux-only for + now), one card per model (`--gpus` is Linux-only for now), no calibration. +- Two Windows-only engine details (#247, #325): hipBLAS can return success and still leave `hipErrorInvalidValue` + set after some BF16/FP16 GEMMs (seen on gfx1201); the engine clears that one stale error after a GEMM that + succeeded, on Windows only. `hipHostGetDevicePointer` returns the host pointer itself on Windows: kernels read + mapped memory through it correctly, but a device-to-device copy into it does not land, which is why + `tests/hip/handoff` times out there (the engine does not use that copy; `tests/hip/mapped_alias` reports it). + +**What is validated (0.1.34):** #325's author ran the engine of this port on an RX 9070 XT (Windows 11, ROCm +10.2.0a20260930 in `.venv`, compiled on the PC): Coder IQ1_M at 32K, 29.2 tok/s decode, ~181 tok/s prefill, +correct answers; ctest 42 of 46. The maintainers have no Windows AMD card: the release zip was built on an NVIDIA PC, +and checked there on the Ryzen CPU's integrated Radeon (gfx1036, a test build of the same tree): with only the zip's +libraries on the PATH, `strata-device` lists the card and a hipBLAS BF16 GEMM matches the CPU; the HIP ctest passes +52 of 56, the 4 failures the same as on the RX 9070 XT (`hip_handoff`, and three tests that need a pack fixture). +The ready-made zip itself has not run a model on a discrete card yet - please report. + +**Reporting a Windows AMD run** (an issue, or on #325): your card and driver version (AMD Software > System), then + +```bat +engine\strata-device.exe --list-devices +engine\strata-device.exe --selftest +``` + +(from the Strata folder, after `set PATH=%CD%\engine\rocm\bin;%PATH%`), the end of `strata-.log`, and the +speed lines the server window prints for a first answer. + +**Building it yourself:** `tools\hip\build_windows.bat` (Visual Studio 2022 Build Tools with the C++ workload, Python, +git; no admin, no AMD GPU) installs ROCm from AMD's TheRock wheels into `.rocm-win`, builds, and packages +`dist\strata-windows-x64-hip.zip`; `START-HERE.bat --backend hip --prebuilt dist\` installs that one. +`tools\hip\build_windows.bat tests` also builds the HIP tests (`ctest` in `build-hip-win`, with +`.rocm-win\Lib\site-packages\_rocm_sdk_devel\bin` on the PATH). `STRATA_HIP_ARCHS` picks other architectures. + +## Build + +Requirements: a working ROCm driver/runtime, HIP development headers and +compiler, hipBLAS and (for tuned dense prefill) hipBLASLt development files, CMake 3.24+, a C++20 host compiler, and Git. +The model still needs sufficient system RAM and fast SSD storage for its PLE +table. VRAM occupancy alone is not a throughput measurement. + +```sh +cmake -S . -B build-hip \ + -DCMAKE_BUILD_TYPE=Release \ + -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF \ + -DCMAKE_HIP_ARCHITECTURES=gfx1100 +cmake --build build-hip --target strata -j2 +``` + +`CMAKE_HIP_ARCHITECTURES` is `gfx1100`, `gfx1101`, `gfx1200`, `gfx1201`, or a list such as `"gfx1100;gfx1201"` +(one binary for both). gfx1102 (the same wave32, 64 KiB LDS and dot4 instruction) builds with a warning: it passed +ctest (#192) but no model run has been reported; so does gfx1030 (RDNA2: the older `v_dot4_i32_i8`, a community run in #311). At startup the engine and `strata-device` compare each GPU they use +(`gcnArchName` up to the `:` feature suffix) with the architectures the binary was compiled for, and require +wave32. A binary carried to another card stops with the card's name, its architecture and the build's list, +instead of failing later with "invalid device function". + +If CMake cannot find the HIP compiler, add +`-DCMAKE_HIP_COMPILER=/path/to/rocm/llvm/bin/clang++`. On the Fedora-family test +host this was `/usr/lib64/rocm/llvm/bin/clang++`. Use the compiler and libraries +from the same ROCm installation. Do not enable both GPU backends in one build. + +Native IQ experts are enabled by default. CMake fetches the llama.cpp revision +pinned by this repository. For an offline build, point `STRATA_GGML_DIR` at a +checkout of that exact revision; using an arbitrary newer checkout changes the +dependency being tested. + +## Model and serving configuration + +Prepare a supported model pack and its MTP runtime using the existing tools. +For OrcaRouter IQ3_XXS, follow [the explicit compatibility conversion](ORCA.md); +this backend does not change quantization, model licenses, or tokenizers. +Add `--experts-bin` to the `tools/iq_pack.py` command: mmap requires the pack's +`experts.bin`, which the default native packing command does not emit. This +consumes additional disk space. Original GSQ-RCO IQ3_XXS uses shard 2 for PLE; +Orca uses shard 1. Keep each model's own pack and tokenizer together. + +Use `build-hip/strata` as the executable in the server JSON. Select the AMD +device with `ROCR_VISIBLE_DEVICES`/`HIP_VISIBLE_DEVICES` if necessary. Start with +a modest context and prefill chunk size before measuring larger workloads. +Keep the PLE file on an SSD. Do not assume a configured context length proves +successful full-window inference. + +Large pinned host allocations can fail on ROCm even when ordinary RAM is +available. The existing `--mmap-experts` path avoids allocating the full pinned +expert arena; it still depends on OS file-cache residency and may stall on +storage reads. It does not make SSD access equivalent to RAM. + +Starting args for the original GSQ-RCO IQ3_XXS model (replace the paths): + +```sh +build-hip/strata --serve \ + --pack packs/iq3xxs \ + --native /path/to/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf \ + --ple-gguf /path/to/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf \ + --mmap-experts --expert-profile data/expert-profile.bin --expert-cache auto \ + --prefill 512 --spec 4 --spec-min-p 0.5 --mtp mtp/rt \ + --max-context 4096 --kv int8 --pool-workers 15 \ + --adapt-every 0 --pcie-frac 0 --vram-reserve-mib 1024 +``` + +`--serve` is the engine's internal token protocol. For a browser or OpenAI API, +put these args in the `args` array of the [server JSON example](ORCA.md#local-server), +set `exe` to `build-hip/strata`, and use the matching pack's `tokenizer` directory. +Launch with `.venv/bin/python -m serve.server --engine strata --config strata-hip.json --port 8080`. +The worker count above was used on a 16-core CPU; measure it for your CPU. +The 4K context is a smoke-test starting point, not a model limit. The expert cache +sizes itself automatically and leaves 1 GiB of VRAM headroom. + +The installer supports this backend (see "Install with setup" above). Images run through the CPU encoder for now (`--vision cpu`). +Setup installs one AMD card, or several with `--gpus` (the engine's layer split; see RDNA4 below). + +## RDNA4 (gfx1201) + +The RX 9070 / 9070 XT and the Radeon AI PRO R9700 run the same kernels as gfx1100: wave32, 64 KiB of LDS per +workgroup, the signed dot4 instruction (`v_dot4_i32_iu8` through `__builtin_amdgcn_sudot4`) and a 100 MHz wall +clock. The first report and patch came from doplxyz (#178). Validated on 2026-09-30 on doplxyz's test machine: +an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 3900X (16 threads, no AVX-512), +47 GB RAM, Ubuntu 24.04 in a KVM/VFIO guest. + +- **Build:** complete HIP build with tests (`-DCMAKE_HIP_ARCHITECTURES=gfx1201 -DSTRATA_BUILD_TESTS=ON + -DSTRATA_PREFILL_MMQ=ON`), with the system ROCm 7.14 (hipBLASLt 1.4.1) and with setup's own path: TheRock + 7.10.0a20251120 wheels from `gfx120X-all` (hipBLASLt 1.2.0) and `build_engine_hip`. +- **ctest** (all 45 registered tests, R9700): 42 pass, `hip_prefill_hipblaslt_gemm` skips (no table), and two + fail for reasons outside the GPU: `ple_parity` needs the Q2_0 model fixture, `expert_multi_test` needs an + AVX-512 CPU. `hip_handoff` needed the volatile ring store: on gfx1201 a plain store to mapped pinned memory + stays in the GPU's L2 until the stream is synchronized. +- **Arch check:** a gfx1100-only build stops on the gfx1201 card at startup with the message above (engine and + `strata-device`). +- **End to end** (Coder IQ1_M, setup's arguments: `--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5`, + MTP, `--kv int8`, `--max-context 32768`; 128 greedy tokens, system ROCm 7.14, no hipBLASLt table). The answers + are coherent and the same on both cards. The live server smoke (`serve/server.py`: web page, models, props, + chat, prefix reuse, streaming, the Anthropic endpoint, a sampled code answer) passed 9/9 on each card. + + | card | expert cache | peak VRAM | 4K prompt | 4K decode | 16K prompt | 16K decode | + |---|---|---|---|---|---|---| + | Radeon AI PRO R9700 32 GB | 12,288 slots, 23.4 GiB | 29.7 GiB | 982 tok/s | 45.5 tok/s | 1,402 tok/s | 48.3 tok/s | + | RX 9070 XT 16 GB | 4,931 slots, 9.4 GiB | 15.6 GiB | 782 tok/s | 30.8 tok/s | 1,235 tok/s | 35.4 tok/s | + | R9700, TheRock 7.10 wheels | 12,288 slots | | 957 tok/s | 44.2 tok/s | 1,284 tok/s | 43.9 tok/s | + + The engine's resident memory was about 26 GB in every run. Since 0.1.31 `__byte_perm` is one `v_perm_b32` and the + packed byte subtracts/compare work on four lanes at once (#262, ttio2tech): decode +15% on the R9700 (46.0 -> 53.0 + tok/s on a 4K prompt, 52.0 -> 60.5 warm) and +5-7% on the 9070 XT, prompts unchanged, the same tokens. +- **hipBLASLt:** the validation above used hipBLASLt 1.4.1. A table calibrated on the R9700 at the engine's shapes + with that version (0.98-1.76x per GEMM over hipBLAS) changed the end-to-end prompt speed by 0-3%, within noise, + so none was shipped for it: there the plain hipBLAS path is already close. For hipBLASLt 1.5.0 (ROCm + 10.2.0a nightly) `tools/hip/gfx1201-hipblaslt-100500.txt` is shipped (see "Tuning table" below); on one R9700 it + measured +3.9% prompt speed on 4,210-token prompts (1,590 vs 1,531 tok/s), a modest gain. +- **Both cards in one run (layer split, engine 0.1.30):** the config's `"backend": "hip", "gpu": [1, 0]` (R9700 + first) runs through `serve/server.py` (setup writes it with `--gpus 1,0` since 0.1.31). Auto split put layers 0-27 on the R9700 and + 28-47 on the 9070 XT. With every expert on the GPUs the split gives exactly the tokens of the R9700 alone (4K and + 16K prompts); checkpoints on the split (second turn, rewind, a prompt sharing a prefix, a cancelled prompt + retried) give exactly the tokens of a fresh read. The conversation cache refuses a split at start (exit 2). + On this pair the split does not pay: the R9700 alone already holds all 12,288 expert pairs. + + | run (the same session, warm) | 4K prompt | 16K prompt | decode | + |---|---|---|---| + | R9700 alone | 1,794 tok/s | 1,804 tok/s | 51-52 tok/s | + | R9700 + 9070 XT, auto split | 1,384 tok/s | 1,906 tok/s | 42-43 tok/s | + | RX 9070 XT alone | 1,016 tok/s | 1,519 tok/s | 38-40 tok/s | + + A split is worth it when no single card holds the model's experts. Since 0.1.31 a split pins the whole expert + arena on Linux (the 8 GiB cap is for Windows/WSL2 only, #253): with an expert cache of 1,500 on the R9700 (most + experts streamed) the split read a 16K prompt at 1,803 tok/s instead of 1,287, with the same tokens in 5 + 5 + starts. `"split_skip_if_fits": true` in the config (0.1.31, opt-in) runs such a pair on the first card alone when it + holds every profiled expert: with the R9700 first, 4K prompts 1,776 tok/s (split: 1,244) and decode ~60 tok/s + (split: ~51), the tokens of the R9700 alone (docs/MULTI_GPU.md). +- **Speed switches (engine 0.1.32, measured on the R9700 / 9070 XT with the Coder IQ1_M pack):** + - the MoE router (`router_top10`) runs a HIP kernel without its serial FP64 sum and block barriers by default: the + same ids and weights bit for bit (`hip_router_fast` checks 65,536 rows), 39 -> 9-12 us per call, the same greedy + tokens (5 + 5 starts). Decode: 62.4 -> 70.0 tok/s on the R9700 and +4% on the 9070 XT in one A/B here (ROCm 10.2 + nightly); a user's repeated A/B/A/B with setup's TheRock 7.10 wheels and an i5-12600K measured +1-4%, inside a + 12-20% run-to-run spread (#432) - how much it gains depends on how much of decode the router is on that setup. + `STRATA_HIP_ROUTER_OLD=1` runs the portable kernel. + - `STRATA_HIP_WMMA=1` (opt-in, gfx12 only, int8 KV): the prompt path's QSA attention on RDNA4 matrix cores + (`v_wmma_f32_16x16x16_f16`, FP16 hi + lo halves like the CUDA tensor-core kernel; `hip_prompt_attn_wmma` bounds it + against the FP32 kernel and FP64). 7.2-7.5x the portable kernel; R9700 prompts 4K 1,784 -> 2,427 tok/s, 16K + 1,797 -> 2,700 (a user with TheRock 7.10: +29-34%, #432). Not bitwise: greedy text differs from token ~50 on, as with the CUDA tensor-core attention. With it + the prompt path's expert ring is 96 slots (as STRATA_PREFILL_RING=96): with the default 384 the 9070 XT's 4K + prompts fell to 718 tok/s; with 96 they gain (1,017 -> 1,211; 16K 1,518 -> 2,032). PR #329 + (bsorensen110) contributed an equivalent gfx12 WMMA kernel of the same speed (within 1%); this one also masks KV + pages that KV streaming has not made resident, as the decode kernel does. + - The prompt path's QSA top-k picks its kernel by the blocks a query actually has, not the cache's capacity (#337, + bsorensen110): the same ids, on by default with AMD (NVIDIA keeps its capacity rule: there the 64K prompts read + 1-3% slower with it). `STRATA_SELECT_WMMA=1` (opt-in, gfx12) adds #337's + matrix-core block scorer; it selects slightly differently (254 of 256 queries the same) and gained +1.5% on 16K + prompts at a 262K context on the R9700. +- **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on + one card or two and on engine 0.1.29 as well; not yet explained. +- **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. + +## Community-validated cards + +Run by their owners, not on the maintainers' machines; setup accepts them like gfx1100 / gfx1201. No hipBLASLt table +is shipped for them (make one with [Tuning table](#tuning-table) and compare the prompt speed with and without it). + +- **gfx1101, RX 7800 XT 16 GB** (jhohertz, #254; engine 0.1.29, Ryzen 9 5950X, 121 GiB RAM, system ROCm with + hipBLASLt 1.4.1): `./setup.sh --backend hip` detected the card and compiled the engine; `strata-device --selftest` + passed; ctest 30/32 (`ple_parity` needs the Q2_0 fixture, `platform_memory_test` the memlock limit). Coder IQ1_M, + 64K context, MTP, with a table the owner calibrated: fresh prompts of 4K-9K tokens at 898-953 tok/s, decode + 38-44 tok/s (128 tokens). +- **gfx1200, RX 9060 XT 16 GB** (Efeisot, #256 after #176; engine 0.1.29, Ryzen 9 7950X, 64 GiB RAM, ROCm 7.2 with + hipBLASLt 1.2.2): ctest 32/32 (without `ple_parity` and `platform_memory_test`). Coder IQ1_M, greedy, MTP + `--spec 4 --spec-min-p 0.5`, with a table the owner calibrated: + + | prompt | prompt speed | decode | + |---|---|---| + | 2,374 tokens | 540 tok/s | 27.1 tok/s (0.69 draft acceptance; 31.0 at 1.00) | + | 65K (`--kv int8 --kv-resident 65536 --prefill 16384`) | 748-753 tok/s | 26-40 tok/s by acceptance | + | 130K (the same flags) | 725 tok/s | - | + + Greedy output was the same across runs. For comparison, llama.cpp's HIP build measured 20 tok/s decode and + 450 tok/s prompt on that card. + +## RDNA2 (gfx1030) + +The RX 6800 / 6800 XT / 6900 XT / 6950 XT run the same kernels: wave32 and 64 KiB of LDS per workgroup. The one +difference is the dot instruction: RDNA2 has no `v_dot4_i32_iu8` (gfx11 and newer), so +`dp4a` uses the plain signed `v_dot4_i32_i8` through `__builtin_amdgcn_sdot4`, which compiles to a single +`v_dot4c_i32_i8` (same signed x signed byte products, modulo 2^32). There is no WMMA; the QSA scorer takes the +same ordered FP32 fallback as gfx1100. CMake lists gfx1030 as unvalidated (the build warns) until a maintainer has +run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx1030), an i7-13700KF (8 P-cores and +8 E-cores, AVX2, no AVX-512), 63 GB RAM, NixOS, ROCm 7.2.3 from nixpkgs (clang 22, hipBLAS 3.2). + +- **Build and tests** (engine 0.1.26): a complete HIP build for gfx1030, made by hand with cmake and ROCm's own + `clang++` (the nixpkgs ROCm is not an `/opt/rocm` tree, so setup's `build_engine_hip` was not exercised; the + binary was placed in `engine/` for setup to use). All 28 registered ctest tests pass on the card, including + `hip_device_selftest`. An engine 0.1.30 build of this branch configures, builds and runs clean on the same card; + the speeds below are measured on it. +- **End to end** (Swift 1.5 IQ3_XXS, `--context 131072` with `--kv-resident 32768 --adapt-every 1 + --vram-reserve-mib 1024`, 200 greedy tokens): 38-42 tok/s decode with the default 15 CPU pool workers (one per + physical core except the host thread; 8 workers: 36; 24 = every logical core: 27), consistent even with the + 131,072-token context full. +- **Prefill** (the same 15-worker configuration): 246 tok/s on a 2,000-token prompt, 330-339 tok/s at the auto + 8,192-token chunk (7,997 and 15,967 tokens; time to first token 8.9 and 48.3 s), 133 tok/s on a 522-token + prompt - short prompts are fixed overhead (19-25 tok/s on 34 tokens). Decode after a 16K prefill holds at + 45.5 tok/s. +- **16 GB card:** the expert cache holds 6,310 slots (10.2 GiB) at 16K context and 5,247 slots at 131,072, where + setup keeps the KV cache in VRAM because IQ3_XXS needs about 60 GB of RAM plus the cache to stream it. The + `--pcie-frac 0` and `--adapt-every 0` of the 7900 XTX configuration in + [AMD_HIP_PERFORMANCE.md](AMD_HIP_PERFORMANCE.md) cost 8.6 and 13.6 tok/s here (30 with the defaults): keep the + defaults on a 16 GB card. +- **hipBLASLt:** ROCm's hipBLASLt ships no gfx1030 kernels, so there is no table and the plain hipBLAS path runs. +- **Not validated:** gfx1031 / gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the + `gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks. + +## Tuning table + +A hipBLASLt table holds solution ids that are valid only for one GPU architecture and one hipBLASLt version, so it +is calibrated on the card with the ROCm the engine runs with. The shipped gfx1100 table's rows are the engine's +dense GEMM shapes; to calibrate them for another card or version (a few minutes): + +```sh +cmake --build build-hip --target tune_hipblaslt +CASES=$(awk 'NR>2 {printf " --case %s,%s,%s,%s,%s", $1, $5, $2, $3, $4}' tools/hip/gfx1100-hipblaslt-100200.txt) +./build-hip/tune_hipblaslt $CASES --tuning-out table.txt +``` + +The file's second line names the architecture and version (`STRATA_HIPBLASLT_TUNING_V1 gfx1201 100401`); save it +as `tools/hip/-hipblaslt-.txt` for setup, or point `STRATA_HIPBLASLT_TUNING` at it. Compare the +prompt speed with and without it before keeping it. + +Shipped tables: + +- `gfx1100-hipblaslt-100100.txt`, `gfx1100-hipblaslt-100200.txt`: RX 7900 XTX. +- `gfx1201-hipblaslt-100500.txt`: Radeon AI PRO R9700 (gfx1201, 32 GB), calibrated with ROCm 10.2.0a20260914 + (AMD's `gfx120X-all` nightly, hipBLASLt 1.5.0, library build `d3164197`). 16 dense GEMM geometries at T=4096 and + T=8192, 32 rows. setup uses it only when the installed hipBLASLt reports 1.5.0 (it is found in `/opt/rocm` + when that is a system ROCm 7 or newer). The version number is the only thing the engine can check, so another + 1.5.0 build could number its solutions differently. `hip_prefill_hipblaslt_gemm` (with `STRATA_HIPBLASLT_TUNING` + set) is a smoke test: it refuses a table for another architecture or version and checks that one BF16 and one + F16 row exist and agree with hipBLASEx, which covers 2 of the 32 rows. It does not prove that a solution id is + valid: the engine falls back to hipBLASEx for an id the library rejects, and the test still passes. Run it with + `STRATA_HIPBLASLT_VERBOSE=1` and look for `fallbacks=0` in its summary line, and recalibrate with + `tune_hipblaslt` before using this table with a different 1.5.0 build. + +## Original backend validation (PR #94) + +The following is historical validation of the original backend, not a fresh +test count for this replacement. Current build/test evidence and performance +limits are recorded in [AMD_HIP_PERFORMANCE.md](AMD_HIP_PERFORMANCE.md). + +Tested against upstream `c1e903310f211e6630780c3bd2038778c071c68d` (0.1.20), +with pinned llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`. +The host has an RX 7900 XTX (24 GiB), Ryzen 9 7950X3D, 64 GiB system RAM, +and Fedora-family Linux with ROCm 7.1.52802 / Clang 20. The original model used +for the smoke check was on mechanical RAID0; cold page faults were slow. Keep +latency-sensitive data on SSD and measure warm residency separately. + +- Complete HIP Release build, including the executable and parity targets. +- All 25 tests selected by the command below passed on 2026-09-29. +- Intrinsic parity includes signed packed-byte dot products and overflow. +- CPU/GPU mapped-memory handoff covers delayed publication, changing payloads, + and repeated graph replay in both directions. +- GR coverage includes the maximum eight-token fused batch and graph replay + after inputs change. Native QSA checks the scalar HIP fallback. +- Q8_K quantization is byte-exact against the existing reference. HIP's + `__fmul_rn` can become ordinary multiplication; disabling contraction in + `quantize_act.cu` preserves the separately rounded product before the magic + rounding bias is added. CUDA's compile flags remain unchanged. +- The mmap regression covers canonical and differing native layer sizes, + truncated/oversized files, lookup bounds, and reopening after errors. +- CUDA 13 / GCC 15 / sm_89 executable build passed; GR, sampler, quantization, + and mmap tests passed on the same tree. This is a regression check, not a + claim of complete CUDA inference validation. +- CPU-only `strata-plan` build passed without either GPU backend. +- Real GSQ-RCO IQ3_XXS server smoke with mmap, the shipped expert profile, + automatic GPU cache, and MTP passed arithmetic, executable Python addition, + system-marker recall, and 1,170-token batched-prefill recall. All four requests + ended normally with correct answers; one engine process served them all. + The cache held 11,142 experts (18.08 GiB), with 874 MiB of VRAM free after + startup. These short checks do not establish a throughput or quality benchmark. + +Build all targets before running the registered focused checks: + +```sh +cmake --build build-hip -j2 +ctest --test-dir build-hip --output-on-failure --timeout 60 \ + -E '^(ple_parity|platform_memory_test)$' +``` + +`ple_parity` requires an external model fixture. `platform_memory_test` requests +256 MiB of locked memory; the test shell's 8 MiB memlock limit prevented that +test from passing. These are explicit exclusions, not skipped tests counted as +passes. Additional unpublished upstream fixture suites are not covered. + +The published performance table explicitly identifies the measured development +snapshot; it must not be read as a benchmark of every subsequent rebase. Vision, long-context stress, broad answer-quality +equivalence, other AMD cards, and mixed-vendor inference are not validated here. diff --git a/engine/strata/docs/AMD_HIP_PERFORMANCE.md b/engine/strata/docs/AMD_HIP_PERFORMANCE.md new file mode 100644 index 00000000..1816c2f9 --- /dev/null +++ b/engine/strata/docs/AMD_HIP_PERFORMANCE.md @@ -0,0 +1,145 @@ +# RX 7900 XTX support and performance evidence + +This opt-in Linux `gfx1100` backend supersedes the initial support in +[PR #94](https://github.com/Niko1221/Strata/pull/94). It retains HIP runtime and +wave32 integer-dot compatibility, native mmap layout validation, and MTP, then +adds HIP MMQ, optional calibrated dense hipBLASLt GEMM, native prefill batching, +and the host-memory / SSD paths used by the measured configuration. HIP blocking +expert uploads use one reusable pinned staging buffer, including prompt-cache +refills, to avoid repeated pageable-source registrations. + +## Reproduce the configuration + +Build instructions are in [AMD_HIP.md](AMD_HIP.md). Use the repository-pinned +llama.cpp dependency; do not silently substitute another revision. Build with +`STRATA_PREFILL_MMQ=ON` and use these runtime variables for the measured arm: + +```sh +export STRATA_PREFILL_MMQ=1 +export STRATA_HIPBLASLT_TUNING="$PWD/tools/hip/gfx1100-hipblaslt-100100.txt" +export STRATA_PREFILL_RING=96 +export STRATA_IO_THREADS=32 +``` + +The supplied table is calibrated for gfx1100 and hipBLASLt version 100100. +It is not a universal ROCm tuning table. The runtime guards architecture, +library version and actual shape/stride/workspace requirements, falling back +when a table entry is unavailable or incompatible. HIP MMQ is opt-in at runtime. Default CUDA selection is preserved. + +Measured engine configuration: Orca Flash Next IQ3_XXS, native pack plus matching +GGUF/tokenizer/template, `--mmap-experts --resident-cpu-experts`, fixed ranked +`--expert-profile`, `--expert-cache auto`, `--prefill 8192`, `--spec 4`, +`--spec-min-p 0.5`, matching MTP runtime, `--max-context 262144`, `--kv int8`, +`--kv-resident 32768`, `--pool-workers 15`, `--adapt-every 0`, `--pcie-frac 0`, +and `--vram-reserve-mib 1024`. Keep PLE on SSD. + +`--resident-cpu-experts` copies the complement of the static GPU cache to ordinary +RAM. It requires mmap and a fixed expert profile. The slots the prompt path may +borrow keep their experts in RAM too as far as the budget below allows (the rest +use the mapped fallback while borrowed and for their refill), and adaptive swaps +(`--adapt-every`) exchange experts between VRAM and the RAM copy without reading +the file. The copy is pageable; `--resident-experts` (CUDA, chosen by setup) +page-locks it and uses 4 GiB of headroom. Allocation needs sufficient available RAM; +on Linux this option requires readable standard cgroup-v2 mounts. For each +finite cgroup ancestor, the guard credits only `inactive_file` after subtracting +`file_dirty` and `file_writeback`, capped by current usage; it remains bounded by +the ancestor limit and host `MemAvailable`, with 8 GiB headroom. This accounts +for reclaimable clean file cache but cannot reserve memory against concurrent +system or process allocations. +The POSIX PLE path issues direct reads through a configurable worker pool. + +Use a dedicated idle server, restart it between arms, and capture its engine log: + +```sh +python3 tools/hip/bench_prefill.py \ + --model MODEL_NAME --url http://127.0.0.1:8080 \ + --engine-log /path/to/engine.log --label candidate --output candidate.json +``` + +The script uses the same synthetic source prompts and request order as the +reported measurements: a small warmup, then 140/280/140/280 functions, with one +follow-up after each fresh prompt. It enforces zero reused tokens for the fresh +prompts and records prefill, decode, wall time and stop reason. It requires the +unbuffered log to contain exactly one completed timing record per request. The +128-token output cap is intentional for throughput measurement, not task success. +Never use cancelled-request timing lines as throughput evidence. + +## Final revision benchmark + +Measured on 2026-09-29, source revision `9568e78da663e6b224ab96d57baf450717b36e73`. +HIP executable SHA-256: `705f5925a788bc227bad72abfb5466032e0879d752fea9afc3eb32051b35182b`. +The control and candidate below were both measured anew in this session; no +historical benchmark values are mixed into the table. The control binary SHA-256 +is `4522d4937ca4a41ca294d31b60df8c2bc4df5b7a6caf65eaad10c036e08491f7`; +its source was an existing local runtime snapshot rather than a clean upstream commit. +Both arms use an RX 7900 XTX 24 GiB / gfx1100, Ryzen 9 7950X3D, +64 GiB installed RAM, Fedora-family Linux, ROCm 7.1 and a 272 W GPU cap. +Other model services are stopped for measurement and restored afterward. +Sampling: temperature 0, top-k 1, top-p 1, min-p 0, seed 42, reasoning disabled. + +| Fresh request, execution order | Control prefill t/s | Candidate prefill t/s | Candidate output t/s | Candidate request wall time | +| --- | ---: | ---: | ---: | ---: | +| 4,210 tokens, first use | 240.0 | 447.5 | 55.5 | 11.729 s | +| 8,830 tokens, first use at this size | 484.8 | 873.7 | 55.7 | 12.420 s | +| 4,210 tokens, warmed | 457.2 | 901.1 | 56.7 | 6.937 s | +| 8,830 tokens, warmed | 478.9 | 966.5 | 59.2 | 11.314 s | + +Each request generated exactly 128 tokens and finished at the intentional length +cap. All four fresh prompts had zero reused KV tokens. Fresh-prompt prefill was +1.80–2.02x the freshly measured existing AMD runtime; fresh-request wall time was +40–46% lower. This is a comparison with our existing HIP runtime, not unmodified +upstream, which does not provide this backend. The candidate also completed four +cached follow-ups in 2.95–3.26 seconds. Those follow-ups are not apples-to-apples +prefill comparisons: cache reuse differs with generated text and checkpoint +selection. Full sanitized measurements are in +[the fresh-run JSON](benchmarks/2026-09-29-gfx1100.json). + +Before this revision, an intermediate package missing the HIP upload staging +buffer stalled on the 8,830-token request and was rejected. Restoring staging +allowed the complete sequence above to finish. That failed attempt is not +included in the throughput table. No watchdog limit was raised to obtain these +results. + +Zero KV reuse is not equivalent to a cold filesystem cache. First-use speed +and warmed speed are reported separately. Individual observations do not +establish confidence intervals or a general rate at every context length. + +## Correctness and quality limits + +Both HIP and CUDA executables built from the measured source revision. CUDA was +compile-checked, not performance-tested by this run. The selected HIP CTest suite +passed **29/29** with the tuning table enabled, including expert-upload readback, +asynchronous handoff, QSA, MMQ, Lt GEMM, KV streaming and PLE reading. The excluded +`ple_parity` requires an external fixture; `platform_memory_test` requires a +larger locked-memory limit than the test account provides. Separately, three +real IQ3_XXS PLE matrix graph replays passed, and the POSIX direct-file test passed +queued reads, short EOF, wake, close/drain and reopen checks. + +Development checks passed eight MMQ numerical comparisons, four actual Lt GEMM +comparisons, and native QSA/indexer/embedding parity including tail states, +chunk continuation and image overrides. Real quantized MMQ relative L2 error +was approximately 0.0026 against raw-FP32/dequantized-weight reference, reflecting +Q8 activation arithmetic; this is not bitwise numerical equivalence. + +End-to-end coding quality is not established by these numerical checks or capped +throughput requests. Validate completed tasks with independent runtime tests; this +contribution makes no broad answer-quality or agentic-reliability claim. + +The changes do not claim better model reasoning, verified full-context behavior, +end-to-end vision validation, Windows HIP, other AMD architectures, or mixed +AMD/NVIDIA execution. Existing CUDA multi-GPU code remains present but is not +validation of HIP multi-GPU support. + +## Attribution and rejected experiments + +The measurements above were taken before this backend was rebased onto engine 0.1.24. The PR's own batched +embedding gather and QSA indexer append (adapted from +[PR #108](https://github.com/Niko1221/Strata/pull/108), commit +`acd487233c0bbe2217a6881c5bb43f8a283b0de5`) were dropped in the rebase: 0.1.24 already does both on every +backend, bit-exact (C-2, C-4). #108's optional GDN parallel/split path is not included. Existing upstream MMQ orchestration is retained and enabled for +HIP with AMD architecture identification and the correct backend compilation. + +Static 16K chunks, expanded FP16 expert tuning, and a 192-slot ring did not offer +a consistent end-to-end win in the evaluated workload. The table includes only +the selected 30 dense-shape rows. Microkernel speedups alone were not sufficient +to select a configuration. No increase in GPU power cap was used. diff --git a/engine/strata/docs/COMMUNITY_BENCHMARKS.md b/engine/strata/docs/COMMUNITY_BENCHMARKS.md new file mode 100644 index 00000000..ff3c312c --- /dev/null +++ b/engine/strata/docs/COMMUNITY_BENCHMARKS.md @@ -0,0 +1,167 @@ +# Community benchmark results + +Share measurements from your own hardware so other users can judge how Strata +might run on a similar machine. This guide suggests a report format and a pull +request workflow; a single model, GPU, or context length is enough to contribute. + +Existing [benchmark reports](../bench/results/) provide examples. The +[engine 0.1.26 speed report](../bench/results/2026-09-29-speed-0126/README.md) +includes hardware, settings, and per-run JSON. The +[technical details](DETAILS.md#speed-measured) explain the published measurements +and their limits. Report what you actually measured and label estimates separately. + +## Community reports + +- [2026-09-30: RTX 5090, Core Ultra 9 285K, 64 GB RAM](../bench/results/2026-09-30-community-rtx-5090/README.md): + Strata 0.1.29, original Flash-Next IQ2_XS, 131,072-token context; three runs + each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks. + +## What to record + +Include enough information for someone else to repeat your run: + +- **Hardware:** GPU model, VRAM, selected GPUs for a multi-GPU run, CPU, installed + RAM, and storage type. Include PCIe link speed and width, GPU power limits, and + other workloads when known or relevant. +- **Software:** OS, Strata commit and engine version, driver and CUDA version + (or ROCm for HIP), and release binary or source build. Include changed build options. +- **Model:** exact repository and revision when available, quantization, GGUF + filenames, and vision encoder if enabled. Identify custom packs, expert + profiles, or draft vocabularies, with hashes or reproducible preparation steps. +- **Settings:** launch command and relevant run configuration, context limit, KV + type and streaming window, expert cache, low-RAM mode, prefill size, CPU workers, + MTP, reasoning effort, sampling, and vision. State whether calibration or + experimental speed projection was enabled; attach the resulting settings. +- **Workload:** benchmark command or script, shareable prompts or instructions to + build them, actual prompt and generated token counts, output cap, repetitions, + and cache state for each run. + +Use GB or GiB consistently and name the unit. Mark unavailable values explicitly +instead of guessing. Remove credentials and private content from configurations, +prompts, and logs before publishing them. + +## How to measure + +Start with a configuration that already works on your machine. You do not need to +download every model or test the largest context. A useful initial speed report +tests one short prompt and one longer prompt that fits, with a fixed output cap +(for example, 256 tokens). Record the actual output length if the model ends early. + +For each configuration, try at least three measured runs and publish all of them +with a median and range. If you only have one run, say so. Explain any warm-up and +whether model loading is included in the timing. + +Strata reuses conversation prefixes and adapts its expert cache. Separate prompts +that are fully processed from follow-ups that reuse tokens, and report the number +of reused and freshly read tokens from the engine log. Describe how you reset or +retained state between runs. A warmed expert cache and a reused prompt prefix are +different conditions; record both when possible. + +Keep these measurements separate: + +- **Prompt throughput:** freshly processed prompt tokens per second, from the + engine's timing output. Keep the corresponding token count and duration. +- **Decode throughput:** generated tokens per second, from the engine's timing + output. Count reasoning tokens too, or explain any different convention. +- **Time to first token:** seconds from sending the request to its first generated + token. For a streaming API measurement, ignore keep-alives and empty deltas and + state whether the first token is reasoning or answer text. +- **Total latency:** elapsed seconds for the whole request. State whether measured + at the engine or client, and whether loading, vision encoding, or queueing is included. +- **Memory:** observed RAM and VRAM usage, including whether the value is a startup + snapshot or a peak during inference. Report paging or out-of-memory failures. + +Attach the engine timing lines and your measurement script if you used one. Avoid +calculating decode throughput by dividing generated tokens by total request time, +which also includes prompt processing. Cancelled or failed requests belong in the +report as failures, outside the successful throughput summary. + +When comparing versions or settings, run both on the same machine and workload +and list every changed setting. Preserve the per-run results: output text and +draft acceptance can change speed even when the input is identical. + +## Optional correctness checks + +Speed measurements alone do not establish answer quality. Include a small check +relevant to your workload, such as a completed coding task with test results, a +tool call followed by its result, or an image question with an expected answer. + +For long-context recall, the repository includes +[`tools/needle_bench.py`](../tools/needle_bench.py). With a running local server, +from the repository root: + +```bash +python tools/needle_bench.py --help +python tools/needle_bench.py --url http://127.0.0.1:8080 --lengths 32k,128k --depths 10,50,90 --out needles.json +``` + +Choose lengths your configured context can hold. The script supports `--api-key` +for an authenticated server; keep that key out of published commands. Save the +reported actual prompt lengths, misses, errors, and skipped cases as well as +successes. A needle test measures recall on those inputs, not overall model quality. + +## Submit a report + +1. Fork Strata and create a branch for your report. +2. Add a folder such as `bench/results/YYYY-MM-DD-community-rtx-5090/`. Use the + measurement date and a short hardware label; add a suffix if the name exists. +3. Put a `README.md` based on the template below in that folder, together with + per-run JSON or CSV and small scripts or prompts needed to repeat it. Use your + own data format and document its fields and units. Keep large model files and + generated packs out of the PR. +4. Open a pull request against `Niko1221/Strata:main`. Summarize the hardware, + model, configurations tested, and limitations. Keep a results-only submission + separate from engine changes so reviewers can assess the measurements directly. + +Maintainers can review the report and decide where to include it. Adding a report +does not require changing the README's headline performance claims. For a failed +run or a suspected bug, a GitHub issue with the configuration and relevant logs +may be more useful than a benchmark PR. + +## Report template + +Copy this into your report's `README.md`, replace the placeholders, and remove +sections that do not apply. Use `not measured` for missing measurements; the table +contains no example performance numbers. + +````markdown +# Community benchmark on GPU name + +Measured on DATE by HANDLE. State what was tested and the main limitation. + +## Hardware and software + +- GPU and VRAM; CPU; installed RAM; storage; PCIe link if known: +- OS; driver; CUDA or ROCm: +- Strata commit; engine version; release binary or source build: +- Background workloads and any power limits: + +## Model and configuration + +- Model repository and revision; quantization; GGUF filenames: +- Vision encoder; custom packs or profiles: +- Context; KV type and streaming; cache; prefill; low-RAM mode: +- MTP; reasoning; sampling; calibration; experimental speed projection: + +```text +Exact launch command and relevant configuration, with credentials removed. +``` + +## Method + +Link prompts and scripts. Describe output cap, repetitions, warm-up, loading, +prompt reuse, expert-cache state, timing boundaries, and memory measurement. + +## Results + +| Configuration | Actual prompt tokens | Reused tokens | Generated tokens | Runs | Prompt tok/s median and range | Decode tok/s median and range | TTFT seconds median and range | +| --- | ---: | ---: | ---: | ---: | --- | --- | --- | +| Fill in measured values | | | | | | | | + +Link per-run data and logs. Include total latency and memory observations when +measured, with units and timing boundaries. List failures and skipped cases. + +## Correctness and limitations + +Describe checks, expected answers, observed results, and untested behavior. +```` diff --git a/engine/strata/docs/DETAILS.md b/engine/strata/docs/DETAILS.md new file mode 100644 index 00000000..e0737ce8 --- /dev/null +++ b/engine/strata/docs/DETAILS.md @@ -0,0 +1,893 @@ +# Strata - the details + +The technical side of Strata: every measured number, the API, images, all settings and how the engine works. +New here? Start with the [README](../README.md); installing step by step is in [INSTALL.md](INSTALL.md), the models in +[MODELS.md](MODELS.md), common problems in [TROUBLESHOOTING.md](TROUBLESHOOTING.md). + +> **On this page:** [Speed](#speed-measured) · [Other GPUs](#other-gpus-estimated) · [Which model?](#which-model) · +> [Requirements](#before-you-start) · [Windows](#windows) · [Linux](#linux) · [API](#using-it) · +> [MCP tools](#tools-from-mcp-servers) · [MCP server](#manage-strata-from-your-ai-assistant-mcp-server) · +> [Images](#images-vision) · +> [Troubleshooting](#troubleshooting) · [How it works](#how-it-works) + +--- + +## Speed (measured) + +RTX 5070 **12 GB**, Ryzen 5 7600 (6 cores), 64 GB DDR5-5200, Windows, engine 0.1.26 with the settings setup writes +(`--prefill auto`, 8-bit KV above 4K, KV streaming from 64K). One code-agent prompt per length, 256 generated tokens, +MTP speculative decoding on. "262K" is the model's full context window (a 259,943-token prompt). The IQ2_XS row was +measured with Swift 1.5's IQ2_XS, which runs at the original's speed. + +### Prompt processing (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 536 | 1,299 | 2,171 | 2,126 | 2,107 | 1,304† | +| **IQ2_XS** | 534 | 1,256 | 2,092 | 1,754 | 1,752 | 1,181*† | +| **IQ3_XXS** | 482 | 1,007 | 1,745 | 1,609 | 1,602 | - | +| **IQ3_S** | 427 | 913 | 1,624 | 1,640 | 1,443 | - | +| **Coder** | 656 | 1,583 | 2,177 | 2,236 | 2,208 | 1,034** | + +Engine 0.1.26; `bench/results/2026-09-29-speed-0126`. At 32K-128K that is 8-28% faster than 0.1.22. † not measured +again: 0.1.22. \* measured with images on (the image encoder's VRAM reserve leaves fewer experts cached). \*\* not +measured again: 0.1.14. + +### Output (tokens/s) + +| Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| **Q2_0** | 87.3 | 93.0 | 81.8 | 76.2 | 73.7 | 60.3† | +| **IQ2_XS** | 79.6 | 78.6 | 76.3 | 63.7 | 62.7 | 52.8† | +| **IQ3_XXS** | 61.9 | 61.6 | 58.5 | 57.2 | 49.0 | - | +| **IQ3_S** | 52.4 | 53.3 | 48.3 | 46.3 | 45.5 | - | +| **Coder** | 58.9 | 55.1 | 54.9 | 53.2 | 43.0 | 42.8† | + +Engine 0.1.26, the same runs. † not measured again: 0.1.14. + +Output speed depends on the text as well: speculative decoding runs faster when more of the drafted tokens are +accepted, so a different answer to the same prompt moves it by several percent. Run back to back on the 4K prompt, +0.1.14 writes 88.5 tokens/s and 0.1.12 85.7. The numbers before 0.1.13 (prompts about half as fast): +[`bench/results/2026-09-24-final`](../bench/results/2026-09-24-final/matrix.md); these: +[`bench/results/2026-09-28-speed-0114`](../bench/results/2026-09-28-speed-0114/README.md). + +IQ3_XXS and IQ3_S at 262K are not measured: with their 43 / 50 GB of experts, a 260K-token context brings a 64 GB PC +to its memory limit by setup's estimate (the experts + the context's KV cache + 24 GB), so setup recommends up to 128K +with them on 64 GB. A longer context you choose (`--context 262144`, or a pick in its list) is kept, with a note: users +ran IQ3_S at 256K on 64 GB with RAM to spare (#406). In the low-RAM mode the KV cache stays in VRAM and the context +does not count against RAM. IQ3_S (engine 0.1.4 or newer) is only published for the original model, not for Swift 1.5. + +**KV streaming (engine 0.1.5):** at 64K and more, setup keeps the context's KV cache in RAM and only the part the +attention reads in VRAM (`--kv-resident 32768`), so more experts fit on the GPU. Q2_0 at 262K: 50.9 -> 62.6 tokens/s +(1,589 -> 3,872 experts in VRAM); at 128K about +6%. The attention reads exactly the same values (only where the KV lives changes); it +costs ~13.7 KB of RAM per context token (1.7 GB at 128K). Existing installs: run `START-HERE.bat --setup` once to turn +it on. Setup turns it on when the RAM has room for it; `--kv-streaming on|off` overrides that (on past the RAM test with a +note; never with `--kv k8v4` or under WSL, which cannot stream). + +**4-bit KV cache (engine 0.1.8, optional):** `START-HERE.bat --setup` asks above 8K context (or pass `--kv q4_0`). It +halves the KV cache's memory with a Hadamard rotation before 4-bit rounding (PR #21), about 4% faster at 128K, but it +is measurably less precise on long documents (perplexity +8-12%; needle tests still pass). 8-bit stays the default. +Details: [`bench/results/2026-09-27-kv-q4`](../bench/results/2026-09-27-kv-q4/README.md). + +**Hybrid K8V4 KV cache (engine 0.1.25, optional, PR #120):** `--kv k8v4` (`START-HERE.bat --setup --kv k8v4`) keeps +the keys at 8 bits and stores the values as rotated 4-bit: 23% less KV memory than 8-bit, so more experts fit in +VRAM. RTX 3090, the Coder at 198K context: 99 instead of 85 tokens/s output, the same needle results, prompts 2-5% +slower. It does not stream its KV cache (KV streaming is on by default from 64K), so it pays off mostly on large +cards at long contexts. + +**Reproducible greedy output (0.1.30, opt-in, `STRATA_IQ_MT_MIN=1`):** with the IQ models, the CPU computes an +expert for one token with ggml's dot product and for several tokens with Strata's multi-token kernels, which round +slightly differently. How many tokens share an expert depends on the drafts in a verify window, so the same prompt +at temperature 0 can end in a different (equally good) answer when the drafting, the cache state or a resumed +conversation differ (issue #152). `STRATA_IQ_MT_MIN=1` (in the config's `env`) uses the multi-token kernels for +every group: the answer then no longer depends on the drafting. Measured on a Ryzen 7600 (AVX-512): IQ3_S decode +-1..-3%, the other models the same; the default stays the fastest rule. Through the server, two more things carry +over from one request to the next (#410): the adaptive tier moves experts between RAM and VRAM (the GPU and the CPU +round an expert differently), and the prompt cache resumes a repeated prompt and reads only its tail through the +decode path. For byte-identical repeats add `--prompt-cache 0 --adapt-swaps 0 --pcie-frac 0` to the engine's args +as well (#410): the PCIe share of the missed experts (computed on the GPU instead of the CPU) still made the first +answer after a start differ from the next ones. Measured here (IQ3_XXS, a 3.6K-token prompt, 4 repeats): with all +three switches 1 answer of 4, without `--pcie-frac 0` 2 of 4 (the first one differs), with the defaults 2 of 4. +`--pcie-frac 0` costs decode speed (the missed experts all run on the CPU), so keep it for A/B runs. + +**The draft layer's tokens (0.1.27, `--draft-vocab`):** the MTP draft layer can only propose tokens from a subset +of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes every Chinese, Japanese and Korean +token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of +VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the +English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get +almost no drafts). `--draft-vocab cyrillic` takes the English/code subset plus the whole Cyrillic script (58,963 +ids): the shipped subsets hold 142 of the vocabulary's 18,580 Cyrillic tokens, so Ukrainian or Russian answers got +1.4 tokens a round; with it 2.1, and 83 -> 109 tokens/s (RTX 5090, the NVFP4 fork), English unchanged. +`tools/draft_vocab.py` builds and inspects subsets. + +**Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, +pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the +experts plus ~10 GB), setup instead maps them from one file in the model's folder (`--mmap-experts`, the pack's +`experts.bin`, +23-50 GB of disk). The OS file cache holds what the GPU does not, and it can give that memory back. +On the Coder the engine's committed memory drops from 36 to ~13 GB, with the same answers. With a big GPU (an RTX +5090 holds all of the Coder's experts, most of Q2_0's) it runs at nearly the usual speed. With a small one, most +experts come from the SSD and it is much slower (setup says so). `START-HERE.bat --setup --low-ram on|off` overrides +the choice. + +**Low-RAM mode, resident (engine 0.1.30):** when the experts the GPU does not hold fit the RAM (with the same ~10 GB +beside them), setup picks the resident variant instead (`--resident-experts`): at start the engine copies exactly those +experts from `experts.bin` into RAM (page-locked when the driver allows, else locked in RAM), so while it answers +nothing is read from the SSD, however little RAM the OS leaves for its file cache. Examples with setup's context: a +32 GB PC with a 24 GB GPU runs Q2_0, IQ2_XS and the Coder this way (~16-18 GB of experts in RAM, the GPU holds the +other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC stays mapped. The details: +- The prompt path borrows room in the GPU's expert cache for its buffers and puts those experts back after the prompt; + as far as the RAM allows, their experts are kept in RAM too (so a prompt reads nothing from the SSD either). +- The cache still follows the conversation (`--adapt-every`): a swap copies the evicted expert back from VRAM into the + RAM place of the one that replaces it, so the RAM copy keeps holding exactly what the GPU does not. +- The answers are the plain mapped mode's for the same expert placement: the bytes are the file's. With a page-locked + copy the GPU also takes its usual share of the misses over PCIe (`--pcie-frac`), as with enough RAM; `--pcie-frac 0` + (or `STRATA_RESIDENT_PIN=0`) gives the mapped mode's exact tokens. +- The engine leaves 4 GB of the RAM it finds free (`STRATA_RESIDENT_HEADROOM_GIB`); when even the experts the GPU does + not hold do not fit, it says so and runs the plain mapped mode. The server log shows, per request, how many expert + reads went to the file (`resident RAM: ... blob reads from the file`: 0 in steady use). +- `--low-ram resident|mmap` forces one variant (also on a PC with enough RAM, e.g. to try it). +- Several GPUs (#364, #384): setup recommends one GPU in the low-RAM mode (the resident variant has no layer split + yet), and asks; `--gpus 0,1` (or answering 2) shares the model across them with the mapped variant + (`--mmap-experts`): the cards together hold more of the experts, and two users measured it 1.3-1.6x faster than + one card, but the OS file cache can fill the RAM to 0 free during long prompts. `--yes` keeps one GPU. A config + with `--resident-experts` started with `--gpus` switches to `--mmap-experts` with a note, and the engine runs that + pair as `--mmap-experts` with a warning instead of refusing it. + +**Low-RAM mode without `experts.bin` (engine 0.1.31):** for the native packs (IQ2_XS, IQ3_XXS, IQ3_S, the Coder, Swift, +Q2_0 packed by `tools/iq_pack.py`; not the canonical Q2_0 pack setup makes for AVX-512 CPUs) the mapped mode no longer +needs the pack's `experts.bin`: when the pack has none, the engine +maps the model's GGUF files themselves and reads each expert's gate, up and down rows from where `native_experts.txt` +says they are (the files are checked against it first: every tensor's name, type, shape, offset and bounds). That +saves the 23-50 GB copy on the disk. The answers are the same: on the Coder, 64 greedy tokens from `experts.bin` and +from the GGUF gave identical tokens and logits. An expert read from the GGUF is three reads instead of one, so the +engine fetches a layer's missing experts on 8 threads (`STRATA_FETCH_THREADS`) with one batched page request +(Windows `PrefetchVirtualMemory`). With an `experts.bin` in the pack, nothing changes. Setup does not use this yet. + +**A RAM budget (engine 0.1.31, `--resident-budget-gib N`):** the resident variant for a model whose experts do not all +fit: the N GiB of experts the GPU cache does not hold that the expert profile ranks hottest are copied into RAM at +start (locked; page-locked when the driver allows the whole budget), and the rest are read from the files through the +OS file cache. It implies `--mmap-experts` and leaves 4 GB of free RAM (a larger N is clamped to that less 256 MiB, +with a message; #403: a clamped budget no longer fails the safety check that follows, and a budget that cannot be +kept at all is a warning, with every expert read from the files). Setup sets N with `--resident-budget-gib N`. With +the GGUF read in place it also warms the next layer's likely experts: while the CPU works on a layer, a thread applies +the next layer's router to this layer's input and asks the OS for the pages of the predicted experts that neither the +GPU nor the RAM budget holds (only pages - the experts computed are the same; `STRATA_LOOKAHEAD=0` turns it off). This +is what runs [Unsloth's UD-Q4_K_XL](UNSLOTH_Q4.md) (72 GiB of experts) on a 64 GB PC: 7-8.5 tokens/s at N = 40 on an +RTX 5070, against ~3 tokens/s before these changes. + +**How much came from where:** with `--stats` the engine prints the tiers of the decode (`expert tiers`: blobs from the +RAM copy, blobs and MB from the files, the time spent reading them; `routing prefetch`: how many of the file reads had +been warmed). The server log has the same per request (`expert tiers: GPU ... hits ...; RAM ... blobs, files ... +blobs ... MB read`), and `GET /metrics` lists `ram_blobs`, `file_blobs` and `file_mb` for each recent request (with +engine 0.1.31 or newer). It also lists each request's speculative drafts, `drafts_offered` and `drafts_accepted` +(`null` when the engine did not report them), and their sums since the server started in `totals` (#457). + +Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K +and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). + +**Faster prompts (engine 0.1.13):** the prompt is read in chunks of up to 8,192 tokens instead of 2,048 (`--prefill +auto`: the largest chunk whose buffers fit in the expert-cache slots it borrows, and a request borrows only what its +prompt needs); the experts are multiplied by llama.cpp's quantized MMQ kernels instead of being expanded to FP16 +first; the next layer's experts stream over PCIe while the current layer's attention runs; the PLE block runs for the +whole chunk at once; unpinned experts are copied by helper threads. Measured on the RTX 5070 12 GB, 64 GB RAM, +32K-token prompt: Q2_0 572 -> 1,290 tokens/s, IQ3_S 383 -> 1,208. Through the server (Q2_0, 128K context): 999 tokens +353 -> 438 tokens/s, 6,927 tokens 529 -> 1,077, 28,584 tokens 584 -> 1,249. Output speed is unchanged. Needles 5/5 +(1K-262K). Details and the quality check: +[`bench/results/2026-09-28-prefill-speed`](../bench/results/2026-09-28-prefill-speed/README.md). Existing installs +switch to `--prefill auto` the next time START-HERE / setup.sh starts them. The raw numbers: +[`bench/results/`](../bench/results/). The [paper](paper/Strata-Paper.pdf) explains every number. + +## Other GPUs (estimated) + +Not measured - estimated from the runs above (same CPU and 64 GB RAM): the GPU part scaled by memory bandwidth, the CPU +part by how many more experts the card's VRAM holds. Treat as **±20%**. Numbers are *prompt / output* tokens/s. +The prompt figures predate engine 0.1.13, which about doubled prompt speed on the measured card; how much of that a +card gains depends on its PCIe link (the experts stream over it), so they are still the older estimates. + +| GPU | Model | 1K | 4K | 32K | 64K | 128K | 262K | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| RTX 5060 Ti 16GB | Q2_0 | ~341 / ~80 | ~472 / ~87 | ~501 / ~81 | ~492 / ~72 | ~476 / ~62 | ~435 / ~53 | +| | IQ2_XS | ~291 / ~80 | ~406 / ~77 | ~434 / ~63 | ~426 / ~62 | ~413 / ~51 | ~383 / ~47 | +| | IQ3_XXS | ~249 / ~66 | ~359 / ~65 | ~381 / ~56 | ~374 / ~54 | ~363 / ~45 | - | +| RTX 3090 24GB | Q2_0 | ~355 / ~128 | ~491 / ~140 | ~521 / ~130 | ~512 / ~115 | ~495 / ~100 | ~453 / ~85 | +| | IQ2_XS | ~303 / ~131 | ~422 / ~128 | ~451 / ~103 | ~444 / ~102 | ~430 / ~85 | ~398 / ~78 | +| | IQ3_XXS | ~260 / ~106 | ~374 / ~103 | ~396 / ~89 | ~390 / ~85 | ~378 / ~71 | - | + +More VRAM matters more than a faster GPU: every extra GB holds ~700 more experts, and every expert on the GPU is one the +CPU does not have to compute. A 3090's 24 GB takes most of the CPU work away. (Since 0.1.14 the expert profile ranks +all 24,576 experts; before, the cache stopped at 8,000, about 10-14 GB. `tools/make_profile.py` builds a profile from +your own prompts: run the engine once with `--dump-routing trace.bin`, see the tool's help.) + +## Which model? + +All three are [ISTA-DASLab's GSQ-RCO quantizations](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF) +of [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next). + +| Model | Download | RAM it uses | Speed | Quality | +| --- | ---: | ---: | --- | --- | +| **Q2_0** | 66 GB | ~34 GB experts + ~6 GB | fastest | good | +| **IQ2_XS** | 68 GB | ~36 GB experts + ~6 GB | close to Q2_0 | a bit better | +| **IQ3_XXS** | 76 GB | ~43 GB experts + ~6 GB | slower (more CPU work) | best | + +With 64 GB of RAM all three fit (close the browser for IQ3_XXS, and keep its context at 128K or less). With 48 GB only Q2_0 / IQ2_XS may fit. With 32 GB: the Coder (below). + +### Or: the Coder (half the experts, for code) + +**[Qwen3.8-Flash-Next GSQ-RCO Coder](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)** is +ISTA-DASLab's expert-pruned release: 256 of each layer's 512 experts are kept (still 10 active per token), chosen with +RCO on code, agentic and vision calibration data; its authors report 91.3% of the full model's SWE-bench Verified and +98.7% of LiveCodeBench v6. One size, named IQ1_M for its 1.89 bits per *original* parameter; the kept experts are +stored like IQ3_S (IQ2_S-IQ4_XS gate/up, IQ4_NL/Q2_0 down). Shard 1 is 29.6 GB (experts: 23 GB of RAM), so it runs +on **32 GB of RAM**, and at 262K on 64 GB. Its shard 2 and its vision encoder are the original's files: with the +original installed, setup downloads only shard 1. Strata ships its expert profile (`data/expert-profile-coder.bin`, +the shipped ranking mapped onto the kept experts through the release's `rco-allocation.txt`: 72% of the expert +reads hit the GPU on a 12 GB card). Images work; the experimental speed projection loads and runs on it (it was made +for the full model). + +``` +START-HERE.bat --setup --family coder +``` + +### Or: Swift 1.5 (a fine-tune that thinks shorter) + +The setup's first question also offers **[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)**, +UkisAI's fine-tune of Qwen3.8-Flash-Next, trained to reach the answer with much less thinking (its authors: 63% fewer +thinking tokens, 1.8x sooner answers, under 1% accuracy loss). Same architecture, the same three sizes, its own +vision encoder; Strata runs it at the same speed (4K, IQ2_XS: 465 prompt / 78.7 output tokens/s, vs 467 / 78.3 for +the original). Its authors recommend **IQ2_XS** (their Q2_0 is marked experimental). Its license is the Swift Open +License 1.0 - read it on the model page. + +Our small check (8 reasoning questions, default thinking, IQ2_XS): both models got **8/8**; Swift used **1,234** +output tokens in 28 s, the original **2,682** in 46 s - most of the difference from one question the original +thought about for 1,524 tokens. Not a benchmark, but consistent with the claim. + +``` +START-HERE.bat --setup --family swift --model IQ2_XS +``` + +### Experimental: Unsloth's UD-Q4_K_XL + +A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Setup offers it from engine 0.1.32 +(`--family unsloth --model UD-Q4_K_XL`: a RAM budget of your RAM less 24 GB, the rest read from the SSD); what it +does and the manual workflow are in **[docs/UNSLOTH_Q4.md](UNSLOTH_Q4.md)**. On a 64 GB PC with a 12 GB RTX 5070 it writes 7-8.5 +tokens/s, most experts read from the SSD; it picks the same tokens as llama.cpp on the same file at 97.5-99% of +the positions of short greedy answers, 90-91% after a 16K prompt, differing mostly at near-ties +([measured](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)). + +## Before you start + +You need **only a graphics driver**: NVIDIA 580 or newer (update it with the NVIDIA App or from +[nvidia.com/drivers](https://www.nvidia.com/drivers)), or for AMD the one in [INSTALL.md](INSTALL.md#what-you-need). +Everything else is installed for you the first time. + +| | | +| --- | --- | +| GPU | NVIDIA **RTX 20, 30, 40 or 50 series**, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. Or AMD **Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series**: [AMD_HIP.md](AMD_HIP.md). | +| RAM | **64 GB** recommended (see the table above). | +| CPU | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. | +| Disk | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB copy of its experts for the fast CPU kernel. An NVMe SSD is strongly recommended. | +| OS | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | + +What the first start installs: in this folder `.venv/`, `engine/` and `third_party/`; the model files (`models/`, +`packs/`, `mtp/`, 70-120 GB) in **`Strata-data` next to this folder**, so a new copy of Strata (an update unzipped +elsewhere) finds them and sets itself up the same way. The place is remembered per user (`%APPDATA%\Strata\settings.json`, +`~/.config/strata/settings.json`); `--data-dir` chooses another. Installs from before 0.1.16 are moved there by the next +start (a rename on the same drive; files on another drive are used where they are). +Python 3.12 if you have none (for your user account, no admin), a private Python environment, NVIDIA's CUDA libraries +(from pip, ~0.4 GB), the ready-made Strata engine for RTX 20/30/40/50, the model and the MTP draft layer. If no +ready-made engine fits your PC, it offers to install the build tools (Visual Studio Build Tools + CUDA Toolkit on +Windows, `build-essential` + CUDA on Ubuntu) and compiles the engine for your GPU (asks first; 20-40 minutes once). + +--- + +## Windows + +### Double-click `START-HERE.bat` + +**The first time** it asks four questions and does the rest: + +1. **Which model?** Qwen3.8-Flash-Next (the original) or Swift 1.5 (the fine-tune that thinks shorter). +2. **Which size?** Q2_0, IQ2_XS or IQ3_XXS (it recommends one for your RAM). +3. **How much context?** 8K to 256K tokens (it recommends one for your VRAM). +4. **Images?** yes / no (see [Images](#images-vision)). + +Then it downloads and prepares everything (the model is 66-76 GB, so the first start takes a while; an interrupted +download continues where it stopped) and **starts the model**: your browser opens `http://127.0.0.1:8080`, the Strata +app. It has three tabs: +- **Chat:** streaming answers, the model's thinking (folded away once it answers), code with a copy button, pictures when + images are on, and sampling and thinking-level settings. Chats stay in your browser. +- **Monitor:** what the model is doing (reading the prompt, with progress, or writing, at how many tokens/s); GPU load, + VRAM, temperature, power and PCIe traffic; CPU, RAM and disk; the context in use; the last requests. +- **About:** the model and engine settings, and the addresses to connect other apps. + +`http://127.0.0.1:8080/?q=your question` opens it with a new chat already asking. The API is at +`http://127.0.0.1:8080/v1` for your apps. + +**Every time after that**, `START-HERE.bat` just starts the model (30-90 s to load 34-43 GB into RAM). Nothing is +downloaded again. Closing the window stops the model. + +``` +START-HERE.bat --setup install another model, or change context / images +SETUP.bat the same (double-click it) +START-HERE.bat --model IQ2_XS --context 32768 --vision yes --yes no questions +START-HERE.bat --gguf-dir D:\models\IQ2_XS use GGUF files you already have +START-HERE.bat --data-dir E:\Strata-data keep the model files somewhere else +START-HERE.bat --port 8081 another port +START-HERE.bat --gpu 1 another GPU (numbered as nvidia-smi; setup picks the one with the most VRAM) +START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start +``` + +With more than one model installed, it asks which one to start. `run-.bat` starts a model directly. + +**Tuning for your PC (`--calibrate`, engine 0.1.19).** Three engine settings depend on the PC more than on the model: +- the share of the experts missing from VRAM that are copied to the GPU instead of computed by the CPU + (`--pcie-frac`: a fast PCIe link and a slower CPU want more, a laptop's narrower link less); +- how sure the draft layer must be to add another guess to a check (`--spec-min-p`); +- how many CPU threads compute experts (`--pool-workers`: on CPUs with efficiency cores, fewer can be faster). + +The defaults were measured on a Ryzen 5 7600 with an RTX 5070. Setup offers to measure them on your PC after an +install; `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) does it any time. It measures the output +speed with each setting and keeps one only when it is more than 3% faster. The result is remembered per PC and model +(in the settings file next to the data folder's record), so updates keep it. + +### Running it at startup (Task Scheduler) + +To have the model up at logon, people start the serve from **Task Scheduler** (or a service). Beware: Windows +throttles such contexts, and the model's ~40 GB expert load then crawls at **~0.05 GiB/s (13-14 minutes)** +instead of **~1.4-1.5 GiB/s (~35 seconds)** - a 24x slower start. Measured on an RTX 5070 Ti + Ryzen 7 9800X3D ++ NVMe, same binary, same args, same cache state: + +| How the serve starts | Expert load | +| --- | ---: | +| Double-click / terminal / SSH | 1.42-1.52 GiB/s (~35 s) | +| Task Scheduler with its defaults | 0.05 GiB/s (821-841 s) | +| Task Scheduler with the two settings below | 1.42 GiB/s (35 s) | + +In the task's properties set both of these (the defaults are the opposite): + +- **Priority level: Normal** (Options tab; the default is Below normal), and +- **Run with highest privileges** (General tab; without it the task runs with a limited user token - which + also strips `SeLockMemoryPrivilege`, the privilege Windows large pages need). + +(Both were changed at once, so the isolated effect of each is not measured.) If the model still starts +slowly, the engine prints a hint under its `loaded ... GiB at ...` line naming this cause. + +### Chat in the terminal (optional) + +``` +.venv\Scripts\python chat.py +``` + +--- + +## Linux + +```bash +./setup.sh +``` + +The same questions, the same automatic install (it uses `sudo apt` for Python and, only if it has to compile, +for the build tools), and the same start: `http://127.0.0.1:8080`. Later runs of `./setup.sh` (or `./run-.sh`) +start the model directly. Options as on Windows (`./setup.sh --setup`, `--model Q2_0 --yes`, `--gguf-dir /data/Q2_0`). +Terminal chat: `.venv/bin/python chat.py`. + +- **Updating:** `git pull`, then `./setup.sh`: it compiles the engine again when its source changed (a minute or + two for the changed files). If that compile fails, it says so and starts the engine you had. +- **Other distributions** (Arch, Fedora, ...): install the C++ compiler and the CUDA Toolkit 13 with your package + manager first (Arch: `sudo pacman -S base-devel cuda`); setup finds `nvcc` on PATH, in `/usr/local/cuda*` and in + `/opt/cuda*`, and does the rest. +- **WSL** works (Ubuntu 24.04 tested), with one limit: the NVIDIA driver pins only about 1 GB of RAM there, so KV + streaming (`--kv-resident`) is off and the KV cache stays in VRAM, and the experts are copied to the GPU from + unpinned RAM (slower prompts than native Linux). + +--- + +## Sharing the GPU with other programs (optional) + +By default the model stays loaded until you close Strata. On a PC that also games, renders or runs another model +server, three server options (all off by default; also as keys in `strata-.json`) give the VRAM back: + +| Option | Config key | What it does | +| --- | --- | --- | +| `--idle-unload 600` | `"idle_unload_s": 600` | unload the model after 600 s without requests; the next request loads it again | +| `--min-free-vram-mib 11000` | `"min_free_vram_mib": 11000` | load an unloaded model only when that much VRAM is free (it waits up to 15 s for memory being given back), else answer **503** "the GPU is in use by another program" instead of starting into what a game left (with several GPUs it checks the first one) | +| `--before-load "cmd"` | `"before_load": "cmd"` or `["cmd", "arg"]` | a command run before the model is loaded again, e.g. one that unloads another server's model | + +`POST /unload` unloads it now (`409` while a request is running) and `POST /load` loads it ahead of a request; +`/health` says `"loaded"`, `/v1/models` lists it as `unloaded` (like llama.cpp's router), `/props` sets +`is_sleeping` and the Monitor shows the state. Unloading ends the engine process - and the image encoder, when images +are on; it is started again first, as at a start - so their VRAM and RAM go straight back. The model files stay in +the OS file cache, so loading again takes seconds while that RAM is not needed elsewhere. Measured on an RTX 5060 Ti +16 GB with Q2_0 in the low-RAM mode: unloading takes ~0.3 s, and a request to an unloaded model answered after +4.6 s (text) or 14.7 s (a picture, image encoder on the CPU). + +--- + +## Using it + +The server listens on `http://127.0.0.1:8080` (change with `--port` in setup, or edit the run script). + +| API | Endpoint | +| --- | --- | +| OpenAI Chat Completions (stream and non-stream, tools) | `POST /v1/chat/completions` | +| Anthropic Messages (stream and non-stream, tools) | `POST /v1/messages` | +| Model list / health | `GET /v1/models`, `GET /models`, `GET /health` | +| Model properties | `GET /props` (also accepts `?model=`) | +| What the model is doing right now | `GET /status`, `GET /slots` (single slot, busy or idle) | +| Everything the Monitor tab shows (engine, live state, last requests, hardware) | `GET /metrics` | +| The MCP servers, their state and tools ([below](#tools-from-mcp-servers)) | `GET /mcp` | + +`/models` and `/v1/models` list only the loaded model, with its context limit and input modalities. `/props` exposes the original chat template, context limit, configured generation defaults (shared settings take precedence), model path and engine version when available. Context means the full engine context, not the resident KV window. `n_predict: -1` means no fixed output cap. Unconfigured sampling fields are omitted. `autoload` has no effect; an unknown `model` returns 404. These metadata endpoints and `/slots` require the API key when one is configured. They do not load, unload or restart models. + +```bash +curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{ + "model": "strata", "messages": [{"role": "user", "content": "Write a haiku about GPUs."}], "max_tokens": 512 }' +``` + +```python +from openai import OpenAI +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="none") +r = client.chat.completions.create(model="strata", messages=[{"role": "user", "content": "Hello!"}]) +print(r.choices[0].message.content) +``` + +- **Thinking levels: none, low, medium, high.** The model thinks before it answers (streamed as + `reasoning_content`, Anthropic: `thinking` blocks). Choose how much per request - in the chat page (the "Thinking" + menu), in `chat.py` (`/think low`), or over the API: + + | API | how | + | --- | --- | + | OpenAI | `"reasoning_effort": "none" \| "low" \| "medium" \| "high"` (also `"reasoning": {"effort": ...}`, or `"chat_template_kwargs": {"enable_thinking": false}`) | + | Anthropic | `"output_config": {"effort": "low" \| "medium" \| "high"}`, `"thinking": {"type": "disabled"}`, or `"thinking": {"type": "enabled", "budget_tokens": N}` (under 2K = low, under 8K = medium, more = high) | + + Without a setting the model uses its own default, **high**. `none` answers at once (fastest); `low` keeps the thinking + short. The levels are instructions the model was trained with, not a hard token limit: on easy questions all three + think briefly, on hard ones `high` thinks longest and is most accurate. +- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` in a request (OpenAI or Anthropic) caps the + thinking at N tokens: when it gets there the server ends it with a short wrap-up line and ``, and the model + answers from there (the engine continues from what it already holds, so nothing is read again). The wrap-up is + part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in + `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; + Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request + with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in + `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short + helper calls (a session title in a few dozen tokens) need; its real turns ask for thinking when it is on there. +- **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls + (the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a + long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every + 15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing the + connection or pressing stop in your app really stops the model, so the next request starts at once. +- **Chat apps.** Any app with an "OpenAI-compatible" provider works: base URL `http://127.0.0.1:8080/v1`, any API key. +- **Claude Code** (Strata 0.1.17 or newer): set `ANTHROPIC_BASE_URL=http://127.0.0.1:8080` and + `ANTHROPIC_MODEL` to a Claude model name it knows (it refuses names it doesn't; Strata ignores the name), plus any + `ANTHROPIC_AUTH_TOKEN` (or your `api_key`, if you set one). +- **Context.** Chosen in setup (8K-262K). Requests longer than that are refused, never silently cut. A request whose + `max_tokens` would run past the context is refused too (400); agents that always ask for their full output cap + can instead get it shortened to the room left: add `"fit_max_tokens": true` to `strata-.json` (or pass + `--fit-max-tokens` to `serve/server.py`). A prompt that leaves no room at all is still refused. +- **Model aliases** (0.1.32). `"aliases": ["qwen", "local-model"]` in `strata-.json` lists the model under + those names too in `/v1/models` (each with its own `id`, and in the model's `aliases`), like llama-server's + `--alias`; a request naming one is answered under that name. Any other name is still served, as before. +- **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise: + run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and + `"api_key": "..."` to `strata-.json`). The server window then prints this PC's addresses + (`from other devices: http://192.168.x.x:8080/`); open that on the other device, or use `.../v1` as an API base URL. + On Windows the firewall blocks it until you allow it: accept its prompt for Python (private networks), or run + `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` + in an admin PowerShell, and make sure the network is set to Private. +- **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/): + `cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC: + add `"api_key": "some-long-secret"` to `strata-.json` (or set the `STRATA_API_KEY` environment variable); + clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass + each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through + a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`. +- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of + those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any + page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. + +**Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the +live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new +assistant turn and every 16K prompt tokens). A checkpoint is used only when the prompt starts with exactly its tokens +and pictures. The oldest checkpoint - in practice the end of the system prompt, which every chat of the same client +shares - is kept for good while the rest rotates by least recent use, so a NEW chat that shares that prefix starts +reading after it instead of from token 0. A prompt read from the start is also checkpointed at the end of its system +prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that root exists for agent clients with long +system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, +`--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`. + +**Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 +--conversation-cache-slots 4` to the engine arguments to park up to four conversations +in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when +their requests alternate; it does not execute requests concurrently. No client session +ID is required: only exact token/image prefixes with matching steering mode are reused. +The default budget is 0 (disabled); `--prompt-cache 0` also disables parking. +The initial shared-core integration supports a single session GPU: combining +enabled parking with `--layer-split` is rejected before model loading. Ordinary +upstream layer-split checkpoints remain available with parking disabled. FP16, +INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring +remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be +reported separately from Linux/CUDA evidence. + +Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V. +They add host RAM, not another model or VRAM allocation. The byte budget also counts +an incoming snapshot during a switch. After a restore, unchanged K/V pages can be +retained for the next parking operation; growth appends storage without copying +the existing pages. Rewinds refresh the affected pages, and running state and +checkpoints are captured again. Retained active K/V counts against the same byte +budget and is discarded before evicting parked entries under memory pressure. +If reserving space for growth would evict another conversation, parking uses a +full capture instead. +Oldest parked entries are evicted first. +Oversized snapshots or host allocation failures fall back to ordinary prompt processing. +`--conversation-cache-min-free-mib N` (default 2560) additionally requires that +physical-RAM headroom remain available: the engine checks before allocation and +again after capture. Unknown telemetry or insufficient RAM skips parking. Windows +uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples, +not a reservation or enforcement of container/job memory limits. An 8 GiB budget +is a cap, not a recommendation for every machine. + +The shared snapshot core validates all layers and checkpoints before applying any +state. Invalid entries are discarded; transfer/synchronization failure is fatal +rather than permission to continue with partial state. Indexer spare keys and the +moving spare row are preserved, including checkpoint rewinds. +The engine log reports parking, restoration, bytes, evictions, individual snapshot +sizes and K/V bytes reused during capture. `STRATA_SNAPSHOT_FULL_CAPTURE=1` disables +retention for diagnostic comparisons. Snapshots are not +persisted across restarts. + +**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats +re-reads the other one unless the opt-in cache above is enabled); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p / +seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result +is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the +engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out +(`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no +block at all a request without sampling keys decodes greedy. The penalties (`presence_penalty`, `frequency_penalty`, +`repetition_penalty`, with `penalty_last_n` capping how many recent tokens they count over, default 64 when any +penalty is set) ride the same path; they count the tokens the request has consumed, so a repetition penalty +suppresses what the model itself just said, not the prompt alone. Since engine 0.1.19 they apply to every token +the speculative decoding checks at once, exactly as if it decoded one token at a time (before, only the first of +each batch got them). That makes requests with penalties 1-11% slower than in 0.1.18: the draft layer guesses +without penalties, so more of its guesses are now rejected. Requests without penalties are unchanged. `top_k` keeps at most 64 candidates: `0` ("off") or anything above 64 uses all 64. + +--- + +## Tools from MCP servers + +The chat page can give the model tools from [MCP](https://modelcontextprotocol.io) servers, as LM Studio and Claude +Desktop do: reading your files, fetching web pages, searching, anything an MCP server offers. List the servers in +`strata-.json` under `"mcp_servers"` - the same shape as Claude Desktop's `mcpServers` block, which you can +also paste as it is (key `"mcpServers"`): + +```json +"mcp_servers": { + "files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\me\\Documents\\notes"]}, + "search": {"url": "http://127.0.0.1:3000/mcp", "headers": {"Authorization": "Bearer ..."}} +}, +"mcp": {"timeout_s": 60, "max_result_chars": 20000, "max_rounds": 8} +``` + +Or keep them in their own file and start the server with `--mcp-config path\to\claude_desktop_config.json` (a file +with an `mcpServers` block; add it to the `serve/server.py` line of your run script). Restart Strata after a change. + +- **A program** (`command`, `args`, optional `env` and `cwd`) is started by Strata and spoken to over its + stdin/stdout; `npx`, `uvx`, `python` and friends are found on `PATH` as usual (Node.js is needed for `npx` + servers). **An address** (`url`, optional `headers`) uses MCP's Streamable HTTP transport (the older SSE-only + transport is not supported). `"disabled": true` leaves an entry out. +- The servers start with Strata, in the background; the server window says what each one offers + (`MCP server 'files': 14 tools (...)`), or why it did not start - its tools are then left out and the chat works + without them. The Monitor tab lists them, and the Sampling drawer has **Use tools from MCP servers** (on by + default). A server that stops later is started again at its next call. +- In the chat each call shows as a small block (tool, arguments, result); the model reads the result and goes on, + up to `max_rounds` calls in a row per answer. A tool that fails or takes longer than `timeout_s` (default 60 s) + gives the model an `error: ...` result instead of ending the chat. Results longer than `max_result_chars` + (default 20,000 characters) are cut, with a note, before the model reads them. Stop stops a running tool too. +- Only the chat page uses them. API clients (omp, Claude Code, OpenAI and Anthropic SDKs) see the API exactly as + before and keep their own tools; a request to `/v1/chat/completions` opts in with `"strata_mcp": true` (it then + gets `strata_mcp` tool events in the stream). + +**Security.** MCP tools run on your PC with your user's rights, and **the model decides when to call them** - also +because of what it reads (a web page or a file can contain instructions). Give a filesystem server only the folders +it needs, prefer read-only tools, and don't add servers you don't trust. The tools can only be used from the chat +page itself (a request with another site's Origin or without a JSON content type is refused); if Strata is reachable +from other devices, set an API key. + +**Context extension past 262K (rope scaling, EXPERIMENTAL, off unless you pick it).** The model was trained on +262,144 positions (rotary base 1e7). Rope scaling rescales the rotation angles so that longer contexts stay usable, +with llama.cpp's types and flag names. `linear` is Position Interpolation: every angle is shrunk by the factor. +`yarn` keeps the high-frequency angles, interpolates the low-frequency ones, and adds the magnitude correction +that keeps the attention temperature where training put it. **Without the flags nothing changes:** an unscaled +run computes exactly what it did before the feature existed, bit for bit. Scaled contexts need proportionally +more VRAM/RAM for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). + +What was measured (contributors' runs, RTX 5080 + IQ3_S, native path, in PR #84): per-position perplexity on the +same tokens, with only the scaling flag changed. At 293K tokens (1.12x the trained length), `yarn` with factor 2 +lowered the NLL by 0.18 nats against both `none` and `linear` 2 (2.04 vs 2.22 / 2.22). That is 3-4x the path noise +measured at the same length. `linear` 2 was indistinguishable from `none`. At 2.7K and 32K no arm separated from the +noise. Needle tests do not tell the arms apart: the unscaled model also finds a needle at 413K. Long real-document +Q&A worked with `yarn` 2 at 421K and `yarn` 4 at 714K (8/8 each), and a 1M-token `yarn` 4 run read end to end. +Taken together, use **yarn**. It is still experimental: the numbers come from one machine and one quant. + +- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one + question when run interactively) and derives the factor from the final context for you (final context / + 262,144, at least 1: 1.5 at 393K, 2 at 512K, 1 inside the trained range; `--rope-scaling`/`--rope-scale` + override; an explicit `--rope-scale` is kept as given even when it is too small for the context actually + served, so check it if you set one). An explicit `--rope-scaling none` for a context past + 262,144 is refused: the setup will not configure a run with the stock angles past the trained range. If + the RAM check reduces a chosen 384K/512K back inside the trained range, an omitted method adds no + scaling, and an explicitly chosen one stays at factor 1 - the trained angles, no expansion (not a + switch for rope as a whole: explicitly supplied rope settings keep their behavior). +- engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, + `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, + `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a + fine-tune ships them, are the defaults the flags override. + +The scaling is fixed for the whole run - the engine stores keys in its cache after rotating them, so one +cache must never mix two scalings, and there is no per-request form. Within the trained 262,144 a scaled +run is a slightly different model: the rescaled angles, and `yarn`'s magnitude correction, apply at every +position, not only past the trained end. That is why the setup turns scaling on only for a context past +262,144. Pictures read the same scaled table (their (t, h, w) positions feed it). That should work, but it is +unmeasured: all the runs above are text. + +--- + +## Manage Strata from your AI assistant (MCP server) + +`tools/strata_mcp.py` is an MCP server for Claude Code, Claude Desktop, Cursor, VS Code, Codex and other assistants. +Once it is added, you can ask your assistant "install Strata for this PC", "start Strata" or "is Strata running?". +In Claude Code, add it with: + +```bash +claude mcp add strata -- python C:\Users\you\Strata\tools\strata_mcp.py +``` + +It has eight tools: status (the running model, what is installed, the hardware, a recommended size), the model +list, install, start, stop, logs, a speed test, and connection settings for other apps. + +Install runs `setup.py` with `--yes` in the background. Before it downloads anything, it shows the plan and waits +for your OK. Start and stop work like the run scripts and the server's own unload. The MCP server only ends +processes it started itself. It uses only Python's standard library, so it works before `.venv` exists. + +The config snippets for every client, the tool arguments and the safety rules are in +[docs/MCP_SERVER.md](MCP_SERVER.md). This is the opposite direction from +[Tools from MCP servers](#tools-from-mcp-servers) above, where the Strata model calls *your* MCP tools. + +--- + +## Images (vision) + +The model has a vision encoder: [`mmproj-Qwen3.8-Flash-Next-BF16.gguf`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF) +(0.9 GB, a 27-layer ViT plus the projector into the language model). It is **optional**: say yes when the setup asks +"Images?", or run it again with `--vision gpu` (or `--vision cpu`). The setup downloads the encoder, builds a small +helper (`strata-vision`, from llama.cpp's `mtmd` library) and adds it to your start script. Nothing else changes. + +| Encoder on | Time per picture | Cost | +| --- | --- | --- | +| **GPU** (recommended) | **0.1-0.5 s** (up to 1,024 image tokens) | ~1.4 GB of VRAM is kept free for it, so the expert cache is smaller: text output is a few % slower (table below) | +| CPU | 10-30 s (pictures are scaled down to ~300 image tokens) | nothing on the GPU | + +A picture becomes up to 1,024 tokens of the context (a 640x480 photo: 300). The same picture sent again, as chat apps +do on every turn, is encoded only once. + +**A spare GPU for the encoder (0.1.33, #408):** with a card the engine doesn't use, add `"cuda_device": 2` (numbered +like `nvidia-smi`) to the `"vision"` section of `strata-.json`: the encoder then runs on that card alone. Lower +`--vram-reserve-mib` in `"args"` to 700 as well, so the engine's cards keep that VRAM for the expert cache. The +encoder's card needs code in the ready-made encoder (RTX 20/30/40/50). + +### Sending a picture + +**Terminal chat:** type `/image `, press Enter, then type your question. + +``` +you> /image C:\Users\me\Pictures\receipt.jpg +(picture attached: receipt.jpg - now type your question) +you> What is the total on this receipt? +``` + +**OpenAI API** (an `image_url` part: a `data:` URL, an `http(s)://` URL or a local file path): + +```python +import base64 +from openai import OpenAI +client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="none") +img = base64.b64encode(open("photo.jpg", "rb").read()).decode() +r = client.chat.completions.create(model="strata", messages=[{"role": "user", "content": [ + {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}}, + {"type": "text", "text": "What is in this picture?"}]}]) +print(r.choices[0].message.content) +``` + +**Anthropic API:** an `image` block with a `base64` (or `url`) source, as usual. + +JPEG, PNG, BMP, GIF, WebP, TIFF and AVIF work (the last ones are converted to PNG first; agents such as omp send +WebP). Chat apps with image upload work the same way. + +### Speed with images on (4K context, measured) + +| Model | Prompt tok/s, images off | Prompt tok/s, images on | Output tok/s, images off | Output tok/s, images on | +| --- | ---: | ---: | ---: | ---: | +| **Q2_0** | 541 | 531 | 90.7 | 86.9 | +| **IQ2_XS** | 468 | 458 | 77.1 | 74.0 | +| **IQ3_XXS** | 411 | 401 | 64.7 | 59.5 | + +"Off" is the published setup; "on" runs with the encoder loaded on the GPU and its VRAM kept free, so ~1,000 fewer +experts fit in VRAM and the CPU computes a few more per token: 2-8% slower. For text, turning images on changes +nothing else (the output is bit-identical when the VRAM is the same). + +A question about a picture (a 640x480 newspaper page = 300 image tokens, a 328-token prompt; the whole request, encoder +on the GPU, measured through the API): + +| Model | Answer ("MEN WALK ON MOON") | Picture encoded | Prompt | Output | +| --- | ---: | ---: | ---: | ---: | +| **Q2_0** | 1.9 s | ~0.1 s | 207 tok/s | 65-73 tok/s | +| **IQ2_XS** | 2.3 s | ~0.1 s | 173 tok/s | 50-60 tok/s | +| **IQ3_XXS** | 2.7 s | ~0.1 s | 144 tok/s | 41-50 tok/s | + +(Short prompts run below the 4K prompt speed: a 2,048-token chunk is where the prompt path is efficient. Short answers +run below the long-output speed: the first rounds have no draft yet.) + +**How it works inside:** the encoder turns the picture into rows of the same width as the model's word embeddings; +Strata puts them where the prompt has `<|image_pad|>` tokens and gives each one its 2-D position (row and column in the +picture; the model uses interleaved M-RoPE). Answers match llama.cpp's multimodal implementation token for token on our +test images. + +--- + +## Experimental speed projection (EXPERIMENTAL, off by default) + +**This is an experiment, not a finished feature.** It ships with Strata but stays off unless you turn it on. + +A 480 KB control vector for Qwen3.8-Flash-Next (`data/experimental-speed-projection/`, see its README). After each +of layers 4-44 the engine removes one direction from every hyper-connection stream of the residual: `h -= (h . v) v`, +one unit vector `v` per layer, exactly as llama.cpp does with the package's `--cvec-mode project` patches. + +**What it changes.** The vector's own package describes it as a **refusal-direction projection**: with it the model +declines far fewer requests (it reports 1 of 50 vs 50 of 50 on its test set), and removing refusals removes a safety +behaviour - you are responsible for what the model writes with it on. It also shifts ordinary answers a little +(measured below). It is not an optimization in the engine: on the same text it costs 0.2-0.4% per token. What a +chat's tokens/s does with it on depends on the text the model writes (length, repetition, how well the drafts land), +so measure it on your own prompts; the Monitor marks every request ESP or stock. + +**Turning it on (at setup).** `START-HERE.bat --setup` asks "Turn on the experimental speed projection?" (default: +no), or pass `--experimental-speed-projection on` (`off`, or a path to another vector GGUF). Only for the original +Qwen3.8-Flash-Next, not Swift 1.5. It writes these engine flags (llama.cpp's) into `strata-.json`: + +``` +--control-vector-scaled \data\experimental-speed-projection\Qwen3.8-Flash-Next-experimental-speed-projection.gguf:1.0 +--control-vector-layer-range 4 44 --cvec-mode project --cvec-dir per-layer +``` + +The engine log then says `control vector mode = project, dir = per-layer, layers 4..44 (41 steered)`, and the web +app's About tab lists it. (`--cvec-mode add` is llama.cpp's stock additive mode, for additive vectors.) + +**Per request.** A loaded vector is on for every request unless it says otherwise: the web app's Sampling drawer has +a switch, and the API takes `"experimental_speed_projection": false` in the request body (OpenAI and Anthropic; a +config default goes in `"sampling": {"experimental_speed_projection": false}`). Switching drops the conversation +cache once, since the model state was computed the other way. Switched off, the output is token-for-token the stock +model's. + +**Measured here** (Q2_0, fixed experts, 2,557 teacher-forced tokens of code, a document and a chat): the top-1 token +changes at 10% of positions, mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3% on +the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. + +--- + +## Troubleshooting + +| Symptom | What to do | +| --- | --- | +| `the NVIDIA driver is too old` | Update the driver (NVIDIA App or nvidia.com/drivers), restart, run `START-HERE.bat` again. | +| Python or the build tools could not be installed | Install what it names (links are printed), then run it again. Everything already done is kept. | +| `port 8080 is already in use` | Strata is already running (look for its window), or another program uses the port: `START-HERE.bat --port 8081`. | +| `cudaHostRegister ... out of memory` in the log | Normal on Windows: the engine pins the experts in per-layer slices instead. Only a problem if the load then fails. | +| `ExpertCache: cudaMalloc(...) failed: out of memory` although VRAM is free | Windows' page file is off or tiny: every allocation on the graphics card is also charged to Windows' commit (RAM + page file). Set the page file to "System managed" (System > About > Advanced system settings > Performance > Advanced > Virtual memory) and restart. Since 0.1.19 the engine retries with a smaller cache instead of stopping, and setup warns about a page file under 4 GB (issue #60). | +| The first start takes minutes | It is reading 34-55 GB into RAM; the second start is faster while the files are in the OS cache. | +| The PC freezes for a few minutes at the start | Normal, most of all the first time (the server window says when it happens): the engine loads the experts into RAM, pins part of it for the GPU and sizes the expert cache. Wait; don't close the window. Still frozen after 10 minutes: restart the PC, close other programs, try again, or pick a smaller size. | +| `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | +| Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | +| `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | +| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (experimental rope scaling), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | +| Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | +| `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | +| A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | +| Pictures are slow (10-30 s) | The encoder runs on the CPU: run setup again with `--vision gpu` (needs ~1.4 GB of VRAM). | +| A request never finishes: "reading the prompt", GPU "100%" at low power | The GPU ran out of VRAM (engines before 0.1.9 could end with ~30 MiB free at large contexts). Run `START-HERE.bat` once to get engine 0.1.9 or newer; the log then says `... MiB of VRAM free with everything loaded` (a few hundred) and names the `--vram-reserve-mib` to add if it is low. | +| Generation stops mid-answer, GPU "100%", one CPU core busy | Fixed in engine 0.1.12 (issue #29, a race in the CPU expert pool on big-VRAM cards). Since then a request that stops moving ends with an error instead of hanging (after 2 minutes; 1 minute from 0.1.13): the log says `no progress for ... s ... (issue #29)` with where it stopped, and the next request starts the engine again. If you see that line, please open an issue with it. Engine 0.1.13 adds a stall report under it (what every expert-pool thread and the GPU handshake were doing, memory and page faults) and, on Windows, a `strata-stall-.dmp` file with every thread's stack: attach both. (`STRATA_WATCHDOG_S` sets the time in seconds; 0 turns it off.) Engine 0.1.14 fixes the stall those reports found (issue #31: with the IQ packs the host could wait forever inside the NVIDIA driver while copying experts in a verify window; the experts are now copied by a GPU kernel, `--pcie-mode dma` restores the old way). | +| `out of memory: cudaFuncSetAttribute` in the log (IQ3_XXS, long prompt) | Fixed in engine 0.1.15: CUDA loaded a kernel's code when it was first needed, and mid-prompt there was no VRAM left for it. Run `START-HERE.bat` (Windows) or `./setup.sh` (Linux) once to update. | +| Anything else | The engine log is `strata-.log` in this folder. | + +--- + +## How it works + +

memory tiers

+ +- **GPU (VRAM):** attention and DeltaNet mixers, the gated-residual weights, routers, shared experts, output head, the MTP + draft layer, the KV cache (from 64K: only its most-read part, the rest streams from RAM), and an **expert cache** that fills the rest of VRAM with the most-used experts (it adapts to + the conversation while you chat). +- **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same time + as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). +- **SSD:** the 28.8 GB n-gram table, read a few rows per token through the OS cache. +- **Speculation:** the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them. 2.4-3.2 + tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** (engine + 0.1.7) drafts up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: + code edits 6-11% faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same. +- **Prompts** are processed in 2,048-token chunks with the experts streamed to the GPU over PCIe. + +The full story, with measurements, bottlenecks and what comes next: **[docs/paper/Strata-Paper.pdf](paper/Strata-Paper.pdf)**. + +--- + +## Credits and licenses + +Strata itself: [MIT](../LICENSE). The model files are not part of it; their licenses apply to them (below). + +- Model: [Qwen/Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; quantizations: + [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF). + The Coder: [ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF) + (Apache-2.0 per its card); its support in Strata came from @pjgmobile's PR #54. + Swift 1.5: [ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) + by UkisAI. Their licenses apply to the weights. +- [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT): the i-quant formats, the GPU dot products and + dequantizers transcribed in `src/kernels/cuda/iq_kernels.cu`, the CPU backend linked for the i-quant experts, the + `mtmd` library behind the image encoder (`tools/vision/`), and `gguf-py` used by the tools. See + `third_party/ggml/LICENSE`. +- Ideas from [Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and + [HyperQwen](https://github.com/syv-ai/HyperQwen); references in the paper. +- The web app's font: [Outfit](https://github.com/Outfitio/Outfit-Fonts) (SIL Open Font License 1.1, see + `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). +- The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, + made from the model's activations (see its README). + +### Start the text API without occupying the GPU + +`serve/server.py --engine strata --config strata-.json --lazy` (or `"lazy_load": true` in that +config) starts the lightweight HTTP API without spawning the native engine. The first generation request +loads it through the existing reload path, including `before_load` and `min_free_vram_mib`. Eager startup +remains the default. This option is text-only: a vision configuration with lazy startup is rejected explicitly. + +`POST /v1/load` and `/v1/unload` are JSON control aliases for integrations, accepting `{}` or +`{"model":""}` and returning model status. They require the configured API key, +`application/json`, and no foreign browser Origin. They return **409** while a request is active or queued, +and **404** for an unknown model. Existing `/load` and `/unload` behavior is preserved. `/api/health` aliases +`/health`; `/v1/status` exposes `loaded` and `auto_load`. The unloaded model remains discoverable. + +Unloading and shutdown close the native engine's stdin after sending `QUIT`, allowing Windows' detached +stdin reader to see EOF. Cleanup waits for process exit before releasing handles; if forced shutdown still +times out, the server keeps ownership and reports an error rather than claiming the model was unloaded. + +### JSON response formats + +`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or +`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`. +The schema must describe an object at its root. Local `#` references work; remote references are refused. +`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install +"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the +server says so once. + +This is **schema prompting followed by server validation**, not grammar-constrained decoding. One generation +is made per request, with no hidden retry. Successful responses contain a validated JSON object. Malformed JSON, +duplicate keys, non-finite numbers, schema violations and incomplete generations return **502** with +`error.code: structured_output_failed`; invalid request schemas return **400**. JSON formats combined with +tools/MCP are refused explicitly. Without `response_format`, ordinary text and tool behavior stays the same. + +Structured SSE buffers the answer while sending keep-alive comments. It emits content only after validation, +then usage/timings and `[DONE]`; failures emit an SSE error and `[DONE]` without invalid content deltas. +`/v1/status.structured_output` advertises the formats, validation method and buffered streaming behavior. + +### API request monitor + +Off by default, since it keeps prompts and answers in memory: turn it on with `"api_monitor": true` in +`strata-.json` (or `serve/server.py --api-monitor`); otherwise nothing is recorded and the two endpoints below +answer 404. +Open `/api-monitor` to inspect API traffic without opening a chat. It shows the model state, safe +load/unload controls, active/queued requests, original request bodies, output, separate reasoning and +non-stream response bodies. Total wall-clock includes FIFO waits and automatic loading; load, queue, +first-token, prompt/output tokens and engine decode timing are shown separately. + +`GET /api/requests` returns compact summaries; `GET /api/requests?id=` returns one retained request. +Both use the existing API-key check. The monitor retains the newest **100 requests in memory** until restart, +with **262,144 characters per input/output/reasoning/response field** and visible truncation flags. The actual API +responses are unaffected. Headers are not recorded, and the monitor key is kept in this tab's session storage. +Treat request history as sensitive input/output when exposing Strata on a network: set an API key as above. +The page uses relative URLs and works through the existing host binding or a reverse proxy. diff --git a/engine/strata/docs/HOW_IT_WORKS.md b/engine/strata/docs/HOW_IT_WORKS.md new file mode 100644 index 00000000..7c8f9eec --- /dev/null +++ b/engine/strata/docs/HOW_IT_WORKS.md @@ -0,0 +1,77 @@ +# How does Strata work? + +Models like Qwen3.8-Flash-Next normally run on servers with hundreds of gigabytes of graphics memory. Your graphics +card has 12-24 GB. Strata makes it fit by **sharing the work across your whole PC** - the same idea as a kitchen, where +the things you use all the time stay on the counter and the rest waits in the pantry. Back to the +[README](../README.md#how-does-it-work). + +## Who does what + +

The model's 24,576 experts: the busiest on the graphics card, all of them in RAM, a lookup table on the SSD

+ +- **The model is a team of 24,576 small specialists ("experts"),** and each word it writes needs only 10 of them. + So it doesn't have to have all of them on the graphics card at once. +- **Your graphics card** does the part of the work needed for every word, and keeps the few thousand experts that + are asked most often. It keeps learning which ones those are while you use it. +- **Your RAM** holds every expert. When a word needs one the card doesn't have, **your processor** works on it - + at the same time as the graphics card, so neither waits for the other. +- **Your SSD** holds a big lookup table; the model only reads a few small rows of it per word. + +The same in technical terms: + +- **GPU (VRAM):** attention and DeltaNet mixers, the gated-residual weights, routers, shared experts, output head, the + MTP draft layer, the KV cache (from 64K: only its most-read part, the rest streams from RAM), and an **expert + cache** that fills the rest of VRAM with the most-used experts (it adapts to the conversation while you chat). + More VRAM matters more than a faster GPU: every extra GB holds ~700 more experts, and every expert on the GPU is one + the CPU does not have to compute. +- **RAM:** all 24,576 experts, pinned. The CPU computes the experts that are not on the GPU **in place**, at the same + time as the GPU works on the cached ones (AVX-512 / AVX2 kernels, ggml's for the i-quants). On a PC with little RAM + and a big card, the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram) keeps in RAM only what the GPU does + not hold. +- **SSD:** the 28.8 GB n-gram table, read a few rows per token through the OS cache. + +This works the same on NVIDIA (CUDA) and AMD (HIP) cards: the same engine, compiled for each. + +## Guess, then check + +

A small helper guesses the next words; the big model checks them all at once and keeps the right ones

+ +- **Guess, then check.** A small, fast helper built into the model guesses the next few words, and the big model + checks all the guesses in one go. It keeps the ones it agrees with and writes the next word itself - so one step + often produces several words. The helper only guesses - the big model decides every word - so you get the same + quality answer, 1.6-1.8x sooner. +- In technical terms: the model's own MTP layer drafts up to 3 tokens; one pass over all 48 layers checks them, 2.4-3.2 + tokens per pass on average. When the reply repeats the context (code edits, quoted text), **prompt lookup** drafts + up to 5 tokens from the earlier copy, but only where its measured acceptance and cost say it pays: code edits 6-11% + faster, other text unchanged. The drafts are checked like the MTP's, so the output is the same. + +## Reading long texts + +**Long texts are read in big pieces** (up to 8,192 tokens - pieces of words - at a time), which is why a long +document or code base is read at over 1,000 tokens per second. The experts of the next layer stream to the GPU over +PCIe while the current layer's attention runs. After the first message, Strata keeps the conversation and reads only +what is new, so follow-ups start in seconds. + +## More + +The [details](DETAILS.md#how-it-works) explain every part and its numbers, and the +[paper](paper/Strata-Paper.pdf) tells the whole story, with the measurements behind it. + +## Credits + +- Model: [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) by the Qwen team; compressed versions by + [ISTA-DASLab](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF); + [Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF) by UkisAI; the experimental + [UD-Q4_K_XL](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF) by Unsloth (its support follows + [eddoursul/Strata](https://github.com/eddoursul/Strata)). Their licenses apply to the model files. +- Built with parts of [llama.cpp / ggml](https://github.com/ggml-org/llama.cpp) (MIT). Ideas from + [Splash](https://github.com/incoai/splash), [ninfer](https://github.com/Neroued/ninfer) and + [HyperQwen](https://github.com/syv-ai/HyperQwen). More in the [details](DETAILS.md#credits-and-licenses). +- The AMD (HIP) backend: [AMD_HIP.md](AMD_HIP.md) names the contributors and the machines it was validated on. + +## License + +Strata is open source under the [MIT License](../LICENSE). A few parts carry their own licenses: `third_party/ggml` +(MIT, llama.cpp / ggml), the web app's font (SIL Open Font License 1.1) and the experimental speed projection's +vector in `data/experimental-speed-projection` (Qwen Community License 1.0, from the model's activations). The +models are not part of this repository; each model's own license applies to its files. diff --git a/engine/strata/docs/INSTALL.md b/engine/strata/docs/INSTALL.md new file mode 100644 index 00000000..60927704 --- /dev/null +++ b/engine/strata/docs/INSTALL.md @@ -0,0 +1,187 @@ +# Installing Strata + +Everything about installing, starting, updating and configuring Strata, on Windows and Linux, with an NVIDIA or an +AMD graphics card. The short version is in the [README](../README.md#install); an AI coding assistant can do all of +this for you with [AI_SETUP.md](AI_SETUP.md). + +> **On this page:** [What you need](#what-you-need) · [Windows](#windows) · [Linux](#linux) · +> [AMD cards](#amd-cards) · [Several cards](#two-or-three-cards) · [Docker](#docker-linux) · [Updating](#updating) · +> [Where things are stored](#where-things-are-stored) · [Setup's questions](#setups-questions) · +> [Tuning](#tuning-for-your-pc) · [All options](#options-without-questions) + +## What you need + +| | | +| --- | --- | +| **GPU** | **NVIDIA** RTX 20, 30, 40 or 50 series, **12 GB VRAM or more** (8 GB runs, slowly). Measured on an RTX 5070 and an RTX 3090; RTX 20 (Turing, since 0.1.27) was tested by a contributor on an RTX 2070. **AMD** Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT and Radeon AI PRO R9700 (validated), RX 7800 XT / 7700 XT and RX 9060 XT (validated by their owners), RX 6800 / 6900 series (community-reported), with 12 GB of VRAM or more. See [AMD cards](#amd-cards). | +| **RAM** | Enough for the size you pick ([which model](MODELS.md#pick-by-ram)); **64 GB** runs every size. A big GPU makes up for less RAM - the [low-RAM mode](MODELS.md#a-big-graphics-card-and-little-ram). | +| **CPU** | x86-64 with AVX2 (any Intel/AMD desktop CPU from the last ~8 years). AVX-512 (Ryzen 7000/9000) is a bit faster. | +| **Disk** | ~70-80 GB free for the model, ~6 GB for the MTP layer (+1 GB with images). **Q2_0 on an AVX-512 CPU** also writes a one-time ~40 GB copy of its experts for the fast CPU kernel. On Linux with an AMD card, ROCm takes ~10 GB more when setup installs it. An NVMe SSD is strongly recommended: it makes the first start much faster. | +| **OS** | Windows 10/11, or Linux (Ubuntu 22.04/24.04 get everything installed automatically). | +| **Driver** | **NVIDIA:** a current driver, version 580 or newer ([nvidia.com/drivers](https://www.nvidia.com/drivers) or the NVIDIA App). **AMD:** on Linux the kernel's amdgpu driver (no ROCm install needed); on Windows a current AMD Software: Adrenalin Edition driver ([amd.com/support](https://www.amd.com/en/support)). | + +The driver is the only thing you install yourself. Everything else - Python, the engine, the model - is set up for +you the first time: Python 3.12 if you have none (for your user account, no admin), a private Python environment in +`.venv/`, the Strata engine, the model and the MTP draft layer. On NVIDIA it uses the ready-made engine for RTX +20/30/40/50 and NVIDIA's CUDA libraries from pip (~0.4 GB); if no ready-made engine fits your PC, it offers to install +the build tools (Visual Studio Build Tools + CUDA Toolkit on Windows, `build-essential` + CUDA on Ubuntu) and compiles +the engine for your GPU (asks first; 20-40 minutes once). More: [details](DETAILS.md#before-you-start). + +## Windows + +1. [Download this project](https://github.com/Niko1221/Strata/archive/refs/heads/main.zip) and unzip it (or + `git clone` it). +2. Double-click **`START-HERE.bat`**. +3. Answer a few questions - or just press Enter each time for the recommended choice ([the questions](#setups-questions)). + +Then it downloads everything (the model is ~70 GB, so the first time takes a while - you can stop and it picks up +where it left off) and **starts the model**. Your browser opens the Strata app at `http://127.0.0.1:8080`. + +> **While the model starts, your PC can be slow or stop responding for 1-3 minutes** (longest the first time): Strata +> loads 35-55 GB into your RAM and locks part of it for the graphics card. That's normal - wait, and don't close the +> window. The window tells you what it is doing. + +**Next time**, just double-click `START-HERE.bat` again: it starts right away (30-90 s to load the model), nothing is +downloaded twice. Close its window to stop the model. `SETUP.bat` (the same as `START-HERE.bat --setup`) installs +another model or changes the settings. Starting Strata from Task Scheduler at logon needs two task settings, or the +start is 24x slower: [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). + +## Linux + +```bash +./setup.sh +``` + +The same questions, the same automatic install (it uses `sudo apt` for Python and, only if it has to compile, for +the build tools), and the same start: `http://127.0.0.1:8080`. Later runs of `./setup.sh` (or `./run-.sh`) +start the model directly; `./setup.sh --setup` installs another model or changes the settings. Other distributions, +WSL and compiling: [details](DETAILS.md#linux). + +## AMD cards + +The steps are the same as with NVIDIA: `START-HERE.bat` on Windows, `./setup.sh` on Linux. Setup finds the Radeon +card and chooses the AMD (HIP) engine by itself on a PC with no NVIDIA card Strata can use; `--backend hip` chooses +it on a PC that has both. Supported cards: RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT +(gfx1200), RX 9070 / 9070 XT and Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030). Integrated +Radeon GPUs are listed as not supported. + +On Linux setup uses a system ROCm 7 when there is one, or installs ROCm into `.venv` from AMD's wheels (~10 GB, no +sudo), and compiles the engine on your PC for the card (10-20 minutes, once; it needs a C++ compiler and git: +`sudo apt install build-essential git`). Several AMD cards share the model with `--gpus`, as on NVIDIA. + +What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, 10-30 s per +picture), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the +build by hand and the tuning tables: [AMD_HIP.md](AMD_HIP.md). + +## Two or three cards + +**Two or three NVIDIA cards?** Just run `START-HERE.bat`: it lists your cards, says which ones Strata can use, and +asks whether to share the model across them (recommended when two can). An install made on one card asks once at +its next start. Or choose yourself: `START-HERE.bat --gpus 0,2` (both, remembered), `--gpus all`, or `--gpu 0` (one +card, this start only). Each card keeps the experts of its own layers, and prompts flow through the cards in a +pipeline: on an RTX 5080 + RTX 3090 prompts were read 18-20% faster than on the 5080 alone, decoding on par. +Every card must be an RTX 20 series or newer with 8 GB or more. See [MULTI_GPU.md](MULTI_GPU.md). + +**Several AMD cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: +`--gpus 1,0` splits the model's layers across them, the first one the main card (numbers as setup lists them). A +split pays only when no single card holds the model's experts ([AMD_HIP.md](AMD_HIP.md#rdna4-gfx1201)). + +## Docker (Linux) + +The same idea, in a container (NVIDIA cards). + +1. Host: Docker with the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) + and a driver **580 or newer** (CUDA 13.0). +2. Build (this compiles the engine into the image, so the container never compiles): + `docker build -t strata .` + `docker build -t strata --build-arg CUDA_ARCHITECTURES=89 .` builds for one card only (faster). + The default covers RTX 30 (86), RTX 40 (89), RTX 50 (120) and A-series (80); a card outside that + set needs a rebuild with its own arch. Add `--build-arg BUILD_VISION=0` to skip the image encoder. +3. Run (the first start downloads the ~70 GB model, then starts; later starts go straight to serving): + `docker run --rm --gpus all -p 8080:8080 --ulimit memlock=-1 -v strata-data:/data strata` + + The setup choices are env vars: `-e MODEL=IQ2_XS -e FAMILY=qwen -e CONTEXT=32768 -e VISION=no` + (or `MODEL=Q2_0|IQ3_XXS|IQ3_S`, `FAMILY=swift|coder`; the defaults above are the recommended ones). + `-e VISION=cpu` keeps the image encoder on the CPU. `-e KV=int8|q4_0|k8v4` picks the KV cache + precision; `k8v4` is INT8 K with 4-bit V and keeps its KV in VRAM from 64K up. + Only the model files, the prepared pack, the MTP layer and the install config live in the + `strata-data` volume; the engine is part of the image. Switching between models already on the + volume needs no setup pass: `-e MODEL=Q2_0 -e FAMILY=coder` picks that model's config. Add + `-e REINSTALL=1` only to change settings for a model already set up (context, vision, KV, host, + api_key, LOW_RAM), since those are recorded in its config. + Strata loads 32-62 GB into RAM. `--gpus all` on a host with two usable cards takes both: the + layer split is setup's recommended default ([MULTI_GPU.md](MULTI_GPU.md)), and a volume + set up for one card switches to the pair on its first start there. Pin one card with `-e GPU=0`, + or name them with `-e GPUS=0,2` and where the later card's layers start with `-e LAYER_SPLIT=18`. + A memory limit needs `-e LOW_RAM=on`, which maps the model's experts from the pack instead of + keeping them in RAM: setup.py measures the host's RAM, not the container's limit, so it cannot + see a cap. LOW_RAM runs on one card unless `GPUS` names several (then the experts the cards do not hold are + read through the OS file cache, which can fill the RAM during long prompts). + The server listens on `0.0.0.0:8080` by default; set `-e API_KEY=` before exposing the port + to a network. The image has a `HEALTHCHECK` on `/health`, so `docker ps` shows the container + healthy once the model is loaded, and `GET /v1/status` says what it is running. + +## Updating + +Download the new version and unzip it anywhere (or `git pull`), then run `START-HERE.bat` (Linux: `./setup.sh`) in +it. The model files are kept in a `Strata-data` folder next to your Strata folder, so a new copy finds them and sets +itself up the same way - nothing big is downloaded again. On Linux after a `git pull`, setup compiles the engine +again when its source changed (a minute or two for the changed files); if that compile fails, it says so and starts +the engine you had. + +## Where things are stored + +- **Your chats: only in your browser.** The Chat tab keeps the conversation, its settings and the API key you typed + in the browser's local storage (`strata.*` keys) - not on the server and not in the Strata folder. Pictures are not + kept, only their names. Another browser or a private window starts empty; clearing the site's data deletes them. +- **How the model starts:** `strata-.json` in the Strata folder (context, GPUs, host, API key, ...), written + by setup; next to it `run-.bat` / `.sh`, the log `strata-.log` and, when you use "Use for other + apps too", `strata-.shared-settings.json`. +- **The model files** (`models/`, `packs/`, `mtp/`, 70-120 GB): in **`Strata-data` next to the Strata folder**, or + wherever `--data-dir` put them. +- **Where that data folder is:** `%APPDATA%\Strata\settings.json` on Windows, `~/.config/strata/settings.json` on + Linux ([details](DETAILS.md#before-you-start)). +- **The program itself:** `.venv/`, `engine/` and `third_party/` in the Strata folder. + +## Setup's questions + +- **Which model and size?** The original, Swift 1.5, the Coder or Unsloth's 4-bit, and Q2_0, IQ2_XS, IQ3_XXS or + IQ3_S - see [which model](MODELS.md). +- **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and + 512K (experimental) extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a + covering factor; `--rope-scaling`/`--rope-scale` override) ([details](DETAILS.md): "Context extension past + 262K"). +- **Images?** Whether it should also read pictures. The image encoder (0.9 GB) runs on the GPU (0.1-0.5 s per + picture, ~1.4 GB of VRAM kept free for it) or on the CPU (10-30 s per picture, nothing on the GPU); with AMD cards + on the CPU for now. [Details](DETAILS.md#images-vision). +- **Experimental speed projection?** Off unless you say yes - [read what it does](DETAILS.md#experimental-speed-projection-experimental-off-by-default) + first. It changes how the model answers, and only the original model offers it. + +With `--yes` setup takes the recommended answer to every question. + +## Tuning for your PC + +Every PC is different: `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) measures a few engine settings +on yours and keeps the fastest (about 5-10 minutes; on an RTX 5070 with a Ryzen 5 7600 it made the Coder 7% faster). +It keeps a setting only when it is more than 3% faster, and the result is remembered per PC and model, so updates +keep it. NVIDIA cards for now. [What it measures](DETAILS.md#double-click-start-herebat). + +## Options without questions + +``` +START-HERE.bat --setup install another model, or change context / images +SETUP.bat the same (double-click it) +START-HERE.bat --model IQ2_XS --context 32768 --vision yes --yes no questions +START-HERE.bat --gguf-dir D:\models\IQ2_XS use GGUF files you already have +START-HERE.bat --data-dir E:\Strata-data keep the model files somewhere else +START-HERE.bat --port 8081 another port +START-HERE.bat --gpu 1 another GPU (setup picks the one with the most VRAM) +START-HERE.bat --gpus 0,2 several GPUs sharing the model +START-HERE.bat --setup --backend hip the AMD engine on a PC that also has an NVIDIA card +START-HERE.bat --setup --host 0.0.0.0 --api-key reachable from other devices, with a key +START-HERE.bat --calibrate tune the engine for this PC (about 5-10 minutes), then start +START-HERE.bat --check only check this PC +``` + +On Linux the same options go to `./setup.sh`. `START-HERE.bat --help` lists them all. The server's own settings +(sharing the GPU with games, MCP tools, CORS, API keys, the API itself) are in the [details](DETAILS.md#using-it). diff --git a/engine/strata/docs/MCP_SERVER.md b/engine/strata/docs/MCP_SERVER.md new file mode 100644 index 00000000..b72c659c --- /dev/null +++ b/engine/strata/docs/MCP_SERVER.md @@ -0,0 +1,205 @@ +# Strata's MCP server: let your AI assistant install and run Strata + +`tools/strata_mcp.py` is an [MCP](https://modelcontextprotocol.io) server for the AI assistant you already use +(Claude Code, Claude Desktop, Cursor, VS Code, Codex ...). Add it once, then ask in plain words: + +- "Install Strata for this PC." +- "Start Strata." / "Stop Strata." +- "Is Strata running? How much VRAM does it use?" +- "Which Strata model fits my PC?" +- "Strata didn't start - what does the log say?" +- "How fast is Strata on this PC?" (a short speed test) +- "How do I connect Open WebUI / the OpenAI SDK / Claude Code to Strata?" + +The assistant calls the server's tools. The tools run Strata's own setup and start the model the way the start +scripts do. It is one Python file that uses only the standard library, so it works before setup has created +`.venv`. It needs Python 3.10 or newer, 64-bit on Windows. + +It is not the same thing as [Tools from MCP servers](DETAILS.md#tools-from-mcp-servers). That feature +(`serve/mcp.py`) lets the *Strata model* call tools from your MCP servers in its chat page. This page is the other +direction: *your assistant* manages Strata. + +## Add it + +You need a copy of Strata: the zip from GitHub, or `git clone https://github.com/Niko1221/Strata`. Below, +`C:\Users\you\Strata` (Windows) and `/home/you/Strata` (Linux) stand for that folder. Use `python3` on Linux. On +Windows, use `py` if `python` is not on your PATH. + +### Claude Code + +```bash +claude mcp add strata -- python C:\Users\you\Strata\tools\strata_mcp.py # Windows +claude mcp add strata -- python3 /home/you/Strata/tools/strata_mcp.py # Linux +``` + +Add `--scope user` to have it in every project. `/mcp` in Claude Code shows that it is connected. + +### Claude Desktop + +Open Settings > Developer > Edit Config (`claude_desktop_config.json`) and add: + +```json +{ + "mcpServers": { + "strata": { + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +On Linux, use `"command": "python3"` and `"args": ["/home/you/Strata/tools/strata_mcp.py"]`. Restart Claude +Desktop after the change. + +### Cursor + +Use `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` in one project. The format is the same as +Claude Desktop's: + +```json +{ + "mcpServers": { + "strata": { + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +### VS Code (GitHub Copilot agent mode) + +Use `.vscode/mcp.json` in a workspace, or run "MCP: Open User Configuration" from the command palette: + +```json +{ + "servers": { + "strata": { + "type": "stdio", + "command": "python", + "args": ["C:\\Users\\you\\Strata\\tools\\strata_mcp.py"] + } + } +} +``` + +On Linux, use `"command": "python3"` and `"args": ["/home/you/Strata/tools/strata_mcp.py"]`. + +### Codex CLI + +In `~/.codex/config.toml`: + +```toml +[mcp_servers.strata] +command = "python" +args = ['C:\Users\you\Strata\tools\strata_mcp.py'] # Linux: command = "python3", args = ["/home/you/Strata/tools/strata_mcp.py"] +tool_timeout_sec = 180 # strata_stop / strata_benchmark can take longer than 60 s +``` + +### Any other MCP client + +The command is `python /tools/strata_mcp.py`. The transport is stdio. It speaks MCP revision +2025-06-18, and also 2025-03-26 and 2024-11-05. + +`--root ` manages a Strata folder other than the one the file is in. For example: +`python D:\tools\strata_mcp.py --root D:\Strata`. + +## The tools + +| Tool | What it does | Arguments (all optional) | +| --- | --- | --- | +| `strata_status` | Whether a model is running: the model, engine version, context, busy or idle, VRAM and RAM in use. What is installed: models, start scripts, engine version, data folder, downloads. An install in progress. This PC's hardware: OS, CPU, RAM, GPUs, page file, free disk. The model and context setup recommends for this PC. | `port`, `hardware` (true/false) | +| `strata_models` | Every family and size setup offers, with download size, RAM needed, whether it fits this PC, and whether it is installed. Also the context lengths and the recommendation. | - | +| `strata_install` | Runs setup without questions, in the background (see below). Without `confirm: true` it only returns the plan. A second call shows the progress. `cancel: true` stops the install. | `family` (qwen, swift, coder, unsloth), `model` (Q2_0, IQ2_XS, IQ3_XXS, IQ3_S, IQ1_M, UD-Q4_K_XL), `context` (8192 ... 524288), `vision` (no, yes, gpu, cpu), `kv` (int8, q4_0, k8v4), `gpu` (a number) or `gpus` ("0,2", "all"), `backend` (auto, cuda, hip), `low_ram`, `port`, `data_dir`, `confirm`, `cancel` | +| `strata_start` | Starts an installed model in the background and waits until it answers. If it is not ready after `wait_seconds` (default 50), it returns "loading". | `model` (an id from `strata_status`, e.g. `q2_0`, `coder-iq1_m`; default: the most recently used), `port`, `gpu`, `wait_seconds` (0-600) | +| `strata_stop` | Unloads the model through the server's own API, then ends the server it started. | `port`, `force` | +| `strata_logs` | The last lines of the server log, the engine log or the setup log. | `source` (server, engine, setup), `model`, `lines` (1-500) | +| `strata_benchmark` | Sends a short fixed request (greedy, thinking off) and reports output and prompt tokens/s. | `port`, `max_tokens` (16-512) | +| `strata_connect_info` | The OpenAI and Anthropic base URLs, the model id, whether a key is needed, and settings for Claude Code, Codex, the OpenAI SDK, curl, Cursor, Continue and Open WebUI. | `port` | + +Every result is JSON with a one-line `summary`. It is sent both as text and as MCP structured content. + +## How it works + +**Install.** `strata_install` uses setup's own logic and tables (it imports `setup.py`'s `MODELS`, `FAMILIES`, +`CONTEXTS` and RAM checks) to fill in what you left out: + +- the size setup itself would pick: IQ3_XXS from 60 GB of RAM, Q2_0 from about 44 GB, the Coder from about 28 GB, + and the Coder in the low-RAM mode below that when the GPU makes up for the RAM; +- the context setup recommends for the GPU's VRAM; +- images off. + +The first call returns the plan: the download size (58-111 GB), the free disk space, the RAM check, and the exact +setup command. The assistant should show you the plan and call again with `confirm: true` once you agree. + +It then runs the same steps `START-HERE.bat` / `setup.sh` run: + +1. It creates `.venv` with the Python it runs on, if `.venv` is missing. +2. It runs `setup.py --yes --no-start --family ... --model ... --context ... --vision ...` as a background process. + The output goes to `.strata-mcp/setup.log` in the Strata folder. + +The tool returns at once. Call it again to see the step (1-7), the download percentage, or setup's error message. +Everything setup has finished is skipped on the next run, and downloads resume. If the AI app closes, the install +keeps running. The install is refused while a model this server started is running, because setup may replace the +engine files that model uses. + +**Start.** `strata_start` runs the same command as the `run-` script, `serve/server.py --engine strata +--config strata-.json --port N`, with the venv's Python, without `--open` (no browser) and without a console +window. The server's output goes to `.strata-mcp/server.log`. The tool then polls `GET /health` until the model +answers. Loading takes 1-3 minutes. If the server ends while loading, the tool returns the end of its log. The model +keeps running after the AI app closes, until `strata_stop`. If the AI app runs its tools inside a Windows job that +does not allow processes to leave it, the model ends together with the app. + +Two cases are refused: + +- a model is already running: the tool returns it and starts nothing; +- another program uses the port: the tool says so. + +**Stop.** `strata_stop` first sends `POST /unload`. The server sends the engine `QUIT`, and the engine frees its +VRAM and pinned RAM itself, as when you close the window. Then the server ends: + +- Linux: SIGTERM, which runs the server's own Ctrl+C path. +- Windows: the process ends. Its job object ends the vision encoder and the MCP servers it started. + +While a request is running, the tool refuses unless you pass `force: true`. + +**Status.** The tool reads `GET /health`, `/v1/status`, `/status` and, on older servers, `/metrics` on 127.0.0.1. +If a config of the folder sets an `api_key`, the tool sends that key with its own requests. It never shows the key. + +## Safety + +- **No shell, no free paths.** Every argument is checked against a fixed schema and against setup's own choices. An + unknown argument, a model or family setup does not offer, or a `gpus` value other than digits and commas is + refused before anything runs. Commands are passed as argument lists; nothing goes through a shell. +- **Paths.** The only path argument is `data_dir`. It must be one of: + - the current Strata data folder; + - a folder inside the Strata folder; + - a new absolute folder whose name starts with `Strata` (e.g. `D:\Strata-data`), whose parent exists, and which is + not in a system folder. + + `..`, relative paths and network (UNC) paths are refused. Logs are read only from `.strata-mcp/` and from the + engine log a config names, if that log is inside the Strata folder or the data folder. +- **Only its own processes.** The server records the process id *and start time* of every process it starts, in + `.strata-mcp/*.json`. It only ends a process when both match, so a process id the OS has given to another program + is never touched. A Strata started some other way (its window, a run script, a service) is only asked over its + API to unload the model. To end that server, close its window. +- **Big downloads need a yes.** `strata_install` does nothing until it is called with `confirm: true`. The plan + shows the download size and the free space first, and the install is refused if the disk is too small. +- **Local only.** The server checks `127.0.0.1` and never changes the network settings: it does not install with + `--host 0.0.0.0` or an API key. To share Strata on your network, run setup yourself (see + [Using it](DETAILS.md#using-it)). Experimental options are left off too: the speed projection, rope scaling past + 262K and `--build`. Run setup by hand for those. + +## Troubleshooting + +- **The assistant does not see the tools.** Run the command by hand: + `python C:\Users\you\Strata\tools\strata_mcp.py`. It should print `[strata-mcp] ready (Strata folder ...)` to + stderr and wait for input (Ctrl+C ends it). If it reports `not a Strata folder`, the path is wrong or `--root` is + needed. Python older than 3.10 is refused. +- **The install failed.** Ask the assistant for the setup log (`strata_logs` with `source: setup`), or open + `.strata-mcp/setup.log`. Setup's `[X]` line says what to fix. Then install again: every finished step is skipped. +- **The model does not start.** Get the server log with `strata_logs`, and the engine log with `source: engine`. + [Troubleshooting](DETAILS.md#troubleshooting) has the usual causes. +- **Tests.** `python -m unittest tools/test_strata_mcp.py` runs the tests with a fake setup and server. They do not + download anything or use the GPU. diff --git a/engine/strata/docs/MODELS.md b/engine/strata/docs/MODELS.md new file mode 100644 index 00000000..fb411700 --- /dev/null +++ b/engine/strata/docs/MODELS.md @@ -0,0 +1,139 @@ +# Which model? Sizes, versions and what fits + +Strata runs one model, [Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next), in several **sizes** +(the same model, compressed more or less) and several **versions** (the original, a coding version, a fine-tune). +The installer recommends one for your PC; this page explains the choice. Back to the [README](../README.md). + +> **On this page:** [Pick by RAM](#pick-by-ram) · [Speed](#how-fast-is-each-size) · [The sizes](#the-sizes) · +> [Will it fit?](#will-it-fit) · [The versions](#the-versions) · [Adding another model](#adding-or-switching-models) + +## Pick by RAM + +| Your RAM | Take | Why | +| --- | --- | --- | +| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too: [low-RAM mode](#a-big-graphics-card-and-little-ram)) | +| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit | +| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits (IQ3_S with little else open) | +| **96 GB or more** | **IQ3_S**, or [Unsloth's 4-bit](#unsloth-ud-q4_k_xl-experimental) (experimental) | room for the largest sizes | + +Not sure? Take **IQ2_XS** - or the **Coder** if you mainly write code, or have 32-48 GB of RAM. + +## How fast is each size + +Measured on an RTX 5070 (12 GB), a Ryzen 5 7600 and 64 GB of RAM: + +| Size | Writes answers (short chat) | Writes answers (128K context) | Reads your prompt | +| --- | ---: | ---: | ---: | +| **Q2_0** | 93 tokens/s | 74 tokens/s | 2,170 tokens/s | +| **IQ2_XS** | 79 tokens/s | 63 tokens/s | 2,090 tokens/s | +| **IQ3_XXS** | 62 tokens/s | 49 tokens/s | 1,750 tokens/s | +| **IQ3_S** | 53 tokens/s | 46 tokens/s | 1,620 tokens/s | +| **Coder** (IQ1_M) | 55 tokens/s | 43 tokens/s | 2,180 tokens/s | + +Measured on an AMD RX 9070 XT (16 GB), a Ryzen 9 3900X and 47 GB of RAM (Linux, setup's own install; Q2_0 is +above setup's RAM estimate for 47 GB and was installed with `--model Q2_0 --yes`): + +| Size | Writes answers (short chat) | Writes answers (128K context) | Reads your prompt | +| --- | ---: | ---: | ---: | +| **Q2_0** | 60 tokens/s | 48 tokens/s | 1,160 tokens/s | +| **IQ2_XS** | 52 tokens/s | 36 tokens/s | 1,110 tokens/s | +| **Coder** (IQ1_M) | 44 tokens/s | 33 tokens/s | 1,420 tokens/s | + +- **Writes answers** = how fast the reply appears (tokens per second; a token is about ¾ of a word). +- **Reads your prompt** = how fast it takes in what you send (long documents, code, chat history), measured on a + 32K-token prompt; a 4K prompt reads at 910-1,580 tokens/s. A 32K prompt takes about 15 seconds with Q2_0. + +A card with more VRAM is faster, because more of the model fits on the GPU: an RTX 3090 (24 GB) should do roughly +100-140 tokens per second. All measurements, long-context numbers and estimates for other cards are in the +[details](DETAILS.md#speed-measured). The AMD measurements per card (RX 9070 XT, Radeon AI PRO R9700, RX 7800 XT, +RX 9060 XT, RX 6900 XT) are in [AMD_HIP.md](AMD_HIP.md#rdna4-gfx1201). + +Every PC is different: `START-HERE.bat --calibrate` measures a few engine settings on yours and keeps the fastest +(about 5-10 minutes; on the PC above it made the Coder 7% faster; NVIDIA cards for now). Measured Strata on your own +PC? See [Community benchmark results](COMMUNITY_BENCHMARKS.md) for a report template and how to share your results +in a pull request. + +## The sizes + +| Model | RAM+VRAM Requirements | Speed | Quality | +| --- | ---: | --- | --- | +| **Q2_0** | 37.6 GB | fastest | good | +| **IQ2_XS** | 39.2 GB | fast | better (**recommended**) | +| **IQ3_XXS** | 47.0 GB | slower | great | +| **IQ3_S** | 54.8 GB | slowest | best: matches the full model on the published tests (original model only) | + +The download is 66-76 GB for the three smaller sizes ([details](DETAILS.md#which-model)); the first start also +fetches the MTP draft layer (~6 GB, +1 GB with images). + +## Will it fit? + +Shard 1 is the part of the model that gets loaded when it starts: its experts go into your **RAM**, the rest onto +your graphics card (the second shard, a 29 GB lookup table, stays on the SSD). So it fits when your **RAM is at least +shard 1 + about 10 GB** for Windows and your other programs. With 64 GB of RAM every size fits (IQ3_S with little +else open); with 48 GB, Q2_0 and IQ2_XS. A bigger graphics card makes it faster, but it doesn't lower the RAM needed +- except in the low-RAM mode below. + +### A big graphics card and little RAM + +On a PC whose RAM cannot hold the experts beside the system, setup maps them from the model's files instead and keeps +in RAM only what the graphics card does not hold (the [low-RAM mode](DETAILS.md#speed-measured), chosen by setup). For +example, a 32 GB PC with a 24 GB GPU runs Q2_0, IQ2_XS and the Coder this way, and a 32 GB PC with a 12-16 GB GPU the +Coder. With a small card most experts then come from the SSD and it is much slower (setup says so). +`START-HERE.bat --setup --low-ram on|off` overrides the choice. + +## The versions + +### Qwen3.8-Flash-Next + +The original, in all four sizes. With images, and with the +[experimental speed projection](DETAILS.md#experimental-speed-projection-experimental-off-by-default) as an option. + +### Coder + +**[Coder](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)** - ISTA-DASLab's coding version: +half of the experts removed, keeping the ones that code, tool use and images need (91% of the full model's SWE-bench +Verified score, 99% of LiveCodeBench, by its authors). One size (IQ1_M: its experts stored like IQ3_S): shard 1 is +**29.6 GB**, so it fits a PC with **32 GB of RAM**, runs 262K context on 64 GB, and reads long prompts the fastest of +all. It is weaker outside code, and that includes Chinese and other CJK text (#438: Chinese answers came out wrong +or looping where English was fine). For general chat or CJK text, take a size that keeps every expert: Q2_0, +IQ2_XS or IQ3_S. +More: [details](DETAILS.md#or-the-coder-half-the-experts-for-code). + +``` +START-HERE.bat --setup --family coder +``` + +### Swift 1.5 + +**[Swift 1.5](https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF)** - a fine-tune by UkisAI that +thinks much shorter before answering, so you get the answer sooner, with about the same quality. Same speed per +token, and about the same RAM as the same size of the original (no IQ3_S). Its own license applies (see its page). +More: [details](DETAILS.md#or-swift-15-a-fine-tune-that-thinks-shorter). + +``` +START-HERE.bat --setup --family swift --model IQ2_XS +``` + +### Unsloth UD-Q4_K_XL (experimental) + +**Unsloth's 4-bit UD-Q4_K_XL** (experimental) is the fourth version in setup's menu (`--family unsloth`): the closest +to the full model, but a 111 GB download whose 77 GB of experts do not fit in RAM. Strata keeps your RAM minus 24 GB +of them in RAM and reads the rest from the SSD while it answers: 7-8.5 tokens/s on a 64 GB PC with a 12 GB GPU, several +times slower than the sizes above, and long prompts are slow. It needs 48 GB of RAM or more, an NVMe SSD and one +NVIDIA GPU (no images yet). Details and measurements: [UD-Q4_K_XL](UNSLOTH_Q4.md). + +``` +START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL +``` + +### OrcaRouter Uncensored IQ3_XXS + +For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](ORCA.md). It needs an +explicit packing conversion and is not an installer menu option. + +## Adding or switching models + +You can add another model any time with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux +`./setup.sh --setup`). Files another model shares are not downloaded again (the Coder uses the original's shard 2 and +vision encoder). With more than one model installed, `START-HERE.bat` asks which one to start; `run-.bat` +(Linux: `run-.sh`) starts one directly. diff --git a/engine/strata/docs/MULTI_GPU.md b/engine/strata/docs/MULTI_GPU.md new file mode 100644 index 00000000..1008620e --- /dev/null +++ b/engine/strata/docs/MULTI_GPU.md @@ -0,0 +1,141 @@ +# Strata on two or three GPUs (layer split) + +One model can run across several NVIDIA cards in one PC. The layers are split into contiguous ranges, one per GPU: +the first card runs layers 0 to K-1, the next card runs K onward, and so on; the last card also runs the output head +and the draft (MTP) layer. Each card keeps an expert cache for **its own layers only**, so two cards hold about twice +the experts one card holds - for the Coder model on a 16 GB + 24 GB pair, nearly all of them, which is where the +speed comes from (decode then barely touches the CPU pool). + +This is pipeline (layer) parallelism, not tensor parallelism: a token crosses from one card to the next once per +verify window (a few hundred KB through pinned RAM), not twice per layer. No NVLink or peer-to-peer access is +needed; cards on x4 or x1 slots work, and the PCIe share of each card is probed on its own link. + +## Using it + +**Nothing to type.** `START-HERE.bat` (Linux: `./setup.sh`) lists your NVIDIA cards and says for each one whether +Strata can use it: + +``` + Your NVIDIA GPUs: + GPU 0: NVIDIA GeForce RTX 5080, 16 GB VRAM - can be used + GPU 1: NVIDIA GeForce GTX 1080 Ti, 11 GB VRAM - not supported - older than the RTX 20 series (compute capability 6.1; Strata needs 7.5 or newer) + GPU 2: NVIDIA GeForce RTX 3090, 24 GB VRAM - can be used + ... + 1) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) + GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) together (recommended) + 2) GPU 2 (NVIDIA GeForce RTX 3090, 24 GB) only + 3) GPU 0 (NVIDIA GeForce RTX 5080, 16 GB) only +Which GPUs? [1]: +``` + +When two or more cards can share the model, the two best together are recommended (the newest generation first: +it becomes the main card). A model installed on one card asks once, at its next start, whether to use both from +now on; the answer is kept. + +**Choosing yourself** (at setup or at any start): + +``` +--gpus 0,2 these cards together, as nvidia-smi numbers them; the first is the main one. Remembered. +--gpus all every card that can share the model +--gpu 0 one card (at a start: for that start only) +--layer-split auto (default) or the first layer of each later card, e.g. 18 or 16,32 +``` + +**Not supported** (setup says so and names the cards that can be used instead): +- a card older than the RTX 20 series (compute capability below 7.5: GTX 10 and older); +- a card with less than 8 GB of VRAM, together with others (each card holds a copy of the dense weights and its + own prompt buffers) - unless you name it with `--gpus`: then setup says the risk and asks (`--yes` with the named + cards goes ahead); +- Intel GPUs, and a mix of NVIDIA and AMD cards. (AMD cards share a model among themselves: `./setup.sh --backend + hip --gpus 1,0`, see [AMD_HIP.md](AMD_HIP.md).) + +Or edit an existing config (`strata-*.json`), then restart: + +```json +"gpu": [0, 2], +"layer_split": "auto" +``` + +**Skip the split when the first card holds everything** (opt-in, 0.1.31): `"split_skip_if_fits": true` in the config +(engine flag `--split-skip-if-fits`, with `--layer-split auto`) runs on the first card alone when it holds every +profiled expert plus the context's KV, the draft layer and the reserve, and says so in the log; otherwise the split +stays. On an R9700 32 GB + RX 9070 XT the R9700 holds all of the Coder's experts: with the flag 4K prompts read at +1,776 tok/s instead of 1,244 (split) and decode runs at ~60 tok/s instead of ~51 (16K prompts ~5% slower than split). + +**Short prompts on a split (0.1.32, #340).** 0.1.30 gave each card's prompt path a loan from its own expert cache, +refilled after every request; on cards that hold nearly all their experts that cost short prompts up to a third of +their speed. 0.1.32 refills all cards at once, uses a smaller streaming ring on a split, and lets a card with free +VRAM keep its own prompt buffers - the same output as 0.1.31, measured on an R9700 + RX 9070 XT: 2K prompts 993 -> +1,265 tok/s, 16K 1,852 -> 1,950, decode unchanged. `STRATA_SPLIT_OWN=1` (opt-in) gives every card its own buffers: +2K 1,450 and 16K 2,227 tok/s there, but a full card then keeps a different set of experts resident, so the output +differs from the default's (stable and coherent); `STRATA_SPLIT_OWN=auto` does that only where the buffers are at +most 12% of each card's VRAM. + +The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages' +devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing +everything - the bit-exact check of the hand-off, not a speed mode. + +**auto** tries every placement (all of them for two or three cards; proportional to the free VRAM beyond that) and +keeps the one whose caches would hold the most of the expert profile, hottest pairs weighted most; ties go to the +placement that leaves the fullest card the most room. The startup log prints the choice: + +``` +strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%) +strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window +``` + +## What each card holds + +- **every card**: a copy of the dense weights (~3.4 GB for the Coder), its own session state (the KV cache of the full + context), its verify window and its prompt-path buffers, and an expert cache for its layers filled from the profile; +- **the last card**: also the output head and the draft layer (~0.8 GB); +- **host RAM**: the expert arena once, shared by all cards (the CPU pool computes whatever no card holds). + +Prompts are read in chunks that flow through the cards in turn; while a later card reads chunk c, the first card +already reads chunk c+1. Conversation checkpoints save and restore every card's state; the adaptive expert swaps copy +into the card that owns the layer. + +## Limits (for now) + +- **Works across cards** (bench/results/2026-09-29-layer-split-limits): + - images (`--vision`): each card keeps its own image-position table; + - control vectors and the experimental speed projection: each card holds the vector's tables, switched on and + off per request on all of them; + - KV streaming (`--kv-resident`): each card streams the KV of its own session; + - mid-prompt checkpoints (`--prompt-cache-every`): each card saves its part of a checkpoint when it has read that + chunk; + - the older helper-GPU caches (`--expert-cache-remote`, docs/SECOND_GPU.md): they take the visible GPUs no stage + runs on, and hold only experts no stage's cache holds. On the test rig, a 2080 Ti helper made decoding slower, + as it did without a split: its per-layer round trip costs more than the CPU pool needs for those experts. +- `--mmap-experts` needs a canonical pack (`experts.bin`), with or without a split; a native (IQ) pack says so at + start. +- The prompt path has its own buffers on every card (1.5 GB each at the default 2048-token chunk; `--prefill 1024` + halves that) instead of borrowing cache slots as one card does. An explicit `--expert-cache` on the first card is + capped to leave room for them. +- Under WDDM (Windows, and WSL2) only 8 GiB of the expert arena is pinned (more, mapped into two GPU contexts, + leaves WDDM refusing allocations); the rest streams through the pinned staging ring. A Linux driver has no such + limit, so there the whole arena is pinned (since 0.1.31; the cap cost a 4090 + 3060 split two thirds of its + prompt speed, #253). `STRATA_ARENA_PIN_GIB=N` pins at most N GiB, `0` the whole arena, on any OS. +- Every card needs compute capability 7.5 (RTX 20 or newer). The pre-sm_80 QSA scorer path is fp32 FMAs, so a + Turing card runs the same kernels instead of the tensor-core prompt attention. + +## Measured + +The Coder on an RTX 5080 + RTX 3090 (Ryzen 9 9950X3D), 32K context; details in +`bench/results/2026-09-29-layer-split/`: + +| | Prompt 16K / 28K tok/s | Decode story / code tok/s | +|---|---|---| +| 5080 alone | 1,726-2,017 / 1,970 | 83-87 / 88-105 | +| 5080 + 3090, best split (K=26) | 2,039 / 2,357 | 84 / 110 | +| 5080 + 3090, auto (K=22) | 2,037 / 2,073 | 80 / 109 | + +- **Prompts gain the most** (+18-20%): each card reads its own layers of the chunk while the other reads the next. +- **Decode is on par with the faster card alone**, and ahead on code. Once both caches hold nearly every routed + expert, the per-layer GPU time decides. +- **Correctness:** one GPU is byte-identical to 0.1.20, and the hand-off itself is bit-exact. + +**Which cards and in what order:** +- Put the fastest card first; auto gives it as many layers as its cache allows. +- Leave out a much slower card when two already hold the model. An RTX 2080 Ti as a third card made the 5080 + + 3090 pair slower (68 / 90 tok/s decode): every extra card costs its own round per window. +- More cards pay off when the model's routed experts do not fit the faster ones. diff --git a/engine/strata/docs/ORCA.md b/engine/strata/docs/ORCA.md new file mode 100644 index 00000000..5d0cfb67 --- /dev/null +++ b/engine/strata/docs/ORCA.md @@ -0,0 +1,95 @@ +# OrcaRouter IQ3_XXS compatibility + +Validated on Linux with an RTX 5090 (32 GB), Ryzen 9 9950X3D and 128 GB RAM on 2026-09-27. + +The target is `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF`, **IQ3_XXS** (two shards, 85.20 GB total). +It has Strata's Qwen4Exp geometry, but ordinary quantization also compresses the hyperconnection, +small attention and PLE projections which Strata's kernels read as BF16. + +`tools/iq_pack.py --compat-bf16` expands only those projections, rounding to BF16 using nearest-even. +This adds rounding relative to the GGUF's dequantized weights; it does not recover the original BF16 +checkpoint or its quality. Expert weights, native attention weights, embeddings and the 28.8 GB PLE +lookup table remain unchanged. The latter stays on disk. The pack records its conversions in +`compat-bf16.json`. + +The native loader retains this pack's converted PLE key. Its existing native Q2_0 key path remains +available to the original model. Hugging Face snapshot symlinks are supported; all split shards must +finish downloading before packing. Pass the snapshot filename, not its hash-named blob target. + +## Preparation + +Build Strata normally using the pinned llama.cpp dependency. Python needs numpy, regex and gguf-py +from that dependency (`STRATA_GGUF_PY` can point to its `gguf-py` directory). + +```sh +.venv/bin/python tools/iq_pack.py \ + --gguf /path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf \ + --out packs/orca-iq3_xxs --compat-bf16 +``` + +Use this model's own tokenizer exported into the pack. Do not share another model's `dense.bin`, +and do not rename the Orca files to impersonate one of setup's GSQ-RCO models. + +Strata's persistent server also requires the MTP runtime, prepared by the existing tools: + +```sh +.venv/bin/python tools/mtp_fetch.py fetch --out mtp +.venv/bin/python tools/mtp_pack.py --src mtp --experts q2_0 --out mtp/mtp-q2_0.gguf +.venv/bin/python tools/mtp_rt.py --gguf mtp/mtp-q2_0.gguf --out mtp/rt +cp data/draft_vocab.bin mtp/rt/draft_vocab.bin +``` + +This uses the original model's draft head, as setup does for Swift. The target model verifies its +proposals; draft acceptance and performance must be measured for this fine-tune. + +## Local server + +Save the following as `strata-orca-iq3_xxs.json` at the repository root, replacing both `/path/to/` +entries with the **same first shard**. Orca's PLE table is in shard 1. Start with a 32K context and +512-token prefill chunks; the expert cache sizes itself to available VRAM. The expert arena alone +needs about 49.8 GiB of available system RAM, plus draft/runtime buffers and other applications. + +```json +{ + "exe": "build/strata", + "args": [ + "--pack", "packs/orca-iq3_xxs", + "--native", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", "/path/to/Qwen3.8-Flash-Next-Uncensored-IQ3_XXS-00001-of-00002.gguf", + "--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto", + "--prefill", "512", "--spec", "4", "--spec-min-p", "0.5", + "--mtp", "mtp/rt", "--max-context", "32768", "--kv", "int8" + ], + "cwd": ".", + "tokenizer": "packs/orca-iq3_xxs/tokenizer", + "model_name": "orcarouter-qwen3.8-flash-next-uncensored-iq3_xxs", + "log": "strata-orca-iq3_xxs.log", + "host": "127.0.0.1", + "port": 8080 +} +``` + +Run from the repository root: + +```sh +.venv/bin/python -m serve.server --engine strata --config strata-orca-iq3_xxs.json --port 8080 +``` + +The web interface is at `http://127.0.0.1:8080`; API clients use `http://127.0.0.1:8080/v1`. +Vision is not configured in this text-only example. Performance of the original GSQ-RCO model +does not establish this fine-tune's speed or accuracy. + +## Scope and validation + +- IQ3_XXS is the target of this change; other Orca quantizations are not validated. +- IQ3_M additionally uses Q5_0 expert down matrices, which the native GPU expert path does not support. +- The installer model menu is unchanged. This is an explicit local packing workflow. +- Focused conversion and split-file tests: `.venv/bin/python -m unittest discover -s tools -p test_iq_pack.py`. +- All eight packing tests, 17 server tests and the GPU gated-residual parity check passed. +- The complete model packed successfully: 460 tensors converted, 1.39 GiB of converted BF16 weights; + 1.43 GiB total packed dense weights. The 48 expert layers remain IQ3_XXS gate/up and IQ4_NL down. +- Real server checks passed: arithmetic, Python code, translation, a longer explanation, multi-turn context + reuse (25 prompt tokens reused), streaming cancellation and a subsequent correct response. The engine + PID stayed unchanged. These are smoke tests, not a quality benchmark or a full-context stress test. +- With the configuration above, a 111-token explanation generated at 77.7 tokens/s (engine decode timing); + total request time was 1.77 seconds. This single short measurement is not a general throughput claim. diff --git a/engine/strata/docs/ORCA_Q4_K_S.md b/engine/strata/docs/ORCA_Q4_K_S.md new file mode 100644 index 00000000..25815ff1 --- /dev/null +++ b/engine/strata/docs/ORCA_Q4_K_S.md @@ -0,0 +1,36 @@ +# OrcaRouter Uncensored Q4_K_S (manual setup) + +This path uses the three original `orcarouter/Qwen3.8-Flash-Next-Uncensored-GGUF` Q4_K_S shards without rewriting their expert, embedding or PLE table bytes. It is separate from the installer model menu. Keep all three shard filenames together. + +The ordinary GGUF quantizes some small projections which Strata reads as BF16. `--compat-bf16` dequantizes and rounds those projections to BF16 in the separate pack; it does not restore their original precision. The Q5_0 PLE table remains in the source GGUF and currently uses the mapped reader (`--ple-io mmap`). The Q4_K gate/up experts and Q5_0/Q5_1 down experts remain in GGUF form, including layers whose three tensors cross shard boundaries (each role is read from its own shard). The GPU expert kernels take Q4_K with Q5_1 (or Q8_0) downs; Q5_0 downs are not among them yet, and the engine refuses to start on a pack with such a layer (it names the layer). + +## Build and prepare + +Build Strata with CUDA, native experts, `STRATA_ORCA_Q4KS_MMQ=ON` (and `STRATA_BUILD_TESTS=ON` for the two parity programs below). This opt-in compiles the Q5_0 GGML MMQ instance for CUDA or HIP (the Q4_K and Q5_1 instances come with the engine's K-quant MMQ build on CUDA); the usual Q8_0 draft-layer instance remains in both builds. HIP also needs `STRATA_PREFILL_MMQ=ON`. Select your card's compute capability, for example `89` on an L40S. On Windows with Ninja and CUDA 12.6, use the Visual Studio developer environment and `-DCMAKE_CUDA_RUNTIME_LIBRARY=Shared` to keep the CUDA runtime linkage consistent. The default pinned ggml checkout is supported by the project build. + +```sh +cmake -S . -B build -G Ninja -DSTRATA_ENABLE_CUDA=ON -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_ORCA_Q4KS_MMQ=ON -DCMAKE_CUDA_ARCHITECTURES=89 -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared -DCMAKE_BUILD_TYPE=Release +cmake --build build --target strata native_expert_parity ple_q5_parity +python tools/iq_pack.py --gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --out packs/orca-q4_k_s --compat-bf16 +``` + +`iq_pack.py` needs NumPy and the `gguf-py` module from the pinned llama.cpp dependency (`STRATA_GGUF_PY` can point to that directory). It writes a roughly 1.43 GiB dense pack and a native-expert manifest. The original 112 GB of model shards are read in place; `experts.bin` is optional and is not written by this command. + +Check the changed kernels against the real files before starting the service: + +```sh +build/native_expert_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00002-of-00003.gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00003-of-00003.gguf 0 5 6 20 47 +build/ple_q5_parity /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf +``` + +## Engine flags + +Pass the same first shard to `--native` and `--ple-gguf`; Strata discovers the other two shards by name. For a first text-only run, use 32K context and a modest cache. Once that passes, increase the context and cache with memory measurements on the target machine. + +```sh +--pack packs/orca-q4_k_s --native /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-gguf /models/Qwen3.8-Flash-Next-Uncensored-Q4_K_S-00001-of-00003.gguf --ple-io mmap --expert-profile data/expert-profile.bin --expert-cache auto --prefill 512 --spec 4 --mtp /path/to/mtp/rt --max-context 32768 --kv int8 +``` + +For two GPUs in persistent server mode, add `--layer-split auto --split-device 1` (with CUDA0 and CUDA1 visible). The usual Strata MTP runtime is built from the original model's draft layer; draft acceptance on the Uncensored fine-tune must be measured. Keep this model's own tokenizer from the pack. Do not combine `--expert-cache-per-layer` with a variable-size native cache: that policy's slot ordering is independent of the pack's per-layer blob sizes. + +This port does not claim that Q4_K_S beats llama.cpp on a given computer. Compare the same model bytes, prompt, context, output length and GPU load; report prefill and decode separately. diff --git a/engine/strata/docs/SECOND_GPU.md b/engine/strata/docs/SECOND_GPU.md new file mode 100644 index 00000000..0ce94e7a --- /dev/null +++ b/engine/strata/docs/SECOND_GPU.md @@ -0,0 +1,85 @@ +# CUDA1–3 expert experiment + +CUDA0 keeps the dense layers, KV/state, MTP and its existing expert cache. Up to +three independent expert caches fill CUDA1, CUDA2 and CUDA3 in that order. Each +expert has one owner: CUDA0, one secondary GPU, or the CPU pool. Each secondary +GPU computes its rows while the CPU pool works; the results return through +private pinned host buffers before CUDA0 continues the layer. The GPU launches +can overlap, but each layer waits for all three. + +The shipped profile ranks 8,000 `(layer, expert)` pairs. CUDA0 takes its usual +`--expert-cache auto` allocation. With only CUDA1, it takes the first remaining +pairs. When CUDA2 or CUDA3 is enabled, the remaining profiled pairs are assigned +round robin to the secondary GPUs. The ranked list is then extended with all +other pairs in expert-then-layer order and distributed in the same way. This +fills the additional VRAM and lets all secondary GPUs see frequent experts, but +unranked experts may hardly ever be routed. The startup +log reports slots and GiB per card; each request reports the number of expert +entries actually computed on each secondary GPU. Remote outputs are packed +before returning over PCIe/USB4: the request log compares MiB transferred +with the previous full-row transfer. The input and routing metadata use pinned +host staging. This reduces transfer traffic and launch overhead, but does not +release the expert arena in system RAM or significantly change VRAM use. + +The optional `--gpu-placement layer` gives each layer to exactly one secondary +GPU (layer number modulo the number of enabled cards). It fills that card with +the most frequently routed experts of its layers first, then the unranked ones. +This can reduce USB4 device switches and synchronization when several secondary +cards serve the same layer in the default `stripe` mode. All three cards still +keep their requested expert slots; the primary CUDA0 cache and CPU fallback +continue to work. The log counts active layer launches on each card, so the +tradeoff can be measured alongside tokens per second. This placement is +experimental and may be slower if a given layer needs more than one card's +compute capacity. + +The experiment requires the corresponding visible CUDA devices and a CUDA +enabled build. Each card must keep at least 512 MiB free. Tiers must be enabled +in order. Under WDDM (Windows, WSL2), CUDA registration of the host expert arena is capped at +8 GiB to leave room for the contexts and MTP on CUDA0 (`STRATA_ARENA_PIN_GIB` overrides it; on Linux the whole +arena is registered). The rest remains +available to the CPU pool; the PCIe expert path is available only for the +registered layers. Without secondary GPUs, the original uncapped registration +behavior applies. + +On an existing Linux installation, apply the patch to its source tree, then run: + +```sh +./setup.sh --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000 +``` + +On Windows, from PowerShell in the installation folder: + +```powershell +.\START-HERE.bat --setup --gpu1-experts 5000 --gpu2-experts 5000 --gpu3-experts 5000 +``` + +To test the layer placement instead, add `--gpu-placement layer` to the setup +command. To go back, run the same command with `--gpu-placement stripe`. After +the new engine is built, the mode can also be changed without a rebuild: edit +`--expert-cache-remote-placement` in `strata-iq3_xxs.json` from `layer` to +`stripe` or vice versa and restart the server. If the argument is absent, the +default is `stripe`. + +Choose the same model, size, context and image settings as your current +installation when prompted. Setup recompiles the engine, updates its server +configuration, and starts it. Later starts keep those settings. To tune the +slots without recompiling, edit the values after `--expert-cache-device1`, +`--expert-cache-device2` and `--expert-cache-device3` in the stored +`strata-iq3_xxs.json`, then restart with `.\run-iq3_xxs.bat`. + +Compare identical requests at one, two and four GPUs, preferably with several +repeats. VRAM use alone does not show useful offload: compare the per-request +CUDA1–3 counts and tokens per second. More GPU contexts and synchronization +may lower the speed. Prompt prefill still uses CUDA0; secondary GPUs serve +decode, including MTP verification. No peer-to-peer access is required. + +Longer contexts reserve more KV/state memory on CUDA0, which reduces its +automatic expert cache. On a 64 GB PC `setup.py` limits IQ3_XXS to 128K even +if 262K was selected; the secondary caches still require the host expert arena. +To try 262K on 64 GB, choose Q2_0 or IQ2_XS instead and check that CUDA0 still +has enough free VRAM after loading. Benchmark long prompts separately from +short decode requests. + +The existing warning about the CUDA0 expert-cache GPU hit path still applies: +its outputs diverge from cache-off runs. Treat performance as experimental +until the generated tokens have been validated. diff --git a/engine/strata/docs/TROUBLESHOOTING.md b/engine/strata/docs/TROUBLESHOOTING.md new file mode 100644 index 00000000..2d040b09 --- /dev/null +++ b/engine/strata/docs/TROUBLESHOOTING.md @@ -0,0 +1,70 @@ +# Something went wrong? + +The common problems and what to do. Back to the [README](../README.md#something-went-wrong). The full table of +error messages, with the older engine fixes, is in the [details](DETAILS.md#troubleshooting). + +## While installing or starting + +**My PC froze, or got very slow, the first time Strata started.** +That's normal while it starts, most of all the first time. Strata loads 35-55 GB into your RAM, locks part of it for +the graphics card, and works out how much of the model fits on your GPU. The mouse can freeze for a few minutes. +**Wait, and don't close the window.** The next starts are much faster. Still frozen after 10 minutes? Restart the +PC, close other programs (browsers use a lot of RAM) and try again. If it keeps happening, pick a smaller size (Q2_0 +or IQ2_XS). + +**It stopped while downloading or installing.** +Run `START-HERE.bat` (Linux: `./setup.sh`) again. It continues where it stopped. + +**It says the NVIDIA driver is too old.** +Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), restart the PC, and run +`START-HERE.bat` again. + +**It says port 8080 is already in use.** +Strata is already running. Look for its window. Or another program uses the port: `START-HERE.bat --port 8081`. + +**Python or the build tools could not be installed.** +Install what it names (links are printed), then run it again. Everything already done is kept. + +**The first start takes minutes.** +It is reading 34-55 GB into RAM; the second start is faster while the files are in the OS cache. Started from Task +Scheduler, it can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). + +## While it answers + +**It's very slow and the disk light keeps blinking.** +Your PC is out of free RAM. Close other programs, or pick a smaller size (Q2_0 or IQ2_XS). + +**An answer stopped with "the engine stopped unexpectedly".** +Usually not enough RAM (on Linux the system then stops the engine). Just send your message again: Strata starts the +engine by itself. If it keeps happening, close other programs or pick a smaller size. + +**It says the prompt exceeds the context.** +The conversation is longer than the context you chose. Start a new chat, or run `SETUP.bat` and pick more +context. + +**It is slower than the tables.** +The monitor plugged into the graphics card and other GPU programs take VRAM from the expert cache; RAM running below +its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. + +**Pictures are refused, or slow.** +"this server was started without the vision encoder": the model was set up for text only - run setup again with +`--vision gpu` (or `--vision cpu`). Pictures that take 10-30 s are read by the encoder on the CPU; `--vision gpu` +(NVIDIA, ~1.4 GB of VRAM) makes it 0.1-0.5 s. + +## AMD cards + +**"No AMD GPU found (the amdgpu driver's KFD topology is empty)" on Linux.** +The kernel's amdgpu driver is not loaded for the card. Integrated Radeon GPUs are listed as not supported; setup +lists every card it found and whether Strata can use it. + +**The engine stops at start with the card's name, its architecture and the build's list.** +The engine was compiled for another card (for example after moving the Strata folder to another PC). Run +`./setup.sh --setup --backend hip`: it compiles the engine for this card's architecture. + +**Large pinned host allocations fail on ROCm although RAM is free.** +See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. + +## Still stuck? + +Look in the [full troubleshooting table](DETAILS.md#troubleshooting), or open an +[issue](https://github.com/Niko1221/Strata/issues) and attach `strata-.log` from the Strata folder. diff --git a/engine/strata/docs/UNSLOTH_Q4.md b/engine/strata/docs/UNSLOTH_Q4.md new file mode 100644 index 00000000..cf8d2ac3 --- /dev/null +++ b/engine/strata/docs/UNSLOTH_Q4.md @@ -0,0 +1,235 @@ +# Unsloth UD-Q4_K_XL (experimental) + +**Experimental.** Setup offers it from engine 0.1.32 ([below](#setup)); the manual workflow after that section works +with engine 0.1.31 or newer. Validated on one PC: Windows 10, an RTX 5070 (12 GB), 64 GB of RAM and an AVX-512 CPU, +on 2026-10-01. + +The target is Unsloth's 4-bit quantization of the same model the other packs use: +[unsloth/Qwen3.8-Flash-Next-GGUF, `UD-Q4_K_XL`, revision `38bb39e`](https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/tree/38bb39ee97821de2c9009abb7e93950eec396e66/UD-Q4_K_XL). +"UD-Q4_K_XL" is a mix of formats, not Q4_K everywhere: the routed experts are Q4_K (Q5_K in layer 2) for gate/up and +Q5_1 (Q8_0 in layers 2, 4, 30, 46, 47) for down; the token embedding, the output head, the attention and shared-expert +projections and the PLE key are Q8_0; the 28.8 GB PLE table is IQ4_NL. The routed experts are 71.7 GiB, about twice +the 3-bit models'. + +## Setup + +`START-HERE.bat --setup` (Linux: `./setup.sh --setup`) and choose **Qwen3.8-Flash-Next (Unsloth)**, marked +`[experimental]`; or directly: + +```sh +START-HERE.bat --setup --family unsloth --model UD-Q4_K_XL +``` + +What setup does differently for this model: + +- It needs 48 GB of RAM or more (with less it asks, default no; `--model UD-Q4_K_XL --yes` installs it anyway) and + engine 0.1.32 or newer (checked before anything is downloaded), and an NVIDIA + GPU: it has not been run on AMD cards (its prompt kernels for the Q4_K / Q5_K experts are NVIDIA-only), so with + `--backend hip` setup says so and asks before the download (#429; `--model UD-Q4_K_XL --yes` tries it). One GPU only: with `--gpus` it uses the first one and says so. No images (the vision encoder is not wired to + this file yet) and no experimental speed projection (not tested with it). +- It downloads the four shards below from the pinned revision `38bb39e` (resumable, like the other models), then + checks each one's size and SHA-256 against the table below; the check takes a few minutes once and is remembered + in the file's finish mark. A file with the wrong hash is deleted, so the next run downloads it again. +- It packs with `--compat-bf16` and never writes `experts.bin` (`--low-ram` does not apply). +- The RAM budget is the PC's RAM less 24 GB: `--resident-budget-gib 40` on 64 GB, at most all 71 GiB of experts on + 96 GB or more. From a 64K context up, where the KV cache moves to RAM, its size comes out of the budget. Setup's + `--resident-budget-gib N` sets another one (a bigger one is kept, with a note on what it risks). +- It recommends an 8K context on a GPU under 14 GB (every GB of KV cache is a GB less of cached experts). + +## The files + +Four shards, 111,334,654,784 bytes (111.3 GB) together. Shard 1 holds only the metadata; layer 11's down projection is +in shard 2 and its gate/up in shard 3, which this engine handles (`native_experts.txt` v4). + +| File | Bytes | SHA-256 | +| --- | --- | --- | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf` | 10,946,624 | `4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf` | 49,859,583,136 | `3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf` | 49,376,141,504 | `56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3` | +| `Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf` | 12,087,983,520 | `753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a` | + +Keep the four files together in one folder under these names (the engine finds shards 2-4 from shard 1's name; a +missing shard is an error that names it). Setup checks them itself; by hand, check them before packing +(`sha256sum -c`, or `Get-FileHash` on Windows). +Hugging Face snapshot symlinks work if you pass the snapshot's file name, not the hash-named blob it points to. + +## What it needs + +| | | +| --- | --- | +| Disk | 111.3 GB for the four files, 1.4 GB for the pack, ~6 GB for the MTP draft layer if you have none yet. **No `experts.bin`**: the engine reads the experts from the GGUF files in place. An NVMe SSD matters: the experts that fit neither VRAM nor the RAM budget are read from it for every token. | +| RAM | 64 GB measured. The RAM budget (below) holds the most-used experts; the rest come from the SSD through the OS file cache. | +| GPU | 12 GB measured (RTX 5070): after the weights, the draft layer and the buffers, the expert cache held 1,280 of the 24,576 experts (3.7 GiB) at 4K context. | + +## The pack (by hand) + +Build Strata (or install 0.1.31+), then, from the repository root, with gguf-py from the pinned llama.cpp +(setup installs it; `STRATA_GGUF_PY` can point to its `gguf-py` folder): + +```sh +.venv/bin/python tools/iq_pack.py \ + --gguf /path/to/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf \ + --out packs/ud-q4_k_xl --compat-bf16 +``` + +About 30 seconds. It writes `index.txt`, `dense.bin` (1.4 GB), `native_experts.txt`, the tokenizer, `conversions.json` +and `compat-bf16.json`. **`--compat-bf16` is required**: this file stores 195 small projections (the hyper-connection +up/down matrices, `output_hc_*` and the PLE value) as Q8_0, while the engine reads them as BF16. Without the flag the +packer refuses and writes nothing; with it, they are dequantized and rounded to BF16 (nearest-even). Do not add +`--experts-bin`: it would write a 77 GB copy of the experts that this mode does not need. + +## The numbers: what is native and what is converted + +The routed experts, the token embedding, the output head, the attention and shared-expert projections, the PLE key and +the PLE table are used as the GGUF stores them (the engine has GPU kernels and CPU (ggml) paths for Q4_K, Q5_K, Q5_1 and +Q8_0). The small tensors the engine reads as floats are converted, and `conversions.json` lists every one with its +source/destination type, method, whether it is exact, the largest absolute error and the source bytes' SHA-256: +264 F32 tensors (routers, injections, SSM gates) whose values are already BF16's are stored as BF16 exactly; the 195 +Q8_0 projections above are rounded to BF16 (largest absolute error 0.0144, in `hc_ffn_up`); the PLE convolution (F32) +is narrowed to F16 when the engine loads it (largest error 3e-8). That is the compatibility Unsloth's file needs; it is +not the original BF16 checkpoint. The output matches llama.cpp's on the same file: +[Quality](#quality-against-llamacpp-on-the-same-file). + +## The MTP draft layer + +The draft layer is the base model's, the same one the other packs use. If setup installed Strata, you have it +(`mtp/rt` in `Strata-data`). Otherwise build it as [docs/ORCA.md](ORCA.md#preparation) shows (`tools/mtp_fetch.py`, +`tools/mtp_pack.py`, `tools/mtp_rt.py`, then copy `data/draft_vocab.bin` to `mtp/rt/`). + +## The server + +Save as `strata-ud-q4_k_xl.json` at the repository root (or next to setup's other `strata-*.json`), with `/path/to/` +pointing at **shard 1**. `--ple-gguf` is not needed: the engine finds the shard that holds the PLE table +(`per_layer_token_embd.weight`, shard 2) by name. `--resident-budget-gib` turns on the mapped mode with a RAM budget +(it implies `--mmap-experts`). + +```json +{ + "exe": "engine/strata.exe", + "args": [ + "--pack", "packs/ud-q4_k_xl", + "--native", "/path/to/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "--resident-budget-gib", "40", + "--expert-profile", "data/expert-profile.bin", "--expert-cache", "auto", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", + "--mtp", "mtp/rt", "--max-context", "8192" + ], + "cwd": ".", + "tokenizer": "packs/ud-q4_k_xl/tokenizer", + "model_name": "qwen3.8-flash-next-ud-q4_k_xl", + "log": "strata-ud-q4_k_xl.log", + "host": "127.0.0.1", + "port": 8080 +} +``` + +```sh +.venv/bin/python -m serve.server --engine strata --config strata-ud-q4_k_xl.json --port 8080 +``` + +(`engine/strata.exe` is setup's engine on Windows; a self-built one is `build/strata`.) The expert profile is the base +model's (`data/expert-profile.bin`); it ranks the same 48 x 512 experts and decides which ones the GPU cache and the RAM +budget take first. + +**Choosing the RAM budget N:** your RAM minus 20-24 GB (the OS, the engine itself, the 126 MB router copy, and room for +the OS file cache that serves the rest). On 64 GB, 40. The engine clamps a budget larger than the RAM it finds free +(minus 4 GB and a 256 MiB margin) and says so; before #403's fix such a clamped budget could then fail the start. Everything above N comes from the SSD for every token, so N is the setting that matters +most; a bigger budget was faster in every measurement (24 / 32 / 40 GiB). When the driver page-locks the whole budget +(24 GiB did on this PC, 32 and 40 did not), the GPU also computes a share of the misses over PCIe, as in the resident +low-RAM mode; `STRATA_RESIDENT_PIN=0` keeps the budget locked only (the CPU then computes every miss). + +**Context:** measured at 4K. The KV cache takes VRAM from the expert cache, so a longer context makes decoding slower; +8K is a reasonable start on 12 GB. `--kv int8` halves the KV cache's VRAM. + +## What to expect (RTX 5070 12 GB, 64 GB RAM, Windows, one short greedy prompt) + +| RAM budget | Greedy output | Notes | +| --- | --- | --- | +| 24 GiB | 5.1-5.2 tok/s (2 runs, before the routing prefetch below) | 2.2 GB read from the SSD per verify round (~3.5 tokens) | +| 40 GiB | **7-8.5 tok/s** (6 runs: 6.7-8.6, mean 7.9) | 1.1 GB read from the SSD per verify round, ~0.33 GB per token | + +- The first answer comes about 60 s after the engine starts (mostly loading: the RAM budget is copied from the GGUF + files at start). A 30-token prompt then took 5-6 s. +- Long prompts (engine 0.1.32): a 16K prompt is read at **160 tokens/s** (15,873 tokens in 99 s; 0.1.31: 57 tokens/s, + 273-282 s). Reading a prompt streams every expert once per 4K chunk, and the third of them outside the RAM budget + come from the SSD (~35 GB per chunk), so the prompt path now reads them with 32 threads and up to 128 blobs in + flight when the experts are read from the GGUF in place (`STRATA_STAGER_THREADS` / `STRATA_STAGER_RING` override + it; 4 and 16 before, still the default for every other model). Between the chunks, the 28.8 GB PLE table's rows + take ~5 s per chunk. +- An engine compiled with `-DSTRATA_MMQ_KQUANTS=ON` multiplies the Q4_K / Q5_K / Q5_1 experts of a prompt with + llama.cpp's MMQ kernels (as the other models' formats always are) instead of dequantizing them to FP16: 4x less GPU + time for those products, but on this PC the prompt waits for the SSD either way (29 s per 4K chunk with or + without). Off in the released engine: it loads every kernel at start, and these took 1-3 expert slots of VRAM from + every model. +- The speed varies from run to run (6.7-8.6 tok/s at 40 GiB for the same prompt), with what the OS file cache holds. +- For comparison, IQ3_S (all its experts in RAM) writes ~53 tok/s on the same PC ([the speed tables](DETAILS.md#speed-measured)). +- Where the time goes (`--stats` on the command line): at 40 GiB about 550-750 ms of each verify round (3.5 tokens) is + reading experts from the SSD, ~75 ms the CPU's expert kernels, ~13 ms the GPU. + +## Quality: against llama.cpp on the same file + +Strata and llama.cpp (the pinned commit `3cf0325`, a CPU build reading the GGUF memory-mapped) were given the same +token sequences, and at every position each wrote its 20 most likely next tokens with their log-probabilities: Strata +through its verify windows (`STRATA_LOGPOS` with `STRATA_LOGPOS_TOPK=20`), llama.cpp from `llama_get_logits_ith` over +one batch. Strata ran with the recommended settings (RAM budget 40 GiB, the MTP draft layer on, greedy, +`--adapt-every 100000` so the expert cache does not move during the run). Per position: whether the most likely token is the same (argmax +agreement), how many of the 5 / 10 most likely tokens both have, the KL divergence (llama.cpp's distribution against +Strata's, over llama.cpp's top 20 plus one bucket for the rest), and the perplexity of the sequence under each. + +| Token set | Positions | Argmax agreement | Top-5 / top-10 overlap | KL | Perplexity Strata / llama.cpp | +| --- | ---: | ---: | ---: | ---: | ---: | +| Code: Strata's greedy answer to a coding prompt (an LRU cache in Python, 56-token prompt) | 400 | **99.0%** | 95.6% / 95.3% | 0.0008 | 1.067 / 1.070 | +| Thinking: Strata's greedy answer to a reasoning puzzle (with thinking, 55-token prompt) | 324 | **97.5%** | 96.2% / 96.4% | 0.0016 | 1.107 / 1.106 | +| After a 16K prompt: Strata's greedy continuation (256 tokens) of the 16,384 real-text tokens below | 256 | 90.2% | 88.1% / 89.3% | 0.039 | 1.619 / 1.623 | +| Real text after a 16K prompt: the last 510 tokens of 16,384 tokens of this repository's docs and code | 510 | 91.2% | 88.3% / 89.9% | 0.035 | 4.27 / 4.29 | +| The same 511 positions with only 512 tokens before them | 511 | 89.2% | 86.0% / 86.3% | 0.061 | 8.99 / 8.87 | + +For comparison, [eddoursul/Strata](https://github.com/eddoursul/Strata) reported 98.2-99.3% (code), 95.6-95.8% +(thinking) and 97.7% (after a 16K prompt) for the same file against llama.cpp on an RTX 3090. + +**Where they differ:** at near-ties. Grouped by llama.cpp's own gap between its two most likely tokens, Strata picks +the same token at every position of the code and thinking answers where that gap is 0.2 or more (695 of 695) and at +every position after the 16K prompt where it is 0.5 or more (144 of 144 in the continuation, 254 of 254 in the real +text; 50 of 54 and 117 of 121 between 0.2 and 0.5). Text after a long document has many more near-ties than a short +answer (58 of the continuation's 256 positions and 135 of the real text's 510 have a gap under 0.2, against 13 of the +code answer's 400), which is why its agreement is lower. It is not the long context itself: the same real-text +positions after only 512 tokens agree a little less (89.2%), and the perplexities match within 3% in every set. For +scale, Strata's own greedy run and its teacher-forced rerun of the continuation pick different tokens at 6% of the +positions (93.8% the same: other window sizes, other experts in VRAM), the same kind of near-tie flips. The 16K +prompts were read by Strata's batched prompt path (15,872 tokens), the rest through the verify windows. These numbers +are the FP16 prompt path's (the released engine's); with the MMQ prompt path (`-DSTRATA_MMQ_KQUANTS=ON`, above) the +continuation after the 16K prompt agrees at 92.2% (KL 0.029, three runs, identical). + +To repeat it: Strata's side is `STRATA_LOGPOS=` with `STRATA_LOGPOS_TOPK=20` (engine 0.1.32) on a serve +engine with `--short-read` covering the positions to compare; llama.cpp's side was a short program over +`llama_decode` / `llama_get_logits_ith` writing the same top 20 per position. + +## Opt-ins and switches (environment variables) + +| | | +| --- | --- | +| `STRATA_LOOKAHEAD=0` | Turns off the routing-aware prefetch (on by default in this mode): while the CPU works on a layer, a thread applies the next layer's router to this layer's input and asks the OS to read the predicted experts' pages. Pages only, the answers are the same. About half of the SSD reads were predicted; mean +14% (6.9 -> 7.9 tok/s). `STRATA_LOOKAHEAD_K` sets the experts per token (default 10). | +| `STRATA_KQ256=1` | Multi-token AVX2 kernels for the Q4_K / Q5_1 / Q8_0 experts. Bit-exact with ggml's, but measured no faster, so off. | +| `STRATA_PARTIAL_PIN=1` | Registers the hottest part of the RAM budget (up to `STRATA_PARTIAL_PIN_GIB`, default 24) with the GPU driver, so the GPU computes a share of the misses over PCIe (`--pcie-frac`). Measured no faster on this PC, and it changes the numerics of those experts (GPU kernels instead of the CPU's), so off. | +| `STRATA_FETCH_THREADS=N` | Threads that read the experts from the GGUF while it answers (default 8; 16 was no faster). The prompt path has its own: `STRATA_STAGER_THREADS` (default 32 here) and `STRATA_STAGER_RING` (128). | + +## Scope and validation + +- Only UD-Q4_K_XL at revision `38bb39e` is targeted. Other Unsloth quantizations use formats this engine may not + have kernels for; the engine checks every layer's formats at start and refuses an unsupported one by name. +- Tests: the packer's synthetic 4-shard and conversion tests (`.venv/bin/python -m unittest discover -s tools -p + test_iq_pack.py`); CTests `gguf_split_test`, `expert_layout_test`, `native_expert_parity_*` (the three real expert + format pairs against ggml-cpu, the Q5_1 min term, Q8_0 rows), `prefill_mmq_kquant_test` (with `-DSTRATA_MMQ_KQUANTS=ON`: the + prompt path's MMQ products for Q4_K / Q5_K / Q5_1 / Q8_0 against ggml's dequantized weights); the in-place mode against `experts.bin` on the Coder + (identical tokens and logits). +- Real runs: greedy answers to a coding prompt (correct) at every budget and setting above, identical across them; + the same tokens as llama.cpp at 97.5-99% of the positions of short greedy answers and 90-91% after a 16K prompt, + differing mostly at near-ties (above). Not yet: sampled decoding, long conversations. Please report what you see. + +## Credits + +The split-artifact loader, the expert formats' GPU kernels and the packing of Unsloth's files follow +[eddoursul/Strata](https://github.com/eddoursul/Strata) (PR #245), which ran these files first. The Q8_0 kernels, the +per-role shard column and the PLE convolution's F32 -> F16 fix come from @gopinath87607's PR #255; per-role shard names +were also proposed by @jagsan-cyber in PR #247. The quantization is [Unsloth](https://huggingface.co/unsloth)'s; the +model is Qwen's ([license](https://huggingface.co/Qwen/Qwen3.8-Flash-Next)). diff --git a/engine/strata/docs/benchmarks/2026-09-29-gfx1100.json b/engine/strata/docs/benchmarks/2026-09-29-gfx1100.json new file mode 100644 index 00000000..bf0e5ef7 --- /dev/null +++ b/engine/strata/docs/benchmarks/2026-09-29-gfx1100.json @@ -0,0 +1,299 @@ +{ + "source_commit": "9568e78da663e6b224ab96d57baf450717b36e73", + "date": "2026-09-29", + "candidate_binary_sha256": "705f5925a788bc227bad72abfb5466032e0879d752fea9afc3eb32051b35182b", + "note": "Fresh same-session control and candidate runs. Throughput cap 128; not a coding-quality benchmark.", + "control": [ + { + "kind": "warmup", + "trial": 0, + "wall_s": 0.45770244899904355, + "metrics": { + "prompt_tokens": 15.0, + "reused": 0.0, + "fresh": 15.0, + "prefill_ms": 335.0, + "prefill_tps": 44.8, + "generated": 2.0, + "decode_ms": 115.0, + "decode_tps": 17.5 + }, + "finish_reason": "stop" + }, + { + "kind": "cold", + "trial": 1, + "wall_s": 20.068275763012934, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 17538.0, + "prefill_tps": 240.0, + "generated": 128.0, + "decode_ms": 2518.0, + "decode_tps": 50.8 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 1, + "wall_s": 4.412000925018219, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 1943.0, + "prefill_tps": 58.7, + "generated": 128.0, + "decode_ms": 2451.0, + "decode_tps": 52.2 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 2, + "wall_s": 20.731399575975956, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 18213.0, + "prefill_tps": 484.8, + "generated": 128.0, + "decode_ms": 2505.0, + "decode_tps": 51.1 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 2, + "wall_s": 5.0592734439997, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 2601.0, + "prefill_tps": 95.4, + "generated": 128.0, + "decode_ms": 2441.0, + "decode_tps": 52.4 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 3, + "wall_s": 11.695648370019626, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 9209.0, + "prefill_tps": 457.2, + "generated": 128.0, + "decode_ms": 2477.0, + "decode_tps": 51.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 3, + "wall_s": 4.093982424004935, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 1896.0, + "prefill_tps": 60.1, + "generated": 128.0, + "decode_ms": 2188.0, + "decode_tps": 58.5 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 4, + "wall_s": 20.84539221401792, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 18437.0, + "prefill_tps": 478.9, + "generated": 128.0, + "decode_ms": 2392.0, + "decode_tps": 53.5 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 4, + "wall_s": 5.357054464984685, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 2658.0, + "prefill_tps": 93.3, + "generated": 128.0, + "decode_ms": 2682.0, + "decode_tps": 47.7 + }, + "finish_reason": "length" + } + ], + "optimized": [ + { + "kind": "warmup", + "trial": 0, + "wall_s": 0.46265592801501043, + "metrics": { + "prompt_tokens": 15.0, + "reused": 0.0, + "fresh": 15.0, + "prefill_ms": 335.0, + "prefill_tps": 44.8, + "generated": 2.0, + "decode_ms": 121.0, + "decode_tps": 16.5 + }, + "finish_reason": "stop" + }, + { + "kind": "cold", + "trial": 1, + "wall_s": 11.728894605010282, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 9408.0, + "prefill_tps": 447.5, + "generated": 128.0, + "decode_ms": 2308.0, + "decode_tps": 55.5 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 1, + "wall_s": 2.9531024169991724, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 740.0, + "prefill_tps": 154.0, + "generated": 128.0, + "decode_ms": 2193.0, + "decode_tps": 58.4 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 2, + "wall_s": 12.42044531099964, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 10107.0, + "prefill_tps": 873.7, + "generated": 128.0, + "decode_ms": 2298.0, + "decode_tps": 55.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 2, + "wall_s": 3.2599652509961743, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8823.0, + "fresh": 248.0, + "prefill_ms": 1070.0, + "prefill_tps": 231.7, + "generated": 128.0, + "decode_ms": 2173.0, + "decode_tps": 58.9 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 3, + "wall_s": 6.937167472002329, + "metrics": { + "prompt_tokens": 4210.0, + "reused": 0.0, + "fresh": 4210.0, + "prefill_ms": 4672.0, + "prefill_tps": 901.1, + "generated": 128.0, + "decode_ms": 2256.0, + "decode_tps": 56.7 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 3, + "wall_s": 3.1877827199932653, + "metrics": { + "prompt_tokens": 4451.0, + "reused": 4337.0, + "fresh": 114.0, + "prefill_ms": 827.0, + "prefill_tps": 137.8, + "generated": 128.0, + "decode_ms": 2350.0, + "decode_tps": 54.5 + }, + "finish_reason": "length" + }, + { + "kind": "cold", + "trial": 4, + "wall_s": 11.314008287008619, + "metrics": { + "prompt_tokens": 8830.0, + "reused": 0.0, + "fresh": 8830.0, + "prefill_ms": 9136.0, + "prefill_tps": 966.5, + "generated": 128.0, + "decode_ms": 2161.0, + "decode_tps": 59.2 + }, + "finish_reason": "length" + }, + { + "kind": "followup", + "trial": 4, + "wall_s": 3.0476601750124246, + "metrics": { + "prompt_tokens": 9071.0, + "reused": 8957.0, + "fresh": 114.0, + "prefill_ms": 734.0, + "prefill_tps": 155.3, + "generated": 128.0, + "decode_ms": 2296.0, + "decode_tps": 55.7 + }, + "finish_reason": "length" + } + ], + "control_binary_sha256": "4522d4937ca4a41ca294d31b60df8c2bc4df5b7a6caf65eaad10c036e08491f7" +} diff --git a/engine/strata/docs/media/guess-and-check.svg b/engine/strata/docs/media/guess-and-check.svg new file mode 100644 index 00000000..f1ff0303 --- /dev/null +++ b/engine/strata/docs/media/guess-and-check.svg @@ -0,0 +1,23 @@ +Speculative decoding: a small helper guesses words, the big model checks them at onceGuess, then check - many words per stepA small, fast helper inside the model guesses the next words. The big model checks all the guesses in one goand keeps the ones it agrees with. The big model decides every word - it just arrives 1.6-1.8x sooner.Helper guessesBig model checksdefreverse(items):defreverse(items):, key):4 words in one step3 guesses kept + its own word \ No newline at end of file diff --git a/engine/strata/docs/media/how-it-works.svg b/engine/strata/docs/media/how-it-works.svg new file mode 100644 index 00000000..cab167b5 --- /dev/null +++ b/engine/strata/docs/media/how-it-works.svg @@ -0,0 +1,23 @@ +How Strata splits the model between your graphics card, RAM and SSDThe model is made of 24,576 small specialists - “experts”.For each word it writes, it asks only 10 of them. Strata keeps the busy oneson your graphics card and the rest in RAM - so it runs on a normal PC.10 at work for one wordGraphics cardSmall but very fast: 12-24 GBRuns the core of the modelfor every word, and keeps the~4,000 experts used mostthe most-used expertsRAM + processorBig: 32-64 GB of memoryHolds all 24,576 experts. When aword needs one the card doesn'thave, the CPU does it - at onceall 24,576 expertsSSDHolds a 29 GB lookup tableThe model looks up a fewsmall rows of it per word -no need to keep it in RAMa few rows per word \ No newline at end of file diff --git a/engine/strata/docs/media/make_figures.py b/engine/strata/docs/media/make_figures.py new file mode 100644 index 00000000..0af0a0e6 --- /dev/null +++ b/engine/strata/docs/media/make_figures.py @@ -0,0 +1,178 @@ +"""docs/media/make_figures.py - the README's "How does it work?" illustrations, in the Strata app's style: its colors +(serve/web/tokens.css), its icons (serve/web/sprite.svg) and its font (Outfit, embedded, SIL OFL 1.1). Light and dark +follow the reader's system setting. + + python docs/media/make_figures.py # writes docs/media/how-it-works.svg and docs/media/guess-and-check.svg +""" +import base64 +import random +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +OUT = ROOT / "docs" / "media" +SPRITE = (ROOT / "serve" / "web" / "sprite.svg").read_text(encoding="utf-8") +FONT = base64.b64encode((ROOT / "serve" / "web" / "fonts" / "outfit-latin-wght.woff2").read_bytes()).decode() + +# the app's tokens (light, then dark) +CSS = """ +@font-face{font-family:"Outfit";src:url(data:font/woff2;base64,%s) format("woff2");font-weight:100 900} +text{font-family:"Outfit",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;fill:#221e1f} +.bg{fill:#f9fafb}.card{fill:#ffffff;stroke:#dee5ee;stroke-width:1}.soft{fill:#f7f7f7} +.muted{fill:#6f6f6f}.ink{fill:#221e1f}.icon{color:#2F384C} +.acc{fill:#10b981}.acc-t{fill:#0c8a60}.acc-tint{fill:#ecfdf5}.acc-line{stroke:#10b981} +.info{fill:#0f97ff}.info-t{fill:#0668c2}.info-tint{fill:#e8f4ff} +.warn{fill:#e39b0b}.warn-t{fill:#8a5a00}.warn-tint{fill:#fff6e0} +.dan{fill:#e0283f}.dan-tint{fill:#fdecee}.dan-t{fill:#b01a2e} +.dot{fill:#dee5ee}.line{stroke:#dee5ee}.arrow{stroke:#6f6f6f;fill:none}.arrowhead{fill:#6f6f6f} +.dash{stroke:#6f6f6f;fill:none;stroke-dasharray:4 4} +.on-acc{fill:#ffffff}.icon-acc{color:#0c8a60}.icon-dan{color:#b01a2e} +@media (prefers-color-scheme:dark){ +text,.ink{fill:#eef1f3}.bg{fill:#0e1113}.card{fill:#161a1d;stroke:#2a3036}.soft{fill:#1d2226} +.muted{fill:#8e979f}.icon{color:#c7cdd3} +.acc{fill:#34d399}.acc-t{fill:#4ade80}.acc-tint{fill:rgba(52,211,153,.12)}.acc-line{stroke:#34d399} +.info{fill:#3aa9ff}.info-t{fill:#7cc4ff}.info-tint{fill:rgba(58,169,255,.12)} +.warn{fill:#f5b53d}.warn-t{fill:#f8c96a}.warn-tint{fill:rgba(245,181,61,.12)} +.dan{fill:#ff5a6e}.dan-tint{fill:rgba(255,90,110,.12)}.dan-t{fill:#ff8a98} +.dot{fill:#2a3036}.line{stroke:#2a3036}.arrow{stroke:#8e979f}.arrowhead{fill:#8e979f}.dash{stroke:#8e979f} +.on-acc{fill:#052e20}.icon-acc{color:#4ade80}.icon-dan{color:#ff8a98} +} +""" % FONT + + +def icon(name, x, y, size=28, cls="icon"): + """A sprite icon at (x, y), `size` px, drawn in the class's color (the icons use currentColor).""" + m = re.search(r']*>(.*?)' % name, SPRITE, re.S) + return (f'{m.group(1)}') + + +def text(x, y, s, size=14, weight=400, cls="ink", anchor="start"): + return (f'{s}') + + +def rect(x, y, w, h, r=14, cls="card"): + return f'' + + +def svg(w, h, body, title): + return (f'{title}' + f'{rect(0, 0, w, h, 20, "bg")}{body}') + + +def dots(x, y, cols, rows, step, lit, lit_cls="acc", r=2.6, seed=1): + """A grid of expert dots; `lit` of them (spread at random) in the accent color.""" + rnd = random.Random(seed) + n = cols * rows + on = set(rnd.sample(range(n), min(lit, n))) + out = [] + for i in range(n): + cx, cy = x + (i % cols) * step, y + (i // cols) * step + out.append(f'') + return "".join(out) + + +def arrow(x1, y1, x2, y2, cls="arrow"): + return (f'' + f'') + + +def how_it_works(): + W, H = 960, 470 + b = [] + # the headline strip: one word, 10 experts + b.append(rect(24, 24, W - 48, 92)) + b.append(icon("i-chat", 48, 50, 36)) + b.append(text(100, 62, "The model is made of 24,576 small specialists - “experts”.", 19, 600)) + b.append(text(100, 88, "For each word it writes, it asks only 10 of them. Strata keeps the busy ones", + 15, 400, "muted")) + b.append(text(100, 106, "on your graphics card and the rest in RAM - so it runs on a normal PC.", 15, 400, "muted")) + b.append(dots(W - 262, 46, 28, 4, 7.6, 10, seed=3)) + b.append(text(W - 262, 94, "10 at work for one word", 12, 500, "acc-t")) + # three cards + cw, ch, cy = 288, 316, 136 + xs = [24, 24 + cw + 24, 24 + 2 * (cw + 24)] + cards = [ + ("i-gpu", "Graphics card", "Small but very fast: 12-24 GB", "acc", + ["Runs the core of the model", "for every word, and keeps the", "~4,000 experts used most"], + "the most-used experts", 5, 26, 26 * 5, "acc"), + ("i-memory", "RAM + processor", "Big: 32-64 GB of memory", "info", + ["Holds all 24,576 experts. When a", "word needs one the card doesn't", "have, the CPU does it - at once"], + "all 24,576 experts", 10, 26, 18, "info"), + ("i-disk", "SSD", "Holds a 29 GB lookup table", "warn", + ["The model looks up a few", "small rows of it per word -", "no need to keep it in RAM"], + "", 0, 0, 0, "warn"), + ] + for (ic, title, sub, tone, lines, dlabel, rows, cols, lit, lit_cls), x in zip(cards, xs): + b.append(rect(x, cy, cw, ch)) + b.append(rect(x + 20, cy + 20, 48, 48, 12, tone + "-tint")) + b.append(icon(ic, x + 30, cy + 30, 28, "icon")) + b.append(text(x + 82, cy + 42, title, 19, 700)) + b.append(text(x + 82, cy + 62, sub, 13, 500, tone + "-t")) + for i, ln in enumerate(lines): + b.append(text(x + 20, cy + 104 + i * 21, ln, 15, 400, "ink")) + if rows: + b.append(dots(x + 26, cy + 196, cols, rows, 9.4, lit, lit_cls, seed=len(title))) + b.append(text(x + 20, cy + 196 + rows * 9.4 + 14, dlabel, 12, 500, "muted")) + else: # the SSD: a table of rows, a few being read + for r in range(6): + yy = cy + 190 + r * 17 + b.append(rect(x + 20, yy, cw - 40, 11, 4, "warn" if r in (1, 4) else "soft")) + b.append(text(x + 20, cy + 306, "a few rows per word", 12, 500, "muted")) + return svg(W, H, "".join(b), "How Strata splits the model between your graphics card, RAM and SSD") + + +def guess_and_check(): + W, H = 960, 330 + b = [rect(24, 24, W - 48, H - 48)] + b.append(icon("i-thinking", 48, 48, 30)) + b.append(text(92, 70, "Guess, then check - many words per step", 19, 700)) + b.append(text(92, 94, "A small, fast helper inside the model guesses the next words. The big model checks all the " + "guesses in one go", 15, 400, "muted")) + b.append(text(92, 113, "and keeps the ones it agrees with. The big model decides every word - it just arrives 1.6-1.8x sooner.", + 15, 400, "muted")) + words = ["def", "reverse", "(items", "):"] + fixed = ", key):" # the model's own word where the guess was wrong + ok = [True, True, True, False] + # row 1: the helper's guesses (dashed chips) + y1, y2 = 156, 238 + b.append(text(48, y1 + 24, "Helper guesses", 14, 600, "muted")) + b.append(text(48, y2 + 24, "Big model checks", 14, 600, "muted")) + x = 176 + xs = [] + for i, w in enumerate(words[:4]): + wd = 34 + len(w) * 9 + xs.append((x, wd)) + b.append(f'') + b.append(text(x + wd / 2, y1 + 25, w, 16, 500, "ink", "middle")) + x += wd + 14 + # row 2: the verdicts + for i, ((x, wd), good) in enumerate(zip(xs, ok)): + tone = "acc" if good else "dan" + b.append(rect(x, y2, wd, 38, 10, tone + "-tint")) + b.append(text(x + wd / 2 - 8, y2 + 25, words[i], 16, 600, tone + "-t", "middle")) + b.append(icon("i-check" if good else "i-error", x + wd - 22, y2 + 11, 16, "icon-" + tone)) + if not good: # the model's own word beside the rejected guess + fx = x + wd + 10 + fw = 26 + len(fixed) * 9 + b.append(rect(fx, y2, fw, 38, 10, "acc-tint")) + b.append(text(fx + fw / 2, y2 + 25, fixed, 16, 600, "acc-t", "middle")) + xs[i] = (fx, fw) + b.append(f'') + # the result + rx = xs[-1][0] + xs[-1][1] + 40 + b.append(arrow(rx, y2 + 19, rx + 30, y2 + 19)) + b.append(rect(rx + 42, y2 - 6, W - 48 - (rx + 42), 50, 12, "acc")) + b.append(icon("i-bolt", rx + 54, y2 + 6, 26, "on-acc-icon")) + b.append(text(rx + 90, y2 + 16, "4 words in one step", 15, 700, "on-acc")) + b.append(text(rx + 90, y2 + 34, "3 guesses kept + its own word", 12, 500, "on-acc")) + return svg(W, H, "".join(b).replace('class="on-acc-icon"', 'class="icon" style="color:#ffffff"'), + "Speculative decoding: a small helper guesses words, the big model checks them at once") + + +if __name__ == "__main__": + (OUT / "how-it-works.svg").write_text(how_it_works(), encoding="utf-8") + (OUT / "guess-and-check.svg").write_text(guess_and_check(), encoding="utf-8") + for f in ("how-it-works.svg", "guess-and-check.svg"): + print(f, (OUT / f).stat().st_size, "bytes") diff --git a/engine/strata/docs/media/pagoda-preview.webp b/engine/strata/docs/media/pagoda-preview.webp new file mode 100644 index 00000000..630ce1d7 Binary files /dev/null and b/engine/strata/docs/media/pagoda-preview.webp differ diff --git a/engine/strata/docs/media/runpagoda.png b/engine/strata/docs/media/runpagoda.png new file mode 100644 index 00000000..45aa6ebe Binary files /dev/null and b/engine/strata/docs/media/runpagoda.png differ diff --git a/engine/strata/docs/paper/Strata-Paper.pdf b/engine/strata/docs/paper/Strata-Paper.pdf new file mode 100644 index 00000000..fcfd2eb5 Binary files /dev/null and b/engine/strata/docs/paper/Strata-Paper.pdf differ diff --git a/engine/strata/docs/paper/tiers.svg b/engine/strata/docs/paper/tiers.svg new file mode 100644 index 00000000..867ba8ee --- /dev/null +++ b/engine/strata/docs/paper/tiers.svg @@ -0,0 +1,18 @@ + + +GPU VRAM 12 GB · 672 GB/s +dense weights ~3.3 GBmixers · GR · routers · head +expert cache: everything left (~6 GB)~4,500 of 24,576 experts, adaptive +MTP layer0.8 GB +KV + state0.3-3 GB +PCIe 4.0 x16 · ~26 GB/s · experts by DMA (prompt, 20% of misses, cache swaps) + +System RAM 64 GB DDR5 · ~41-52 GB/s · 6 CPU cores (AVX-512) +pinned expert arena: all 24,576 experts34 GB (Q2_0) · 35.5 GB (IQ2_XS) · 43 GB (IQ3_XXS); the CPU computes misses in place +OS page cache: hot n-gram rows+ OS, embedding table, buffers +NVMe · 16 row reads per token, issued a step ahead + +SSD +GGUF shard 1 (37.6-47 GB): read once at start +GGUF shard 2: n-gram table 28.8 GB, memory-mapped + \ No newline at end of file diff --git a/engine/strata/include/strata/artifact/dequant.hpp b/engine/strata/include/strata/artifact/dequant.hpp new file mode 100644 index 00000000..d5a314ce --- /dev/null +++ b/engine/strata/include/strata/artifact/dequant.hpp @@ -0,0 +1,292 @@ +#pragma once +// src/artifact/dequant.cpp - P1.S3: scalar reference dequantizers, transcribed from ggml. +// +// P1.S3 asks for every encoding present in the Q2_0 file. This starts with the ones on the critical +// path (the routed experts are all Q2_0) plus the trivial element types, and is structured so the +// rest drop in. Source of truth per encoding is quoted in each function. +// +// Q2_0 is the one that matters, and its contract is settled from source in docs/q2_0-contract.md: +// block = { fp16 d; uint8 qs[16] } = 64 elements, 18 bytes +// code {0,1,2,3} -> symbol {-1,0,+1,+2}; v = (code - 1) * d +// 4 codes per byte, LSB-first: byte j/4, bits (j%4)*2 +// QK2_0 = 64 is PROVEN from the artifact's own offset brackets, not assumed (the llama.cpp PR that +// introduced the type used 128; this artifact is 64). +// +// Validation: `--check ` dequantizes real blocks and asserts the STRUCTURAL invariant that +// every output value is one of {-d, 0, +d, +2d} for that block's own scale. That catches bit-order, +// sign and stride bugs, which are the failure modes a dequantizer actually has. It is deliberately +// not a correctness-vs-ggml test - that needs ggml linked, which is P1.S3's next step. + +#include +#include +#include +#include +#include +#include + +#define STRATA_GGUF_MAIN_DISABLED 1 +#include "strata/artifact/gguf_reader.hpp" + +namespace strata { + +// ---- fp16/bf16 -> fp32. Both handle subnormals and infinities; naive shifts do not. +inline float fp16_to_fp32(uint16_t h) { + const uint32_t sign = (uint32_t)(h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) + f = sign << 31; + else { + exp = 127 - 15 + 1; + while (!(man & 0x400u)) { + man <<= 1; + --exp; + } + man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); + } + } else if (exp == 31) + f = (sign << 31) | 0x7F800000u | (man << 13); + else + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + float out; + std::memcpy(&out, &f, 4); + return out; +} + +inline float bf16_to_fp32(uint16_t h) { + const uint32_t f = (uint32_t)h << 16; + float out; + std::memcpy(&out, &f, 4); + return out; +} + +inline uint16_t read_u16(const uint8_t* p) { + return (uint16_t)(p[0] | (p[1] << 8)); +} + +// ---- Q2_0: 64 elements from an 18-byte block. Mirrors dequantize_row_q2_0 (ggml master 3cf03257). +inline void dequantize_q2_0(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const uint8_t* qs = block + 2; + for (int j = 0; j < 64; ++j) { + const int byte_index = j / 4; + const int bit_offset = (j % 4) * 2; + const int code = (qs[byte_index] >> bit_offset) & 0x03; + out[j] = (float)(code - 1) * d; // code {0,1,2,3} -> symbol {-1,0,+1,+2} + } +} + +// ---- Q8_0: 32 elements from a 34-byte block. +inline void dequantize_q8_0(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const int8_t* qs = (const int8_t*)(block + 2); + for (int j = 0; j < 32; ++j) out[j] = (float)qs[j] * d; +} + +// ---- Q4_0: 32 elements from an 18-byte block. Low nibble is element j, high nibble is j+16. +inline void dequantize_q4_0(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const uint8_t* qs = block + 2; + for (int j = 0; j < 16; ++j) { + out[j] = (float)((int)(qs[j] & 0x0F) - 8) * d; + out[j + 16] = (float)((int)(qs[j] >> 4) - 8) * d; + } +} + +// ---- Q5_0: 32 elements from a 22-byte block. Same nibble layout as Q4_0 plus a 5th bit per element +// packed in qh[4]; the 32 bits of qh are the high bits of elements 0..31 in order. +inline void dequantize_q5_0(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const uint8_t* qh = block + 2; + const uint8_t* qs = block + 6; + const uint32_t h = + (uint32_t)qh[0] | ((uint32_t)qh[1] << 8) | ((uint32_t)qh[2] << 16) | ((uint32_t)qh[3] << 24); + for (int j = 0; j < 16; ++j) { + const int x0 = (int)(qs[j] & 0x0F) | (int)(((h >> j) & 1u) << 4); + const int x1 = (int)(qs[j] >> 4) | (int)(((h >> (j + 16)) & 1u) << 4); + out[j] = (float)(x0 - 16) * d; + out[j + 16] = (float)(x1 - 16) * d; + } +} +// ---- IQ4_NL: 32 elements from an 18-byte block. Non-linear 4-bit codebook, NOT a linear grid, so +// the table must be exact. Copied verbatim from ggml-common.h `kvalues_iq4nl` at 3cf03257: +// -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 +// Layout matches dequantize_row_iq4_nl (ggml-quants.c): low nibble is element j, high nibble j+16. +static const int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, + 1, 13, 25, 38, 53, 69, 89, 113}; + +inline void dequantize_iq4_nl(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const uint8_t* qs = block + 2; + for (int j = 0; j < 16; ++j) { + out[j] = d * (float)kvalues_iq4nl[qs[j] & 0x0F]; + out[j + 16] = d * (float)kvalues_iq4nl[qs[j] >> 4]; + } +} +// ---- Q6_K: 256 elements from a 210-byte super-block, transcribed from dequantize_row_q6_K +// (ggml-quants.c at 3cf03257). Layout: ql[128] low nibbles, qh[64] high 2 bits, scales[16] int8, +// fp16 d LAST. Processed in two 128-element halves, each advancing ql by 64, qh by 32, sc by 8. +// The `sc` indices are is+{0,2,4,6} with is = l/16 - so each 32-element group draws from 8 of the 16 +// scales, and the four output positions within a 32-group use different scales. Easy to get subtly +// wrong, which is why it is transcribed rather than recalled. +inline void dequantize_q6_K(const uint8_t* block, float* out) { + const uint8_t* ql = block; // 128 bytes + const uint8_t* qh = block + 128; // 64 + const int8_t* sc = (const int8_t*)(block + 192); // 16 + const float d = fp16_to_fp32(read_u16(block + 208)); + float* y = out; + for (int n = 0; n < 256; n += 128) { + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + const int q1 = (int)((ql[l + 0] & 0x0F) | (((qh[l] >> 0) & 3) << 4)) - 32; + const int q2 = (int)((ql[l + 32] & 0x0F) | (((qh[l] >> 2) & 3) << 4)) - 32; + const int q3 = (int)((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32; + const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32; + y[l + 0] = d * (float)sc[is + 0] * (float)q1; + y[l + 32] = d * (float)sc[is + 2] * (float)q2; + y[l + 64] = d * (float)sc[is + 4] * (float)q3; + y[l + 96] = d * (float)sc[is + 6] * (float)q4; + } + y += 128; + ql += 64; + qh += 32; + sc += 8; + } +} +// ---- Q4_K: 256 elements from a 144-byte super-block. Layout is `fp16 d`, `fp16 dmin` (so the FIRST +// four bytes are the scale pair, unlike Q6_K where d is last), `scales[12]`, `qs[128]`. +// Both functions transcribed from ggml-quants.c at 3cf03257. The 6-bit scale/min unpacking in +// get_scale_min_k4 is the part that is impossible to recall reliably: the low 4 bits of the second +// half come from q[j+4], and the high 2 bits from the low halves' top bits (q[j-4] and q[j]). +static inline void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { + if (j < 4) { + d = q[j] & 63; + m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4); + } +} + +inline void dequantize_q4_K(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); // d + const float mn = fp16_to_fp32(read_u16(block + 2)); // dmin + const uint8_t* scales = block + 4; // 12 bytes + const uint8_t* q = block + 16; // 128 bytes + float* y = out; + int is = 0; + for (int j = 0; j < 256; j += 64) { + uint8_t sc, m; + get_scale_min_k4(is + 0, scales, sc, m); + const float d1 = d * (float)sc, m1 = mn * (float)m; + get_scale_min_k4(is + 1, scales, sc, m); + const float d2 = d * (float)sc, m2 = mn * (float)m; + for (int l = 0; l < 32; ++l) *y++ = d1 * (float)(q[l] & 0x0F) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * (float)(q[l] >> 4) - m2; + q += 32; + is += 2; + } +} +// ---- Q5_K: 256 elements from a 176-byte super-block: `fp16 d`, `fp16 dmin`, `scales[12]`, +// `qh[32]`, `qs[128]`. Same shape as Q4_K plus the 5th bit plane. Transcribed from +// dequantize_row_q5_K (ggml-quants.c, 3cf03257). The 5th bits are selected by a mask that SHIFTS LEFT +// BY 2 each 64-element group (u1 = 1,4,16,64; u2 = 2,8,32,128) - a recalled version would very likely +// have used a fixed mask or a shift by 1. +inline void dequantize_q5_K(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const float mn = fp16_to_fp32(read_u16(block + 2)); + const uint8_t* scales = block + 4; // 12 + const uint8_t* qh = block + 16; // 32 + const uint8_t* ql = block + 48; // 128 + float* y = out; + int is = 0; + uint8_t u1 = 1, u2 = 2; + for (int j = 0; j < 256; j += 64) { + uint8_t sc, m; + get_scale_min_k4(is + 0, scales, sc, m); + const float d1 = d * (float)sc, m1 = mn * (float)m; + get_scale_min_k4(is + 1, scales, sc, m); + const float d2 = d * (float)sc, m2 = mn * (float)m; + for (int l = 0; l < 32; ++l) *y++ = d1 * (float)((ql[l] & 0x0F) + ((qh[l] & u1) ? 16 : 0)) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2; + ql += 32; + is += 2; + u1 = (uint8_t)(u1 << 2); + u2 = (uint8_t)(u2 << 2); + } +} +// ---- Q3_K: 256 elements from a 110-byte super-block: `hmask[32]`, `qs[64]`, `scales[12]`, `fp16 d` +// LAST. Transcribed from dequantize_row_q3_K (ggml-quants.c, 3cf03257). This type has NO `dmin` - its +// scales are SIGNED 6-bit with a `- 32` bias - so it does not follow the Q4_K/Q5_K pattern at all. +// Two details that cannot be recalled: +// * the 12 scale bytes are bit-repacked through three 32-bit masks before use (kmask1/2 below), +// because 16 six-bit scales do not fit in 12 bytes linearly; +// * the low 2 bits are offset by -4 when the high bit is CLEAR, i.e. the correction is NEGATIVE. +inline void dequantize_q3_K(const uint8_t* block, float* out) { + const uint8_t* hm = block; // 32 + const uint8_t* q = block + 32; // 64 + const float d_all = fp16_to_fp32(read_u16(block + 108)); + + const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu; + uint32_t aux[4] = {0, 0, 0, 0}; + std::memcpy(aux, block + 96, 12); + const uint32_t tmp = aux[2]; + aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); + aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); + aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); + aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); + const int8_t* scales = (const int8_t*)aux; + + float* y = out; + int is = 0; + uint8_t m = 1; // hoisted: ggml declares this BEFORE the n loop, so it does not reset between halves + for (int n = 0; n < 256; n += 128) { + int shift = 0; + for (int j = 0; j < 4; ++j) { + float dl = d_all * (float)(scales[is++] - 32); + for (int l = 0; l < 16; ++l) + *y++ = dl * (float)((int8_t)((q[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4)); + dl = d_all * (float)(scales[is++] - 32); + for (int l = 0; l < 16; ++l) + *y++ = dl * (float)((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4)); + shift += 2; + m = (uint8_t)(m << 1); + } + q += 32; + } +} +// ---- IQ4_XS: 256 elements from a 136-byte super-block: `fp16 d`, `uint16 scales_h`, `scales_l[4]`, +// `qs[128]`. Transcribed from dequantize_row_iq4_xs (ggml-quants.c, 3cf03257). Reuses the IQ4_NL +// codebook. Eight 32-element groups; each group's scale is 6 bits assembled from the LOW nibble of +// `scales_l[ib/2]` (selected by ib%2) and TWO bits of `scales_h` at shift 2*ib - so the high bits come +// from a 16-bit field indexed by group, not from a byte array. Then `- 32`, as in Q3_K. +inline void dequantize_iq4_xs(const uint8_t* block, float* out) { + const float d = fp16_to_fp32(read_u16(block)); + const uint16_t scales_h = read_u16(block + 2); + const uint8_t* scales_l = block + 4; // 4 + const uint8_t* qs = block + 8; // 128 + float* y = out; + for (int ib = 0; ib < 8; ++ib) { + const int ls = ((scales_l[ib / 2] >> (4 * (ib % 2))) & 0x0F) | (((scales_h >> (2 * ib)) & 3) << 4); + const float dl = d * (float)(ls - 32); + for (int j = 0; j < 16; ++j) { + y[j + 0] = dl * (float)kvalues_iq4nl[qs[j] & 0x0F]; + y[j + 16] = dl * (float)kvalues_iq4nl[qs[j] >> 4]; + } + y += 32; + qs += 16; + } +} +// ---- element types +inline void dequantize_f32(const uint8_t* p, float* out, int n) { + std::memcpy(out, p, (size_t)n * 4); +} +inline void dequantize_f16(const uint8_t* p, float* out, int n) { + for (int i = 0; i < n; ++i) out[i] = fp16_to_fp32(read_u16(p + 2 * i)); +} +inline void dequantize_bf16(const uint8_t* p, float* out, int n) { + for (int i = 0; i < n; ++i) out[i] = bf16_to_fp32(read_u16(p + 2 * i)); +} + +} // namespace strata diff --git a/engine/strata/include/strata/artifact/gguf_reader.hpp b/engine/strata/include/strata/artifact/gguf_reader.hpp new file mode 100644 index 00000000..298dc3bc --- /dev/null +++ b/engine/strata/include/strata/artifact/gguf_reader.hpp @@ -0,0 +1,606 @@ +// include/strata/artifact/gguf_reader.hpp - generated from src/artifact/gguf_reader.cpp by +// scripts/split_artifact.py. Header-only on purpose: the reader is one translation unit's worth of +// code with no state to hide, and a header-only split cannot introduce a duplicate-symbol or +// missing-declaration bug in code that is already validated. +#pragma once +// src/artifact/gguf_reader.cpp - P1.S2: GGUF v3 reader, mmap, no ggml dependency. +// +// The C++ counterpart of tools/gguf_reader.py, which has been the reference since P0.S6 (written +// because gguf-py cannot represent type 42 / Q2_0). Per P1.S2 it must: +// * mmap the file and parse header, metadata KV (ALL value types incl. arrays), tensor directory +// * be multi-shard aware (split.* keys) +// * carry an architecture guard: general.architecture == "qwen4exp" and the compiled-in constants +// must match, refusing with a precise error otherwise +// * have no ggml dependency +// +// This file is the reader plus a `--check` mode that validates it the way the Python one is +// validated: parse the tiny model AND both real shards, and report counts that other harnesses have +// already established independently (1,223 / 1 tensors; 202 Q2_0 in shard 1). Agreement with those +// numbers is the test. +// +// Build: scripts/build_artifact.bat Run: gguf_reader.exe [--check] + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "strata/artifact/gguf_split.hpp" + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX // windows.h's min/max macros would break std::min/std::max in every file that includes this one +#endif +#include +#else +#include +#include +#include +#include +#endif + +namespace strata { + +// ---- ggml type ids we care about. 42 = Q2_0, the PrismML ternary 2-bit encoding this engine targets. +inline const char* ggml_type_name(uint32_t t) { + switch (t) { + case 0: + return "F32"; + case 1: + return "F16"; + case 2: + return "Q4_0"; + case 3: + return "Q4_1"; + case 6: + return "Q5_0"; + case 7: + return "Q5_1"; + case 8: + return "Q8_0"; + case 9: + return "Q8_1"; + case 10: + return "Q2_K"; + case 11: + return "Q3_K"; + case 12: + return "Q4_K"; + case 13: + return "Q5_K"; + case 14: + return "Q6_K"; + case 15: + return "Q8_K"; + case 16: + return "IQ2_XXS"; + case 17: + return "IQ2_XS"; + case 18: + return "IQ3_XXS"; + case 19: + return "IQ1_S"; + case 20: + return "IQ4_NL"; + case 21: + return "IQ3_S"; + case 22: + return "IQ2_S"; + case 23: + return "IQ4_XS"; + case 24: + return "I8"; + case 30: + return "BF16"; + case 34: + return "TQ1_0"; + case 35: + return "TQ2_0"; + case 39: + return "MXFP4"; + case 40: + return "NVFP4"; + case 41: + return "Q1_0"; + case 42: + return "Q2_0"; + default: + return "?"; + } +} + +// Block geometry: (elements per block, bytes per block). Q2_0 is 64/18 - proven from this artifact's +// own offset brackets in P0.S6 and recorded in docs/q2_0-contract.md. +inline bool block_geometry(uint32_t t, int& elems, int& bytes) { + switch (t) { + case 0: + elems = 1; + bytes = 4; + return true; + case 1: + case 30: + elems = 1; + bytes = 2; + return true; + case 2: + elems = 32; + bytes = 18; + return true; + case 3: + elems = 32; + bytes = 20; + return true; + case 6: + elems = 32; + bytes = 22; + return true; + case 7: + elems = 32; + bytes = 24; + return true; + case 8: + elems = 32; + bytes = 34; + return true; + case 9: + elems = 32; + bytes = 36; + return true; + case 10: + elems = 256; + bytes = 84; + return true; + case 11: + elems = 256; + bytes = 110; + return true; + case 12: + elems = 256; + bytes = 144; + return true; + case 13: + elems = 256; + bytes = 176; + return true; + case 14: + elems = 256; + bytes = 210; + return true; + case 16: + elems = 256; + bytes = 66; + return true; + case 17: + elems = 256; + bytes = 74; + return true; + case 18: + elems = 256; + bytes = 98; + return true; + case 20: + elems = 32; + bytes = 18; + return true; + case 21: // IQ3_S + elems = 256; + bytes = 110; + return true; + case 22: // IQ2_S + elems = 256; + bytes = 82; + return true; + case 23: + elems = 256; + bytes = 136; + return true; + case 29: // IQ1_M + elems = 256; + bytes = 56; + return true; + case 24: // I8: raw bytes (the FP8 PLE table of tools/ple_fp8_pack.py) + elems = 1; + bytes = 1; + return true; + case 42: + elems = 64; + bytes = 18; + return true; + default: + return false; + } +} + +struct TensorInfo { + std::string name; + std::vector shape; // GGUF order: dim 0 varies fastest + uint32_t type = 0; + uint64_t offset = 0; + uint64_t elements() const { + uint64_t n = 1; + for (auto d : shape) n *= d; + return n; + } + const char* type_name() const { return ggml_type_name(type); } +}; + +// A bounds-checked cursor over the mmapped header region. Every read is checked, so a truncated or +// corrupt file produces a precise error rather than a segfault. +class Cursor { +public: + Cursor(const uint8_t* base, size_t size) : base_(base), size_(size) {} + void need(size_t n) const { + if (pos_ + n > size_) throw std::runtime_error("GGUF: unexpected end of file in header"); + } + template T read() { + need(sizeof(T)); + T v; + std::memcpy(&v, base_ + pos_, sizeof(T)); + pos_ += sizeof(T); + return v; + } + std::string str() { + const uint64_t n = read(); + need((size_t)n); + std::string s(reinterpret_cast(base_ + pos_), (size_t)n); + pos_ += (size_t)n; + return s; + } + size_t pos() const { return pos_; } + +private: + const uint8_t* base_; + size_t size_; + size_t pos_ = 0; +}; + +enum class MetaType : uint32_t { U8 = 0, I8, U16, I16, U32, I32, F32, BOOL, STRING, ARRAY, U64, I64, F64 }; + +struct MetaValue { + MetaType type = MetaType::U32; + uint64_t u = 0; // integer payloads + double f = 0; // float payloads + std::string s; // string payloads + MetaType elem = MetaType::U32; // arrays + uint64_t count = 0; + std::vector items; + bool is_num() const { return type != MetaType::STRING && type != MetaType::ARRAY; } + double num() const { return (type == MetaType::F32 || type == MetaType::F64) ? f : (double)u; } +}; + +inline MetaValue read_value(Cursor& c, MetaType t, int depth = 0) { + if (depth > 2) throw std::runtime_error("GGUF: array nesting too deep"); + MetaValue v; + v.type = t; + switch (t) { + case MetaType::U8: + v.u = c.read(); + break; + case MetaType::I8: + v.u = (uint64_t)(int64_t)c.read(); + break; + case MetaType::U16: + v.u = c.read(); + break; + case MetaType::I16: + v.u = (uint64_t)(int64_t)c.read(); + break; + case MetaType::U32: + v.u = c.read(); + break; + case MetaType::I32: + v.u = (uint64_t)(int64_t)c.read(); + break; + case MetaType::F32: { + float x = c.read(); + v.f = x; + v.u = 0; + break; + } + case MetaType::BOOL: + v.u = c.read() ? 1 : 0; + break; + case MetaType::STRING: + v.s = c.str(); + break; + case MetaType::U64: + v.u = c.read(); + break; + case MetaType::I64: + v.u = (uint64_t)c.read(); + break; + case MetaType::F64: + v.f = c.read(); + break; + case MetaType::ARRAY: { + v.elem = (MetaType)c.read(); + v.count = c.read(); + if (v.count > (1u << 24)) throw std::runtime_error("GGUF: implausible array length"); + v.items.reserve((size_t)std::min(v.count, 64)); + for (uint64_t i = 0; i < v.count; ++i) { + MetaValue e = read_value(c, v.elem, depth + 1); + if (i < 64) v.items.push_back(std::move(e)); // keep a sample; the count is what matters + } + break; + } + default: + throw std::runtime_error("GGUF: unknown metadata value type"); + } + return v; +} + +class GgufFile { +public: + explicit GgufFile(const std::string& path) : path_(path) { + try { open(); } + catch (...) { close(); throw; } + } + ~GgufFile() { close(); } + GgufFile(const GgufFile&) = delete; + GgufFile& operator=(const GgufFile&) = delete; + + const std::vector& tensors() const { return tensors_; } + const std::map& metadata() const { return meta_; } + uint32_t version() const { return version_; } + uint64_t data_start() const { return data_start_; } + uint64_t file_size() const { return size_; } + uint64_t alignment() const { return alignment_; } + const std::string& path() const { return path_; } + + const TensorInfo* find(const std::string& name) const { + for (const auto& t : tensors_) + if (t.name == name) return &t; + return nullptr; + } + uint64_t count_type(const char* tn) const { + uint64_t n = 0; + for (const auto& t : tensors_) + if (std::strcmp(t.type_name(), tn) == 0) ++n; + return n; + } + const MetaValue* get(const std::string& key) const { + auto it = meta_.find(key); + return it == meta_.end() ? nullptr : &it->second; + } + const uint8_t* tensor_data(const TensorInfo& t) const { return base_ + data_start_ + t.offset; } + +private: + void open() { +#ifdef _WIN32 + HANDLE h = CreateFileA(path_.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("cannot open " + path_); + LARGE_INTEGER li{}; + GetFileSizeEx(h, &li); + size_ = (uint64_t)li.QuadPart; + HANDLE m = CreateFileMappingA(h, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (!m) { + CloseHandle(h); + throw std::runtime_error("CreateFileMapping failed"); + } + base_ = (const uint8_t*)MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + if (!base_) { + CloseHandle(m); + CloseHandle(h); + throw std::runtime_error("MapViewOfFile failed"); + } + map_ = m; + file_ = h; +#else + int fd = ::open(path_.c_str(), O_RDONLY); + if (fd < 0) throw std::runtime_error("cannot open " + path_); + fd_ = fd; + struct stat st{}; + if (fstat(fd, &st) != 0) throw std::runtime_error("fstat failed"); + size_ = (uint64_t)st.st_size; + void* p = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, 0); + if (p == MAP_FAILED) throw std::runtime_error("mmap failed"); + base_ = (const uint8_t*)p; +#endif + parse(); + } + void close() { +#ifdef _WIN32 + if (base_) UnmapViewOfFile(base_); + if (map_) CloseHandle((HANDLE)map_); + if (file_) CloseHandle((HANDLE)file_); +#else + if (base_) munmap((void*)base_, size_); + if (fd_ >= 0) ::close(fd_); +#endif + } + + void parse() { + Cursor c(base_, size_); + const uint32_t magic = c.read(); + if (magic != 0x46554747u) throw std::runtime_error("not a GGUF file (bad magic)"); + version_ = c.read(); + if (version_ != 3) + throw std::runtime_error("GGUF v" + std::to_string(version_) + ", this reader handles v3"); + const uint64_t n_tensors = c.read(); + const uint64_t n_kv = c.read(); + + for (uint64_t i = 0; i < n_kv; ++i) { + std::string key = c.str(); + MetaType t = (MetaType)c.read(); + meta_.emplace(std::move(key), read_value(c, t)); + } + tensors_.reserve((size_t)n_tensors); + // GGUF has no index to arbitrate between two tensors of one name: find() is first-match, so a + // duplicate would silently win by position. Refuse the file at open instead, naming both. + std::set names; + for (uint64_t i = 0; i < n_tensors; ++i) { + TensorInfo t; + t.name = c.str(); + if (!names.insert(t.name).second) + throw std::runtime_error("GGUF: duplicate tensor name '" + t.name + "' in " + path_); + const uint32_t nd = c.read(); + if (nd == 0 || nd > 4) throw std::runtime_error("GGUF: bad n_dims for " + t.name); + t.shape.resize(nd); + for (uint32_t d = 0; d < nd; ++d) t.shape[d] = c.read(); + t.type = c.read(); + t.offset = c.read(); + tensors_.push_back(std::move(t)); + } + uint64_t align = 32; + if (const MetaValue* a = get("general.alignment")) + if (a->u) align = a->u; + alignment_ = align; + data_start_ = (c.pos() + align - 1) / align * align; + if (data_start_ > size_) throw std::runtime_error("GGUF: data section starts past EOF"); + } + + std::string path_; + const uint8_t* base_ = nullptr; + uint64_t size_ = 0, data_start_ = 0, alignment_ = 32; + uint32_t version_ = 0; +#ifdef _WIN32 + void* file_ = nullptr; + void* map_ = nullptr; +#else + int fd_ = -1; +#endif + std::vector tensors_; + std::map meta_; +}; + +// Bytes of a tensor's payload from its shape and block geometry; 0 when the type is unknown, a row is not whole +// blocks, or the count overflows. +inline uint64_t tensor_payload_bytes(const TensorInfo& t) { + int be = 0, bb = 0; + if (t.shape.empty() || !block_geometry(t.type, be, bb) || t.shape[0] % (uint64_t) be) return 0; + uint64_t elements = 1; + for (uint64_t d : t.shape) { + if (d == 0 || elements > (std::numeric_limits::max)() / d) return 0; + elements *= d; + } + const uint64_t blocks = elements / (uint64_t) be; + if (blocks > (std::numeric_limits::max)() / (uint64_t) bb) return 0; + return blocks * (uint64_t) bb; +} + +// The shards of one model (strata::gguf_split_paths), opened together; tensors are looked up across all of them. +// From eddoursul/Strata 8029fa9, with the split-key validation of #255 (gopinath87607) made a property of the +// model rather than of one loader: a split GGUF carries the model's metadata (general.architecture and the +// qwen4exp keys) in its FIRST shard only, and the later shards just declare split.count / split.no / +// split.tensors.count. Unsloth's UD-Q4_K_XL is the extreme case: shard 1 holds the metadata and no tensor at +// all, and output.weight, token_embd.weight and the PLE table live in shard 2. So the architecture is checked +// on `meta()` and a tensor is read from the shard that holds it. +// +// Refused at construction: a later shard whose split keys disagree with shard 1's (another model's shard, or a +// shard renamed into the family), a split model whose tensor directories do not add up to split.tensors.count, +// and a tensor name present in two shards (GGUF has no index to say which one is meant). +class GgufModel { +public: + explicit GgufModel(const std::vector& paths) { + if (paths.empty()) throw std::runtime_error("GGUF: a model needs at least one shard"); + for (const auto& p : paths) shards_.push_back(std::make_unique(p)); + validate_split(); + for (size_t i = 0; i < shards_.size(); ++i) + for (const auto& t : shards_[i]->tensors()) { + const auto ins = index_.emplace(t.name, std::make_pair(i, &t)); + if (!ins.second) + throw std::runtime_error("GGUF: tensor " + t.name + " is in two shards (" + + shards_[ins.first->second.first]->path() + " and " + + shards_[i]->path() + ")"); + } + } + /// Opens every shard of the model that `any_shard` belongs to (throws when one is missing). + static GgufModel open(const std::string& any_shard) { return GgufModel(gguf_split_paths(any_shard)); } + + size_t size() const { return shards_.size(); } + const GgufFile& shard(size_t i) const { return *shards_[i]; } + /// The metadata shard: general.architecture and the model's keys. + const GgufFile& meta() const { return *shards_[0]; } + /// The tensor named `name` (its shard index in `*shard`), or nullptr. + const TensorInfo* find(const std::string& name, size_t* shard = nullptr) const { + const auto it = index_.find(name); + if (it == index_.end()) return nullptr; + if (shard) *shard = it->second.first; + return it->second.second; + } + /// Whether `t` (a tensor of shard `s`) has a known byte count that lies inside its file. + bool in_bounds(const TensorInfo& t, size_t s) const { + const GgufFile& g = *shards_[s]; + const uint64_t bytes = tensor_payload_bytes(t); + const uint64_t payload = g.file_size() - g.data_start(); + return bytes != 0 && t.offset <= payload && bytes <= payload - t.offset; + } + +private: + void validate_split() const { + const size_t n = shards_.size(); + const MetaValue* count0 = shards_[0]->get("split.count"); + if (n == 1) { + if (count0 && count0->u > 1) + throw std::runtime_error("GGUF: " + shards_[0]->path() + " is shard 1 of " + std::to_string(count0->u) + + ", but it was opened as a whole model"); + return; + } + if (!shards_[0]->get("general.architecture")) + throw std::runtime_error("GGUF: " + shards_[0]->path() + " has no general.architecture; the first shard " + "of a split model carries the metadata"); + const MetaValue* total = shards_[0]->get("split.tensors.count"); + uint64_t tensors = 0; + for (size_t i = 0; i < n; ++i) { + const GgufFile& g = *shards_[i]; + const MetaValue* count = g.get("split.count"); + const MetaValue* no = g.get("split.no"); + const MetaValue* tc = g.get("split.tensors.count"); + if (!count || !no || count->u != n || no->u != i || (total && (!tc || tc->u != total->u))) + throw std::runtime_error("GGUF: " + g.path() + " does not declare itself shard " + std::to_string(i + 1) + + " of " + std::to_string(n) + " of this model (split.count / split.no / " + "split.tensors.count)"); + tensors += g.tensors().size(); + } + if (total && tensors != total->u) + throw std::runtime_error("GGUF: the " + std::to_string(n) + " shards hold " + std::to_string(tensors) + + " tensors, but split.tensors.count is " + std::to_string(total->u)); + } + + std::vector> shards_; + std::map> index_; +}; + +// ---- architecture guard (P1.S2). The engine is specialised to ONE model; anything else must be +// refused with a precise error rather than silently mis-run. +struct Qwen4ExpGuard { + uint32_t block_count = 48, hidden = 2560, experts = 0, experts_used = 0, head_count = 24, + head_count_kv = 2; // 0 = presence-only: pruned variants (GSQ-RCO Coder) legitimately ship + // fewer experts than the canonical 512; the graph reads the true value +}; + +inline std::string check_architecture(const GgufFile& g, const Qwen4ExpGuard& want = {}) { + const MetaValue* arch = g.get("general.architecture"); + if (!arch) return "missing general.architecture"; + if (arch->s != "qwen4exp") return "architecture is '" + arch->s + "', this engine requires 'qwen4exp'"; + struct Req { + const char* key; + uint64_t want; + }; + const Req reqs[] = { + {"qwen4exp.block_count", want.block_count}, + {"qwen4exp.embedding_length", want.hidden}, + {"qwen4exp.expert_count", want.experts}, + {"qwen4exp.expert_used_count", want.experts_used}, + {"qwen4exp.attention.head_count", want.head_count}, + {"qwen4exp.attention.head_count_kv", want.head_count_kv}, + }; + for (const auto& r : reqs) { + const MetaValue* v = g.get(r.key); + if (!v) return std::string("missing ") + r.key; + if (r.want && v->u != r.want) + return std::string(r.key) + " = " + std::to_string(v->u) + ", expected " + std::to_string(r.want); + } + return {}; // empty == ok +} + +} // namespace strata diff --git a/engine/strata/include/strata/artifact/gguf_split.hpp b/engine/strata/include/strata/artifact/gguf_split.hpp new file mode 100644 index 00000000..0f01001f --- /dev/null +++ b/engine/strata/include/strata/artifact/gguf_split.hpp @@ -0,0 +1,52 @@ +// include/strata/artifact/gguf_split.hpp - the shards of a split model. Separate from gguf_reader.hpp, which +// includes , so any translation unit can resolve a model's shards. +// +// From eddoursul/Strata 8029fa9 (gguf_split_paths), with one change of contract: upstream's model_shards() +// skipped a shard it could not open and returned the rest, so a download that was still running (or a shard +// deleted by hand) produced a model with some layers missing and an error much later, or none. A missing shard +// is now an error that names it. +#pragma once + +#include +#include +#include +#include +#include + +namespace strata { + +// Split models: `-00001-of-0000N.gguf` ... `-0000N-of-0000N.gguf`, as llama.cpp's gguf-split names +// them. Given ANY shard's path, the shards in split order (the metadata shard, 00001, first); a file without that +// suffix is a model of one shard. Only the five digits of the shard number are rewritten, so the directory and +// the stem are the caller's own spelling (a symlinked Hugging Face snapshot keeps its split names). Throws when +// a shard is missing. +inline std::vector gguf_split_paths(const std::string& any) { + static const char tag[] = "-of-"; + const size_t at = any.rfind(tag); + // "...-NNNNN-of-MMMMM.gguf": five digits before the tag, five after it, then the extension + if (at == std::string::npos || at < 6 || any[at - 6] != '-' || any.size() != at + 4 + 5 + 5 || + any.compare(at + 9, 5, ".gguf") != 0) + return {any}; + int no = 0, n = 0; + for (size_t i = 0; i < 5; ++i) { + const char a = any[at - 5 + i], b = any[at + 4 + i]; + if (a < '0' || a > '9' || b < '0' || b > '9') return {any}; + no = no * 10 + (a - '0'); + n = n * 10 + (b - '0'); + } + if (n < 1 || no < 1 || no > n) return {any}; + std::vector out; + for (int i = 1; i <= n; ++i) { + char num[8]; + std::snprintf(num, sizeof num, "%05d", i); + std::string p = any; + p.replace(at - 5, 5, num); + if (!std::ifstream(p, std::ios::binary)) + throw std::runtime_error("missing model shard " + p + " (shard " + std::to_string(i) + " of " + + std::to_string(n) + "; is the download complete?)"); + out.push_back(std::move(p)); + } + return out; +} + +} // namespace strata diff --git a/engine/strata/include/strata/core/conversation_buffer.hpp b/engine/strata/include/strata/core/conversation_buffer.hpp new file mode 100644 index 00000000..1cb8af77 --- /dev/null +++ b/engine/strata/include/strata/core/conversation_buffer.hpp @@ -0,0 +1,154 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +// Snapshot-owned host storage. Appending never relocates existing payloads; +// only the small segment directory can move. No sharing or copy-on-write is +// needed because a parked image and its retained active buffers have one owner. +class ConversationBuffer { +public: + static constexpr size_t segment_bytes = 16 * 1024 * 1024; + ConversationBuffer() = default; + ConversationBuffer(std::initializer_list values) { + resize(values.size()); + visit(0, size(), [&](uint8_t* p, size_t n, size_t at) { + std::memcpy(p, values.begin() + at, n); + return true; + }); + } + ConversationBuffer(const ConversationBuffer&) = default; + ConversationBuffer& operator=(const ConversationBuffer&) = default; + ConversationBuffer(ConversationBuffer&& other) noexcept + : segments_(std::move(other.segments_)), size_(std::exchange(other.size_, 0)) {} + ConversationBuffer& operator=(ConversationBuffer&& other) noexcept { + if (this == &other) return *this; + segments_ = std::move(other.segments_); + size_ = std::exchange(other.size_, 0); + return *this; + } + + size_t size() const { return size_; } + bool empty() const { return size_ == 0; } + size_t bytes() const { + size_t n = segments_.capacity() * sizeof(Segment); + for (const auto& segment : segments_) n += segment.capacity(); + return n; + } + // Includes the old directory while reserve allocates its replacement. + // Saturation makes an overflowing estimate fail admission before resize. + size_t allocation_peak(size_t n) const { + size_t total = bytes(); + if (n <= size_) return total; + const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); + const size_t extra = n - size_ - std::min(n - size_, spare); + const size_t full = extra / segment_bytes, tail = extra % segment_bytes; + if (!add(total, full * segment_bytes)) return SIZE_MAX; + if (tail && !add(total, segment_capacity(tail, full ? segment_bytes : + segments_.empty() ? 0 : segments_.back().capacity(), size_ != 0))) return SIZE_MAX; + size_t count = segments_.size(); + if (!add(count, full + (tail != 0))) return SIZE_MAX; + if (count > segments_.capacity() && + (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; + return total; + } + void resize(size_t n, uint8_t value = 0) { + if (n > size_) { + const bool growing = size_ != 0; + const size_t spare = segments_.empty() ? 0 : segments_.back().capacity() - segments_.back().size(); + const size_t extend = std::min(n - size_, spare); + const size_t extra = n - size_ - extend; + segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); + if (extend) { + segments_.back().resize(segments_.back().size() + extend, value); + size_ += extend; + } + while (size_ < n) { + const size_t count = std::min(segment_bytes, n - size_); + const size_t previous = segments_.empty() ? 0 : segments_.back().capacity(); + Segment segment; + segment.reserve(segment_capacity(count, previous, growing)); + segment.resize(count, value); + segments_.push_back(std::move(segment)); + size_ += count; + } + } else { + while (!segments_.empty() && size_ - segments_.back().size() >= n) { + size_ -= segments_.back().size(); + segments_.pop_back(); + } + if (size_ > n) segments_.back().resize(segments_.back().size() - (size_ - n)); + size_ = n; + } + } + void pop_back() { resize(size_ - 1); } + + // fn(pointer, count, absolute_offset); false aborts a transfer immediately. + template bool visit(size_t offset, size_t count, Fn fn) { + return visit_impl(*this, offset, count, fn); + } + template bool visit(size_t offset, size_t count, Fn fn) const { + return visit_impl(*this, offset, count, fn); + } + bool read(void* target, size_t offset, size_t count) const { + return visit(offset, count, [&](const uint8_t* p, size_t n, size_t at) { + std::memcpy(static_cast(target) + at - offset, p, n); + return true; + }); + } + bool operator==(const ConversationBuffer& other) const { + if (size_ != other.size_) return false; + size_t a = 0, b = 0, x = 0, y = 0; + while (a < segments_.size() && b < other.segments_.size()) { + const auto& left = segments_[a]; + const auto& right = other.segments_[b]; + const size_t n = std::min(left.size() - x, right.size() - y); + if (std::memcmp(left.data() + x, right.data() + y, n)) return false; + x += n; y += n; + if (x == left.size()) { ++a; x = 0; } + if (y == right.size()) { ++b; y = 0; } + } + return true; + } + +private: + using Segment = std::vector; + // A fresh capture allocates exactly its payload. Later appends reserve + // geometrically growing segments, bounded by 16 MiB. Small chat turns then + // extend the final allocation instead of adding one transfer per turn. + static size_t segment_capacity(size_t count, size_t previous, bool growing) { + if (!growing) return count; + return std::max(count, std::min(segment_bytes, std::max(65536, std::min(previous, segment_bytes/2)*2))); + } + static bool add(size_t& n, size_t extra) { + if (extra > SIZE_MAX - n) return false; + n += extra; + return true; + } + template static bool visit_impl(Self& self, size_t offset, size_t count, Fn fn) { + if (offset > self.size_ || count > self.size_ - offset) return false; + size_t begin = 0; + for (auto& segment : self.segments_) { + if (!count) break; + const size_t end = begin + segment.size(); + if (offset < end) { + const size_t n = std::min(count, end - offset); + if (!fn(segment.data() + offset - begin, n, offset)) return false; + offset += n; count -= n; + } + begin = end; + } + return count == 0; + } + std::vector segments_; + size_t size_ = 0; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/conversation_cache.hpp b/engine/strata/include/strata/core/conversation_cache.hpp new file mode 100644 index 00000000..0a190c70 --- /dev/null +++ b/engine/strata/include/strata/core/conversation_cache.hpp @@ -0,0 +1,217 @@ +// CPU-only ownership and matching policy for --serve's parked conversations. +// Token equality, image identity, and steering mode are all required for reuse. +#pragma once + +#include "strata/core/conversation_buffer.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { + +struct ConversationImageKey { + int64_t start = 0; + uint64_t hash = 0; + bool operator==(const ConversationImageKey&) const = default; +}; + +struct ConversationCheckpoint { + std::vector ids; + std::vector imgs; + std::vector gdn, ple, tails, dead, block_pos; + uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention + // Ordinary layer-split checkpoints retain each device's running state. + // Whole-session parking is currently single-GPU and rejects these parts. + std::vector stage_parts; + + size_t bytes() const { + size_t n = ids.capacity() * sizeof(int32_t) + imgs.capacity() * sizeof(ConversationImageKey) + + gdn.capacity() + ple.capacity() + tails.capacity() + dead.capacity() + block_pos.capacity() + + stage_parts.capacity() * sizeof(ConversationCheckpoint); + for (const auto& part : stage_parts) n += part.bytes(); + return n; + } +}; + +// Identity-layout K/V pages and completed indexer rows. For streamed layers the +// source is the authoritative host pool, NOT the replaceable VRAM slots. +struct ConversationKv { + int format = 0; + int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; + ConversationBuffer k, v, k_scale, v_scale, pooled; + size_t bytes() const { + return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); + } +}; + +struct ConversationKvReuse { + std::vector kv; + // Original image extent for validation, and the earliest subsequent rewrite. + int64_t captured_tokens = 0, unchanged_tokens = 0; + size_t bytes() const { + size_t n = kv.capacity() * sizeof(ConversationKv); + for (const auto& layer : kv) n += layer.bytes(); + return n; + } +}; + +struct SavedConversation { + // Runtime compatibility only; NOT a model/weights identity or disk schema. + std::array geometry{}; + // The session's layer carve the image was captured from ([0, n_layers) on one GPU); restore requires the same. + int64_t layer_lo = 0, layer_hi = 0; + ConversationCheckpoint live; + std::vector checkpoints; + std::vector kv; // main layers followed by the draft layer + bool cvec = true; + + size_t bytes() const { + size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) + + kv.capacity() * sizeof(ConversationKv); + for (const auto& c : checkpoints) n += c.bytes(); + for (const auto& k : kv) n += k.bytes(); + return n; + } +}; + +template +int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector& prompt, + const std::vector& images) { + const size_t n = c.ids.size(); + // The last prompt token always starts the next verify window. + if (n == 0 || n >= prompt.size() || !std::equal(c.ids.begin(), c.ids.end(), prompt.begin())) return 0; + size_t j = 0; + for (const auto& image : images) { + if (image.start >= (int64_t) n) continue; + if (j == c.imgs.size() || !(c.imgs[j++] == image)) return 0; + } + if (j != c.imgs.size()) return 0; + return (int64_t) n; +} + +class ConversationCache { +public: + struct Match { + size_t index = 0; + int64_t tokens = 0; + bool live = false; + }; + + ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {} + bool enabled() const { return budget_ != 0 && slots_ != 0; } + size_t bytes() const { return bytes_ + reuse_.bytes(); } + size_t size() const { return entries_.size(); } + size_t evictions() const { return evictions_; } + + // Retain only the restored K/V buffers, not duplicate running checkpoints. + // This optimization never evicts a parked conversation to make itself fit. + void retain(std::vector&& kv, int64_t tokens) { + reuse_ = {}; + ConversationKvReuse candidate{std::move(kv), tokens, tokens}; + if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate); + } + void limit_reuse(int64_t first_dirty) { + reuse_.unchanged_tokens = std::min(reuse_.unchanged_tokens, first_dirty); + if (reuse_.unchanged_tokens <= 0) reuse_ = {}; + } + ConversationKvReuse take_reuse() { return std::exchange(reuse_, {}); } + size_t retained_bytes() const { return reuse_.bytes(); } + bool can_fit(size_t incoming, size_t held = 0) const { + return enabled() && held <= budget_ && incoming <= budget_ - held && + entries_.size() < slots_ && bytes() <= budget_ - held - incoming; + } + + template + Match best(const std::vector& prompt, const std::vector& images, bool cvec) const { + Match best; + // Ties prefer the most recently parked branch. The caller prefers its + // already-active state when that offers the same prefix length. + for (size_t i = entries_.size(); i-- > 0;) { + const auto& e = entries_[i]; + if (e.cvec != cvec) continue; + auto consider = [&](const ConversationCheckpoint& c, bool live) { + const int64_t n = conversation_prefix(c, prompt, images); + if (n > best.tokens) best = {i, n, live}; + }; + consider(e.live, true); + for (const auto& c : e.checkpoints) consider(c, false); + } + return best; + } + + SavedConversation take(size_t index) { + SavedConversation out = std::move(entries_.at(index)); + bytes_ -= out.bytes(); + entries_.erase(entries_.begin() + (std::ptrdiff_t) index); + return out; + } + + // Reserve before allocating a snapshot. held is an incoming image removed + // with take() but still alive during the exchange; count it against RAM too. + bool make_room(size_t incoming, size_t held = 0) { + if (!enabled() || held > budget_ || incoming > budget_ - held) return false; + if (bytes() > budget_ - held - incoming) reuse_ = {}; + while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) { + bytes_ -= entries_.front().bytes(); + entries_.pop_front(); + ++evictions_; + } + return true; + } + + // #342: drop the parked entries an outgoing conversation (its live tokens and checkpoint chain) supersedes: + // the same conversation a turn back, whose DEEPEST checkpoint the outgoing chain still holds, so all it adds + // is the tail the client rewrote (the reply as it was generated, before the next request re-rendered it) and + // checkpoints older than that one. A subagent's successive turns parked one such copy each, and make_room's + // oldest-first eviction then pushed the parent conversation out after `slots` turns. An entry without + // checkpoints, or whose deepest checkpoint the outgoing chain does not hold (another conversation that only + // shares the system prompt's root with it), is kept. Returns how many were dropped. + size_t drop_superseded(const std::vector& ids, const std::vector& images, + const std::vector& checkpoints, bool cvec) { + auto held = [&](const ConversationCheckpoint& c) { + if (c.ids == ids && c.imgs == images) return true; + for (const auto& k : checkpoints) + if (k.ids == c.ids && k.imgs == c.imgs) return true; + return false; + }; + size_t dropped = 0; + for (size_t i = 0; i < entries_.size();) { + const auto& e = entries_[i]; + const ConversationCheckpoint* deepest = nullptr; + for (const auto& c : e.checkpoints) + if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c; + if (e.cvec == cvec && deepest && !deepest->ids.empty() && held(*deepest)) { + bytes_ -= e.bytes(); + entries_.erase(entries_.begin() + (std::ptrdiff_t) i); + ++dropped; + continue; + } + ++i; + } + superseded_ += dropped; + return dropped; + } + size_t superseded() const { return superseded_; } + + bool put(SavedConversation&& image, size_t held = 0) { + const size_t n = image.bytes(); + if (!enabled() || held > budget_ || n > budget_ - held) return false; // make_room's refusal, first + drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec); + if (!make_room(n, held)) return false; + entries_.push_back(std::move(image)); + bytes_ += n; + return true; + } + +private: + size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0, superseded_ = 0; + std::deque entries_; // least recently active first + ConversationKvReuse reuse_; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/conversation_memory.hpp b/engine/strata/include/strata/core/conversation_memory.hpp new file mode 100644 index 00000000..0e908b40 --- /dev/null +++ b/engine/strata/include/strata/core/conversation_memory.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +namespace strata::core { + +// Host physical memory, not swap/commit or a container/job memory reservation. +// Unknown telemetry is deliberately distinct from a measured zero. +std::optional conversation_available_memory(); +std::optional conversation_mem_available(std::istream& meminfo); + +inline bool conversation_memory_admit(std::optional available, + uint64_t allocation, uint64_t floor) { + return available && *available >= floor && allocation <= *available - floor; +} + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/conversation_snapshot.hpp b/engine/strata/include/strata/core/conversation_snapshot.hpp new file mode 100644 index 00000000..a840bf2e --- /dev/null +++ b/engine/strata/include/strata/core/conversation_snapshot.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include "strata/core/conversation_cache.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/session.hpp" + +#include + +namespace strata::core { + +// Caller synchronizes the device before saving, and after restoring all layers. +// include_index is false for the draft layer (its attention has no indexer). +size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index); +// A nonzero unchanged_tokens is valid only for storage retained from an image +// actually restored into this session, bounded by every subsequent rewrite. +// Equal token IDs alone do not establish that its K/V bytes are unchanged. +bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error, + int64_t unchanged_tokens = 0, size_t* reused_bytes = nullptr); +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, size_t& bytes, std::string& error); +// No CUDA calls or destination writes. Used for whole-session prevalidation. +bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); +bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, std::string& error); +// Diagnostic read-back after a synchronized restore. Uses 64 KiB of stack +// workspace, compares authoritative bytes and resident draft-ring pages, and +// fingerprints the authoritative payload only. Never changes model state. +bool conversation_kv_verify(const ConversationKv& image, const QsaState& state, const ModelGeometry& g, + int64_t upto, bool include_index, uint64_t& fingerprint, std::string& error); + +struct ConversationStateSizes { + size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0; +}; +/// Whole-model sizes: `gdn` covers every GDN layer, the indexer sizes are per QSA layer. +bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& sizes, std::string& error); +/// The same for one session's layer carve (#216): `gdn` covers its `gdn_alloc` rows; the per-QSA-layer sizes +/// apply to each owned state [qsa_ord0, qsa_ord0 + qsa_alloc). Rejects an inconsistent carve. Checkpoints, +/// snapshots and their validation all use this: a session saves and restores only the state it owns. +bool conversation_session_sizes(const ModelGeometry& g, const SessionState& session, ConversationStateSizes& sizes, + std::string& error); +bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const SessionState& session, + const ModelGeometry& g, std::string& error); +bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session, + const ModelGeometry& g, std::string& error); +bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, + const ModelGeometry& g, std::string& error); + +struct ConversationView { + const std::vector& ids; + const std::vector& images; + const std::vector& checkpoints; + bool cvec; +}; +bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session, + const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error); +bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, + const SessionState& session, const ModelGeometry& g, + const QsaState& draft, size_t& bytes, std::string& error); +// The capture estimate includes retained capacity and transient segment directories; +// only estimate - reuse.bytes() requires additional physical RAM. Capture consumes +// the uniquely owned reusable buffers, including on failure. +// Caller admits the estimate before invoking capture. Allocation failures propagate +// to the RAM policy; the active session is never modified by capture. +bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, + const SessionState& session, const ModelGeometry& g, + const QsaState& draft, std::string& error, + ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); +bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, + const ModelGeometry& g, const QsaState& draft, std::string& error); +enum class ConversationRestore { restored, invalid, transfer_failed }; +// Invalid images are rejected before any CUDA call/write. Transfer failure may +// leave partial state: caller MUST NOT continue inference from that session. +ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, + const ModelGeometry& g, const QsaState& draft, + std::string& error); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/coupled_draft.hpp b/engine/strata/include/strata/core/coupled_draft.hpp new file mode 100644 index 00000000..d095e3a0 --- /dev/null +++ b/engine/strata/include/strata/core/coupled_draft.hpp @@ -0,0 +1,90 @@ +// include/strata/core/coupled_draft.hpp - COUPLED DRAFT SAMPLING (STRATA_SPEC_COUPLED=1, off by default). +// +// Under sampling the verify window samples row t of a window at position pos0 as Philox(seed, pos0 + t) over the +// sampler chain (penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick; verify.cpp run(), +// sampler.cu), and a draft is kept only when it EQUALS that row's pick. The output is therefore a function of the +// seed alone, whatever the drafts are: drafts only decide how many tokens a window yields. +// +// The MTP draft layer used to propose its ARGMAX. In coupled mode it SAMPLES instead, with the target's own chain +// (the request's top_k / top_p / min_p / temperature and penalties over the same history) and the SAME uniform the +// target will draw for the row that verifies the draft. When the draft's distribution is close to the target's, +// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's +// pick - and so the text - does not change, because verification is still exact-match against the target's sample. +// +// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its +// pick is the token at pos0 + t + 1, drawn with counter pos0 + t): +// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at +// c + 2 (mtp.hpp). +// * After a window at p with a drafts accepted, the next window starts at p' = p + a + 1 (its row 0 is the token +// the window picked at row a). Chain step j (j = 0 ..) runs at cell p + a + j and predicts the token at +// p + a + j + 2 = p' + j + 1: row j + 1 of the next window, VERIFIED BY ROW j's pick, counter p' + j. +// * So a draft made at cell c is verified with counter c + 1 - whatever the window size T, the accepted count, a +// suffix-drafter window in between (its drafts are then simply not used), or `draft_first` (cell p - 1, a = 0 for +// a window at p). The kernel reads c from the step record the host already stages for the cell (device memory, +// so the captured graphs replay with each round's own counter), and the seed and chain from a device copy of the +// request's SamplerParams, refreshed at the start of every round graph. +// +// THE PENALTY HISTORY. The verify row j of the next window counts penalties over penalty_rows(consumed', window') +// row j: the last h of (consumed', x', drafts 0 .. j-1), where consumed' is what the session holds after the commit +// and x' the window's pick at row a. The drafter keeps a device RING of kCoupledHistCap + max_t slots: the host +// stages the base (the last h of consumed' + x', -1 padded in front) in [cap - h, cap) before the round, and draft j +// writes its token to cap + j - so draft j's window is [cap + j - h, cap + j), exactly the row the target will use. +#pragma once + +#include "strata/kernels/sampler.hpp" + +#include +#include +#include +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_COUPLED_HD __host__ __device__ +#else +#define STRATA_COUPLED_HD +#endif + +namespace strata::core { + +/// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap). +inline constexpr int kCoupledHistCap = 4096; + +inline bool& coupled_draft_state() { + static bool on = [] { + const char* e = std::getenv("STRATA_SPEC_COUPLED"); + return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; + }(); + return on; +} + +/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag). +inline bool coupled_draft_env() { + return coupled_draft_state(); +} + +inline void set_coupled_draft(bool on) { + coupled_draft_state() = on; +} + +/// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there). +STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; } + +/// The Philox counter the verify window will draw for the row that checks the draft made at MTP cell `cell`. +STRATA_COUPLED_HD inline uint64_t coupled_draft_counter(int64_t cell) { return (uint64_t) (cell + 1); } + +/// The penalty window the draft layer and the target use: min(penalty_last_n, cap), 0 when penalties are off. +STRATA_COUPLED_HD inline int coupled_hist_len(int penalty_last_n, int cap) { + return penalty_last_n <= 0 ? 0 : (penalty_last_n < cap ? penalty_last_n : cap); +} + +/// Where draft j's penalty window starts in the ring (base in [cap - h, cap), draft i at cap + i). +STRATA_COUPLED_HD inline int coupled_hist_start(int cap, int j, int h) { return cap + j - h; } + +/// The ring's base on the host: the last `h` tokens of (tail[0..n_tail), next), -1 padded in front, into +/// out[0..h) - row 0 of `penalty_rows` for the one-token window [next]. +inline void coupled_hist_base(const int32_t* tail, int64_t n_tail, int32_t next, int h, int32_t* out) { + if (h <= 0) return; + strata::kernels::penalty_rows(tail, n_tail, &next, 1, h, out); +} + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/device.hpp b/engine/strata/include/strata/core/device.hpp new file mode 100644 index 00000000..091dff1c --- /dev/null +++ b/engine/strata/include/strata/core/device.hpp @@ -0,0 +1,95 @@ +// include/strata/core/device.hpp - P2.S1: the device arena and the runtime's device facts. +// +// `DeviceArena` is ONE cudaMalloc per planner region with bump sub-allocation below it and no frees. That is +// not a simplification for the first version: the memory plan from P1.S9 is fixed at startup, so the set of +// regions and their sizes is known before anything is allocated, and an allocator that can free would be +// solving a problem the engine does not have while adding fragmentation and failure modes it does. +// +// The reason to get this in early is that the VRAM budget is the binding constraint of the whole design +// (5.95 GB pooled between KV and the expert cache, 33.97 GB of experts in DRAM). A runtime that discovers at +// token 4000 that it has overcommitted has already lost; the plan is printed against `cudaMemGetInfo` at +// startup so the discrepancy is visible immediately. +#pragma once + +#include +#include +#include +#include + +namespace strata::core { + +struct DeviceInfo { + int ordinal = -1; + std::string name; + int cc_major = 0, cc_minor = 0; + uint64_t total_bytes = 0; // as reported by cudaMemGetInfo at query time + uint64_t free_bytes = 0; + int driver_version = 0, runtime_version = 0; + int multi_processor_count = 0; + std::string arch; // HIP: gcnArchName without its feature suffix ("gfx1201"); empty on CUDA +}; + +// HIP builds: whether GPU `ordinal` can run this binary - its architecture must be one the binary was COMPILED +// for (STRATA_HIP_ARCHS, set by cmake/hip_backend.cmake) and it must run wave32. "" when it can (or when there +// is no such device: the caller's own device errors apply), else the reason in a sentence. A binary carried to +// another card would otherwise fail later with "invalid device function". CUDA builds: always "". +std::string gpu_arch_problem(int ordinal); + +// The GPU architectures this binary was compiled for ("gfx1100,gfx1201"); "" on CUDA builds. +const char* compiled_gpu_archs(); + +// How many devices the runtime enumerates, numbered as HIP_VISIBLE_DEVICES / CUDA_VISIBLE_DEVICES number them; 0 when +// there is none (or no usable runtime). `device_info` throws on a card this binary cannot run, so a caller that LISTS +// every card - the ones it has no code for included (`strata-device --list-devices`) - counts them with this first. +int device_count(); + +// One line per device for `strata-device --list-devices`, without the arch check that `device_info` applies: +// "arch gfx1201, 15.9 GiB" (HIP) or "compute capability 12.0, 11.9 GiB" (CUDA), plus the device's name. false when +// the runtime cannot describe it. +bool device_summary(int ordinal, std::string& name, std::string& detail); + +// Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than +// run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and +// this is the matching check at run time (a binary can be carried to a different machine). +DeviceInfo device_info(int ordinal = 0); + +/// "" when this build has device code for the current device, else CUDA's error: a build for other GPUs would +/// otherwise fail at its first kernel launch, with nothing that names the cause. +std::string device_code_error(); + +class CudaError : public std::runtime_error { +public: + CudaError(const std::string& what, int code) : std::runtime_error(what), code_(code) {} + int code() const { return code_; } + +private: + int code_; +}; + +// One cudaMalloc, bump-allocated below. `poison` fills new allocations with a NaN-ish pattern in a debug +// build so that reading uninitialised VRAM gives a NaN rather than a plausible number - the same reasoning as +// the harness work in Phase 1: a wrong value that looks right is the expensive kind. +class DeviceArena { +public: + explicit DeviceArena(uint64_t bytes, int ordinal = 0, bool poison = false); + ~DeviceArena(); + DeviceArena(const DeviceArena&) = delete; + DeviceArena& operator=(const DeviceArena&) = delete; + + // `align` must be a power of two; 256 keeps every sub-allocation at a sector boundary. + void* alloc(uint64_t bytes, uint64_t align = 256); + + uint64_t capacity() const { return capacity_; } + uint64_t used() const { return used_; } + uint64_t peak() const { return used_; } // no frees, so used IS the peak + int ordinal() const { return ordinal_; } + void* base() const { return base_; } + +private: + void* base_ = nullptr; + uint64_t capacity_ = 0, used_ = 0; + int ordinal_ = 0; + bool poison_ = false; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/emulate.hpp b/engine/strata/include/strata/core/emulate.hpp new file mode 100644 index 00000000..6f28b97f --- /dev/null +++ b/engine/strata/include/strata/core/emulate.hpp @@ -0,0 +1,36 @@ +// strata/core/emulate.hpp - STRATA_EMULATE_CC: another GPU generation's code paths, run on this card (tests only). +// +// A build whose device code is PTX for an older architecture (CMAKE_CUDA_ARCHITECTURES=86-virtual) runs on a newer +// card through the driver's JIT, and every kernel then sees __CUDA_ARCH__ = 860. What the host decides from the +// device must agree with that, or it picks paths and shared-memory sizes the device code was not built for: +// STRATA_EMULATE_CC=75|80|86|89 makes each such query (compute capability, shared memory per block) answer as that +// card would. Speed under it says nothing about the real card; results do - the kernels are the real card's. +#pragma once + +#include + +namespace strata { + +/// the emulated compute capability as 10 * major + minor, or 0 (off) +inline int emulated_cc() { + static const int cc = [] { + const char* e = std::getenv("STRATA_EMULATE_CC"); + const int v = e ? std::atoi(e) : 0; + return v >= 75 && v < 120 ? v : 0; + }(); + return cc; +} +inline int cc_major_of(int real_major) { return emulated_cc() ? emulated_cc() / 10 : real_major; } +inline int cc_minor_of(int real_minor) { return emulated_cc() ? emulated_cc() % 10 : real_minor; } +/// cudaDevAttrMaxSharedMemoryPerBlockOptin as the emulated card reports it: 64 KB on Turing, 163 KB on the A100, +/// 99 KB on the other Ampere and Ada cards +inline int smem_optin_of(int real) { + switch (emulated_cc()) { + case 0: return real; + case 75: return 65536; + case 80: return 166912; + default: return real < 101376 ? real : 101376; + } +} + +} // namespace strata diff --git a/engine/strata/include/strata/core/expert_cache.hpp b/engine/strata/include/strata/core/expert_cache.hpp new file mode 100644 index 00000000..bf3b5831 --- /dev/null +++ b/engine/strata/include/strata/core/expert_cache.hpp @@ -0,0 +1,165 @@ +// include/strata/core/expert_cache.hpp - R4: the VRAM-resident expert tier. +// +// **WHY THIS EXISTS, IN ONE PARAGRAPH.** The CPU expert pool is the engine's largest single cost: measured, +// **663.6 MB of expert bytes per token at ~40 GB/s = 16.2 ms**, on a token of ~53 ms, and `test_expert_pool` +// says the pipeline hides **1.055 ms of 19.035** - the CPU work is 96% exposed because the residual chain is +// strictly serial. The only way past it is to stop reading those bytes: put some of the 48 x 512 experts in +// VRAM and let the GPU compute them, so the CPU reads only the misses. +// +// **THE DESIGN IS SIZED AGAINST MEASUREMENTS, NOT AGAINST THE PLAN'S ASSUMPTIONS.** +// +// * `h_expert` at 4,105 slots, **ten-fold leave-one-out: 0.6447 [0.6110, 0.6750]** (`tools/routing_kfold.py`). +// The 0.6573 the README published is in-sample and 0.4720 measured a single-prompt CORPUS, not the metric. +// * VRAM, measured on a live run rather than at startup: **6414 MiB free** with the engine at steady state, +// against **5413 MiB** for 4,105 slots. It fits, with ~1 GB spare. `strata-device`'s planner agrees and says +// FITS, but the planner runs before the dense arena exists, so the live figure is the one that counts. +// * `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so +// this cannot be a per-layer grouped kernel and the three-way split is not an optimisation. +// +// **WHAT THIS FILE IS AND IS NOT, TODAY.** It is the SLOT STORAGE and the RESIDENCY TABLE: it allocates the +// VRAM, fills it from the host arena, and answers `(layer, expert) -> slot or -1`. It does **not** yet compute +// anything - `moe_hit_grouped_s2` does not exist and the hit/miss split is not wired into the graph - so with +// the cache on and nothing consuming it, **the engine is slower by the fill cost and faster by nothing.** +// That is stated here rather than discovered from a benchmark, and it is why `--expert-cache` defaults to 0. +// +// The order of work is `Memory/R4-design-note.md` §7: slots and residency first, then the split, then the +// kernel. This is that first step, and the step it unblocks is the one that can be measured. +#pragma once + +#include +#include +#include +#include + +namespace strata::core { + +/// Where one expert's VRAM lives, or -1. `int32_t` and not a bool because the slot index is what the kernel +/// needs, and a table that has to be re-derived from a bitmask is a table that will be re-derived differently +/// in the two places that use it. +inline constexpr int32_t kNotResident = -1; + +/// **THE STATIC RESIDENCY PLAN, READ BACK FROM THE FILE `tools/make_profile.py` WROTE.** +/// +/// `profile.bin` is `STRP`, then `version, n_layers, n_expert, slots, n_ranked`, then `n_ranked` `(layer, +/// expert)` pairs ranked by descending routing frequency, then a `n_layers x n_expert` frequency table. +/// +/// **WHY A PROFILE AND NOT THE COMPULSORY-MISS POLICY THIS ENGINE ALREADY HAD.** Compulsory-miss fills with +/// the first `S` DISTINCT experts the run happens to route, which on this workload is whatever the prompt +/// touched first - it measured `h = 0.4864`. A profile ranked by frequency over a whole trace is what the +/// plan's `0.6447` refers to, and the CPU's half of the drain is linear in `h`, so the gap is worth about +/// 4 ms of drain. The point of reading it from a file is that a profile built on ONE prompt can be scored on +/// ANOTHER, which is the only way to know whether it transfers. +/// +/// The frequency table is not returned: it is the profile's own working, and the engine measures `h` by +/// running rather than by re-deriving what the file claims. +bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, + std::vector>& ranked, int64_t& slots, std::string& err); + +class ExpertCache { +public: + ExpertCache() = default; + ~ExpertCache(); + ExpertCache(const ExpertCache&) = delete; + ExpertCache& operator=(const ExpertCache&) = delete; + + /// Allocates `n_slots * blob_bytes` of DEVICE memory and a `n_layers * n_expert` residency table, and + /// **CHECKS THE ALLOCATION AGAINST WHAT THE CARD ACTUALLY HAS** rather than assuming the planner was right. + /// A cache that silently allocates less than it was asked for would report a hit rate for slots it does + /// not have, which is the shape of error this project keeps paying for. + bool open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes, std::string& err); + /// Plan v0.3 P6: slots of the given sizes, back to back (a native pack's blobs differ per layer, and a + /// profile-filled tier never moves an expert to another layer's slot, so each slot keeps its first size). + bool open_sized(const std::vector& slot_bytes, int64_t n_layers, int64_t n_expert, std::string& err); + /// Byte offset of each slot in the arena (null for uniform slots). + const uint64_t* slot_offsets() const { return off_.empty() ? nullptr : off_.data(); } + void close(); + + bool valid() const { return base_ != nullptr; } + int64_t slots() const { return slots_; } + /// Slots actually claimed. Not the same as `slots()` - the cache does not evict, so a run that routes + /// fewer distinct experts than there are slots leaves the rest empty. + int64_t resident() const { return per_layer_ ? admitted_ : next_free_; } + int64_t bytes() const { return off_.empty() ? slots_ * blob_ : (int64_t) off_.back(); } + double gib() const { return (double) bytes() / 1073741824.0; } + + /// `(layer, expert)` -> slot index, or `kNotResident`. Bounds-checked: a bad layer or expert returns + /// `kNotResident` rather than reading whatever is adjacent in the table. + int32_t slot_of(int64_t layer, int64_t expert) const; + /// Claims the next free slot for `(layer, expert)`. Returns the slot, or `kNotResident` when the cache is + /// full - **it never evicts**, because eviction policy is a measured question (`R4.1`'s LFU-decay vs LRU + /// sweep) and a placeholder policy would set the hit rate that everything downstream is then sized against. + int32_t admit(int64_t layer, int64_t expert); + + /// **R4.2g: GIVE EACH LAYER ITS OWN SLOTS. ROUND 328 MEASURED WHY THE GLOBAL FORM CANNOT WORK.** + /// + /// `admit`'s original policy hands out slots in ARRIVAL ORDER from one counter shared by every layer + /// (`if (next_free_ >= slots_) return kNotResident;`). A position looks at 10 experts in each of 48 + /// layers, so the first `n_slots` distinct (layer, expert) pairs are **about 26 layers of POSITION 0** - + /// the cache fills entirely inside the first position it ever sees and never changes again, so hits are + /// confined to those few layers for the rest of the run. + /// + /// Measured, `--expert-cache 256`: **1781 of 60000 = 2.97%**. `Memory/cache_allocation.py` scores the + /// same run's routing and says **8 slots per layer is worth 21.4%** and 64 is worth **70.4%**. The cache + /// was never short of capacity - it was handing all of it to two layers. + /// + /// With this on, layer `l` may only use slots `[l*q, (l+1)*q)` where `q = slots()/n_layers`, the last + /// layer taking the remainder. **EVICTION IS STILL ABSENT** - the property the comment above calls + /// deliberate is preserved exactly; only WHICH slot a layer may take changes. Default off, so every + /// caller that predates this flag is bit-for-bit unaffected. + void set_per_layer_admission(bool on) { per_layer_ = on; } + bool per_layer_admission() const { return per_layer_; } + /// The slot range layer `l` may admit into under per-layer admission. Exposed so a test can check it. + void layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const; + + /// The device address of one slot. + uint8_t* device_slot(int32_t slot); + const uint8_t* device_slot(int32_t slot) const; + + /// Copies `(layer, expert)`'s blob from `host_blob` into `slot` on `stream`. Asynchronous: the caller + /// orders it. Returns false if the indices are out of range rather than reading past the arena. + /// `bytes` (plan v0.3 P6): the blob's own size when it is smaller than the slot (a native pack); 0 = the slot. + bool fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes = 0); + + /// **THE SAME COPY, BUT BLOCKING, AND THE PROFILE FILL NEEDS IT.** `fill_slot` is asynchronous because on + /// the token path the fill and the kernel that reads it are ordered by one stream and waiting would be a + /// synchronisation per layer. At STARTUP there is no such ordering to lean on: the source is pageable host + /// memory, `verify_slot` reads the slot back on the LEGACY stream, and a legacy-stream copy is not ordered + /// against a `cudaStreamNonBlocking` one. The first version used the async form and `verify_slot` refused + /// the whole run with "slot 0 differs from the arena at byte 0" - which is the check doing its job. + bool fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); + /// perf-review D-4: `fill_slot_blocking`'s copy on the same (legacy) stream, but queued: many slots are refilled + /// with one `sync_queued` at the end instead of a wait per slot. Same ordering against earlier work, same bytes. + bool fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); + bool sync_queued(std::string& err); + + /// Reads `slot` back to the host and compares it to `host_blob`, byte for byte. **THE ONLY THING THAT SAYS + /// THE CACHE HOLDS THE EXPERT IT CLAIMS TO.** A slot table that is right about indices and wrong about + /// bytes produces a plausible token, which is exactly the failure this project has paid for most often. + bool verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes = 0); + + /// Slots filled so far, for the startup report. + int64_t fills() const { return fills_; } + +private: +#if defined(STRATA_USE_HIP) + bool ensure_blocking_staging(std::size_t bytes, std::string& err); + uint8_t* blocking_staging_ = nullptr; + std::size_t blocking_staging_bytes_ = 0; +#endif + uint8_t* base_ = nullptr; + std::vector residency_; ///< [n_layers * n_expert] -> slot or kNotResident + int64_t slots_ = 0; + int64_t n_layers_ = 0; + int64_t n_expert_ = 0; + int64_t blob_ = 0; + int64_t next_free_ = 0; + int64_t fills_ = 0; + /// R4.2g. `per_layer_` off (the default) leaves `next_free_` as the only admission counter, so the + /// pre-existing path is untouched. + bool per_layer_ = false; + std::vector layer_next_; ///< [n_layers] -> that layer's next free slot + std::vector off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized + int64_t admitted_ = 0; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/expert_source.hpp b/engine/strata/include/strata/core/expert_source.hpp new file mode 100644 index 00000000..e2669ebe --- /dev/null +++ b/engine/strata/include/strata/core/expert_source.hpp @@ -0,0 +1,660 @@ +// include/strata/core/expert_source.hpp - P2.S3/P2.S5: the expert pool's adapter to the host loop. +// +// `session_loop` publishes, per layer, the NORMED activation `x_f`, the ten routed expert ids and their router +// weights, and expects `k x n_embd` floats back. This is the piece that turns those four things into an +// `ExpertPool::run` call. Nothing here is clever, and that is the point: the pool, the kernel and the loop are +// each already verified, so this file has exactly one job - get the CONTRACT between them right. +// +// THE CONTRACT, and each clause is a way to be wrong: +// +// 1. **`x_f` IS THE SAME PINNED BUFFER EVERY LAYER.** Its ADDRESS never changes, so the `ActQ` cannot be +// cached by pointer - a cache keyed on `x_f` would quantize layer 0 and reuse it for all 47 remaining +// layers, which is a finite, plausible, completely wrong token. There is no cache here at all: the +// conversion is one 2560-element pass against a 0.3 ms/layer budget, and a correct answer is worth more +// than the microseconds. +// 2. **THE POOL DOES NOT APPLY THE ROUTER WEIGHT.** `moe_combine` (`src/core/layer.cpp:479`) sums +// `w[i] * parts[i]` on the device. `ExpertJob::weight` is a diagnostic field; setting it here would +// apply the weight twice, which is invisible in a single layer and compounds over 48. +// 3. **THE KERNEL'S GEOMETRY IS FIXED BY THE ARTIFACT** (`H = 2560`, `FF = 640`, `BLOB = 1,382,400`). A +// different `n_embd` or a different expert width is REFUSED rather than mis-indexed, because the blob's +// internal offsets are compile-time constants and reading a 640-wide expert as a 2560-wide one walks off +// the end into the next expert's bytes without faulting. +#pragma once + +#include "strata/core/expert_cache.hpp" +#include "strata/core/hit_hook.hpp" +#include "strata/kernels/cpu/pool.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels::cpu { +struct ExpertLayout; +} + +namespace strata::core { + +class RemoteExperts; +struct LoadStats; + +namespace detail { + +/// Sentinel used by the pure complement planner for a blob that remains in the mmap fallback. +inline constexpr uint64_t kNoCacheComplement = ~uint64_t{0}; + +/// Required cgroup-v2 usage counters for the conservative cache-reclaim allowance. +struct CgroupMemoryStat { + uint64_t current = 0; + uint64_t inactive_file = 0; + uint64_t file_dirty = 0; + uint64_t file_writeback = 0; + bool valid = false; +}; + +/// Calculate additional bytes under a finite cgroup limit after reclaiming only clean inactive file cache. +/// Returns false when the required memory.stat counters were unavailable. +bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes); + +/// Build compact offsets for experts absent from both the primary GPU cache and an optional second GPU tier. +/// Kept CPU-only so selection and byte accounting can be tested without initializing a GPU. +bool make_cache_complement_plan( + int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, + const std::vector>& primary_gpu_pairs, + const std::vector>& additional_gpu_pairs, + std::vector& offsets, uint64_t& bytes, std::string& err); + +/// Resolve one blob through the compact copy when present, otherwise preserve its exact mapped-file fallback. +const uint8_t* cache_complement_blob_or_fallback( + size_t index, const std::vector& offsets, const uint8_t* complement_host, + const uint8_t* mapped_fallback); + +/// The resident RAM mode: which GPU-cache slots' experts are kept in RAM too. The prompt path lends the cache's +/// LAST slots (from `lend_from` on; a short prompt lends only the last few), and a lent slot's expert is streamed +/// from RAM during the prompt and copied back into its slot after it. `base_bytes` (every expert no slot holds) +/// must fit `budget`; slots are then added from the end down to `lend_from` while they still fit. Returns the +/// first slot kept in RAM (`slot_bytes.size()` = none), or -1 when `base_bytes` alone exceeds `budget`. +int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, + int64_t lend_from); + +/// The adaptive tier swapped `in` into a GPU slot and `out` out of it: `out` takes `in`'s place in the compact copy +/// (the caller copies out's bytes there). False, and nothing changed, unless `in` is in the copy and `out` is not. +bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out); + +} // namespace detail + + + +/// Where one routed expert's bytes come from. +/// +/// Phase 2 has NO cache (`phase-2-correct-engine.md`: hit rate `h = 0`), so the only implementation is a +/// file-backed reader. The interface exists anyway because Phase 3 replaces exactly this object with the VRAM +/// cache, and because a test can supply an in-memory source without a 34 GB artifact. +class ExpertSource { +public: + virtual ~ExpertSource() = default; + + /// The expert-layout blob for `(layer, expert)`, or nullptr if it cannot be produced. + /// + /// The pointer only has to stay valid until the next `blob()` call: with `h = 0` every expert is computed + /// immediately and nothing is retained. A CACHING source must return pointers into the cache, not into a + /// reused staging buffer - otherwise the pool would read the next expert's bytes while computing this one. + virtual const uint8_t* blob(int64_t layer, int64_t expert) = 0; + + /// Blobs touched, for the driver to report. A source that does not count returns 0. + virtual int64_t reads() const { return 0; } + + /// Plan v0.3 P5: whether `blob(layer, expert)` lies in page-locked, CUDA-registered memory, so an + /// asynchronous host-to-device copy can DMA it directly (no staging copy on the CPU). + virtual bool pinned(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; } + + /// Called once before the first expert of a layer. A source that reads from disk wants to start the read + /// here so it overlaps the quantisation, and a prefetching source in Phase 3 wants the ids. + virtual void begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) layer; (void) ids; (void) k; } + /// Plan v0.3 P6: the DEVICE address of a pinned, mapped blob (the GPU can read it over PCIe), or null. + virtual const uint8_t* device_alias(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return nullptr; } + /// Whether the verify window may give the GPU a PCIe share of this layer's misses at all (each expert is still + /// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact + /// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy. + virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; } + + /// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its + /// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer + /// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the + /// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead. + virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; } + /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose + /// `transient` can be true. + virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst); + /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may + /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. + virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their + /// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing. + virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// Whether `warm` does anything (the predictor is not run otherwise). + virtual bool warms() const { return false; } +}; + +/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer +/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the +/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the +/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages: +/// it never changes which experts are computed or how. +class RouterLookahead { +public: + RouterLookahead() = default; + ~RouterLookahead(); + RouterLookahead(const RouterLookahead&) = delete; + RouterLookahead& operator=(const RouterLookahead&) = delete; + /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd. + bool start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src, + std::string& err); + /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a + /// prediction still running for an earlier layer makes this one skip. + void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res); + int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); } + int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); } + double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; } + +private: + void run(); + std::vector> routers_; + int64_t n_embd_ = 0, n_expert_ = 0; + int k_ = 10; + ExpertSource* src_ = nullptr; + std::thread thread_; + std::mutex mu_; + std::condition_variable cv_; + bool quit_ = false, pending_ = false, busy_ = false; + int64_t layer_ = -1, n_tok_ = 0; + const int32_t* host_res_ = nullptr; + std::vector x_; + std::atomic predicted_{0}, skipped_{0}; + std::atomic busy_us_{0}; +}; + +/// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right +/// after the ring and published before the CPU starts its own share. Groups of entries that share a blob; the +/// blob is a VRAM slot or a pinned host blob read over PCIe. +struct GpuPlanSink { + int32_t* counts = nullptr; ///< [0] groups, [1] entries + int32_t* start = nullptr; ///< cap + 1 + int32_t* dst = nullptr; ///< cap: the entry's row of parts (token * k + j) + int32_t* tok = nullptr; ///< cap: the entry's token + unsigned long long* ptr = nullptr; ///< cap: the group's blob, device address + /// Plan v0.3 P6 (DMA): the PCIe share is a second list of groups - `ptr2[q]` is staging slot q, `start2` indexes + /// the same dst/tok entries - computed by the GPU after `fetch` has copied their blobs into staging with the + /// copy engine. counts[0] = VRAM groups, counts[1] = all entries, counts[2] = PCIe groups. + unsigned long long* ptr2 = nullptr; + int32_t* start2 = nullptr; + unsigned long long staging = 0; + int64_t staging_cap = 0; + int64_t cap = 0; + void (*publish)(void* ctx) = nullptr; + /// Starts the DMA copies of `n` host blobs (pinned) into staging slots 0..n-1 and signals the GPU when they land. + void (*fetch)(void* ctx, const uint8_t* const* src, int n, size_t bytes) = nullptr; + void* ctx = nullptr; + /// Plan v0.3 P6: how a PCIe group reaches the GPU. 0 = the copy engine stages it (DMA, `fetch`); 1 = the grouped + /// kernel reads the mapped arena directly; 2 = a copy kernel stages it inside the graph. For 1 and 2 `ptr2` + /// holds the arena's device alias. + int pcie_mode = 0; +}; + +/// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). +struct ExpertDispatch { + // Default-off local extension. The callback owns only kind==-1 entries and + // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched. + using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*, + int64_t, int64_t, int32_t*, float*, std::string&); + ExperimentalMiss experimental_miss = nullptr; + void* experimental_miss_user = nullptr; + strata::kernels::cpu::ExpertPool* pool = nullptr; + ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts + RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows + int remote_count = 0; + int64_t n_expert = strata::kernels::cpu::NE; + + /// Counters, for the driver to report rather than for control flow. + int64_t layers = 0; + int64_t experts = 0; + int64_t missing = 0; + + // ================================ R4: THE VRAM TIER, MEASURED BEFORE IT IS USED ================================ + // + // **THE CACHE IS CONSULTED AND FILLED HERE, AND NOTHING IS COMPUTED FROM IT YET.** That is deliberate and + // it is `R4-design-note.md` §7 step 2: the *dispatch* is measured on its own before any kernel is written, + // because a hit rate measured after the kernel exists cannot say whether a disappointing result was the + // policy, the split or the kernel. + // + // So every expert is still computed by the CPU, exactly as before, and the run is numerically identical + // with the cache on or off. What changes is that the engine now reports **h on its own routing, on a real + // workload** - which is the number `R4.1` asks for and which until now existed only from offline traces. + // + // The policy is compulsory-miss: the first time `(layer, expert)` is routed, if a slot is free it is + // admitted and filled from the arena. No eviction, because eviction policy is the measured question + // (`R4.1`'s LFU-decay vs LRU sweep) and a placeholder would set the hit rate everything is sized against. + ExpertCache* cache = nullptr; + int64_t cache_hits = 0; ///< lookups already resident + int64_t cache_admitted = 0; ///< lookups that took a slot + int64_t cache_refused = 0; ///< lookups with no slot free (the cache is full) + void* cache_stream = nullptr; + const char* cache_fail = nullptr; + + // ================================ R4.2c: THE HITS GO TO THE GPU ================================ + // + // **THE SPLIT IS BY ROUTER INDEX, AND THAT IS THE WHOLE TRICK.** A layer routes ten experts; the resident + // ones are computed on the GPU and the rest on the CPU, and both answers have to end up in `parts` at the + // index the ROUTER gave them, because that is the order `moe_combine` weights against. So the CPU's `out` + // rows are zeroed for the hits, and each hit carries its routed index to the kernel as `dst`. + // + // Everything below is per-session state rather than per-call, so the token path allocates nothing (P2.T10). + const uint8_t* cache_base = nullptr; ///< the slot arena on the DEVICE + int64_t cache_blob = 0; ///< bytes per slot + const uint64_t* cache_slot_off = nullptr; ///< plan v0.3 P6: per-slot offsets when the slots differ in size + void* hit_scratch = nullptr; ///< `moe_hit_grouped_scratch_bytes(K, ...)` + float* parts_out = nullptr; ///< the graph's `parts` buffer, on the device + /// Where the GPU's hits land, `K x n_embd`, DEVICE and separate from `parts_out` on purpose: see + /// `HitPhase`. Zeroed by the hit path each layer before the kernel writes it. + float* hit_out = nullptr; + int64_t parts_elems = 0; ///< `K * n_embd`, the length of both buffers + const float* mixed = nullptr; ///< the layer's normed activation, for the hit kernel's Q8_0 + uint8_t* x_q8_0_hit = nullptr; ///< `(n_embd/32) * 34` bytes, its own buffer + /// **R4.2h: THE CPU's fp32 ACTIVATION SCALES, `(n_embd/32)` FLOATS.** Without them the GPU's hits are + /// computed with the `block_q8_0`'s fp16 `d` while the CPU's misses use the fp32 `ActQ::scale` + /// (`cpu/expert.cpp:92`) - **4.761e-04 relative on 80 of 80 chunks**, measured with both real + /// implementations linked in `bench/micro/act_quant_parity.cu`. That disagreement is why turning the + /// cache on changed the generated tokens. Required whenever the hit path runs. + float* x_q8_0_hit_scale = nullptr; + int32_t* d_slot = nullptr; ///< device, K entries + int32_t* d_dst = nullptr; ///< device, K entries + std::vector h_slot, h_dst; ///< host staging, sized at session setup + /// **PER ROUTER INDEX, DECIDED IN `Launch` AND CONSUMED BY THE POOL.** The two callbacks share it + /// so the decision is made exactly once, on this layer's ids, and neither side can re-decide it. + std::vector is_hit; + bool decided = false; + /// Plan v0.3 P4 token graph: the STATIC residency table (`n_layers x n_expert`, slot or -1), the host's copy + /// of what the device hit path reads. When set, the pool leaves a resident expert's row at zero (the GPU + /// computes it) without any `Launch` callback. + const int32_t* host_res = nullptr; + /// Plan v0.3 P4: split every expert by rows across the pool's threads (default on; A/B `--no-split-rows`). + bool split_rows = true; + + // ================================ R4.2d: DID THE GPU ACTUALLY START? ================================ + // + // **THE HIT PATH IS 0.91 ms SLOWER AND THE ONLY EXPLANATION LEFT IS THAT IT NEVER OVERLAPS.** The kernel + // is 159 GB/s against the CPU's 35, the CPU's half of the drain falls 6 ms, and none of it reaches the + // token - which is what it would look like if the enqueued hit kernels did not BEGIN until the host next + // entered the driver, i.e. after `pool()` returned. That is the third sighting of this driver behaving + // that way (rounds 195/287 on the doorbell, round 36 on the head and sampler) and it decides whether R4 can + // pay at all, so it gets measured rather than argued. + // + // `hit_done` is recorded on the stream straight after the hit kernel. `Combine` - which runs after the + // pool - queries it: SUCCESS means the GPU finished while the CPU was working, NOT-READY means it had not. + // Same shape as the doorbell's `rings_mid_graph`, and for the same reason. + void* hit_done = nullptr; ///< cudaEvent_t, created at session setup + int64_t hit_ready = 0; ///< layers where the hit work was DONE by the time the pool returned + int64_t hit_late = 0; ///< layers where it was not + /// The candidate fix, as an A/B arm: enter the driver once right after the hit launch. If submission is + /// lazy, this starts the GPU work before the pool instead of after it. + bool hit_poke = false; + bool hit_cpu_order = false; ///< experimental CPU-order GPU expert arithmetic; opt-in only + int64_t n_hits = 0; ///< this layer's hits + /// Set by `Launch` and consumed by `Combine`, so a `Combine` with no `Launch` in front of it cannot + /// add a stale buffer into `parts`. + bool hit_pending = false; + const char* hit_fail = nullptr; + + /// Whether the hit path is wired up. All of it or none of it: a half-configured hit path would compute + /// some experts twice and others not at all, which is a wrong token rather than an error. + bool hits_ready() const { + return cache != nullptr && cache_base != nullptr && parts_out != nullptr && hit_out != nullptr && + mixed != nullptr && + hit_scratch != nullptr && x_q8_0_hit != nullptr && x_q8_0_hit_scale != nullptr && d_slot != nullptr && d_dst != nullptr; + } + + std::vector jobs; + strata::kernels::cpu::ActQ act; + /// Plan v0.3 P6 verify window: one quantized activation per token, the multi-token jobs, and the expert -> + /// job map (reset after every layer). + std::vector act_multi; + /// Plan v0.3 P6: a native pack's per-token activations (MAXT x kNativeActBytes). + std::vector nact_multi; + std::vector jobs_multi; + std::vector job_of; + /// Plan v0.3 P6: the verify window's GPU plan (VRAM hits + the PCIe share of the misses); `pcie_num`/256 of + /// each layer's distinct missed experts (the last ones in routing order) are read by the GPU over PCIe. + GpuPlanSink* plan = nullptr; + int pcie_num = 0; + int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows + double ms_plan = 0, ms_actq = 0, ms_jobs = 0, ms_run = 0; ///< verify-window dispatch sections + /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off), + /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds. + std::vector usage; + int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windows + int64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows + /// Set when `dispatch` could not produce an answer. The loop itself has no error channel, so this is + /// where a source failure surfaces: the driver checks it after `session_loop` returns rather than the + /// engine computing from a half-filled `parts`. + /// + /// **`failed` LATCHES AND `fail` IS ONLY THE MESSAGE.** Clearing the message must not re-arm the adapter: + /// a session that failed at layer 5 has already fed `moe_combine` whatever `parts` held, so every layer + /// after it is built on a hole - and resuming into a plausible-looking token is the exact outcome this + /// whole mechanism exists to prevent. `failed` is what the short-circuit reads. + bool failed = false; + const char* fail = nullptr; + int64_t fail_layer = -1; + int64_t fail_expert = -1; +}; + +/// `strata::core::PoolFn`, exactly. Silent on failure BY SIGNATURE - see `ExpertDispatch::fail`. +void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, + int64_t k, float* out); + +/// Plan v0.3 P6: the pool for a verify window of `n_tok` tokens. `x_f` is (n_tok, n_embd), `ids` (n_tok, k) and +/// `out` (n_tok * k, n_embd). Each distinct missed expert is computed once for all the tokens routed to it; +/// resident experts' rows are zeroed (the GPU adds them). Requires `host_res` (the token-graph residency). +void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, + float* out); + +/// **THE HITS, LAUNCHED AFTER THE MISSES ARE STAGED AND BEFORE `post[l]`.** Same shape as `PoolFn` and for the +/// same reason: `session_loop` owns the ORDER and this owns the work, so the loop needs to know nothing about +/// expert caches. Returns immediately when there are no hits, which is every layer until the cache is warm. +/// +/// It must run AFTER the host has copied the misses into `parts_dev` (it writes into the same buffer, on rows +/// the CPU zeroed) and BEFORE `post[l]` (which reads it). Both are stream-ordered on the loop's own stream. +void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k); +/// The pool half of the same decision; see `ExpertDispatch::is_hit`. + +/// **PHASE 2'S ONLY SOURCE: `experts.bin`, memory-mapped, no cache.** +/// +/// `experts.bin` is 33,973,862,400 B and `BLOB` is 1,382,400, so it holds exactly `48 x 512 = 24,576` blobs and +/// the index is `layer * 512 + expert` with NO padding. A mapping is therefore the whole implementation: the +/// blob pointer is base plus a multiply, and the page fault that follows is the read. +/// +/// **AND THAT IS NOT AS SLOW AS IT SOUNDS, WHICH IS THE POINT.** The expert set is 34 GB and this machine has +/// 64 GB of DDR5, so a warm OS page cache holds ALL of it - the second token onward is a DRAM read at the +/// measured 44.14 GB/s, not a disk read. The first token's 663.6 MB comes off the disk and is the cold-path +/// number; `benches` should report the two separately rather than blending them. +/// +/// IT IS NOT AN LRU, AN LFU OR A PREFETCHER. Phase 3 replaces this object with those. Phase 2 is hit rate +/// `h = 0` on purpose, so that the CPU path and the host round trip are exercised on every layer of every +/// token - which is the only way they get debugged before speed matters. +class FileExpertSource : public ExpertSource { +public: + FileExpertSource() = default; + ~FileExpertSource() override; + FileExpertSource(const FileExpertSource&) = delete; + FileExpertSource& operator=(const FileExpertSource&) = delete; + + /// Maps `/experts.bin` and checks its size against the loaded expert layout. Canonical packs use + /// `n_layers * n_expert * BLOB`; native packs use their variable per-layer blob sizes and offsets. + /// + /// The size check is not a formality: a short file would fault at the END of a long sequence, and an + /// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers. + /// + /// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file + /// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when + /// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy. + /// With experts.bin present nothing changes. + bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); + /// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`. + void set_gguf(const std::string& native) { gguf_ = native; } + /// Whether the experts are read from the GGUF shards in place (no experts.bin). + bool gguf_mode() const { return !role_ptr_.empty(); } + /// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open + /// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation. + /// + /// The resident RAM mode (`--resident-experts`, `--resident-cpu-experts`): + /// - `pin`: page-locked and mapped (`cudaHostAlloc`), so the prompt path copies it by DMA and the verify + /// window may read a share of the misses over PCIe; when the driver refuses, ordinary memory locked in the + /// working set instead. `pin = false` is ordinary pageable memory (the ROCm arm: large pinned allocations + /// can fail there, and it is what the HIP measurements used). + /// - `lend_from_slot` >= 0: the GPU-cache slots from there to the end are the prompt path's lend region; their + /// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows + /// (a lent slot's expert is streamed during the prompt and copied back after it). + /// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false. + /// + /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken + /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the + /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files). + /// #467: `budget_bytes` = `kResidentWhatFits` is that path sized by the RAM alone (available minus the headroom + /// and the #403 margin) - the soft --resident-experts mode's second try when the whole complement does not fit; + /// false when not even one expert fits. On Windows the mapped experts leave the working set before any reading. + static constexpr uint64_t kResidentWhatFits = ~0ull; + bool pin_cache_complement( + const ExpertCache& cache, std::string& err, bool pin = true, + const std::vector>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1, + uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0, + const std::vector>* rank = nullptr); + void close(); + + bool mapped() const { return base_ != nullptr; } + int64_t blobs() const { return blobs_; } + uint64_t pinned_bytes() const { return complement_pinned_ ? complement_pin_limit_ : 0; } + uint64_t resident_bytes() const { return complement_bytes_; } + bool complement_pinned() const { return complement_pinned_; } + bool complement_ready() const { return complement_ready_; } + uint64_t locked_bytes() const { return complement_locked_; } + /// Lend-region slots whose experts the compact copy holds (the last ones of the cache). + int64_t resident_lent_slots() const { return complement_lent_slots_; } + + // ---- the resident RAM mode and the adaptive tier. A swap puts `in` (held here) into a GPU slot and evicts + // `out` (held only by that slot). Before the slot is overwritten the caller copies it back into an exchange + // buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU + // computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into + // `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file. + /// Whether the compact copy holds `(layer, expert)`. + bool has_resident(int64_t layer, int64_t expert) const; + /// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`. + bool reserve_exchanges(int64_t n, std::string& err); + int64_t exchange_capacity() const { return xstage_cap_; } + uint8_t* exchange_buffer(int64_t q) const; + /// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob. + bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q); + /// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied. + int64_t commit_exchanges(); + int64_t exchanges() const { return exchanges_; } + /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from + /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here. + int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); } + /// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs + /// `file_reads` counts, plus the prompt path's copies of them). + int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); } + uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); } + /// Of those, the bytes `blob` read (decode windows, adaptive swaps; the rest are the prompt path's copies), and + /// the time spent reading the files, summed over threads. + uint64_t file_blob_bytes() const { return file_blob_bytes_.load(std::memory_order_relaxed); } + double file_ms() const { return (double) file_us_.load(std::memory_order_relaxed) / 1000.0; } + /// Threads `prefetch` reads the GGUF with (STRATA_FETCH_THREADS, default 8). + void set_fetch_threads(int n) { fetch_threads_ = n < 1 ? 1 : n; } + + const uint8_t* blob(int64_t layer, int64_t expert) override; + bool pinned(int64_t layer, int64_t expert) const override; + const uint8_t* device_alias(int64_t layer, int64_t expert) const override; + bool pcie_layer(int64_t layer) const override; + bool transient(int64_t layer, int64_t expert) const override; + bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override; + /// CS-T: advances the assembled blobs' age (see staged_blob). + void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; + /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. + void prefetch(int64_t layer, const int64_t* experts, int64_t n) override; + /// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows, + /// madvise(WILLNEED) elsewhere), skipping the RAM copy's. + void warm(int64_t layer, const int64_t* experts, int64_t n) override; + bool warms() const override { return !role_ptr_.empty(); } + /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand. + int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); } + int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); } + + /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only + /// interesting once Phase 3 makes it not so. + int64_t reads() const override { return reads_; } + +private: + const uint8_t* mapped_blob(int64_t layer, int64_t expert) const; + /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`. + bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const; + bool open_gguf(std::string& err); + const uint8_t* staged_blob(int64_t layer, int64_t expert); + bool claim_stage(int64_t key, size_t& v, bool& fill); + bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst); + static constexpr uint64_t kNoComplement = detail::kNoCacheComplement; + // ---- CS-T: the GGUF shards in place + std::string gguf_; + struct Map { + const uint8_t* base = nullptr; + uint64_t bytes = 0; +#if defined(_WIN32) + void* file = nullptr; + void* mapping = nullptr; +#else + int fd = -1; +#endif + }; + std::vector maps_; + std::vector role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0 + std::vector role_bytes_; ///< 3 x n_layers: bytes per expert of that role + // the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is + // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds + // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next). + static constexpr uint64_t kStageAge = 3; + std::mutex stage_mu_; + std::vector> stage_buf_; + std::vector stage_key_; + std::vector stage_epoch_, stage_used_; + std::vector stage_busy_; ///< being filled (outside stage_mu_): never a victim + std::condition_variable stage_cv_; + int fetch_threads_ = 8; + std::atomic file_blob_bytes_{0}, file_us_{0}; + std::unique_ptr[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed + std::atomic warm_hits_{0}, warm_count_{0}; + std::unordered_map stage_of_; + uint64_t stage_blob_ = 0; + uint64_t stage_seq_ = 0; + uint64_t epoch_ = 0; + int64_t last_layer_ = -1; + bool stage_grew_ = false; + std::atomic ram_reads_{0}; + std::atomic file_read_bytes_{0}; + const uint8_t* base_ = nullptr; + int64_t blobs_ = 0; + int64_t n_layers_ = 0; + int64_t n_expert_ = 0; + uint64_t mapped_bytes_ = 0; + std::vector layer_offsets_, layer_blob_bytes_; + void* complement_arena_ = nullptr; + const uint8_t* complement_host_ = nullptr; + const uint8_t* complement_device_ = nullptr; + uint64_t complement_bytes_ = 0; + std::vector complement_offsets_; + bool complement_pinned_ = false; + bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered + uint64_t complement_pin_limit_ = 0; + uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked) + bool complement_ready_ = false; + uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) + int64_t complement_lent_slots_ = 0; + std::vector override_; ///< staged exchanges: an evicted expert read from its exchange buffer + struct Exchange { size_t in, out; int64_t q; uint64_t bytes; }; + std::vector staged_; + uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_` + bool xstage_pinned_ = false; + int64_t xstage_cap_ = 0; + uint64_t xstage_blob_ = 0; + int64_t exchanges_ = 0; + std::atomic file_reads_{0}; + int64_t reads_ = 0; +#if defined(_WIN32) + void* file_ = nullptr; + void* mapping_ = nullptr; +#else + int fd_ = -1; +#endif +}; + +// ================================ THE RESIDENT ARENA (R2.1) ================================ +// +// **THE MMAP ABOVE IS THE REVIEW'S FINDING C1 AND IT IS WORTH 2.2x.** Read the comment on `FileExpertSource` +// about the page cache holding all 34 GB: that is true of the expert file ALONE, and it is not what this engine +// does. The PLE/n-gram shard is a 26.8 GB file that the engine also maps, so 34 GB of experts plus 26.8 GB of +// n-gram is 60.8 GB of mapped, file-backed pages on a 63 GB machine - and file-backed pages are exactly the ones +// the OS drops from the standby list when it wants memory. The expert stream then re-faults from disk. +// +// Measured, this round: the pool runs at **~19 GB/s in the engine against 42.8 GB/s in `bench/micro/cpu_s2.cpp` +// on the same machine, reading the same 34 GB**. The micro does `std::fread` into a heap arena and reads +// ordinary (anonymous, resident) memory; the engine reads `MapViewOfFile`. That is the whole difference, and it +// is why this class exists. +// +// It reads `experts.bin` into a `PinnedArena` once at startup, so the expert stream comes from anonymous memory +// the OS has no cheaper reason to evict. `PinnedArena` also tries `cudaHostRegister`, which the GPU needs for +// Phase 3's cache fills and the CPU/PCIe miss split - but registration is best-effort and reported, not assumed. +class ArenaExpertSource : public ExpertSource { +public: + ArenaExpertSource() = default; + ~ArenaExpertSource() override; + ArenaExpertSource(const ArenaExpertSource&) = delete; + ArenaExpertSource& operator=(const ArenaExpertSource&) = delete; + + /// Allocates and loads `/experts.bin`. Prints nothing; the caller reports `note()` and the load + /// rate, because those are the two numbers that say whether the arena is the one that was asked for. + bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, std::string& err, + uint64_t max_pinned_bytes = 0, const std::string& shared_arena_file = {}); + /// Plan v0.3 P6: a native pack without experts.bin takes its experts from the model's GGUF: `native` is the + /// --native shard, and native_experts.txt names the other shards beside it (per layer, or per role in v4). + void set_gguf(const std::string& native) { gguf_ = native; } + void close(); + + bool mapped() const { return base_ != nullptr; } + int64_t blobs() const { return blobs_; } + const uint8_t* blob(int64_t layer, int64_t expert) override; + int64_t reads() const { return reads_; } + bool pinned(int64_t layer, int64_t expert) const override; + const uint8_t* device_alias(int64_t layer, int64_t expert) const override; + + /// What backing was obtained and why, for the startup print. "The engine adapts to the machine it is on" is + /// only true if the engine says what it got. + const std::string& note() const { return note_; } + double load_gib_per_second() const { return gib_per_s_; } + // Loader fix: the load, split. `load_seconds()` is the wall clock of the load loop; the other two are + // sums over the reader threads (see LoadStats), so on their own they say how much of that wall was spent + // waiting for the disk and how much in memcpy + FNV-1a. + double load_seconds() const { return load_seconds_; } + double load_read_seconds() const { return load_read_s_; } + double load_copy_seconds() const { return load_copy_s_; } + +private: + void* arena_ = nullptr; ///< the PinnedArena, owned + std::vector dev_slice_; ///< device alias of each registered slice (or of the whole range) + uint64_t slice_bytes_ = 0; + const uint8_t* base_ = nullptr; + int64_t blobs_ = 0; + int64_t n_expert_ = 0; + int64_t reads_ = 0; + std::string note_; + double gib_per_s_ = 0.0; + double load_seconds_ = 0.0; + double load_read_s_ = 0.0; + double load_copy_s_ = 0.0; + uint64_t pinned_bytes_ = 0; + std::string gguf_; +}; + +/// Plan v0.3 P6: checks native_experts.txt's GGUF spans against the files, before anything is read: each layer's +/// gate/up/down at its recorded (file, offset) must be that tensor (`blk.L.ffn__exps.weight`), of the +/// layout's type and dimensions, and inside the file. `native` is the --native shard (see set_gguf). +bool check_experts_gguf(const std::string& native, const strata::kernels::cpu::ExpertLayout& lay, std::string& err); +/// Fills `dst` (lay.total bytes, the experts.bin layout) from the GGUF files, one role at a time. +LoadStats load_experts_gguf(const std::string& native, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, + int threads); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/graph.hpp b/engine/strata/include/strata/core/graph.hpp new file mode 100644 index 00000000..369bfe3f --- /dev/null +++ b/engine/strata/include/strata/core/graph.hpp @@ -0,0 +1,117 @@ +// include/strata/core/graph.hpp - P2.S5: the GraphRegistry. +// +// `GraphRegistry`: capture/replay wrappers keyed by `(layer_type, n_tokens)`, with static input/output +// buffers at fixed addresses. +// +// THREE THINGS ARE BAKED INTO THIS INTERFACE, and each one is a measurement rather than a preference. All +// three come from `bench/micro/graph_capture.cu`, which was written to answer the phase's own instruction - +// "verify on the installed CUDA version with a minimal test before building on it". +// +// 1. **THE WAIT MUST POLL THE DRIVER, NOT MEMORY.** The phase's host loop says "spin on +// doorbell_seq == expected ... no cudaStreamSynchronize anywhere". A spin that only reads memory NEVER +// RUNS THE KERNEL: 5,907,703 spins over 500 ms, and the datum flips to 1 the instant anything calls into +// the driver and never before. On Windows the display driver model BATCHES command submission, and a +// thread that only reads memory gives it no reason to flush. Hence `wait_ms`, which polls an event - +// a QUERY and not a blocking sync, so P2.X3's "zero synchronization calls in the layer loop" still holds, +// and it costs 0.021 ms. +// +// 2. **A GRAPH RE-READS ITS INPUT BUFFERS AT REPLAY, BUT NOT ITS KERNEL ARGUMENTS.** Verified: eight +// replays with a different pinned input each time all tracked correctly, so the data path is live; but a +// kernel argument is copied into the node at capture and is never re-read. **Anything that changes per +// step - a position, a page-table base, a token id - must be DATA in a device buffer, never an argument.** +// This is the phase's "graph capture with pointers that change between steps silently replays stale +// addresses" hazard, and it now has a measurement behind it. +// +// 3. **FIXED ADDRESSES ARE THE CALLER'S OBLIGATION.** The registry cannot check them. Every buffer a +// captured body touches must be allocated before `record` and never reallocated; the registry holds the +// graph, not the memory. +// +// What the registry is FOR: a layer's ops are the same every token, so recording them once and replaying +// removes the per-call host cost of submitting them individually. Measured, that cost is 10-22 us PER CALL +// into the driver on this machine, and a layer with 8 submissions is ~0.1 ms of round trip. +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace strata::core { + +/// The two attention families. `docs/semantics.md`: 36 GDN layers and 12 QSA, at indices 3, 7, ... 47. +enum class LayerType : int { GDN = 0, QSA = 1 }; +inline const char* to_string(LayerType t) { return t == LayerType::GDN ? "GDN" : "QSA"; } + +/// One recorded graph. Move-only: it owns a `cudaGraphExec_t` and an event, and two owners would +/// double-destroy. +class CapturedGraph { +public: + CapturedGraph() = default; + ~CapturedGraph() { reset(); } + CapturedGraph(const CapturedGraph&) = delete; + CapturedGraph& operator=(const CapturedGraph&) = delete; + CapturedGraph(CapturedGraph&& o) noexcept { *this = std::move(o); } + CapturedGraph& operator=(CapturedGraph&& o) noexcept; + + /// Start recording everything the caller launches into `stream`. + bool begin(void* stream, std::string& err); + + /// Stop recording, instantiate, and record the completion event. A capture that produced ZERO nodes is + /// reported as an error: it means the body did nothing, which is a wiring mistake and NOT an empty graph + /// to be replayed happily forever. + bool end(void* stream, std::string& err); + + /// Replay. Does not synchronise. + bool launch(void* stream, std::string& err) const; + + /// The host loop's wait: poll `done_` until it completes or `timeout_ms` elapses. Returns false on + /// timeout, which the caller must treat as a hang and not as "probably fine". See NOTE 1 above for why + /// this exists instead of a memory spin. + bool wait_ms(int timeout_ms) const; + + size_t nodes() const { return nodes_; } + bool valid() const { return exec_ != nullptr; } + +private: + void reset(); + cudaGraph_t graph_ = nullptr; + cudaGraphExec_t exec_ = nullptr; + cudaEvent_t done_ = nullptr; + size_t nodes_ = 0; +}; + +/// Capture-once, replay-many, keyed by `(layer_type, n_tokens)`. +/// +/// `record` is given a CALLABLE that launches the layer's ops. On the first call for a key it captures; +/// afterwards it returns the cached graph and does NOT run the callable - so a caller that mutates state +/// inside the body will be surprised, which is why the body must only launch. +class GraphRegistry { +public: + explicit GraphRegistry(void* stream) : stream_(stream) {} + + /// Capture `body` for `key` if it is not already recorded. Returns false and fills `err` on failure. + /// Recording the same key twice is a no-op and is NOT an error - that is the point of a registry, and a + /// regression test asserts that the body runs exactly once across many calls. + bool record(LayerType type, int n_tokens, const std::function& body, std::string& err); + + const CapturedGraph* find(LayerType type, int n_tokens) const; + + /// Launch and wait, in that order, the two things the host loop does per layer. + bool launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const; + + size_t size() const { return graphs_.size(); } + /// How many times a BODY was actually captured. With a working cache this equals `size()`. + size_t captures() const { return captures_; } + +private: + using Key = std::pair; + void* stream_ = nullptr; + std::map graphs_; + size_t captures_ = 0; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/hit_hook.hpp b/engine/strata/include/strata/core/hit_hook.hpp new file mode 100644 index 00000000..8c21035c --- /dev/null +++ b/engine/strata/include/strata/core/hit_hook.hpp @@ -0,0 +1,41 @@ +// include/strata/core/hit_hook.hpp - R4.2c: the seam between the host loop and the VRAM expert tier. +// +// **IT IS ITS OWN HEADER BECAUSE BOTH SIDES NEED IT AND NEITHER SHOULD OWN IT.** `session.hpp` declares the +// loop that calls the hook; `expert_source.hpp` declares the implementation that answers it. Putting the type +// in either one makes the other include a header it has no other use for, and the loop knowing what an expert +// cache is (or the adapter knowing what a graph is) is exactly the coupling this seam exists to avoid. +#pragma once + +#include + +namespace strata::core { + +/// **TWO PHASES, AND THE SPLIT IS THE WHOLE POINT.** `Launch` runs BEFORE the CPU pool and `Combine` runs +/// AFTER the misses have been copied into `parts`. That ordering is what lets the GPU's resident experts run +/// at the same time as the CPU's misses instead of after them: +/// +/// ring -> hits(Launch) [GPU: quantize + grouped experts into `hit_out`] +/// -> pool() [CPU: the misses, CONCURRENT with the GPU] +/// -> H2D misses into `parts` +/// -> hits(Combine) [GPU: parts += hit_out] +/// -> post[l] +/// +/// **MEASURED, AND WHY IT IS NOT THE OBVIOUS ORDER.** The first version called the hit path once, after the +/// pool, writing straight into `parts`. The drain duly fell **18.2 -> 10.2 ms** - the CPU really was doing +/// half the experts - and **the token did not move at all**, because the GPU's half had simply been moved onto +/// the critical path behind the CPU's instead of beside it. A second buffer and one `add_inplace` buy the +/// overlap back. +enum class HitPhase { Launch, Combine }; + +/// `ids` AND `k` ARE THE ROUTER'S OWN OUTPUT, AND THEY ARE WHY THIS HOOK TAKES ARGUMENTS AT ALL. +/// +/// The first version took only `(user, stream, phase)` and left the hit/miss decision inside the pool +/// callback - which runs AFTER `Launch`. So `Launch` read the hit list from the PREVIOUS layer and computed +/// the previous layer's experts into the current layer's rows. It produced a token, the timings looked +/// plausible, and **C1 moved from mean KL 9.69e-02 to 1.03e+00 and top-1 from 0.867 to 0.333.** The decision +/// has to happen in `Launch`, on the ids the doorbell published for THIS layer, and the pool then consumes it. +/// +/// A null `HitFn` means "no VRAM tier" - the default, and what every caller had before R4. +using HitFn = void (*)(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/keyless.hpp b/engine/strata/include/strata/core/keyless.hpp new file mode 100644 index 00000000..4665c458 --- /dev/null +++ b/engine/strata/include/strata/core/keyless.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "strata/core/layout.hpp" +#include +namespace strata::core { +bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error); +const float* keyless_routing(int64_t layer); +} +namespace strata::kernels { +// In-place, one independent matrix for each query head. No cached keys are produced. +void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream); +} diff --git a/engine/strata/include/strata/core/layer.hpp b/engine/strata/include/strata/core/layer.hpp new file mode 100644 index 00000000..e7cfeb24 --- /dev/null +++ b/engine/strata/include/strata/core/layer.hpp @@ -0,0 +1,628 @@ +// include/strata/core/layer.hpp - one GDN LAYER, composed. P2.S5's mixer. +// +// This is the first place in the engine where the kernels are COMPOSED rather than tested individually, so +// the thing it has to get right is the ORDER and the buffers, not the arithmetic. Every kernel it calls is +// parity-tested on its own; what can go wrong here is a buffer sized for the wrong shape, a step done in the +// wrong order, or a value that should have been converted and was not. +// +// `ref/gdn.py::gdn_decode` is the specification, and the order below is its docstring verbatim: +// +// qkv = wqkv @ x (10240 = q|k|v, each a contiguous run of 128-wide heads) +// conv -> SiLU (SiLU is applied to the WHOLE conv output before the split) +// q,k = l2_norm (v is NOT normalised) +// beta = sigmoid(wbeta @ x) +// gate = softplus(walpha @ x + dt) * ssm_a +// recurrent step +// y = rms_norm(o, ssm_norm) * sigmoid(z) <- SIGMOID for qwen4exp; qwen3.5 used SiLU +// out = ssm_out @ y +// +// FOUR THINGS IN THAT ORDER ARE EASY TO READ PAST, and each produces a plausible number: +// +// * **SiLU is applied BEFORE the split**, to the whole 10240-wide conv output. Applying it only to q and +// k, or after the reshape, is the same arithmetic on different data. +// * **v is NOT normalised.** `l2_norm` applies to q and k only - two rows of 16 heads, not the 48 of v. +// * **the `/hc`-style scale on q is `1/sqrt(S)`**, applied by the CALLER because `ref/gdn.py` says the two +// llama.cpp paths apply it in different places. It goes on AFTER the norm. +// * **the state is transposed** relative to the reference: (S, h_v, S) here, (S, S, h_v) there. That is +// `gdn.hpp`'s choice and it is the reason `gdn_step`'s arguments are laid out as they are. +// +// THE ACTIVATIONS FOLLOW THE CONTRACT, which is why three different GEMVs appear below: `attn_qkv`, +// `attn_gate` and `ssm_out` are K-quants (Q8_K), while `ssm_alpha` and `ssm_beta` are BF16 (bf16). Using one +// activation format for all five would be a 0.66-1.41% error on the three that matter - measured, in +// `s_gemv_q8k_parity` and `bf16_gemv_parity`. +#pragma once + +#include "strata/core/layout.hpp" +#include "strata/core/weights.hpp" + +#include "strata/kernels/gr.hpp" +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/ple.hpp" + +#include +#include +#include +#include + +namespace strata::core { + +/// Select pinned CUDA BF16/F32 projections for SSM gates, routing and the sparse indexer. +/// Configure before session capture; captured graphs retain the selected implementation. +/// Does not change GR, PLE or the shared expert's scalar gate. +void layer_set_native_bf16(bool enabled); +// Diagnostic vector-attention adapter; configure before capture, context <=256. +void layer_set_native_flash_attn_short(bool enabled); + +/// Every buffer one GDN layer needs, carved from an arena ONCE. Sizes are functions of `ModelGeometry`, and +/// `gdn_buffers_bytes` returns the total so a caller can size the arena before committing. +struct GdnBuffers { + // the activation, in the formats the contract asks for. BOTH quantized images are produced for every + // layer, because WHICH ONE A WEIGHT WANTS IS A PROPERTY OF THE WEIGHT and the pack mixes them by layer - + // `attn_qkv` alone is IQ4_XS on 13 layers, Q3_K on 18, Q4_K on 4 and S2 on 1. + uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K + uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 + uint16_t* x_bf16 = nullptr; ///< n_embd, bf16 bits + + // the qkv path + float* qkv = nullptr; ///< conv_channels + float* conv_out = nullptr; ///< conv_channels + float* h = nullptr; ///< conv_channels = silu(conv_out), and it IS q|k|v in place + + // the per-head scalars and the recurrence + float* alpha = nullptr; ///< h_v + float* beta = nullptr; ///< h_v + float* gate = nullptr; ///< h_v + float* o = nullptr; ///< h_v * S + float* z = nullptr; ///< value_dim + float* y = nullptr; ///< value_dim + uint8_t* y_q8k = nullptr; ///< value_dim, block_q8_K + uint8_t* y_q8_0 = nullptr; ///< value_dim, block_q8_0 + + // the recurrent state, which outlives the call + float* state = nullptr; ///< S * h_v * S + float* conv_state = nullptr; ///< conv_channels * (d_conv-1) +}; + +/// Bytes needed for `b`, 16-byte aligned between regions. +uint64_t gdn_buffers_bytes(const ModelGeometry& g); +/// Carves `base` (which must be DEVICE memory) into `b`. Returns the bytes used. +uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b); +/// Zeroes the recurrent and conv state, so a fresh sequence starts from the reference's own `zeros()`. +void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream); + +/// `Mixed` (n_embd f32) through one GDN layer to `out` (n_embd f32). `state` and `conv_state` are updated. +/// +/// `layer` selects the weights; `tables` must outlive the call. Returns false and fills `err` if a tensor is +/// missing - which is a wiring mistake here rather than a shape problem, because `check_layer` already +/// asserted the shapes at load time. +bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b, + const float* mixed, float* out, void* stream, std::string& err); + +// ================================ the MoE block ================================ + +struct Doorbell; // defined with the rest of the handoff, below; only a pointer is needed here + +/// Buffers for the MoE block, on EVERY layer. +struct MoEBuffers { + uint16_t* x_bf16 = nullptr; ///< n_embd, for the ROUTER's weight, which is BF16 + uint16_t* x_f16 = nullptr; ///< n_embd, for the SHARED EXPERT's weights (see the note in `moe_layer`) + float* logits = nullptr; ///< n_expert + int* ids = nullptr; ///< k + float* weights = nullptr; ///< k + float* shared = nullptr; ///< n_embd + float* sh_scratch = nullptr; ///< shared_expert_scratch_bytes(n_ff): the shared expert's own scratch + uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - the shared expert's weights want Q8_0 on the layers + ///< whose types are Q2_0/Q4_0/Q5_0/Q8_0/IQ4_NL, which is most of them + uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - and Q8_K on the K-quant ones +}; + +uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k); +uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b); + +/// The MoE block: router -> (the caller's expert outputs) -> combine. +/// +/// `parts` is (k, n_embd) device f32 and is **filled by the CALLER** - by the CPU pool and the VRAM-resident +/// experts. That split is the architecture's, not a shortcut: the routed experts are the only part of the +/// model that does not fit in VRAM, and every design decision in this engine exists to keep them out of the +/// graph. This function therefore owns the two ends - which experts, and how their outputs are combined - +/// and deliberately not the middle. +/// +/// TWO ACTIVATION FORMATS AGAIN, and the router's is the one that matters most: +/// +/// * `ffn_gate_inp.weight` is BF16, so the router sees a BF16 activation. `ref/moe.py` L88-92 calls this +/// "the highest-consequence rounding in the model": the logits were measured **8.100e-03** off without it, +/// which is enough to FLIP a top-10 selection - and a flipped selection is not a small numeric error, it +/// is a different expert reading a different weight. +/// * the shared expert's weights are Q3_K/IQ4_XS/Q5_0 IQ-quants whose contract is Q8_K, which +/// `shared_expert` does not implement; it takes fp16. That is the known gap its own header documents and +/// `docs/activation-contract.md` names as outstanding. +bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, + const float* x, const float* parts, float* out, void* stream, std::string& err, + const Doorbell* db = nullptr); + +// ================================ THE MOE, SPLIT AT THE ROUTER ================================ +// +// **THE SPLIT EXISTS BECAUSE THE ONE-LAYER DELAY WAS NOT A TIMING CHANGE.** `moe_layer` is +// `route -> publish -> shared expert -> combine`, and `combine` multiplies `parts` by THIS layer's +// `b.weights`. So `parts` must be THIS layer's expert outputs. A host loop that hands layer `l`'s pool +// result to layer `l+1` computes `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` while the model is +// `sum_j w_l[j] * expert_{ids_l,j}(x_l)` - **both the expert selection and the input one layer stale while the +// weights are current** - and `session.hpp` states the contract it violates: the doorbell is "a change to WHEN +// the host runs, not to what this function computes". +// +// The one-layer delay was introduced for a real reason - it is the only way to overlap a CPU pool with a GPU +// that has already queued the combine - and the fix is to split the GRAPH, not to delay the answer: +// +// block_layer_pre[l] attn -> mixer -> gr_write -> ffn gr_read -> moe_route [rings the doorbell] +// ... the host runs the pool here, on the ids `moe_route` just published ... +// block_layer_post[l] moe_finish -> gr_write +// +// `post[l]` is launched AFTER the pool returns, so it sees layer `l`'s experts with layer `l`'s weights, and it +// is still a captured graph. What it costs is the overlap: the window is now whatever GPU work follows the +// ring inside `pre[l]` - the shared expert and nothing else, because everything after the combine depends on +// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is why +// Phase 3's VRAM expert cache is the answer to the CPU term and the doorbell is not. + +/// The routing half: bf16 activation, the router GEMV, top-k, and the doorbell publish. Ends with the ring +/// rung, so a host that sees it knows `h_x_f`/`h_ids`/`h_weights` are in place. +bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, + const float* x, void* stream, std::string& err, const Doorbell* db = nullptr); + +/// The finishing half: the shared expert and the combination. +/// +/// **`parts` MUST BE THE EXPERTS THIS LAYER'S OWN ROUTER SELECTED.** It is combined with `b.weights`, which +/// `moe_route` wrote for THIS layer. Passing the previous layer's vectors is the L100 bug: it produces a +/// finite, fluent, deterministic token that is not the model's. +bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, + const float* x, const float* parts, float* out, void* stream, std::string& err); + +/// Plan v0.3 P3: the two parts of `moe_finish` separately. `moe_shared` computes the shared expert into +/// `b.shared` and needs only `x`; `moe_combine_parts` combines `parts` with `b.weights` and `b.shared`. +/// `moe_finish` is exactly `moe_shared` followed by `moe_combine_parts`. +bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, + const float* x, void* stream, std::string& err); +bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts, + float* out, void* stream, std::string& err); + +/// Plan v0.3 P3 (default ON): the shared expert runs at the END OF `pre[l]`, after the doorbell has rung, so +/// the GPU computes it while the host runs the CPU pool; `post[l]` then only combines. Same kernels on the +/// same inputs in the same stream order relative to their consumers, so the result is bitwise unchanged. +/// Must be set before capture. `false` restores the shared expert inside `post[l]` (A/B arm). +void layer_set_shared_early(bool enabled); +bool layer_shared_early(); + +// ================================ the QSA mixer ================================ + +/// THE PERSISTENT STATE OF ONE QSA LAYER FOR ONE SEQUENCE: the KV cache, the indexer's pooled keys, the rope +/// tables, and the per-token step buffer. None of it is scratch - it survives every token. +/// +/// `max_cells` is the sequence capacity the arena was sized for, and it fixes the rope table's length: a table +/// shorter than the sequence would have `rope_neox_apply` read past it, which is a wrong rotation rather than a +/// fault. +struct QsaState { + uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) + uint16_t* v_pool = nullptr; + /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. + bool without_key = false; + bool kv_int8 = false; + int8_t* k_q = nullptr; + int8_t* v_q = nullptr; + uint16_t* k_scale = nullptr; + uint16_t* v_scale = nullptr; + /// PR #21: Q4_0 KV with Walsh-Hadamard rotation (qsa_set_kv_q4, kv_q4.hpp): 144 B per cell and head + bool kv_q4 = false; + uint8_t* k_q4 = nullptr; + uint8_t* v_q4 = nullptr; + /// Hybrid K8V4: K in INT8 (unrotated - the scores stay exact), V in rotated Q4_0 (kv_q4.hpp): 816 B per cell. + /// Uses k_q/k_scale + v_q4. Mode 0 only (no KV streaming, no ring); under this setting the MTP drafter's + /// ring state stays plain INT8, so the block movers never see the hybrid layout. + bool kv_hybrid = false; + /// K and V go through kv_q4.hpp's Walsh-Hadamard rotation before they are stored, the queries too, the output + /// back: always for Q4_0, for INT8 by qsa_set_kv_int8_rotate (spreads outlier channels over the scale groups) + bool kv_rot = false; + int32_t* page_table = nullptr; ///< (n_pages,) logical page -> physical page (-1: not resident, streamed) + int64_t n_pages = 0; + int64_t max_cells = 0; + + /// KV STREAMING (docs/kv-streaming-design.md, `kv_stream.hpp`). `kv_mode` 0: every page in VRAM, identity + /// table (n_slots == n_pages, no host copy). 1: streamed - the authoritative K/V in `host`, `n_slots` pages + /// in VRAM, `map` resolves the selection's blocks on device. 2: a ring (the MTP drafter's window) - `n_slots` + /// pages at `block % n_slots`, with the host copy for a resume. The pool pointers above point at the slots. + int kv_mode = 0; + int64_t n_slots = 0; + strata::kernels::KvHostPools host; + strata::kernels::KvStreamMap map; + int64_t idx_pooled_rows = 0; ///< rows of `idx_pooled` (a ring, which has no indexer, keeps 2) + + float* idx_tail = nullptr; ///< (idx_block - 1, idx_dim): the raw tail of the block being filled + float* idx_dead = nullptr; ///< (idx_dim,): the spare slot's key, CONSTANT for the sequence + float* idx_pooled = nullptr; ///< (max_cells/idx_block + 2, idx_dim) + int32_t* idx_block_pos = nullptr; + + float* cos_tab = nullptr; ///< (max_cells, n_rot/2), built on the HOST in float64 + bool owns_rope = false; ///< built the table above (not borrowed with share_rope): it releases it + float* sin_tab = nullptr; + + /// THE PER-TOKEN COUNTS, IN DEVICE MEMORY - the whole reason this layer can be a graph. `qsa_step_fill` + /// computes all four from the position, so one H2D per token updates every count every kernel needs. + int32_t* step = nullptr; + int32_t* attention_status = nullptr; ///< per-layer device status, captured D2H to host_step[kStepCount] + /// The rope positions, (n_head,) int32, all equal to the current position. `rope_neox_apply` reads its + /// positions from the DEVICE, so a host scalar here would be an illegal access (and uncapturable). + int32_t* pos_dev = nullptr; + + /// PINNED HOST STAGING AT FIXED ADDRESSES, and they are not an optimisation. The uploads in `qsa_layer` + /// copy FROM these, so a CUDA graph captures the SOURCE POINTER - and the first version of the layer filled + /// a stack array and a local `std::vector` instead. Those addresses are dead by the time the graph is + /// replayed, which is this project's own recorded pitfall ("graph inputs live at fixed addresses") walked + /// straight into: the replay would read whatever the stack held, and the step counts would be wrong in a way + /// that looks like a working token. + /// + /// Pinned as well as fixed, because a pageable source would make `cudaMemcpyAsync` a synchronous staged + /// copy and give back the overlap the doorbell protocol exists for. + int32_t* host_step = nullptr; ///< (kStepCount + 1,) pinned; final element is attention status + int32_t* host_pos = nullptr; ///< (n_head,) pinned +}; + +/// Plan v0.3 P7: the RoPE cos/sin table (max_cells x n_rot/2 x 2 floats, 64 MiB at 262K) is identical in every +/// QSA layer. `with_rope = false` sizes a state that borrows it; `share_rope` points `st` at another state's table +/// instead of building a copy (the session builds it once, in the first QSA layer). +uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope = true, int64_t ring_cells = 0); +/// KV streaming: keep `cells` cells of each QSA layer in VRAM and the rest in pinned host memory (0: all in VRAM, +/// the default). Set before sizing and initializing the session; a context that fits in `cells` is not streamed. +/// Also puts the MTP drafter's K/V in a ring of its window (`ring_cells` of qsa_state_bytes/init; -1 forces a fully +/// resident state). +void qsa_set_kv_resident(int64_t cells); +int64_t qsa_kv_resident(); +/// The fewest resident cells a streamed layer may have: one verify window's selections (8 queries x 2,051 cells +/// in whole blocks) must fit at once, with room to spare. +int64_t qsa_kv_resident_min(); +/// Pinned host bytes the streamed states hold (their host copies). +uint64_t qsa_kv_host_bytes(); +/// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and +/// initializing the session; default off until gate G-C accepts it. +void qsa_set_kv_int8(bool enabled); +void qsa_set_without_key(bool enabled); +bool qsa_without_key(); +/// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) +void qsa_set_kv_int8_rotate(bool enabled); +bool qsa_kv_int8(); +/// PR #21: store K/V as Q4_0 after a Hadamard rotation (`--kv q4_0`): 576 B per cell, vs 1,056 in INT8. +void qsa_set_kv_q4(bool enabled); +bool qsa_kv_q4(); +/// Hybrid K8V4 (`--kv k8v4`): K in INT8, V in rotated Q4_0 - 816 B per cell. Not with --kv-resident. +void qsa_set_kv_hybrid(bool enabled); +bool qsa_kv_hybrid(); +/// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4). +inline int qsa_kv_format(const QsaState& st) { + // A hybrid K8V4 state is mode 0 only and never reaches the block movers; refuse rather than let it + // fall through to kKvF16 - a wrong layout silently applied is worse than a hard stop (PR review). + if (st.kv_hybrid) { + std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n"); + std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu) + } + if (st.without_key) return strata::kernels::kKvValueInt8; + return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; +} +uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, + const QsaState* share_rope = nullptr, int64_t ring_cells = 0); +/// KV streaming: the pools a reader sees (the VRAM slots) and, when streamed, make the selection's blocks resident. +strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st); +void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q, + int64_t cap, void* stream); +/// Zeroes the pools AND the indexer, so a fresh sequence matches the reference's own `zeros()`. The KV pool +/// matters even for cells that are never attended, because `kv_gather` reads whatever the selection names. +void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream); + +// ================================ PER-STAGE TIMING, DEBUG ONLY ================================ +// +// Event pairs around the pieces of `block_layer_pre`/`_post`, recorded per (layer, stage) and read once at the +// end so that **NOTHING IS SYNCHRONISED DURING THE RUN** - a per-stage sync would serialise the pipeline and +// report the serialised time. **CAPTURED GRAPHS CANNOT USE IT**: an event record inside a stream capture is +// silently dropped, so this is for the `--no-capture` path only. +// +// It exists because the engine spends ~1.047 ms per layer with the experts off while every cost model in +// `bench/` predicts less than half that, and the gap has to be attributed before it can be attacked. +// slot 0 gr_read(attn) 1 the attention block 2 gr_write(attn) 3 gr_read(ffn) 4 router +// slot 5 moe_finish 6 gr_write(ffn) +bool stage_timing_enable(); +void stage_timing_name(int slot, const char* name); +void stage_timing_report(int64_t n_layers); +/// The same event pairs, reachable from `session.cpp`, for marks that sit OUTSIDE the captured graphs - the +/// two `cudaGraphLaunch` calls per layer. Those are ordinary stream operations, so an event around them is +/// legal and is not captured, which is what lets the captured path's 1.047 ms/layer be split into the two +/// graphs' execution and the gap the host spends between them. Slots 16 and 17 are reserved for it; slots +/// 0-15 are the in-layer marks and are only meaningful with `--no-capture`. +void stage_mark_begin(int64_t layer, int slot, void* stream); +void stage_mark_end(int64_t layer, int slot, void* stream); + +/// Scratch for one QSA layer. Every buffer here is overwritten by every token. +struct QsaBuffers { + uint8_t* x_q8_0 = nullptr; ///< n_embd, block_q8_0 - `attn_q` is Q2_0, whose vec_dot_type is Q8_0 + uint8_t* x_q8k = nullptr; ///< n_embd, block_q8_K - the three K-quant projections + uint16_t* x_bf16 = nullptr; ///< n_embd - the two BF16 indexer projections + float* q_full = nullptr; ///< n_head * 2 * head_dim: the raw `attn_q` output, q | gate per head + float* qcur = nullptr; ///< n_head * head_dim: the FIRST half of each head, contiguously + float* kcur = nullptr; ///< n_head_kv * head_dim + float* vcur = nullptr; ///< n_head_kv * head_dim + float* idx_raw = nullptr; ///< idx_key_dim: NEVER normed and NEVER rotated + float* q_idx = nullptr; ///< idx_q_heads * idx_key_dim + float* cell_scores = nullptr; ///< max_cells + int32_t* ids = nullptr; ///< cap = qsa_selection_width(kTopkMaxCells, s) + uint16_t* k_scratch = nullptr; ///< cap * n_head_kv * head_dim + uint16_t* v_scratch = nullptr; + float* attn = nullptr; ///< n_head * head_dim + uint16_t* attn16 = nullptr; ///< n_head * head_dim, for a fp16-activation consumer + /// `attn * sigmoid(gate)` in f32 and then in Q8_K - what `attn_output` ACTUALLY wants. Its weights are + /// Q4_K/Q5_K/Q6_K, whose `vec_dot_type` is Q8_K, and the fp16 path is worth 0.66-1.41% against the + /// reference. `docs/activation-contract.md`. + float* attn32 = nullptr; + uint8_t* attn_q8k = nullptr; + float* attn_scratch = nullptr; ///< plan v0.3 P3: split-K decode attention partials +}; + +uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells); +uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b); + +/// `x` (n_embd f32) through one QSA layer to `out` (n_embd f32) at sequence position `pos`. +/// +/// `pos_base` is the sequence's FIRST cell's position, which the indexer needs and cannot derive - equating a +/// cell's position with its index is only right for a sequence starting at 0. +/// +/// THE OP ORDER IS `ref/model.py::_qsa`, and two things in it are easy to read past: +/// +/// * the indexer's raw key is appended BEFORE any norm or rotation, and it is the raw `indexer.k_proj` +/// output that is pooled and rotated LATER, once per block and at the block's FIRST cell; +/// * `q_full` is split into q and gate by HALVES of each head's 2*head_dim block, contiguous, not +/// interleaved - `qsa_gate_apply` reads the second half and `qcur` is copied out of the first. +/// +/// THE THREE ACTIVATION FORMATS FOLLOW `docs/activation-contract.md`, and they are not interchangeable: +/// `attn_q` is Q2_0 (Q8_0 activation), `attn_k`/`attn_v`/`attn_output` are K-quants (Q8_K), and the two +/// indexer projections are BF16 (bf16). +bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, + const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, + std::string& err, float* dump = nullptr); + +// ================================ THE DOORBELL ================================ + +/// THE HANDOFF: `x_f` and the miss list reach the CPU WHILE THE LAYER IS STILL RUNNING. +/// +/// Everything about the shape of this struct comes from two measurements, and neither was a guess: +/// +/// * **THE WAIT MUST POLL THE DRIVER.** Round 195: a host spin that only reads a memory location never runs +/// the kernel - 5,907,703 spins over 500 ms and the datum flips the instant `cudaStreamSynchronize` is +/// called and never before, because on Windows the driver BATCHES command submission and a memory-only +/// spin gives it no reason to flush. So `h_seq` is read AND `cudaEventQuery` is called, which is a query +/// and not a blocking sync - P2.X3's "zero synchronization calls in the layer loop" still holds. +/// * **THE WRITE MUST BE CAPTURABLE, AND A KERNEL IS.** Round 199: `cudaEventRecord` inside a capture is +/// SILENTLY DROPPED - 2 nodes for two kernels plus an event record, and the event never completed across a +/// 41 ms graph. A mid-graph doorbell KERNEL is captured normally, and round 209 measured the host seeing a +/// pinned handoff **0.050 ms** into a 39.8 ms graph. +/// +/// The memory is MAPPED PINNED, so it has one address for the device and another for the host and both refer +/// to the same bytes. Pinned as well as mapped, because a pageable destination would turn the device's write +/// into a staged copy and give back the overlap this exists for. +struct Doorbell { + int64_t n_embd = 0; + int64_t k = 0; + // the HOST's view + float* h_x_f = nullptr; ///< n_embd + int32_t* h_ids = nullptr; ///< k + float* h_weights = nullptr; ///< k + uint32_t* h_seq = nullptr; ///< 1 + /// Plan v0.3 P3 token graph: the HOST's answer. The host writes the ring value it has served (after the + /// pool's output is in place); the device's `doorbell_wait` spins until the flag equals the ring. + uint32_t* h_flag = nullptr; ///< 1 + // the DEVICE's view of the same bytes + float* d_x_f = nullptr; + int32_t* d_ids = nullptr; + float* d_weights = nullptr; + uint32_t* d_seq = nullptr; + uint32_t* d_flag = nullptr; +}; + +/// Allocates the four mapped-pinned regions. Returns the bytes, or 0 on failure. +uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db); +void doorbell_free(Doorbell& db); +/// Zeroes `h_seq` (and `h_flag`), so a caller can wait for it to become `expected` from a known state. +void doorbell_reset(const Doorbell& db); + +// ================================ ONE WHOLE BLOCK ================================ + +/// The gated-residual stack plus the two buffers the halves hand to each other. +/// +/// `R` is (hc, n_embd) and is BOTH the input and the output: `hc` residual streams, each n_embd wide, which is +/// what `gr_read`/`gr_write` exist for. It is not one vector with a gate. +struct BlockBuffers { + float* R = nullptr; ///< (hc, n_embd) + float* mixed = nullptr; ///< n_embd: what the mixer consumes + float* block_out = nullptr; ///< n_embd: what a half produces + float* inject = nullptr; ///< hc: `gr_read`'s per-stream injection, reused per half + /// Plan v0.3 P3 fused GR: the FFN half's injection lives here (the attention half's stays in `inject`), + /// because the fused read of one half reads the other half's injection while writing its own. + float* inject2 = nullptr; ///< hc + float* gr_rs = nullptr; ///< hc: the fused read's per-stream 1/rms + uint8_t* head_q8k = nullptr; ///< `q8k_bytes(n_embd)`: the head's Q8_K activation image + strata::kernels::GrWorkspace gr; ///< `gr_read`'s scratch + + /// THE HALF-LEVEL C1 ORACLE, and it is a HOST buffer of `(2 * n_embd + 2 * hc + n_head * head_dim)` floats + /// PER LAYER: `[0, n_embd)` the attention half's `block_out`, `[n_embd, 2*n_embd)` the MoE half's, the two + /// `hc`-vectors of `inject`, and finally the QSA layers' PRE-GATE attention (`n_head * head_dim`, unused by + /// GDN). The residual ladder (`session_loop`'s `dump_layers`) says WHICH LAYER diverges; this says which + /// stage, and it is the only way to separate the reference's `linear_attn_out-` from its `ffn_out-` + /// without re-deriving one of them. The copies are issued from inside `block_layer_pre`/`_post`, so they + /// are recorded as nodes of the per-layer captured graph and replay with the layer they belong to. Null + /// means no dumping, which is the default and costs nothing. + float* dump = nullptr; +}; + +uint64_t block_buffers_bytes(const ModelGeometry& g); + +/// Plan v0.3 P3: the hyper-connection read as two fused kernels with the previous half's write folded in +/// (`strata/kernels/fused_gr.hpp`). Requires the native MMVF contract (FP32 activations). The residual `R` +/// then lags by one pending write between halves; it is materialised before the layer-1 PLE and after the last +/// layer. Set before capture; not for the per-stage or dump measurements. +void layer_set_fused_gr(bool enabled); +bool layer_fused_gr(); + +/// Plan v0.3 P3/P7: QSA attention by the split-K kernel reading the KV pools directly (default ON; `false` keeps +/// the gather + one-block-per-head kernel). Set before capture. +void layer_set_fast_attn(bool enabled); +/// Plan v0.3 P3: doorbell payload + ring as one kernel, QSA step staging read by a kernel from mapped memory +/// (default ON; `false` keeps the memcpy nodes). Set before capture. +void layer_set_publish_kernel(bool enabled); +/// Plan v0.3 P3: GDN step + output norm as one coalesced kernel under the native contract (default ON). +void layer_set_fused_gdn(bool enabled); +/// Plan v0.3 P7: QSA block scores in FP32 and a radix top-k over blocks (default ON; `false` = the FP64 row scores +/// and the bit-serial cell top-k). Set before capture. +void layer_set_fast_select(bool enabled); +/// Plan v0.3 P6: whether the current decode configuration is the one the speculative verify window reproduces +/// bit for bit (native projections, fused GR and GDN, split-K attention, block selection, native indexer). +bool layer_verify_compatible(std::string& why); +uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b); + +// ================================ THE TWO ENDS OF A TOKEN ================================ + +/// THE EMBEDDING LOOKUP, done as a COLUMN DEQUANT rather than a GEMV. +/// +/// `token_embd.weight` is `[n_embd, n_vocab]`, so `out[i] = W[i][token]` - one column, `n_embd` values. Running +/// `output`-style arithmetic on a one-hot activation would produce the same numbers with 248320x the work. +/// +/// **THE DECODE IS TRANSCRIBED FROM `s_gemv_q8k_split` AND MUST STAY BIT-IDENTICAL TO IT**: the code is the +/// `CODE_BITS`-wide field, least-significant first, at bit `(i % PER_BYTE) * CODE_BITS` of byte `i / PER_BYTE`; +/// the value is `(code + code_bias) * scales[i / group_elems] + offsets[i / group_elems]`; and the column's +/// planes start at `token * n_in / PER_BYTE` and `token * n_in / group_elems`. A second decoder that drifts +/// from the kernel's would make the prompt embed differently from the tokens generated after it. +bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev, void* stream, + std::string& err); + +/// `ref/model.py` L520: `fin = GR.gr_read(R, output_hc_*..., inject=None, rms_eps); logits = output @ fin`. +/// +/// `R` is read from `bb.R` and the result goes to `logits`, which the caller sizes at `output.weight`'s `ne1` +/// (the vocabulary). `bb.head_q8k` and `bb.mixed` are scratch. +bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, float* logits, + void* stream, std::string& err); + +/// Compute the final residual mix in bb.mixed, before the output projection. This is shared by the +/// canonical and experimental native head so only the projection's arithmetic changes in their A/B test. +bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, + void* stream, std::string& err); + +/// THE PER-LAYER OP ORDER of `phases/phase-2-correct-engine.md` P2.S5, architecture §6.1, for ONE layer: +/// +/// gr_read (attn) -> mixer -> gr_write (attn) +/// gr_read (ffn) -> MoE -> gr_write (ffn) +/// +/// `layer` picks the mixer: `is_qsa_layer` selects `qsa_layer`, otherwise `gdn_layer`. `pos`/`pos_base` reach +/// the QSA layer and are ignored by GDN, which has no position argument at all - its whole per-token input is +/// `x` and what advances between tokens is its recurrent state. +/// +/// **`parts` IS THE CALLER'S**, and that is the architecture's split rather than an omission: the routed experts +/// are the only part of the model that does not fit in VRAM, so the CPU pool and the VRAM-resident experts fill +/// `parts` and this function owns the two ends. In P2.S5 everything is a miss, so a caller passes whatever the +/// pool produced; the doorbell protocol is what lets it be produced DURING this layer rather than before it. +// ================================ THE PLE (LAYER 1'S PER-LAYER EMBEDDING) ================================ +// +// **THIS MODULE EXISTED, WAS PARITY-TESTED, AND WAS NEVER CALLED - WHICH IS WHY GATE C1 FAILED.** Layer 1 is +// the only layer with `blk.1.ple_*` tensors (six of them) and `block_layer` ran GDN/QSA + GR + MoE without it, +// so the engine computed a different model. `ple_parity` verifies all three pieces against things that are +// not this project's code - the hash against `ref/ngram.py` with the artifact's own constants, the IQ4_NL row +// read against numpy over the original GGUF, and the block against ggml's own graph - and none of that helps +// if nothing calls it. +// +// THE TABLE IS NOT IN THE PACK. `per_layer_token_embd.weight` is 51.2e9 elements (28.8 GB) of IQ4_NL in the +// ORIGINAL second GGUF shard, and it is the only tensor this engine reads from the GGUF rather than from the +// canonical pack. It is also why the PLE is cheap: sixteen 90-byte rows per token is 1440 bytes of traffic, +// against the experts' 664 MB. +struct PleRun { + /// Null when the PLE is not wired (no table, or a pack without `blk.1.ple_*`). Then `block_layer_pre` + /// SKIPS the module entirely, which is what every measurement before this change did. + strata::kernels::PleTable* table = nullptr; + strata::kernels::PleWeights w; + /// The session's PLE state, by pointer so `block_layer_pre` needs no `SessionState`. + const int32_t* token = nullptr; ///< the token being decoded + const int32_t* prev = nullptr; ///< (2,) predecessors, OLDEST FIRST, `-1` where there is none + float* hist = nullptr; ///< NG_HIST x hc_dim NORMALIZED history, row-fastest + /// The gathered 2560-wide row vector on the DEVICE, and the host staging it is copied from: `gather` + /// writes HOST memory (the table is a host mapping) and the block wants the device. + float* emb_dev = nullptr; + float* emb_host = nullptr; + /// Internal workspace plus a disjoint normalized export for the next history row. + /// Allocate ple_run_scratch_bytes(), not merely the lower-level ple_block_scratch_bytes(). + float* scratch = nullptr; + strata::kernels::PleConsts consts; + bool ready() const { + return table != nullptr && table->is_open() && hist != nullptr && emb_dev != nullptr && + emb_host != nullptr && scratch != nullptr && token != nullptr && prev != nullptr && + ((w.key_codes != nullptr && w.key_scales != nullptr) || w.key_bf16 != nullptr || + w.key_native_data != nullptr) && + w.value_bf16 != nullptr && + w.norm_key != nullptr && w.norm_query != nullptr && w.norm_conv != nullptr && + w.conv1d_f16 != nullptr; + } +}; + +/// **CALLED ONCE PER TOKEN, FROM THE DRIVER, *OUTSIDE* ANY CAPTURE.** The n-gram hash and the table gather +/// are host operations, and `block_layer_pre` is captured - so doing them there would run them once, at capture +/// time, and replay the same rows for every token forever. This is the doorbell's cloned-literal bug in a +/// different coat: silent, finite, and stable. +bool ple_stage_token(const PleRun& p, void* stream, std::string& err); + +/// Plan v0.3 P2: `ple_stage_token` in two halves, so the SSD reads overlap other host work. +/// `ple_issue_token` hashes the token and starts its 16 row reads; `ple_finish_token` waits for them, +/// dequantizes and queues the upload. Both are driver-side, outside any capture, like `ple_stage_token`. +bool ple_issue_token(const PleRun& p, std::string& err); +bool ple_finish_token(const PleRun& p, void* stream, std::string& err); + +/// Internal PLE workspace plus one separate hc_dim normalized row for advancing history. +uint64_t ple_run_scratch_bytes(); + +/// `ple` is the layer-1 PLE, or null to skip it (which is what every measurement before LEDGER L123 did). +/// It is applied INSIDE `pre[1]`, before layer 1's own `gr_read`, because the block's output is +/// `hidden + gated + silu(conv)` on the residual itself - it is a residual UPDATE, and the architecture puts +/// the gathered rows in place "before layer 2". +bool block_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, + const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, + int64_t k, const BlockBuffers& bb, const float* parts, void* stream, std::string& err, + const Doorbell* db = nullptr, const PleRun* ple = nullptr); + +/// **THE BLOCK, SPLIT AT THE ROUTER, SO A HOST LOOP CAN PUT THE CPU POOL IN THE MIDDLE.** +/// +/// pre[l] gr_read(attn) -> mixer -> gr_write(attn) -> gr_read(ffn) -> moe_route [rings the doorbell] +/// post[l] moe_finish -> gr_write(ffn) +/// +/// `parts` reaches only `post`, and it must be THIS layer's experts. The two calls are NOT independent: `post` +/// reads `bb.mixed` and `bb.inject` exactly as `pre` left them, so nothing may run between them that touches the +/// block buffers - and in particular `pre[l+1]` may NOT be launched between them, because its own `gr_read` +/// overwrites both. That constraint is why the doorbell's window is the shared expert and nothing more, and +/// why the CPU expert term is answered by Phase 3's VRAM cache rather than by this pipeline. +/// +/// **`half` EXISTS SO THE CAPTURED GRAPH CAN BE SPLIT FOR MEASUREMENT, AND IT IS THE ONLY REASON.** +/// +/// The plan's R3 items - GR, GDN, the router - are each worth several milliseconds and there has never been a +/// per-stage breakdown of the CAPTURED graph to choose between them. The `--no-capture` table cannot supply +/// one: round 312 showed its `moe_finish` figure was a host-gap artefact, four times the captured cost of the +/// same work. An event recorded BETWEEN two `cudaGraphLaunch` calls IS valid, so the answer is to capture the +/// layer as more than one graph and time them from outside. +/// +/// `half` selects a prefix of the stages, and the seam is the one this file already documents: +/// +/// 1 = stages 0..2 gr_read -> attention -> gr_write the MIXER +/// 2 = stages 3..4 gr_read -> moe_route the FFN front and the ROUTER +/// 0 = both, which is what every caller before this used and what `session_loop` still uses +/// +/// **A half is not a free-standing call.** `2` reads what `1` left in `bb.mixed`/`bb.inject`, exactly as +/// `block_layer_post` does; the two are only meaningful replayed in order on one stream, which is what +/// `session_replay_stages` does. +bool block_layer_pre(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, + int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, + const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, void* stream, std::string& err, + const Doorbell* db = nullptr, const PleRun* ple = nullptr, int half = 0, + int stage_prefix = 0); + +bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, + const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream, + std::string& err); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/layout.hpp b/engine/strata/include/strata/core/layout.hpp new file mode 100644 index 00000000..7b27fec9 --- /dev/null +++ b/engine/strata/include/strata/core/layout.hpp @@ -0,0 +1,97 @@ +// include/strata/core/layout.hpp - the pack's LAYOUT, resolved by name and checked against the kernels. +// +// `WeightTable` answers "where are the bytes". This answers "is this the tensor I think it is", and it is +// the layer where a pack and a kernel disagree - which is the failure this project keeps paying for. Two +// examples, both real: +// +// * round 194 sized the indexer key store from `indexer.head_count = 4`, which counts QUERY heads. The +// cached key is ONE shared head of 128 (`indexer.k_proj` is [2560, 128]), so the term was 4x too big and +// the error survived a round because it moved in the direction that TIGHTENS the budget. +// * `docs/semantics.md` and the tensor manifest agree on every dimension here, but nothing CHECKED that a +// named tensor had the shape the kernel reading it assumes. +// +// So this header does two things: it names the tensors per layer type, and it asserts every shape the +// kernels depend on. A mismatch is reported with the tensor name, the shape found and the shape required, +// at LOAD time - not as a wrong number inside a GEMV at token 4000. +#pragma once + +#include "strata/core/weights.hpp" + +#include +#include + +namespace strata::core { + +/// The model's geometry, taken from `docs/semantics.md` and the artifact's own metadata. Every field here +/// is a number a kernel depends on, so a change is a change to a kernel contract and not a tuning knob. +struct ModelGeometry { + int64_t n_embd = 2560; + int64_t n_layers = 48; + int64_t qsa_interval = 4; ///< every 4th layer is full attention: layers 3, 7, ... 47 + + // GDN (36 layers) + int64_t ssm_state_size = 128; + int64_t ssm_k_heads = 16; + int64_t ssm_v_heads = 48; + int64_t ssm_d_conv = 4; + int64_t ssm_conv_channels = 10240; ///< 2*128*16 + 128*48 + int64_t ssm_value_dim = 6144; ///< 128 * 48 + + // QSA (12 layers) + int64_t n_head = 24; + int64_t n_head_kv = 2; + int64_t head_dim = 256; + int64_t idx_q_heads = 4; + int64_t idx_key_dim = 128; + + // gated residual, on every layer + int64_t hc = 4; + int64_t hc_lr = 320; + + // MoE, on every layer + int64_t n_expert = 512; + int64_t n_ff = 640; + + int64_t hc_dim() const { return hc * n_embd; } + /// `layer % qsa_interval == qsa_interval - 1` is full attention. Derived, not a second list. + int64_t n_qsa_layers() const { return n_layers / qsa_interval; } + int64_t n_gdn_layers() const { return n_layers - n_qsa_layers(); } +}; + +/// True for the full-attention layers. `docs/semantics.md` gives this twice over - `full_attention_interval +/// = 4` and an explicit `attention.compress_ratios` array - and this is the first of the two. +inline bool is_qsa_layer(const ModelGeometry& g, int64_t layer) { + return layer % g.qsa_interval == g.qsa_interval - 1; +} + +/// One layer's tensors, resolved by NAME. `get("attn_qkv.weight")` looks up `blk..attn_qkv.weight` +/// and returns null if the pack does not have it - a null is information, because a GDN layer has no +/// `attn_q` and a QSA layer has no `attn_qkv`. +/// +/// Holds a reference to the table; the table must outlive it. +class LayerView { +public: + LayerView(const WeightTable& table, int64_t layer) : table_(&table), layer_(layer) {} + + int64_t layer() const { return layer_; } + std::string name(const char* suffix) const; + const WeightRef* get(const char* suffix) const { return table_->find(name(suffix)); } + +private: + const WeightTable* table_; + int64_t layer_; +}; + +/// Every shape the kernels depend on, asserted for ONE layer. Returns false and fills `err` with the first +/// mismatch, naming the tensor, what it has and what is required. +/// +/// This is deliberately a separate function from `LayerView`: a caller that only wants the pointers should +/// not pay for the checks, and a caller that wants the checks should get ALL of them rather than the ones +/// its own call site happens to touch. +bool check_layer(const WeightTable& table, const ModelGeometry& g, int64_t layer, std::string& err); + +/// `check_layer` over every layer, plus the cross-layer properties: exactly 12 QSA layers at the right +/// indices, every GDN layer having the GDN set and no QSA tensor, and vice versa. Returns the first failure. +bool check_all(const WeightTable& table, const ModelGeometry& g, std::string& err); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/mtp.hpp b/engine/strata/include/strata/core/mtp.hpp new file mode 100644 index 00000000..e2084f6d --- /dev/null +++ b/engine/strata/include/strata/core/mtp.hpp @@ -0,0 +1,186 @@ +// include/strata/core/mtp.hpp - plan v0.3 P6: the MTP draft layer on the GPU. +// +// The model ships one multi-token-prediction layer (vLLM 0.30.0 `qwen4_exp` MTP; transcribed and validated in +// `tools/mtp_probe.py`, where it accepts 0.89 / 0.86 / 0.85 of greedy drafts at steps 1-3). Cell i of its +// sequence pairs the main model's final multi-stream residual at position i with the token at position i+1, at +// rope position i (vLLM's convention); its output predicts the token at position i+2, and its own residual feeds +// the next draft step. +// +// e = fc_embedding(rms(embed(tok)) * (1+w)) h = fc_hidden per stream(rms_10240(R) * (1+w)) +// R = h + e -> attention hyper-connection -> QSA attention (own K/V) -> MLP hyper-connection -> +// MoE (512 experts, top-10, shared expert) -> R += y * 2 sigmoid(inject / hc) -> final mixer -> head +// +// Runtime choices, each a trade of exactness for simplicity that only affects DRAFT quality, never the output +// (the verify window decides every emitted token): +// * the large projections run as Q8_0 through the multi-column MMVQ (`tools/mtp_rt.py` quantizes them); +// * the attention is DENSE over every cell the layer has seen - identical to the model's sparse selection +// below 2,051 cells - so speculative cells (draft steps, rejected window rows) never touch indexer state and +// are simply overwritten when their positions are processed again; +// * all 512 routed experts live in VRAM (708 MB) and run through the grouped hit kernels. +#pragma once + +#include "strata/core/layer.hpp" +#include "strata/core/session.hpp" +#include "strata/kernels/sampler.hpp" + +#include + +#include +#include +#include + +namespace strata::core { + +class NativeHead; + +class MtpDrafter { +public: + MtpDrafter() = default; + ~MtpDrafter(); + MtpDrafter(const MtpDrafter&) = delete; + MtpDrafter& operator=(const MtpDrafter&) = delete; + + /// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows. + /// Call before the VRAM expert tier is sized: this takes ~0.9 GB. + bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, + int64_t window = 32768); + /// The prompt's length: prefill() skips the cells the attention window can never reach again. + void set_prompt_len(int64_t n) { prompt_len_ = n; } + /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. + void set_max_drafts(int k) { max_drafts_ = k; } + uint64_t vram_bytes() const { return vram_; } + /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) + const QsaState& kv_state() const { return st_; } + /// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at + /// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring. + void kv_restore(int64_t upto); + /// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and + /// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this. + uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const; + /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). + bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err); + + /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, + /// the token at position cell+1). Runs in batches of up to max_t rows. + bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); + + /// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's + /// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last + /// accepted row) for T-1 drafts at cells p+a+1 ... `drafts` gets T-1 tokens. + bool draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err, + float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr); + + /// The first round: one cell (`cell`) from `R_row` (device) and `token` -> T-1 drafts. + bool draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, + float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr); + + /// COUPLED DRAFT SAMPLING (core/coupled_draft.hpp; STRATA_SPEC_COUPLED=1, set up by bind()): the request's + /// sampling. A sampled request (temperature > 0, not greedy) then drafts by SAMPLING with the target's chain and + /// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a + /// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off. + void set_draft_sampling(const strata::kernels::SamplerParams& sp); + /// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the + /// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0). + void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next); + bool coupled() const { return coupled_active_; } + + double ms_draft = 0, ms_prefill = 0; + int64_t rounds = 0; + + /// E-9: the prompt path computes this layer's prompt K/V in batches (Prefill::draft_kv): its tensors, its K/V + /// state, the first cell a round can still read, its device, and a wait for its own stream. + const float* tensor_f32(const char* name) const { return f32(name); } + const uint16_t* tensor_bf16(const char* name) const { return bf16(name); } + const void* tensor_q8(const char* name) const { return q8(name); } + QsaState& kv_state_rw() { return st_; } + int64_t first_needed() const { return (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; } + int device() const { return device_; } + bool idle(std::string& err) { + if (cs_ && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "mtp: its stream failed"; return false; } + return true; + } + +private: + bool record_forward(int T, int step_row0, cudaStream_t cs, std::string& err); + bool capture_prefill(int T, std::string& err); + bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device) + bool capture_round(int T, bool coupled, std::string& err); + bool capture_step(int j, bool coupled, std::string& err); + cudaGraphExec_t step_exec_[9] = {}; + // coupled draft sampling: its own round/step graphs (the argmax ones stay as they were), the request's + // parameters and the penalty ring (mapped staging + device copies), the split scratch, token id -> subset index + bool setup_coupled(std::string& err); + cudaGraphExec_t round_exec_c_[9] = {}; + cudaGraphExec_t step_exec_c_[9] = {}; + bool coupled_ok_ = false, coupled_active_ = false; + bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_) + int coupled_j_ = 0; + strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr; + int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr; + void* cscratch_ = nullptr; + const float* f32(const char* name) const; + const uint16_t* bf16(const char* name) const; + const void* q8(const char* name) const; + + const ModelGeometry* g_ = nullptr; + SessionState* ss_ = nullptr; + const WeightTable* wt_ = nullptr; + const NativeHead* head_ = nullptr; + const float* window_R_ = nullptr; + int max_t_ = 0; + int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split) + int max_drafts_ = 1 << 30; + int64_t n_vocab_ = 0; + uint64_t vram_ = 0; + cudaStream_t cs_ = nullptr; + cudaGraphExec_t prefill_exec_[9] = {}; + cudaGraphExec_t prefill_dev_exec_[9] = {}; + int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at once + int64_t pf_cap_ = 0; ///< its capacity in ints + cudaGraphExec_t round_exec_[9] = {}; + + struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; }; + std::vector tensors_; + uint8_t* dense_ = nullptr; + uint8_t* experts_ = nullptr; + void* state_arena_ = nullptr; + QsaState st_; + void* arena_ = nullptr; + + // mapped staging: tokens, step records (2*max_t rows), positions per head (2*max_t rows), the selected row, + // the drafts out + int32_t *h_tok_ = nullptr, *m_tok_ = nullptr, *h_step_ = nullptr, *m_step_ = nullptr; + int32_t *h_pos_ = nullptr, *m_pos_ = nullptr, *h_row_ = nullptr, *m_row_ = nullptr; + int32_t *h_out_ = nullptr, *m_out_ = nullptr; + float *h_prob_ = nullptr, *m_prob_ = nullptr; // each draft's probability under the draft layer + // the draft head: the main head's rows for a token subset (rt/draft_vocab.bin), or the whole head + uint8_t* dhead_ = nullptr; + int32_t* dvocab_ = nullptr; + int64_t n_dvocab_ = 0; + std::string rt_dir_; + int64_t window_ = 0; // attention over the last window_ cells (0 = every cell) + int64_t prompt_len_ = 0; + float* probs_ = nullptr; + // device + int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *row_ = nullptr, *ident_ = nullptr; + float *Rin_ = nullptr, *R_ = nullptr, *emb_ = nullptr, *en_ = nullptr, *e2_ = nullptr, *hn_ = nullptr, *h2_ = nullptr; + float *mixed_ = nullptr, *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *bo_ = nullptr; + float* xn_ = nullptr; + uint8_t* xq_ = nullptr; + float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr; + float* attn_scratch_ = nullptr; + float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *y_ = nullptr, *sample_ = nullptr; + int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr, *out_ids_ = nullptr; + uint8_t* hit_xq_ = nullptr; + unsigned long long* grp_ptr_ = nullptr; + int32_t *grp_start_ = nullptr, *grp_counts_ = nullptr; + float* hit_xs_ = nullptr; + void* hit_scratch_ = nullptr; + float* sh_scratch_ = nullptr; + uint16_t* x_bf16_ = nullptr; + float* head_logits_ = nullptr; + float* dummy_inj_ = nullptr; + int64_t cap_ = 0, attn_scratch_floats_ = 0; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/native_dense.hpp b/engine/strata/include/strata/core/native_dense.hpp new file mode 100644 index 00000000..8330fac5 --- /dev/null +++ b/engine/strata/include/strata/core/native_dense.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata::core { +class WeightTable; + +// Experimental GDN/QSA/shared-expert projection overrides. Upload unchanged native GGUF +// blocks once, then attach them to the matching canonical WeightRef. Unsupported +// types retain their canonical paths. Owns one Q8_1 scratch vector shared by all +// these projections, so use one ordered session stream and keep this object +// alive until all graphs that reference it have been destroyed and synchronized. +class NativeDense { +public: + NativeDense() = default; + ~NativeDense(); + NativeDense(const NativeDense&) = delete; + NativeDense& operator=(const NativeDense&) = delete; + bool load(const std::vector& shards, WeightTable& table, std::string& err, + bool include_ple_key = false); + /// Plan v0.3 P1: the canonical tensor names `load` would serve natively from these shards (eligible name, + /// supported type, 2-D), read from the GGUF headers only - so the canonical arena can skip them. + static bool served_names(const std::vector& shards, bool include_ple_key, + std::set& out, std::string& err); + /// #326: a native pack whose `blk.1.ple_key.weight` row is unquantized (iq_pack --compat-bf16 of a GGUF key + /// the native kernel also reads, e.g. OrcaRouter's IQ3_XXS) serves the PLE from that row, so it is taken out + /// of `skip` and `load` does not upload the GGUF key over it. A quantized row leaves `skip` unchanged. + static bool keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, std::string& err); + uint64_t weight_bytes() const { return bytes_; } + size_t tensor_count() const { return weights_.size(); } + +private: + std::vector weights_; + void* scratch_ = nullptr; + uint64_t bytes_ = 0; +}; +} // namespace strata::core diff --git a/engine/strata/include/strata/core/native_head.hpp b/engine/strata/include/strata/core/native_head.hpp new file mode 100644 index 00000000..ff45dd6e --- /dev/null +++ b/engine/strata/include/strata/core/native_head.hpp @@ -0,0 +1,68 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata::core { + +/// Opt-in native output projection. Uploads unchanged GGUF blocks once at startup and owns its +/// activation scratch. The normal canonical head remains available for numerical A/B comparisons. +/// Plan v0.3 P6: any type the native MMVQ takes (Q5_K in the Q2_0 / IQ3_XXS files, IQ4_XS in IQ2_XS). +/// `load` takes the model's shards (strata::gguf_split_paths): the architecture is checked on the first, the +/// tensor is read from the shard that holds it. +class NativeHead { +public: + NativeHead() = default; + ~NativeHead(); + NativeHead(const NativeHead&) = delete; + NativeHead& operator=(const NativeHead&) = delete; + + bool load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err); + bool run(const float* mixed, float* logits, void* stream, std::string& err) const; + uint64_t weight_bytes() const { return bytes_; } + bool loaded() const { return weights_ != nullptr; } + /// Plan v0.3 P6: the GGUF blocks, for the verify window's multi-column head. + const void* weights() const { return weights_; } + int type() const { return type_; } + /// Bytes of one vocabulary row. + size_t row_bytes() const { return n_out_ > 0 ? (size_t) (bytes_ / (uint64_t) n_out_) : 0; } + +private: + void* weights_ = nullptr; + void* scratch_ = nullptr; + uint64_t bytes_ = 0; + int n_in_ = 0, n_out_ = 0; + int type_ = -1; +}; + +/// Plan v0.3 P6: `token_embd.weight` in its GGUF form (the IQ model files), in mapped pinned host memory: a row +/// is read over PCIe per token, so the table costs no VRAM. `embed_row`, the verify window and the MTP drafter +/// use it instead of the canonical table when it is set (`set_native_embed`). +class NativeEmbed { +public: + NativeEmbed() = default; + ~NativeEmbed(); + NativeEmbed(const NativeEmbed&) = delete; + NativeEmbed& operator=(const NativeEmbed&) = delete; + bool load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err); + /// Rows for device token ids. + void gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const; + /// One row for a host token id. + void gather_one(int64_t token, float* out, void* stream) const; + uint64_t bytes() const { return bytes_; } + int type() const { return type_; } + +private: + void* host_ = nullptr; + const void* dev_ = nullptr; + uint64_t bytes_ = 0; + size_t row_ = 0; + int64_t n_embd_ = 0, n_vocab_ = 0; + int type_ = -1; +}; +void set_native_embed(const NativeEmbed* e); +const NativeEmbed* native_embed(); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/on_device.hpp b/engine/strata/include/strata/core/on_device.hpp new file mode 100644 index 00000000..ed876f46 --- /dev/null +++ b/engine/strata/include/strata/core/on_device.hpp @@ -0,0 +1,22 @@ +#pragma once +// Multi-GPU: make `device` current for a scope and restore the caller's device after it. An object that owns CUDA +// streams, graphs and buffers on one device (a verify stage, the drafter) wraps its public calls in this, so the +// caller's thread may be on any device. A negative device, or the device already current, does nothing. + +#include + +namespace strata::core { + +struct OnDevice { + int previous = -1; + explicit OnDevice(int device) { + int cur = 0; + if (device >= 0 && cudaGetDevice(&cur) == cudaSuccess && cur != device && cudaSetDevice(device) == cudaSuccess) + previous = cur; + } + ~OnDevice() { if (previous >= 0) cudaSetDevice(previous); } + OnDevice(const OnDevice&) = delete; + OnDevice& operator=(const OnDevice&) = delete; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/pinned.hpp b/engine/strata/include/strata/core/pinned.hpp new file mode 100644 index 00000000..d98951fa --- /dev/null +++ b/engine/strata/include/strata/core/pinned.hpp @@ -0,0 +1,133 @@ +// include/strata/core/pinned.hpp - P2.S1: the host arena the expert weights live in. +// +// 33.97 GB of expert weights cannot fit in a 12 GB card, so they stay in host memory and are streamed. That +// makes this arena the engine's real working set: it must be PAGE-LOCKED for the copy engine to reach full +// bandwidth, and it must say which backing it got, because the two options differ by more than twice in TLB +// reach: +// +// * LARGE PAGES (2 MB) - `mmap(MAP_HUGETLB)` / hugetlbfs on Linux, `VirtualAlloc(MEM_LARGE_PAGES)` on +// Windows. 33.97 GB at 4 KB pages is 8.3 million TLB entries, which does not fit in any TLB, so every +// block of every expert matvec takes TLB misses. +// * NORMAL PAGES - the fallback. Correct, slower, and it must be REPORTED rather than silently accepted: +// "the engine adapts to the machine it is on" is only true if the engine says what it got. On Windows +// large pages additionally need SeLockMemoryPrivilege, which a normal user account does not have, so this +// fallback is the common case and not an error path. +#pragma once + +#include +#include +#include + +namespace strata::core { + +enum class PageBacking { LargePages, NormalPages, PinnedByCuda }; + +/// #243: STRATA_ARENA_PIN_GIB, the cap on the expert arena's CUDA registration in GiB. -1 when unset (the engine +/// decides, as in 0.1.30), 0 = no cap (the whole arena, or as many slices as the driver takes), N > 0 = at most N GiB, +/// -2 for "auto" (Windows: the sliced pin stays below the GPU's shared-memory budget). +int arena_pin_cap_gib(); + +struct PinnedArena { + void* base = nullptr; + uint64_t capacity = 0; + PageBacking backing = PageBacking::NormalPages; + std::string note; // why the backing is what it is, for the startup print + uint64_t locked_bytes = 0; // resident via the working-set lock when CUDA could not pin it + /// Plan v0.3 P5: when the whole arena cannot be registered, it is registered in `slice`-byte pieces from the + /// start; this is the pinned prefix (a copy that stays inside one slice can then DMA straight from the arena). + uint64_t registered_bytes = 0; + uint64_t slice_bytes = 0; + int registered_slices = 0; + + PinnedArena() = default; + /// `slice`: the piece size for the per-slice registration fallback (0 = none). + explicit PinnedArena(uint64_t bytes, uint64_t slice = 0); + /// Plan v0.3 P6: slices of different sizes (one per layer of a native pack), given as their start offsets + /// followed by the end of the last one. `slice_starts` holds the registered ones. + /// `max_pinned_bytes`: optional cap on CUDA registration. 0 preserves the normal unrestricted path. + /// `shared_file`: on Linux, use a file-backed MAP_SHARED mapping instead of anonymous memory. + /// `shared_pack_hash` identifies the pack that is allowed to populate that backing. The file carries a + /// small header and is refused when its stored hash does not match. Empty `shared_file` preserves the + /// existing allocation path. Population/coordination and backing-file lifetime remain the caller's job. + PinnedArena(uint64_t bytes, const std::vector& bounds, uint64_t max_pinned_bytes = 0, + const std::string& shared_file = {}, uint64_t shared_pack_hash = 0); + std::vector slice_starts; + void* mapping_base = nullptr; ///< actual mapping start; differs from base when a shared-file header exists + uint64_t mapping_bytes = 0; ///< bytes to release from mapping_base + ~PinnedArena(); + PinnedArena(const PinnedArena&) = delete; + PinnedArena& operator=(const PinnedArena&) = delete; + + bool valid() const { return base != nullptr; } + uint8_t* data() const { return (uint8_t*) base; } +}; + +struct LoadStats { + double seconds = 0.0; + // Loader fix: the two halves of `seconds`, both SUMMED OVER THE READER THREADS rather than wall clock, so + // either can exceed `seconds` when the threads overlap. They exist to separate the read from the copy and + // the hash: an 8 MiB chunk that reaches the disk as ~2048 4 KiB reads spends its time in the first one. + double read_seconds = 0.0; // inside the read call only: no seek, no copy, no hash + double copy_seconds = 0.0; // memcpy + FNV-1a + // A short read is not a slow load, it is a WRONG one: the caller must refuse the pack rather than run + // on an arena whose tail was never written. `seconds` alone cannot say that (it is -1.0 on failure, but + // the caller's own check is on the REQUESTED byte count, which a refused read does not change). + bool ok = true; // false: the load failed, see `error` + std::string error; // why it failed, for the caller's message + uint64_t bytes = 0; + uint64_t layers = 0; + std::vector layer_checksums; // one FNV-1a per layer + double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; } + // Aggregate rate of the readers WHILE THEY WERE INSIDE THE READ CALL: `bytes` over the mean per-thread + // read time. `gib_per_second()` above divides the same bytes by the wall clock of the whole loop, which + // also contains the copy and the hash, so the two differ by how much of the loop was not I/O. + double read_gib_per_second(int threads) const { + if (read_seconds <= 0.0 || threads < 1) return 0.0; + return (double) bytes / (1024.0 * 1024 * 1024) / (read_seconds / (double) threads); + } +}; + +// Load `layers` layers of the expert arena into `dst` with `threads` readers, `chunk` bytes at a time. +// Each thread opens its OWN handle and seeks, which is the portable form of parallel pread: a shared handle +// needs a lock around the seek and defeats the parallelism on Windows. +// +// The reads go through `fread()` on a per-thread `FILE*`, NOT through `std::ifstream`. MSVC's +// `basic_filebuf::xsgetn` splits every request larger than `_INTERNAL_BUFSIZ - 1` into 4095-byte `fread()` +// calls, so an 8 MiB `chunk` reached the disk as ~2048 4 KiB operations and the chunking did nothing at all +// (measured on a 42.9 GB pack: 1222 s, 4096 bytes per operation, 0.03 GiB/s). `fread()` hands a request +// larger than the stream buffer straight to `_read()`/`ReadFile()`, which is what `chunk` is for. The +// control flow, the copy, the per-layer FNV-1a and therefore the checksums are unchanged, so a pack loaded +// by the old and the new reader must produce identical `layer_checksums`. +LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, + uint64_t layers, int threads, uint64_t chunk); +/// Plan v0.3 P6: the same with one byte range per layer (`layer_off[L]`, `layer_bytes[L]`). +LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, + const std::vector& layer_bytes, int threads, uint64_t chunk); + +// FNV-1a 64. Per layer, so a corrupt or short read names WHICH layer rather than just failing a whole-file +// comparison - the same reason the Phase 1 tools report the first differing element. +uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed = 1469598103934665603ull); + +// ---- the expert stream ----------------------------------------------------- +// +// THIS IS THE NUMBER THE OBJECTIVE DEPENDS ON. With one expert per stream, the design's own arithmetic is: +// +// per token: E = 663.6 MB of expert weights, of which only the MISSES cross the bus +// miss fraction (1 - h) x 663.6 MB / measured bandwidth = milliseconds per token +// +// So `h` (the VRAM hit rate, ~0.167 by design) is only worth anything if a per-expert transfer can actually +// reach the bus's bandwidth. A 1,382,400-byte copy is SMALL, and if small copies run at a fraction of large +// ones then the architecture's central constant is wrong and no kernel optimisation can fix it. That is what +// this measures: the same total bytes at several granularities, so the difference is visible. +struct StreamStats { + double seconds = 0.0; + uint64_t bytes = 0; + uint64_t chunk = 0; + double gib_per_second() const { return seconds > 0 ? (double) bytes / (1024.0 * 1024 * 1024) / seconds : 0.0; } +}; + +// Copy `bytes` from pinned host memory at `src` to a device buffer of `chunk` bytes, in `chunk`-sized +// transfers, `iters` times. The destination is REUSED, so this measures the bus and not allocation. +StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/progress.hpp b/engine/strata/include/strata/core/progress.hpp new file mode 100644 index 00000000..46c93783 --- /dev/null +++ b/engine/strata/include/strata/core/progress.hpp @@ -0,0 +1,59 @@ +// include/strata/core/progress.hpp - issue #29: whether a request is still moving, and where it is. +// +// The engine's host loop and the GPU wait on each other through flags; a protocol bug there does not crash, it +// spins forever (the GPU "100%", one CPU core busy, no tokens). `--serve` runs a watchdog thread over this: a +// request whose heartbeat stops for `STRATA_WATCHDOG_S` seconds (default 60; 0 = off) ends the engine with the +// stage it was stuck in, and the server starts it again instead of hanging. Tokens, prompt chunks and verify +// windows beat; the stage is two relaxed stores per layer, which the token path does not notice. +#pragma once + +#include +#include +#include +#include + +namespace strata::core { + +struct Progress { + std::atomic beats{0}; + std::atomic busy{false}; + std::atomic where{"idle"}; + std::atomic detail{-1}; + std::atomic chunk{-1}; ///< #251: the prompt chunk (its first position) a batched-read stage is in + std::atomic since_ms{0}; ///< when `where` was set (steady clock): how long a stage has lasted + std::atomic ticks{0}; ///< layers served: a window that still moves, slowly, against one that stopped +}; + +inline int64_t progress_now_ms() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} + +/// What the watchdog prints about a part of the engine when it fires (the expert pool, the verify window). +using DiagFn = void (*)(std::FILE*); +inline std::atomic& diag_pool_fn() { static std::atomic f{nullptr}; return f; } +inline std::atomic& diag_verify_fn() { static std::atomic f{nullptr}; return f; } +/// #267: what a path that ends the engine runs first - it releases the GPU's spin waits on host flags (the verify +/// window's), so no kernel stays resident while the process goes away (on Windows that left the GPU "lost"). +inline std::atomic& release_gpu_fn() { static std::atomic f{nullptr}; return f; } +inline void release_gpu_waits(std::FILE* f) { + if (auto fn = release_gpu_fn().load()) fn(f); +} + +inline Progress& progress() { + static Progress p; + return p; +} + +inline void progress_at(const char* where, int64_t detail = -1, int64_t chunk = -1) { + Progress& p = progress(); + p.where.store(where, std::memory_order_relaxed); + p.detail.store(detail, std::memory_order_relaxed); + p.chunk.store(chunk, std::memory_order_relaxed); + p.since_ms.store(progress_now_ms(), std::memory_order_relaxed); +} + +inline void progress_beat() { progress().beats.fetch_add(1, std::memory_order_relaxed); } +inline void progress_tick() { progress().ticks.fetch_add(1, std::memory_order_relaxed); } + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/remote_experts.hpp b/engine/strata/include/strata/core/remote_experts.hpp new file mode 100644 index 00000000..805bc950 --- /dev/null +++ b/engine/strata/include/strata/core/remote_experts.hpp @@ -0,0 +1,85 @@ +#pragma once + +#include "strata/core/expert_cache.hpp" +#include "strata/core/expert_source.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::core { + +/// A static, profile-filled expert tier on another CUDA device. CUDA0 keeps all +/// dense weights and state; results return through the existing pinned CPU rows. +class RemoteExperts { +public: + RemoteExperts() = default; + ~RemoteExperts(); + RemoteExperts(const RemoteExperts&) = delete; + RemoteExperts& operator=(const RemoteExperts&) = delete; + + /// Initialise the device before the host expert arena registers + /// tens of GiB of portable mapped memory with CUDA. + static bool preflight(int device, double& free_gib, std::string& err); + bool open(int device, int slots, int64_t layers, int64_t experts, + const std::vector>& ranked, + const ExpertCache& primary, ExpertSource& source, + std::vector& claimed, std::string& err); + void close(); + + /// `kind` is the primary verifier's classification (-1 = CPU candidate), + /// or null on the one-token path. Entries already served on CUDA0 are excluded. + bool begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, + int64_t k, const int32_t* kind, const int32_t* primary_res, + std::string& err); + bool owns(int64_t index) const { return owned_[(size_t) index] != 0; } + bool finish(float* out, std::string& err); + int64_t resident() const { return cache_.resident(); } + int64_t computed() const { return computed_; } + int64_t launched_layers() const { return launched_layers_; } + double gib() const { return cache_.gib(); } + uint64_t returned_bytes() const { return returned_bytes_; } + uint64_t full_row_bytes() const { return full_row_bytes_; } + /// host time spent in begin() (staging + launches) and in finish() (waiting for this GPU), cumulative + double ms_begin() const { return ms_begin_; } + double ms_wait() const { return ms_wait_; } + +private: + int device_ = -1; + int64_t n_expert_ = 0; + int32_t groups_ = 0; + int64_t computed_ = 0; + int64_t launched_layers_ = 0; + uint64_t returned_bytes_ = 0; + uint64_t full_row_bytes_ = 0; + double ms_begin_ = 0, ms_wait_ = 0; + ExpertCache cache_; + cudaStream_t stream_ = nullptr; + float* h_x_ = nullptr; + float* h_out_ = nullptr; + void* h_meta_ = nullptr; + float* d_x_ = nullptr; + float* z_x_ = nullptr; ///< h_x_ as the helper GPU sees it (zero-copy: no input copy per layer) + float* z_out_ = nullptr; ///< h_out_ as the helper GPU sees it (zero-copy: no result copy) + bool zero_copy_ = false; + float* d_out_ = nullptr; + uint8_t* d_q8_ = nullptr; + float* d_scales_ = nullptr; + void* d_scratch_ = nullptr; + void* d_meta_ = nullptr; ///< one contiguous upload of grouped indices, instead of five small copies + int32_t* d_start_ = nullptr; + int32_t* d_dst_ = nullptr; + int32_t* d_tok_ = nullptr; + int32_t* d_count_ = nullptr; + unsigned long long* d_ptr_ = nullptr; + std::vector owned_; + std::vector layers_present_; + std::vector group_of_, group_id_; + std::vector start_, dst_, tok_, original_row_; + std::vector ptr_; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/session.hpp b/engine/strata/include/strata/core/session.hpp new file mode 100644 index 00000000..6d1becfa --- /dev/null +++ b/engine/strata/include/strata/core/session.hpp @@ -0,0 +1,435 @@ +// include/strata/core/session.hpp - ONE TOKEN through all 48 layers, and the doorbell protocol between them. +// +// P2.S5's host loop, and the first place the engine runs a whole forward pass rather than one block. What it +// owns is the ORDER across layers and the state that outlives a layer: +// +// * the gated residual stack `R` - (hc, n_embd), which every block reads and writes; +// * 12 QSA states (KV cache + indexer) and 36 GDN states (recurrence + conv history), because `is_qsa_layer` +// splits the 48 layers 12/36 and the two kinds of state have nothing in common; +// * the per-token expert handoff, which is where the CPU pool meets the GPU. +// +// WHY THE LAYER GRAPHS ARE CAPTURED AND THE LOOP IS NOT. A graph bakes in its arguments, so the graph unit is +// ONE LAYER: everything per-token (the position, the step counts) arrives through fixed-address device buffers +// (rounds 211-214), and the HOST decides when each layer runs. That decision is the whole point - it is what +// lets the CPU expert pool start while the GPU is still working on the next layer. +#pragma once + +#include "strata/core/hit_hook.hpp" +#include "strata/core/layer.hpp" + +#include + +#include +#include +#include + +namespace strata::core { + +/// Everything a sequence needs that is NOT a weight: the per-layer state, the block scratch, and the pinned +/// handoff between the GPU and the CPU expert pool. +struct SessionState { + int64_t max_cells = 0; + + GdnBuffers gdn; ///< the 36 GDN layers share one set of scratch; their STATE is per layer + float* gdn_state = nullptr; ///< (n_gdn_layers, gdn_state_floats) + + QsaState* qsa_states = nullptr; ///< one per QSA layer + void* qsa_state_arena = nullptr; + QsaBuffers qsa_bufs; ///< scratch, shared across the 12 (they never run concurrently) + void* qsa_buf_arena = nullptr; + + MoEBuffers moe; + void* moe_arena = nullptr; + BlockBuffers block; + void* block_arena = nullptr; + + float* R = nullptr; ///< alias of `block.R`, named for what it means at this level + int64_t k = 10; ///< experts per token + + // **THE LAYER-RANGE CARVE (multi-GPU).** A split stage's session used to carve state for ALL 48 layers + // (every QSA KV pool at max_cells, every GDN recurrence) while running only its slice - the same + // whole-model-sized-buffer disease the QSA chunked-prefill PR cured upstream. A session now owns + // [layer_lo, layer_hi): `qsa_states`/`gdn_state` keep GLOBAL ordinal indexing, the arrays simply hold + // fewer rows, so per-layer consumers subtract `gdn_ord0`, and every old model-level `qsa_states[0]` use + // (the shared RoPE table, the prefill staging identity, the MTP rope borrow) reads `qsa_states[primary]`. + // A range with no QSA layer still carves ONE primary state so those model-level uses stay valid. + int64_t layer_lo = 0, layer_hi = 0; ///< resolved by `session_init` (hi = n_layers for the full range) + int64_t qsa_ord0 = 0; ///< global QSA ordinal of the first allocated state + int64_t qsa_alloc = 0; ///< allocated QSA states (>= 1 whenever the model has any) + int64_t gdn_ord0 = 0; ///< global GDN ordinal of `gdn_state` row 0 + int64_t gdn_alloc = 0; ///< allocated GDN rows + int qsa_primary() const { return (int) qsa_ord0; } + /// The doorbell the host loop polls. Null until a caller provides one - the engine runs without it, and + /// neither `session_token` nor `session_replay` looks at it. + const Doorbell* db = nullptr; + + // ================================ THE PLE, AND IT IS SEQUENCE STATE ================================ + // + // **THE PLE IS A LAYER-1 MODULE AND THIS ENGINE DID NOT RUN IT, WHICH IS WHY C1 FAILED** (LEDGER L123). + // Every part of it was already built and parity-tested - the hash against `ref/ngram.py` with the + // artifact's own constants, the IQ4_NL row read against numpy over the original GGUF, and the block + // against ggml's own graph - and none of it was ever called from the model path. These fields are what + // was missing on the state side. + // + // `ple_prev` is the last two tokens OLDEST FIRST with `-1` where there is none, which is exactly + // `ngram_rows`' `prev` argument; `ple_token` is the token being decoded. **They are advanced by the + // DRIVER, once per token**, because the hash is a function of the sequence and not of a layer. + int32_t ple_prev[2] = {-1, -1}; + int32_t ple_token = -1; + /// `NG_HIST` rows of `hc_dim` NORMALIZED history, **ROW-FASTEST**: `ple_hist[row + NG_HIST*channel]`. + /// That is `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`, not a layout choice - the transposed + /// reading fails ggml's own assert (`ple_layer_xcheck.cpp` L79-83). + float* ple_hist = nullptr; + /// **THE WHOLE PLE RUN LIVES HERE, AND THAT IS NOT A CONVENIENCE.** Its history and its token window are + /// sequence state, so the session is where they belong - and putting the rest of it here too means + /// `session_capture`/`session_loop`/`session_token` need no new parameter to reach it. A `PleRun` whose + /// `ready()` is false is skipped, which is what every caller had before LEDGER L123. + PleRun ple; +}; + +/// Bytes for a whole session at `max_cells` of context. Every layer's state is sized at once, because P2.T10 +/// requires ZERO token-path allocations - a `cudaMalloc` that happened on the first token of a longer sequence +/// would satisfy every test here and fail that one. +/// +/// [layer_lo, layer_hi) carves only that range's per-layer state (a split stage runs a slice of the model); +/// the default full range is byte-identical to the old whole-model carve. Pure arithmetic - safe to call for +/// a candidate range before anything is allocated, which is how the layer-split search prices a placement. +uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo = 0, + int64_t layer_hi = -1); +/// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`. +uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, + int64_t layer_lo = 0, int64_t layer_hi = -1); +/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the +/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory. +void session_release(SessionState& s); +/// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts +/// from the reference's own `zeros()`. +void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream); + +/// One token: layers 0..47 in order, each a `block_layer`, and the residual is updated in place. +/// +/// `parts` is (k, n_embd) DEVICE memory, filled by the caller - by the CPU expert pool and the VRAM-resident +/// experts. In this phase `moe_layer` consumes it directly; the doorbell protocol's job is to let it be +/// produced DURING the layer rather than before it, which is a change to *when* the host runs, not to what this +/// function computes. +/// +/// `sync_every_layer` inserts a device synchronisation and an error check after EVERY layer. That is the +/// `--sync-every-layer` debug mode, and it is deliberately a parameter rather than a compile-time choice: the +/// errors it catches (a kernel reading a buffer that a later layer writes) are invisible otherwise, and the +/// synchronisation it costs is exactly what P2.X3 forbids in the fast path. +bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base, + SessionState& s, const float* parts, void* stream, bool sync_every_layer, + std::string& err); + +// ================================ the captured form ================================ + +/// ONE GRAPH PER LAYER, because a graph bakes in its POINTERS and every layer has different weights AND +/// different state. That is not a limitation to work around - it is what makes the per-layer graph the right +/// unit: the host decides when each layer runs, which is what lets the CPU expert pool start while the GPU is +/// still working on the next one. +/// +/// WHY THIS IS WORTH DOING, MEASURED: **the engine is launch-bound, not bandwidth-bound.** Every kernel in +/// `gdn_layer` measured ~0.028 ms - including `gdn_gate`, which processes FORTY-EIGHT elements, and a kernel +/// cannot execute for 28 us. That is what a null-stream launch costs on this driver, and `gdn_layer` makes ~19 +/// of them while a block makes ~45. Replaying the 43-node block graph measured **1.585 ms against 2.393 ms** +/// for the same work as direct launches - a 1.51x that is pure launch overhead. +struct SessionGraphs { + cudaGraphExec_t* execs = nullptr; ///< one per layer, in layer order + int64_t n = 0; + /// **THE SECOND GRAPH PER LAYER: `moe_finish` + `gr_write`, launched AFTER the host has run the pool.** + /// + /// Without it the loop has to hand layer `l`'s expert vectors to layer `l+1`, which multiplies them by + /// layer `l+1`'s router weights - see `layer.hpp`'s note on `moe_route`. With it, `post[l]` is launched + /// after the pool returns, so layer `l`'s experts are combined with layer `l`'s weights. + /// + /// The cost is the overlap, and it is worth stating: the window is now whatever GPU work follows the ring + /// inside `pre[l]` - the shared expert, and nothing else, because everything after the combine depends on + /// `parts`. **A per-layer CPU pool cannot be hidden behind a strictly serial residual chain**, which is + /// why the CPU term is answered by Phase 3's VRAM cache and not by this pipeline. + cudaGraphExec_t* posts = nullptr; + bool captured = false; + /// THE DEVICE ADDRESS THE GRAPHS WERE CAPTURED WITH. The host loop copies each layer's expert outputs + /// here before launching the next layer, and a graph bakes the POINTER, so it has to be this one. + float* parts_dev = nullptr; + + /// **DIAGNOSTIC, AND IT IS THE ONE THAT SAYS WHETHER THE DOORBELL IS DECORATIVE.** + /// + /// Counts the layers where the ring was observed while the graph was STILL RUNNING - i.e. the layers where + /// the pool actually had a window to work in. A nonzero `h_seq` read at the same moment + /// `cudaEventQuery` returns `cudaSuccess` means the layer was already over, and the pool then runs with the + /// GPU IDLE, which makes the whole pipeline equivalent to a serialised one. + /// + /// That distinction is invisible in the loop's RETURN VALUE - both paths produce a correct token - and it + /// is invisible in a per-layer timing, because the layer still takes the same time either way. It shows up + /// only as "the overlap hides nothing", which is why it is counted here. + int64_t rings_mid_graph = 0; + + /// **THE WINDOW, MEASURED RATHER THAN ASSUMED.** Milliseconds from `cudaGraphLaunch` to the moment the + /// ring was observed, summed over the loop. The pool's window is `layer period - this`, and that is the + /// entire budget the overlap has: if the CPU's per-layer work exceeds it, the GPU goes idle for the + /// difference on every layer and a "pipelined" loop measures the same as a serialised one. + /// + /// It is NOT the same as the doorbell's position inside the graph. It includes the launch itself, the + /// driver's submission, and however long the host took to notice - all of which are real and none of which + /// the pool gets to use. + double ms_to_ring = 0; + + // ================================ R0.9: THE LAYER AS THREE GRAPHS ================================ + // + // **THE CAPTURED PER-STAGE TABLE THE PROTOCOL HAS DEMANDED SINCE R0 AND NOBODY HAS HAD.** Round 309's + // came from `--no-capture`, and round 312 showed its `moe_finish` figure was a host-gap artefact four + // times the captured cost of the same work - so the plan has been choosing between R3.3, R3.4 and R3.5 + // without knowing what any of them is worth. + // + // An event recorded BETWEEN two `cudaGraphLaunch` calls is not inside a capture and is therefore valid, + // so the layer is captured at its own documented seam (`block_layer_pre`'s `half`) and timed from outside. + /// **R0.11: FIVE PREFIX GRAPHS, ADDED BESIDE `preA`/`preB` RATHER THAN REPLACING THEM.** + /// `preP[k]` (k = 1..5) runs stages `0..k-1`. Consecutive differences are the per-stage times, which is + /// what prices the two `gr_read`s and the `gr_write` (R3.3) against GDN's interior (R3.4). A prefix and not + /// a range, because the stages are a chain: stage 1 reads what stage 0 wrote and stage 2 mutates the + /// residual in place. + /// + /// **THE FIFTH PREFIX USED TO BE `execs[l]`, AND THAT WAS THE BUG ROUND 324 COULD NOT FIND.** Prefix 5 + /// has ~7 more nodes than prefix 4, so the two differ in launch setup as well as in execution - and the + /// difference attributed ALL of it to stage 4, the router. Capturing prefix 5 the same way as the others + /// makes the two comparable and the difference purely stage 4's. + cudaGraphExec_t* preP[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; + cudaGraphExec_t* preA = nullptr; ///< `half == 1`: gr_read -> attention -> gr_write (the MIXER) + cudaGraphExec_t* preB = nullptr; ///< `half == 2`: gr_read -> moe_route (FFN front + ROUTER) + bool split_captured = false; + + /// How many times `session_loop` has run. `rings_mid_graph` and `ms_to_ring` are CUMULATIVE and the loop + /// is called once per token, so anything reporting a ratio needs this - and prefill runs the loop too, so + /// "per generated token" is the wrong denominator. + int64_t calls_total = 0; + + /// **WHERE THE PER-LAYER ROUND TRIP GOES, AND `ms_to_ring` ALONE CANNOT SAY.** + /// + /// `--no-pool` measures **38.73 ms/token against a 26.32 ms pure-GPU floor**, so ~12.4 ms/token - a quarter + /// of the token - is spent in the loop with no expert work at all: 0.258 ms per layer. `ms_to_ring` covers + /// only the first half of that; it stops when the ring is seen, and everything the host then does before + /// the next `pre` is launched is invisible to it. + /// + /// So the round trip is split at the ring, and **`ms_to_ring` above IS the first half** - do not add a + /// second counter for it: + /// + /// * `ms_to_ring` - launch -> ring observed. The GPU is working (or already finished) here. + /// * `ms_host` - ring observed -> `pre[l+1]` launched. **The GPU has nothing queued and is IDLE for + /// all of this unless `pre[l]`'s tail still covers it.** This is + /// `cudaMemcpyAsync(parts)` + `cudaGraphLaunch(post[l])` + `cudaGraphLaunch(pre[l+1])` + + /// `cudaEventRecord`, and if it is the large half then the fix is fewer driver calls + /// (R2.4), not a faster kernel. + /// + /// Cumulative, like `ms_to_ring`; divide by `calls_total * n_layers`. + double ms_host = 0; +}; + +/// Captures all 48 layer graphs. Idempotent: a second call is a no-op. +/// +/// `pos`/`pos_base` are baked in ONLY through the fixed-address pinned staging in each `QsaState`, which the +/// replay re-reads every token - so the position is data, not an argument. That is the whole reason rounds +/// 211-214 moved the per-token counts into device buffers. +bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts, + SessionGraphs& gr, std::string& err, bool split = false, int64_t layer_lo = 0, + int64_t layer_hi = -1); + +/// One token by REPLAYING the captured graphs. Identical arithmetic to `session_token`; the only difference is +/// that ~2,000 kernel launches become 48 graph launches. +bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, + void* stream, std::string& err); + +/// One token by replaying BOTH halves of every layer - `pre[l]` and `post[l]` - with no pool running. +/// +/// **THIS IS THE TRUE PER-TOKEN GPU FLOOR, AND `session_replay` IS NOT.** `session_replay` launches only +/// `gr.execs[l]`, the `pre` graphs, so it omits the 48 `post` graphs (shared expert, combine, second `gr_write`) +/// entirely - and everything published as "39.8 ms pure GPU" came from it while being described as the whole +/// GPU. See `Memory/ERRORS.md` A4. +/// +/// `parts` is left at whatever the buffer holds, because no pool writes it; that is deliberate and makes the +/// measurement pure GPU work. The LM head is NOT included here - the caller times it separately, since it runs +/// on the host-side path rather than inside a captured graph. +bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::string& err); + +/// **ONE TOKEN THROUGH THE SPLIT GRAPHS, WITH EVERY STAGE TIMED FROM OUTSIDE THE CAPTURE.** Requires +/// `session_capture(..., split = true)`. Replays `preA[l]`, `preB[l]`, `post[l]` in order on one stream - +/// the same order `session_loop` uses - and reports the three totals in milliseconds for the whole token. +/// +/// The stages are ordered by the stream, so an event pair around each launch measures that launch's GPU work +/// plus the gap the driver left before it. That gap is real and is why the three totals sum slightly above +/// `session_replay_full`; the comparison is printed by the caller rather than hidden here. +/// **R0.11: THE FIVE STAGES SEPARATELY, BY DIFFERENCING PREFIXES.** `stage_ms` is resized to 5 and holds +/// stages 0..4 in milliseconds for a whole token; `mixer_per_layer` holds prefix 3's time for each layer, which +/// is what R0.10's GDN-versus-QSA split needs. Requires `session_capture(..., split = true)`. +/// +/// **THE RESIDUAL IS SAVED AND RESTORED BETWEEN PREFIXES.** Stage 2 is `gr_write`, which mutates `R` in +/// place, so without the restore every prefix after the first reads a residual the earlier ones already +/// advanced - and every number after the first would be measuring a different tensor while looking correct. +bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::vector& stage_ms, + std::vector& mixer_per_layer, std::string& err); + +/// **R3.5c: ONE PREFIX, ALL 48 LAYERS, BACK TO BACK.** `k` in 1..5 replays `preP[k-1][l]` (or `execs[l]` for +/// k = 5) for every layer with no other graph in between, and reports the whole sweep in milliseconds. +/// +/// **WHY THIS EXISTS: TO RULE OUT THE PREFIX TABLE'S OWN BIAS.** The five-stage table differences prefix +/// times measured with FIVE DIFFERENT GRAPHS LAUNCHED PER LAYER. Stage 4's interval therefore contains the +/// launch of `execs[l]` - the full five-stage graph - while stage 3's contains `preP[3][l]`, a four-stage one. +/// A launch cost that scales with graph size would inflate stage 4 specifically, and stage 4 is the router, +/// which is the thing under investigation. This sweep launches ONE graph type per layer, so there is nothing +/// to switch between and nothing to attribute wrongly. +/// +/// Five separate sweeps give five totals; their consecutive differences are the stage times on the same +/// arithmetic as before, and **if the two methods disagree the difference is the bias and the sweep is right.** +bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, int k, double& ms, std::string& err); + +bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post, + std::string& err); + +/// **THE SAME REPLAY, KEEPING EVERY LAYER INSTEAD OF SUMMING THEM.** +/// +/// The 48 layers are not 48 of the same thing: 36 are GDN and 12 are QSA, and the mixer - 55.8% of the GPU +/// floor - contains both. A total cannot separate them; a per-layer vector can, and it is already being +/// measured. `out` is resized to `n_layers` and holds each layer's mixer time in milliseconds. +/// +/// **THIS IS THE CHEAPEST HALF OF R0.10 AND IT NEEDS NO NEW SPLIT.** Round 309's uncaptured table put GDN at +/// 10.88 ms for 36 layers and QSA at 4.56 for 12, which would make the recurrence the largest single R3 +/// target; that table also had `moe_finish` wrong by 4x, so the ratio is worth re-deriving from the captured +/// graph rather than inherited. +bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::vector& mixer_per_layer, + double& ms_ffn, double& ms_post, std::string& err); + +/// Releases the graph execs. The `SessionGraphs` struct holds no device memory of its own. +void session_graphs_free(SessionGraphs& gr); + +// ================================ THE HOST LOOP ================================ + +/// WHAT THE POOL HAS TO DO, as the loop sees it: given the `x_f` a layer published and the miss list it +/// selected, produce the `k` expert outputs into `out` (k x n_embd, HOST memory). A function pointer rather +/// than a virtual class because the loop is the thing under test and the pool is the thing being faked. +using PoolFn = void (*)(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, + int64_t k, float* out); + +/// **R4.2c: THE VRAM-RESIDENT HALF OF THE LAYER'S EXPERTS.** Called by the loop after the misses have been +/// staged into `parts` and before `post[l]` is launched, so its kernels are stream-ordered between them: the +/// misses are already in `parts`, the hits overwrite the rows the CPU zeroed, and `post[l]`'s `moe_combine` +/// reads the sum and cannot tell which engine produced which row. +/// +/// **WHY IT IS A CALLBACK RATHER THAN MORE PARAMETERS.** `session_loop` owns the ORDER across layers and has +/// no business knowing what an expert cache is. Everything the hit path needs lives on the caller's `user`, +/// and this has the same shape as `PoolFn` for the same reason. +/// +/// A null pointer means "no VRAM tier" - the default, and what every caller had before R4. +// The hit hook's type lives in its own header - see `hit_hook.hpp` for why and for the ordering it wants. + +/// `phases/phase-2-correct-engine.md` P2.S5's host loop, which is the point of everything above it: +/// +/// launch G[l] -> poll the doorbell -> read the miss list -> dispatch the pool -> wait for it -> +/// write y_miss -> launch G[l+1] +/// +/// **NO `cudaStreamSynchronize` IN THE LOOP**, which is P2.X3. Waiting is `cudaEventQuery` on an event recorded +/// right after the launch - a QUERY, and it is not optional: round 195 measured a host spin that only read +/// memory never running the kernel at all, 5,907,703 spins over 500 ms with the datum flipping only when +/// `cudaStreamSynchronize` was called. +/// +/// **THE OVERLAP IS THE ONE-LAYER DELAY.** A layer publishes `x_f` at ~71% of its own duration, so the pool has +/// the remaining 29% of that layer to work in; its result is consumed by the NEXT layer, which is why the +/// combine is not waiting on it. `overlap = false` runs the same sequence with a synchronisation after every +/// layer, which is the comparison that says whether the pipeline is worth its complexity - and it is a +/// parameter rather than a second function so that the two cannot drift. +/// +/// **`dump_layers`, WHEN NOT NULL, IS THE C1 ORACLE AND IT IS A HOST BUFFER OF `(n_layers + 1) * hc * n_embd` +/// FLOATS.** Slot 0 is the residual the function was ENTERED with - the token's embedding broadcast to every +/// stream, which is the reference's `hc_init` node - and slot `l + 1` is `s.R` after layer `l`, which is the +/// reference's `l_last-`. Each is enqueued as a device-to-host copy, and the final `cudaStreamSynchronize` +/// at the end of the loop is what makes every one of them complete. **NO EXTRA SYNCHRONISATION IS INSERTED**, +/// which is the whole reason this is written as an enqueue rather than a read: `pre[l+1]` does not write `R` and +/// `post[l+1]` is launched after the copy on the same stream, so FIFO order alone makes slot `l + 1` a true +/// snapshot. It costs 40 KB per layer per token, and it is the only way to bisect the engine against the +/// reference layer by layer instead of against one end-to-end perplexity. +/// Per-token scratch that MUST NOT be reallocated per token (P2.T10, review finding H3). +/// +/// **`session_loop` IS CALLED ONCE PER TOKEN, SO ANYTHING IT ALLOCATES IS A PER-TOKEN ALLOCATION.** It used to +/// allocate three things on every token of every run: +/// +/// * `cudaHostAlloc` for the pool's pinned staging, freed by an RAII destructor at the end of the call - and +/// `cudaFreeHost` IMPLICITLY SYNCHRONISES THE DEVICE, so every token ended with a device sync; +/// * `cudaEventCreate` / `cudaEventDestroy` for the doorbell probe; +/// * a host-affinity change (`physical_cores` + pin + restore). +/// +/// A comment in the old code said "allocated once", but once per token is not once. +/// +/// Own one of these at session setup and pass it in. **Passing `nullptr` keeps the old behaviour** - the loop +/// allocates and frees locally - so every existing caller and test is unaffected, but the allocation is then +/// visible at the call site instead of hidden inside a hot function. +struct SessionLoopScratch { + float* y_miss = nullptr; ///< pinned host staging for the pool's answer, `parts_bytes` long + size_t parts_bytes = 0; + cudaEvent_t probe = nullptr; + long long pinned_core = -1; ///< the affinity to restore, or -1 if the host was never pinned + bool pinned = false; + + /// Allocates the buffers and pins the host thread. Call ONCE, at session setup. + bool init(size_t parts_bytes_in, std::string& err); + /// Frees everything and restores the affinity. Safe to call twice, or on a default-constructed object. + void free(); +}; + +bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, + PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err, + float* dump_layers = nullptr, SessionLoopScratch* scratch = nullptr); + +// ================================ plan v0.3 P3: THE WHOLE TOKEN AS ONE GRAPH ================================ +// +// Under WDDM every graph launch costs ~0.3-0.4 ms of submission latency, and the per-layer loop above makes 96 +// of them per token: measured 48.6 ms/token for 12 ms of GPU kernels and 27 ms of pool. The token graph holds +// all 48 layers. Between `pre[l]` (which rings the doorbell) and the parts copy, a one-thread kernel waits ON +// THE DEVICE until the host writes the ring value into `db.h_flag`; the host only polls rings, runs the pool +// and writes flags, with no driver call in the loop (bench/micro/device_wait.cu: 5.2 us per handoff). +// +// for l: pre[l] (.. router, doorbell ring, shared expert) -> doorbell_wait -> parts <- y_miss (H2D) +// -> post[l] (combine, gr_write) +// +// Same kernels, same order per layer as `session_loop`, so the token is bitwise the same. No VRAM expert tier +// yet (the hit decision is a host step between ring and post); the caller falls back to `session_loop` then. +struct TokenGraph { + cudaGraphExec_t exec = nullptr; + bool captured = false; + int64_t n_layers = 0; + const float* y_src = nullptr; ///< the pinned host staging the graph's H2D copies read (baked in) + size_t parts_bytes = 0; + int64_t calls = 0; + double ms_wait = 0; ///< host waiting for rings (the GPU is running) + double ms_pool = 0; ///< host inside the pool + int64_t flushes = 0; ///< cudaStreamQuery calls made because a ring was slow to appear +}; + +/// Plan v0.3 P4: the VRAM expert tier inside the token graph. Residency is STATIC during a token (a +/// `n_layers x n_expert` table, slot or -1, on the device; the host pool reads its own copy), so the hit list +/// is built on the device right after the ring and the hits run while the CPU computes the misses. +struct TokenHits { + const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] + int64_t n_expert = 0; + const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena + int64_t blob = 0; ///< bytes per slot + int32_t* d_slot = nullptr; ///< device, k entries + int32_t* d_dst = nullptr; ///< device, k entries + int32_t* d_count = nullptr; ///< device, 1 + uint8_t* x_q8 = nullptr; ///< the activation's q8_0 blocks, (n_embd/32)*34 B + float* x_scale = nullptr; ///< and its fp32 scales (the CPU pool's contract) + void* scratch = nullptr; ///< moe_hit_grouped_scratch_bytes(k, ...) + float* hit_out = nullptr; ///< device, k * n_embd + bool on() const { return d_res && cache_base && d_slot && d_dst && d_count && x_q8 && x_scale && scratch && hit_out; } +}; + +bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev, + const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err, + const TokenHits* hits = nullptr); +bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg, + PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err); +void token_graph_free(TokenGraph& tg); + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/verify.hpp b/engine/strata/include/strata/core/verify.hpp new file mode 100644 index 00000000..29b064fb --- /dev/null +++ b/engine/strata/include/strata/core/verify.hpp @@ -0,0 +1,272 @@ +// include/strata/core/verify.hpp - plan v0.3 P6: the speculative VERIFY window. +// +// T tokens at consecutive positions p0 .. p0+T-1 - the last accepted token and T-1 drafts - go through all 48 +// layers in ONE captured graph, and the head's argmax is produced for every one of them. Token t's argmax is +// what plain greedy decode would produce after token t, BIT FOR BIT: every kernel here is either the single-token +// kernel applied per token, or a multi-token kernel whose per-token arithmetic is the single-token kernel's +// (multi-column MMVQ in exact mode, the T-token GDN kernels, the per-token hit activation, the multi-token CPU +// expert rows). So a draft is accepted exactly when greedy decode would have produced it. +// +// What the window costs is the dense weights read ONCE for T tokens and the union of the T tokens' missed +// experts on the CPU (measured on decode traces: 1.75x one token's misses for T=2, 2.4x for 3, 3.05x for 4). +// +// STATE. The window appends K/V and indexer keys for all T positions and leaves the GDN state untouched. +// `commit(n_keep)` then makes the first `n_keep` tokens permanent: the GDN conv history and recurrent state are +// advanced by replaying those tokens from inputs the window stored, the indexer's key tail is restored from a +// snapshot and the accepted keys re-appended (a rejected key can land in a slot the current block still needs), +// and the PLE history is set to its snapshot after token n_keep-1. K/V cells past the accepted prefix are simply +// overwritten when those positions are processed again, before any query can read them. +// +// Requires the default native decode configuration (native projections, fused GR, fused GDN, fast attention and +// selection, native indexer) and a profile-filled VRAM expert tier with its residency table on the device. +#pragma once + +#include + +#include "strata/core/expert_source.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/session.hpp" +#include "strata/kernels/sampler.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::core { + +class NativeHead; + +/// The CPU pool for a window: x_f (n_tok, n_embd), ids (n_tok, k) -> out (n_tok * k, n_embd), hit rows zeroed. +using PoolMultiFn = void (*)(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, + int64_t layer); + +struct VerifyHits { + const int32_t* d_res = nullptr; ///< device [n_layers * n_expert] slot or -1 + const uint8_t* cache_base = nullptr; ///< slot 0 of the VRAM expert arena + const uint64_t* slot_off = nullptr; ///< E-6: host per-slot offsets when slots differ in size (null: slot * blob) + int64_t n_slots = 0; ///< E-6: how many (for the device copy) + int64_t blob = 0; +}; + +class Verifier { +public: + Verifier() = default; + ~Verifier(); + Verifier(const Verifier&) = delete; + Verifier& operator=(const Verifier&) = delete; + + /// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags. + void diag(std::FILE* f) const; + + /// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU + /// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the + /// paths that give up on the engine (a timed-out window, the serve watchdog): the window then ran on whatever + /// the flags guarded, so this verifier refuses every later window. True when the streams finished. + bool release_gpu_waits(int timeout_ms); + + /// `max_t` <= kVerifyMaxT. `head` may be null (the canonical head is then run per token). + bool init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, + const NativeHead* head, int max_t, std::string& err); + + /// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t. + /// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use. + bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err); + /// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run(). + bool copy_logits(int t, float* host) const; + int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; } + /// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per + /// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its + /// parameters would otherwise be baked forever - so this can change between requests freely. + void set_sampling(const strata::kernels::SamplerParams& sp) { + sampling_ = sp; // row t of a window at pos0 draws Philox(seed, pos0 + t): see run() + if (next_) next_->set_sampling(sp); + } + + /// The penalty histories for `sampling_.penalty_last_n`: ONE ROW PER WINDOW ROW, T rows of `history_len` + /// int32 slots at that stride (`strata::kernels::penalty_rows` builds them), most recent token LAST, unused + /// front slots -1 (the kernel reads only the tail window). Row t follows the window's drafts 1..t - staging + /// row 0 alone (before 0.1.19) left the drafted rows with unwritten histories. Null disables the penalties + /// entirely - the neutral run's sampling call is byte-for-byte what it was. The engine re-uploads the rows + /// before every window; the buffer must hold kVerifyMaxT rows and stay alive across the request. + void set_history(const int32_t* history, int history_len) { + hist_d_ = history; + hist_len_ = history_len; + if (next_) next_->set_history(history, history_len); + } + /// Off: `run` skips the request's head sampling and `out` is the recorded greedy pick. For windows whose + /// picks are discarded - a prompt read through windows commits every token - so they cost no sampler launch + /// or sync and never read a history staged for another position. + void set_head_sampling(bool on) { head_sampling_ = on; if (next_) next_->set_head_sampling(on); } + + /// LAYER SPLIT (multi-GPU): this verifier runs layers [layer_begin, layer_end) of every window. A stage that + /// does not start at layer 0 takes its residual from `handoff_in` instead of embedding the tokens; a stage that + /// does not end at the last layer writes its residual to `handoff_out` and has no head. The hand-off holds, + /// per token, the residual R (hc x n_embd), the last layer's pending write bo (n_embd) and inject (hc): the next + /// stage folds that write into its first read exactly as the unsplit window does, so the split is bit-exact. + /// Both pointers must be device-visible (mapped pinned memory, portable when the stages are on two devices). + /// Set before `init`. Default: the whole model, no hand-off. + void set_stage(int64_t layer_begin, int64_t layer_end, const float* handoff_in, float* handoff_out) { + lb_ = layer_begin; le_ = layer_end; hand_in_ = handoff_in; hand_out_ = handoff_out; + } + /// The next stage: `run` and `commit` continue into it (its pool calls get `next_user`); sampling settings + /// and `final_R` are the last stage's. + void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; } + /// floats per token in a hand-off buffer + static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; } + + /// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them. + bool commit(int n_keep, std::string& err); + /// commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on + /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes + /// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt + /// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait. + static void set_commit_async(bool on); + /// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device); + /// false with `err` when it failed. Free when nothing is pending. + bool wait_commit(std::string& err); + + /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - + /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the + /// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of + /// `extra_id` in the same row, and the last column is the target's log-probability in that row renormalized + /// over every token but `extra_id` (both nan when they do not apply). A layer split's earlier stage forwards + /// to the stage that holds the head. + bool window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out, + std::string& err); + + /// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`. + const float* final_R(int t) const; + const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; } + + /// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the + /// dispatch (`ExpertDispatch::plan`) before the first `run`. + GpuPlanSink* plan_sink() { return &sink_; } + /// Plan v0.3 P6: split the window into two token groups and pipeline the CPU experts of one with the GPU work + /// of the other (default on). Set before the first `run`. + void set_split(bool on) { split_ = on; } + /// Plan v0.3 P6: how the PCIe share of the misses reaches the GPU: 0 = DMA into staging (the copy engine works + /// beside the CPU; best when the CPU is compute-bound, the i-quants), 1 = the grouped kernel reads the mapped + /// arena directly, 2 = a copy kernel stages it inside the graph (no API calls on the pool's thread; best when + /// the CPU is RAM-bound, Q2_0). Set before the first `run`. + void set_pcie_mode(int mode) { sink_.pcie_mode = mode; } + /// the pool never plans a PCIe share (--pcie-frac 0): the window skips that path. Before the first run. + + double ms_wait = 0, ms_pool = 0, ms_host = 0, ms_commit = 0; + int64_t windows = 0; + /// STRATA_VERIFY_PROFILE=1 - GPU stage times of the windows since the last call (ms per + /// window), as one line; empty when off. + std::string profile_report(); + +private: + bool capture(int T, std::string& err); + strata::kernels::SamplerParams sampling_ = [] { + strata::kernels::SamplerParams s; + s.greedy = true; + s.temperature = 0.0f; + return s; + }(); ///< greedy by default; per-request via set_sampling + const int32_t* hist_d_ = nullptr; ///< penalty-history row (set_history); null = no penalties apply + int hist_len_ = 0; + bool head_sampling_ = true; ///< set_head_sampling + int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) + std::atomic released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows + bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN) + uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's) + unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device + int64_t lb_ = 0, le_ = -1; ///< set_stage: the layers this verifier runs (-1: to the last) + const float* hand_in_ = nullptr; + float* hand_out_ = nullptr; + Verifier* next_ = nullptr; + void* next_user_ = nullptr; + bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs + bool capture_commit(std::string& err); + bool record_window(int T, cudaStream_t cs, std::string& err); + static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second + // half's up-stamp at slot 32 = the next layer's slot 0: D8) + bool prof_on_ = false; + unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps + std::vector prof_h_; + double prof_sum_[2][kProfPer] = {}; // [GDN / QSA layers][stage] + int64_t prof_windows_ = 0; + + const WeightTable* wt_ = nullptr; + const ModelGeometry* g_ = nullptr; + SessionState* ss_ = nullptr; + VerifyHits hits_; + const NativeHead* head_ = nullptr; + int max_t_ = 0; + int last_t_ = 0; + int64_t last_pos0_ = 0; + int32_t last_tokens_[8] = {}; + int64_t n_vocab_ = 0; + cudaStream_t cs_ = nullptr; + cudaGraphExec_t exec_[9] = {}; + cudaGraphExec_t commit_exec_ = nullptr; + + // mapped staging (host pointer, device alias) + int32_t* h_tok_ = nullptr; int32_t* m_tok_ = nullptr; // T + int32_t* h_step_ = nullptr; int32_t* m_step_ = nullptr; // T * kStepCount + int32_t* h_pos_ = nullptr; int32_t* m_pos_ = nullptr; // T * n_head + int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] + float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd + int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids + float* trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study + std::FILE* trace_file_ = nullptr; + float* trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer + std::FILE* trace_q_file_ = nullptr; + float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd + int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k + float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k + uint32_t* h_seq_ = nullptr; uint32_t* m_seq_ = nullptr; + uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr; + uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place + uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed + cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit + bool commit_pending_ = false; + cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) + struct FlagSet { uint32_t* flag; uint32_t value; }; + FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group) + static void fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes); + static void raise_flag(uint32_t* flag, uint32_t value); + int32_t* h_plan_ = nullptr; int32_t* m_plan_ = nullptr; // counts | start | dst | tok | ptr (as int32 pairs) + int64_t plan_i32_ = 0; // int32 words in the plan block + GpuPlanSink sink_; + uint32_t cur_layer_ = 0; + static void publish_plan(void* ctx); + void set_plan_slot(int grp); + bool split_ = false; // opt-in (--spec-split): exact but slower, see the overlap study + int groups_[9] = {}; + float* h_ymiss_ = nullptr; float* m_ymiss_ = nullptr; // T * k * n_embd + + // device + void* arena_ = nullptr; + int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *commit_ = nullptr; + float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr; + float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr; + uint8_t* xq_ = nullptr; // T columns of q8_1 + float *qkv_L_ = nullptr, *h_L_ = nullptr, *gate_L_ = nullptr, *beta_L_ = nullptr; // per GDN layer + float *z_ = nullptr, *y_ = nullptr, *y_dummy_ = nullptr; + float *qfull_ = nullptr, *qcur_ = nullptr, *kcur_ = nullptr, *vcur_ = nullptr, *idx_raw_L_ = nullptr; + float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr; + float* tail_snap_ = nullptr; // per QSA layer + int32_t* sel_ = nullptr; + float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr; + int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr; + int32_t* plan_ = nullptr; // device copy of the plan block + uint8_t* staging_ = nullptr; // VRAM slots for the PCIe share of the misses + static constexpr int64_t kStagingBlobs = 16; + uint8_t* hit_xq_ = nullptr; + uint8_t* nat_xq_ = nullptr; // plan v0.3 P6: q8_1 activations for a native pack's grouped experts + float* hit_xs_ = nullptr; + void* hit_scratch_ = nullptr; + float *head_mixed_ = nullptr, *head_inj_ = nullptr, *head_logits_ = nullptr; + uint16_t* sh_bf16_ = nullptr; + float *sh_gate_ = nullptr, *sh_up_ = nullptr, *sh_g_ = nullptr; + float* hist_snap_ = nullptr; // T * NG_HIST * NG_HC_DIM + int64_t cap_ = 0, max_blocks_ = 0, attn_scratch_floats_ = 0; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/core/weights.hpp b/engine/strata/include/strata/core/weights.hpp new file mode 100644 index 00000000..5c6414f8 --- /dev/null +++ b/engine/strata/include/strata/core/weights.hpp @@ -0,0 +1,141 @@ +// include/strata/core/weights.hpp - the dense weights, loaded into VRAM in ENGINE form. +// +// The pack is the ARTIFACT's business; this is the ENGINE's. The differences are deliberate, and they run in +// BOTH directions: +// +// * SHRINKING. A tensor whose source type is BF16 is stored in the pack promoted to 32 bits, because that is +// lossless and it keeps the canonical decoder simple, but a running engine re-rounds it to 16 - which costs +// nothing at all, because the value CAME from 16 bits. Per `tools/pack_budget.py` that saving is the +// difference between the dense weights fitting in VRAM beside the expert cache and not fitting at all. +// +// * GROWING. 90 of the 303 quantized tensors carry fp16 SCALES in the pack (all 58 Q2_0 expert tensors, plus +// Q4_0, Q5_0, Q8_0 and IQ4_NL) because that is what the source block holds. Every kernel here takes +// `const float* scales`, and fp16 is a subset of f32, so this loader WIDENS them - exactly, changing no +// value - for 11,407,360 B. See `docs/pack-format.md` §2.4; assuming 4 bytes per scale instead of reading +// `scales_fp16` is what made the plane arithmetic disagree with the pack for a whole round. +// +// pack 5.305 GiB dense + 0.444 GiB embd +// engine 4.067 GiB dense + 0.444 GiB embd + 10.88 MiB widened scales = 4.522 GiB +// +// WHAT THE LOADER DOES NOT DO: it does not know what any tensor MEANS. It reads a flat index +// (`/index.txt`, written by `tools/pack_index.py`), copies each tensor into one arena at a recorded +// offset - as a list of PLANE SEGMENTS, because a scale plane can change width and the rest cannot - and hands +// back a name -> WeightRef map. Geometry, forms and semantics belong to the caller. +// +// WHY AN INDEX FILE AND NOT A JSON PARSER: a JSON parser in the engine would be a new, unaudited component +// whose failure mode is a wrong byte offset - which decodes to a plausible weight and produces plausible +// logits. Python wrote the manifest and already parses it correctly. +#pragma once + +#include +#include +#include +#include +#include + +namespace strata::core { + +/// What the loader had to DO for a tensor, decided by `tools/pack_index.py` and written into the index +/// rather than inferred here. The four cases are distinguishable in the manifest only by combining +/// `source_type` with `values_fp16`, and getting that combination wrong yields a plausible tensor. +enum class WeightKind : int { + Verbatim = 0, ///< quantized planes, or F16 already stored as 2 bytes: copy straight through + Bf16InF32 = 1, ///< the pack holds the bf16 value promoted to f32: take the HIGH 16 BITS (exact) + F32 = 2, ///< copy 4 bytes per element + F16InF32 = 3, ///< an f16 value promoted to f32: a real f32->f16 conversion, not a truncation +}; + +struct WeightRef { + const void* data = nullptr; ///< device pointer inside the arena + uint64_t bytes = 0; + int64_t ne0 = 0; ///< the manifest's own shape, ne0 the CONTIGUOUS axis + int64_t ne1 = 0; + int64_t elements = 0; + WeightKind kind = WeightKind::Verbatim; + /// The canonical-form attributes, valid only for a quantized VERBATIM tensor (`code_bits != 0`). + int code_bits = 0; + int code_bias = 0; + int group_elems = 0; + bool codebook_iq4nl = false; + bool has_offset = false; + + /// THE THREE PLANE SIZES, IN ENGINE FORM, in the order they sit inside `data`. Recorded by the loader + /// from what the index TOLD it rather than re-derived by each caller: the one time this layout was + /// re-derived independently it assumed 4-byte scales for tensors whose pack scales are fp16, and the + /// only reason that was not a silent wrong answer is that the re-derivation checked itself and refused. + /// Two places computing one layout is two places to disagree. + uint64_t codes_bytes = 0; + uint64_t scales_bytes = 0; ///< always 4 B per scale in the arena, whatever the pack held + uint64_t offset_bytes = 0; ///< 0 when the form has no offset plane + + /// WHERE THIS TENSOR CAME FROM, so a caller can check the loader's work against the pack's own bytes + /// instead of against the loader's opinion of them. Without `src_off` a test can only compare two + /// derived numbers; with it, the widening of an fp16 scale plane can be verified value by value against + /// `.bin` - and the pack files are named, so `file_id` says which one to open. + uint64_t src_off = 0; + uint64_t src_bytes = 0; + int file_id = 0; + bool scales_fp16 = false; ///< the PACK's width, before the loader widened it + + /// WHICH ACTIVATION THIS WEIGHT WANTS - 0 for Q8_0, 1 for Q8_K. Decided by ools/pack_index.py from + /// source_type and carried here, because **the S-form CANNOT express it**: Q5_0 and Q5_K are both 8-bit + /// with bias -16, and IQ4_NL and IQ4_XS differ in nothing the S-form holds. docs/activation-contract.md. + int act_kind = 0; + bool wants_q8k() const { return act_kind == 1; } + + bool quantized() const { return code_bits != 0; } + + // Optional native GGUF projection, owned by NativeDense. All references in + // one table share its scratch and must execute on one ordered session stream. + const void* native_data = nullptr; + void* native_q8_1 = nullptr; + int native_type = -1; + /// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it + /// (native GGUF projections, the native head). The metadata above stays valid; `data` is null. + bool resident = true; +}; + +struct LoadReport { + size_t tensors = 0; + uint64_t arena_bytes = 0; + size_t re_rounded = 0; ///< tensors written as 16 bits out of a 32-bit container + uint64_t bytes_saved = 0; ///< what those conversions saved against the pack + double read_ms = 0.0; + double upload_ms = 0.0; +}; + +class WeightTable { +public: + /// The arena size the index asks for, readable WITHOUT loading anything - so a caller can size its + /// `DeviceArena` before committing to the load, and a plan that cannot fit is refused at startup rather + /// than halfway through a 5 GB upload. + /// With `skip`, the size of the compacted arena that holds every tensor EXCEPT the named ones. + static bool pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err, + const std::set* skip = nullptr); + + /// The `code_bits` field of one row of `/index.txt`, readable WITHOUT loading anything (0 = the + /// pack stores the tensor unquantized, e.g. a --compat-bf16 key; -1 = no such row). #326: the loader has + /// to know this before it builds the skip set. + static bool index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits, + std::string& err); + + /// Load every tensor in `/index.txt` into `arena_base`. + /// + /// `arena_bytes` MUST be at least `pool_bytes`; the loader checks rather than trusting the caller, + /// because the failure mode otherwise is a device write past the end of the arena. + /// With `skip`, the named tensors are not read: their rows keep their metadata with `data == nullptr` and + /// `resident == false`, and the other tensors are packed into the compacted arena `pool_bytes` sized. + bool load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err, + const std::set* skip = nullptr); + + const WeightRef* find(const std::string& name) const; + const std::map& all() const { return table_; } + const LoadReport& report() const { return report_; } + +private: + friend class NativeDense; + std::map table_; + LoadReport report_; +}; + +} // namespace strata::core diff --git a/engine/strata/include/strata/hip_compat/cublas_v2.h b/engine/strata/include/strata/hip_compat/cublas_v2.h new file mode 100644 index 00000000..f162474b --- /dev/null +++ b/engine/strata/include/strata/hip_compat/cublas_v2.h @@ -0,0 +1,19 @@ +#pragma once +#include +#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F +#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH +#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT +#define CUBLAS_OP_N HIPBLAS_OP_N +#define CUBLAS_OP_T HIPBLAS_OP_T +#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS +#define CUDA_R_16BF HIP_R_16BF +#define CUDA_R_16F HIP_R_16F +#define CUDA_R_32F HIP_R_32F +#define cublasCreate hipblasCreate +#define cublasDestroy hipblasDestroy +#define cublasGemmEx hipblasGemmEx +#define cublasHandle_t hipblasHandle_t +#define cublasSetMathMode hipblasSetMathMode +#define cublasSetStream hipblasSetStream +#define cublasSetWorkspace hipblasSetWorkspace +#define cublasStatus_t hipblasStatus_t diff --git a/engine/strata/include/strata/hip_compat/cuda_fp16.h b/engine/strata/include/strata/hip_compat/cuda_fp16.h new file mode 100644 index 00000000..969acef6 --- /dev/null +++ b/engine/strata/include/strata/hip_compat/cuda_fp16.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/engine/strata/include/strata/hip_compat/cuda_runtime.h b/engine/strata/include/strata/hip_compat/cuda_runtime.h new file mode 100644 index 00000000..40c1c79c --- /dev/null +++ b/engine/strata/include/strata/hip_compat/cuda_runtime.h @@ -0,0 +1,115 @@ +#pragma once +// Included only by STRATA_ENABLE_HIP builds. CUDA builds use NVIDIA headers. +#if defined(_WIN32) +// hip_runtime.h pulls in on Windows: keep its min/max macros and the rarely used APIs out of the engine. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#endif +#include +// Do not let HIP's legacy macro corrupt libstdc++ attribute names. +#ifdef __noinline__ +#undef __noinline__ +#endif +#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeMaxSharedMemoryPerBlock +#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount +#define cudaDevAttrClockRate hipDeviceAttributeClockRate +#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor +#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor +#define cudaDeviceGetAttribute hipDeviceGetAttribute +#define cudaDeviceProp hipDeviceProp_t +#define cudaDeviceSynchronize hipDeviceSynchronize +#define cudaDriverGetVersion hipDriverGetVersion +#define cudaErrorNotReady hipErrorNotReady +#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported +#define cudaError_t hipError_t +#define cudaEventCreate hipEventCreate +#define cudaEventCreateWithFlags hipEventCreateWithFlags +#define cudaEventDestroy hipEventDestroy +#define cudaEventDisableTiming hipEventDisableTiming +#define cudaEventElapsedTime hipEventElapsedTime +#define cudaEventQuery hipEventQuery +#define cudaEventRecord hipEventRecord +#define cudaEventSynchronize hipEventSynchronize +#define cudaEvent_t hipEvent_t +#define cudaFree hipFree +#define cudaFreeHost hipFreeHost +#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize +#define cudaGetDevice hipGetDevice +#define cudaGetDeviceCount hipGetDeviceCount +#define cudaGetDeviceProperties hipGetDeviceProperties +#define cudaGetErrorString hipGetErrorString +#define cudaGetLastError hipGetLastError +#define cudaGraphDestroy hipGraphDestroy +#define cudaGraphExecDestroy hipGraphExecDestroy +#define cudaGraphExec_t hipGraphExec_t +#define cudaGraphGetNodes hipGraphGetNodes +#define cudaGraphLaunch hipGraphLaunch +#define cudaGraphUpload hipGraphUpload +#define cudaGraph_t hipGraph_t +#define cudaHostAlloc hipHostMalloc +#define cudaHostAllocDefault hipHostAllocDefault +#define cudaHostAllocMapped hipHostAllocMapped +#define cudaHostAllocPortable hipHostAllocPortable +#define cudaHostGetDevicePointer hipHostGetDevicePointer +#define cudaHostRegister hipHostRegister +#define cudaHostRegisterMapped hipHostRegisterMapped +#define cudaHostRegisterPortable hipHostRegisterPortable +#define cudaHostUnregister hipHostUnregister +#define cudaLaunchHostFunc hipLaunchHostFunc +#define cudaMalloc hipMalloc +#define cudaMallocHost(...) (::strata::hip_compat::malloc_host(__VA_ARGS__)) +#define cudaMemGetInfo hipMemGetInfo +#define cudaMemcpy hipMemcpy +#define cudaMemcpy2DAsync hipMemcpy2DAsync +#define cudaMemcpyAsync hipMemcpyAsync +#define cudaMemcpyDefault hipMemcpyDefault +#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice +#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost +#define cudaMemcpyHostToDevice hipMemcpyHostToDevice +#define cudaMemset hipMemset +#define cudaMemsetAsync hipMemsetAsync +#define cudaPeekAtLastError hipPeekAtLastError +#define cudaRuntimeGetVersion hipRuntimeGetVersion +#define cudaSetDevice hipSetDevice +#define cudaStreamBeginCapture hipStreamBeginCapture +#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal +#define cudaStreamCaptureStatus hipStreamCaptureStatus +#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone +#define cudaStreamCreate hipStreamCreate +#define cudaStreamCreateWithFlags hipStreamCreateWithFlags +#define cudaStreamDestroy hipStreamDestroy +#define cudaStreamEndCapture hipStreamEndCapture +#define cudaStreamIsCapturing hipStreamIsCapturing +#define cudaStreamNonBlocking hipStreamNonBlocking +#define cudaStreamQuery hipStreamQuery +#define cudaStreamSynchronize hipStreamSynchronize +#define cudaStreamWaitEvent hipStreamWaitEvent +#define cudaStream_t hipStream_t +#define cudaSuccess hipSuccess + +namespace strata::hip_compat { +template +inline hipError_t malloc_host(T** pointer, size_t bytes) { + return hipHostMalloc(reinterpret_cast(pointer), bytes, hipHostMallocDefault); +} +} // namespace strata::hip_compat + +template +inline hipError_t cudaFuncSetAttribute(Kernel kernel, hipFuncAttribute attribute, int value) { + return hipFuncSetAttribute(reinterpret_cast(kernel), attribute, value); +} +inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) { + return hipGraphInstantiateWithFlags(exec, graph, flags); +} +inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, + hipGraphNode_t* error, char* log, size_t size) { + return hipGraphInstantiate(exec, graph, error, log, size); +} +#define __trap() __builtin_trap() // the compiled-out sm_80 paths (never selected on AMD) +#define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(HIP_SYMBOL(symbol), __VA_ARGS__) + +#include "intrinsics.hpp" diff --git a/engine/strata/include/strata/hip_compat/cuda_runtime_api.h b/engine/strata/include/strata/hip_compat/cuda_runtime_api.h new file mode 100644 index 00000000..cf546fc3 --- /dev/null +++ b/engine/strata/include/strata/hip_compat/cuda_runtime_api.h @@ -0,0 +1,2 @@ +#pragma once +#include "cuda_runtime.h" diff --git a/engine/strata/include/strata/hip_compat/intrinsics.hpp b/engine/strata/include/strata/hip_compat/intrinsics.hpp new file mode 100644 index 00000000..a789e38c --- /dev/null +++ b/engine/strata/include/strata/hip_compat/intrinsics.hpp @@ -0,0 +1,132 @@ +#pragma once + +// CUDA device intrinsics used by Strata kernels that HIP does not provide on RDNA2 / RDNA3 / RDNA4 (wave32). +// This header is included only from the HIP cuda_runtime compatibility shim. +#if defined(__HIPCC__) + +#include + +namespace strata::hip_compat { + +__device__ __forceinline__ int signed_byte(uint32_t word, int lane) { + const unsigned value = (word >> (lane * 8)) & 0xffu; + return value < 0x80u ? static_cast(value) : static_cast(value) - 0x100; +} + +// CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. +__device__ __forceinline__ int dp4a(int a, int b, int c) { +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \ + defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + // RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark + // both packed operands signed to preserve CUDA __dp4a semantics; keep the + // portable path for other HIP compilers/targets. + return __builtin_amdgcn_sudot4(true, a, true, b, c, false); +#elif (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)) && __has_builtin(__builtin_amdgcn_sdot4) + // RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same + // signed x signed byte products accumulated modulo 2^32, no clamp. + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + const uint32_t ua = static_cast(a); + const uint32_t ub = static_cast(b); + uint32_t sum = static_cast(c); +#pragma unroll + for (int lane = 0; lane < 4; ++lane) + sum += static_cast(signed_byte(ua, lane) * signed_byte(ub, lane)); + return static_cast(sum); +#endif +} + +// CUDA's __byte_perm (default mode): result byte i is byte s.nibble[i] & 7 of the pair {y:x}, x the low word. +// HIP's own version indexes a byte array in private memory, which becomes scratch traffic in the i-quant table +// lookups; v_perm_b32 is the same selection in one instruction (selector bytes 0-3 pick from its second +// operand, 4-7 from its first), so the nibble selector is spread to bytes and masked to 0-7. +__device__ __forceinline__ uint32_t byte_perm(uint32_t x, uint32_t y, uint32_t s) { + const uint32_t sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// The packed byte operations below work on all four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have +// no packed 8-bit subtract, and a per-lane loop costs the Q3_K/Q6_K dots and the i-quant sign expansion several +// times the instructions. kHigh is each lane's top bit. +constexpr uint32_t kHigh = 0x80808080u; + +// CUDA's packed byte subtract wraps independently in each unsigned byte lane: subtract the low seven bits with the +// minuend's top bit forced on (so no borrow crosses a lane), then fix each top bit by XOR. +__device__ __forceinline__ int vsub4(int a, int b) { + const uint32_t ua = static_cast(a); + const uint32_t ub = static_cast(b); + return static_cast(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); +} + +// CUDA's packed signed-byte saturating subtract: the wrapping difference, and in each lane that overflowed (operand +// signs differ and the result's sign differs from the minuend's) the bound on the minuend's side, 0x7f or 0x80. +__device__ __forceinline__ int vsubss4(int a, int b) { + const uint32_t ua = static_cast(a); + const uint32_t ub = static_cast(b); + const uint32_t d = static_cast(vsub4(a, b)); + const uint32_t overflow = (ua ^ ub) & (ua ^ d) & kHigh; + const uint32_t mask = (overflow >> 7) * 0xffu; + const uint32_t bound = 0x7f7f7f7fu + ((ua & kHigh) >> 7); + return static_cast((d & ~mask) | (bound & mask)); +} + +// CUDA's four-lane byte compare, returning 0xff for each unequal lane and 0 otherwise: a lane of a ^ b is nonzero +// when its low seven bits carry into the top bit on adding 0x7f, or its top bit is already set. +__device__ __forceinline__ int vcmpne4(int a, int b) { + const uint32_t t = static_cast(a) ^ static_cast(b); + const uint32_t nonzero = (((t & ~kHigh) + ~kHigh) | t) & kHigh; + return static_cast((nonzero >> 7) * 0xffu); +} + +// CUDA's mask argument describes participating lanes. The current kernel set uses full +// wave32 masks; reject future partial-mask use instead of silently dropping its semantics. +__device__ __forceinline__ void require_full_wave_mask(uint32_t mask) { + if (mask != 0xffffffffu) __builtin_trap(); +} + +template +__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) { + require_full_wave_mask(mask); + return __shfl_xor(value, lane_mask, width); +} + +template +__device__ __forceinline__ T shfl_down_sync(uint32_t mask, T value, unsigned delta, int width = 32) { + require_full_wave_mask(mask); + return __shfl_down(value, delta, width); +} + +template +__device__ __forceinline__ T shfl_up_sync(uint32_t mask, T value, unsigned delta, int width = 32) { + require_full_wave_mask(mask); + return __shfl_up(value, delta, width); +} + +template +__device__ __forceinline__ T shfl_sync(uint32_t mask, T value, int source_lane, int width = 32) { + require_full_wave_mask(mask); + return __shfl(value, source_lane, width); +} + +__device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) { + require_full_wave_mask(mask); + return static_cast(__ballot(predicate)); +} + +} // namespace strata::hip_compat + +#define __dp4a(a, b, c) (::strata::hip_compat::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (::strata::hip_compat::byte_perm((x), (y), (s))) +#define __vsub4(a, b) (::strata::hip_compat::vsub4((a), (b))) +#define __vsubss4(a, b) (::strata::hip_compat::vsubss4((a), (b))) +#define __vcmpne4(a, b) (::strata::hip_compat::vcmpne4((a), (b))) +#define __shfl_xor_sync(...) (::strata::hip_compat::shfl_xor_sync(__VA_ARGS__)) +#define __shfl_down_sync(...) (::strata::hip_compat::shfl_down_sync(__VA_ARGS__)) +#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__)) +#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__)) +#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate))) +// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a +// backoff hint, so use its smallest portable delay independently of CUDA cycle counts. +#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1) + +#endif // defined(__HIPCC__) diff --git a/engine/strata/include/strata/kernels/bf16_bits.hpp b/engine/strata/include/strata/kernels/bf16_bits.hpp new file mode 100644 index 00000000..5c32532f --- /dev/null +++ b/engine/strata/include/strata/kernels/bf16_bits.hpp @@ -0,0 +1,61 @@ +// include/strata/kernels/bf16_bits.hpp - the bf16 conversions, written out, as bits. +// +// bf16 is the TOP HALF of an f32, so `f32_from_bf16` is a shift and needs no rounding at all. The forward +// direction does: ggml's `ggml_compute_fp32_to_bf16` adds `((i >> 16) & 1) + 0x7FFF` and truncates 16 bits. +// +// **THE `& 1` IS ON BIT 16**, the lowest KEPT bit, which is what makes an exact tie round to EVEN. Using bit +// 15 there is a plausible mistake: it differs only on exact ties, i.e. almost never on real data, which is +// exactly why it would survive any amount of end-to-end testing. `ref/quant.py` documents the same rule for +// the same reason. +// +// WHY THIS IS SEPARATE FROM `f16_bits.hpp`: fp16 and bf16 are not two spellings of one idea. fp16 has 5 +// exponent bits and 10 mantissa bits; bf16 has 8 and 7. A conversion routine written for one and reused for +// the other is wrong in a way that produces plausible numbers - bf16's 2^-9 relative precision looks like a +// small fp16 error and is not small at all next to fp16's 2^-11. +// +// `gr.cu` carried a private copy of `f32_to_bf16_bits` until this header existed. It now includes this. +#pragma once + +#include +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_BF16_HD __host__ __device__ +#else +#define STRATA_BF16_HD +#endif + +namespace strata::kernels { + +/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16. +/// +/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone +/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so +/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the +/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input, +/// infinities included, rounds exactly as before. +STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) { + uint32_t i; +#if defined(__HIP_DEVICE_COMPILE__) + __builtin_memcpy(&i, &f, 4); +#else + std::memcpy(&i, &f, 4); +#endif + if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u); + i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; + return (uint16_t) (i >> 16); +} + +/// bf16 bits -> f32. Exact, and no rounding: the low 16 bits of an f32 are simply zero. +STRATA_BF16_HD inline float f32_from_bf16(uint16_t h) { + const uint32_t i = (uint32_t) h << 16; + float f; +#if defined(__HIP_DEVICE_COMPILE__) + __builtin_memcpy(&f, &i, 4); +#else + std::memcpy(&f, &i, 4); +#endif + return f; +} + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/bf16_gemv.hpp b/engine/strata/include/strata/kernels/bf16_gemv.hpp new file mode 100644 index 00000000..906a8f0b --- /dev/null +++ b/engine/strata/include/strata/kernels/bf16_gemv.hpp @@ -0,0 +1,52 @@ +// include/strata/kernels/bf16_gemv.hpp - the GEMV for a BF16 weight, P2.S5. +// +// WHY THIS EXISTS WHEN `s_gemv` ALREADY DOES. `s_gemv` decodes the S-family canonical forms (S2/S4/S8) from +// `codes` + `scales`, and a BF16 weight is not one of them - it has no codes and no scales, it is a plain +// 16-bit matrix. Six tensors per layer are in that state: +// +// ssm_alpha.weight, ssm_beta.weight GDN, [n_embd, 48] +// indexer.q_proj.weight, indexer.k_proj.weight QSA, [n_embd, 512] and [n_embd, 128] +// ple_value.weight layer 1, [n_embd, n_embd] +// ffn_gate_inp.weight handled inside `router_top10` +// +// The original entry points take BF16 activation bits for the historical CPU-derived contract. The explicit +// FP32 entry point below follows the pinned CUDA single-token MMVF contract. See docs/activation-contract.md +// for why activation precision depends on backend and batch geometry rather than weight type alone. +#pragma once + +#include + +namespace strata::kernels { + +/// `y[o] = sum_i f32(x[i]) * f32(w[o*n_in + i])`, with both sides bf16-valued so every product is exact in +/// f32 and only the summation order differs. +/// +/// THE WEIGHT LAYOUT IS THE MANIFEST'S: shape [n_in, n_out] with ne0 = n_in CONTIGUOUS, so row `o` is a +/// contiguous run of `n_in` bf16 values. That is the same convention `s_gemv` uses, and it is what +/// `strata::core::WeightRef::ne0/ne1` already report. +void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream); + +/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the +/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes +/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout. +/// +/// NOT bit-identical to `bf16_gemv`: the partial sums are added in a different order. Both are kept and both +/// are tested, because the naive one is the reference the split one is checked against. +void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, + int threads_per_row, void* stream); + +/// Single-token, contiguous 2D BF16-weight/F32-activation MMVF from the pinned llama.cpp CUDA path. +/// Preserves pair accumulation, adaptive block size and warp-XOR reduction order. This is a separate +/// opt-in entry point; the legacy BF16-activation kernels above retain their behavior. +/// `w[o*n_in+i]` is BF16 bits; x/y are F32. n_in must be positive and even, n_out positive, both <= INT_MAX. +/// x must be 8-byte aligned, w 4-byte aligned, and y 4-byte aligned. Throws on invalid geometry/pointers. +/// The device buffers must not overlap; allocation bounds remain the caller's responsibility. +/// No allocations or synchronization, including when stream is null (the CUDA default stream). +void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y, + int64_t n_in, int64_t n_out, void* stream); +/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch, +/// the weight read once, every output bit-identical to its own single-row call. +void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/cpu/expert.hpp b/engine/strata/include/strata/kernels/cpu/expert.hpp new file mode 100644 index 00000000..ab05db84 --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/expert.hpp @@ -0,0 +1,179 @@ +// include/strata/kernels/cpu/expert.hpp - P2.S3: the CPU expert path. +// +// This is the Q2_0 expert kernel promoted out of `bench/micro/cpu_s2.cpp`, which is the instrument that +// measured `c` (Memory/LEDGER.md L9/L10: 15.03 ms for one token's full routed set on 6 cores, DRAM-bound at +// 44.14 GB/s) and whose P0.T2 parity passes at 1.461e-06. +// +// IT IS THE SAME CODE, NOT A COPY. Keeping a second implementation next to a validated one is how a project +// ends up with two answers and no way to say which is right, so `cpu_s2.cpp` is expected to become a thin +// benchmark over these functions. (Until it is, the two exist side by side and this header says so.) +// +// WHAT MAKES IT FAST, and each of the three was paid for once: +// +// * `vpdpbusd` (AVX512-VNNI) does four int8 MACs per instruction. The scalar loop it replaces ran at +// 9.89 GB/s on one core; VNNI is the reason the 6-core figure is 42.55 GB/s. +// * `vpmultishiftqb` (AVX512-VBMI) unpacks the 2-bit codes eight at a time. Its ARGUMENT ORDER is +// (control, data) and was determined empirically - the Intel guide states the opposite, and following the +// guide produced 43 of 64 wrong codes. +// * The row accumulator stays a FLOAT VECTOR and is reduced ONCE at the end of the row. Reducing per +// 64-weight block cost more than the dot products themselves: it made the kernel compute-bound at +// 21 GB/s instead of DRAM-bound at 32. +// +// THE CONTRACT THAT MATTERS, because collapsing it is invisible and cannot match ggml's logits: one Q2_0 +// WEIGHT block is QK=64 weights with one fp16 scale, while one ACTIVATION chunk is QKA=32 elements with +// its OWN scale. So a weight block spans TWO activation chunks with two different scales. Using one scale +// per weight block is the natural-looking mistake. +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +// ---- geometry, all of it fixed by the artifact (tools/verify_q2_0_geometry.py: 202/202 tensors at QK=64) ---- +inline constexpr int H = 2560; // n_embd +inline constexpr int FF = 640; // expert intermediate width +inline constexpr int NE = 512; // routed experts per layer +inline constexpr int QK = 64; // QK2_0: weights per fp16 scale +inline constexpr int QKA = 32; // QK8_1/QK8_0: ACTIVATION elements per scale +inline constexpr int BB = 18; // bytes per 64-weight Q2_0 block: 2 fp16-scale + 16 codes +inline constexpr int MAXC = H / QKA; // 80 activation chunks across the widest reduction +inline constexpr int ROW_GU = H * 2 / 8; // 640 B of codes per gate/up row +inline constexpr int ROW_D = FF * 2 / 8; // 160 B of codes per down row +inline constexpr int SC_GU = H / QK; // 40 weight blocks per gate/up row +inline constexpr int SC_D = FF / QK; // 10 weight blocks per down row +inline constexpr size_t BLOB = 3ull * (H * FF * BB / QK); // 1,382,400 + +// ---- the blob's internal layout (one expert) ---- +inline constexpr size_t O_GU_CODES = 0; +inline constexpr size_t O_D_CODES = 2ull * FF * ROW_GU; +inline constexpr size_t O_GU_SCALES = O_D_CODES + 1ull * H * ROW_D; +inline constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2; + +/// One activation in Strata's planar storage: `QKA` elements per chunk. +/// The default legacy quantizer uses FP32 scales and half-away rounding. It is +/// not the pinned ggml CPU Q8_0 contract; expert_set_oracle_q8_0 selects that +/// experimental contract (FP16-rounded scales and x86 nearest-even codes). +/// +/// The historical function name `act_quant_q8_1` does not describe a native +/// ggml block layout. One 64-weight block always spans two 32-element chunks. +/// +/// `hx[k] = scale[k] * sum[k]` is the weight-independent correction the Q2_0 identity needs +/// (`sum (c-1) d_w xhat d_x = d_w (d_x*sum(c*xhat) - d_x*sum(xhat))`), precomputed once per layer rather than +/// once per row: 640 rows would otherwise recompute it 640 times. +struct ActQ { + alignas(64) int8_t q[H]; + float scale[MAXC]; + int32_t sum[MAXC]; + float hx[MAXC]; + int nchunks; +}; + +/// Per-worker scratch. Owned by the caller and passed in, so the token path performs NO allocations +/// (P2.T10) - the kernel itself allocates nothing. +struct ExpertScratch { + ActQ a1; + ActQ a2; + alignas(64) float ff[FF]; +}; + +/// Runtime CPU feature check. The kernel uses AVX512-VNNI + AVX512-VBMI + AVX512VL, and code compiled with +/// `/arch:AVX512` can emit AVX-512 anywhere in its translation unit, so a machine without them must be +/// REFUSED rather than silently run. `s2_expert_scalar` is the fallback and exists for tests. +struct CpuFeatures { + bool avx512f = false; + bool avx512bw = false; + bool avx512vl = false; + bool avx512_vnni = false; + bool avx512_vbmi = false; + bool usable() const { return avx512f && avx512bw && avx512vl && avx512_vnni && avx512_vbmi; } + /// A one-line description of what is missing, or "ok". + const char* reason() const; +}; +CpuFeatures cpu_features(); + +/// Exits with a clear message if the CPU cannot run `s2_expert_vnni`. Called once at startup, so a user on an +/// older CPU learns why at second zero instead of seeing an illegal instruction at token 4000. +void cpu_require_expert_support(); + +/// Select the pinned x86 Q8_0 activation contract at BOTH expert quantization +/// boundaries and the pinned generic CPU Q2_0 dot reduction in all projections. +/// Default false preserves the legacy quantizer and eight-lane FP32 reduction. +/// Configure before starting worker threads and do not change during a request. +/// GPU expert-cache parity is not established for this mode; the driver must +/// reject combining it with that cache. No allocation occurs in either mode. +void expert_set_oracle_q8_0(bool enabled); + +/// `x` -> `a` in the configured contract. The function name is historical; +/// `n` must be a multiple of QKA and at most H. No allocation occurs. +void act_quant_q8_1(const float* x, int n, ActQ& a); + +/// One expert: `out(H) = down( swiglu( gate(x), up(x) ) )`, all three projections Q2_0, +/// with the configured activation and dot contracts at both quantization boundaries. +/// +/// `blob` is one 1,382,400-byte expert in the pack's layout; `x` is the H-wide input; `out` is H-wide. +void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws); + +/// The same, with the activation ALREADY quantized in the configured contract. +/// Workers may share this read-only activation; each must own its scratch/output. +/// +/// This split exists for the pool. A layer runs TEN experts against ONE activation, so quantizing inside +/// `s2_expert_vnni` would do the same 2560-element conversion ten times per layer per token - 480 redundant +/// conversions per token. P2.S3's work item is `(blob, x-hat quantized, block sums, weight, out)`, and this +/// is the entry point that matches it. +void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws); + +/// Plan v0.3 P6: ONE expert applied to up to MAXT tokens that were all routed to it (a speculative verify +/// window routes ~1.5 tokens to each distinct expert). The 1.38 MB blob is read and its 2-bit codes unpacked +/// ONCE per block for all tokens; only the VNNI dot and the accumulation run per token. Every token's output +/// is bitwise equal to `s2_expert_vnni_q` on that token (same operation order per token). Legacy activation +/// contract only; with `expert_set_oracle_q8_0(true)` it falls back to one `s2_expert_vnni_q` per token. +inline constexpr int MAXT = 8; +/// Plan v0.3 P4: the expert in row ranges, so several threads can share one expert. `s2_expert_gu_rows` writes +/// ff[r] = silu(gate_r . x) * (up_r . x) for r in [r0, r1) (of FF); `s2_expert_down_rows` writes out[r] for r in +/// [r0, r1) (of H) from the intermediate's quantized image. Together with `act_quant_q8_1(ff, FF, a2)` in +/// between they are exactly `s2_expert_vnni_q`, row for row (same `row_dot`), so the result is bitwise the same. +bool expert_oracle_q8_0_enabled(); +void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1); +void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1); + +/// Plan v0.3 P6: the row-range kernels for up to MAXT tokens routed to the same expert (legacy contract only). +/// Each token's rows are bitwise the single-token `s2_expert_gu_rows` / `s2_expert_down_rows`. +void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0, + int r1); +void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0, + int r1); + +struct ExpertScratchMulti { + ActQ a2[MAXT]; + alignas(64) float ff[MAXT][FF]; + ExpertScratch single; // the oracle-contract fallback +}; +void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out, + ExpertScratchMulti& ws); + +/// The scalar transcription of ggml's formula - NOT a second opinion, but the ORACLE the VNNI path is checked +/// against, and the only path available on a CPU without AVX-512. +/// +/// `quant_acts` makes the oracle consume the SAME INT8 activation values the VNNI path uses, **at BOTH +/// stages**. With it OFF the oracle is exact-FP32-activation and the gap between them IS the activation +/// contract; with it ON the two differ only by FP32 evaluation order, so a small gap there proves the kernel +/// itself correct. That separation is the whole point of P0.T2 and it is why this parameter exists rather +/// than two functions. +/// +/// CORRECTION TO THE ORIGINAL: `bench/micro/cpu_s2.cpp`'s comment says "at both stages" but its code +/// quantizes only the intermediate, leaving the gate/up projections on raw f32 `x`. That is invisible when +/// the caller passes an already-quantized input - which the engine does - and shows up as a ~1.2% gap when it +/// does not, which reads as a kernel bug and is not one. This version quantizes both. +/// Plan v0.3 P6: rows [r0, r1) of a Q2_0 matrix in the GGUF block layout (18 bytes per 64 weights, `row_bytes` +/// per row, `nblocks` blocks each) against `nt` activations: out[t][r]. +void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1); +/// The same two for CPUs without AVX-512 (src/kernels/cpu/q2_avx2.cpp, compiled for AVX2 only). +void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1); +void act_quant_q8_1_avx2(const float* x, int n, ActQ& a); + +void s2_expert_scalar(const uint8_t* blob, const float* x, float* out, bool quant_acts); + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/expert_layout.hpp b/engine/strata/include/strata/kernels/cpu/expert_layout.hpp new file mode 100644 index 00000000..9a8b9918 --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/expert_layout.hpp @@ -0,0 +1,66 @@ +// include/strata/kernels/cpu/expert_layout.hpp - plan v0.3 P6: where each routed expert lives in experts.bin. +// +// A Q2_0 pack (tools/strata_pack.py) has one blob size for every layer, `BLOB`, in the Strata expert form. A +// native pack (tools/iq_pack.py, the IQ2_XS / IQ3_XXS files) keeps each expert's raw GGUF slices, so the blob +// size and the formats change from layer to layer; `native_experts.txt` says how. Everything that touches an +// expert blob - the arena, the VRAM tier, the prompt path, the CPU pool, the GPU window - asks this table. +#pragma once + +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/native_expert.hpp" + +#include +#include +#include + +namespace strata::kernels::cpu { + +struct ExpertLayout { + bool native = false; + int64_t n_layers = 0, n_expert = NE; + std::vector fmt; ///< per layer (native packs) + std::vector offset, bytes; ///< per layer: where its 512 blobs start, bytes per blob + /// Plan v0.3 P6: per layer, the absolute offsets of the gate / up / down tensors in their GGUF files, so the + /// arena can be filled from the GGUF itself when the pack has no experts.bin (3 x n_layers, 0 = unknown). + std::vector gguf_off; + /// Per layer PER ROLE (3 x n_layers, `3 * layer + role`, matching `gguf_off`), the GGUF file - a name beside + /// the --native shard - that holds that role's tensor. Empty = the --native shard itself. Per role because a + /// shard boundary can fall inside a layer: Unsloth's UD-Q4_K_XL has layer 11's down in shard 2 and its gate + /// and up in shard 3 (native_experts.txt v4, the `gate,up,down` shard column). + std::vector gguf_file; + int version = 0; ///< native_experts.txt's header version (0 = none given) + uint64_t max_blob = BLOB; + uint64_t total = 0; ///< experts.bin size + + uint64_t blob_bytes(int64_t layer) const { return native ? bytes[(size_t) layer] : (uint64_t) BLOB; } + uint64_t layer_offset(int64_t layer) const { + return native ? offset[(size_t) layer] : (uint64_t) layer * (uint64_t) n_expert * (uint64_t) BLOB; + } + uint64_t blob_offset(int64_t layer, int64_t expert) const { + return layer_offset(layer) + (uint64_t) expert * blob_bytes(layer); + } +}; + +/// Plan v0.3 P6: whether this CPU (and its OS) runs the AVX-512 kernels (F, BW, VL, VNNI, VBMI). Probed in a +/// file compiled without AVX-512, so asking is safe everywhere; STRATA_FORCE_AVX2=1 answers no (for tests). +bool cpu_avx512_ok(); +/// Whether this CPU (and its OS) runs the AVX2 kernels (AVX, AVX2, FMA, F16C): the floor of every expert kernel +/// (q2_avx2.cpp, iq_avx2.cpp, and ggml-cpu in the portable build). STRATA_FORCE_AVX2 does not change it. +bool cpu_avx2_ok(); +/// The CPU's brand string (CPUID 0x80000002..4), for messages; "unknown" when it has none. +std::string cpu_name(); +/// Q2_0 GGUF rows / activation quantizer on the kernels this CPU has. +void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, + int r0, int r1); +void act_quant_any(const float* x, int n, ActQ& a); + +/// The process-wide layout (canonical Q2_0 until `expert_layout_load` finds a native pack). +const ExpertLayout& expert_layout(); +/// Reads `/native_experts.txt` when it exists (a native pack), else sets the canonical layout. +/// Versions up to kExpertLayoutVersion are read; a newer one is refused (a newer packer wrote it). +bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err); +/// The newest native_experts.txt this engine reads. v4 = v3 plus the per-role shard column `gate,up,down`, +/// written only when some layer's roles are in different shards (every other pack stays v3, byte for byte). +inline constexpr int kExpertLayoutVersion = 4; + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/iq_avx2.hpp b/engine/strata/include/strata/kernels/cpu/iq_avx2.hpp new file mode 100644 index 00000000..2fc6f57e --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/iq_avx2.hpp @@ -0,0 +1,26 @@ +// include/strata/kernels/cpu/iq_avx2.hpp - AVX-2 multi-token dot products for the i-quant expert +// formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S) against Q8_K activations (ggml's block_q8_K). +// +// The AVX-512 kernel's scheme on the CPUs without it (AMD Zen 2/3, Intel Core 12th-14th gen): the weights of a +// 32-value chunk are decoded once per verify window and every token applies them with five instructions. +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +bool iq256_supported(int ggml_type) noexcept; +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. +void iq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1); +/// out[t][r] = w_r . a[t], rows [r0, r1). +void iq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, + float* const* out, int r0, int r1); + +/// out[t][r] = w_r . h[t] for IQ4_NL (type 20) rows against Q8_0 activations (ggml's block_q8_0). +/// IQ4_NL is a 32-value-block format, so this does not go through iq256_rows (QK_K blocks, Q8_K acts). +void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, + float* const* out, int r0, int r1); + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/iq_avx512.hpp b/engine/strata/include/strata/kernels/cpu/iq_avx512.hpp new file mode 100644 index 00000000..a9a71c46 --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/iq_avx512.hpp @@ -0,0 +1,18 @@ +// include/strata/kernels/cpu/iq_avx512.hpp - plan v0.3 P6: AVX-512 multi-token dot products for the i-quant +// expert formats (IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S) against Q8_K activations (ggml's block_q8_K). +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +bool iq512_supported(int ggml_type) noexcept; +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. +void iq512_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1); +/// out[t][r] = w_r . a[t], rows [r0, r1). +void iq512_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, + float* const* out, int r0, int r1); + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/kq_avx2.hpp b/engine/strata/include/strata/kernels/cpu/kq_avx2.hpp new file mode 100644 index 00000000..01b7a63c --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/kq_avx2.hpp @@ -0,0 +1,25 @@ +// include/strata/kernels/cpu/kq_avx2.hpp - AVX-2 multi-token dot products for Unsloth UD-Q4_K_XL's expert formats +// (Q4_K gate/up against Q8_K activations; Q5_1 down against Q8_1, Q8_0 down against Q8_0), bit-exact against +// ggml-cpu's AVX2 vec_dot for every token. See src/kernels/cpu/kq_avx2.cpp. +#pragma once + +#include +#include + +namespace strata::kernels::cpu { + +/// Q4_K (12), Q5_1 (7), Q8_0 (8). +bool kq256_supported(int ggml_type) noexcept; +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. +void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + int nt, float* const* ff, int r0, int r1); +/// out[t][r] = w_r . a[t], rows [r0, r1). +void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, + float* const* out, int r0, int r1); + +/// out[r] = w_r . x for BF16 rows (bits), fp32 x: the routing-aware prefetch's router (an estimate only). +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out); +/// The same for `nt` <= 8 tokens (x: nt rows of cols, cols % 8 == 0), out[t * rows + r]. +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out); + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/native_expert.hpp b/engine/strata/include/strata/kernels/cpu/native_expert.hpp new file mode 100644 index 00000000..9b807427 --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/native_expert.hpp @@ -0,0 +1,49 @@ +// include/strata/kernels/cpu/native_expert.hpp - plan v0.3 P6: one routed expert in its GGUF form on the CPU. +// +// The IQ2_XS / IQ3_XXS model files keep their experts in i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, +// IQ3_S gate/up; Q2_0 or IQ4_NL down) whose values cannot be re-expressed in the Q2_0 pack form. A native expert +// blob is the three GGUF slices back to back, [gate rows | up rows | down rows], and the arithmetic is ggml-cpu's +// own (`ggml_get_type_traits_cpu`): the activation is quantized with the weight type's `vec_dot_type` and each row +// is one `vec_dot`, exactly what llama.cpp's CPU backend computes for the same tensor. +#pragma once + +#include +#include +#include + +namespace strata::kernels::cpu { + +/// Bytes of the largest quantized activation any native layer uses (2560 values as Q8_K: 10 x 292). +inline constexpr size_t kNativeActBytes = 4096; +/// Bytes of the largest quantized down activation (640 values as Q8_0: 20 x 34, or Q8_K 3 x 292). +inline constexpr size_t kNativeHBytes = 1024; + +/// One layer's native expert geometry. +struct NativeFmt { + int gu_type = -1, d_type = -1; ///< ggml types of gate/up and of down + int gu_act = -1, d_act = -1; ///< their vec_dot_type (the activation formats) + int64_t n_embd = 0, n_ff = 0; + size_t gu_row = 0, d_row = 0; ///< bytes per weight row + size_t up_off = 0, down_off = 0; ///< inside the blob + size_t bytes = 0; ///< the whole blob + size_t act_bytes = 0, h_bytes = 0; ///< quantized activation sizes (n_embd of gu_act, n_ff of d_act) +}; + +/// Whether this build has the ggml-cpu path. +bool native_experts_available() noexcept; +/// Fills `f` for a layer; false (with a reason) when ggml-cpu has no dot product for a type. +bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err); + +/// x (n_embd floats) -> the gate/up activation (act_bytes). +void native_quant_act(const NativeFmt& f, const float* x, void* dst); +/// h (n_ff floats) -> the down activation (h_bytes). +void native_quant_h(const NativeFmt& f, const float* h, void* dst); + +/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]) for rows r in [r0, r1), `nt` tokens. +void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff, + int r0, int r1); +/// out[t][r] = down_r . hq[t] for rows r in [r0, r1). +void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out, + int r0, int r1); + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cpu/pool.hpp b/engine/strata/include/strata/kernels/cpu/pool.hpp new file mode 100644 index 00000000..76bda6de --- /dev/null +++ b/engine/strata/include/strata/kernels/cpu/pool.hpp @@ -0,0 +1,272 @@ +// include/strata/kernels/cpu/pool.hpp - P2.S3: the CPU expert pool. +// +// A layer runs TEN experts against ONE activation, and the expert kernel is DRAM-bound (Memory/LEDGER.md L9: +// 42.55 GB/s on 6 cores, tracking core count almost exactly). So the pool's job is not to be clever - it is +// to keep every physical core reading expert bytes for the whole layer, and to be cheap enough that ten +// dispatches per layer cost less than one expert. +// +// WHY A FLAT BATCH AND NOT A RING. P2.S3 describes a "lock-free SPMC ring", which is what you need when +// jobs arrive while others are still being computed. Here they cannot: the host must SUM all ten outputs +// before the next layer starts, so a layer is a barrier by construction and the queue never holds more than +// one batch. A ring would add a wrap-around to get wrong and buy nothing. What is kept from the phase is +// the part that matters: `head`/`done` are single fetch_add counters, one claim per worker, no lock. +// +// THE COMPLETION PROTOCOL, because this is where a pool usually goes wrong. `run()` waits for `done == n` +// AND for every worker to PARK. Waiting only for `done` is not enough: a worker can still be inside the +// drain loop after its last `done` increment, and the host resetting `head` underneath it would let that +// worker claim a job from the NEXT batch before the next batch has been published. +// +// **AND `parked` IS NOT ENOUGH EITHER (issue #29).** A worker that went to sleep (after `kSpinBeforeSleep`) is +// still counted as parked when it wakes, so for a moment after it has seen a new epoch the host believes it is +// idle. On a card with most experts in VRAM the workers sleep in the middle of a request, tiny batches finish +// before a sleeper is awake, and that moment comes round constantly: a late worker could claim from the NEXT +// batch while the host was still writing it, run a job twice, or add to `done` after the host had reset it - +// and `done != n` then never ended, with the GPU waiting on the pool forever. So every claim carries its +// batch: `head` is one 64-bit word `epoch | njobs | index`, a claim is a CAS that only succeeds for the epoch +// the worker woke for, and a late worker's claim simply fails. A claim that succeeds belongs to the current +// batch, whose description the host cannot change until that job's `done` has landed. +#pragma once + +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/native_expert.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels::cpu { + +/// One expert evaluation. `act` is SHARED and read-only across the whole batch - that sharing is the point +/// of `s2_expert_vnni_q` and it is what saves 480 redundant activation conversions per token. +struct ExpertJob { + const uint8_t* blob = nullptr; ///< one 1,382,400-byte expert + const ActQ* act = nullptr; ///< the layer's quantized activation, shared + float* out = nullptr; ///< H floats, written by exactly one worker + float weight = 1.0f; ///< the router weight; applied by the HOST, not here + int slot = -1; ///< the job's index, for diagnostics +}; + +/// Plan v0.3 P6: one expert for the `nt` tokens of a verify window that were routed to it. Every token's output +/// is bitwise the single-token job's. +struct ExpertJobMulti { + const uint8_t* blob = nullptr; + int nt = 0; + const ActQ* act[MAXT] = {}; + float* out[MAXT] = {}; + /// Plan v0.3 P6: a native pack's activations (the layer's `vec_dot_type`), one per token. + const void* nact[MAXT] = {}; +}; + +/// How worker threads are allocated across physical/logical CPU cores (#272). `All` is the layout the pool has +/// always used and the default; the hybrid-aware ones are opt-in (--pool-affinity auto|p-cores). +enum class PoolAffinity { + Auto, ///< Hybrid: prioritize physical P-cores, then SMT, then E-cores (defaults to P-core count) + PCores, ///< Restrict workers strictly to Performance cores and their SMT siblings + All, ///< The default: one worker per physical core in the OS's order, without hybrid distinction +}; + +struct CpuTopology { + bool is_hybrid = false; + int p_cores = 0; ///< Physical performance cores + int p_threads = 0; ///< Total logical threads on performance cores + int e_cores = 0; ///< Efficient cores + std::vector worker_cores; ///< Ordered logical core IDs for workers (excluding host if skip_first) + int host_core = -1; ///< Logical core reserved for host thread +}; + +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity = PoolAffinity::All); + +/// One logical processor per PHYSICAL core, so a worker is never scheduled onto an SMT sibling of another +/// worker. On the 6-core/12-thread machine this project measures on, `hardware_concurrency()/2` workers on +/// logical processors 0..5 would put every worker on a sibling pair and halve the useful bandwidth - which is +/// exactly the kind of error that shows up as "the CPU path is slower than the model says" with no clue why. +/// +/// `skip_first` drops the first core, which P2.S3 reserves for the host loop. +std::vector physical_cores(bool skip_first, PoolAffinity affinity = PoolAffinity::All); + +/// **THE RESERVATION IS A FICTION UNLESS THE HOST IS ACTUALLY PUT THERE.** +/// +/// `physical_cores(true)` keeps the workers off the first physical core so that the host loop can spin on +/// `cudaEventQuery` without stealing a worker's cycles. Nothing in the pool can enforce the other half of +/// that, so this is it: the host loop calls this on entry and restores on exit. +/// +/// MEASURED, and this is why it exists: the pool runs at **36.32 GB/s on 5 workers with nothing else running** +/// - exactly 5/6 of L9's 44.14 on 6 - and at **26.9 GB/s inside the host loop**, where the unpinned spinning +/// host is free to land on a worker's core or its SMT sibling. That 1.35x is not the kernel. +/// +/// Returns the PREVIOUS affinity mask, or -1 if the platform refused; pass it to `restore_thread_affinity`. +long long pin_current_thread(int core); +void restore_thread_affinity(long long previous); + +class ExpertPool { +public: + /// `n_workers <= 0` means "every physical core except the first". Workers are pinned to physical cores + /// (minus core 0 by default) and each owns one `ExpertScratch`, so nothing in the token path allocates. + /// + /// **`host_works` PUTS THE HOST THREAD INTO THE DRAIN (R2.2's FIRST HALF).** + /// + /// The pool reserves core 0 for the host loop so the doorbell spin cannot steal a worker's cycles - but + /// during `run()` the host does not spin, it waits, so core 0 is idle for the whole drain. Measured on the + /// 6-core machine this project targets: the engine's pool drains at **33.7 GB/s** (663.6 MB of expert + /// blobs in 19.71 ms/token) where the same kernel on 5 workers should reach 5/6 x 44.14 = 36.8 and the + /// machine measures 44.14 GB/s on all six. So the sixth core is being paid for and not used. + /// + /// With `host_works`, `run()` claims jobs itself instead of spinning on `done_`, and the pool is six + /// threads on six cores. `false` is the A/B arm and exists so the change is measurable rather than + /// asserted - the counter it moves is `pool phases ... drain`, which is host-side and needs no profiler. + explicit ExpertPool(int n_workers = 0, bool pin = true, bool host_works = true, + PoolAffinity affinity = PoolAffinity::All); + /// The watchdog's view of the pool (issue #31): the batch, the counters, every thread's state. + void diag(std::FILE* f) const; + ~ExpertPool(); + ExpertPool(const ExpertPool&) = delete; + ExpertPool& operator=(const ExpertPool&) = delete; + + int workers() const { return n_; } + /// Whether the host thread also drains. Reported at startup, because "the engine adapts to the machine it + /// is on" is only true if the engine says which adaptation it took. + bool host_works() const { return host_works_; } + + bool is_hybrid() const { return topo_.is_hybrid; } + int p_cores() const { return topo_.p_cores; } + int p_threads() const { return topo_.p_threads; } + int e_cores() const { return topo_.e_cores; } + PoolAffinity affinity() const { return affinity_; } + + /// Publish `n` jobs, then block until every one has been claimed AND every worker has parked. + /// `jobs` must outlive the call (it does, and the workers never touch it afterwards). + void run(ExpertJob* jobs, int n); + + /// Plan v0.3 P4: the same outputs as `run`, bitwise, with every expert split by rows across all threads + /// (gate/up rows, then the intermediate's quantization, then down rows). With fewer experts than threads - + /// the case once the VRAM tier takes half of them - `run` leaves cores idle and each expert streams at one + /// core's bandwidth; this streams every expert at all of them. At most `kMaxSplit` experts. + void run_split(ExpertJob* jobs, int n); + static constexpr int kMaxSplit = 16; + /// Plan v0.3 P6: `run_split` for multi-token jobs (at most `kMaxSplitMulti`); the rows of each expert are + /// read once for all of its tokens. + void run_split_multi(ExpertJobMulti* jobs, int n); + /// Plan v0.3 P6: the same for a native pack's layer (ggml-cpu arithmetic, `nact` activations). + void run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n); + static constexpr int kMaxSplitMulti = 96; + /// run_split_multi's phases, accumulated ms: gate/up rows, the intermediate quantization, down rows. + double ms_multi_gu = 0, ms_multi_q = 0, ms_multi_down = 0; + int64_t multi_bytes = 0; + + /// Total `_mm_pause` iterations spent waiting, over all workers, is no longer counted - see the note on the + /// atomics below. It was a LOCKED read-modify-write in the park loop, so measuring the contention added to + /// it. + long long pauses() const { return 0; } + + /// **WHERE `run()` SPENDS ITS TIME, in milliseconds accumulated over its lifetime.** Three phases per + /// layer - wait for every worker to be parked, wait for the drain, wait for them to re-park - and until now + /// all three were reported as one number. Without the split there is no way to tell a pool that is slow at + /// the WORK from one that is slow at the SYNCHRONISATION, and those need opposite fixes: the first is a + /// kernel problem and the second is a barrier problem. + /// + /// Only the host thread touches these, in `run()`, so they need no atomics. + void phase_ms(double& wait_park, double& drain, double& repark) const { + wait_park = ms_wait_park_; + drain = ms_drain_; + repark = ms_repark_; + } + + /// **A PARKED WORKER SPINS FOR THIS LONG, THEN SLEEPS.** The park is a `_mm_pause` spin because a layer's + /// batches are microseconds apart and a wake-up from the OS costs more than that. But a spin that never ends + /// keeps every worker's core at 100% while the engine waits for a request - issue #4, "CPU 50% even when + /// doing nothing" (7 of the 5700X's 16 threads). Between requests the workers block on `sleep_cv_`. NOT only + /// between requests: with most experts in VRAM (a 24 GB card) many layers have no CPU work, so the workers + /// also sleep mid-request - which the claim protocol above must survive (issue #29). + /// `STRATA_POOL_SPIN_US` overrides it (a test knob: a short spin makes the workers sleep constantly). + static constexpr std::chrono::milliseconds kSpinBeforeSleep{20}; + /// A pool wait that sees no completion for this long is a bug; the engine stops with a message instead of + /// spinning forever, and the server starts it again (issue #29). + static constexpr std::chrono::seconds kStall{60}; + +private: + void worker(int id); + void drain(int id, ExpertScratch& scratch, uint32_t epoch); + void run_phase(int mode, int n_tasks); + /// Claim the next job of batch `epoch`, or -1 (that batch is exhausted, or it is not the current one). + int claim(uint32_t epoch); + /// Publish the batch whose description the caller has just written: reset `done`, then `head`, then the epoch. + uint32_t begin_batch(int n); + /// The host's waits, bounded by `kStall`. + void wait_parked(const char* what); + void wait_done(int n); + /// Bump `epoch_`, and wake the workers that went to sleep. Every publish goes through here. + void publish(); + + int n_ = 0; + bool host_works_ = true; + ExpertJob* jobs_ = nullptr; + int njobs_ = 0; + /// The host's own scratch when `host_works_`. A separate object rather than a share of `scratch_[i]`, + /// because a worker may own any index and the two must not be able to collide. + ExpertScratch host_scratch_; + // `run()`'s three phases, accumulated. Host-thread only; see `phase_ms`. + double ms_wait_park_ = 0.0; + double ms_drain_ = 0.0; + double ms_repark_ = 0.0; + // ---- EACH ATOMIC GETS ITS OWN CACHE LINE, AND THE SPIN COUNTER IS GONE. (Review finding C3.) + // + // These were six adjacent atomics, which put `head_`, `done_`, `parked_` and `epoch_` on ONE cache line - + // the four that workers and the host actually contend on, invalidating each other on every access. + // + // Worse, the parked spin did `pauses_.fetch_add(1)` on EVERY iteration: a LOCKED read-modify-write, five + // workers against one line, at roughly one iteration per `_mm_pause`. So the line the host must WRITE to + // publish work (`epoch_`) and READ to confirm the workers are parked (`parked_`) was being hammered by the + // very threads waiting for it. That is contention the pool imposes on itself. + // + // The counter was diagnostic only - `pauses()` was read in one place, to print a number nothing branched on + // - so it is deleted rather than amortised. `alignas(64)` then stops the remaining four sharing. + // issue #31 diagnostics: each worker's state (kParked, kSleeping, kBetween, or the job it runs) and the host's + // (kIdle, kWaitParked, kWaitDone, or its job), printed by the serve watchdog through `diag` + static constexpr int32_t kParked = -1, kSleeping = -2, kBetween = -3, kIdle = -10, kWaitParked = -11, + kWaitDone = -12; + std::unique_ptr[]> wstate_; + std::atomic hstate_{kIdle}; + std::atomic hstate_ms_{0}; + alignas(64) std::atomic head_{0}; // epoch << 32 | njobs << 16 | next index (issue #29) + alignas(64) std::atomic done_{0}; + alignas(64) std::atomic parked_{0}; + alignas(64) std::atomic epoch_{0}; + alignas(64) std::atomic stop_{false}; + // The sleep after `kSpinBeforeSleep`. `sleepers_` is how `publish` knows whether anyone needs waking, so the + // token path pays one uncontended load per publish and never takes the mutex while the workers spin. + alignas(64) std::atomic sleepers_{0}; + std::mutex sleep_mu_; + std::condition_variable sleep_cv_; + std::chrono::microseconds spin_before_sleep_{kSpinBeforeSleep}; + std::vector threads_; + std::vector scratch_; // one per worker: no allocation, no false sharing of the hot data + // run_split state: mode 0 = whole experts, 1 = gate/up row parts, 2 = down row parts + int mode_ = 0; + int parts_a_ = 1, parts_b_ = 1; + struct SplitBuf { + alignas(64) float ff[FF]; + ActQ a2; + }; + std::vector split_; + // run_split_multi state: mode 3 = gate/up row parts, 4 = down row parts + ExpertJobMulti* mjobs_ = nullptr; + int64_t mrows_ = 0; // rows of the current multi phase across all its experts (n * FF, then n * H) + int mtasks_ = 1; // equal row ranges the phase is cut into + struct SplitBufMulti { + alignas(64) float ff[MAXT][FF]; + ActQ a2[MAXT]; + alignas(64) uint8_t hq[MAXT][kNativeHBytes]; // plan v0.3 P6: native down activations + }; + const NativeFmt* nfmt_ = nullptr; + std::vector split_multi_; + PoolAffinity affinity_ = PoolAffinity::All; + CpuTopology topo_; +}; + +} // namespace strata::kernels::cpu diff --git a/engine/strata/include/strata/kernels/cvec.hpp b/engine/strata/include/strata/kernels/cvec.hpp new file mode 100644 index 00000000..a447eb52 --- /dev/null +++ b/engine/strata/include/strata/kernels/cvec.hpp @@ -0,0 +1,61 @@ +// include/strata/kernels/cvec.hpp - a control vector on the residual stream: the engine's side of llama.cpp's +// `llama_adapter_cvec` with the `--cvec-mode` / `--cvec-dir` extension of the `experimental-speed-projection` +// package (its `02-cvec-projection-mode.patch`, and `01-qwen4exp-cvec-hooks.patch` for WHERE it applies). +// +// After layer l's FFN write - llama.cpp's `build_cvec(res_hc, il)` right after the layer's second +// `build_hc_combine` - every one of the hc residual streams h of every token becomes +// +// project: h <- h - s_l (h . v_l) v_l v_l = d / |d|, s_l = |d|, d = the scaled direction +// add: h <- h + d llama.cpp's stock additive control vector +// +// for l in [first, last]. `d` is the GGUF's `direction.` times the file's scale (summed over files), with +// src = l (per-layer) or one fixed layer (single:L, project mode only), exactly as llama.cpp's loader places it; +// layer 0 has no direction. Off unless a vector is loaded (--control-vector-scaled); a loaded one is switched +// per request through a device flag, so the captured graphs are the same either way. With the flag off the +// result is bit-identical to the engine without a vector: the kernel then only applies the pending residual +// write, with the fused read's own arithmetic. +#pragma once + +#include +#include +#include + +namespace strata::kernels { + +struct Cvec { + const float* dir = nullptr; ///< device, n_layers * n_embd: project = the unit v_l, add = d_l; zero rows elsewhere + const float* s = nullptr; ///< device, n_layers: project = s_l, add = 1; 0 = the layer is not steered + const int* on = nullptr; ///< device int: 0 = this request runs the stock model + int mode = 0; ///< 0 = project, 1 = add + int first = 0, last = -1; ///< the steered layers, inclusive + int64_t n_embd = 0, hc = 0; + bool loaded() const { return dir != nullptr; } + /// Layer l's FFN write is followed by the vector (with a real direction there). Decided at load time, never + /// per request: it changes where the residual write happens, so the graphs depend on it. + bool covers(int64_t l) const { return loaded() && l >= first && l <= last && l < (int64_t) steered.size() && steered[(size_t) l]; } + std::vector steered; ///< host copy of s_l != 0 +}; + +/// The loaded vector (empty until `cvec_upload`). +const Cvec& cvec(); + +/// Upload a vector built by the loader: `dir` is n_layers * n_embd, `s` n_layers (see `Cvec`). Starts ON. +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& err); + +/// A layer split: put the loaded vector's tables on the CURRENT device too (cvec_apply uses the tables of the device +/// it runs on). No-op without a vector or when this device has them already. +bool cvec_replicate(std::string& err); + +/// The per-request switch, on every device that holds the vector. Synchronizes them when it changes, so call it +/// between requests. +void cvec_set_enabled(bool on); +bool cvec_enabled(); + +/// Layer `layer`'s vector on T tokens' residual stacks (`R + t * r_ld`, hc streams of n_embd). With `write`, the +/// pending FFN write `R += bo * 2 sigmoid(inj / hc)` (the fused read's arithmetic) is applied first, for callers +/// whose writes are folded into the next layer's read; without it, R must already hold the layer's output. +void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, + int64_t inj_ld, bool write, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/dequant_bf16.hpp b/engine/strata/include/strata/kernels/dequant_bf16.hpp new file mode 100644 index 00000000..5a8ed088 --- /dev/null +++ b/engine/strata/include/strata/kernels/dequant_bf16.hpp @@ -0,0 +1,27 @@ +// include/strata/kernels/dequant_bf16.hpp - plan v0.3 P5: native GGUF blocks -> BF16 on the device, for the +// tensor-core GEMMs of batched prompt processing. +// +// One thread per 32-element group, transcribed from the reference `dequantize_row_*` functions of the pinned +// llama.cpp (`ggml/src/ggml-quants.c`, MIT): Q4_0 (2), Q5_0 (6), Q8_0 (8), Q3_K (11), Q4_K (12), Q5_K (13), Q6_K (14), +// IQ4_NL (20), IQ4_XS (23) and Q2_0 (42). A row-major (n_rows, n_cols) tensor of blocks becomes a row-major BF16 +// matrix; `n_cols` must be a multiple of the type's block size. +#pragma once + +#include + +namespace strata::kernels { + +bool dequant_bf16_supported(int ggml_type) noexcept; + +/// `rows` rows of `cols` values starting at block row `row0` (so a caller can dequantize a slice of a tensor). +void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, + void* stream); + +/// The same into FP16 bits (the prompt path's quantized-weight GEMMs: Q2_0 values are exact in FP16). +void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, + void* stream); + +/// The same into FP32 (tests and small tensors). +void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/dequant_s2.hpp b/engine/strata/include/strata/kernels/dequant_s2.hpp new file mode 100644 index 00000000..2603f48d --- /dev/null +++ b/engine/strata/include/strata/kernels/dequant_s2.hpp @@ -0,0 +1,18 @@ +// include/strata/kernels/dequant_s2.hpp - the S2 decode, host-callable. +// +// S2 is Q2_0's canonical form and 31.64 GiB of the artifact is Q2_0, so this is the hottest decode in the +// engine. Plane layout is docs/pack-format.md's: codes packed 4 per byte LSB-first (element i at byte i/4, +// bits (i%4)*2) and one FP32 scale per group of 64. Decode is `(code - 1) * scale` with the subtraction in +// the INTEGER domain, which is what makes it bit-exact (docs/pack-format.md §3.1). +#pragma once + +#include + +namespace strata::kernels { + +// Decode `n_blocks` S2 blocks. `codes` is n_blocks*16 bytes, `scales` n_blocks floats, `out` n_blocks*64 +// floats. All device pointers. Synchronises before returning, so a caller can read `out` immediately - +// correctness first; overlap is a Phase 3 concern. +void dequant_s2(const uint8_t* codes, const float* scales, float* out, int64_t n_blocks); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/dp4a.hpp b/engine/strata/include/strata/kernels/dp4a.hpp new file mode 100644 index 00000000..cbca6a9a --- /dev/null +++ b/engine/strata/include/strata/kernels/dp4a.hpp @@ -0,0 +1,42 @@ +// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have. +// +// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time +// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is +// missing exactly two things the i-quant kernels rely on: +// +// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). Its fallback below is +// llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), which is the reference for the kernels in this +// directory: they are transcribed from llama.cpp's vecdotq.cuh, and that wrapper's operands are the same +// sites. It reinterprets the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a` +// does for these calls, so the fallback is bit-exact rather than merely close. +// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that +// spins without it is correct, merely busier. +// +// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX +// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is +// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is +// HIP's own `__nanosleep`. +#pragma once + +#include + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610 +__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) { + const int8_t* a8 = (const int8_t*) &a; + const int8_t* b8 = (const int8_t*) &b; + return c + a8[0] * b8[0] + a8[1] * b8[1] + a8[2] * b8[2] + a8[3] * b8[3]; +} +#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c)) +#else +#define STRATA_DP4A(a, b, c) __dp4a((a), (b), (c)) +#endif + +/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a +/// contract, and only pre-Volta CUDA has no `__nanosleep` at all. +__device__ __forceinline__ void strata_spin_pause() { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700 + // sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed. +#else + __nanosleep(100); +#endif +} diff --git a/engine/strata/include/strata/kernels/elementwise.hpp b/engine/strata/include/strata/kernels/elementwise.hpp new file mode 100644 index 00000000..0136176c --- /dev/null +++ b/engine/strata/include/strata/kernels/elementwise.hpp @@ -0,0 +1,120 @@ +// include/strata/kernels/elementwise.hpp - the small ops a LAYER needs between its GEMVs, P2.S5. +// +// These are not interesting kernels and that is why they are in one file with one parity test: they are the +// glue in the per-layer graph, and glue that is written inline at each call site is glue with several +// slightly different float conventions. Three of them exist because a projection returns a DIFFERENT +// quantity from the one the next kernel wants: +// +// * `gdn_gate` turns (alpha, dt, ssm_a) into the recurrence's `gate`. `ref/gdn.py` L265: +// `gate = softplus(w_alpha . x + dt) * ssm_a`, with `softplus(x) = log1p(exp(x))` and the large-x branch +// `ggml_compute_softplus_f32` uses. `ssm_a` is NEGATIVE, which is what puts `exp(gate)` in (0,1). +// * `scale_inplace` applies the delta net's `1/sqrt(S)` to q. It is a separate op because +// `ref/gdn.py` says the two llama.cpp paths apply it in DIFFERENT places, so the caller has to own the +// choice rather than have it buried in a kernel. +// * `f32_to_f16_bulk` is what lets the f32 arithmetic of the mixer feed the fp16-activation GEMVs. +// `docs/activation-contract.md` is explicit that this is NOT the contract for a quantized weight - it is +// the bridge between two stages that both already exist, and the contract decision is a separate one. +// +// `silu_inplace` is here because `shared_expert` has its own copy inline and `gdn` needs one for the conv +// output; a third copy would be two too many. +#pragma once + +#include + +namespace strata::kernels { + +/// Decode one canonical embedding row already selected by the caller. Codes are +/// packed low bits first (2, 4 or 8 bits); scales/offsets are FP32 per group. +/// The optional offset defaults to +0. Multiplication and addition round separately, +/// matching the former CPU decoder. Launches asynchronously on the supplied stream. +/// The caller validates positive, divisible dimensions and row/plane bounds. +void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets, + int64_t n, int code_bits, int code_bias, int group_elems, + float* out, void* stream); + +/// `y[t][h] = softplus(alpha[t][h] + dt[h]) * ssm_a[h]`, one thread per (t, h). In place is not possible: +/// `alpha` is read and `gate` is written, and they are different buffers by construction. +/// +/// `h_v` is the number of v heads (48) and `n_tokens` the leading dimension; the real call is (1, 48). +void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens, + int64_t h_v, void* stream); + +/// `x[i] *= s`, in place. +void scale_inplace(float* x, int64_t n, float s, void* stream); +/// `dst[i] += src[i]`. **ADDED FOR R4's HIT/MISS SPLIT, WHERE THE TWO HALVES COME FROM DIFFERENT +/// ENGINES.** The CPU writes the misses into `parts` and the GPU writes the resident experts into a +/// buffer of their own, so that the GPU's work can run CONCURRENTLY with the CPU's instead of after it - +/// and the two are summed here, on the stream, immediately before `moe_combine` reads the result. +/// +/// The alternative - having the hit kernel write straight into `parts` - costs the whole overlap, because +/// the copy of the misses into `parts` cannot happen until the pool has produced them, and the kernel is +/// then ordered behind that copy. Measured: the drain fell 18.2 -> 10.2 ms and the token did not move. +void add_inplace(float* dst, const float* src, int64_t n, void* stream); + +/// `y[i] = f16(x[i])`, round-to-nearest-even, using the shared conversion in `f16_bits.hpp`. +void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream); + +/// `y[i] = bf16(x[i])`, for the weights whose contract is a bf16 activation - the BF16 `hc_*`, `ssm_alpha`, +/// `ssm_beta`, `indexer.*` and `ple_value` tensors. +/// +/// A SEPARATE ENTRY POINT FROM `f32_to_f16_bulk` and not a flag on it, because the two conversions are not +/// variants of one idea: fp16 has 5 exponent bits and 10 mantissa bits, bf16 has 8 and 7. A caller that +/// picked the wrong one would get a plausible tensor at the wrong precision - 2^-11 against 2^-9, a factor of +/// four - and nothing downstream could tell which was intended. +void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream); + +/// `x[i] = x[i] / (1 + exp(-x[i]))`, in place. +void silu_inplace(float* x, int64_t n, void* stream); + +/// `build_norm`: `y[r][c] = x[r][c] / sqrt(MEAN_c(x[r]^2) + eps) * w[c]`, over the LAST axis. +/// +/// QSA's norm, used on `attn_q` (24x256), `attn_k` (2x256) and `indexer.q_proj` (4x128). `w` may be null. +/// +/// **IT IS NOT `gdn_l2_norm` AND THE DIFFERENCE IS A FACTOR OF sqrt(cols) = 16 HERE.** `gdn_l2_norm` divides by +/// `sqrt(SUM(x^2) + eps)` and applies no weight; this divides by `sqrt(MEAN(x^2) + eps)` and multiplies by `w`. +/// Two kernels whose names both say "norm" and whose bodies differ in one `/ cols` is exactly the pair that +/// gets swapped, and swapping them produces a well-scaled, plausible tensor - so they are separate entry +/// points and the parity test asserts the two readings are OBSERVABLE apart rather than trusting the names. +/// +/// There is NO `(1 + w)` folding: `ref/qsa.py::rms_norm` is `y * w`, and `build_norm` in the source is +/// `ggml_rms_norm` followed by a plain multiply. Some norms in this artifact DO fold (the GDN path records +/// which); this one does not, and the same `sqrt(cols)`-sized argument applies to getting it wrong. +void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream); + +/// *seq = v in MAPPED PINNED memory - THE DOORBELL. A KERNEL and not cudaEventRecord, because round 199 +/// found that an event record inside a capture is SILENTLY DROPPED while a kernel is captured normally, and +/// round 209 measured the host seeing this one's result 0.050 ms into a 39.8 ms graph. +/// +/// It lives here because the caller that needs it - moe_layer - is a HOST translation unit, where +/// __global__ and <<<>>> do not exist. +/// *seq += 1 - AN INCREMENT, NOT A STORE OF A CALLER-SUPPLIED VALUE. A value passed in is evaluated on the +/// HOST at CAPTURE time, so a captured graph would ring the same number on every replay. Reading and +/// incrementing in memory is what makes the count advance under cudaGraphLaunch. +void doorbell_ring(uint32_t* d_seq, void* stream); + +/// Plan v0.3 P3 token graph: one thread spins until the host-written `*d_flag` equals the ring value `*d_seq` +/// (both mapped pinned memory), then fences so everything the host wrote before the flag is visible to the +/// nodes that follow. Captured once per layer between `pre[l]` and the parts copy; it is what lets one graph +/// hold the whole token (bench/micro/device_wait.cu: 5.2 us per handoff, no driver call). +void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream); + +/// Plan v0.3 P3 token graph: copy `n` floats from MAPPED pinned host memory (`src` is its device pointer) into +/// device memory with a kernel, so the handoff stays on the compute queue (a memcpy node is a copy-engine +/// operation, which WDDM submits separately and which measured 67 flushes per token). +void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream); +/// `rows` rows of `width` floats from mapped memory, except the rows listed in hit_rows[0, *count) (device), +/// which are written +0.0 instead (a verify window's GPU-computed entries: the pool leaves zeros there). +void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows, + const int32_t* count, void* stream); + +/// Plan v0.3 P3: the doorbell's payload and its ring in ONE kernel. Copies `x` (n floats), `ids` and `weights` +/// (k each) into the mapped host regions, fences, and increments the mapped sequence number - replacing three +/// device-to-host memcpy nodes (copy-engine operations in the middle of the layer chain) and the ring kernel. +void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, + int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream); + +/// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA +/// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer. +void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/f16_bits.hpp b/engine/strata/include/strata/kernels/f16_bits.hpp new file mode 100644 index 00000000..396d690a --- /dev/null +++ b/engine/strata/include/strata/kernels/f16_bits.hpp @@ -0,0 +1,104 @@ +// include/strata/kernels/f16_bits.hpp - the fp16 conversions, written out, as bits. +// +// WHY THIS IS NOT `__float2half`. Round 193 found `__float2half` producing 0x2600 for a value whose correct +// fp16 encoding is 0x26DB, and 0x3C01 for a value that is exactly 1.0 - i.e. wrong bits, not a rounding +// difference. The cause was never isolated (it is either `__float2half` itself or `__half_as_ushort`), so +// `src/kernels/cuda/quantize_act.cu` replaced it with the version below, which then came out byte-exact over +// all 20,480 blocks of the fixture. `shared_expert.cu` carries the same function privately for the same +// reason. Three copies of a converter whose failure mode is silent wrong bits is two copies too many, so the +// copy lives here and the kernel and its TEST both include it - with the test checking it against vectors +// generated by numpy's float16 (an oracle that shares no code with this), which is what neither private copy +// had. +// +// The rounding is ROUND-TO-NEAREST-EVEN, which is what numpy's `.astype(np.float16)` does and what IEEE-754 +// specifies for the default mode. The three interesting regimes are all handled explicitly and all three are +// covered by the test's oracle vectors: +// +// * normal - exponent fits, mantissa is rounded from 13 surviving bits with a sticky remainder +// * subnormal - the implicit 1 is restored and the result is shifted right, so the rounding point MOVES +// * overflow - exp >= 31 saturates to inf (0x7C00) and keeps the sign; a NaN input stays a NaN +// +// `f32_from_f16` deliberately does NOT round: it is used to compare against a reference that holds the same +// bits, so it only has to be exact. +#pragma once + +#include +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_HD __host__ __device__ +#else +#define STRATA_HD +#endif + +namespace strata::kernels { + +/// Round-to-nearest-even f32 -> fp16, returned as raw bits. +STRATA_HD inline uint16_t f16_from_f32(float f) { + uint32_t x; +#if defined(__HIP_DEVICE_COMPILE__) + __builtin_memcpy(&x, &f, 4); +#else + std::memcpy(&x, &f, 4); +#endif + const uint32_t sign = (x >> 16) & 0x8000u; + const uint32_t rawexp = (x >> 23) & 0xFFu; + int exp = (int) rawexp - 127 + 15; + uint32_t man = x & 0x7FFFFFu; + // TWO different things reach here and they must not be conflated: an f32 inf/NaN (raw exponent 255) stays + // an inf/NaN, and a FINITE value too large for fp16 (1e30) SATURATES TO INF. The version of this function + // in quantize_act.cu and shared_expert.cu tests `if (exp >= 31) return sign | 0x7C00 | (man ? 0x200 : 0)` + // and therefore returns a NaN for every overflowing finite value - which their own fixtures cannot see, + // because all of their values are O(1). Round 198's numpy oracle caught it here on the first run (1e30, + // 65536, 1e45: numpy says inf, the conflated test said NaN). + if (rawexp == 0xFFu) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); // inf, or a quiet/NaN + if (exp >= 31) return (uint16_t) (sign | 0x7C00u); // finite overflow -> inf + if (exp <= 0) { + if (exp < -10) return (uint16_t) sign; // underflows to a signed zero + man |= 0x800000u; // restore the implicit 1 + const uint32_t sh = (uint32_t) (14 - exp); + uint32_t h = (man >> sh) & 0x3FFu; + const uint32_t rem = man & ((1u << sh) - 1u); + if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h; + return (uint16_t) (sign | h); + } + uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13)); + const uint32_t rem = man & 0x1FFFu; + if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; // the carry may bump the exponent + return h; +} + +/// Exact fp16 bits -> f32. No rounding, no exceptions: every one of the 65,536 inputs maps to a value f32 +/// represents exactly, including the subnormals (which is why the `ex == 0` case cannot be skipped). +STRATA_HD inline float f32_from_f16(uint16_t h) { + const uint32_t sign = (uint32_t) (h & 0x8000u) << 16; + const uint32_t ex = (h >> 10) & 0x1Fu, man = h & 0x3FFu; + uint32_t out; + if (ex == 0) { + // Subnormal or zero. The value is `man * 2^-24`, so after `s` left shifts the leading 1 reaches bit + // 10 and the value is `(1 + frac) * 2^(-14-s)`: the f32 exponent field is 113 - s and `frac` is the low + // ten bits. Flushing these to zero - which the two private copies of this function in the tree do - + // maps 0x0001 to 0.0 instead of 2^-24, a 100% relative error on any KL-quant scale that lands here. + if (man == 0) { + out = sign; + } else { + uint32_t m = man; + int s = 0; + while ((m & 0x400u) == 0) { m <<= 1; ++s; } + out = sign | ((uint32_t) (113 - s) << 23) | ((m & 0x3FFu) << 13); + } + } else if (ex == 31) { + out = sign | 0x7F800000u | (man << 13); + } else { + out = sign | ((ex - 15 + 127) << 23) | (man << 13); + } + float f; +#if defined(__HIP_DEVICE_COMPILE__) + __builtin_memcpy(&f, &out, 4); +#else + std::memcpy(&f, &out, 4); +#endif + return f; +} + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/fused_gdn.hpp b/engine/strata/include/strata/kernels/fused_gdn.hpp new file mode 100644 index 00000000..0cf7c66c --- /dev/null +++ b/engine/strata/include/strata/kernels/fused_gdn.hpp @@ -0,0 +1,35 @@ +// include/strata/kernels/fused_gdn.hpp - plan v0.3 P3: the gated delta-net step and its output norm in ONE kernel. +// +// The native step (after llama.cpp's gated_delta_net.cu) gives each warp one (head, column) and strides its 32 +// lanes over the 128 ROWS of the state, which is stored `[row][head][col]`: every lane's load is 24.5 KB from its +// neighbour's, so each 32 B sector delivers 4 useful bytes - 47.6 us per layer for 6.3 MB of state traffic. Here a +// block owns one whole head, its 512 threads are (row group of 32, column), and a row's 128 columns are one +// contiguous 512 B load. With the head in one block, the per-head RMS norm, the norm weight and the sigmoid(z) +// gate of `gdn_out_norm` run in the same kernel. +// +// S <- g S + k (beta (v - g S^T k))^T (g = exp(gate[head]), per value head; q/k shared by h_v / h_k heads) +// o = (S^T q) / sqrt(128) +// y = rmsnorm(o) * gamma * sigmoid(z) +#pragma once + +#include + +namespace strata::kernels { + +/// The 4-tap causal conv + SiLU over all `channels` (history is `[channel][3]`, updated), then the L2 norm of +/// each of the first `qk_heads` 128-channel heads (q then k), eps as the native `l2_norm` (x / sqrt(sum + eps)). +/// One block per 128-channel head; replaces conv_silu + two l2_norm launches. +void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads, + float eps, void* stream); + +/// alpha and beta, both `(h_v, n_embd)` BF16 against the FP32 activation, with their epilogues: +/// gate = softplus(alpha + dt) * ssm_a, beta = sigmoid(beta). One warp per row; replaces two MMVF launches and +/// two elementwise kernels. +void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a, + float* gate, float* beta, int n_embd, int h_v, void* stream); + +void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, + void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/fused_gr.hpp b/engine/strata/include/strata/kernels/fused_gr.hpp new file mode 100644 index 00000000..40eff30f --- /dev/null +++ b/engine/strata/include/strata/kernels/fused_gr.hpp @@ -0,0 +1,65 @@ +// include/strata/kernels/fused_gr.hpp - plan v0.3 P3: the hyper-connection read in TWO kernels, with the +// previous half's write folded in. +// +// The native path spends six kernels per `gr_read` (norm, down MMVF, silu, up MMVF, gate+mean, inject MMVF) and +// one per `gr_write`, 96 + 96 times per token, and its up projection (10240 rows of 320) runs one 160-thread +// block per row: 20.6 us for 6.5 MB. Here: +// +// fused_gr_down : R' = R + bo_prev * 2 sigmoid(inj_prev / hc) (only when `apply`, computed on the fly) +// rs[c] = rsqrt(mean(R'[c]^2) + eps), xn = R' * w_norm * rs +// lo[k] = silu((w_down[k] . xn) / hc) k < hc_lr +// inject[c] = w_inject[c] . xn when w_inject is given +// fused_gr_up : R <- R' in place for this block's columns (when `apply`) +// mixed[d] = mean_c xn[c,d] * sigmoid(w_up[c*n_embd + d] . lo) +// +// FP32 activations and BF16 weights, like the native MMVF contract; the summation order differs from it (G-C +// judges the result). Geometry is the artifact's: n_embd 2560, hc 4, hc_lr 320. `inj_prev` and `inject_out` +// must be different buffers (every block reads the former while one block writes the latter). +#pragma once + +#include + +namespace strata::kernels { + +struct FusedGrArgs { + const float* R = nullptr; ///< (hc, n_embd), read by `down`; `up` updates it in place when apply + float* R_out = nullptr; ///< == R for the in-place update + bool apply = false; ///< fold the previous half's gr_write + const float* bo_prev = nullptr; ///< that half's block output, n_embd + const float* inj_prev = nullptr; ///< that half's injection, hc + const float* w_norm = nullptr; ///< (hc * n_embd) f32 + const uint16_t* w_down = nullptr; ///< bf16 [hc_lr][hc*n_embd] + const uint16_t* w_up = nullptr; ///< bf16 [hc*n_embd][hc_lr] + const uint16_t* w_inject = nullptr;///< bf16 [hc][hc*n_embd], or null (the final mixer) + float eps = 1e-6f; + float* lo = nullptr; ///< workspace, hc_lr floats + float* rs = nullptr; ///< workspace, hc floats + float* inject_out = nullptr; ///< hc floats (when w_inject) + float* mixed = nullptr; ///< n_embd +}; + +bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr); +void fused_gr_read(const FusedGrArgs& a, void* stream); + +/// Plan v0.3 P6: the same read for up to 8 tokens that share the weights (a verify window): the weights are read +/// once for all of them. `a[t]` is token t's arguments (its own R, pending write, lo, rs, inject, mixed; the four +/// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every +/// token's outputs are bitwise `fused_gr_read(a[t])`. +constexpr int kFusedGrMaxT = 8; +void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, + unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); + +/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing +/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token +/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm +/// one block per token and stream, then the plain down projection) and staged (split's norm, and the down +/// projection's activations staged ahead by cp.async, two half-stream tiles in flight, bank-conflict-free). +/// `fused_gr_check` runs all of them and the single-token read on the current card with random weights and inputs +/// (1..8 tokens, with and without the pending write) and from then on uses there the newest one that agrees with the +/// plain read bit for bit; STRATA_HC_SPLIT=0 keeps the plain read, =1 stops at split. It runs once per card +/// (Verifier::init calls it) and prints which one runs. On a card it has not checked, `fused_gr_variant` is the +/// plain read unless STRATA_HC_SPLIT=1 or 2 names a variant. +void fused_gr_check(); +int fused_gr_variant(); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/gdn.hpp b/engine/strata/include/strata/kernels/gdn.hpp new file mode 100644 index 00000000..898e2a85 --- /dev/null +++ b/engine/strata/include/strata/kernels/gdn.hpp @@ -0,0 +1,97 @@ +// include/strata/kernels/gdn.hpp - the gated delta-net (GDN) layer's non-projection parts, P2.S2. +// +// Transcribed from `ref/gdn.py`, which is itself transcribed from `build_layer_attn_linear` and +// `build_delta_net_autoregressive`. The projections (`wqkv`, `wqkv_gate`, `ssm_out`) are the existing +// `s_gemv`/`s2_gemv` kernels; what lives here is everything BETWEEN them. +// +// Geometry of the real artifact (48 layers are GDN, 12 are QSA): +// +// S = state_size = 128 head_k_dim == head_v_dim +// h_k = 16 k/q heads h_v = 48 v heads (idx[h] = h % h_k) +// C = 2*128*16 + 128*48 = 10240 channels d_conv = 4 +// +// STATE LAYOUT. This is the one place the kernels deliberately differ from the reference, and the reason is +// coalescing. `ref/gdn.py` carries the state as (S, S, H_v) = (i, j, h); here it is **(S, H_v, S)** = +// (i, h, j), so that for a fixed i a warp walking consecutive j reads CONTIGUOUS memory. The state is a +// runtime buffer, not a weight, so this costs nothing to choose - but it must be said, because the two +// layouts index the same three numbers and a mismatch is silent. +// +// WHAT MAKES THE RECURRENCE PARALLEL, and it is worth stating because it is not obvious: +// +// dec = exp(gate) (h_v,) +// st = state * dec +// sk[h,j] = sum_i st[i,j,h] * k[idx[h]][i] +// d[h,j] = (v[h,j] - sk[h,j]) * beta[h] +// st[i,j,h] += k[idx[h]][i] * d[h,j] +// o[h,j] = sum_i st[i,j,h] * q[idx[h]][i] +// +// Every line touches ONLY the (j, h) column. Nothing couples one column to another, so one thread can own a +// column for the whole step and no barrier is needed anywhere in the recurrence. (The decay must still be +// applied BEFORE the rank-1 update - `ref/gdn.py` PROPERTY 5 pins that, and the test re-pins it here.) +#pragma once + +#include + +namespace strata::kernels { + +/// Geometry of one GDN layer. The real artifact: S = 128, h_k = 16, h_v = 48. +struct GdnShapes { + int64_t S = 0; ///< head dim, and the state's contracted axis + int64_t h_k = 0; ///< key/query heads (q and k are (h_k, S)) + int64_t h_v = 0; ///< value heads (v, z, o are (h_v, S)); h_v must be a multiple of h_k +}; + +/// One step of the delta-rule recurrence, IN PLACE on `state`. +/// +/// state (S, h_v, S) f32, j fastest, updated in place +/// q, k (h_k, S) already L2-normalised, and q ALREADY SCALED by 1/sqrt(S) - the two llama.cpp paths +/// apply that scale in different places, so the caller owns it +/// v (h_v, S) +/// gate (h_v,) the PRE-exp value; `dec = exp(gate)` is formed here +/// beta (h_v,) +/// o (h_v, S) +/// +/// The head pairing is `h % h_k` (MODULO), not `h / (h_v/h_k)` (INTERLEAVE). `ref/gdn.py` PROPERTY 8 and 11 +/// pin this and the test re-pins it, because both conventions produce well-formed output. +void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, float* o, const GdnShapes& s, void* stream); + +/// `ggml_ssm_conv` with the carried state prepended. Updates `conv_state` in place. +/// +/// conv_state (d_conv-1, channels) the previous d_conv-1 input columns, OLDEST FIRST +/// x (channels,) the new column +/// kW (channels, d_conv) the weight in GGML-NATIVE layout: `kW[c*d_conv + i]` is tap i of +/// channel c. The manifest gives `ssm_conv1d.weight` ne = [4, 10240], +/// i.e. ne0 = d_conv is the FAST axis, which is this and NOT the +/// reference's row-major (d_conv, channels). +/// out (channels,) +/// +/// out[c] = sum_{i +#include + +namespace strata::kernels { + +/// Select the activation precision for subsequent gr_read launches (default: false/BF16). +/// Configure before creating/capturing a session, and do not mutate concurrently with gr_read. +/// A captured graph retains the kernel variants chosen at capture; changing this flag cannot alter it. +/// This changes activation precision only; the existing FP32 reduction trees remain unchanged. +void gr_set_fp32_activations(bool enabled); + +/// Select pinned single-token BF16/F32 MMVF projections for subsequent gr_read launches (default false). +/// This implies FP32 activations regardless of gr_set_fp32_activations. Configure before session capture; +/// a captured graph retains its selected kernels. Requires even hc*n_embd and hc_lr, as MMVF reads pairs. +/// This also selects pinned weighted F32 RMSNorm and nonlinear/combine arithmetic. +/// Layer reads use fused HC pre; the final mixer (null w_inject) retains its unfused graph order. +/// Subsequent gr_write calls select pinned sigmoid/scatter arithmetic under the same setting. +void gr_set_native_mmvf(bool enabled); + +/// Geometry of the hyper-connection. The real model: n_embd = 2560, hc = 4, hc_lr = 320. +struct GrShapes { + int64_t n_embd = 0; ///< width of one residual stream + int64_t hc = 0; ///< number of streams in the stack + int64_t hc_lr = 0; ///< rank of the down/up bottleneck +}; + +/// Scratch for `gr_read`. EXPLICIT and caller-owned, because P2.T10 requires ZERO token-path allocations: +/// a hidden `cudaMalloc` on first use would satisfy every test here and fail the memory test in P2.S10. +/// +/// **IT MUST BE DEVICE MEMORY.** `gr_workspace_init` takes a raw pointer and does no checking, so handing it +/// a host buffer produces device kernels writing to a truncated host address - an illegal access whose +/// reported fault address is the low 32 bits of a host pointer, which reads as a wild pointer rather than as +/// the mistake it is. That cost one round in `gr_parity`; +/// +/// xn hc*n_embd floats the unrounded activated streams (the gated mean needs the unrounded value) +/// xq hc*n_embd uint16 bf16(xn), used by the default activation contract +/// lq hc_lr uint16 bf16(lo), used by the default activation contract +/// gated hc*n_embd floats xn * sigmoid(gate), before the mean over streams +/// lo hc_lr floats SiLU bottleneck, used by the FP32 activation contract +/// +/// `cudaMalloc(gr_workspace_bytes(s))`, then `gr_workspace_init(s, ptr, ws)` to carve it. +struct GrWorkspace { + float* xn = nullptr; + uint16_t* xq = nullptr; + uint16_t* lq = nullptr; + float* gated = nullptr; + float* lo = nullptr; + /// Set by `gr_workspace_init`. `gr_read` CHECKS it, so an under-sized buffer is a loud failure at the + /// first call instead of silent corruption - which is what a mis-ordered region table used to produce. + size_t bytes = 0; +}; + +/// Carves `base` (which must be DEVICE memory, or null to size only) into `out` and returns the bytes needed. +/// 16-byte aligned between regions. +size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out); +inline size_t gr_workspace_bytes(const GrShapes& s) { GrWorkspace w; return gr_workspace_init(s, nullptr, w); } + +/// `build_hc_mix`. ONE token: `R` is (hc, n_embd) with n_embd fastest, i.e. stream c starts at c*n_embd. +/// +/// w_norm (hc*n_embd) per-stream RMSNorm gamma, STORED AS (1 + w) by the converter +/// w_down (hc_lr, hc*n_embd) MANIFEST LAYOUT - row k is contiguous, `w_down[k*hc*n_embd + i]` +/// w_up (hc*n_embd, hc_lr) MANIFEST LAYOUT - row i is contiguous, `w_up[i*hc_lr + k]` +/// w_inject (hc, hc*n_embd) null for the FINAL mixer, which has no write-back to gate +/// +/// mixed (n_embd) = mean over streams of xn * sigmoid(bf16(lo) @ w_up.T) +/// inject (hc) = bf16(xn) @ w_inject.T, or untouched when w_inject is null +/// +/// `lo = silu((bf16(xn) @ w_down.T) / hc)` - the division by hc is INSIDE the silu, which is easy to read +/// past and changes the result materially. +/// With gr_set_fp32_activations(true), replace bf16(xn) and bf16(lo) by xn and lo respectively. +/// +/// **NO PERMUTATION: both matrices are taken exactly as the manifest stores them**, so the loader does nothing +/// to them. Both are coalesced because each projection assigns ONE WARP PER OUTPUT ROW and strides the +/// reduction axis across its 32 lanes: for a fixed output, consecutive lanes touch consecutive addresses in +/// either orientation. An earlier version assigned one THREAD per row, which is coalesced with itself and 32 +/// transactions away from its warp neighbours - see the history below. +/// +/// **HISTORY, because this kernel was the engine's worst and the reason is instructive.** The first version +/// was launched `<<<1, 256>>>` with `xn`/`xq` in shared memory, and at the real geometry it cost **2.67 ms per +/// call, 96 calls per token = 262 ms/token, about 3.8 tok/s, 134x off the 643 GB/s memory floor.** The cause +/// was isolated by elimination: NOT memory latency (four independent accumulator chains made it 17% SLOWER), +/// NOT the SM clock (`nvidia-smi` reported 2917 MHz and 99% utilisation throughout), and only partly +/// coalescing (transposing one of the two matrices gave 31% and transposing the other gave nothing). It was +/// ISSUE THROUGHPUT - ~8.4M iterations of 6-8 instructions issued by ONE of 48 SMs. +/// +/// This version splits the work the way the shapes want: `hc` blocks for the per-stream norm, one warp per +/// row for each of the two projections, and one block-tile for the mean. The transposes are gone because the +/// warp-per-row mapping makes them unnecessary. +void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up, + const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed, + float* inject, void* stream); + +/// `build_hc_combine`. `R_out[i] = R[i] + block_out[d] * w[c]` with `w[c] = 2*sigmoid(inject[c]/hc)`. +/// +/// The `2*sigmoid` is what CENTRES the gate on 1, so a zero injection is a plain residual add - the source +/// comment says so outright and `gr_write`'s test asserts it. Note the block output is added to EVERY stream +/// identically; only the weight is per-stream. +void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out, + void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/iq_kernels.hpp b/engine/strata/include/strata/kernels/iq_kernels.hpp new file mode 100644 index 00000000..c2bb2b5c --- /dev/null +++ b/engine/strata/include/strata/kernels/iq_kernels.hpp @@ -0,0 +1,69 @@ +// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, +// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's +// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding). +// +// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh, +// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it +// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract. +#pragma once + +#include +#include + +namespace strata::kernels { + +/// ggml type ids handled here. +bool iq_supported(int ggml_type) noexcept; +/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30). +bool embed_type_supported(int ggml_type) noexcept; +/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block). +size_t iq_row_bytes(int ggml_type, int64_t n) noexcept; + +/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks. +void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream); + +/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column). +void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream); + +/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32. +void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream); +void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream); +/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped +/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256). +void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, + int64_t n_embd, float* out, void* stream); +/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path +/// uses: row 2r = gate row r, row 2r+1 = up row r. +void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, + void* stream); + +/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks. +struct NativeExpertLayout { + int gu_type = -1, d_type = -1; + int64_t n_embd = 0, n_ff = 0; + size_t gu_row = 0, d_row = 0; // bytes per row + size_t up_off = 0, down_off = 0; // byte offsets inside the blob + size_t bytes = 0; // the whole blob +}; +NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the +/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). +bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; + +/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries. +size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff); + +/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries +/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1) +/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device. +void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, + int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream); + +/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; +/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give +/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. +void iq_set_old_kernels(bool old); +bool iq_old_kernels(); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/kv_q4.hpp b/engine/strata/include/strata/kernels/kv_q4.hpp new file mode 100644 index 00000000..930b628c --- /dev/null +++ b/engine/strata/include/strata/kernels/kv_q4.hpp @@ -0,0 +1,61 @@ +// include/strata/kernels/kv_q4.hpp - Q4_0 KV storage with Walsh-Hadamard rotation for the QSA layers (`--kv q4_0`). +// +// From PR #21 (code-martin). K and V are rotated by the orthonormal 256-point Hadamard matrix H before they are +// quantized to ggml's q4_0 (32 values per block: an fp16 scale + 16 bytes of 4-bit codes, 144 B per head per cell, +// 576 B per cell for K and V of both heads, vs 1,056 B in INT8). The rotation spreads a head's outlier channels +// over all 256 dimensions, which is what makes 4 bits usable. The query is rotated the same way, so +// = and the scores are unchanged, and the attention output (a mix of rotated values) is rotated +// back with H (self-inverse). What is lossy is the 4-bit rounding itself: measured, not assumed, in +// bench/results/2026-09-27-kv-q4. +// +// With KV streaming (--kv-resident) the codes live in the host copy and the resident slots like INT8's (KvHostPools +// k_q4/v_q4, the same block granule), so both options combine. +#pragma once + +#include "strata/kernels/qsa.hpp" + +#include + +namespace strata::kernels { + +inline constexpr int QK4_0 = 32; + +#pragma pack(push, 1) +struct block_q4_0 { + uint16_t d; // scale (fp16 bits) + uint8_t qs[QK4_0 / 2]; // 32 4-bit codes: element j in the low nibble of qs[j], j + 16 in the high one +}; +#pragma pack(pop) + +static_assert(sizeof(block_q4_0) == 18, "block_q4_0 must be 18 bytes"); + +/// Bytes per cell and KV head: 8 blocks of 32 for head_dim 256 -> 144. +inline uint64_t kv_q4_bytes_per_head(int head_dim) { return (uint64_t) (head_dim / QK4_0) * sizeof(block_q4_0); } + +/// Bytes per cell (one token, one layer): K and V of every KV head. +inline uint64_t kv_q4_bytes_per_cell(const QsaShapes& s) { + return (uint64_t) s.n_head_kv * kv_q4_bytes_per_head((int) s.head_dim) * 2; +} + +/// Orthonormal Fast Walsh-Hadamard Transform of rows of 256 floats (scale 1/16): its own inverse. +void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream); +inline void fwht256_inplace_cuda(float* data, int64_t n_rows, void* stream) { fwht256_cuda(data, data, n_rows, stream); } + +/// Append the (already rotated) cell at step[kStepPos]. With a host copy (KV streaming) it is written there too, +/// and to VRAM only if its block is resident. +void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host = nullptr); + +/// The prompt path: T consecutive (rotated) cells from pos0, K/V [T, n_head_kv, 256]; also into `stage` (identity +/// layout, the one-layer staging pool of a streamed session) when given. +void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K, + const float* V, const QsaShapes& s, void* stream, const KvHostPools* host = nullptr, + const KvHostPools* stage = nullptr); + +/// Gather step[kStepWidth] cells named by `ids` into FP16 scratch [id][kv_head][head_dim] (still rotated). +void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids, + const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, + uint16_t* v_scratch, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/kv_q8.hpp b/engine/strata/include/strata/kernels/kv_q8.hpp new file mode 100644 index 00000000..a535cc32 --- /dev/null +++ b/engine/strata/include/strata/kernels/kv_q8.hpp @@ -0,0 +1,41 @@ +// include/strata/kernels/kv_q8.hpp - plan v0.3 P7: 8-bit KV storage for the QSA layers. +// +// The FP16 KV pools cost 2 x 12,288 bytes per token over the 12 QSA layers; with the FP32 pooled indexer keys the +// engine allocates 29 KB per token, 7.65 GB at 262K (bench/results/2026-09-23-p7-int-audit), which cannot fit +// 12 GB. This stores K and V as int8 codes with one FP16 scale per 64 values (per cell, per KV head): +// scale = fp16(max|x| / 127), code = clamp(rint(x / scale), -127, 127), x' = fp16(code * scale) +// Per layer and token: 2 KV heads x 256 values x (K, V) = 1,024 values -> 1,024 B of codes + 32 B of scales, +// instead of 2,048 B in FP16. Over the 12 QSA layers: 12,672 B/token instead of 24,576 (3.3 GB at 262K, not 6.4). +// +// Only STORAGE changes: `kv_gather_q8_step` dequantizes the selected cells into the same FP16 scratch the +// attention kernels already read, so `qsa_attend` and the native attention adapter are untouched. Layout mirrors +// the FP16 pools: codes `[page][kv_head][page_size][head_dim]`, scales `[page][kv_head][page_size][head_dim/64]`. +#pragma once + +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/qsa.hpp" + +#include + +namespace strata::kernels { + +inline constexpr int KV_Q8_GROUP = 64; + +/// Bytes per cell (one token, one layer): K and V codes plus their scales. +inline uint64_t kv_q8_bytes_per_cell(const QsaShapes& s) { + return (uint64_t) s.n_head_kv * s.head_dim * 2 + (uint64_t) s.n_head_kv * (s.head_dim / KV_Q8_GROUP) * 2 * 2; +} + +/// Append the cell at step[kStepPos] (graph-capturable: position and page come from device memory). With a host +/// copy (KV streaming, `kv_stream.hpp`) the cell is written there too, and to VRAM only if its block is resident. +void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host = nullptr); + +/// Gather step[kStepWidth] cells named by `ids` into FP16 scratch `[id][kv_head][head_dim]`; the grid is sized by +/// `max_ids` (capacity), the kernel reads the real count from `step`. +void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, + const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, + const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/kv_stream.hpp b/engine/strata/include/strata/kernels/kv_stream.hpp new file mode 100644 index 00000000..90483fa0 --- /dev/null +++ b/engine/strata/include/strata/kernels/kv_stream.hpp @@ -0,0 +1,98 @@ +// include/strata/kernels/kv_stream.hpp - KV streaming for the QSA layers (docs/kv-streaming-design.md). +// +// A streamed QSA layer keeps its AUTHORITATIVE K/V in pinned, device-mapped host memory, laid out exactly as a +// fully resident pool with the identity page table would be. VRAM holds a pool of `n_slots` pages (one page = +// `page_size` = 4 cells = one indexer block, all KV heads, K and V: 4,224 B in int8), and the page table becomes a +// RESIDENCY MAP: `page_table[block]` is the slot holding that block, or -1. +// +// Every reader (`qsa_decode_attn_*`, `kv_gather_*`) is unchanged: it goes through the page table as before. What +// changes is that after the selection and before the attention, `kv_stream_resolve` makes every block the +// selection names resident - on device, inside the captured graphs: +// 1. one block of 1,024 threads walks the selected ids: a resident block gets this call's epoch and its clock +// reference bit, a missing block is claimed once (page_table -1 -> -2) into a miss list; +// 2. the same block picks one victim slot per miss with a CLOCK sweep (second chance) that never takes a slot +// this call uses, re-points the page table (old block -> -1, new block -> slot); +// 3. a copy kernel reads the missed blocks from the host copy (zero-copy, over PCIe) into their slots. +// Writers (`kv_append_*`) write the host copy always, and the slot only if the block is resident, so the slots +// never go stale and nothing needs invalidating - not after a rejected draft, not on a conversation-cache resume. +// +// A RING (the MTP drafter, which only ever reads its last `window` cells) uses the same host copy with a static +// table `block -> block % n_slots` and no resolve: the ring is refilled from the host copy on a resume. +#pragma once + +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +namespace strata::kernels { + +/// The host copy of one layer's K/V: device-mapped pointers (UVA) into pinned memory, identity layout +/// `[block][kv_head][page_size][head_dim]`. All null when the layer is fully resident. +struct KvHostPools { + uint16_t* k_pool = nullptr; ///< fp16 mode + uint16_t* v_pool = nullptr; + int8_t* k_q = nullptr; ///< int8 mode: codes + int8_t* v_q = nullptr; + uint16_t* k_scale = nullptr; ///< int8 mode: fp16 scale per 64 values + uint16_t* v_scale = nullptr; + uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head + uint8_t* v_q4 = nullptr; + bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; } +}; + +/// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0. +/// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) +enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvValueInt8 = 4 }; + +/// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in). +struct KvStreamMap { + int32_t* page_table = nullptr; ///< (n_blocks,) block -> slot, or -1 + int32_t* slot_block = nullptr; ///< (n_slots,) slot -> block, or -1 + int32_t* slot_stamp = nullptr; ///< (n_slots,) the resolve epoch that last used the slot + int32_t* slot_ref = nullptr; ///< (n_slots,) clock reference bit + int32_t* ctl = nullptr; ///< kKvCtlInts: epoch, hand, misses of the last call, overflow, u64 counters + int32_t* miss_block = nullptr; ///< (n_slots,) + int32_t* miss_slot = nullptr; ///< (n_slots,) + int64_t n_blocks = 0; + int64_t n_slots = 0; +}; + +inline constexpr int kKvCtlInts = 16; ///< [0] epoch [1] hand [2] misses [3] overflow; u64 at [4] misses, [6] lookups, [8] calls +/// Bytes of the map's arrays besides the page table (which the state already has): 5 per-slot ints + ctl. +inline uint64_t kv_stream_map_bytes(int64_t n_slots) { return (uint64_t) n_slots * 4 * 5 + kKvCtlInts * 4; } + +/// Every block evicted: page table all -1, slots free, counters zero. +void kv_stream_reset(const KvStreamMap& m, void* stream); + +/// Make every block named by the selections of `n_q` queries resident (ids [n_q][cap], width from +/// steps[q * kStepCount + kStepWidth]). Capturable. `n_slots` must hold the distinct blocks of one call +/// (n_q x (cap / page_size + 2)); a call that cannot sets ctl[3] (see `kv_stream_counters`). +void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt, + const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s, + void* stream); + +/// The static ring table `block -> block % n_slots`. +void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* stream); + +/// Copy blocks [b0, b1) of the host copy into the pool pages `page_table` names (host-side table `phys(b)` +/// computed as `b % n_slots`: the ring restore). Not capturable. +void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, + int64_t n_slots, const QsaShapes& s, void* stream); + +/// Copy the first `n_blocks` blocks of the host copy into a fully resident (identity-layout) pool: the prompt +/// path's staging of one layer. Not capturable (DMA). +void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, + const QsaShapes& s, void* stream); + +struct KvStreamCounters { + uint64_t misses = 0, lookups = 0, calls = 0; + bool overflow = false; +}; +/// Synchronous read of the counters (debug and the end-of-request summary). +KvStreamCounters kv_stream_counters(const KvStreamMap& m); + +/// Bytes of one block (page) of K and V together. +uint64_t kv_block_bytes(const QsaShapes& s, int fmt); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/mrope.hpp b/engine/strata/include/strata/kernels/mrope.hpp new file mode 100644 index 00000000..cb1451c4 --- /dev/null +++ b/engine/strata/include/strata/kernels/mrope.hpp @@ -0,0 +1,61 @@ +// strata/kernels/mrope.hpp - multimodal rotary positions (the vision path). +// +// qwen4exp rotates with interleaved M-RoPE (llama.cpp LLAMA_ROPE_TYPE_IMROPE, rope.dimension_sections 11/11/10/0): +// each of the 32 rotated pairs takes its position from one of three streams, time t, height h and width w. Text +// has t = h = w, which is why every rope kernel here takes one position per row. An image does not: its tokens +// share t and differ in h and w (mtmd: t = p, h = p + y, w = p + x), and the text after it continues at +// p + max(nx, ny), not at its cell index. +// +// The table: nullptr (the default) keeps every kernel exactly as before - the position a caller passes is the +// rotary position. Set, it is a DEVICE int32 [cells][3] (t, h, w) and the position a caller passes is read as a +// CELL index; pair i rotates by tab[cell * 3 + mrope_sector(i)]. Every caller in the engine passes cell indices +// (pos_base is 0 everywhere), so the table covers the prompt path, the verify window and the MTP drafter at once. +// The pointer must be set before any CUDA graph is captured (kernels take it as an argument); the contents may +// change between requests. +#pragma once + +#include + +#include "strata/kernels/rope_scaling.hpp" + +namespace strata::kernels { + +/// The table of the CURRENT device (a layer split sets one per device; null = the identity). +void mrope_table_set(const int32_t* device_table); +const int32_t* mrope_table(); + +/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's +/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT +/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under +/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode +/// (fast-math) disagree with each other. +struct RopeTab { + const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did + const float* sin = nullptr; + int max_pos = 0; +}; +/// Registers the table the session just built with `scaling` (the latest one of the device wins). +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling); +/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release). +void rope_table_release(const float* cos_tab); +/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the +/// kernels compute the angle exactly as before). +RopeTab rope_table_for(const RopeScaling& scaling); + +#if defined(__CUDACC__) || defined(__HIPCC__) +/// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33), +/// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3. +__device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) { + return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos; +} +/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false +/// when there is no table or p lies past it - then the caller computes the angle as it always did +__device__ __forceinline__ bool rope_tab_cs(const RopeTab& t, int p, int pair, float& c, float& s) { + if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false; + c = __ldg(t.cos + (size_t) p * 32 + pair); + s = __ldg(t.sin + (size_t) p * 32 + pair); + return true; +} +#endif + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_flash_attn.hpp b/engine/strata/include/strata/kernels/native_flash_attn.hpp new file mode 100644 index 00000000..b517156e --- /dev/null +++ b/engine/strata/include/strata/kernels/native_flash_attn.hpp @@ -0,0 +1,36 @@ +#pragma once +#include "strata/kernels/qsa.hpp" + +namespace strata::kernels { + +enum NativeFlashAttnStatus : int32_t { + kNativeFlashAttnSuccess = 0, + kNativeFlashAttnUnsupportedStep = 1, +}; + +// Explicitly selected short-context adapter for pinned CUDA F16/F16 vector +// FlashAttention. Geometry is exactly Q24x256, KV2x256, one query/sequence, +// scale=1/16, no ALiBi/softcap/sink. No allocation, synchronization, or KV rewrite. +// q/output: contiguous [24,256] F32. k/v: existing gathered [capacity,2,256] +// F16 buffers, with only step[kStepWidth] initialized rows required. Optional +// mask: 256 F16 additive logits, broadcast over heads; at least one valid key +// must be unmasked. Finite live q/k/v and finite or -inf live mask entries are +// preconditions; unused k/v/mask padding may contain arbitrary bytes. +// Padding is synthesized as zero K/V and -inf mask without reading it. +// +// capacity >=256; max_context in [1,256] is the HOST session limit. The device +// step must satisfy pos+1==n_kv==width in [1,max_context] and n_bid==n_kv/4. +// An invalid step writes status=UnsupportedStep and NaN output, without reading +// q/k/v/mask. status is one caller-owned device int32, overwritten on every call; +// integration MUST inspect it at its normal completion boundary. Host context +// limits must prevent unsupported steps before decoding. This is not a 20K path. +// +// All buffers (including optional mask and status) must have disjoint spans, +// with four-byte alignment for F32/step/status and two-byte alignment for F16. +// A nonnull explicit stream is mandatory. All pointers remain live for replay. +void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v, + const int32_t* step, int64_t capacity, int max_context, + const QsaShapes& shapes, float* output, int32_t* status, + const uint16_t* mask, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_gdn.hpp b/engine/strata/include/strata/kernels/native_gdn.hpp new file mode 100644 index 00000000..feebefe9 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_gdn.hpp @@ -0,0 +1,22 @@ +#pragma once +#include "strata/kernels/gdn.hpp" + +namespace strata::kernels { + +// Configure before creating/capturing a session. Existing captures retain their +// selected kernel, so changing the flag does not change an existing graph. +void native_gdn_set_enabled(bool enabled); +bool native_gdn_enabled(); + +// Pinned CUDA gated_delta_net recurrence for one token, S=128 and h_v % h_k=0. +// q/k are normalized F32 inputs; q MUST NOT be pre-scaled by 1/sqrt(S). +// Scaling is applied to the completed readout, as in the pinned fused operator. +// State retains Strata's layout: state[(i*h_v+h)*S+j]. The caller owns it and +// output; both must be disjoint from each other and from every read-only input. +// All spans must be aligned to four bytes. A nonnull ordered stream is required. +// No allocation, wait, or change to normalization/gate preprocessing occurs. +void native_gdn_step(float* state, const float* q, const float* k, const float* v, + const float* gate, const float* beta, float* output, + const GdnShapes& shapes, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_gdn_preprocess.hpp b/engine/strata/include/strata/kernels/native_gdn_preprocess.hpp new file mode 100644 index 00000000..58334f42 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_gdn_preprocess.hpp @@ -0,0 +1,37 @@ +#pragma once +#include + +namespace strata::kernels { + +// Optional pinned CUDA GDN preprocessing. The layer selects these functions with +// native_gdn_enabled(); direct callers explicitly select them by calling them. +// Require a nonnull ordered stream, finite inputs, and four-byte aligned spans. +// No function allocates or synchronizes. All pointers are caller-owned. + +// Four-tap convolution, then FP32 fast-math SiLU. History is [channels,3], oldest +// first; weights are [channels,4]. Both outputs are required, mutually disjoint, +// and disjoint from input/weights/history. History must not alias other spans. +void native_gdn_conv_silu(float* history, const float* input, const float* weights, + float* raw_output, float* silu_output, int64_t channels, + int64_t d_conv, void* stream); + +// In-place [rows,128]: scale(rms_norm(x,epsilon/128),1/sqrt(128)). This includes +// the L2 normalization scale, but NOT the recurrence's readout scale. +// Epsilon is finite/nonnegative; epsilon=0 additionally requires nonzero rows. +void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream); + +// In-place sigmoid over per-head beta; one token. +void native_gdn_beta_gate(float* beta, int64_t heads, void* stream); + +// One token: gate[h] = softplus(alpha[h]+dt[h])*ssm_a[h], using the pinned CUDA +// log(1+exp(x)) expression and threshold 20. Output is disjoint from inputs. +void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a, + float* gate, int64_t heads, void* stream); + +// [heads,128]: rms_norm(output,epsilon)*gamma*sigmoid(z). Gamma contains only +// 128 floats and broadcasts across heads. Destination is disjoint from inputs. +void native_gdn_out_norm(const float* output, const float* z, const float* gamma, + float* destination, int64_t heads, int64_t cols, + float epsilon, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_gr_norm.hpp b/engine/strata/include/strata/kernels/native_gr_norm.hpp new file mode 100644 index 00000000..b8bb4ed1 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_gr_norm.hpp @@ -0,0 +1,18 @@ +#pragma once + +namespace strata::kernels { + +// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA weighted F32 +// RMSNorm for contiguous [n_cols, n_rows] data and equally shaped F32 gamma. +// Every row has independent norm statistics. Output is (scale * input) * gamma. +// Uses 256 threads below n_cols=1024, otherwise 1024, with the pinned XOR tree. +// Compile the implementation with --use_fast_math; no FP64, allocation, or wait. +// All buffers are caller-owned, nonoverlapping, and at least four-byte aligned. +// Require positive dimensions and finite nonnegative epsilon. Inputs/gamma and +// intermediate sums must be finite; epsilon=0 additionally requires nonzero rows. +// Enqueues on the supplied CUDA stream. A null handle explicitly selects CUDA's +// default stream, preserving gr_read's existing API; this function never syncs. +void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output, + int n_cols, int n_rows, float epsilon, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_gr_postops.hpp b/engine/strata/include/strata/kernels/native_gr_postops.hpp new file mode 100644 index 00000000..790b883c --- /dev/null +++ b/engine/strata/include/strata/kernels/native_gr_postops.hpp @@ -0,0 +1,28 @@ +#pragma once + +namespace strata::kernels { + +// Pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d contiguous F32 +// single-token GR post-operations. Explicit stream, no allocation or wait; null +// selects the default stream. Positive dimensions with n*hc <= INT_MAX, finite +// values/intermediates, and four-byte alignment are required. +// Buffers must not overlap except the explicitly in-place arguments below. +// Implementation compiles separately with --use_fast_math. + +// In-place pinned SCALE(1/hc), then SiLU, applied to the raw down projection. +void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream); + +// xn and raw gate contain [n_embd,hc]. gate is overwritten with xn*sigmoid(gate). +// Layer path: pinned DSV4_HC_PRE_GATED ordered FMA accumulation, then scale. +// Head path (fused_layer=false): individually rounded products, ordered adds +// starting from stream zero, then SCALE. This retains the oracle's il=-1 graph. +void native_gr_pre_gated(const float* xn, float* gate, float* mixed, + int n_embd, int hc, bool fused_layer, void* stream); + +// inject[hc] -> SCALE(1/hc), sigmoid, SCALE(2), identity DSV4_HC_POST. +// residual/output contain [n_embd,hc], block_out has n_embd elements. +// output may equal residual exactly; all other overlaps are invalid. +void native_gr_post(const float* residual, const float* block_out, const float* inject, + float* output, int n_embd, int hc, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_mmvq.hpp b/engine/strata/include/strata/kernels/native_mmvq.hpp new file mode 100644 index 00000000..9f69dd94 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_mmvq.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include + +namespace strata::kernels { + +// Native GGUF Q2_0, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL +// and IQ4_XS / CUDA Q8_1 adapters, pinned to llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d, sm_120 generic MMVQ. +// All pointers are device pointers, at least 4-byte aligned, with no overlap. +// All calls enqueue on the explicit non-null CUDA stream; no allocation or wait. +// The translation unit must use --use_fast_math, as the pinned CUDA oracle does. +// +// Shapes use GGUF order: n_in is the contiguous reduction dimension, n_out is +// the weight row count, and ncols is the activation column/token count, 1..8 +// (plan v0.3 P3). Columns are contiguous: activation column j is x + j * n_in +// (its Q8_1 blocks at j * n_in / 32) and output column j is y + j * n_out. See +// native_mmvq_set_multi_exact for how ncols > 1 relates to ncols == 1. +// n_in must be a positive multiple of 32 for quantization/Q4_0/Q5_0/Q8_0/IQ4_NL, +// 64 for Q2_0, or 256 for the other formats. n_out must be positive. Weights remain +// unmodified row-major GGUF blocks: Q3_K=110, Q4_K=144, Q5_K=176, Q6_K=210 and +// IQ4_XS=136 bytes per 256 elements; Q2_0 is 18 bytes per 64 elements. +// Q4_0/IQ4_NL=18, Q5_0=22, Q8_0=34 bytes per 32 elements. +// Q8_1 scratch has 36 bytes per 32 elements, with no extra row padding here. +// Input floats must be finite, and their block scales/sums representable in FP16. +std::size_t native_q8_1_bytes(int n_in, int ncols = 1); + +// Layout for ncols > 1. false: llama.cpp's generic multi-column table (upstream), equal to ncols == 1 to +// float rounding, speed not yet measured. true (default): the ncols == 1 layout, every column bitwise equal to a +// single-column call. Set before +// graph capture; captured graphs keep the kernels they captured. +void native_mmvq_set_multi_exact(bool exact); +bool native_mmvq_multi_exact(); + +// One quantization may serve multiple weight matrices sharing the same input. +// Q8_1 stores FP16 scale and FP16 warp sum of the ORIGINAL float inputs; it does +// not reconstruct that sum from the quantized integers. +void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, + void* stream); + +void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +// Convenience composition: caller owns scratch sized by native_q8_1_bytes. +void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream); + +// Storage/dispatch helpers take stable GGML type IDs, avoiding a ggml runtime +// dependency in the engine: Q4_0=2, Q5_0=6, Q8_0=8, Q3_K=11, Q4_K=12, Q5_K=13, +// Q6_K=14, IQ4_NL=20, IQ4_XS=23, Q2_0=42. Unsupported IDs throw in the byte-count +// and launch helpers; only the +// capability query returns false. +bool native_mmvq_supported(int ggml_type) noexcept; +std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out); +void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_moe.hpp b/engine/strata/include/strata/kernels/native_moe.hpp new file mode 100644 index 00000000..34760efe --- /dev/null +++ b/engine/strata/include/strata/kernels/native_moe.hpp @@ -0,0 +1,21 @@ +#pragma once +#include + +namespace strata::kernels { +// Configure before constructing/capturing sessions. Existing captures keep their +// selected kernels; changing this flag does not rewrite an existing graph. +void native_moe_combine_set_enabled(bool enabled); +bool native_moe_combine_enabled(); + +// Pinned CUDA weighted-reduction contract for one token, k in [1, 15]. +// The backend fuses k=2..15; k=1 is its ordinary multiply/contiguous/add path. +// parts: k contiguous F32 rows of n_embd; weights: k F32 values. The first +// product rounds to F32, following products accumulate with FMA in expert order, +// and optional shared is added once afterward. Shared is not router weighted. +// Requires a nonnull ordered stream and disjoint output. No allocation or sync. +void native_moe_combine(const float* parts, const float* weights, const float* shared, + float* output, int64_t n_embd, int64_t k, void* stream); +/// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call. +void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream); +} diff --git a/engine/strata/include/strata/kernels/native_ple_postops.hpp b/engine/strata/include/strata/kernels/native_ple_postops.hpp new file mode 100644 index 00000000..97c49903 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_ple_postops.hpp @@ -0,0 +1,38 @@ +#pragma once +#include "strata/kernels/ple.hpp" + +namespace strata::kernels { + +// Fixed qwen4exp single-token geometry: embd=2560, streams=4, history=9, +// convolution kernel=4/dilation=3. All buffers are caller-owned and capture-safe. +struct NativePlePostopsBuffers { + float* key; // 10240, normalized projected key + float* query; // 10240, temporary normalized hidden; may equal normalized + float* gate; // 4 + float* gated; // 10240 + float* normalized; // 10240, append this to history AFTER this function + float* conv; // 10240 + float* result; // 10240, may equal hidden exactly +}; + +// Matches pinned llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d CUDA +// build_ple AFTER the two projections. Only norm_key/query/conv and conv1d_f16 +// fields of weights are used. Gamma is full [2560,4]; history is row-fastest +// [9,10240], and F16 taps are [4,10240]. Inputs must be finite. +// Require an explicit stream, nonnull aligned pointers and disjoint writable +// spans, with only the two exact aliases documented above allowed. No allocation +// or synchronization; retain every buffer through any captured graph execution. +void native_ple_postops(const float* projected_key, const float* hidden, + const float* value, const float* history, + const PleWeights& weights, const NativePlePostopsBuffers& buffers, + void* stream); + +/// The prompt path: T tokens at once, element for element the arithmetic of T calls of native_ple_postops with +/// the history advanced after each. `key` (T x 10240) holds the projected keys and is normalized in place; +/// `hidden` (T x 10240) becomes the result; `value` T x 2560; `query_norm` (T x 10240, the normalized hidden, then +/// the normalized gated values), `gated` (T x 10240) and `gate` (T x 4) are scratch; `history` (9 rows per +/// channel) is advanced past the T tokens. +void native_ple_postops_batch(float* key, float* hidden, const float* value, float* history, const PleWeights& w, + float* query_norm, float* gated, float* gate, int T, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_qsa.hpp b/engine/strata/include/strata/kernels/native_qsa.hpp new file mode 100644 index 00000000..c56eb4d2 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_qsa.hpp @@ -0,0 +1,30 @@ +#pragma once + +namespace strata::kernels { + +// Set before session construction/capture; existing CUDA graphs retain their +// selected kernels. Disabled by default. Integration chooses the call sites. +void native_qsa_set_enabled(bool enabled); +bool native_qsa_enabled(); + +// Pinned single-token CUDA F32 arithmetic from llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d. No allocation or synchronization; +// both functions require a nonnull caller-owned stream and four-byte alignment. +// Positive dimensions with n_cols*n_rows (or head_dim*n_head) <= INT_MAX. +// Finite inputs and finite intermediate sums/products are caller preconditions. + +// Contiguous input/output [n_cols,n_rows], gamma[n_cols] broadcast over rows. +// Each row has independent RMS statistics. Exact output==input is supported; +// otherwise all three spans must be disjoint. Epsilon must be finite and >= 0; +// epsilon==0 additionally requires a nonzero sum of squares in every row. +// Pinned 256-thread (width<1024) or 1024-thread XOR reduction, (scale*x)*gamma. +void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, + int n_cols, int n_rows, float epsilon, void* stream); + +// attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is +// [query channels, gate channels]. Output is attn*sigmoid(second-half gate). +// Exact output==attn is supported; all other spans must be disjoint. +void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, + int n_head, int head_dim, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_qsa_indexer.hpp b/engine/strata/include/strata/kernels/native_qsa_indexer.hpp new file mode 100644 index 00000000..fe66d4b0 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_qsa_indexer.hpp @@ -0,0 +1,46 @@ +#pragma once +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/rope_scaling.hpp" + +namespace strata::kernels { + +// Configure before session construction/capture. Disabled independently of the +// native QSA norm/gate switch; existing captures retain their selected kernels. +void native_qsa_indexer_set_enabled(bool enabled); +bool native_qsa_indexer_enabled(); + +// Pinned F16 raw-key cache / F32 pooling / weighted RMSNorm / text IMRoPE. +// Fixed single-sequence geometry: idx_dim=128, idx_block=4, n_rot=64. +// Uses the existing buffers: tail[3,128] stores half-rounded raw values expanded +// to F32; dead[128] is the repeated-cell0 spare key; pooled[max_cells/4+1,128] +// contains completed blocks followed by the spare; block_pos[1] changes only on +// completion and records that block's first absolute position. +// +// relative_pos_device is a cell index, advancing 0..max_cells-1 (use kStepPos, +// not the absolute RoPE position vector). The sequence is text, +// contiguous, with nonnegative pos_base divisible by four. Clear state before +// starting a new sequence. Completed block b rotates at pos_base+4*b; the spare +// always rotates at zero, including nonzero sequence bases, as in the oracle. +// Under rope scaling (rope_scaling.hpp) the zero angle keeps the spare's +// rotation an identity; YaRN's mscale rides in through cos(0) on both the pooled +// keys and the indexer queries, so selection is unchanged. +// +// Explicit nonnull stream; no allocation or synchronization. All spans must be +// aligned and disjoint, remain valid through replay, and contain finite values; +// raw values must round to finite F16 and epsilon must be finite and positive. +// max_cells is a positive fixed capacity; pos_base+max_cells must fit int32. +// Out-of-range device positions are ignored defensively, not host-validated. +// This adapter does not alter score accumulation, top-k, or finite 1e9 tail bias. +// perf-review C-2: the appends of cells [p0, p0 + n) at once, leaving the buffers exactly as n calls of the +// single append in order would (the prompt path appends a chunk before any query reads the state). raw [n, 128]. +// Host-side positions (not for a captured graph). +void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, + float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, + const RopeScaling& scaling, void* stream); + +void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, + int32_t pos_base, const float* gamma, float epsilon, + const QsaIndexerBuffers& buffers, const QsaShapes& shapes, + int64_t max_cells, const RopeScaling& scaling, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_qsa_score.hpp b/engine/strata/include/strata/kernels/native_qsa_score.hpp new file mode 100644 index 00000000..9427a77e --- /dev/null +++ b/engine/strata/include/strata/kernels/native_qsa_score.hpp @@ -0,0 +1,31 @@ +#pragma once +#include "strata/kernels/qsa.hpp" + +namespace strata::kernels { + +// Configure before capture; independent of native key pooling and norm/gate. +void native_qsa_score_set_enabled(bool enabled); +bool native_qsa_score_enabled(); + +// SM120, single contiguous text sequence: F32 pooled[128,max_blocks] and +// query[128,4], four-cell blocks, top-k budget2048. Matches the pinned CUDA MMF +// dispatch with the model's n_kv padded to256 (n_blocks a multiple of64), even +// when only a partial32-row tile is live. This is not the unpadded odd-row +// cuBLAS contract. MMA consumes the same raw F32 register bits as the oracle. +// +// step[kStepCount] is device memory, refreshed before each replay. max_blocks +// must equal max_cells/4+1. Completed pooled rows[0,n_bid) and the spare row +// [n_bid] must be initialized. Writes cell_scores[0,n_kv) only. Applies ReLU +// separately per head, ordered F32 head addition, optional F32 block bias, +// then finite1e9 F32 bias for the incomplete tail; full blocks also receive +// the reference's +0 bias. Does not alter selection, ties, or selected order. +// +// All spans are aligned, disjoint, persistent through replay; inputs finite. +// Explicit nonnull stream. No allocation, host count reads, or synchronization. +// Invalid device counts suppress writes defensively; callers own count validity. +void native_qsa_score(const float* pooled, const float* query, const float* block_bias, + const QsaShapes& shapes, const int32_t* step, + int64_t max_blocks, int64_t max_cells, + float* cell_scores, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/native_rope.hpp b/engine/strata/include/strata/kernels/native_rope.hpp new file mode 100644 index 00000000..95511b88 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_rope.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include "strata/kernels/rope_scaling.hpp" + +namespace strata::kernels { +void native_rope_set_enabled(bool enabled); +bool native_rope_enabled(); + +// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four +// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live +// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected. +// Explicit stream required. No allocation or synchronization. +// +// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the +// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the +// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin. +// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid. +void native_rope_apply(const float* x, float* out, int rows, int head_dim, + int n_rot, const RopeScaling& scaling, const int* positions, void* stream); +} diff --git a/engine/strata/include/strata/kernels/native_router.hpp b/engine/strata/include/strata/kernels/native_router.hpp new file mode 100644 index 00000000..0511b0b0 --- /dev/null +++ b/engine/strata/include/strata/kernels/native_router.hpp @@ -0,0 +1,19 @@ +#pragma once +#include + +namespace strata::kernels { +// Configure before session capture. Existing graphs retain their selected kernels. +// This experiment is off by default and does not modify the legacy router. +void native_router_set_enabled(bool enabled); +bool native_router_enabled(); + +// Pinned CUDA topk-moe contract for ONE token, 512 experts, top 10, softmax, +// no selection bias, lower normalization clamp 2^-14, and scale 1. +// Reads 512 finite F32 logits; writes 10 I32 IDs and 10 F32 weights. Equal +// computed probabilities select the lower expert index. All spans must be +// four-byte aligned and outputs disjoint from each other and the input. +// Requires a nonnull ordered CUDA stream. No allocation or synchronization. +void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream); +/// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call. +void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream); +} diff --git a/engine/strata/include/strata/kernels/ngram.hpp b/engine/strata/include/strata/kernels/ngram.hpp new file mode 100644 index 00000000..688c74d9 --- /dev/null +++ b/engine/strata/include/strata/kernels/ngram.hpp @@ -0,0 +1,229 @@ +// include/strata/kernels/ngram.hpp - P2.S4: the PLE n-gram hash and the per-layer token table. +// +// Two halves that share nothing but the row indices they exchange: +// +// * `ngram_rows` - the HOST hash. Sixteen row indices per token from the last three token ids, computed +// with 64-bit multiply/xor and no tensor op at all. `qwen4exp.cpp` L1092-1124, where the source says +// outright that it is host-side because "ggml has no int64 and no xor". +// * `PleTable` - the row gather. `per_layer_token_embd.weight` is IQ4_NL and is NOT IN THE PACK: it is +// 51.2e9 elements (28.8 GB) in the ORIGINAL second GGUF shard, and it is the only tensor this engine +// reads from the GGUF rather than from the canonical pack. +// +// THE HASH IS THE ONE PLACE IN THIS MODEL WHERE A WRONG BIT IS SILENTLY PLAUSIBLE. Every one of its +// properties has a rival reading that produces a valid index in range: +// +// * XOR, not sum. Two equal tokens with equal multipliers cancel to zero under XOR and double under sum. +// * `%` vocab_size, not `& (vocab_size-1)`. The vocab sizes are 20000003, 20000023, 20000033, ... - not +// powers of two, so a mask would be a different function. +// * the EOS cut propagates FORWARD: an EOS at any position replaces that position AND every older one. +// * a missing predecessor is `LLAMA_TOKEN_NULL = -1`, tested as `t < 0`. Token id 0 is a REAL token. +// * the token's OWN eos does not cut its own context - only the predecessors are examined. +// +// All of those are asserted observable in `ple_parity.cpp` rather than trusted. +#pragma once + +#include +#include +#include + +namespace strata::kernels { + +// ---- geometry, every value confirmed against the artifact (docs/gguf-metadata.txt) ---- +inline constexpr int NG_N_EMBD = 2560; // n_embd +inline constexpr int PLE_HEAD_DIM = 160; // qwen4exp.embedding_length_per_layer_input +inline constexpr int NGRAM_SIZE = 3; // qwen4exp.ple.ngram_size +inline constexpr int HEADS_PER_NGRAM = 8; // qwen4exp.ple.heads_per_ngram +inline constexpr int PLE_N_HEADS = (NGRAM_SIZE - 1) * HEADS_PER_NGRAM; // 16 +inline constexpr int PLE_CONV_KERNEL = 4; // qwen4exp.ple.conv_kernel +inline constexpr int32_t PLE_EOS_TOKEN_ID = 248044; +inline constexpr int NG_HC = 4; // hyper_connection.count +inline constexpr int NG_HC_DIM = NG_HC * NG_N_EMBD; // 10240 +inline constexpr int NG_HIST = (PLE_CONV_KERNEL - 1) * NGRAM_SIZE; // 9 +inline constexpr int32_t TOKEN_NULL = -1; // LLAMA_TOKEN_NULL +inline constexpr float NG_RMS_EPS = 1e-6f; + +// The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements = +// 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560. +inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull; +inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row +inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value +inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8; + +/// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`: +/// +/// layer_multipliers = [23703573157769, 20109073645365, 8052911324071] +/// head_vocab_sizes = [20000003, 20000023, ...] 16 entries, NOT an arithmetic sequence +/// head_offsets = [0, 20000003, 40000026, ...] the running sum of head_vocab_sizes +/// +/// `ref/ngram.py::selftest` calls its own copies "synthetic but STRUCTURALLY REAL"; they are in fact +/// `20000003 + 10*i` for the vocab sizes, which the artifact's are not (20000003, 20000023, 20000033 - the +/// differences are 20, 10, ...). A selftest is free to use whatever constants it likes, but a PARITY test +/// against the artifact must use these, and the difference is recorded because it is exactly the kind of +/// thing that gets copied from the reference into an engine. +struct PleConsts { + uint64_t mult[NGRAM_SIZE]; + uint64_t vocab[PLE_N_HEADS]; + uint64_t offset[PLE_N_HEADS]; +}; +PleConsts ple_artifact_consts(); + +/// `mixed_n = (ctx[0]*m[0]) ^ (ctx[1]*m[1]) ^ ... ^ (ctx[n-1]*m[n-1])` in uint64. +/// +/// Exposed separately so a test can assert the XOR STRUCTURE directly rather than only its consequences. +uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n); + +/// The sixteen row indices per token. `qwen4exp.cpp` L1092-1124. +/// +/// tokens (n_tokens,) the ubatch's own tokens +/// prev (n_tokens, 2) predecessors OLDEST FIRST, `TOKEN_NULL` where there is none +/// out (n_tokens, 16) row indices into the PLE table +/// +/// The window is built once per token and then only its PREFIXES are used, which is what makes the bigram +/// heads (0..7) and the trigram heads (8..15) agree about the recent history. +void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out); + +/// The IQ4_NL codebook: `{-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}`, +/// which is `kvalues_iq4nl` from `ggml-common.h` L1121 and also the manifest's `codebooks.IQ4NL`. +/// +/// There is NO `-8` in this version of ggml. Some releases of `dequantize_row_iq4_nl` subtract 8 from the +/// codebook value; at 3cf03257 they do not, and the difference would shift every one of the 51.2e9 elements. +int iq4nl_code(int code); + +/// One 90-byte row -> 160 floats. The canonical rule `value = cb[code] * scale + offset` with offset 0, +/// because IQ4_NL has no min term (`has_offset` is false in the manifest). +/// +/// THE NIBBLE ORDER IS SPLIT-HALF, NOT INTERLEAVED, and that is the trap here. `dequantize_row_iq4_nl` is +/// y[j] = d * kvalues[qs[j] & 0xf]; +/// y[j + QK4_NL/2] = d * kvalues[qs[j] >> 4]; +/// so byte j carries elements j and j+16 - NOT 2j and 2j+1, which is the natural reading and which produces +/// a perfectly plausible embedding of the wrong 160 values. +void iq4nl_dequant_row(const uint8_t* row, float* out160); + +/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the +/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and +/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row. +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160); + +/// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD, +/// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the +/// A/B arm; it returns the same bytes. +/// +/// NEVER KEEP THE SHARD MAPPED WHILE READING IT DIRECT: a live section on the same file serializes the unbuffered +/// reads (311 -> 1,575 us per token, bench/results/2026-09-23-p2-ssd-direct). Direct mode drops its own mapping +/// after the header parse; nothing else in the process may hold one. +enum class PleIo { Direct, Mmap }; + +struct PleIoOptions { + PleIo mode = PleIo::Direct; + uint32_t max_inflight = 64; ///< outstanding SSD reads (decode needs 16; prefill chunks use more) + uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables + bool io_thread = true; ///< reads submitted by a worker thread, not the caller + /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on + /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome. + bool lock = false; + /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table + /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows + /// (see PleReader::set_keepalive). + double keepalive_ms = 0; + double keepalive_window_s = 60; +}; + +/// The PLE table. Held by pointer-to-impl so this header does not drag `` into every +/// translation unit that wants the hash. +class PleTable { +public: + PleTable(); + ~PleTable(); + PleTable(const PleTable&) = delete; + PleTable& operator=(const PleTable&) = delete; + + /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). + bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + + /// Experimental CPU quality arm: read rows from a verified KAR-2 archive + /// while the rest of the engine continues to use its normal model pack. + /// The CUDA selective-row path is measured separately and is not used here. + bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, + uint64_t expected_rows = PLE_TABLE_ROWS); + + /// Experimental bounded compressed-row cache. It accepts only the + /// level-2/group-32 KAR PLE layout and leaves the CPU gather available + /// for consumers that still use mapped host memory. + bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err); + bool kar_gpu_cache_enabled() const; + bool collect_device(float* device_out2560, void* stream, std::string& err); + bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, + void* stream, std::string& err); + + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 + /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. + bool issue(const uint32_t* rows16); + bool collect(float* out2560, std::string& err); + /// Plan v0.3 P5: the rows of `n_tokens` tokens (16 each, `rows` token-major) into `out` (2560 floats per token), + /// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not + /// while a single-token `issue` is pending. The mapped mode gathers row by row. + bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err); + + /// Fault injection (Direct mode): every row read completes no earlier than `us` after issue. + void set_injected_delay_us(double us); + + /// Maps the ORIGINAL second GGUF shard read-only. The tensor's data does NOT start at file offset 0: + /// the manifest's `shard2_tensor.offset` is relative to the GGUF's DATA SECTION, and the header before it + /// is 192 bytes. Reading at 0 would silently decode the header plus 192 bytes of shifted rows - still + /// plausible IQ4_NL, which is why the reader takes the offset from a real GGUF parse (`GgufFile`, the + /// project's validated reader) and checks that the tensor exactly fills the rest of the file. + bool open(const std::string& gguf_path, std::string& err); + void close(); + bool is_open() const; + /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched). + bool locked() const; + uint64_t rows() const; + /// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3). + const char* format() const; + + /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values + /// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain + /// n_embd-wide vector for the block that consumes it. + void gather(const uint32_t* rows16, float* out2560) const; + + /// One row -> 160 floats, for diagnostics and for the parity test's oracle comparison. + void read_row(uint32_t row, float* out160) const; + + /// Bytes actually touched since `open`, for the "how often is it not ready" measurement P2.S4 asks for. + uint64_t bytes_read() const; + + /// One line of reader statistics (Direct mode), e.g. for --stats. Empty in Mmap mode. + std::string io_report() const; + PleIo mode() const; + +private: + struct Impl; + Impl* impl_ = nullptr; +}; + +// ================================ THE PLE GATHER'S PREFETCH, AND ITS A/B ARM ================================ +// +// `gather` issues its sixteen row reads as sixteen SEPARATE page faults into a 26.8 GB mapping, which measured +// **2.10-2.61 ms per token** and is second only to the layer loop among the token's avoidable terms. The table +// is 90 B per row, so the sixteen rows are 1,440 B - 0.5 MB/s, which is latency and not bandwidth, and it is +// because the sixteen pages are taken one at a time. `PrefetchVirtualMemory` issues them in one call. +// +// **THIS SWITCH EXISTS SO THE CLAIM CAN BE MEASURED RATHER THAN ASSERTED.** Cross-build comparisons in this +// project have repeatedly turned out to be machine drift - `LAYERS` alone moves 48.9 -> 52.3 between runs of +// one binary - so the two arms are alternated inside one session. Off is `--no-ple-prefetch`. +void ple_prefetch_enable(bool on); +bool ple_prefetch_enabled(); + +// ---- NOTE ON `madvise(MADV_RANDOM)` ------------------------------------------------------------------ +// P2.S4 asks for `madvise(MADV_RANDOM)` on the mapping, and on Linux that is exactly right: a token gathers +// 16 rows scattered over 28.8 GB, so read-ahead is pure waste and would evict useful pages. +// +// THERE IS NO LINUX, SO THERE IS NO MADV_RANDOM HERE. Windows has no equivalent of the advice - the closest +// is `FILE_FLAG_RANDOM_ACCESS` at CreateFile time, which suppresses the cache-manager's read-ahead for the +// whole handle, and `PrefetchVirtualMemory` for the positive case. `GgufFile` opens with neither, so this +// build gets the DEFAULT sequential read-ahead on a random access pattern. Saying so is the point: a +// comment claiming MADV_RANDOM here would be a comment about code that does not run. On Linux the advice +// belongs in `GgufFile::open`, which this module does not own. +// ------------------------------------------------------------------------------------------------------ + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/ple.hpp b/engine/strata/include/strata/kernels/ple.hpp new file mode 100644 index 00000000..fabad838 --- /dev/null +++ b/engine/strata/include/strata/kernels/ple.hpp @@ -0,0 +1,119 @@ +// include/strata/kernels/ple.hpp - P2.S4: the PLE block's GPU half (`build_ple`, qwen4exp.cpp L1206-1293). +// +// One token, sixteen gathered rows of 160 -> a residual-stack update: +// +// key = grouped_norm(ple_key @ emb) hc_dim, per-stream RMS then a [n_embd,hc] gamma +// query = grouped_norm(hidden, ple_norm_query) +// value = ple_value @ emb n_embd +// s[c] = sum_d(key[c]*query[c]) / sqrt(n_embd) +// gate[c] = sigmoid(sign(s) * sqrt(max(|s|, 1e-6))) signed square root, then sigmoid +// gated[c] = value * gate[c] value broadcast over the hc streams +// normalized= grouped_norm(gated, ple_norm_conv) <-- THE CONV INPUT +// conv = sum_k kW[k][c] * padded[hist + t - (kern-1-k)*dil][c] +// out = hidden + gated + silu(conv) +// +// **`normalized` IS THE CONV INPUT, AND `ref/ngram.py` SAYS OTHERWISE.** Its `ple_block` docstring calls +// `terms` "the padded gated values", but the source pads `normalized` - the grouped_norm of the gated values, +// not the gated values themselves - and `ple_layer_xcheck.cpp` L107-112 builds it that way from ggml. The +// reference computes `normalized` and then ignores it, passing `terms` in from the caller, so its own code +// does not contradict its docstring and nothing catches it. This header takes the HISTORY OF NORMALIZED +// ROWS, which is what the state actually is. +// +// WHERE THE WEIGHTS LIVE, and the two different layouts in play. `ple_conv1d.weight` has manifest shape +// [4, 10240] with ne0 = 4 fast, so ggml's flat index is `k + 4*c`; `ref/ngram.py`'s `kernel` is a (4, 10240) +// numpy array whose flat index is `k*10240 + c`. They are transposes, and the source's own view +// (`ggml_view_2d(tWc, 1, hc_dim, nb[1], k*nb[0])`) confirms which is meant. `ple_key` and `ple_value` are +// [2560, n] with ne0 = 2560 fast, which IS the reference's row-major orientation. +#pragma once + +#include + +namespace strata::kernels { + +/// Opt in to pinned CUDA BF16/F32 MMVF for the PLE value projection only (default false). +/// Configure before session capture; captured graphs retain their selected projection kernels. +void ple_set_native_bf16(bool enabled); + +/// Opt in to pinned CUDA postprojection norms, gate, convolution and residual +/// arithmetic (default false). Set before capture; existing graphs keep their +/// selected kernels. Independent of the key/value projection options. +void ple_set_native_postops(bool enabled); +bool ple_native_postops_enabled(); + +/// Weights of the single PLE layer (`ple.layers = [1]`). `blk.1.*` in the pack. +/// +/// key_codes / key_scales `ple_key.weight` S2, [n_embd, hc_dim], code_bias -1, group 64. +/// The pack stores `scales_fp16: true`, and every S-form kernel in this project +/// (including `s2_gemv_q8`) takes scales as F32 - so the LOADER widens them once, +/// as it already must for the experts. Recorded because "the manifest says fp16" +/// and "the kernel wants float" is a silent 2x-read if nobody says which wins. +/// value_bf16 `ple_value.weight` BF16 as raw bits, [n_embd, n_embd] +/// norm_key/query/conv F32 [hc_dim], NO (1+w) folding - `ref/gdn.py` records the same for `ssm_norm` +/// conv1d_f16 `ple_conv1d.weight` F16, GGML-NATIVE `kW[k + kern*c]` +struct PleWeights { + const uint8_t* key_codes = nullptr; // hc_dim * (n_embd/4) bytes + const float* key_scales = nullptr; // hc_dim * (n_embd/64) floats + const uint16_t* value_bf16 = nullptr; // n_embd * n_embd + const float* norm_key = nullptr; // hc_dim + const float* norm_query = nullptr; // hc_dim + const float* norm_conv = nullptr; // hc_dim + const uint16_t* conv1d_f16 = nullptr; // PLE_CONV_KERNEL * hc_dim, flat index k + 4*c + + /// Optional unchanged GGUF Q2_0 [2560,10240] key projection. Nonnull data + /// requires type 42 and caller-owned native_q8_1_bytes(2560) device scratch, + /// disjoint from the PLE workspace, inputs, weights and exported outputs. + /// Use an explicit ordered stream and retain both buffers through graph + /// execution. Null data preserves the canonical key projection. + const void* key_native_data = nullptr; + int key_native_type = -1; + void* key_native_q8_1 = nullptr; + /// Plan v0.3 P6: the IQ model files keep `ple_key` in BF16 ([n_embd, hc_dim], `w[o*n_embd+i]`); when set it + /// replaces both key paths above. + const uint16_t* key_bf16 = nullptr; +}; + +/// Everything the block produces, in the order `ple_layer_xcheck`'s oracle writes it. Any pointer may be +/// null; the caller that only wants the result passes nothing else. Having the intermediates is what makes +/// the parity test able to say WHICH stage diverged instead of only that the sum did. +/// Every nonnull output region, including result, must be disjoint from the block's entire scratch region. +/// result may alias hidden. The block rejects scratch/output overlap before launching any work. +struct PleOut { + float* key = nullptr; // hc_dim + float* value = nullptr; // n_embd + float* gate = nullptr; // hc + float* gated = nullptr; // hc_dim + float* normalized = nullptr; // hc_dim + float* conv = nullptr; // hc_dim + float* result = nullptr; // hc_dim +}; + +/// One token. `emb` is the 2560-wide gathered n-gram embedding, `hidden` the hc_dim residual stack, and +/// `hist_rows` the NG_HIST previous NORMALIZED rows, oldest first (the caller owns that cache). +/// +/// `hist_rows` IS ROW-FASTEST: `hist_rows[row + NG_HIST*channel]`. That is not a choice - it is +/// `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`, so ne0 = the history row varies fastest, and +/// `ple_layer_xcheck.cpp` L79-83 records the transposed reading failing ggml's own assert. +/// +/// The block does NOT write back to the history: the caller keeps ownership of its state and this stays a +/// pure function of its inputs, which is what makes the chunked-versus-single-shot property testable. +/// Bytes the caller must hand `ple_block` as its workspace: five `hc_dim` buffers (key, query, norm, +/// gated, conv), one `n_embd` (value) and one `hc` (gate), plus the Q8 activation image and the BF16 +/// embedding copy. **THE WORKSPACE IS THE CALLER'S BECAUSE THIS FUNCTION IS CAPTURED**: it used to +/// `cudaMalloc` three times and `cudaStreamSynchronize` once per call, and inside a graph both are errors - +/// `ple_block: scratch: operation not permitted when stream is capturing`. Same defect, same fix as +/// `shared_expert`. +uint64_t ple_block_scratch_bytes(); + +void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w, + PleOut& out, void* scratch, void* stream); + +/// Advance the row-fastest normalized history by one token: hist[r,c] = old_hist[r+1,c], then append +/// normalized[c] at row NG_HIST-1. One thread owns each channel, making the in-place shift well-defined. +/// hist and normalized must be nonnull, disjoint device regions of NG_HIST*NG_HC_DIM and NG_HC_DIM floats. +/// Async on stream, allocation-free and capture-safe. Throws on null or overlapping regions. +void ple_history_advance(float* hist, const float* normalized, void* stream); + +/// Whether the CUDA path is available. The host hash and the table read work without it; the block does not. +bool ple_block_available(); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/qsa.hpp b/engine/strata/include/strata/kernels/qsa.hpp new file mode 100644 index 00000000..dc26024a --- /dev/null +++ b/engine/strata/include/strata/kernels/qsa.hpp @@ -0,0 +1,369 @@ +// include/strata/kernels/qsa.hpp - the QSA (full-attention) layer's cache, indexer and attention, P2.S2. +// +// Spec of record: `ref/qsa.py` (whose own selftest carries eleven PROPERTY checks) and `ref/model.py::_qsa` / +// `_indexer` / `_attend`, transcribed from `build_layer_attn` / `build_attn_qsa` in the source. The +// projections are NOT here: `attn_q`, `attn_k`, `attn_v`, `attn_output`, `indexer.q_proj` and +// `indexer.k_proj` are the existing `s_gemv`/`s2_gemv` kernels, exactly as `gdn_step` leaves them. What lives +// here is everything BETWEEN the projections: +// +// kv_append the new token's K and V into the paged cache +// indexer_key_append the raw indexer tail, and the pooling that fires on block completion +// qsa_index per-CELL indexer scores: Relu per head, sum over heads, + bias, mapped by cell_block +// topk_512 the selection: the `width` largest cells, ties by ascending index, returned ascending +// kv_gather selected cells through the PAGE TABLE into a contiguous scratch +// qsa_attend softmax GQA over the scratch +// qsa_gate_apply `attn * sigmoid(gate)` and the round to the fp16 activation `attn_output` consumes +// +// DECODE ONLY, and that is a deliberate scope statement rather than an omission. `ref/qsa.py::indexer_scores` +// has no mask parameter and says why: "The causal part of the mask is already satisfied: every cached cell +// precedes the query at decode." The plan's `qsa_index` bullet asks for a "block-causal mask", and at decode +// its entire content is the TAIL -> SPARE SLOT mapping (`cell_block`), which is implemented here and tested. +// The per-query form - a query at position i may only see blocks with `block_start + r - 1 <= i`, plus the tail +// tokens - is a PREFILL property: `phases/phase-5-prefill-and-context-reuse.md` L73 builds it as a +// [chunk x blocks] GEMM with per-row top-k. Adding a mask flag here that decode cannot exercise would be a +// parameter with no observable behaviour, and this project has already been bitten by checks that cannot see +// the thing they claim to check. +// +// ============================================================================================ +// **THIS WHOLE API IS NOT YET CAPTURABLE, AND IT IS NOT OBVIOUS WHICH PARTS ARE NOT.** +// +// A CUDA graph bakes kernel ARGUMENTS in at capture time. Any argument that CHANGES PER TOKEN is therefore +// frozen at its first-token value on replay - silently, because the graph still runs, still produces finite +// output, and still looks correct. Auditing this header for that property (round 211-212) found FIVE entry +// points, not one: +// +// kv_append int64_t pos every token the new cell's position +// qsa_index int64_t n_bid every token completed blocks +// qsa_index int64_t n_kv every token cached cells +// topk_512 int64_t n_kv every token cached cells +// kv_gather int64_t n_ids every token = qsa_selection_width(n_kv, s) +// qsa_attend int64_t n_ids every token as above +// indexer_key_append int64_t pos FIXED now takes `const int32_t* pos_dev` +// +// WHAT A CAPTURED LAYER WOULD ACTUALLY DO, and it is worse than a crash: `kv_append` would write EVERY token to +// position 0, `qsa_index` and `topk_512` would score exactly one cell, `kv_gather` would gather one cell, and +// attention would be over a single cell for the whole sequence. Finite, plausible, and indistinguishable from +// "the model has no context" - a symptom that would be blamed on the KV cache, the selection, or the weights. +// +// THE FIX IS ONE DEVICE BUFFER, NOT SIX SIGNATURES. Every one of these values is a pure function of the +// current position and the geometry, so they belong together in a small device-resident step state that is +// written once per token: +// +// step[0] = pos step[1] = n_kv = pos+1 +// step[2] = n_bid step[3] = width = qsa_selection_width(n_kv, s) +// +// Each kernel reads the entries it needs, every argument list becomes constant across tokens, and the whole +// QSA path captures. Writing it as six separate pointer parameters would leave six places to forget and no +// single thing to check. +// ============================================================================================ +// +// ---- LAYOUTS. Every one of these is a runtime buffer and not a weight, so the layout is a free choice - but +// it must be WRITTEN DOWN, because the alternatives index the same numbers and a mix-up is silent. +// +// K/V CACHE: FP16, paged, `[page][kv_head][page_size][head_dim]` with head_dim fastest. The plan says "FP16 +// first" and fp16 is also what makes 32K of context fit: 12 layers x 2 heads x 256 dims x 2 (K and V) x 2 B x +// 32768 = 805 MiB, against 1.6 GiB in f32. The page granule is coarse (the shape's `page_size`) for the +// reason `Memory/Qwen-5070-engine-campaign/src/plans/paged-kv-cache.md` L146-170 gives: this engine serves a +// handful of sequences and not hundreds, so fine granularity buys nothing and costs per-token indirection. The +// physical row for logical cell `t` and head `h` is +// +// page = table[t / page_size]; (page * n_head_kv + h) * page_size + (t % page_size) +// +// i.e. ONE HEAD's worth of consecutive cells is contiguous within a page. That is the property attention +// wants; the alternative (cell-major inside the page) makes a cell's two heads contiguous instead, which is +// the property `kv_append` wants and nowhere near as valuable. **Nothing outside this header may assume the +// mapping**: `qsa_attend` reads a gathered scratch and never a pool, and the test runs the same fixture at +// page_size 1, 4 and 512 with a permuted page table and requires the attention output to be IDENTICAL, so the +// granule cannot leak into the result. +// +// INDEXER KEYS: FP32, not fp16 and not the plan's INT8. These carry no tolerance anywhere in the contract: +// `docs/capture-format.md` L127 makes `indexer_ids` an EXACT key, because a different selected cell is a +// different attention input. The key is a pooled MEAN of four raw keys followed by a norm and a rotation, so +// an fp16 store perturbs every score by ~2^-11 relative, and the selection boundary is exactly where that +// matters. The cost of fp32 is 512 B per block per layer = 128 B/token/layer = 1.5 KiB/token over the 12 QSA +// layers, i.e. 50 MiB at 32K: cheap next to a correctness contract. The plan's INT8 indexer key is a Phase 3 +// optimisation and it has to be justified by a measured selection-flip rate against this baseline. +// +// The RAW tail is fp32 for the same reason and because it is only `idx_block - 1` rows. +#pragma once + +#include + +namespace strata::kernels { + +/// Geometry of one QSA layer. The real artifact: n_head 24, n_head_kv 2, head_dim 256, n_rot 64, +/// idx_n_head 4, idx_dim 128, idx_block 4, idx_top_k 2048, freq_base 1e7, rms_eps 1e-6. +struct QsaShapes { + int64_t n_head = 0; ///< query heads (24). n_head must be a multiple of n_head_kv + int64_t n_head_kv = 0; ///< key/value heads (2). The q -> kv map is `q / (n_head/n_head_kv)`, NOT `q % kv` + int64_t head_dim = 0; ///< 256, and must be a multiple of 4 + int64_t n_rot = 0; ///< 64 rotated dims of head_dim (and of idx_dim), NEOX pairs + int64_t idx_n_head = 0; ///< indexer query heads (4) + int64_t idx_dim = 0; ///< indexer key width (128) + int64_t idx_block = 0; ///< r = 4: the indexer pools one key per 4 cells + int64_t idx_top_k = 0; ///< 2048 cells of selection budget + int64_t page_size = 0; ///< KV page granule in CELLS; 1 is a legal unpaged configuration +}; + +/// The real artifact's geometry, so no caller transcribes it by hand. +inline QsaShapes qsa_real_shapes() { + QsaShapes s; + s.n_head = 24; s.n_head_kv = 2; s.head_dim = 256; s.n_rot = 64; + s.idx_n_head = 4; s.idx_dim = 128; s.idx_block = 4; s.idx_top_k = 2048; + // one page = one indexer block (4 cells): the granule KV streaming keeps resident (kv_stream.hpp). The readers + // resolve a row per cell anyway, so the page size costs them nothing (measured: identical output and speed). + s.page_size = 4; + return s; +} + +/// The one legal RMSNorm epsilon for this artifact (`attention.layer_norm_rms_epsilon`). +inline float qsa_rms_eps() { return 1e-6f; } +/// `rope.freq_base`, the DEFAULT frequency base. The artifact ships no `rope.scaling` keys, so the +/// process's rope scaling starts at none - the runtime configuration lives in `rope_scaling.hpp` +/// (`rope_scaling_set`, once at startup, before the table is built and any graph captured), and this +/// constant is what that config's `freq_base` defaults to and what CLI `--rope-freq-base` overrides. +inline double qsa_freq_base() { return 1e7; } + +/// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`. +/// +/// The `r - 1 = 3` is not slack, it is the incomplete tail: the budget is whole blocks PLUS whatever cells do +/// not fill one. So the plan's "selection skipped when context <= 2,048" is conservative by two - the source's +/// own bound is 2,051, and `ref/qsa.py` L292-294 records the disagreement. Below the bound the selection is +/// the IDENTITY, which `topk_512` is required to reproduce exactly rather than approximately. +inline int64_t qsa_selection_width(int64_t n_kv, const QsaShapes& s) { + const int64_t w = s.idx_top_k + s.idx_block - 1; + return n_kv < w ? n_kv : w; +} + +/// THE PER-TOKEN VALUES EVERY QSA KERNEL NEEDS, IN DEVICE MEMORY. +/// +/// This exists so the QSA layer can be a CUDA graph. A graph bakes kernel ARGUMENTS in at capture time, so any +/// per-token argument is frozen at its first-token value on replay - silently, because the graph still runs and +/// still produces finite output. Six entry points used to take one of these as a host scalar; every one of +/// them now reads it from here instead, which makes every argument list constant across tokens. +/// +/// WHAT IT PREVENTS, concretely: with `pos` frozen, `kv_append` writes every token to cell 0, `qsa_index` and +/// `topk_512` score one cell, `kv_gather` gathers one cell, and attention runs over a single cell for the whole +/// sequence. Finite, plausible, and indistinguishable from "the model does not use its context". +/// +/// The four entries are NOT independent - `n_kv = pos+1` and `width = qsa_selection_width(n_kv, s)` - which is +/// exactly why they live in one buffer with one writer: `qsa_step_write` computes all four from `pos`, so a +/// caller cannot update one and forget another. +/// +/// It is written by a plain H2D copy of four int32, which IS capturable and re-reads its source at replay +/// (`bench/micro/pinned_capture.cu` case B) - so the same buffer works in a captured graph and in a direct +/// launch. +enum QsaStep : int { + kStepPos = 0, ///< the new cell's sequence position + kStepNKv = 1, ///< pos + 1: how many cells are in the cache + kStepNBid = 2, ///< n_kv / idx_block: how many blocks have COMPLETED + kStepWidth = 3, ///< qsa_selection_width(n_kv, s): how many cells the selection returns + kStepCount = 4, +}; + +/// `step` is (kStepCount,) int32 DEVICE memory. Pointers to it are passed to the entry points below; it is +/// allocated by the caller (it is per-sequence state, not scratch). +/// +/// Returns the bytes one step buffer needs, so a caller sizing an arena does not transcribe `kStepCount`. +inline uint64_t qsa_step_bytes() { return sizeof(int32_t) * (uint64_t) kStepCount; } + +/// Fills a HOST array of `kStepCount` int32 from `pos`, so a caller can upload it in one copy. Keeping the +/// arithmetic here rather than at the call site is the point of the buffer: `n_kv` and `width` are derived, +/// and a caller computing them by hand is a caller who can compute them differently. +void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s); + + +/// One token's K and V into the paged FP16 cache, at logical cell `pos`. +/// +/// k_pool, v_pool `[page][kv_head][page_size][head_dim]` fp16, page_size*n_pages cells each +/// page_table (n_pages,) i32: logical page -> physical page. NOT assumed to be the identity +/// kcur, vcur (n_head_kv, head_dim) f32. `kcur` must ALREADY be normed and rotated - V is never rotated +/// +/// The fp32 -> fp16 conversion is `f16_from_f32` (see f16_bits.hpp) and not `__float2half`. +void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream); + +/// The selected cells through the page table into a contiguous scratch. +/// +/// ids (n_ids,) i32, logical cells, ASCENDING and unique as `topk_512` returns them +/// k_scratch etc (n_ids, n_head_kv, head_dim) fp16, written in full +/// +/// A cell that is not gathered does not exist for `qsa_attend`, which is how the top-k mask is realised: the +/// source fills the kq mask with -inf and leaves the selected cells at zero, so an unselected cell has weight +/// exactly zero even when it would score highest (`ref/qsa.py` PROPERTY 8 tests precisely that). +void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, + int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream); + +/// WHERE THE INDEXER'S PER-SEQUENCE STATE LIVES. One set per QSA layer per sequence. +/// +/// tail (idx_block - 1, idx_dim) f32 the RAW tail: cells of the block being filled, slot = pos % idx_block +/// dead (idx_dim,) f32 the spare slot's key, = rms_norm(raw key of cell 0), CONSTANT +/// pooled (max_cells/idx_block + 1, idx_dim) f32 block b at row b, the spare slot at row n_bid +/// block_pos (1,) i32 scratch: the kernel writes the completed block's first-cell +/// position here so the rotation can read it ON THE DEVICE +/// +/// **Every pointer in this struct is a DEVICE pointer**, and so are every other pointer this header's entry +/// points take: `rope_neox_apply` indexes its cos/sin table and its position array on the device, so a host +/// scalar passed as `pos` is an illegal access rather than a convenience. `block_pos` exists for exactly that +/// reason - the rotation position is derived from the host's `pos`, so it has to be handed to the device +/// through memory, which is also the only form a CUDA graph can replay. +/// +/// The spare slot MOVES: it is at row `n_bid`, and `n_bid` grows by one on every block completion. It is also +/// constant in value, because it is derived from cell 0's raw key and `rope_neox(., 0)` is the identity - which +/// is what makes a tail of three keys sufficient. A design that pooled only from the tail could not produce +/// this key at all after the first block. +struct QsaIndexerBuffers { + float* tail = nullptr; + float* dead = nullptr; + float* pooled = nullptr; + int32_t* block_pos = nullptr; +}; + +/// Append one raw indexer key (IDX_DIM wide, fp32, NEVER normed and NEVER rotated - `ref/qsa.py` L201-210) and +/// run the pooling if this cell COMPLETES a block. +/// +/// `pooled[b] = rope_neox(rms_norm(mean(raw[b*r .. b*r+r-1]), w_k_norm), pos of cell b*r)` for b = pos/r on a +/// completion, and the spare slot `pooled[n_bid] = rope_neox(rms_norm(raw[0], w_k_norm), 0)`. The rotation +/// position is the block's FIRST cell, which `ref/qsa.py` PROPERTY 4 pins and the test re-pins: rotating at the +/// block's LAST cell keeps every shape and every magnitude. +/// +/// **`pos_dev` IS A DEVICE POINTER AND THIS FUNCTION IS CAPTURABLE.** It used to take `int64_t pos` as a host +/// scalar, and a CUDA graph bakes kernel ARGUMENTS in at capture time - so a captured call would have replayed +/// the FIRST token's position forever: `slot = pos % idx_block` would never advance, no block would ever +/// complete, the indexer would keep pooling cells 0-3, and the selection would stay pinned to the first block. +/// Not a crash and not a small error - a plausible attention output over the wrong cells. Worse than a stale +/// POINTER, which this project's pitfalls list already warns about, because a stale pointer tends to fault while +/// a stale VALUE looks like a working graph. +/// +/// It could not be fixed by swapping the scalar for a pointer alone: `pos` was ALSO read on the host, to decide +/// whether to run the completion rotation at all and which pooled row to rotate. So the rotation moved INTO +/// the pooling kernel, which is why this now takes `cos_tab`/`sin_tab` and `n_rot`, and why `block_pos` is kept +/// only as a readable record of the rotation position rather than as the input to a second launch. +/// +/// `pos_base` IS THE SEQUENCE'S FIRST CELL'S POSITION, so cell j sits at position `pos_base + j`. The kernel +/// cannot derive it: `QsaCache.pos` is what the reference rotates by, and equating a cell's position with its +/// index is only right for a sequence that starts at 0. The test runs the fixture at `pos_base = 100`, where +/// the two readings are 514% apart. `pos_base` is CONSTANT for a sequence, so unlike `pos_dev` it is safe to +/// bake into a graph. +void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm, + float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab, + const float* sin_tab, void* stream); + +/// Per-CELL indexer scores, `n_kv = pos + 1` of them, fp32. +/// +/// pooled (n_bid + 1, idx_dim) block keys, the spare slot last, as `indexer_key_append` maintains them +/// q_idx (idx_n_head, idx_dim) ALREADY normed and rotated by the caller +/// bias (n_bid + 1,) or null optional additional per-block bias +/// +/// score[j] = bias[cb] + sum_h Relu(dot(pooled[cb], q_idx[h])), cb = min(j / r, n_bid) +/// score[j] += 1e9f for incomplete-tail cells (j >= (n_kv / r) * r). +/// The tail bias matches llama.cpp's causal decode input and applies even when bias is null. +/// Completed blocks receive no tail bias; the step API derives this from each replay's n_kv. +/// +/// The Relu is PER HEAD and the sum is over heads AFTERWARDS: `relu(sum_h dot_h)` is the rival reading, and it +/// is a different number whenever any head's dot is negative. Flipping one query head's sign can never lower +/// the score, which is the property the test asserts. There is NO softmax and NO 1/sqrt(d) here. +void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s, + int64_t n_kv, float* cell_scores, void* stream); + +/// The largest `qsa_selection_width(n_kv)` cells of `cell_scores`, ascending, into `ids`. +/// +/// Ties are broken by ASCENDING INDEX. ggml does not specify that, and `ref/qsa.py` is explicit about it so a +/// mismatch is at least diagnosable; the host test compares against `np.lexsort((arange, -scores))`, which is +/// the same rule, implemented independently of the kernel's threshold search. +/// +/// `cap` is the caller's buffer size in ids and must be >= the width; the kernel writes EXACTLY `width` and +/// refuses rather than truncating. The `-1` padding that `docs/capture-format.md` L66-73 describes is the +/// capture writer's job, not this kernel's: the padded width is a property of the run, not of one token. +/// +/// `n_kv` must be <= 32768 (`kTopkMaxCells`): the selection runs in ONE block, which is what makes the +/// ascending tie rule deterministic without a second pass over global memory. Phase 3 replaces this with a +/// radix select and Phase 7 raises the cap; until then a longer context is refused loudly. +inline constexpr int64_t kTopkMaxCells = 32768; + +void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids, + void* stream); + +/// Softmax GQA over ONLY the gathered cells. `q` is (n_head, head_dim) f32, already normed and rotated. +/// +/// scores[j] = dot(k[j][q / (n_head/n_head_kv)], q[h]) / sqrt(head_dim) +/// w = softmax_j(scores) +/// attn[h] = sum_j w[j] * v[j][q / (n_head/n_head_kv)] +/// +/// The q -> kv head map is INTEGER DIVISION (`ggml-cpu/ops.cpp` L8729: `iv2 = iq2 / rv2`), not `q % n_head_kv` +/// - with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...], and both produce a well-formed result. +/// +/// `attn` is (n_head, head_dim) f32 and NOT yet gated; `weights`, when non-null, is (n_head, n_ids) f32, which +/// is what `docs/capture-format.md`'s `L{n}.qsa_scores` records. Produced here rather than recomputed by the +/// caller so the capture cannot drift from the attention it claims to describe. An EMPTY `ids` is legal and +/// gives a zero `attn` (no selected cell has no softmax to take). +void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids, + const QsaShapes& s, float* attn, float* weights, void* stream); + +/// `attn *= sigmoid(gate)` in f32, then ONE round to fp16 for the `attn_output` GEMV. +/// +/// q_full (n_head, 2*head_dim) f32 the raw `attn_q` projection, BEFORE any norm +/// gate = q_full[h][head_dim + d] - the SECOND half of each head's 2*head_dim block +/// out (n_head, head_dim) fp16 +/// +/// The split is NOT element-interleaved (`ref/qsa.py` PROPERTY 10 pins that: `q = per_head[:, :head_dim]`, +/// `gate = per_head[:, head_dim:]`), and the rounding happens AFTER the multiply so there is one rounding +/// rather than two. SIGMOID, not SiLU: this artifact's QSA gate is a sigmoid. +void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream); + +/// THE SAME MULTIPLY WITHOUT THE fp16 ROUND, for the caller whose weight wants Q8_K. +/// +/// `attn_output` is a K-quant (Q4_K/Q5_K/Q6_K in every QSA layer of this artifact) and its `vec_dot_type` is +/// **Q8_K, not fp16** - `docs/activation-contract.md` is explicit, and the measured cost of getting it wrong is +/// 0.66-1.41% per GEMV against a 1e-3 tolerance, which is above what Gate C1 allows. The fp16 form exists +/// because that is what the engine did first; this one exists because that was a gap, and the caller quantizes +/// to Q8_K between the two calls. +/// +/// The arithmetic is IDENTICAL to `qsa_gate_apply`'s up to the last step, and the multiply is in double in both +/// - so switching between them changes exactly one rounding, which is the point. +void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream); + +// ================= THE CAPTURABLE ENTRY POINTS ================= +// +// These take the per-token counts from `step` AND size every launch from a CONSTANT capacity, which is the two +// things a CUDA graph requires. The host-scalar entry points above are thin wrappers over these: they fill a +// module-level step buffer and pass this token's counts as the capacities, so they behave exactly as before and +// stay convenient for a direct launch or a test. +// +// **THE LAYER MUST USE THESE.** The wrappers are correct for a direct launch and WRONG inside a graph: their +// grid and their shared size change per token, and a graph bakes both in. A captured `qsa_index` launched for +// one block leaves every other pooled row unscored; a captured `qsa_attend` sized for one cell reads past its +// shared buffer once the sequence grows. Both failures are silent. +// +// The kernels already guard for the surplus: `qsa_index_kernel` returns for `b > n_bid`, `kv_gather_kernel` +// returns past its device `n_ids`, and `qsa_attend_kernel` handles an empty selection itself. So passing a +// capacity LARGER than this token needs is correct, not merely safe. + +/// `max_blocks` must be at least `(max_cells / idx_block) + 2`. +void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s, + const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream); + +/// `cap` must be `qsa_selection_width(kTopkMaxCells, s)` - the largest width the kernel can ever write. +void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step, + int32_t* ids, void* stream); + +/// `max_ids` must be the CAPACITY of `k_scratch`/`v_scratch` in ids. +void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, + const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, + uint16_t* k_scratch, uint16_t* v_scratch, void* stream); + +/// `max_ids` must be at least the largest selection the geometry can produce, because it sizes the SHARED +/// memory the softmax works in. +void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, + const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights, + void* stream); + +struct KvHostPools; // kv_stream.hpp + +/// The cell's position comes from `step`, so this is the form a graph may contain. With a host copy (KV streaming) +/// the cell is written there too, and to VRAM only if its block is resident. +void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host = nullptr); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/qsa_decode_attn.hpp b/engine/strata/include/strata/kernels/qsa_decode_attn.hpp new file mode 100644 index 00000000..f67bfad2 --- /dev/null +++ b/engine/strata/include/strata/kernels/qsa_decode_attn.hpp @@ -0,0 +1,51 @@ +// include/strata/kernels/qsa_decode_attn.hpp - plan v0.3 P3/P7: split-K decode attention over the selected cells. +// +// The first attention kernel runs one block per query head (24 blocks on a 48-SM part), reads each key row with one +// thread (uncoalesced) and walks every selected cell serially for the values; at a 4K context (2,051 selected +// cells) that costs ~0.3-0.5 ms per QSA layer. This one reads the KV POOLS directly through the page table and the +// selection ids (no gather copy), in chunks of CHUNK cells per block, and serves all `n_head / n_head_kv` query +// heads that share a KV head from one read of the chunk: +// +// grid (ceil(cap / CHUNK), n_head_kv): s = q.k * scale for 12 heads x CHUNK cells, chunk max m and sum l, +// acc = p . V -> partials +// grid (n_head): merge the chunks with the usual log-sum-exp rescale +// +// FP16 pools or INT8 pools (codes + fp16 scale per 64 values, `kv_q8.hpp`). The grid is sized by the capacity; +// the real count comes from `step[kStepWidth]` as for every other capturable QSA kernel. +#pragma once + +#include "strata/kernels/qsa.hpp" + +#include + +namespace strata::kernels { + +struct QsaAttnPools { + bool without_key = false; + const float* keyless_cos = nullptr; + const float* keyless_sin = nullptr; + int keyless_n_rot = 0; + const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions + const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 + const uint16_t* v_pool = nullptr; + const int8_t* k_q = nullptr; ///< int8 codes, same layout + const int8_t* v_q = nullptr; + const uint16_t* k_scale = nullptr; ///< fp16 [page][kv_head][page_size][head_dim / 64] + const uint16_t* v_scale = nullptr; + const uint8_t* k_q4 = nullptr; ///< q4_0 block_q4_0 [page][kv_head][page_size][head_dim / 32 * 18] + const uint8_t* v_q4 = nullptr; + const int32_t* page_table = nullptr; +}; + +/// Scratch floats for `cap` selected cells: partial accumulators, maxima and sums. +uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s); + +void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream); + +/// Plan v0.3 P5: `n_q` queries at once, each with its own selection: q [n_q, n_head, 256], ids [n_q, cap], steps +/// [n_q, kStepCount], attn [n_q, n_head, 256]; scratch is `n_q` times the single-query size. +void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/qsa_prompt_attn.hpp b/engine/strata/include/strata/kernels/qsa_prompt_attn.hpp new file mode 100644 index 00000000..37261a10 --- /dev/null +++ b/engine/strata/include/strata/kernels/qsa_prompt_attn.hpp @@ -0,0 +1,31 @@ +// include/strata/kernels/qsa_prompt_attn.hpp - perf-review D-1: the prompt path's QSA attention on tensor cores. +// +// `qsa_decode_attn_batch` serves a prompt one query at a time with the decode kernel: FP32 dot products with a warp +// reduction per head and cell, 64-cell chunks whose partial sums go through global scratch to a second (merge) +// kernel. At 32K that is 21% of the prompt (5.6 s of 26 s on a 5070, Q2_0, int8 KV), and it is limited by +// instruction issue, not memory (~150 GB/s of logical reads, 3.4 TFLOP/s). +// +// This kernel keeps the same per-query selection (no masking, no union) and reads the same pools, but: +// * one block per (query, KV head) walks all its selected cells in chunks of 32 with an online softmax: no +// split-K scratch and no merge kernel; +// * q.k and p.v are m16n8k16 FP16 MMAs with FP32 accumulation over the 12 query heads of the KV head (+4 pad rows); +// * the stored values enter exactly: int8 codes are exact in FP16 and their per-64 scales are applied in FP32 +// (to the q.k partial of each 64-dim group, and folded into p for p.v); FP16 KV is used as is; +// * q and p are split into FP16 hi + lo parts (two MMAs each), so they keep ~22 bits: the result differs from +// the FP32 kernel by summation order and the exp2 rounding, not by an FP16 cast. +// Not bitwise equal to `qsa_decode_attn_batch`; `qsa_prompt_attn_parity` bounds the difference and the prompt +// quality gate (needles, teacher-forced top-1) checks it end to end. Q4_0 KV is not handled (returns false). +#pragma once + +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +namespace strata::kernels { + +/// Same arguments and output as `qsa_decode_attn_batch` minus the scratch. Returns false (nothing launched) when the +/// pools are Q4_0 or the geometry is not 24 heads / 2 KV heads / 256: the caller then uses the old kernel. +bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/qsa_select.hpp b/engine/strata/include/strata/kernels/qsa_select.hpp new file mode 100644 index 00000000..b1b1a625 --- /dev/null +++ b/engine/strata/include/strata/kernels/qsa_select.hpp @@ -0,0 +1,48 @@ +// include/strata/kernels/qsa_select.hpp - plan v0.3 P5/P7: the QSA indexer's block scores and top-k selection, +// for many queries at once and at long context. +// +// The per-token path scores every pooled block with one FP64 block per row (qsa_index_kernel) and selects with a +// single-block kernel that makes 32 bit-serial passes over every CELL (topk_kernel): ~0.1-0.2 ms per query at 32K, +// once per QSA layer and token - 1-2 ms of a decode token and most of a 32K prompt's time. Here: +// +// qsa_block_scores : one warp per (query, block), FP32; relu per indexer head, summed; block n_bid (the +// incomplete tail) scores the `dead` key and gets +1e9 when it has cells - which is exactly +// what the per-token path reads there, because pooled[n_bid] holds `dead` at that time (in +// a chunk it may already hold a block completed later, so it is not read). +// qsa_block_topk : one block per query; a 4-pass radix select over the query's n_bid + 1 blocks, each +// weighted by its cell count, then the cells emitted in ascending order with ties to the +// lowest index - the same selection as topk_kernel, over a quarter of the elements. +// +// Queries carry their own step record (pos, n_kv, n_bid, width) as everywhere else in QSA. +#pragma once + +#include "strata/kernels/qsa.hpp" + +#include + +namespace strata::kernels { + +/// scores [nq, max_blocks]; q_idx [nq, idx_n_head, idx_dim] (normed and rotated); steps [nq, kStepCount]. +void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, + int64_t active_blocks = -1); ///< perf-review C-1: > 0 launches only this many blocks (the + ///< batch's largest n_bid + 1; not for a captured graph) + +/// The same scores on tensor cores (3xTF32, FP32-level accuracy but another summation order: not bitwise; the tail +/// block n_bid is the warp kernel's arithmetic). For the prompt path; false (nothing launched) on another geometry. +/// On AMD it is the gfx12 (RDNA4) WMMA kernel (a three-way bf16 split, six products); false on any other AMD target. +bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks); + +/// ids [nq, cap] (cells, ascending); `cap` >= the largest selection width. +void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, + int64_t active_blocks = -1); ///< > 0: no query of the call has more than this many blocks (n_bid + 1; + ///< the same contract as qsa_block_scores's). The register kernel is + ///< chosen by this, not by the capacity max_blocks (a long + ///< --max-context otherwise sends every short prompt to the slow one) +/// The original kernel (keys read from memory on every radix pass), for tests: the same ids. +void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/quantize_act.hpp b/engine/strata/include/strata/kernels/quantize_act.hpp new file mode 100644 index 00000000..49d858b2 --- /dev/null +++ b/engine/strata/include/strata/kernels/quantize_act.hpp @@ -0,0 +1,58 @@ +// include/strata/kernels/quantize_act.hpp - activation quantization, host-callable (P2.S2). +// +// `ggml_mul_mat` converts src1 (the ACTIVATION) to the weight's `vec_dot_type` before the dot product. The +// CPU expert path already does this (`bench/micro/cpu_s2.cpp`, int8 + vpdpbusd, parity 1.461e-06); the GPU +// kernels take FP16 activations. Leaving the two inconsistent means the same token computes different +// numbers for different experts, so this is the GPU half of the same rule. +// +// Q2_0 -> Q8_0 is the case that matters most: the routed experts are all Q2_0, which is 31.64 GiB of the 38 +// GiB pack. Q8_K is the OTHER HALF of `VEC_DOT_TYPE` (Q3_K/Q4_K/Q5_K/Q6_K/IQ4_XS) and covers 2.89 GiB of +// dense weights - the attention projections and `ssm_out`, i.e. the numerically sensitive ones. +// +// `docs/activation-contract.md` records the decision that BOTH must exist and be used: an FP16 activation +// against a quantized weight disagrees with the oracle by 0.6-0.9%, which is 6-9x P2.S2's 1e-3 tolerance. +#pragma once + +#include + +namespace strata::kernels { + +// x (n floats) -> ggml's block_q8_0 layout: 34 bytes per 32 elements, { fp16 d ; int8 qs[32] }. +// n must be a multiple of 32. `stream` may be null, in which case the call synchronises. +void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream); + +// **R4.2h: THE SAME BLOCKS, PLUS THE CPU's fp32 SCALE - and the CPU's rounding rule with it.** The engine +// computes each routed expert twice (misses on the CPU through `act_quant_q8_1`, hits on the GPU through +// `quantize_q8_0`) and the two disagreed: `ActQ::scale` is fp32 while a `block_q8_0` stores fp16 `d`, which is +// **4.761e-04 relative on 80 of 80 chunks** (`bench/micro/act_quant_parity.cu`). This variant exists so the +// hit path can use the CPU's multiplier. Writes `blocks[n/32 * 34]` and `scales[n/32]`; `scales` must not be +// null. `quantize_q8_0` is unchanged and still matches ggml's bytes, which is what `moe_hit_parity` checks. +void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream); + +// The inverse, for round-trip checks: each element becomes `q * d16`. +void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream); + +// x (n floats) -> ggml's block_q8_K layout: 292 bytes per 256 elements +// { float d ; int8_t qs[256] ; int16_t bsums[16] } +// n must be a multiple of 256. `stream` may be null, in which case the call synchronises. +// +// This is `quantize_row_q8_K_ref` (ggml-quants.c L2768) transcribed, including the two things that look like +// mistakes and are not: +// +// * the scale is `-127/max`, NOT `-128/max`. The source carries the `-128` version COMMENTED OUT with the +// note that IQ2_XXS needs the change for an awkward AVX implementation. Getting this wrong is a 0.79% +// scaling error - the same order as the quantisation step, so it yields a working-looking activation that +// ggml never sees. It cost round 120. +// * `max` is the SIGNED value at the position of the largest magnitude, so a POSITIVE max gives a NEGATIVE +// iscale and the `+max` element maps to -127 while the `-max` element maps to +127. +// +// The rounding is `nearest_int`, which is round-half-to-EVEN via the 12582912.0f magic number - not +// `roundf`'s half-away-from-zero. They differ only on exact ties, i.e. almost never on real data, which is +// precisely why the wrong one would survive any amount of end-to-end testing; the parity test constructs +// exact ties on purpose. +void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream); + +// The inverse: each element becomes `d * qs[j]`, with `d = 1/iscale` stored as f32. +void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/rope.hpp b/engine/strata/include/strata/kernels/rope.hpp new file mode 100644 index 00000000..45e54faf --- /dev/null +++ b/engine/strata/include/strata/kernels/rope.hpp @@ -0,0 +1,64 @@ +// include/strata/kernels/rope.hpp - NEOX partial RoPE, host-callable (P2.S2). +// +// Pairing is NEOX: (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1). The rotation is PARTIAL - only the +// first n_rot of head_dim are touched, 64 of 256 in this artifact - and the tail passes through. +// +// The cos/sin table is built on the HOST in float64 (see src/kernels/cuda/rope.cu for why) and the kernel is +// a pure rotation over it. The table depends on (n_rot, theta, position) and not on the token, so it is worth +// caching; `build_rope_table` fills `max_pos` positions of `n_rot/2` pairs each. +// +// ROPE SCALING RIDES IN THE TABLE, NOT IN THE KERNEL. The kernels below read cos/sin values and +// cannot tell a scaled table from an unscaled one - with scaling on, the scaled angles (and YaRN's +// mscale magnitude correction, folded into the same values) simply ARE the table. That is why +// neither `rope_neox_apply` nor the indexer's pooling kernel takes any scaling argument: the config +// enters once, here, at build time (`rope_scaling.hpp`). +#pragma once + +#include + +#include "strata/kernels/rope_scaling.hpp" + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_ROPE_HD __host__ __device__ +#else +#define STRATA_ROPE_HD +#endif + +namespace strata::kernels { + +/// ONE NEOX PAIR: `(a, b) -> (a*c - b*s, a*s + b*c)`. +/// +/// This exists so the pairing and the sign convention live in ONE place. `rope_neox_apply` walks a whole row +/// with it, and `indexer_key_append`'s pooling kernel uses it to rotate the single pooled row it has just +/// written - two call sites that MUST agree, because the indexer's key is compared against query scores +/// downstream and a mismatched rotation produces a well-formed key pointing the wrong way. +/// +/// It is `__host__ __device__` (the `f16_bits.hpp` pattern) rather than device-only so a host-side reference in +/// a test can call THE SAME function instead of transcribing it. A transcription is exactly how the pairing +/// convention gets written down wrong. +/// +/// In-place is safe: the caller writes both outputs from the two inputs it read, and under NEOX no two pairs +/// share an element (`i` pairs with `i + n_rot/2`, so the halves are disjoint). +STRATA_ROPE_HD inline void rope_neox_pair(float a, float b, float c, float s, float& oa, float& ob) { + oa = a * c - b * s; + ob = a * s + b * c; +} + +void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab); + +/// The same table under the process's rope scaling (rope_scaling.hpp). For `RopeScalingType::None` +/// this IS the five-argument builder above - the parity test holds the two to be bit-identical - and +/// for linear/YaRN the scaled angles (YaRN's mscale included) replace them. The math is ggml's, +/// transcribed; see the header of `rope_scaling.hpp` for what arrives from where. +void build_rope_table(int n_rot, const RopeScaling& scaling, int max_pos, float* cos_tab, float* sin_tab); + +// `x` and `out` are (rows, head_dim) and `pos` is (rows,) - one position per row, so a batch of heads at +// different sequence positions is one call. `cos_tab`/`sin_tab` are (max_pos, n_rot/2). `out` may equal `x`. +// +// **`pos` IS A DEVICE ARRAY, NOT A HOST SCALAR**, and that is a graph-capture requirement rather than a style +// choice: a CUDA graph bakes kernel arguments in at capture time, so a host scalar position would replay the +// first token's value forever. See the same note on `indexer_key_append` in `qsa.hpp`. +void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab, + const float* sin_tab, const int* pos, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/rope_scaling.hpp b/engine/strata/include/strata/kernels/rope_scaling.hpp new file mode 100644 index 00000000..b494ddc7 --- /dev/null +++ b/engine/strata/include/strata/kernels/rope_scaling.hpp @@ -0,0 +1,193 @@ +// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one. +// +// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no +// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by +// rescaling the rotation angles. Three types, the llama.cpp set: +// +// none freq_scale 1, no correction - today's behaviour, exactly +// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all +// frequencies compressed uniformly +// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency +// pairs are interpolated, and the pairs in between blend - plus a magnitude correction +// `mscale` that keeps the attention temperature where training put it +// +// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the +// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the +// interpolation mix and the mscale formula below are line-for-line that source, with the MIT +// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel +// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel +// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against +// `corr_dims` directly. Same numbers, one less division per call site. +// +// HOW IT REACHES THE ROPE. Two forms, one config: +// +// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels: +// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks +// bit-exactly against a float64 reference; +// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants +// as kernel arguments. +// +// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture +// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly +// the constraint the per-token values already respect by living in device memory (`st.pos_dev`). +// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet, +// before any graph exists. There is deliberately no way to change it mid-process: the K already in +// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache. +#pragma once + +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_ROPE_SCALING_HD __host__ __device__ +#else +#define STRATA_ROPE_SCALING_HD +#endif + +namespace strata::kernels { + +enum class RopeScalingType { None, Linear, YaRN }; + +/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are +/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f` +/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit. +struct RopeKernelArgs { + float freq_scale = 1.0f; + float corr_low = 0.0f; + float corr_high = 0.0f; + float ext_factor = 0.0f; + float attn_factor = 1.0f; +}; + +/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to. +/// +/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That +/// identity is a regression gate, not a coincidence - the parity test compares the default's table +/// against the pre-scaling builder bit for bit. +struct RopeScaling { + RopeScalingType type = RopeScalingType::None; + double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`) + double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes + double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor + double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over + double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN + double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor) + double beta_fast = 32.0; ///< `--yarn-beta-fast` + double beta_slow = 1.0; ///< `--yarn-beta-slow` + + /// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes + /// `factor` positions into the trained range. + double freq_scale() const { + if (type == RopeScalingType::None) return 1.0; + return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor; + } + + /// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term + /// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the + /// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction. + double mscale() const { + if (ext_factor == 0) return attn_factor; + return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale())); + } + + /// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained + /// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's + /// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below). + void corr_dims(int n_rot, double out[2]) const { + const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base)); + const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base)); + out[0] = start < 0 ? 0 : start; + out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end; + } + + /// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold - + /// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an + /// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn` + /// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting). + RopeKernelArgs kernel_args(int n_rot) const { + RopeKernelArgs a; + if (type == RopeScalingType::None) return a; + double cd[2]; + corr_dims(n_rot, cd); + a.freq_scale = (float) freq_scale(); + a.corr_low = (float) cd[0]; + a.corr_high = (float) cd[1]; + a.ext_factor = (float) ext_factor; + a.attn_factor = (float) attn_factor; + return a; + } + +private: + /// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` + /// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`". + /// float64 rather than ggml's float32: the table path computes in float64 and is held to a + /// bit-exact float64 reference, so its inputs are float64 too. + static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) { + return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) / + (2.0 * std::log(base)); + } +}; + +/// The ramp between extrapolation (1) and interpolation (0). +/// +/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with +/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes +/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The +/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high. +STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) { + const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f); + const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y); + return 1.0f - clamped; +} + +/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic). +/// +/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle +/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor` +/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant; +/// this helper keeps that shape so the native path reads against ggml line by line). +STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, + float corr_high, float ext_factor, float mscale_in, + int pair, float& cos_out, float& sin_out) { + // The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn). + float theta = freq_scale * theta_extrap; + float mscale = mscale_in; + if (ext_factor != 0.0f) { + const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor; + theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix; + // "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting. + mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale); + } + cos_out = cosf(theta) * mscale; + sin_out = sinf(theta) * mscale; +} + +/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation +/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns +/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite` +/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip +/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them). +inline const char* rope_scaling_invalid(const RopeScaling& s) { + if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1"; + if (s.type == RopeScalingType::None) return nullptr; + if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1"; + if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0) + return "the frequency scale must be finite and positive (0 = 1/factor)"; + const double fs = s.freq_scale(); + if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value"; + if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0"; + if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0"; + if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0"; + if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0) + return "the YaRN betas must be finite and > 0"; + if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0"; + return nullptr; +} + +/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file +/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the +/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no +/// atomics: one writer on the startup thread, every reader after it. +void rope_scaling_set(const RopeScaling& scaling); +const RopeScaling& rope_scaling(); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/router_top10.hpp b/engine/strata/include/strata/kernels/router_top10.hpp new file mode 100644 index 00000000..e10295e1 --- /dev/null +++ b/engine/strata/include/strata/kernels/router_top10.hpp @@ -0,0 +1,26 @@ +// include/strata/kernels/router_top10.hpp - the MoE router, host-callable (P2.S2). +// +// logits (n_tokens, n_expert) -> the top-k experts per token with renormalised weights. Semantics are +// `ref/moe.py::router`'s: softmax over ALL experts, stable descending argsort (ties break by index), gather, +// then renormalise with ggml's 2**-14 lower clamp. +// +// The BF16 GEMV that PRODUCES the logits is a separate kernel and is not here; this handles the routing only, +// which is why `logits` is taken as an f32 buffer the caller has already filled. +#pragma once + +#include + +namespace strata::kernels { + +// `stream` may be null, in which case the call synchronises before returning. `ids` is (n_tokens, k) int32 and +// `weights` is (n_tokens, k) f32, both device pointers. k must be <= 64. +void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, + void* stream); + +/// Tests (S6, HIP only): one router kernel by name - 0 the portable kernel, 1 the AMD fast kernel (the default there +/// for 64 < n_expert <= 512, k <= 32; bitwise the same results), 2 the fast kernel forced onto its serial-sum path. +/// False (nothing launched) on CUDA builds or outside that geometry. +bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, + void* stream, int variant); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/s2_expert_grouped.hpp b/engine/strata/include/strata/kernels/s2_expert_grouped.hpp new file mode 100644 index 00000000..af6f52f9 --- /dev/null +++ b/engine/strata/include/strata/kernels/s2_expert_grouped.hpp @@ -0,0 +1,131 @@ +// include/strata/kernels/s2_expert_grouped.hpp - R4's GPU expert tier. +// +// **WHAT THIS IS FOR.** The CPU expert pool is the engine's largest single cost - 663.6 MB of expert bytes per +// token at ~40 GB/s = 16.2 ms on a ~53 ms token - and `test_expert_pool` measures the pipeline hiding +// **1.055 ms of 19.035**. The CPU work is 96% exposed because the residual chain is strictly serial, so the +// only way past it is to stop reading those bytes on the CPU: put experts in VRAM and compute them on the GPU. +// +// **WHY GROUPED, AND WHY THAT WORD IS THE WHOLE DESIGN.** A layer routes ten experts. The obvious +// implementation is a loop over hits calling the per-matrix kernel, and it is wrong by arithmetic: five +// launches per expert at ~6.45 hits and 48 layers is **~1,550 launches per token**, which at a real-stream +// launch cost of ~3.6 us is 5.6 ms - most of the 10.4 ms the tier is supposed to save. So the hits are grouped +// into ONE launch per projection: +// +// 1. `gu_kernel` n_hits x 2 x FF rows - gate and up, together +// 2. `swiglu_kernel` n_hits x FF - silu(gate) * up +// 3. `quantize_q8_0` (the existing one) - the down weight's own activation contract +// 4. `down_kernel` n_hits x H rows +// +// **four launches per layer, not five per expert.** +// +// `h_layer` held-out is **0.0456** - only 4.6% of (layer, token) pairs have all ten experts resident - so this +// cannot be a per-layer grouped kernel with a fixed grid, and the hit list is passed **as data** so the caller +// can keep one captured graph per layer with the maximum grid and a device-side count. +#pragma once + +#include + +namespace strata::kernels { + +/// Bytes of caller-owned scratch `moe_hit_grouped_s2` needs for `n_hits` experts. +/// +/// Two regions: the gate/up activations (`n_hits x 2 x FF` floats) and the quantized intermediate +/// (`n_hits x (FF/32) x 34` bytes). Carved from the caller's arena rather than allocated - a `cudaMalloc` +/// on the token path is forbidden by P2.T10 and illegal during stream capture, and this is called from both. +uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff); + +/// **ONE GROUPED EXPERT EVALUATION.** For each hit `h` in `[0, n_hits)`, evaluates the expert held in +/// `blob_base + slot_index[h] * blob_bytes` against `x_q8_0` and writes `n_embd` floats to +/// `out + dst_index[h] * n_embd`. +/// +/// * `blob_base` the device slot arena; slot `s` starts at `blob_base + s * blob_bytes` +/// * `slot_index` `n_hits` `int32_t` slot indices on the DEVICE, so the caller can change which experts are +/// resident without recapturing anything +/// * **`dst_index` where each hit's answer goes, also on the device and also `n_hits` long.** +/// +/// **THIS IS NOT A CONVENIENCE - IT IS WHAT LETS THE TWO HALVES MEET.** A layer routes ten +/// experts and only some are resident, so the CPU produces the misses at their ROUTED indices +/// (the router's order is what `moe_combine` weights against) and the GPU produces the hits in +/// whatever order the cache happens to hold them. Writing the hits sequentially would land +/// them on the misses' rows; `dst_index` puts hit `h`'s answer on the row its expert was routed +/// to, so the CPU can zero the hit rows, the GPU can fill them, and `moe_combine` needs no +/// change at all. +/// * `x_q8_0` `(n_embd/32)` `block_q8_0`, 34 bytes each, from `quantize_q8_0` +/// * `scratch` `moe_hit_grouped_scratch_bytes(n_hits, n_embd, n_ff)`, caller-owned +/// * `out` `(k, n_embd)` floats - the SAME buffer the misses were written into +/// * **`x_scales` R4.2h, OPTIONAL, and null keeps the previous behaviour exactly.** When non-null it is +/// `n_embd/32` **fp32** activation scales from `quantize_q8_0_scaled`, and they REPLACE the +/// block's fp16 `d` as the activation multiplier - for the gate/up projection and for the +/// intermediate's own quantization in step 3. +/// +/// **THIS EXISTS BECAUSE A HIT AND A MISS MUST PRODUCE THE SAME NUMBER.** The CPU pool +/// multiplies by the fp32 `ActQ::scale` (`cpu/expert.cpp:92`); this kernel read fp16 `d` out +/// of the `block_q8_0`. `bench/micro/act_quant_parity.cu` measured the gap with both real +/// implementations linked: **80 of 80 chunks differ, max relative 4.761e-04** - 2^-11, pure +/// fp16 rounding - which is why enabling the cache changed the generated tokens. Pass null +/// and this is bit-for-bit the kernel `moe_hit_parity` has always checked at 6.279e-08. +/// +/// **THE BLOB LAYOUT IS `expert.hpp`'s AND IS NOT RESTATED HERE.** Gate/up codes are interleaved by row +/// (`2r` = gate, `2r+1` = up), the down codes follow, and each plane's scales are fp16 - which is the ONE +/// difference from `s_gemv_q8`'s S-forms, whose scales are fp32. That difference is why this is a separate +/// kernel rather than a call into the dense path. +void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out, + void* stream, const float* x_scales = nullptr); + +/// Experimental CPU-order implementation. Eight CUDA lanes reproduce the CPU VNNI accumulator lanes, +/// fused multiply-add order, separate correction, and final horizontal reduction. The input must use +/// the CPU quantization contract and fp32 scales. SiLU uses accurate CUDA expf, which can differ from +/// the CPU math library by last bits. End-to-end correctness must be checked against the C1 oracle. +/// Validate both intermediate quantization and final outputs. +/// Optional gate_up_trace receives [all gates | all ups] before SiLU, for parity diagnostics only. +/// Plan v0.3 P4 token graph: the hit path with NO host step. `moe_hit_select` builds this layer's hit list +/// from the routed `ids` and the static residency row (`res_row[e]` = slot or -1) into `slot`/`dst`/`count` +/// (device); `moe_hit_grouped_s2_dev` is `moe_hit_grouped_s2` sized for `cap` hits that reads the real count +/// from `d_count`; `moe_hit_add` adds each hit's row of `hit_out` into `parts` (rows the CPU left at zero). +void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst, + int32_t* count, void* stream); +void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, + void* scratch, float* out, void* stream, const float* x_scales); +void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap, + int64_t n_embd, void* stream); +/// Plan v0.3 P6 verify window: `moe_hit_select` over `n` <= 128 routed entries (T tokens x k, flattened), and the +/// hit kernel with one activation PER TOKEN - entry `dst` reads token `dst / k_per_token`'s rows of `x_q8_0` +/// ((n_embd/32)*34 bytes each) and `x_scales` (n_embd/32 floats each). Per hit, bitwise `moe_hit_grouped_s2_dev`. +/// Plan v0.3 P6: routed experts GROUPED. Group g's blob is at device address grp_ptr[g] (a VRAM slot, or a mapped +/// host blob the kernel reads over PCIe); its entries are [grp_start[g], grp_start[g+1]) with ent_tok (the token +/// whose activation row of x_q8_0/x_scales it reads) and ent_dst (its row of `out`). Each row of a blob is read +/// once for all of its entries. Counts are read from device memory; every entry is bitwise the per-entry kernel. +void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, + const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, + const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream); +/// Plan v0.3 P6: the groups for `moe_grouped_s2` when every expert id is resident at base + id * blob (the MTP +/// layer's 512 experts): counts[0] groups, counts[1] entries; entry dst = routing index, tok = index / k_per_tok. +void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst, + int32_t* ent_tok, void* stream); +void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst, + int32_t* count, void* stream); +void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, + const float* x_scales, int k_per_token, void* scratch, float* out, void* stream); +/// The per-hit kernels (`moe_hit_grouped_s2`, `_dev`, `_multi`) and the grouped ones (`moe_grouped_s2`) +/// were rewritten with bitwise-identical outputs: conflict-free staged activations, `hx` once per chunk, wide loads, +/// two rows per warp. The previous kernels stay for A/B: `STRATA_OLD_GROUPED=1` in the environment selects them, +/// and so does `moe_grouped_select_old(1)`; `0` forces the new ones, `-1` returns to the environment. The environment +/// variable is read once, on first use; the kernel choice is made at each launch (so a captured graph keeps the +/// kernels chosen at capture). Use `moe_grouped_select_old` to switch at runtime. `STRATA_GROUPED_PAIR_MIN_HITS=N` +/// (read once too) keeps the previous per-hit kernels below N hits of capacity; a forced choice overrides it. The +/// new kernels also need 4-byte aligned activations and scratch, and the per-hit ones an 8-byte aligned arena and +/// slot size; otherwise the previous kernels run. +void moe_grouped_select_old(int old); +/// Which kernels the last call of the entry points above launched: 1 = new, 0 = previous, -1 = none since the +/// previous query (the query clears it). For the parity test, which must know the path it compared was taken. +int moe_grouped_last_path(); +void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index, + const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes, + const uint8_t* x_q8_0, void* scratch, float* out, void* stream, + const float* x_scales, float* gate_up_trace = nullptr); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/s2_gemv.hpp b/engine/strata/include/strata/kernels/s2_gemv.hpp new file mode 100644 index 00000000..a09b8226 --- /dev/null +++ b/engine/strata/include/strata/kernels/s2_gemv.hpp @@ -0,0 +1,25 @@ +// include/strata/kernels/s2_gemv.hpp - the S2 GEMV, host-callable (P2.S2). +// +// The expert matvec is the hottest thing in the engine: every token runs 48 layers x 10 experts x 3 roles of +// it, against weights that live in DRAM at 31.64 GiB. Layout is `docs/pack-format.md`'s S2: codes packed 4 +// per byte LSB-first, one FP32 scale per 64 elements. GGUF's ne[0] varies fastest, so a tensor is [n_in, +// n_out] with n_in CONTIGUOUS - which is why one thread per output row reads a contiguous run of blocks. +// +// Activations are FP16 per the phase spec ("FP16 activations in"). The OUTPUT here is FP32 rather than FP16: +// the intended FP16 out needs an f32->fp16 conversion, and rather than write one under a parity test that +// would then be testing two new things at once, this step keeps the output width the one that can be checked +// exactly. The FP16 output and its 1e-3 tolerance is the next increment, and this file says so rather than +// leaving a reader to wonder. +#pragma once + +#include + +namespace strata::kernels { + +// y[o] = sum_i fp16(x[i]) * W[i][o], with W in S2 canonical planes. +// `codes` is n_out * (n_in/64) * 16 bytes, `scales` n_out * (n_in/64) floats, `x` n_in uint16 fp16 patterns, +// `y` n_out floats. All device pointers. n_in must be a multiple of 64. +void s2_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/s2_gemv_q8.hpp b/engine/strata/include/strata/kernels/s2_gemv_q8.hpp new file mode 100644 index 00000000..9c7beb97 --- /dev/null +++ b/engine/strata/include/strata/kernels/s2_gemv_q8.hpp @@ -0,0 +1,22 @@ +// include/strata/kernels/s2_gemv_q8.hpp - the S2 GEMV over Q8_0-QUANTIZED activations. +// +// `ggml_mul_mat` converts src1 to the weight's `vec_dot_type`, which for Q2_0 is Q8_0. The other CUDA kernels +// here take FP16 activations, and the CPU expert path already quantizes to int8 - so this is the missing GPU +// half of the same rule, and without it the two paths disagree on the same token. +// +// CORRECTNESS VERSION: the activation is dequantized inside the loop. The speed win here is `__dp4a` (four +// int8 MACs per instruction) and belongs to Phase 3, once the numerics are settled. +#pragma once + +#include + +namespace strata::kernels { + +// `act` (n_in/32) ggml Q8_0 blocks, 34 bytes each, as `quantize_q8_0` produces +// `codes` n_out * (n_in/4) bytes, one 2-bit code byte per quad +// `scales` n_out * (n_in/64) +// `y` n_out floats +void s2_gemv_q8(const uint8_t* act, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/s_gemv.hpp b/engine/strata/include/strata/kernels/s_gemv.hpp new file mode 100644 index 00000000..340df04e --- /dev/null +++ b/engine/strata/include/strata/kernels/s_gemv.hpp @@ -0,0 +1,133 @@ +// include/strata/kernels/s_gemv.hpp - the S-family GEMV, host-callable (P2.S2). +// +// ONE kernel for S2, S4 and S8, because `docs/pack-format.md` gives them ONE decode: +// +// value = cb[code] * scale + offset +// +// with a per-TYPE codebook, code bias, group size and offset presence. That uniformity is the point of the +// canonical form - 13 source types collapse to three code widths and a handful of attributes - so the kernel +// takes those attributes as ARGUMENTS rather than being specialised per source type. The manifest already +// carries them per tensor (round 163 added the tests that keep it honest). +#pragma once + +#include + +namespace strata::kernels { + +// Which table turns a code into a number. `Affine` is `code + bias`; `Iq4Nl` is the non-linear +// `kvalues_iq4nl`, which no bias can express - the reason the canonical form carries a codebook at all. +enum class Codebook : int { Affine = 0, Iq4Nl = 1 }; + +struct SForm { + int code_bits = 2; // 2, 4 or 8 + int code_bias = -1; // subtracted from the code IN THE INTEGER DOMAIN before the multiply + int group_elems = 64; // elements per scale (and per offset, when present) + Codebook codebook = Codebook::Affine; + bool has_offset = false; // only the K-quants with a min (Q4_K, Q5_K) have one + + /// WHICH ACTIVATION THIS WEIGHT'S `vec_dot_type` IS: 0 = Q8_0, 1 = Q8_K. + /// + /// **IT IS AN ATTRIBUTE OF THE CANONICAL FORM AND IT CANNOT BE DERIVED FROM THE OTHERS.** Q5_0 and Q5_K + /// are both 8-bit with bias -16 (only `has_offset` differs); IQ4_NL and IQ4_XS are both 4-bit with the + /// IQ4NL codebook and no offset, and differ in NOTHING this struct otherwise holds. So it is CARRIED from + /// the manifest's `source_type` rather than reconstructed - see `docs/activation-contract.md` and the + /// `act_kind` column `tools/pack_index.py` writes. + int act_kind = 0; +}; + +// y[o] = sum_i fp16(x[i]) * W[i][o]. GGUF's ne[0] varies fastest, so a tensor is [n_in, n_out] with n_in +// CONTIGUOUS: row o is a contiguous run of n_in/group_elems groups. +// +// `codes` n_out * (n_in / (8/code_bits)) bytes +// `scales` n_out * (n_in / group_elems) floats +// `offset` the same count as scales, or nullptr when `has_offset` is false +// `y` n_out floats +void s_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, float* y, + int64_t n_in, int64_t n_out, const SForm& form); + +// The same computation with the ROW SPLIT ACROSS THREADS: one block of `threads_per_row` threads per output +// row, each accumulating a strided subset, reduced through shared memory. +// +// WHY BOTH EXIST. `s_gemv` gives one thread per output row, so its parallelism is the OUTPUT WIDTH - and the +// expert gate/up shape is [2560 x 640], which is 640 threads over 48 SMs, 13 per SM. Measured, that +// orientation ran 4.6x slower than [640 x 2560] with identical weights (Memory/LEDGER.md L1). This variant +// makes the parallelism independent of the output width. +// +// It is NOT bit-identical to `s_gemv`: the partial sums are added in a different order, so the parity test +// carries a tolerance for exactly this reason. Both are kept and both are tested, because the naive one is +// the reference the split one is checked against. +void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row); + +// S2 ONLY, with the code load amortised over four consecutive elements (they share one byte) and the +// activation load over four halves (one 64-bit word). S2 is 31.64 GiB of the 38 GiB pack, so it is the kernel +// whose instruction count matters. No `offset` - S2 has none, and a parameter that is always null is a +// parameter that will eventually be passed by mistake. +void s2_gemv_quads(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row); + +// S2 with two further instruction reductions: `x` staged in SHARED memory once per block instead of re-read +// from global by every output row, and the code unpack replaced by a 256-entry constant-memory table of +// float4 (one broadcast load per four elements instead of shifts, masks and an int-to-float convert). +// `stage_x` selects the staging so the two can be measured against each other rather than assumed. +void s2_gemv_fast(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row, bool stage_x); + +// The same computation as `s_gemv_split` but launched on `stream` (a cudaStream_t passed as void*, so this +// header stays free of CUDA types) and WITHOUT synchronising. It exists because the architecture's premise - +// that the expert stream overlaps with the compute that consumes it - cannot be measured through an entry +// point that waits for every stream. The synchronous ones remain the default; this is for the loop that has +// to overlap, and for the test that establishes whether overlapping is worth building. +void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row, + void* stream); + +/// THE SAME GEMV OVER **Q8_K** ACTIVATIONS, which is the contract for every K-quant and IQ-quant weight. +/// +/// `docs/activation-contract.md` settles this: `ggml_mul_mat` converts the activation to the weight's +/// `vec_dot_type`, and for Q3_K/Q4_K/Q5_K/Q6_K/IQ4_XS that type is Q8_K - NOT fp16. The two differ by +/// 0.6-0.9% per GEMV against a 1e-3 tolerance, and the K-quants are 2.89 GiB of the dense weights: the +/// attention projections and `ssm_out`, i.e. the numerically sensitive ones. +/// +/// `x` is the block_q8_K layout, 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`. +/// `bsums` is NOT read here - it exists for ggml's AVX2 path - but the STRIDE includes it, so a buffer +/// produced by `quantize_q8_K` can be passed straight in. +/// +/// The activation is dequantized on the fly (`d * qs[i]`), one multiply per element, exactly as the fp16 path +/// does one `__half2float` per element. The weight decode is the SAME code as `s_gemv` - one implementation, +/// because a second decode of the canonical form is a second thing to get wrong. +void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); + +/// The row-split form, for output widths too small to fill the machine. +/// +/// **THERE IS NO `threads_per_row` HERE, AND THAT IS A FIX RATHER THAN AN OVERSIGHT.** The parameter used to be +/// in this signature and the implementation threw it away - `(void) threads_per_row; // informational` - so a +/// caller reading the declaration reasonably believed it was tunable, and round 224 spent a whole sweep +/// measuring it and concluding from the flat result that the kernel was instruction-bound. The sweep could not +/// have shown anything else: **it was measuring a knob that is not connected.** +/// +/// This form is WARP per output row, which is what the shape wants, and the parameter is gone from the +/// interface so that no one can believe otherwise. `s_gemv_split`/`s_gemv_split_async` DO take threads_per_row +/// and DO use it, if a caller wants to tune that shape. +void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); + +/// THE SAME, OVER A **Q8_0** ACTIVATION - `block_q8_0`, 34 bytes per 32 elements, from `quantize_q8_0`. +/// +/// **THIS IS THE KERNEL THAT WAS MISSING, AND ITS ABSENCE WAS DESCRIBED INCORRECTLY FOR SEVERAL ROUNDS.** The +/// legacy block formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0, not Q8_K. Every one of them +/// in this pack except `ffn_down_shexp` is `Q2_0`, whose attributes happen to BE S2's (2 bits, group 64, +/// bias -1) - so `s2_gemv_q8`, which hardcodes those, covered them by coincidence. `ffn_down_shexp` is +/// IQ4_NL/Q4_0/Q5_0/Q8_0 in every layer with **group 32 and bias -16/0/-8**, and its `n_in` is **640**. +/// +/// 640 is a multiple of 32 and NOT of 256, so **Q8_K is structurally impossible for it rather than merely +/// unimplemented** - which is what the "Q8_K is not implemented" note in `shared_expert.hpp` was really +/// pointing at. +/// +/// `n_in` must be a multiple of 32. `group_elems` must be a power of two and a multiple of four, the same two +/// requirements `s_gemv_q8k_split` has and for the same reasons. +void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/sampler.hpp b/engine/strata/include/strata/kernels/sampler.hpp new file mode 100644 index 00000000..bdf9f56f --- /dev/null +++ b/engine/strata/include/strata/kernels/sampler.hpp @@ -0,0 +1,81 @@ +// include/strata/kernels/sampler.hpp - the sampler chain, host-callable (P2.S2). +// +// penalties -> top_k -> top_p -> min_p -> temperature -> pick +// +// llama.cpp's default chain (issue #53): ONE penalties stage, first, and temperature AFTER the truncation filters; +// top_p cuts before min_p. `src/kernels/cuda/sampler.cu` has the details and `sampler_parity` pins them. +#pragma once + +#include +#include +#include + +namespace strata::kernels { + +struct SamplerParams { + int top_k = 20; // sampled path: 1..64 as given; 0 (off) or more than 64 keep the widest list, 64 + float top_p = 0.95f; // 1.0 disables the filter + float min_p = 0.0f; // 0 disables; keeps tokens with p >= min_p * p_max (a prefix of the top_k list) + float temperature = 1.0f; // <= 0 means greedy + int min_keep = 1; // top_p keeps at least this many + int penalty_last_n = 0; // 0 disables; the window over `history` to count occurrences in + float penalty_repeat = 1.0f; + float penalty_freq = 0.0f; + float penalty_present = 0.0f; + uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index) + uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls + bool greedy = false; +}; + +// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`. +// +// **`logits` AND `out` ARE DEVICE POINTERS.** This is a CUDA kernel launch, not a host function, and nothing +// in the parameter names or the types says so - `const float* logits` reads exactly like a host buffer. +// Measured: passing host memory for `logits` faults inside the kernel with an ILLEGAL MEMORY ACCESS that is +// reported by whatever synchronising call happens NEXT, which will be somewhere else entirely and will name a +// buffer that has nothing to do with it. A sticky async fault does not know where it came from. +// +// `history` is (n_tokens, history_len) int32 - ONE ROW PER TOKEN ROW, at a stride of `history_len` - the most +// recent tokens that row's pick follows, with any unused slots set to -1; only the last `p.penalty_last_n` of +// each row are counted, and ids outside [0, n_vocab) are ignored. Pass nullptr and 0 when no penalties apply. +// A verify window's rows need DIFFERENT histories: row t follows the window's drafts 1..t (`penalty_rows`). +void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, + const SamplerParams& p, int* out, void* stream); + +// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers +// throughout; every per-request / per-round value comes from device memory, so the calls can be captured. +// +// The scratch `coupled_draft_sample` needs for `nv` logits (0: too wide for the split merge, coupled cannot run). +size_t coupled_draft_scratch_bytes(int nv); +// A round's inputs: `*params` <- `*mapped_params`, ring[cap - h, cap) <- mapped_hist[cap - h, cap) with h = +// coupled_hist_len(penalty_last_n, cap). `mapped_*` are mapped host memory. +void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params, + int32_t* ring, int cap, void* stream); +// Draft j of the chain from ONE row of `nv` logits (modified in place: the penalties): the target's chain with +// `*params`, the penalty window ring[cap + j - h, cap + j), Philox counter coupled_draft_counter(step_rec[0]). +// `sub_to_id` / `id_to_sub` map the draft head's subset to token ids and back (null: the whole vocabulary, +// `id_vocab` ids). Writes the token id to *out_id, its probability under the final distribution to *out_prob, and +// the id to ring[cap + j]. +void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab, + const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec, + void* scratch, int32_t* out_id, float* out_prob, void* stream); + +// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h` +// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots. +// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the +// drafts: row t is exactly the history plain decode counts when it picks the token after `window[t]`, so drafting +// cannot change which tokens are penalised. Row 0 alone is the single row the engine staged before 0.1.19. +inline void penalty_rows(const int32_t* tail, int64_t n_tail, const int32_t* window, int T, int h, int32_t* out) { + for (int t = 0; t < T; ++t) { + int32_t* row = out + (size_t) t * (size_t) h; + const int64_t avail = n_tail + t + 1; // tail + window[0..t] + const int take = (int) std::min(h, avail); + std::fill(row, row + (h - take), -1); + for (int j = 0; j < take; ++j) { + const int64_t i = avail - take + j; // index into (tail, window) + row[h - take + j] = i < n_tail ? tail[i] : window[i - n_tail]; + } + } +} + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/shared_expert.hpp b/engine/strata/include/strata/kernels/shared_expert.hpp new file mode 100644 index 00000000..8909ed9e --- /dev/null +++ b/engine/strata/include/strata/kernels/shared_expert.hpp @@ -0,0 +1,101 @@ +// include/strata/kernels/shared_expert.hpp - the shared expert, host-callable (P2.S2). +// +// h = silu(x @ gate_shexp.T) * (x @ up_shexp.T) <- SILU ON GATE +// h = h @ down_shexp.T +// g = sigmoid(x @ gate_inp_shexp) one SCALAR per token +// return h * g[:, None] +// +// The result is ADDED to the routed output, not weighted against it. Shape note: `n_ff` for the shared expert +// matches the routed experts' width (640) in this artifact. +// +// The SForm arguments describe canonical planes for the three expert projections and their historical +// CPU-derived activation images (Q8_0 or Q8_K). The default scalar gate separately consumes BF16 activations. +// The opt-in native BF16 gate instead consumes the original F32 activation and uses the pinned CUDA MMVF +// contract. Optional native projection weights select the pinned CUDA Q8_1 MMVQ contract independently. +#pragma once + +#include + +#include "strata/kernels/s_gemv.hpp" + +namespace strata::kernels { + +/// Opt in to pinned CUDA BF16/F32 MMVF and FP32 sigmoid for the shared scalar gate (default false). +/// Configure before session capture; captured graphs retain their selected kernels. +/// In this mode shared_expert requires its optional unrounded x_f32 input. +void shared_expert_set_native_bf16(bool enabled); + +/// Optional native GGUF projections. Each supported type with nonnull data +/// replaces only that canonical projection; absent or unsupported entries fall +/// back independently. Any active entry selects pinned FP32 SwiGLU arithmetic. +/// Caller owns device weights and Q8_1 scratch for the largest active input +/// (n_embd for gate/up, n_ff for down), sized by native_q8_1_bytes. All storage +/// must survive graph execution; use one ordered nonnull stream with no overlap. +struct NativeSharedWeights { + int gate_type = -1, up_type = -1, down_type = -1; + const void* gate_data = nullptr; + const void* up_data = nullptr; + const void* down_data = nullptr; + void* q8_1 = nullptr; +}; + +/// Bytes of caller-owned scratch `shared_expert` needs. **THE KERNEL USED TO `cudaMalloc` FOUR BUFFERS ON +/// EVERY CALL**, which is two separate violations in one line: `cudaMalloc` is ILLEGAL INSIDE A CAPTURE +/// (`cudaErrorStreamCaptureUnsupported`), so the MoE - and therefore the whole per-layer graph - could not be +/// captured at all; and P2.T10 requires ZERO token-path allocations, which this was. Neither is visible in a +/// test that only checks the output, and the capture test found it in one run. +uint64_t shared_expert_scratch_bytes(int64_t n_ff); + +/// `x_q8_0` and `x_q8k` are the TWO QUANTIZED IMAGES of the same activation, and which one a projection uses is +/// decided per weight by its `SForm::act_kind`. There is no fp16 activation here any more. +/// +/// **THE fp16 PATH WAS A REAL ERROR AND IT WAS DESCRIBED WRONG FOR SEVERAL ROUNDS.** This header used to say +/// the weights "are Q3_K / IQ4_XS / Q5_0 whose `vec_dot_type` is Q8_K, which is not implemented". In fact +/// `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0/Q2_0 in every layer - **no K-quant at all** - so its contract is +/// Q8_0; and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is structurally impossible for it**. +/// The gate/up weights are Q2_0 on 21 and 13 layers (Q8_0 again) and K-quants on the rest. +/// +/// x_f32 is required for the native BF16 gate or native gate/up projections. +/// Native down reads the unrounded F32 SwiGLU intermediate directly. No allocation occurs. +/// +/// Measured cost of the wrong choice: 0.66-1.41% per GEMV. `s_gemv_q8_0_split` was written for the Q8_0 half +/// (LEDGER L55) and `s2_gemv_q8` already served the Q2_0 half. +void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* x_bf16, const SForm& gate_form, + const uint8_t* gate_codes, const float* gate_scales, const float* gate_off, + const SForm& up_form, const uint8_t* up_codes, const float* up_scales, const float* up_off, + const SForm& down_form, const uint8_t* down_codes, const float* down_scales, + const float* down_off, const uint16_t* gate_inp_bf16, float* scratch, float* out, + int64_t n_embd, int64_t n_ff, int tpr, void* stream, const float* x_f32 = nullptr, + const NativeSharedWeights* native = nullptr); + +/// Plan v0.3 P6: the shared expert for `n_tok` <= 8 tokens (a verify window) with all three projections native: +/// multi-column MMVQ, so the weights are read once; every token is bitwise `shared_expert` on that token. +/// `x` (n_tok, n_embd) f32, `x_bf16` the same rounded (only read when the native BF16 gate is off), `gate`/`up` +/// (n_tok, n_ff) scratch, `g` n_tok floats, `out` (n_tok, n_embd). `nw.q8_1` must hold n_tok columns of n_embd. +void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, + const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, + int64_t n_ff, void* stream); + +/// The MoE block's final combination, `ref/moe.py::moe` L156: +/// +/// y = sum over the k routed experts of w[k] * parts[k] + shared +/// +/// `parts` is (k, n_embd) contiguous - one row per SELECTED expert, in the router's own order - and `shared` +/// may be null for a layer with no shared expert. +/// +/// TWO THINGS A READER GETS WRONG HERE, and they are why this is not inlined at the call site: +/// +/// * The ROUTED outputs are router-WEIGHTED; the SHARED output is ADDED PLAIN. `ref/moe.py` L116 says so +/// outright - "router-weighted, not renormalised against it" - and weighting the shared term too is a +/// one-line change that produces a plausible number. +/// * The weights come from `router_top10` ALREADY renormalised (they sum to 1 over the selected experts). +/// Normalising again here would be a second, different normalisation, and it is invisible whenever the +/// router's weights happen to sum near 1 anyway. +/// +/// One thread per output element, k accumulations each; k is 10 at the real geometry. This is where the CPU +/// expert pool's outputs are summed: `ExpertPool` carries a `weight` per job and deliberately does NOT apply +/// it, because the sum has to happen once over all k and not once per worker. +void moe_combine(const float* parts, const float* weights, const float* shared, float* y, int64_t n_embd, + int64_t k, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/kernels/verify_kernels.hpp b/engine/strata/include/strata/kernels/verify_kernels.hpp new file mode 100644 index 00000000..50d951a6 --- /dev/null +++ b/engine/strata/include/strata/kernels/verify_kernels.hpp @@ -0,0 +1,98 @@ +// include/strata/kernels/verify_kernels.hpp - plan v0.3 P6: kernels for the speculative VERIFY window, where T +// tokens (the last accepted token and T-1 drafts) go through a layer at once. +// +// The GDN recurrence is the one piece of state that cannot simply be overwritten by the next window, so its +// kernels come in two halves: +// +// * the verify half reads the conv history and the recurrent state, runs all T tokens in order (bitwise the +// single-token kernels' arithmetic per token) and writes ONLY the per-token outputs - the state is left +// untouched; +// * the commit half, launched once acceptance is known, replays the first `n_keep` tokens from the inputs the +// verify half stored and writes the state. Rejected tokens therefore never touch the state and there is no +// snapshot of the 113 MB recurrent state to keep. +// +// Everything that varies per window (token ids, `n_keep`) is read from DEVICE memory so the kernels can be captured. +#pragma once + +#include + +namespace strata::kernels { + +inline constexpr int kVerifyMaxT = 8; + +/// For token t of T: conv over [history(3) | qkv_0 .. qkv_t] -> SiLU -> L2 norm of the q/k heads -> h[t]. +/// `history` is NOT written. Bitwise `fused_gdn_conv_l2` per token. +void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, + int qk_heads, float eps, int n_tok, void* stream, int t_begin = 0); +/// history <- the last 3 entries of [history | qkv_0 .. qkv_{n-1}], n = *n_keep (0 leaves it as it was). +void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream); +/// alpha/beta for T columns of x (T, n_embd): gate (T, h_v), beta (T, h_v). Bitwise `fused_gdn_ab` per column. +void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a, + float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream); +/// The recurrence + output norm for T tokens (h = (T, conv_channels) as q|k|v, gate/beta (T, h_v), z/y +/// (T, value_dim)). With `n_keep == nullptr` the state is read and NOT written (verify); otherwise the first +/// *n_keep tokens are run and the state is written (commit; `y` may be scratch). Bitwise `fused_gdn_step_norm`. +void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, + const int32_t* n_keep, void* stream, int t_out_begin = 0); +/// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be +/// outstanding at once (the split verify window keeps two). +void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream); +/// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). +void gpu_stamp(unsigned long long* buf, int i, void* stream); + +// ---- perf-review E-6: a layer whose routed experts are all in VRAM needs nothing from the host +/// One group's plan, built on the device when every routed expert of its n*k entries is resident: the host pool's +/// layout (counts | start | dst | tok | pad | ptr | ptr2 | start2, `capx` entries) and order (distinct experts in +/// routing order, their entries ascending), no PCIe groups. *skip = ring when it did, else 0. +void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, + const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, + long long capx, uint32_t* skip, uint32_t ring, void* stream); +/// wait_flag_ge that also returns when *skip == value (device memory). +void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream); +/// copy_i32_from_mapped unless *skip == value. +void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value, + void* stream); +/// copy_from_mapped, or zeros when *skip == value (n a multiple of 4, 16-byte aligned). +void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value, + void* stream); + +/// Rows of the S2/S4/S8 embedding for T token ids read from DEVICE memory; out (T, n). Bitwise `embedding_gather`. +void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens, + int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes, + uint64_t row_groups, float* out, void* stream); +/// R[t][c][:] = x[t][:] for the hc streams. +void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream); +/// dst[:n] = src[(*index) * stride + :n] (index read from device memory; a negative index copies nothing). +void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream); + +/// Plan v0.3 P6: copy *n (device memory) blobs of `blob_bytes` from mapped host memory (src[k], device aliases) +/// into dst + k * blob_bytes with coalesced 16-byte loads - the PCIe share of a layer's missed experts, staged +/// into VRAM before the grouped expert kernel reads them. Launched for a capacity of `cap` blobs. +void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream); +/// ptr[k] = base + k * blob_bytes for k < *n (the staged copies `fetch_blobs` made). +void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream); + +// ---- the MTP draft layer (src/core/mtp.cpp) +/// R[t][c][:] = h[t][c][:] + e[t][:] (the embedding branch added to every stream). +void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream); +/// Every routed expert is resident (slot = expert id): slot[i] = ids[i], dst[i] = i, *count = n. +void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream); +/// The draft chain's next input: R_dst[:] = R_src[row], tok_dst[0] = ids[row], out[j] = ids[row], with +/// row = *row_dev (device memory). `out` may be mapped host memory. +void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, + int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs = nullptr, + float* out_p = nullptr); +/// dst row i = src row ids[i] (row_bytes each, multiple of 16), for n rows. +void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream); +/// ids[t] = table[ids[t]] for n entries (a subset index back to a token id). +void map_ids(int32_t* ids, const int32_t* table, int n, void* stream); +/// probs[t] = softmax(logits[t])[ids[t]] for n_rows rows of n_vocab (the probability of each row's argmax). +void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream); +/// Dense-attention step records for `n` cells: [cell, cell+1, (cell+1)/4, cell+1] from cells[i] (device memory). +void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream); +/// A sliding attention window: for `n` step records (kStepCount ints each, n_kv at [1]) the selection becomes the +/// last `window` cells: ids[q * ids_stride + j] = max(0, n_kv - window) + j and the record's width = the count. +void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream); + +} // namespace strata::kernels diff --git a/engine/strata/include/strata/ngram/ple_reader.hpp b/engine/strata/include/strata/ngram/ple_reader.hpp new file mode 100644 index 00000000..2884817e --- /dev/null +++ b/engine/strata/include/strata/ngram/ple_reader.hpp @@ -0,0 +1,100 @@ +// include/strata/ngram/ple_reader.hpp - plan v0.3 P2: the n-gram table read straight from the SSD. +// +// The table is 320,001,536 rows of 90 bytes (IQ4_NL, 26.8 GiB) or 160 (FP8 E4M3, 51.2 GB) and is never held in RAM: every row comes from an +// unbuffered 4 KiB read (platform::DirectFile). A token needs 16 rows on 16 different pages, and all 16 depend +// on the token itself, so the only time to hide them is the embedding plus layer 0. Hence the split API: +// +// Ticket t = reader.issue(rows, n, out_raw); // as soon as the token id is known +// ... // embedding, layer 0 +// reader.collect(t); // before layer 1 reads the rows +// +// `issue` also serves prefill: pass all 16 x N rows of a chunk; pages are deduplicated, sorted by offset and +// kept at most `max_inflight` deep, so a chunk's reads can run while the previous chunk computes. +// +// THE ROW CACHE IS NOT THE TABLE. It keeps rows this process has already fetched (90 bytes each, bounded, +// clock eviction). Measured on the frozen corpus (bench/results/2026-09-23-ngram-io): 1M rows (~95 MB) +// would serve up to ~82% of reads; within one long prompt 20-34% of rows recur. Capacity 0 disables it. +#pragma once + +#include "strata/platform/direct_file.hpp" + +#include +#include +#include + +namespace strata::ngram { + +inline constexpr uint32_t ROW_BYTES = 90; ///< an IQ4_NL row; `open` takes the table's own size +inline constexpr uint32_t PAGE = 4096; + +struct ReaderStats { + uint64_t requests = 0; ///< rows asked for + uint64_t cache_hits = 0; ///< rows served from the row cache + uint64_t dedup_rows = 0; ///< rows that shared a page already being read in the same ticket + uint64_t reads = 0; ///< SSD read requests issued + uint64_t bytes = 0; ///< bytes read from the SSD + double wait_us = 0; ///< time `collect` spent blocked + double submit_us = 0; ///< time spent inside the read submission call (non-zero = it blocks) + double read_us_sum = 0; ///< sum of per-read latencies (issue to completion) + uint64_t late_injected = 0; ///< reads delayed by fault injection + uint64_t keepalive_reads = 0; ///< pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies) + double keepalive_us_max = 0; ///< the slowest of them + std::vector read_us; ///< last <= 65,536 read latencies, for percentiles + double percentile(double q) const; +}; + +class PleReader { +public: + struct Ticket { + uint32_t id = 0; + }; + + PleReader(); + ~PleReader(); + PleReader(const PleReader&) = delete; + PleReader& operator=(const PleReader&) = delete; + + /// `table_offset` is the byte offset of row 0 in the file and `n_rows` the row count; both come from a + /// validated GGUF parse (PleTable::open checks the table exactly fills the file from there). + /// `io_thread` (default): a worker thread submits and reaps reads, so `issue` costs the caller no ReadFile + /// calls. false: the caller's thread does it (A/B arm). + /// `row_bytes`: one row's size in the file (90 IQ4_NL, 160 FP8), at most one page. + bool open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, + uint64_t cache_rows, std::string& err, bool io_thread = true, uint32_t row_bytes = ROW_BYTES); + uint32_t row_bytes() const; + void close(); + bool is_open() const; + + /// Start fetching `n` rows; row i's raw bytes land at `out_raw + row_bytes * i`. `out_raw` must stay valid + /// until `collect` returns. Out-of-range rows produce zero bytes (the mmap path's behaviour). + Ticket issue(const uint32_t* rows, size_t n, uint8_t* out_raw); + + /// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`). + bool collect(Ticket t, std::string& err); + + /// Keep the SSD awake while the table is in use (io_thread mode only; call after `open`): when no read has + /// gone out for `period_ms`, the worker reads one page of the table, until `window_s` after the last `issue`. + /// Some SSDs drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms + /// (a WD_BLACK SN7100 on Windows 11; the NVMe idle timeouts of the power plan did not change it), which in + /// decode happens after a few rounds whose rows all came from the row cache. 0 turns it off (the reader's + /// default; generate turns it on, see STRATA_SSD_KEEPALIVE). A keep-alive read that fails turns it off. + void set_keepalive(double period_ms, double window_s); + + /// Fault injection for tests and for the plan's P2 exit check: every read completes no earlier than + /// `delay_us` after it was issued. 0 disables. + void set_injected_delay_us(double delay_us); + + /// Read with no ticket in flight (the worker updates these while reads are outstanding; with the keep-alive + /// on it may also be counting a keep-alive read - `snapshot` takes a consistent copy). + const ReaderStats& stats() const; + ReaderStats snapshot() const; + void reset_stats(); + uint64_t cache_capacity() const; + uint64_t cache_size() const; + +private: + struct Impl; + Impl* impl_ = nullptr; +}; + +} // namespace strata::ngram diff --git a/engine/strata/include/strata/plan/plan.hpp b/engine/strata/include/strata/plan/plan.hpp new file mode 100644 index 00000000..b974f1f5 --- /dev/null +++ b/engine/strata/include/strata/plan/plan.hpp @@ -0,0 +1,168 @@ +// include/strata/plan/plan.hpp - P1.S9 census + memory planner. +// +// This is the component that makes one binary adapt to the GPU it is running on. The engine has 33.97 GB of +// expert weights (has to live in DRAM and be streamed) and a fixed VRAM budget that has to hold the dense +// weights, the KV cache, the indexer keys, the recurrent state and as many expert-cache slots as remain. +// Every one of those competes, so the plan is an arithmetic result rather than a configuration choice, and +// it must REFUSE rather than silently overcommit. +// +// DERIVATION POLICY. `phases/00-README.md` §2 gives three rows of expected values but no formula, so the +// arithmetic here is derived from the model's geometry and the table is used as a CHECK. Where the two +// disagree the geometry wins and the disagreement is reported - a table transcribed by hand is not a +// specification, and fitting formulas to it would hide exactly the errors this is supposed to catch. +#pragma once + +#include +#include +#include +#include + +namespace strata::plan { + +// ---- model geometry (the real Qwen3.8-Flash-Next artifact) ------------------ +struct Geometry { + int n_layers = 48; + int n_qsa_layers = 12; // layers 3, 7, ... 47 - the full-attention ones + int n_kv_heads = 2; + int head_dim = 256; + int kv_group = 64; // INT8 KV is grouped-64: one fp16 scale per 64 elements + int qsa_block = 4; // the indexer pools one key per 4-token block + /// THE INDEXER'S KEY STORE, and the trap that has now been walked into twice in opposite directions. + /// + /// `indexer.q_proj.weight` is [2560, 512] = **4 QUERY heads** of 128. `indexer.k_proj.weight` is + /// [2560, 128] = **ONE shared KEY head**. The queries are not cached; only the key is. So the cache + /// holds one 128-wide key per TOKEN, pooled to one per `qsa_block`-token block - which + /// `include/strata/kernels/qsa.hpp` states directly: `pooled (max_cells/idx_block + 1, idx_dim)`, and + /// its own note that the fp32 store is "50 MiB at 32K" (12 layers x 8192 blocks x 128 x 4 B = 48 MiB). + /// + /// original indexer_heads(1) * head_dim(256) / 4 = 64 B/token/layer 2x too big + /// round 194 indexer_heads(4) * key_dim(128) / 4 = 128 B/token/layer 4x too big + /// correct key_heads(1) * key_dim(128) / 4 = 32 B/token/layer + /// + /// Round 194 "fixed" this by reading `indexer.head_count = 4` out of the metadata and multiplying by it - + /// right about the metadata, wrong about what was being counted. **A head count in the metadata does not + /// say WHICH tensor it counts.** + int indexer_q_heads = 4; // query heads: they multiply the SCORES, and cost no cache at all + int indexer_key_heads = 1; // k_proj is [n_embd, 128]: ONE shared key head + int indexer_key_dim = 128; // the key width, and the width of the thing that IS cached + + /// GDN geometry. `docs/semantics.md`: `ssm.state_size = 128`, `ssm.time_step_rank = 48` (the v heads), + /// `ssm.conv_kernel = 4`, and `n_embd_r() = (d_conv-1) * (ssm_d_inner + 2*n_group*d_state) = 3 * 10240`. + int ssm_state_size = 128; + int ssm_v_heads = 48; + int ssm_d_conv = 4; + int ssm_conv_channels = 10240; + + /// 36 of the 48 layers are GDN; the rest are QSA. Declared as a derivation rather than a third constant, + /// because a `n_gdn_layers = 36` alongside `n_layers` and `n_qsa_layers` is a third thing to keep in step. + int n_gdn_layers() const { return n_layers - n_qsa_layers; } +}; + +// ---- byte costs ------------------------------------------------------------ +struct Costs { + uint64_t expert_blob = 1382400; // one expert's gate_up+down, codes and scales (architecture §3.2) + uint64_t dense_bytes = 0; // from the manifest: every non-expert tensor, canonical form + uint64_t embd_bytes = 0; // token embedding + uint64_t mtp_bytes = 0; // multi-token-prediction head, when present + uint64_t workspace_bytes = 0; + uint64_t state_bytes = 0; // GDN recurrence + conv history + replay log, per sequence +}; + +// GDN recurrence + conv history, bytes per sequence. DERIVED, for the same reason everything else here is. +// +// This term was MISSING from the plan until round 198: `Costs::state_bytes` exists and `--state` exists, but +// nothing passed it, so the planner was fed zero and quietly planned without it. 36 GDN layers of fp32 state +// is **117.7 MB, or 85 expert cache slots** - not a rounding error. +// +// recurrence (S, h_v, S) fp32 = 128 * 48 * 128 * 4 = 3,145,728 B per layer +// conv history (d_conv-1, C) fp32 = 3 * 10240 * 4 = 122,880 B per layer +// +// It is a FIXED cost and not a cache: it is state, it is resident for the life of a sequence, and it cannot be +// evicted to make room for an expert. A planner that omits it returns a plan it cannot honour, which is the +// failure `DoesNotClose` exists to prevent. +inline uint64_t state_bytes(const Geometry& g) { + const uint64_t per_layer = (uint64_t) g.ssm_state_size * (uint64_t) g.ssm_v_heads * + (uint64_t) g.ssm_state_size * sizeof(float) + + (uint64_t) (g.ssm_d_conv - 1) * (uint64_t) g.ssm_conv_channels * sizeof(float); + return (uint64_t) g.n_gdn_layers() * per_layer; +} + +// INT8 KV + indexer keys, bytes per token. Both terms come from the geometry above and nothing else. +inline uint64_t kv_bytes_per_token(const Geometry& g) { + const uint64_t kv_elems = 2ull * g.n_kv_heads * g.head_dim; // K and V + const uint64_t kv_scales = (kv_elems / (uint64_t)g.kv_group) * 2; // fp16 scale per group + const uint64_t per_layer = kv_elems * 1 + kv_scales; // INT8: one byte per element + // indexer: ONE cached key per block, `idx_dim` wide, SHARED across the query heads. See the note on + // `indexer_key_heads` above - this term has been wrong in both directions and the derivation is why. + const uint64_t idx_layer = + (uint64_t) g.indexer_key_heads * (uint64_t) g.indexer_key_dim / (uint64_t) g.qsa_block; + return (uint64_t)g.n_qsa_layers * (per_layer + idx_layer); +} + +// ---- the plan -------------------------------------------------------------- +struct Plan { + uint64_t max_context = 0; + uint64_t kv_bytes = 0; // KV + indexer keys at max_context + uint64_t state_bytes = 0; // GDN recurrence + conv history - FIXED, not evictable + uint64_t cache_bytes = 0; // what is left for expert cache slots + uint64_t cache_slots = 0; + uint64_t vram_budget = 0; + uint64_t vram_used = 0; + uint64_t dram_experts = 0; // the whole expert arena, streamed + std::vector notes; +}; + +// Thrown when the requested context and the fixed costs cannot both fit. A planner that returns a plan it +// cannot honour is worse than one that fails, because the failure then happens at token 4000 instead of at +// startup. +struct DoesNotClose : std::runtime_error { + explicit DoesNotClose(const std::string& w) : std::runtime_error(w) {} +}; + +// The VRAM budget that the KV cache and the expert cache share. This is the one number taken from +// `00-README.md` §2 rather than derived: the table's three rows all leave `KV + cache` constant, and that +// constant is what the planner is dividing. Expressed in bytes, decimal, matching how the table rounds. +inline uint64_t vram_pool_bytes() { + return 5943000000ull; +} + +inline Plan make_plan(uint64_t max_context, const Geometry& g, const Costs& c, + uint64_t pool = vram_pool_bytes()) { + Plan p; + p.max_context = max_context; + p.vram_budget = pool; + p.kv_bytes = kv_bytes_per_token(g) * max_context; + p.state_bytes = c.state_bytes; + p.dram_experts = c.dense_bytes + c.embd_bytes; // costs that never enter the pool + + const uint64_t fixed = c.dense_bytes + c.embd_bytes + c.mtp_bytes + c.workspace_bytes + c.state_bytes; + if (p.kv_bytes + fixed > pool) { + throw DoesNotClose("max-context " + std::to_string(max_context) + " needs " + + std::to_string(p.kv_bytes + fixed) + " B of the " + std::to_string(pool) + + " B VRAM pool; reduce --max-context"); + } + p.cache_bytes = pool - p.kv_bytes - fixed; + p.cache_slots = p.cache_bytes / c.expert_blob; + p.vram_used = pool - p.cache_bytes % c.expert_blob; // slot remainder is unusable, not free + if (p.cache_slots == 0) { + throw DoesNotClose("no room for even one expert cache slot at max-context " + + std::to_string(max_context)); + } + return p; +} + +inline std::string to_string(const Plan& p) { + auto gb = [](uint64_t b) { return std::to_string(b / 1e9); }; + std::string s; + s += "memory plan --max-context " + std::to_string(p.max_context) + "\n"; + s += " KV + indexer keys " + gb(p.kv_bytes) + " GB\n"; + s += " recurrent state " + gb(p.state_bytes) + " GB (GDN recurrence + conv history, NOT evictable)\n"; + s += " expert cache " + gb(p.cache_bytes) + " GB (" + std::to_string(p.cache_slots) + + " slots of 1,382,400 B)\n"; + s += " VRAM pool " + gb(p.vram_budget) + " GB\n"; + s += " expert arena (DRAM) " + gb(p.dram_experts) + " GB\n"; + for (const std::string& n : p.notes) s += " note: " + n + "\n"; + return s; +} + +} // namespace strata::plan diff --git a/engine/strata/include/strata/platform/direct_file.hpp b/engine/strata/include/strata/platform/direct_file.hpp new file mode 100644 index 00000000..c59eb910 --- /dev/null +++ b/engine/strata/include/strata/platform/direct_file.hpp @@ -0,0 +1,60 @@ +// include/strata/platform/direct_file.hpp - plan v0.3 P1/P2: unbuffered asynchronous file reads. +// +// The n-gram table (26.8 GiB) stays on the SSD and must never occupy RAM, including the OS file cache. A memory +// map cannot promise that; an unbuffered read can. On Windows this is FILE_FLAG_NO_BUFFERING | OVERLAPPED with +// an I/O completion port; on Linux, O_DIRECT preads. Both issue the reads from a small thread pool (submit only +// queues), so many reads are in flight: STRATA_IO_THREADS sets its size (default 4 on Windows, 16 on Linux). +// +// Contract of every read: offset, length and buffer address are multiples of `alignment()` (4096 here). +// Reads past end of file return the bytes that exist; `Completion::bytes` says how many. +#pragma once + +#include +#include + +namespace strata::platform { + +struct Completion { + uint64_t tag = 0; ///< the caller's tag from `submit` + uint32_t bytes = 0; ///< bytes transferred (short only at end of file) + bool ok = false; +}; + +class DirectFile { +public: + DirectFile(); + ~DirectFile(); + DirectFile(const DirectFile&) = delete; + DirectFile& operator=(const DirectFile&) = delete; + + bool open(const std::string& path, std::string& err); + void close(); + bool is_open() const; + uint64_t size() const; + static constexpr uint32_t alignment() { return 4096; } + + /// Queue one read. Returns false (and sets `err`) if the request could not be queued; a queued request + /// always produces exactly one completion. + bool submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err); + + /// Wait for up to `max` completions; returns how many were written to `out`. `timeout_ms` < 0 waits + /// forever; 0 polls. A `wake()` shows up as one completion with tag `WAKE_TAG`. + int wait(Completion* out, int max, int timeout_ms); + + /// Make a thread blocked in `wait` return (thread-safe). Used to hand it newly queued work. + static constexpr uint64_t WAKE_TAG = ~0ull; + void wake(); + + /// Allocation helpers for aligned read buffers (page-aligned, never touched by the cache manager). + static void* alloc_aligned(size_t bytes); + static void free_aligned(void* p); + +private: + struct Impl; + Impl* impl_ = nullptr; +}; + +/// Monotonic time in microseconds, for latency accounting. +double now_us(); + +} // namespace strata::platform diff --git a/engine/strata/include/strata/platform/memory.hpp b/engine/strata/include/strata/platform/memory.hpp new file mode 100644 index 00000000..ece6c9e4 --- /dev/null +++ b/engine/strata/include/strata/platform/memory.hpp @@ -0,0 +1,35 @@ +// include/strata/platform/memory.hpp - plan v0.3 P0.1/P1: keep a large host region resident. +// +// `cudaHostRegister` refuses the 31.6 GiB expert arena on Windows, and an unlocked arena is trimmed under memory +// pressure (the CPU pool then swung 2x between runs). With the n-gram table out of RAM there is headroom to lock +// it instead: raise the process's minimum working set by the region's size, then VirtualLock it (Windows needs +// only SeIncreaseWorkingSetPrivilege, which ordinary accounts hold). Linux: mlock. +#pragma once + +#include +#include + +namespace strata::platform { + +struct LockResult { + bool ok = false; + uint64_t locked_bytes = 0; ///< may be less than requested; the rest stays pageable + std::string note; ///< what was done or why it failed, for the startup print +}; + +/// Lock [p, p + bytes) into physical memory. Partial success is reported, not hidden. +LockResult lock_resident(void* p, uint64_t bytes); + +/// Undo lock_resident for the same region (best effort). +void unlock_resident(void* p, uint64_t bytes); + +/// #243, Windows: the GPU's shared (non-local) memory budget and this process's use of it, from DXGI +/// (IDXGIAdapter3::QueryVideoMemoryInfo, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) for the adapter whose LUID is the +/// 8 bytes at `luid` (cudaDeviceProp::luid). Page-locked host memory the GPU maps is charged there. False (and +/// `why` says so) when the query is not possible - always elsewhere than Windows. +bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why); + +/// The machine's physical RAM in bytes (0 when unknown). +uint64_t total_physical_memory(); + +} // namespace strata::platform diff --git a/engine/strata/include/strata/prefill/gemm.hpp b/engine/strata/include/strata/prefill/gemm.hpp new file mode 100644 index 00000000..c9ddc6f4 --- /dev/null +++ b/engine/strata/include/strata/prefill/gemm.hpp @@ -0,0 +1,59 @@ +// include/strata/prefill/gemm.hpp - plan v0.3 P5: the batched projections of prompt processing. +// +// Every projection of a chunk of T tokens is Y[T, N] = X[T, K] . W[N, K]^T with W row-major (the GGUF / pack layout) +// and FP32 outputs. Weights are BF16 on the device - either already (the pack's BF16 tensors) or dequantized from +// their native GGUF blocks into a reusable scratch (`dequant_bf16`) right before the product - and activations are +// rounded to BF16, which is also what llama.cpp's batched CUDA path does. Tensor-core GEMM through cuBLAS. +#pragma once + +#include +#include +#include + +namespace strata::prefill { + +class Gemm { +public: + Gemm() = default; + ~Gemm(); + Gemm(const Gemm&) = delete; + Gemm& operator=(const Gemm&) = delete; + + /// `scratch_elems`: BF16 elements of the dequantization scratch (the largest weight dequantized at once). + bool init(void* stream, int64_t scratch_elems, std::string& err); + /// The same with caller-owned device buffers (the prompt path borrowing expert-cache slots). + bool init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes, + std::string& err); + + /// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds. + void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, + float beta = 0.0f); + + /// Y = X . W^T with both in FP16 (bits). + void f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0, + float beta = 0.0f); + + /// W given as native GGUF blocks of `ggml_type`, dequantized to FP16 in the scratch, X in FP16. + void native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, + int64_t ldy = 0, float beta = 0.0f); + + /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). + void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); + + uint16_t* scratch() const { return scratch_; } + int64_t scratch_elems() const { return scratch_elems_; } + void* stream() const { return stream_; } + +private: + void* handle_ = nullptr; + void* stream_ = nullptr; + uint16_t* scratch_ = nullptr; + int64_t scratch_elems_ = 0; + void* workspace_ = nullptr; + bool external_ = false; + void* hipblaslt_state_ = nullptr; +}; + + + +} // namespace strata::prefill diff --git a/engine/strata/include/strata/prefill/kernels.hpp b/engine/strata/include/strata/prefill/kernels.hpp new file mode 100644 index 00000000..8f6145bf --- /dev/null +++ b/engine/strata/include/strata/prefill/kernels.hpp @@ -0,0 +1,97 @@ +// include/strata/prefill/kernels.hpp - plan v0.3 P5: the element-wise and stateful kernels of a prompt chunk. +// +// T tokens at a time, all row-major with the token as the slow index. The arithmetic mirrors the per-token native +// kernels (the decode path), batched; where a step is a recurrence in time (the GDN conv and state, the PLE conv) +// the kernel walks the chunk's tokens in order inside one launch. +#pragma once + +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/rope_scaling.hpp" + +#include + +namespace strata::prefill { + +// ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320) +/// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image. +/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x. +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); +/// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R. +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo = nullptr); +/// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits). +void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, + int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); +/// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as +/// the two calls, without reading R back. +void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr); +/// lo16[t, k] = bf16(silu(lo[t, k] / hc)) +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr); +/// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null). +void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, + uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr); +/// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld) +void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream); +/// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast). +void gr_broadcast(const float* e, float* R, int64_t T, void* stream); + +// ---- GDN (state 128, 16 k heads, 48 v heads, 10240 conv channels, 4 taps) +/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, 48 + h]) (ab: [T, 96]) +void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream); +/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then +/// the L2 norm of the q and k heads of every token. h: [T, C]. +void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream); +/// The recurrence over the chunk, block per value head, state in registers; y[t] = rmsnorm(o) * gamma * sigmoid(z) +/// (FP32 and FP16 bits: the out projection is quantized). +void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream); + +// ---- MoE +/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router). +void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream); +/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640]. +void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); +/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up) +void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream); +/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640) +void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream); +/// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits +/// behind the copy engine's queue (the prompt path's grouping tables, while the expert stream fills it). +void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream); +/// Gather rows: dst16[i, :] = x16[src[i], :] (n rows of `width` BF16). +void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream); +/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :] +void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, + int64_t T, void* stream); + +// ---- QSA helpers +/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`). +void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream); +/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope +/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly. +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream); +/// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256] +void split_q(const float* q_full, float* q, int64_t T, void* stream); +/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream); + +/// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16 +/// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic. +/// K, V: [T, 2, 256]. +void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host = nullptr, + const strata::kernels::KvHostPools* stage = nullptr); + +/// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs). +void to_f16(const float* x, uint16_t* y, int64_t n, void* stream); +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr); +/// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment) +void round_f16(const float* x, float* y, int64_t n, void* stream); +/// Expert blob -> FP16 (Q2_0 values are exact in FP16). +void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream); + +} // namespace strata::prefill diff --git a/engine/strata/include/strata/prefill/moe_mmq.hpp b/engine/strata/include/strata/prefill/moe_mmq.hpp new file mode 100644 index 00000000..d9f0eba6 --- /dev/null +++ b/engine/strata/include/strata/prefill/moe_mmq.hpp @@ -0,0 +1,78 @@ +// include/strata/prefill/moe_mmq.hpp - prompt-speed plan step 2b: the prompt path's experts through llama.cpp's MMQ +// kernels (ggml-cuda mmq.cuh, MIT): the weights stay quantized and the activations are rounded to q8_1, the +// products run on int8 tensor cores. The dequantize-to-FP16 + cuBLAS path wrote ~10 MB of FP16 per expert and +// multiplied in FP16; this reads the ~1.4-2 MB expert once. A group of experts is gathered into one buffer +// (`gather_*`, one launch per expert as its blob arrives) and multiplied in one launch per product. +#pragma once + +#include +#include + +namespace strata::prefill::mmq { + +/// This build has the MMQ path (the ggml sources were available to the build). +bool built(); +/// MMQ covers this ggml type (the i-quants and Q2_0 the packs use, Q8_0, and in a CUDA build with STRATA_MMQ_KQUANTS +/// the Q4_K / Q5_K / Q5_1 of Unsloth's UD-Q4_K_XL; IQ1_M is not covered). +bool supported(int ggml_type); +/// #420: `supported`, and on every visible GPU llama.cpp's MMQ has a tile for this type and a weight matrix of +/// `w_rows` rows that fits the card's shared memory - the same test its tile choice makes, which aborts the process +/// ("J_best=0") when nothing fits. false (said once per type) keeps that product on the non-MMQ path. +bool fits(int ggml_type, int64_t w_rows); +/// Bytes of one expert's gate+up ([2*n_ff, n_embd]) or down ([n_embd, n_ff]) weights in `ggml_type`. +size_t matrix_bytes(int ggml_type, int64_t rows, int64_t cols); +/// Bytes of `rows` activation rows of `cols` values quantized for MMQ (the row padded to 512 values). +size_t q8_bytes(int64_t rows, int64_t cols); + +/// q8_1 activations for MMQ against weights of `ggml_type`: row i of the output is row ids[i] of x (or row i when +/// ids is null); `x` has `ld` floats per row. +void quantize(const float* x, const int32_t* ids, void* xq, int ggml_type, int64_t cols, int64_t ld, int64_t rows, + void* stream); + +/// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows +/// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into +/// dst rows of the same indices (`ld_dst` floats apart, via `ids`: dst row = ids[row], an identity table works). +/// `total_rows`: the rows of xq; `max_rows`: the most rows one expert has (the launch grid). +struct Product { + const void* w = nullptr; + int type = -1; + int64_t w_rows = 0, w_cols = 0; + size_t expert_bytes = 0; + int n = 0; + const void* xq = nullptr; + const int32_t* bounds = nullptr; + const int32_t* ids = nullptr; + int64_t total_rows = 0, max_rows = 0; + float* dst = nullptr; + int64_t ld_dst = 0; +}; + +/// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path. +class Context { +public: + Context(); + ~Context(); + Context(const Context&) = delete; + Context& operator=(const Context&) = delete; + void run(const Product& p, void* stream); + +private: + void* ctx_ = nullptr; +}; + +/// A GGUF-native expert (gate at `gate`, up at `up`, down at `down`, each its GGUF rows) into a group buffer's +/// slot: gate rows then up rows at `gu_dst`, down at `d_dst`. +void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, + void* gu_dst, void* d_dst, void* stream); +/// A Strata-pack Q2_0 expert blob (codes and fp16 scales in separate planes, gate/up rows interleaved) into GGUF +/// Q2_0 blocks: gate/up [1280, 2560] at `gu_dst` (rows stay interleaved), down [2560, 640] at `d_dst`. Same values. +void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream); + +/// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split +/// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats). +void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream); + +/// dst[i] = i for i < n (the identity row map MMQ's MoE mode writes through). +void iota(int32_t* dst, int64_t n, void* stream); + +} // namespace strata::prefill::mmq diff --git a/engine/strata/include/strata/prefill/prefill.hpp b/engine/strata/include/strata/prefill/prefill.hpp new file mode 100644 index 00000000..da225d3b --- /dev/null +++ b/engine/strata/include/strata/prefill/prefill.hpp @@ -0,0 +1,127 @@ +// include/strata/prefill/prefill.hpp - plan v0.3 P5: batched prompt processing. +// +// The prompt's positions [pos0, pos0 + n) are processed in chunks of `chunk` tokens through all 48 layers, leaving +// the session state (GDN recurrence and conv state, QSA KV pools and indexer, PLE history) where the token path +// would have left it; the decode loop then continues with the next token. Per layer: the projections are +// tensor-core GEMMs (quantized weights dequantized to FP16 on the fly, BF16 weights as they are), the recurrences +// walk the chunk inside one kernel, and the routed experts are grouped by expert: resident ones are read from the +// VRAM tier, the others streamed from the host arena through a pinned ring on a copy stream. +// +// Requires the native weights (`--native`): every quantized projection must carry its GGUF blocks. +#pragma once + +#include "strata/core/expert_cache.hpp" +#include "strata/core/expert_source.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/session.hpp" +#include "strata/core/weights.hpp" + +#include +#include +#include +#include + +namespace strata::prefill { + +struct PrefillStats { + int64_t tokens = 0; + int64_t chunks = 0; + double ms_total = 0; + double ms_experts_host = 0; ///< host time staging non-resident experts + int64_t experts_streamed = 0; ///< expert blobs copied host -> device + int64_t experts_dma = 0; ///< ...of which straight from the pinned arena (no CPU copy) + int64_t experts_resident = 0; ///< expert-layer groups served from the VRAM tier + double ms_ple = 0; +}; + +} // namespace strata::prefill +namespace strata::core { class MtpDrafter; } +namespace strata::prefill { + +class Prefill { +public: + /// E-9: the draft layer's K/V for prompt cells [cell0, cell0 + n) from their final residual rows `R_rows` + /// (device) and `next_tokens` (host: the token at cell+1), in batches through this path's GEMMs and its idle + /// scratch - call it from on_chunk. false with `err` empty: not applicable here (a ring or hybrid K/V, another + /// device, too little scratch; STRATA_MTP_BATCH=0), the caller runs the drafter's own pass. Not bit-identical to + /// that pass (FP16 GEMMs instead of Q8_1 activations): the drafts may differ, never the target's tokens' logits. + bool draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, + std::string& err); + Prefill(); + ~Prefill(); + Prefill(const Prefill&) = delete; + Prefill& operator=(const Prefill&) = delete; + + /// Frees every buffer, stream and event `init` made (as the destructor does) and starts over empty, so `init` can + /// run again - with a smaller chunk when the first one did not fit. The stage range (`set_stage`) and the + /// callbacks stay. The device `init` ran on must be current. + void reset(); + + /// `host_res`: the static residency table (n_layers x n_expert, slot or -1) or null; `cache` its slots. + /// `borrow`/`borrow_bytes`: device memory to carve every buffer from (the top slots of the expert cache, + /// lent for the prompt and refilled after it); null = allocate normally. + bool init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, + core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, + void* stream, std::string& err, void* borrow = nullptr, uint64_t borrow_bytes = 0); + + /// With borrowed buffers: lay them out again for chunks of `chunk` tokens (at most `init`'s) in `borrow` - a + /// request lends only the slots its prompt needs. The stream must be idle (between prompts). + bool relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err); + int64_t chunk() const; + + /// The share of the streamed experts' bytes DMA-able straight from pinned RAM (1 = all). Sizes the streamed + /// ring (a big one only pays when the copy engine, not the host copies, is the limit); set before bytes_needed. + static void set_pinned_share(double share); + static double pinned_share(); + /// #340: the streamed ring's slot count for chunks that stream every expert, instead of the pinned-share rule + /// (0 = that rule). Set before any `bytes_needed`/`init` (both count the ring); STRATA_PREFILL_RING still wins. + static void set_ring_override(int slots); + + /// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). + static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk); + + /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest + /// first, -1 for none) and is advanced to the last two of these. + bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); + + const PrefillStats& stats() const { return stats_; } + + /// Plan v0.3 P6: called after every chunk with the chunk's final multi-stream residual rows (device, + /// T x hc*n_embd, valid until the next chunk) and the chunk's first position; the MTP draft layer builds its + /// K/V from them. The prefill stream is synchronized before the call. + std::function on_chunk; + + /// Layer split: called by every stage when it has read a chunk, with the position reached, while its own state + /// is still at that chunk's end (its stream synchronized; the last stage calls it just before `on_chunk`). An + /// earlier stage is a chunk or more ahead of the last one by the time `on_chunk` runs, so this is where a + /// mid-prompt checkpoint takes each stage's part. Runs on that stage's thread, with its device current. + std::function on_stage_chunk; + + /// Checked before every chunk: true stops the prompt early (`run` returns false with err "cancelled"). + std::function should_stop; + + /// The vision path: HOST rows (n_embd floats) indexed by absolute position, read in place of the token + /// embedding where non-null (an image's <|image_pad|> cells). Null (default): every position embeds its token. + const float* const* embd_rows = nullptr; + + /// LAYER SPLIT (multi-GPU): this prompt path runs layers [layer_begin, layer_end) (-1: to the last) on the + /// device `init` runs on. A stage that does not start at layer 0 reads each chunk's residual rows from the + /// previous stage instead of embedding the tokens; a stage that does not end at the last layer copies its rows + /// to pinned host buffers (two, allocated by `init`) and runs `next` on them - on a thread, so the next stage + /// reads chunk c while this one reads chunk c + 1. `on_chunk` belongs on the last stage. Set before `init`. + void set_stage(int64_t layer_begin, int64_t layer_end, Prefill* next) { + stage_lb_ = layer_begin; stage_le_ = layer_end; next_ = next; + } + +private: + int64_t stage_lb_ = 0, stage_le_ = -1; + Prefill* next_ = nullptr; + const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) + bool carve(std::size_t T, void* alloc); // the device buffers of a chunk (prefill.cpp's Alloc) + void release(); // the destructor's cleanup (also `reset`'s) + struct Impl; + std::unique_ptr impl_; + PrefillStats stats_; +}; + +} // namespace strata::prefill diff --git a/engine/strata/include/strata/program/conv_cache.hpp b/engine/strata/include/strata/program/conv_cache.hpp new file mode 100644 index 00000000..7fe4bfa7 --- /dev/null +++ b/engine/strata/include/strata/program/conv_cache.hpp @@ -0,0 +1,43 @@ +// include/strata/program/conv_cache.hpp - the conversation cache's retention policy: which checkpoint +// leaves when the cache is over its slot budget. +// +// The cache holds conversation checkpoints: snapshots of the running state (the GDN recurrence, the PLE +// history, the QSA indexer tails - `ConvCheckpoint` in generate.cpp) that a request resumes its prompt +// from instead of reading those tokens again. The request path keeps only the checkpoints whose tokens +// are a prefix of the current prompt - any other checkpoint's positional cells have been overwritten, +// because the KV cache is one arena that holds one branch of history at a time - so at any moment the +// retained checkpoints are a CHAIN: sorted by length, each a prefix of the next. That is a radix cache's +// tree collapsed onto the one branch of history the session can hold. +// +// The chain's root is therefore the deepest point every request so far has shared - in practice the end +// of the system prompt, which every new chat of the same client mounts through - and it is exactly the +// node a radix cache keeps alive while its leaves rotate. First-in-first-out kept it only by accident of +// being first: after `prompt_cache` newer checkpoints it was gone, and the next chat read the whole +// prefix again at prefill speed. So: +// +// * the root is PINNED: dropping it frees one slot's ~118 MB and costs every future conversation that +// shares the prefix a full re-read of it (a 30K system prompt is ~30 s at ~1,000 tok/s); +// * every other slot rotates by least recent use. A checkpoint's stamp advances when it is created, +// when a new checkpoint lands on its length, and when a request mounts through it. +// +// With a budget below two slots there is no room to keep root and leaf apart, so the pin switches off and +// the oldest checkpoint leaves - the previous behaviour, one slot = the newest point only. +#pragma once + +#include +#include + +namespace strata::program::conv_cache { + +/// The index in `stamps` of the chain item to drop once the chain holds more than `cap` items. `stamps` +/// are the items' last-use stamps; the caller owns the chain and erases the returned index. Pure and +/// deterministic so conv_cache_test.cpp can walk the scenarios by hand. +inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap) { + if (cap < 2 || n < 2) return 0; // no room for root and leaf: the pin is off, the oldest leaves + size_t v = 1; // the root (0) is pinned; least recent use among the rest + for (size_t i = 2; i < n; ++i) + if (stamps[i] < stamps[v]) v = i; + return v; +} + +} // namespace strata::program::conv_cache diff --git a/engine/strata/include/strata/program/logits_selection.hpp b/engine/strata/include/strata/program/logits_selection.hpp new file mode 100644 index 00000000..04462a82 --- /dev/null +++ b/engine/strata/include/strata/program/logits_selection.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include +#include + +namespace strata::program::logits_selection { + +// Storage selection only: callers must still condition on every input token. +// Positive decimal int64, with no sign, whitespace, suffix or overflow. +inline bool parse_stride(std::string_view text, int64_t& result) { + if (text.empty() || text.front() < '0' || text.front() > '9') return false; + int64_t value = 0; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || value <= 0) return false; + result = value; + return true; +} + +// Zero-based multiples of stride, followed by the final input position once. +inline constexpr bool selected(int64_t position, int64_t total, int64_t stride) { + return total > 0 && stride > 0 && position >= 0 && position < total && + (position % stride == 0 || position == total - 1); +} + +inline constexpr int64_t row_count(int64_t total, int64_t stride) { + return total > 0 && stride > 0 ? (total - 1) / stride + 1 + ((total - 1) % stride != 0) : 0; +} + +} // namespace strata::program::logits_selection diff --git a/engine/strata/include/strata/spec/controller.hpp b/engine/strata/include/strata/spec/controller.hpp new file mode 100644 index 00000000..4864ce93 --- /dev/null +++ b/engine/strata/include/strata/spec/controller.hpp @@ -0,0 +1,73 @@ +// include/strata/spec/controller.hpp - plan v0.3 P6: which drafter, and how many draft tokens, this step. +// +// Each step the controller maximizes E[tokens committed] / T(step) over the choices +// none (k = 0) | suffix lookup with k <= its proposal | MTP with k <= K_MAX +// using running estimates of per-position acceptance and a cost model of a (k+1)-token verify pass. It keeps +// k = 0 unless the best choice beats plain decoding by `min_gain` (plan: 5%). +// +// Acceptance: for MTP, position i's conditional acceptance p_i (EMA). For lookup, one conditional acceptance per +// match-length bucket (a long match is far more reliable than a trigram), also an EMA. `observe` updates them +// from how many drafted tokens the verify pass accepted. +// +// Cost: T(n tokens) = dense(n) + experts(n) + sync + draft. The defaults are the 23 Sep measurements: +// dense ratio per token count from native MMVQ (bench/results/2026-09-23-mmvq-multi), distinct experts per window +// from the routing trace (2026-09-23-spec-economics), extra-token CPU cost 0.2-0.35 (2026-09-23-cpu-expert-multi). +// Replace them with in-engine measurements through `CostModel`. +#pragma once + +#include +#include + +namespace strata::spec { + +inline constexpr int K_MAX = 8; + +struct CostModel { + double dense_ms = 11.0; // one-token dense pass (plan P3 target) + std::array dense_ratio{1.0, 1.05, 1.3, 1.45, 1.85, 2.2, 2.6, 3.0, 3.3}; // by n = k+1 (index n-1) + double cpu_all_miss_ms = 15.8; // 480 experts on the CPU + double hit_rate = 0.55; // share of distinct experts served from VRAM + std::array distinct_ratio{1.0, 1.70, 2.31, 2.88, 3.40, 3.89, 4.35, 4.80, 5.2}; // U(n)/U(1) + double extra_use_cost = 0.25; // each extra token on an expert, fraction of a read + double sync_ms = 2.4; + double mtp_draft_ms = 1.2; // per MTP draft token + double lookup_draft_ms = 0.01; + + /// Step time for verifying n = k + 1 tokens, plus drafting k tokens with the given source. + double step_ms(int k, bool mtp) const; +}; + +enum class Source { None, Lookup, Mtp }; + +struct Choice { + Source source = Source::None; + int k = 0; + double expected_tokens = 1.0; + double tokens_per_ms = 0.0; +}; + +class Controller { +public: + explicit Controller(CostModel cost = {}, double min_gain = 0.05, double ema = 0.05); + + /// `lookup_available` tokens the suffix drafter can propose now, from a match of `lookup_match` tokens. + Choice choose(int lookup_available, int lookup_match, bool mtp_ready) const; + + /// After verification: `accepted` of the `k` drafted tokens matched (a prefix). + void observe(const Choice& c, int accepted, int lookup_match); + + double mtp_accept(int position) const { return mtp_p_[position]; } // position 0 = first draft token + double lookup_accept(int match) const { return lookup_q_[bucket(match)]; } + const CostModel& cost() const { return cost_; } + +private: + static int bucket(int match) { return match >= 16 ? 3 : match >= 8 ? 2 : match >= 5 ? 1 : 0; } + static double expected(const double* p, int k, bool conditional_same); + + CostModel cost_; + double min_gain_, ema_; + std::array mtp_p_{}; + std::array lookup_q_{}; +}; + +} // namespace strata::spec diff --git a/engine/strata/include/strata/spec/draft_policy.hpp b/engine/strata/include/strata/spec/draft_policy.hpp new file mode 100644 index 00000000..c77b8696 --- /dev/null +++ b/engine/strata/include/strata/spec/draft_policy.hpp @@ -0,0 +1,52 @@ +// include/strata/spec/draft_policy.hpp - per verify round: the MTP's window, or a lookup (suffix) window? +// +// The suffix drafter (prompt lookup) proposes the tokens that followed an earlier repeat of the context. Taken +// whenever it proposes more than the MTP, it lost 2-8% on ordinary text: a long lookup window costs much more to +// verify than the MTP's usual 3-4 tokens, and it is only worth that when enough of it is accepted. llama.cpp's +// lookup decoding answers the same problem with confidence thresholds on its n-gram statistics; here the policy +// learns both sides online and compares expected committed tokens per millisecond: +// +// MTP E = the mean tokens a window of that size has committed (EMA), at the measured cost of that size +// lookup E(k) = 1 + q + q^2 + ... + q^k for k <= the proposal, q = the acceptance rate of lookup drafts whose +// match was about as long (4 buckets of match length, decayed counts), at the measured cost of k + 1 +// +// and takes the lookup window only when its best E/cost beats the MTP's by `margin`. Costs are the measured round +// times per window size (EMA; sizes not seen yet are scaled from seen ones by a prior shape), so the policy adapts +// to the machine and the context length. It only chooses which drafts to verify: the output is unchanged. +#pragma once + +#include + +namespace strata::spec { + +class DraftPolicy { +public: + static constexpr int kMaxT = 8; + static constexpr int kBuckets = 4; + + explicit DraftPolicy(int max_t, double margin = 0.03); + + struct Pick { + bool lookup = false; + int t = 1; // window size (1 + drafts) + }; + /// `t_mtp`: the MTP's window; `lookup_k`: the lookup proposal's length (0 = none); `match`: its match length. + Pick choose(int t_mtp, int lookup_k, int match) const; + /// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft). + void observe(bool lookup, int t, int accepted, int match, double round_ms); + + double lookup_rate(int match) const; // current q for a match length + double cost_ms(int t) const; // measured or scaled round time of a window of t tokens + +private: + static int bucket(int match); + double mtp_tokens(int t) const; + + int max_t_; + double margin_; + std::array cost_{}, cost_n_{}; // round ms by window size + std::array mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size + std::array ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed +}; + +} // namespace strata::spec diff --git a/engine/strata/include/strata/spec/suffix_drafter.hpp b/engine/strata/include/strata/spec/suffix_drafter.hpp new file mode 100644 index 00000000..731bbef1 --- /dev/null +++ b/engine/strata/include/strata/spec/suffix_drafter.hpp @@ -0,0 +1,53 @@ +// include/strata/spec/suffix_drafter.hpp - plan v0.3 P6: the suffix-lookup drafter (no weights, no GPU). +// +// Proposes the tokens that followed the longest earlier occurrence of the sequence's current suffix: when the +// output quotes its input (edits, refactors, repeated code) the continuation is usually exact, and a verify pass +// accepts many tokens at once. It needs no model and costs microseconds. +// +// Index: every trigram of the history (prompt + accepted output) maps to its WAYS most recent end positions in a +// fixed-size open-addressing table, so memory is bounded (~20 bytes per history token) and appends are O(1). +// A proposal checks those candidates, extends each match backwards up to `max_match`, and takes the longest +// (most recent on ties). Matches shorter than `min_match` propose nothing. +#pragma once + +#include +#include +#include + +namespace strata::spec { + +class SuffixDrafter { +public: + static constexpr int WAYS = 4; + + explicit SuffixDrafter(int min_match = 3, int max_match = 32, size_t capacity_tokens = 1u << 19); + + void reset(); + /// Add tokens to the history (the prompt, then every accepted token). + void append(const int32_t* tokens, size_t n); + void append(int32_t token) { append(&token, 1); } + + /// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match). + int propose(int max_k, int32_t* out); + + /// Length of the match behind the last proposal (0 if none). + int last_match() const { return last_match_; } + size_t size() const { return hist_.size(); } + +private: + struct Slot { + uint64_t key = 0; // trigram hash + 1 (0 = empty) + uint32_t pos[WAYS] = {}; // end positions, most recent first + uint8_t n = 0; + }; + Slot* find_slot(uint64_t key, bool insert); + uint64_t key_at(size_t end) const; + + int min_match_, max_match_; + std::vector hist_; + std::vector table_; + size_t mask_ = 0; + int last_match_ = 0; +}; + +} // namespace strata::spec diff --git a/engine/strata/ref/load.py b/engine/strata/ref/load.py new file mode 100644 index 00000000..0e4575ac --- /dev/null +++ b/engine/strata/ref/load.py @@ -0,0 +1,212 @@ +"""ref/load.py - P1.S4: GGUF -> FP32 tensors on demand, with LAZY per-expert dequantization. + +The plan is explicit: "experts are dequantized lazily per (layer, expert) - do not materialize 120B +parameters". That is the whole design constraint here, and it is what `expert()` below exists for: the +routed-expert tensors are fused `[in, out, experts]`, and touching one expert must not touch the other +511. + +Dequantization itself is NOT reimplemented. `gguf-py` handles the twelve standard encodings and is +already the reference this project validates its C++ against; `Q2_0` (type 42) is the one gguf-py +cannot represent at all, so it is served by this project's own decoder. That split is deliberate: it +means a bug in `tools/gguf_writer.dequantize_q2_0` cannot hide behind gguf-py and vice versa. + + from ref.load import Gguf + g = Gguf("path.gguf") + w = g.tensor("blk.0.attn_gate.weight") # (out, in) fp32, whole tensor + e = g.expert("blk.0.ffn_gate_exps.weight", 7) # (out, in) fp32, ONE expert only +""" +from __future__ import annotations + +import pathlib +import re +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "tools")) +from gguf_reader import GGUFFile # noqa: E402 +from gguf_writer import dequantize_q2_0 # noqa: E402 + +# gguf-py names differ from our reader's names in a few places; map only what differs. +_GGUF_PY_NAME = {"Q4_0": "Q4_0", "Q8_0": "Q8_0", "Q4_K": "Q4_K", "Q5_K": "Q5_K", "Q6_K": "Q6_K", + "Q3_K": "Q3_K", "IQ4_NL": "IQ4_NL", "IQ4_XS": "IQ4_XS", "Q5_0": "Q5_0"} + +# (elements per block, bytes per block) - mirrors block_geometry() in src/artifact/gguf_reader.cpp +GEOM = {"F32": (1, 4), "F16": (1, 2), "BF16": (1, 2), + "Q4_0": (32, 18), "Q5_0": (32, 22), "Q8_0": (32, 34), "IQ4_NL": (32, 18), + "Q3_K": (256, 110), "Q4_K": (256, 144), "Q5_K": (256, 176), "Q6_K": (256, 210), + "IQ4_XS": (256, 136), "Q2_0": (64, 18)} + + +def _dequant_flat(type_name: str, raw: np.ndarray) -> np.ndarray: + """One dequantization dispatch, shared by tensor()/expert()/rows(). + + Q2_0 is this project's own decoder because gguf-py's enum cannot represent type 42 at all; + everything else goes through gguf-py, which is already the reference this project validates its + C++ against. Keeping one dispatch means a type added in one path cannot be forgotten in another. + """ + if type_name == "Q2_0": + return dequantize_q2_0(raw.tobytes()) + if type_name == "BF16": + return _bf16_to_f32(raw) + if type_name == "F32": + return raw.view(np.float32) + if type_name == "F16": + return raw.view(np.float16).astype(np.float32) + from gguf import quants, GGMLQuantizationType as Q + return quants.dequantize(raw, Q[_GGUF_PY_NAME[type_name]]).astype(np.float32) + + +def _bf16_to_f32(raw: np.ndarray) -> np.ndarray: + return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) + + +def _discover_shards(path) -> list[pathlib.Path]: + """Resolve a GGUF argument to its shard list. + + The real artifact is TWO files and the split is not incidental: shard 2 holds exactly one tensor, + `per_layer_token_embd.weight` (26.82 GiB). A reader that opens one file can therefore load the + whole model EXCEPT the PLE table and will not fail until a forward pass reaches layer 1 - so + shard discovery is not a convenience, it is a correctness requirement for the real model. + + Accepts a directory (all `*.gguf` in it), any single shard (siblings found by the + `-NNNNN-of-MMMMM` suffix), or an explicit list. + """ + if isinstance(path, (list, tuple)): + return [pathlib.Path(p) for p in path] + p = pathlib.Path(path) + if p.is_dir(): + # A directory is ambiguous in practice: the project root holds BOTH the model shards (in a + # subdirectory) and an unrelated `mmproj-*.gguf`. Globbing `*.gguf` there silently loaded + # the multimodal projector instead of the model. So prefer an explicit shard set, accept a + # single unambiguous file, and REFUSE to guess otherwise. + shards = sorted(p.glob("*-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9].gguf")) + if shards: + totals = {re.match(r"^.*-(\d{5})-of-(\d{5})\.gguf$", s.name).group(2) for s in shards} + if len(totals) != 1: + raise ValueError(f"{p}: shard files from more than one split: {sorted(totals)}") + return shards + found = sorted(p.glob("*.gguf")) + if len(found) == 1: + return found + if not found: + raise FileNotFoundError(f"no .gguf files in {p}") + raise ValueError( + f"{p}: {len(found)} .gguf files and none is a shard set, so which is the model is " + f"ambiguous: {[f.name for f in found]}. Pass one file explicitly.") + m = re.match(r"^(.*)-(\d{5})-of-(\d{5})\.gguf$", p.name) + if m: + stem, _, total = m.groups() + sibs = sorted(p.parent.glob(f"{stem}-*-of-{total}.gguf")) + if len(sibs) != int(total): + raise FileNotFoundError( + f"{p.name}: expected {total} shards, found {len(sibs)} in {p.parent}") + return sibs + return [p] + + +class Gguf: + """Read-only, demand-paged view of a (possibly multi-shard) GGUF. + + Nothing is dequantized until asked for. `g` is the FIRST shard's `GGUFFile`, so metadata and the + tensor directory are reachable as before; reads route to whichever shard owns the tensor. + """ + + def __init__(self, path): + self.paths = _discover_shards(path) + self.path = self.paths[0] + self.shards: list[tuple[GGUFFile, object]] = [] + self._by_name: dict[str, tuple[int, object]] = {} + for i, sp in enumerate(self.paths): + gf = GGUFFile(sp) + self.shards.append((gf, sp.open("rb"))) + for t in gf.tensors: + if t.name in self._by_name: + raise ValueError(f"{sp.name}: duplicate tensor {t.name} across shards") + self._by_name[t.name] = (i, t) + self.g = self.shards[0][0] # metadata / directory / alignment live in shard 1 + + # ---- raw bytes + def _raw(self, name: str, nbytes: int, byte_offset: int = 0) -> bytes: + i, t = self._by_name[name] + gf, fh = self.shards[i] + fh.seek(gf.data_start + t.offset + byte_offset) + return fh.read(nbytes) + + def info(self, name: str): + return self._by_name[name][1] + + def row_bytes(self, t) -> int: + el, by = GEOM[t.type_name] + return t.shape[0] // el * by + + # ---- full tensors + def tensor(self, name: str) -> np.ndarray: + """Dequantize a whole tensor to FP32, shape as GGUF order reversed to (out, in[, experts]).""" + t = self.info(name) + el, by = GEOM[t.type_name] + if t.elements % el: + raise ValueError(f"{name}: {t.elements} not a multiple of block {el}") + raw = np.frombuffer(self._raw(name, t.elements // el * by), dtype=np.uint8) + flat = _dequant_flat(t.type_name, raw) + # GGUF dim 0 varies fastest; numpy's last axis does, so reverse and transpose to (out, in). + return flat.reshape(tuple(reversed(t.shape))) + + # ---- the lazy row path + def rows(self, name: str, idx) -> np.ndarray: + """Gather specific ROWS of a 2-D tensor without decoding the rest of it. + + This exists for `per_layer_token_embd.weight`, which is `[160, 320001536]` IQ4_NL = **26.82 + GiB** - 43% of the artifact, the entire second shard - and is read 16 rows per token by one + layer (see round 98's finding). Calling `tensor()` on it would dequantize 320 million rows to + FP32, about 205 GB, to use 2.5 KB of them. + + A row is contiguous in GGUF (ne0 varies fastest), so one row is `row_bytes` at + `row * row_bytes`. The type's block size must divide the row width; for this table it does + (160 = 5 x 32 for IQ4_NL). + """ + t = self.info(name) + if len(t.shape) != 2: + raise ValueError(f"{name}: rows() needs a 2-D tensor, got shape {t.shape}") + el, by = GEOM[t.type_name] + width = t.shape[0] + if width % el: + raise ValueError(f"{name}: row width {width} is not a multiple of block {el}") + rb = self.row_bytes(t) + idx = np.asarray(idx, dtype=np.int64).ravel() + if idx.size and (idx.min() < 0 or idx.max() >= t.shape[1]): + raise ValueError(f"{name}: row index out of range (0..{t.shape[1] - 1})") + out = np.empty((idx.size, width), dtype=np.float32) + for k, r in enumerate(idx): + raw = np.frombuffer(self._raw(name, rb, int(r) * rb), dtype=np.uint8) + out[k] = _dequant_flat(t.type_name, raw) + return out + + # ---- the lazy path + def expert(self, name: str, expert_id: int) -> np.ndarray: + """One expert out of a fused `[in, out, experts]` tensor, WITHOUT touching the others. + + In GGUF order the expert index is the LAST axis, so expert e's matrix occupies a contiguous + run of `in*out` elements at offset e*in*out. Only that run is read and decoded - which is the + plan's "do not materialize 120B parameters" requirement, and the reason the engine can run at + all on a machine where the expert set is 34 GB. + """ + t = self.info(name) + if len(t.shape) != 3: + raise ValueError(f"{name}: not a fused expert tensor (shape {t.shape})") + in_f, out_f, n_exp = t.shape + if not 0 <= expert_id < n_exp: + raise ValueError(f"{name}: expert {expert_id} out of range (0..{n_exp - 1})") + el, by = GEOM[t.type_name] + per_expert = in_f * out_f + if per_expert % el: + raise ValueError(f"{name}: per-expert element count {per_expert} not a multiple of {el}") + # byte offset of expert e: whole experts before it, in blocks + start = expert_id * (per_expert // el) * by + raw = np.frombuffer(self._raw(name, per_expert // el * by, start), dtype=np.uint8) + flat = _dequant_flat(t.type_name, raw) + return flat.reshape((out_f, in_f)) + + def close(self) -> None: + for _, fh in self.shards: + fh.close() diff --git a/engine/strata/requirements.txt b/engine/strata/requirements.txt new file mode 100644 index 00000000..3db8418a --- /dev/null +++ b/engine/strata/requirements.txt @@ -0,0 +1,23 @@ +# The Python packages setup.py installs into .venv, pinned so a checkout installs the same ones on any day (#214). +# setup.py's pip step reads this file; an install from before it keeps the packages it has. +# Python 3.10+ (numpy's newest releases need a newer Python: one line per range). +numpy==2.5.3; python_version >= "3.12" +numpy==2.4.6; python_version == "3.11" +numpy==2.2.6; python_version < "3.11" +jinja2==3.1.6 +regex==2026.9.10 +pyyaml==6.0.3 +tqdm==4.70.1 +requests==2.34.2 +cmake==4.4.3 +ninja==1.13.2 +pillow==12.3.0 +psutil==7.2.2 + +# their dependencies +markupsafe==3.0.3 +certifi==2026.7.22 +charset-normalizer==3.5.1 +idna==3.20 +urllib3==2.8.0 +colorama==0.4.6; sys_platform == "win32" diff --git a/engine/strata/serve/__init__.py b/engine/strata/serve/__init__.py new file mode 100644 index 00000000..c3b0bdd9 --- /dev/null +++ b/engine/strata/serve/__init__.py @@ -0,0 +1 @@ +"""serve - plan v0.3 P8: the API layer (text in, token ids to the engine, text deltas out).""" diff --git a/engine/strata/serve/chat_golden.json b/engine/strata/serve/chat_golden.json new file mode 100644 index 00000000..652e3369 --- /dev/null +++ b/engine/strata/serve/chat_golden.json @@ -0,0 +1,197 @@ +[ + { + "name": "single user", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "system + user", + "messages": [ + { + "role": "system", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "What is 2+2?" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nWhat is 2+2?<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "multi-turn", + "messages": [ + { + "role": "system", + "content": "Be brief." + }, + { + "role": "user", + "content": "Hi" + }, + { + "role": "assistant", + "content": "Hello! How can I help?" + }, + { + "role": "user", + "content": "Explain BPE in one sentence." + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHello! How can I help?<|im_end|>\n<|im_start|>user\nExplain BPE in one sentence.<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\nBe brief.<|im_end|>\n<|im_start|>user\nHi<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHello! How can I help?<|im_end|>\n<|im_start|>user\nExplain BPE in one sentence.<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "assistant with thinking", + "messages": [ + { + "role": "user", + "content": "What is 17*23?" + }, + { + "role": "assistant", + "content": "Let me compute.", + "reasoning_content": "17*23 = 17*20 + 17*3 = 340+51 = 391" + }, + { + "role": "user", + "content": "Thanks" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nWhat is 17*23?<|im_end|>\n<|im_start|>assistant\n\n17*23 = 17*20 + 17*3 = 340+51 = 391\n\n\nLet me compute.<|im_end|>\n<|im_start|>user\nThanks<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nWhat is 17*23?<|im_end|>\n<|im_start|>assistant\n\n17*23 = 17*20 + 17*3 = 340+51 = 391\n\n\nLet me compute.<|im_end|>\n<|im_start|>user\nThanks<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "no generation prompt", + "messages": [ + { + "role": "user", + "content": "Hello" + }, + { + "role": "assistant", + "content": "Hi there" + } + ], + "add_generation_prompt": false, + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHi there<|im_end|>\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\nHi there<|im_end|>\n" + }, + { + "name": "thinking disabled", + "messages": [ + { + "role": "user", + "content": "Hello" + } + ], + "enable_thinking": false, + "rendered": "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + "error": null, + "hf": "<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + }, + { + "name": "unicode content", + "messages": [ + { + "role": "user", + "content": "你好,世界 😀" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n你好,世界 😀<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n你好,世界 😀<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "tool call and response", + "messages": [ + { + "role": "user", + "content": "Weather in Oslo?" + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "type": "function", + "function": { + "name": "get_weather", + "arguments": { + "city": "Oslo" + } + } + } + ] + }, + { + "role": "tool", + "content": "{\"temp\": 3}", + "name": "get_weather" + }, + { + "role": "user", + "content": "And in Bergen?" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the weather", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + } + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\n# Tools\n\nYou have access to the following functions:\n\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"Get the weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}}\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n<|im_end|>\n<|im_start|>user\nWeather in Oslo?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n\n\nOslo\n\n\n<|im_end|>\n<|im_start|>user\n\n{\"temp\": 3}\n<|im_end|>\n<|im_start|>user\nAnd in Bergen?<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.\n\n# Tools\n\nYou have access to the following functions:\n\n\n{\"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"description\": \"Get the weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\"}}, \"required\": [\"city\"]}}}\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n<|im_end|>\n<|im_start|>user\nWeather in Oslo?<|im_end|>\n<|im_start|>assistant\n\n\n\n\n\n\n\nOslo\n\n\n<|im_end|>\n<|im_start|>user\n\n{\"temp\": 3}\n<|im_end|>\n<|im_start|>user\nAnd in Bergen?<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "empty user", + "messages": [ + { + "role": "user", + "content": "" + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n\n" + }, + { + "name": "whitespace and newlines", + "messages": [ + { + "role": "user", + "content": " line1\n line2\n\n\nend " + } + ], + "rendered": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nline1\n line2\n\n\nend<|im_end|>\n<|im_start|>assistant\n\n", + "error": null, + "hf": "<|im_start|>system\nReasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.<|im_end|>\n<|im_start|>user\nline1\n line2\n\n\nend<|im_end|>\n<|im_start|>assistant\n\n" + } +] \ No newline at end of file diff --git a/engine/strata/serve/chat_template.jinja b/engine/strata/serve/chat_template.jinja new file mode 100644 index 00000000..a0877006 --- /dev/null +++ b/engine/strata/serve/chat_template.jinja @@ -0,0 +1,184 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- set sysns = namespace(count=0, text='') %} +{%- for message in messages %} + {%- if sysns.count == loop.index0 and (message.role == 'system' or message.role == 'developer') %} + {%- set sys_content = render_content(message.content, false, true)|trim %} + {%- if sys_content %} + {%- set sysns.text = sysns.text + ('\n' if sysns.text else '') + sys_content %} + {%- endif %} + {%- set sysns.count = sysns.count + 1 %} + {%- endif %} +{%- endfor %} +{%- set num_sys = sysns.count %} +{%- set merged_system = sysns.text %} +{%- set reasoning_instructions = '' %} +{%- if enable_thinking is undefined or enable_thinking is true %} + {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %} + {%- if resolved_reasoning_effort == 'high' %} + {%- set resolved_reasoning_effort = 'xhigh' %} + {%- endif %} + {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %} + {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }} + {%- endif %} + {%- if resolved_reasoning_effort == 'xhigh' %} + {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %} + {%- elif resolved_reasoning_effort == 'low' %} + {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %} + {%- endif %} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {%- if reasoning_instructions %} + {{- reasoning_instructions + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if merged_system %} + {{- '\n\n' + merged_system }} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if merged_system %} + {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + merged_system + '<|im_end|>\n' }} + {%- elif reasoning_instructions %} + {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if loop.index0 >= num_sys %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" or message.role == "developer" %} + {{- raise_exception('System message must be at the beginning.') }} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if tool_call.name is not defined or tool_call.name is none %} + {{- raise_exception('Tool call is missing a function name.') }} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is mapping %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- elif tool_call.arguments is string %} + {%- if tool_call.arguments|trim %} + {{- raise_exception('Tool call arguments for function "' + (tool_call.name | string) + '" were passed as a JSON string. Parse them into an object before calling apply_chat_template.') }} + {%- endif %} + {%- elif tool_call.arguments is defined and tool_call.arguments is not none %} + {{- raise_exception('Tool call arguments for function "' + (tool_call.name | string) + '" must be an object/mapping or a JSON string.') }} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} +{#- Unsloth fixes - developer role, merged system messages, tool calling #} \ No newline at end of file diff --git a/engine/strata/serve/frontend.py b/engine/strata/serve/frontend.py new file mode 100644 index 00000000..07e369d0 --- /dev/null +++ b/engine/strata/serve/frontend.py @@ -0,0 +1,579 @@ +"""serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine. + +Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module + + * normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form, + * renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face + does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools), + * parses the streamed output incrementally into reasoning (`...`), content and tool calls in + the template's XML form (`VALUE...`), + never emitting a partial tag to the client. + +Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja +and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port +(or a pybind wrapper) a local change. +""" +from __future__ import annotations + +import json +import uuid +from dataclasses import dataclass, field +from pathlib import Path + +import jinja2 +from jinja2.sandbox import ImmutableSandboxedEnvironment + + +# ------------------------------------------------------------------------------------------------ template +class TemplateRequestError(jinja2.exceptions.TemplateError, ValueError): + """The template refused the request's messages (e.g. "No user query found in messages."): a ValueError, so the + client gets a 400 with the template's message instead of a dropped connection (#365).""" + + +class ChatTemplate: + """The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template.""" + + def __init__(self, path: str | Path): + def raise_exception(message): + raise TemplateRequestError(message) + + def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False): + return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys) + + env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"]) + env.filters["tojson"] = tojson + env.globals["raise_exception"] = raise_exception + self.source = Path(path).read_text(encoding="utf-8") + self.template = env.from_string(self.source) + + def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True, + **kwargs) -> str: + return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, + **kwargs) + + +# ------------------------------------------------------------------------------------------------ requests +def _text_of(content) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + return "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in + ("text", "input_text", None)) + + +IMAGE_PARTS = ("image_url", "input_image", "image") + +# Thinking levels. The model's template knows low, medium and xhigh (its default; "high" means xhigh), and +# enable_thinking=false for none. Clients spell these many ways; everything maps onto those four. +EFFORT = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None, + "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"} + + +def effort_kwargs(value) -> dict: + """A reasoning effort as given by a client -> the template's kwargs. Unknown values are a 400, not a crash.""" + if value is None or value == "": + return {} + if value is False: + return {"enable_thinking": False} + key = str(value).strip().lower() + if key not in EFFORT: + raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high") + level = EFFORT[key] + return {"enable_thinking": False} if level is None else {"reasoning_effort": level} + + +def budget_effort(tokens) -> dict: + """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high.""" + try: + n = int(tokens) + except (TypeError, ValueError): + return {} + return {"reasoning_effort": "low" if n < 2048 else "medium" if n < 8192 else "xhigh"} + + +def _has_image(content) -> bool: + return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content) + + +def _image_source(part: dict) -> str: + """An image part's source as one string: a data: URL, an http(s) URL or a local file path. + OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style + {"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64", + "media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}.""" + if part.get("type") == "image": + src = part.get("source") or {} + if src.get("type") == "base64": + return f"data:{src.get('media_type', 'image/png')};base64,{src.get('data', '')}" + return src.get("url") or src.get("path") or "" + url = part.get("image_url") + if isinstance(url, dict): + url = url.get("url") + return url or "" + + +def _parts_of(content): + """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the + template's list form - text items and image items, in order - whose image items carry their source.""" + if not _has_image(content): + return _text_of(content) + items = [] + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") in IMAGE_PARTS: + items.append({"type": "image", "source": _image_source(part)}) + elif part.get("type") in ("text", "input_text", None) and "text" in part: + items.append({"type": "text", "text": part.get("text", "")}) + return items + + +def images_of(messages: list[dict]) -> list[str]: + """The image sources of the rendered conversation, in prompt order (the template renders one + <|vision_start|><|image_pad|><|vision_end|> per image item, message by message).""" + return [item["source"] for m in messages if isinstance(m.get("content"), list) + for item in m["content"] if item.get("type") == "image"] + + +def _late_system_to_user(messages: list[dict]) -> list[dict]: + """The chat template takes a system message only at the start ("System message must be at the beginning"). + Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user + turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place: + merging them into the first one would change the prompt's start and cost the conversation cache every turn.""" + return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)] + + +def _object_list(value, name: str) -> list[dict]: + """#460: a request's "messages" (or a message's "tool_calls") as a list of objects. Some clients send the array + double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a + string is decoded. Anything that is still not a list of objects is a ValueError, which the server answers with + a 400 naming the field. None (or no field) is an empty list, as a missing field always was.""" + if value is None: + return [] + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + raise ValueError(f"{name} must be a list of objects (a string was sent that is not JSON)") from None + if not isinstance(value, list) or not all(isinstance(m, dict) for m in value): + raise ValueError(f"{name} must be a list of objects") + return value + + +def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: + """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" + messages = [] + for m in _object_list(req.get("messages"), "messages"): + role = m.get("role") + if role == "developer": + role = "system" + out = {"role": role, "content": _parts_of(m.get("content")) if role in ("user", "tool", "assistant") else _text_of(m.get("content"))} + if m.get("reasoning_content"): + out["reasoning_content"] = m["reasoning_content"] + if m.get("tool_calls"): + calls = [] + for c in _object_list(m["tool_calls"], "tool_calls"): + fn = c.get("function", c) + if not isinstance(fn, dict): + raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") + args = fn.get("arguments") + if isinstance(args, str): # the template requires a mapping, not a JSON string + args = json.loads(args) if args.strip() else {} + calls.append({"function": {"name": fn.get("name"), "arguments": args or {}}}) + out["tool_calls"] = calls + messages.append(out) + tools = [t.get("function", t) if isinstance(t, dict) and t.get("type") == "function" else t + for t in req.get("tools") or []] or None + kwargs = {} + # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...} + reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {} + kwargs.update(effort_kwargs(req.get("reasoning_effort") or reasoning.get("effort"))) + # the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}} + for k, v in (req.get("chat_template_kwargs") or {}).items(): + if k == "enable_thinking" and not v: + kwargs = {"enable_thinking": False} + elif k == "reasoning_effort" and "enable_thinking" not in kwargs: + kwargs.update(effort_kwargs(v)) + return _late_system_to_user(messages), tools, kwargs + + +def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]: + """Anthropic Messages -> (template messages, template tools, template kwargs). `think_unasked`: a request + without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False + renders it without thinking (#278, the config's "anthropic_thinking": "on_request").""" + messages = [] + system = req.get("system") + if system: + messages.append({"role": "system", "content": _text_of(system)}) + for m in _object_list(req.get("messages"), "messages"): + content = m.get("content") + if isinstance(content, str): + messages.append({"role": m["role"], "content": content}) + continue + if m.get("role") == "user" and _has_image(content) and not any( + isinstance(b, dict) and b.get("type") == "tool_result" for b in content): + messages.append({"role": "user", "content": _parts_of(content)}) + continue + text, reasoning, calls = [], [], [] + for block in content or []: + kind = block.get("type") + if kind == "text": + text.append(block.get("text", "")) + elif kind == "thinking": + reasoning.append(block.get("thinking", "")) + elif kind == "tool_use": + calls.append({"function": {"name": block.get("name"), "arguments": block.get("input") or {}}}) + elif kind == "tool_result": + messages.append({"role": "tool", "content": _text_of(block.get("content"))}) + if text or calls or reasoning: + out = {"role": m["role"], "content": "".join(text)} + if reasoning: + out["reasoning_content"] = "".join(reasoning) + if calls: + out["tool_calls"] = calls + messages.append(out) + tools = [{"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})} + for t in req.get("tools") or []] or None + kwargs = {} + # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N}; + # "output_config": {"effort": "low" | "medium" | "high"} + thinking = req.get("thinking") + effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None + if isinstance(thinking, dict) and thinking.get("type") == "disabled": + kwargs["enable_thinking"] = False + elif effort: + kwargs.update(effort_kwargs(effort)) + elif isinstance(thinking, dict) and thinking.get("budget_tokens"): + kwargs.update(budget_effort(thinking["budget_tokens"])) + elif thinking is None and not req.get("reasoning_budget_tokens") and not think_unasked: + # Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a + # client that never asks would otherwise lose the thinking on every turn). Anthropic's thinking is + # opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none + # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. + # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A + # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. + kwargs["enable_thinking"] = False + return _late_system_to_user(messages), tools, kwargs + + +# ------------------------------------------------------------------------------------------------ output parser +@dataclass +class ToolCall: + name: str + arguments: dict + id: str = field(default_factory=lambda: "call_" + uuid.uuid4().hex[:24]) + + +@dataclass +class Event: + kind: str # "reasoning" | "content" | "tool_call" + text: str = "" + call: ToolCall | None = None + + +THINK_END = "" +CALL_START = "" +CALL_END = "" + + +PARAM_END = "" +FUNC_END = "" + + +def param_end(text: str, final: bool = False) -> int: + """Where a parameter value in `text` ends: the first `` followed (after whitespace) by the next + `` - the same text inside a value (a file that documents the call format, #210) is + part of the value. -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it).""" + at = text.find(PARAM_END) + while at >= 0: + after = text[at + len(PARAM_END):].lstrip() + if after.startswith(("` after the call's own ``, found by walking + its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in + the call format ends at the first ``, as before.""" + s = text.lstrip() + pos = len(text) - len(s) + if not s.startswith("", pos) + if gt < 0: + return -1 + pos = gt + 1 + while True: + rest = text[pos:] + s = rest.lstrip() + pos += len(rest) - len(s) + if s.startswith("", pos) + if gt < 0: + return -1 + end = param_end(text[gt + 1:]) + if end < 0: + return -1 + pos = gt + 1 + end + len(PARAM_END) + elif s.startswith(FUNC_END): + rest = text[pos + len(FUNC_END):] + s = rest.lstrip() + if s.startswith(CALL_END): + return pos + len(FUNC_END) + len(rest) - len(s) + return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos) + elif not s or " ToolCall: + """`\\n\\nVALUE\\n...` -> ToolCall. Values are JSON-decoded + when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON + objects/arrays/numbers/booleans).""" + body = body.strip() + if not body.startswith("" not in body: + raise ValueError("malformed tool call: " + body[:80]) + name = body[len("")] + rest = body[body.index(">") + 1:] + props = ((schema or {}).get("parameters") or {}).get("properties") or {} + args = {} + while "")] + rest = rest[rest.index(">") + 1:] + end = param_end(rest, final=True) + value = rest[:end] if end >= 0 else rest + rest = rest[end + len(PARAM_END):] if end >= 0 else "" + if value.startswith("\n"): + value = value[1:] + if value.endswith("\n"): + value = value[:-1] + declared = (props.get(pname) or {}).get("type") + if declared == "string": + args[pname] = value + else: + try: + args[pname] = json.loads(value) + except ValueError: + args[pname] = value + return ToolCall(name=name, arguments=args) + + +class OutputParser: + """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back + until it is complete, so clients never see ` between -> str|raw -> ... -> done + self.scall = None # the ToolCall being streamed (its id is reused by the final event) + self.sfirst = True + self.sval_started = False + self.sdeclared = {} + + def _scan(self) -> list[Event]: + """Advance the streaming view of the call body in self.buf (see stream_tools).""" + out = [] + + def args(s): + if s: + out.append(Event("tool_args", s, call=self.scall)) + while True: + rest = self.buf[self.sp:] + if self.ss == "name": + a = rest.find("", a + 10) if a >= 0 else -1 + if b < 0: + return out + name = rest[a + 10:b] + self.scall = ToolCall(name=name, arguments={}) + props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {} + self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()} + out.append(Event("tool_start", call=self.scall)) + args("{") + self.sp += b + 1 + self.ss = "between" + elif self.ss == "between": + stripped = rest.lstrip() + self.sp += len(rest) - len(stripped) + if stripped.startswith("") + if b < 0: + return out + pname = stripped[11:b] + args(("" if self.sfirst else ",") + json.dumps(pname) + ":") + self.sfirst = False + self.sp += b + 1 + if self.sdeclared.get(pname) == "string": + args('"') + self.ss, self.sval_started = "str", False + else: + self.ss = "raw" + elif stripped.startswith(""): + args("}") + self.sp += len("") + self.ss = "done" + else: + return out # a tag still arriving (or trailing text): wait + elif self.ss == "str": + if not self.sval_started: + if not rest: + return out + if rest[0] == "\n": # the value's leading newline is not part of it + self.sp += 1 + rest = rest[1:] + self.sval_started = True + end = param_end(rest) + if end >= 0: + value = rest[:end] + if value.endswith("\n"): + value = value[:-1] + args(json.dumps(value)[1:-1] + '"') + self.sp += end + len(PARAM_END) + self.ss = "between" + continue + # an undecided (-2) is held from its start, like a tag still arriving + safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,)) + if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before + safe -= 1 + if safe > 0: + args(json.dumps(rest[:safe])[1:-1]) + self.sp += safe + return out + elif self.ss == "raw": + end = param_end(rest) + if end < 0: + return out + value = rest[:end] + if value.startswith("\n"): + value = value[1:] + if value.endswith("\n"): + value = value[:-1] + try: + v = json.loads(value) + except ValueError: + v = value + args(json.dumps(v, ensure_ascii=False)) + self.sp += end + len(PARAM_END) + self.ss = "between" + else: + return out + + def _close_scan(self) -> list[Event]: + """A streamed call that ended without a clean : close its JSON so clients can still parse it.""" + out = [] + if self.scall is None or self.ss == "done": + return out + tail = "" + if self.ss == "str": + tail += '"' + elif self.ss == "raw": + tail += json.dumps(self.buf[self.sp:].strip("\n")) + tail += "}" + out.append(Event("tool_args", tail, call=self.scall)) + self.ss = "done" + return out + + def _hold(self, text: str, tags: tuple[str, ...]) -> int: + """Length of the longest suffix of `text` that is a proper prefix of one of `tags`.""" + best = 0 + for tag in tags: + for n in range(1, len(tag)): + if text.endswith(tag[:n]): + best = max(best, n) + return best + + def feed(self, delta: str) -> list[Event]: + self.buf += delta + out: list[Event] = [] + while True: + if self.state == "reasoning": + i = self.buf.find(THINK_END) + if i < 0: + keep = self._hold(self.buf, (THINK_END,)) + if len(self.buf) > keep: + out.append(Event("reasoning", self.buf[:len(self.buf) - keep])) + self.buf = self.buf[len(self.buf) - keep:] + return out + if i: + out.append(Event("reasoning", self.buf[:i])) + self.buf = self.buf[i + len(THINK_END):] + self.state, self.lead = "content", True + elif self.state == "content": + if self.lead: # newlines right after or a call + stripped = self.buf.lstrip("\n") + if not stripped: + self.buf = "" + return out + self.buf, self.lead = stripped, False + i = self.buf.find(CALL_START) + if i < 0: + # Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped, + # so emitting them early would make streamed and whole outputs differ. + j = len(self.buf) - self._hold(self.buf, (CALL_START,)) + while j > 0 and self.buf[j - 1] == "\n": + j -= 1 + if j > 0: + out.append(Event("content", self.buf[:j])) + self.buf = self.buf[j:] + return out + if i and self.buf[:i].strip(): + out.append(Event("content", self.buf[:i].rstrip("\n"))) + self.buf = self.buf[i + len(CALL_START):] + self.state = "call" + else: + i = call_end(self.buf) + if self.stream_tools: + if i >= 0: + whole, self.buf = self.buf, self.buf[:i] # scan only the body + out += self._scan() + out += self._close_scan() + self.buf = whole + else: + out += self._scan() + if i < 0: + return out + body = self.buf[:i] + self.buf = self.buf[i + len(CALL_END):] + name = body.strip()[len("", 1)[0] + call = parse_tool_call(body, self.schemas.get(name)) + if self.scall is not None: + call.id = self.scall.id + out.append(Event("tool_call", call=call)) + self._reset_scan() + self.state, self.lead = "content", True + + def finish(self) -> list[Event]: + """End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was + already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211).""" + out = [] + if self.state == "call" and self.stream_tools and self.scall is not None: + out += self._scan() # the output ended inside a call that was already announced + if self.ss == "done": # only its
is missing: the call itself is whole + out.append(Event("tool_call", call=self.scall)) + self.buf = "" + self._reset_scan() + return out + if self.buf: + kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content") + text = self.buf if self.state != "call" else CALL_START + self.buf + out.append(Event(kind, text)) + self.buf = "" + return out diff --git a/engine/strata/serve/mcp.py b/engine/strata/serve/mcp.py new file mode 100644 index 00000000..4586e2c1 --- /dev/null +++ b/engine/strata/serve/mcp.py @@ -0,0 +1,676 @@ +"""serve/mcp.py - tools from MCP (Model Context Protocol) servers for the web app's chats. + +The user lists servers in the run config (`"mcp_servers"`, or Claude Desktop's `"mcpServers"` block pasted as is) or +in a separate file (`--mcp-config`). Each one is either a program Strata starts (`command`, `args`, `env`, `cwd`: +the stdio transport, newline-delimited JSON-RPC 2.0 on its stdin/stdout) or an address (`url`, `headers`: the +Streamable HTTP transport, JSON-RPC POSTed, answered as JSON or as an event stream). Both are implemented here with +the standard library only; no MCP SDK is needed. + +`McpHub` owns every configured server: it starts them in the background when the server starts, offers their tools to +the model as OpenAI function tools named `__` (two servers may both have a `search`), and routes a call +back to the server that has it. A server that does not start is left out with one log line; the chat works without +it. A server that stops later (a crash) is started again on its next call. + +Tool results reach the model as text: the MCP content blocks joined, capped at `max_result_chars` (a directory tree or +a web page can be megabytes, far more than a context holds) with a note saying so. A failed call - the tool's own +error, a crash, a timeout - becomes a result that starts with "error:", so the model can react instead of the chat +breaking. +""" +from __future__ import annotations + +import collections +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request + +from serve.winjob import contain + +PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given +DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} + + +class McpError(RuntimeError): + """A server answered with an error, stopped, or could not be reached.""" + + +class McpTimeout(McpError): + pass + + +class McpCancelled(McpError): + """The chat was stopped while the call ran.""" + + +class _Slot: + """One request waiting for its response.""" + + def __init__(self): + self.done = threading.Event() + self.msg = None + self.error = None + + +def _wait(slot: _Slot, timeout: float, cancel: threading.Event | None, what: str): + """Wait for a response, checking the chat's stop button and the deadline a few times a second.""" + deadline = time.monotonic() + timeout + while not slot.done.wait(0.05): + if cancel is not None and cancel.is_set(): + raise McpCancelled("stopped") + if time.monotonic() > deadline: + raise McpTimeout(f"{what} timed out after {timeout:g} s") + if slot.error: + raise slot.error + msg = slot.msg + if "error" in msg: + err = msg["error"] if isinstance(msg["error"], dict) else {"message": str(msg["error"])} + raise McpError(f"{err.get('message') or 'error'} (code {err.get('code')})") + return msg.get("result") or {} + + +# ------------------------------------------------------------------------------------------------ transports +class StdioTransport: + """A server Strata starts: JSON-RPC messages one per line on its stdin and stdout; its stderr is its log.""" + kind = "stdio" + + def __init__(self, name: str, cfg: dict): + self.name, self.cfg = name, cfg + self.proc = None + self.lock = threading.Lock() # the pending requests + self.write_lock = threading.Lock() # stdin; separate, so a full pipe can't block the reader + self.pending: dict[int, _Slot] = {} + self.next_id = 0 + self.stderr = collections.deque(maxlen=40) # its last log lines, for the error message when it fails + self.protocol = PROTOCOL + + def start(self): + env = dict(os.environ) + env.update({str(k): str(v) for k, v in (self.cfg.get("env") or {}).items()}) + command = str(self.cfg["command"]) + # On Windows `npx`, `uvx` and friends are .cmd files that CreateProcess finds only with their extension + exe = shutil.which(command, path=env.get("PATH")) or command + extra = {} + if os.name == "nt": + extra["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0) + else: + extra["start_new_session"] = True # its own process group, so close() ends its children too + try: + self.proc = subprocess.Popen([exe, *[str(a) for a in self.cfg.get("args") or []]], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cfg.get("cwd") or None, + env=env, **extra) + except OSError as e: + raise McpError(f"could not start {command!r}: {e}") from None + contain(self.proc) # ends with the server, however it ends (Windows) + self._err_reader = threading.Thread(target=self._read_stderr, daemon=True) + self._err_reader.start() + threading.Thread(target=self._read, daemon=True).start() + + def alive(self) -> bool: + return self.proc is not None and self.proc.poll() is None and not getattr(self, "ended", False) + + @staticmethod + def _lines(f): + """A pipe's lines until it closes (or close() closed it under us).""" + try: + yield from f + except (OSError, ValueError): + return + + def _read_stderr(self): + for raw in self._lines(self.proc.stderr): + line = raw.decode("utf-8", "replace").rstrip() + if line: + self.stderr.append(line) + if os.environ.get("STRATA_DEBUG"): + print(f"[mcp {self.name}] {line}", flush=True) + + def _read(self): + for raw in self._lines(self.proc.stdout): + line = raw.decode("utf-8", "replace").strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: # a server that prints to stdout; the spec forbids it + self.stderr.append(line) + continue + for m in msg if isinstance(msg, list) else [msg]: + if isinstance(m, dict): + self._dispatch(m) + self.ended = True + # the server's last log line says why it stopped: let the stderr reader take it first (the pipe closes with + # the process), or the error raced it and said only "the server stopped" + self._err_reader.join(1.0) + code = self.proc.poll() + err = McpError(f"the server stopped{f' (exit code {code})' if code is not None else ''}{self._tail()}") + with self.lock: + slots, self.pending = list(self.pending.values()), {} + for s in slots: + s.error = err + s.done.set() + + def _tail(self) -> str: + return f": {self.stderr[-1][:300]}" if self.stderr else "" + + def _dispatch(self, m: dict): + if "method" in m: + if "id" in m: # a request from the server: we offer no client features + try: + if m["method"] == "ping": + self._send({"jsonrpc": "2.0", "id": m["id"], "result": {}}) + else: + self._send({"jsonrpc": "2.0", "id": m["id"], + "error": {"code": -32601, "message": f"method not supported: {m['method']}"}}) + except McpError: + pass + return # notifications (log messages, list changes): not used + with self.lock: + slot = self.pending.pop(m.get("id"), None) + if slot is not None: # an answer to a call that timed out is simply dropped + slot.msg = m + slot.done.set() + + def _send(self, msg: dict): + data = json.dumps(msg, ensure_ascii=False).encode("utf-8") + b"\n" + try: + with self.write_lock: + self.proc.stdin.write(data) + self.proc.stdin.flush() + except (OSError, ValueError): + raise McpError(f"the server stopped{self._tail()}") from None + + def request(self, method: str, params: dict, timeout: float, cancel=None): + if not self.alive(): + raise McpError(f"the server is not running{self._tail()}") + slot = _Slot() + with self.lock: + self.next_id += 1 + rid = self.next_id + self.pending[rid] = slot + try: + self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + return _wait(slot, timeout, cancel, method) + except (McpTimeout, McpCancelled) as e: + with self.lock: + self.pending.pop(rid, None) + try: # tell the server to stop working on it + self.notify("notifications/cancelled", {"requestId": rid, "reason": str(e)}) + except McpError: + pass + raise + + def notify(self, method: str, params: dict | None = None): + self._send({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})}) + + def close(self): + """As the spec says: close its stdin, give it a moment to exit, then end it (and what it started).""" + p = self.proc + if p is None: + return + try: + p.stdin.close() + except OSError: + pass + try: + p.wait(timeout=2) + except subprocess.TimeoutExpired: + self._kill_tree(p) + for f in (p.stdout, p.stderr): + try: + f.close() + except OSError: + pass + + @staticmethod + def _kill_tree(p): + try: + if os.name == "nt": # npx.cmd -> node: end the whole tree + subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=10) + else: + os.killpg(p.pid, signal.SIGTERM) + try: + p.wait(timeout=2) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGKILL) + except (OSError, subprocess.SubprocessError): + pass + try: + p.kill() + except OSError: + pass + + +class HttpTransport: + """A server at an address (Streamable HTTP): every message is a POST; the answer is JSON or an event stream that + carries it. The session id the server hands out at `initialize` rides on every later request.""" + kind = "http" + + def __init__(self, name: str, cfg: dict): + self.name, self.url = name, str(cfg["url"]) + self.headers = {str(k): str(v) for k, v in (cfg.get("headers") or {}).items()} + self.session = None + self.protocol = None # sent as MCP-Protocol-Version once negotiated + self.next_id = 0 + self.lock = threading.Lock() + self.broken = None + + def start(self): + pass + + def alive(self) -> bool: + return self.broken is None + + def _headers(self) -> dict: + h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "User-Agent": "strata", **self.headers} + if self.session: + h["Mcp-Session-Id"] = self.session + if self.protocol: + h["MCP-Protocol-Version"] = self.protocol + return h + + def _post(self, msg: dict, rid, timeout: float, slot: _Slot | None): + try: + req = urllib.request.Request(self.url, data=json.dumps(msg, ensure_ascii=False).encode("utf-8"), + headers=self._headers(), method="POST") + with urllib.request.urlopen(req, timeout=timeout) as r: + if r.headers.get("Mcp-Session-Id"): + self.session = r.headers["Mcp-Session-Id"] + if slot is None: # a notification: 202, nothing to read + return + ctype = r.headers.get("Content-Type", "") + if "text/event-stream" in ctype: + found = self._from_events(r, rid) + else: + body = r.read() + found = None + parsed = json.loads(body) if body.strip() else None + for m in parsed if isinstance(parsed, list) else [parsed]: + if isinstance(m, dict) and m.get("id") == rid and "method" not in m: + found = m + if found is None: + raise McpError("the server's answer did not contain a response") + slot.msg = found + except urllib.error.HTTPError as e: + detail = "" + try: + detail = e.read().decode("utf-8", "replace")[:300] + except OSError: + pass + if e.code == 404 and self.session: # the session expired: a restart starts a new one + self.broken = McpError("the server ended the session") + err = McpError(f"HTTP {e.code} {e.reason}{': ' + detail if detail else ''}") + if slot is None: + raise err from None + slot.error = err + except (OSError, ValueError, McpError) as e: + err = e if isinstance(e, McpError) else McpError(f"could not reach {self.url}: {e}") + if slot is None: + raise err from None + slot.error = err + finally: + if slot is not None: + slot.done.set() + + @staticmethod + def _from_events(r, rid): + """Read the event stream until the event that answers `rid` (it may carry notifications first).""" + data = [] + for raw in r: + line = raw.decode("utf-8", "replace").rstrip("\r\n") + if line.startswith("data:"): + data.append(line[5:].lstrip(" ")) + elif not line and data: + try: + m = json.loads("\n".join(data)) + except ValueError: + m = None + data = [] + for x in m if isinstance(m, list) else [m]: + if isinstance(x, dict) and x.get("id") == rid and "method" not in x: + return x + return None + + def request(self, method: str, params: dict, timeout: float, cancel=None): + if self.broken: + raise self.broken + with self.lock: + self.next_id += 1 + rid = self.next_id + slot = _Slot() + # the POST runs on its own thread so the stop button and the deadline are noticed while it waits + threading.Thread(target=self._post, args=({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}, + rid, timeout + 5, slot), daemon=True).start() + try: + return _wait(slot, timeout, cancel, method) + except (McpTimeout, McpCancelled) as e: + threading.Thread(target=self._quiet_notify, args=("notifications/cancelled", + {"requestId": rid, "reason": str(e)}), daemon=True).start() + raise + + def _quiet_notify(self, method, params): + try: + self.notify(method, params) + except McpError: + pass + + def notify(self, method: str, params: dict | None = None): + self._post({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})}, + None, 10, None) + + def close(self): + if not self.session: + return + try: # end the session on the server (it may not allow that) + req = urllib.request.Request(self.url, headers=self._headers(), method="DELETE") + urllib.request.urlopen(req, timeout=3).close() + except (OSError, ValueError): + pass + + +# ------------------------------------------------------------------------------------------------ one server +class McpServer: + """One configured server: started once (and again after it stopped), with the tools it listed.""" + + def __init__(self, name: str, cfg: dict, settings: dict): + self.name, self.cfg, self.settings = name, cfg, settings + self.kind = "http" if cfg.get("url") else "stdio" + self.status = "idle" # idle -> starting -> ready | failed; ready -> stopped when it ends + self.error = None + self.tools: list[dict] = [] + self.info: dict = {} + self.transport = None + self.lock = threading.Lock() + self.last_start = 0.0 + + def start(self) -> bool: + with self.lock: + return self._start() + + def _start(self) -> bool: + if self.transport is not None: + self.transport.close() + self.status, self.error, self.last_start = "starting", None, time.monotonic() + t = HttpTransport(self.name, self.cfg) if self.kind == "http" else StdioTransport(self.name, self.cfg) + self.transport = t + timeout = float(self.settings["start_timeout_s"]) + try: + t.start() + res = t.request("initialize", {"protocolVersion": PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "strata", "title": "Strata", "version": "1"}}, + timeout) + t.protocol = str(res.get("protocolVersion") or PROTOCOL) + self.info = {k: v for k, v in (res.get("serverInfo") or {}).items() if k in ("name", "title", "version")} + self.info["protocol"] = t.protocol + t.notify("notifications/initialized") + tools, cursor = [], None + for _ in range(100): # pages; a server that never stops paging is cut off + try: + page = t.request("tools/list", {"cursor": cursor} if cursor else {}, timeout) + except McpError as e: + if "code -32601" in str(e) and not tools: # a server without tools (prompts/resources only) + break + raise + tools += [x for x in page.get("tools") or [] if isinstance(x, dict) and x.get("name")] + cursor = page.get("nextCursor") + if not cursor: + break + self.tools, self.status = tools, "ready" + names = ", ".join(x["name"] for x in tools[:8]) + (", ..." if len(tools) > 8 else "") + print(f"[strata] MCP server {self.name!r}: {len(tools)} tool{'s' * (len(tools) != 1)}" + f"{' (' + names + ')' if tools else ''}", flush=True) + return True + except McpError as e: + self.status, self.error, self.tools = "failed", str(e), [] + t.close() + print(f"[strata] MCP server {self.name!r} did not start: {e}. Its tools are left out; the chat works " + "without them.", flush=True) + return False + + def call(self, tool: str, arguments: dict, timeout: float, cancel=None) -> dict: + with self.lock: + if self.transport is None or not self.transport.alive(): + # it stopped since its last call (a crash, an expired session): start it again; one that failed to + # start is tried again at most every 10 s, so a broken command does not run on every call + if self.status == "failed" and time.monotonic() - self.last_start < 10: + raise McpError(f"the server is not running ({self.error or 'it stopped'})") + print(f"[strata] MCP server {self.name!r} had stopped; starting it again", flush=True) + if not self._start(): + raise McpError(f"the server could not be started again: {self.error}") + t = self.transport + try: + return t.request("tools/call", {"name": tool, "arguments": arguments}, timeout, cancel) + except McpError as e: + if not t.alive(): + self.status, self.error = "stopped", str(e) + raise + + def close(self): + with self.lock: + if self.transport is not None: + self.transport.close() + if self.status in ("ready", "starting"): + self.status = "stopped" + + +# ------------------------------------------------------------------------------------------------ the hub +def result_text(result: dict) -> str: + """An MCP tool result as the text the model reads: the text blocks as they are, other blocks named.""" + parts = [] + for block in result.get("content") or []: + if not isinstance(block, dict): + continue + kind = block.get("type") + if kind == "text": + parts.append(str(block.get("text", ""))) + elif kind == "resource": + res = block.get("resource") or {} + parts.append(str(res["text"]) if "text" in res else f"[resource {res.get('uri', '')} " + f"({res.get('mimeType', 'binary')}), not shown]") + elif kind == "resource_link": + parts.append(f"[resource link: {block.get('name') or ''} {block.get('uri', '')}]".replace(" ", " ")) + elif kind in ("image", "audio"): + size = len(block.get("data") or "") * 3 // 4 + parts.append(f"[{kind} ({block.get('mimeType', '?')}, {size:,} bytes): not shown to the model]") + else: + parts.append(json.dumps(block, ensure_ascii=False)) + if not parts and result.get("structuredContent") is not None: + parts.append(json.dumps(result["structuredContent"], ensure_ascii=False)) + return "\n".join(parts) + + +def _clean(name: str) -> str: + return re.sub(r"[^A-Za-z0-9_-]", "_", str(name)) or "x" + + +class McpHub: + """Every configured server, and the merged, namespaced tool list the model sees.""" + + def __init__(self, servers: dict[str, dict], settings: dict | None = None): + self.settings = {**DEFAULTS, **(settings or {})} + self.servers = {name: McpServer(name, cfg, self.settings) for name, cfg in servers.items()} + self.threads: list[threading.Thread] = [] + self._routes: dict[str, tuple[McpServer, str]] = {} + + def start(self, wait: bool = False): + """Start every server on its own thread (npx may download a package first: that must not delay the chat).""" + self.threads = [threading.Thread(target=s.start, daemon=True, name=f"mcp-{s.name}") + for s in self.servers.values()] + for t in self.threads: + t.start() + if wait: + self.wait(None) + + def wait(self, timeout: float | None) -> None: + """Wait (up to `timeout` s in all) for servers that are still starting.""" + end = None if timeout is None else time.monotonic() + timeout + for t in self.threads: + t.join(None if end is None else max(0.0, end - time.monotonic())) + + def routes(self) -> dict[str, tuple[McpServer, str]]: + """tool name the model sees -> (server, the tool's own name). A server that stopped after it was ready keeps + its tools here: a call starts it again.""" + out = {} + for s in self.servers.values(): + if s.status not in ("ready", "stopped"): + continue + for t in s.tools: + name = f"{_clean(s.name)}__{_clean(t['name'])}"[:64] + n = 2 + while name in out: # two names that differ only in cleaned characters + name = f"{name[:60]}_{n}" + n += 1 + out[name] = (s, t["name"]) + self._routes = out + return out + + def template_tools(self, exclude=()) -> list[dict]: + """The tools in the chat template's form ({name, description, parameters}); `exclude`: names the request + brought itself (those win).""" + out = [] + for name, (s, tool) in self.routes().items(): + if name in exclude: + continue + t = next(x for x in s.tools if x["name"] == tool) + schema = t.get("inputSchema") if isinstance(t.get("inputSchema"), dict) else {} + out.append({"name": name, "description": str(t.get("description") or t.get("title") or ""), + "parameters": schema or {"type": "object", "properties": {}}}) + return out + + def openai_tools(self) -> list[dict]: + return [{"type": "function", "function": t} for t in self.template_tools()] + + def call(self, name: str, arguments: dict, cancel: threading.Event | None = None) -> dict: + """Run one tool -> {"ok", "text" (what the model reads, capped), "chars" (its full length), "truncated", + "ms", "server", "tool"}. Errors become text starting with "error:"; only McpCancelled is raised.""" + t0 = time.monotonic() + server, tool = self._routes.get(name) or self.routes().get(name, (None, name)) + out = {"server": server.name if server else None, "tool": tool} + if server is None: + text, ok = f"error: there is no tool named {name!r}", False + else: + try: + res = server.call(tool, arguments if isinstance(arguments, dict) else {}, + float(self.settings["timeout_s"]), cancel) + text, ok = result_text(res), not res.get("isError") + if not ok: + text = "error: " + (text or "the tool reported an error") + except McpCancelled: + raise + except McpError as e: + text, ok = f"error: {e}", False + cap = int(self.settings["max_result_chars"]) + full = len(text) + if cap > 0 and full > cap: + text = text[:cap] + (f"\n\n[... truncated: the tool returned {full:,} characters; only the first " + f"{cap:,} are shown]") + out.update(ok=ok, text=text, chars=full, truncated=cap > 0 and full > cap, + ms=int((time.monotonic() - t0) * 1000)) + return out + + def status(self) -> dict: + """GET /mcp: every server, its state and its tools (for the web app).""" + routes = self.routes() + servers = [] + for s in self.servers.values(): + names = {tool: n for n, (srv, tool) in routes.items() if srv is s} + servers.append({"name": s.name, "transport": s.kind, "status": s.status, "error": s.error, + "info": s.info, + "tools": [{"name": names.get(t["name"], t["name"]), "tool": t["name"], + "description": str(t.get("description") or "")[:300]} for t in s.tools]}) + return {"servers": servers, "tools": len(routes), + "settings": {k: self.settings[k] for k in ("timeout_s", "max_result_chars", "max_rounds")}} + + def close(self): + for s in self.servers.values(): + try: + s.close() + except Exception: # noqa: BLE001 - closing is best effort + pass + + +# ------------------------------------------------------------------------------------------------ config +def _check_server(name, cfg, where) -> dict: + if not isinstance(cfg, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r} must be an object with \"command\" or \"url\"") + if cfg.get("url"): + if cfg.get("type") == "sse": + raise SystemExit(f"[strata] {where}: MCP server {name!r} uses the old SSE transport (\"type\": \"sse\"); " + "Strata speaks Streamable HTTP - most servers offer it at /mcp") + if not isinstance(cfg.get("headers") or {}, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"headers\" must be an object") + return cfg + if not isinstance(cfg.get("command"), str) or not cfg["command"].strip(): + raise SystemExit(f"[strata] {where}: MCP server {name!r} needs \"command\" (a program to start) or \"url\"") + if not isinstance(cfg.get("args") or [], list): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"args\" must be a list") + if not isinstance(cfg.get("env") or {}, dict): + raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"env\" must be an object") + return cfg + + +def servers_from(block, where: str) -> dict[str, dict]: + """{"name": {...}} with the entries checked; `"disabled": true` leaves one out.""" + if block is None: + return {} + if not isinstance(block, dict): + raise SystemExit(f"[strata] {where}: the MCP servers must be an object {{\"name\": {{...}}}}") + return {str(n): _check_server(n, c, where) for n, c in block.items() + if not (isinstance(c, dict) and c.get("disabled") is True)} + + +def settings_from(cfg: dict) -> dict: + """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s.""" + out = {} + for key, value in (cfg.get("mcp") or {}).items(): + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key in ("timeout_s", "start_timeout_s"): + if not number or value <= 0: + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a number of seconds > 0") + out[key] = float(value) + elif key in ("max_result_chars", "max_rounds"): + if not number or value != int(value) or value < 1: + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a positive integer") + out[key] = int(value) + else: + print(f"[strata] config mcp.{key}={value!r}: unknown key, ignored", flush=True) + return out + + +def hub_from_config(cfg: dict, mcp_config_path: str | None = None) -> McpHub | None: + """The run config's `"mcp_servers"` (or `"mcpServers"`) plus the servers in the --mcp-config file (Claude + Desktop's format: {"mcpServers": {...}}); a name in both takes the file's entry. None when there are none.""" + servers = {} + servers.update(servers_from(cfg.get("mcp_servers"), "config mcp_servers")) + servers.update(servers_from(cfg.get("mcpServers"), "config mcpServers")) + if mcp_config_path: + try: + with open(mcp_config_path, encoding="utf-8-sig") as f: + data = json.load(f) + except (OSError, ValueError) as e: + raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: {e}") from None + block = data.get("mcpServers", data.get("mcp_servers")) if isinstance(data, dict) else None + if block is None: + raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: expected {{\"mcpServers\": {{...}}}}") + servers.update(servers_from(block, f"--mcp-config {mcp_config_path}")) + if not servers: + return None + return McpHub(servers, settings_from(cfg)) + + +if __name__ == "__main__": # python -m serve.mcp config.json: list what a config offers + hub = hub_from_config(json.load(open(sys.argv[1], encoding="utf-8-sig")) if len(sys.argv) > 1 else {}, + sys.argv[2] if len(sys.argv) > 2 else None) + if hub is None: + sys.exit("no MCP servers configured") + hub.start(wait=True) + print(json.dumps(hub.status(), indent=1)) + hub.close() diff --git a/engine/strata/serve/mcp_fake_server.py b/engine/strata/serve/mcp_fake_server.py new file mode 100644 index 00000000..c4200b07 --- /dev/null +++ b/engine/strata/serve/mcp_fake_server.py @@ -0,0 +1,172 @@ +"""serve/mcp_fake_server.py - a small MCP server for serve/test_mcp.py (no MCP SDK, no network beyond localhost). + + python serve/mcp_fake_server.py stdio: JSON-RPC lines on stdin/stdout + python serve/mcp_fake_server.py --http 8765 Streamable HTTP on 127.0.0.1:8765/mcp + +Tools: echo (returns its text), fail (a tool error, isError), sleep (answers after `seconds`), big (`n` characters), +die (the process exits mid-call), add (two integers). tools/list pages two tools at a time (`--page N`), so the +client's pagination is exercised. `--crash-at-start` exits before answering anything. With FAKE_MCP_LOG set, the +server appends what it saw (calls, cancellations) to that file, one JSON line each. +""" +from __future__ import annotations + +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +TOOLS = [ + {"name": "echo", "description": "Returns the text it is given.", + "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}, + {"name": "fail", "description": "Always fails.", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "sleep", "description": "Waits, then answers.", + "inputSchema": {"type": "object", "properties": {"seconds": {"type": "number"}}}}, + {"name": "big", "description": "Returns n characters.", + "inputSchema": {"type": "object", "properties": {"n": {"type": "integer"}}}}, + {"name": "die", "description": "Ends the server.", "inputSchema": {"type": "object", "properties": {}}}, + {"name": "add", "description": "Adds two integers.", + "inputSchema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}}}, +] +PAGE = 2 +cancelled: set = set() + + +def log(event: dict): + path = os.environ.get("FAKE_MCP_LOG") + if path: + with open(path, "a", encoding="utf-8") as f: + f.write(json.dumps(event) + "\n") + + +def text(t, error=False): + return {"content": [{"type": "text", "text": t}], "isError": error} + + +def handle(msg: dict): + """-> the response for a request, None for a notification.""" + method, rid, params = msg.get("method"), msg.get("id"), msg.get("params") or {} + if "id" not in msg: + if method == "notifications/cancelled": + cancelled.add(params.get("requestId")) + log({"cancelled": params.get("requestId")}) + return None + if method == "initialize": + return {"jsonrpc": "2.0", "id": rid, "result": { + "protocolVersion": params.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}}, + "serverInfo": {"name": "fake", "version": "0.1"}}} + if method == "tools/list": + start = int(params.get("cursor") or 0) + page = {"tools": TOOLS[start:start + PAGE]} + if start + PAGE < len(TOOLS): + page["nextCursor"] = str(start + PAGE) + return {"jsonrpc": "2.0", "id": rid, "result": page} + if method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + log({"call": name, "arguments": args}) + if name == "echo": + result = text(str(args.get("text", ""))) + elif name == "fail": + result = text("it failed on purpose", error=True) + elif name == "sleep": + time.sleep(float(args.get("seconds", 1))) + result = text("slept") + elif name == "big": + result = text("y" * int(args.get("n", 100000))) + elif name == "die": + sys.stderr.write("dying on purpose\n") + sys.stderr.flush() + os._exit(3) + elif name == "add": + result = text(str(int(args.get("a", 0)) + int(args.get("b", 0)))) + else: + return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32602, "message": f"unknown tool {name}"}} + return {"jsonrpc": "2.0", "id": rid, "result": result} + return {"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": f"no method {method}"}} + + +def stdio(): + for f in (sys.stdin, sys.stdout, sys.stderr): # MCP's stdio is UTF-8, whatever the Windows code page is + f.reconfigure(encoding="utf-8") + out = threading.Lock() + + def answer(msg): + r = handle(msg) + if r is not None and msg.get("id") not in cancelled: + with out: + sys.stdout.write(json.dumps(r) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + if not line.strip(): + continue + msg = json.loads(line) + if msg.get("method") == "tools/call": # calls on threads: a slow one must not block cancellation + threading.Thread(target=answer, args=(msg,), daemon=True).start() + else: + answer(msg) + + +def http_server(port: int = 0) -> ThreadingHTTPServer: + """Streamable HTTP at /mcp: JSON answers, except tools/call, which answers as an event stream (a progress + notification first); a session id from initialize is required afterwards.""" + sessions = set() + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.0" + + def log_message(self, *a): + pass + + def do_POST(self): + msg = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) + if msg.get("method") != "initialize" and self.headers.get("Mcp-Session-Id") not in sessions: + self.send_response(400) + self.end_headers() + return + r = handle(msg) + if r is None: + self.send_response(202) + self.end_headers() + return + if msg.get("method") == "tools/call": + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + note = {"jsonrpc": "2.0", "method": "notifications/progress", "params": {"progress": 1}} + self.wfile.write(b"event: message\ndata: " + json.dumps(note).encode() + b"\n\n") + self.wfile.write(b"event: message\ndata: " + json.dumps(r).encode() + b"\n\n") + return + body = json.dumps(r).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + if msg.get("method") == "initialize": + sid = f"s-{len(sessions) + 1}" + sessions.add(sid) + self.send_header("Mcp-Session-Id", sid) + self.end_headers() + self.wfile.write(body) + + def do_DELETE(self): + sessions.discard(self.headers.get("Mcp-Session-Id")) + self.send_response(200) + self.end_headers() + + httpd = ThreadingHTTPServer(("127.0.0.1", port), H) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd + + +if __name__ == "__main__": + if "--page" in sys.argv: + PAGE = int(sys.argv[sys.argv.index("--page") + 1]) + if "--crash-at-start" in sys.argv: + sys.stderr.write("cannot start: missing configuration\n") + sys.exit(2) + if "--http" in sys.argv: + server = http_server(int(sys.argv[sys.argv.index("--http") + 1])) + print(f"listening on http://127.0.0.1:{server.server_address[1]}/mcp", flush=True) + threading.Event().wait() + stdio() diff --git a/engine/strata/serve/server.py b/engine/strata/serve/server.py new file mode 100644 index 00000000..f611530b --- /dev/null +++ b/engine/strata/serve/server.py @@ -0,0 +1,2619 @@ +"""serve/server.py - plan v0.3 P8: OpenAI and Anthropic endpoints over any engine that maps token ids to tokens. + + python -m serve.server --engine mock --port 8095 (a scripted engine, for clients and tests) + python -m serve.server --engine strata --config strata.json --port 8080 (the real engine, resident) + +Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream and +non-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence). +Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests that +ask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw. +Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64 +data, http(s) URLs or local file paths) go through `strata-vision` (the model's mmproj file) and reach the engine as +embeddings (`GENI`). JPEG/PNG/BMP/GIF go straight in; WebP, TIFF, AVIF, ... (agents like omp send WebP) are +converted to PNG first with Pillow. +Requests whose prompt plus max tokens exceed the engine's context are REJECTED with 400, never truncated. +An unset (or 0, or -1) max tokens means "unlimited": whatever the prompt leaves of the context. + +The engine boundary is `Engine.generate(prompt_ids, max_new, sampling, cancel) -> iterator of token ids`. +`StrataEngine` keeps one `strata --serve` process resident (weights, expert arena and VRAM tier load once) and +talks to it over stdin/stdout; `MockEngine` is a scripted stand-in that makes every API path testable without a GPU. +""" +from __future__ import annotations + +import argparse +import collections +import base64 +import hashlib +import hmac +import codecs +import ctypes +import json +import os +import queue +import re +import select +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Iterator, Protocol +from urllib.parse import parse_qs, urlsplit + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module +from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 + images_of, openai_to_messages) +from serve.mcp import McpCancelled, hub_from_config # noqa: E402 +from serve.winjob import contain # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 + +IM_END = "<|im_end|>" +IMAGE_PAD = "<|image_pad|>" +VISION_START = "<|vision_start|>" +# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) +REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" +CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here +# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first +# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer. +RATE_WINDOW_S = 2.0 +RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here + + +# ------------------------------------------------------------------------------------------------ engines +class Engine(Protocol): + max_context: int + def generate(self, ids: list[int], max_new: int, sampling: dict, cancel: threading.Event) -> Iterator[int]: ... + + +class MockEngine: + """Replays a scripted completion (text) as token ids, one per step, then the end-of-turn token. Given a list of + scripts, each request gets the next one and the last one repeats (a tool call, then the answer after it).""" + + def __init__(self, tokenizer, script: str | list[str], max_context: int = 32768, delay_s: float = 0.0): + self.tok, self.max_context, self.delay = tokenizer, max_context, delay_s + end = tokenizer.encode(IM_END, parse_special=True) + self.scripts = [tokenizer.encode(x, parse_special=True) + end for x in ([script] if isinstance(script, str) + else script)] + self.script, self.turns = self.scripts[0], 0 + self.last_prompt: list[int] = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_prompt = list(ids) + self.last_embeddings = embeddings + if len(self.scripts) > 1: + self.script = self.scripts[min(self.turns, len(self.scripts) - 1)] + self.turns += 1 + for t in self.script[:max_new]: + if cancel.is_set(): + return + if self.delay: + time.sleep(self.delay) + yield t + + +class EngineDied(RuntimeError): + """The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer).""" + + +class EngineStarting(RuntimeError): + """The engine is (re)starting and has not said READY yet (#344): no context size to plan a request with - a 503, + not a 400 about the prompt.""" + + +class ModelBusy(RuntimeError): + """Explicit model controls must not interrupt active or queued requests.""" + + +class EngineStuck(RuntimeError): + """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than + reporting its GPU and RAM as given back.""" + + +class GpuBusy(RuntimeError): + """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another + model server) is using it, so the engine is not started into the little that is left.""" + + +ENGINE_REQUEST = re.compile( + r"prompt (?P\d+) tokens = (?P\d+) reused \+ \d+ read in (?P[\d.]+) ms \((?P[\d.]+) tok/s\), " + r"(?P\d+) generated in (?P[\d.]+) ms \((?P[\d.]+) tok/s\)") + + +_echoing: set[str] = set() # the logs echo_requests already follows (restart() runs StrataEngine.__init__ again) + + +def echo_requests(log_path: str, offset: int) -> None: + """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log. + + The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this + process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the + total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y + tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token). + """ + with open(log_path, "r", encoding="utf-8", errors="replace") as f: + f.seek(offset) + while True: + line = f.readline() + if not line: + time.sleep(0.2) + continue + m = ENGINE_REQUEST.search(line) + if m: + read_ms, gen_ms = float(m["read"]), float(m["gen_ms"]) + print("[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s " + "tok/s decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"], + m["tg"]), flush=True) + + +def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None: + """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB + into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more - + people closed the window thinking it had hung. The warning comes at that step, not after it.""" + gb = 0.0 + if "--native" in args: # about the size of the experts it will read + try: + gb = os.path.getsize(args[args.index("--native") + 1]) / 1e9 + except (OSError, IndexError): + pass + size = f"about {gb:.0f} GB" if gb >= 1 else "tens of GB" + t0 = last = time.time() + said = set() + + def say(key, text): + nonlocal last + if key not in said: + said.add(key) + last = time.time() + print(text, flush=True) + + say("weights", "[strata] starting the engine: reading the model's weights ...") + pos = offset + while not done.wait(0.5): + try: + with open(log_path, "rb") as f: + f.seek(pos) + chunk = f.read() + except OSError: + chunk = b"" + if chunk.count(b"\n"): + cut = chunk.rfind(b"\n") + 1 + pos += cut + for line in chunk[:cut].decode("utf-8", "replace").splitlines(): + if "PLE on" in line or "expert arena:" in line: + say("arena", f"[strata] loading the experts into RAM ({size}) and locking part of them for the GPU.\n" + " YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES NOW - this is normal.\n" + " Please wait and don't close this window; the browser opens when it is ready.") + elif " loaded " in line and "GiB at" in line: + say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() + + f" ({time.time() - t0:.0f} s so far)") + elif "expert cache " in line and " slots, " in line and "auto" not in line: + n = line.split("expert cache ", 1)[1].split(";")[0].replace(" slots,", " experts,").strip() + say("cache", f"[strata] filling the GPU's expert cache ({n}) ...") + elif "session is up" in line: + say("up", "[strata] almost ready ...") + if time.time() - last > heartbeat: + last = time.time() + print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True) + + +class StrataEngine: + """The resident engine: `strata --serve` reads `GEN ` lines and streams `T ` lines, then + `DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough. + + Per-request sampling rides the same line as engine-side keys between max_new and the ids + (`temperature=F top_p=F top_k=N seed=N`, the engine's own spelling). An absent temperature keeps the + engine's default, which is greedy; `temperature=0` means the same thing, so it is not forwarded. + """ + + def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None, + env: dict | None = None, lazy: bool = False): + self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27) + paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")} + self.model_path = paths.get("--native") or paths.get("--pack", "pack/full") + self.log_path = log + self.proc, self.pump, self.log = None, None, None + self.ended, self.unloaded = True, True + self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096 + self.can_stop = False # the engine honours a STOP line mid-request (READY stop) + self.last = {} + self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab) + self.prefill_tok_s_mean = None + self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines + try: # a ready-made engine's BUILD.json says its version + self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version") + except (OSError, ValueError): + self.info["version"] = None + if lazy: + return + self.unloaded = False # `ended` stays True until READY (below): not alive while starting (#344) + self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL + loading = threading.Event() # set once READY: the narrator below stops + if log: + threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading), + daemon=True).start() + # once per log: the follower keeps reading the same (appended) log across restarts and reloads + if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing: + _echoing.add(os.path.abspath(log)) + threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start() + self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) # ends with the server, however it ends (Windows) + self.max_context = 0 + for line in self.proc.stdout: + if line.startswith("INFO "): + for kv in line.split()[1:]: + k, _, v = kv.partition("=") + self.info[k] = int(v) if v.lstrip("-").isdigit() else v + if line.startswith("READY"): + f = line.split() + self.max_context = int(f[1]) + self.can_stop = "stop" in f[2:] + break + loading.set() + if self.max_context <= 0: + raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "")) + # (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that + # report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones + if self.info.get("engine"): + self.info["version"] = str(self.info["engine"]) + self.ended = False # READY: alive from here (restart() set it True, #344) + # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks) + self.lines: queue.Queue = queue.Queue() + self.pump = threading.Thread(target=self._pump, daemon=True) + self.pump.start() + + def _pump(self): + proc, lines = self.proc, self.lines # this process's: a restart replaces both (#344) + for line in proc.stdout: + lines.put(line) + if self.proc is proc: # a killed engine's pump must not mark its successor dead + self.ended = True # its output closed: it is gone, even before the OS says so + lines.put(None) + + def death_note(self) -> str: + """Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM.""" + tail = "" + try: + with open(self.log_path, "rb") as f: + f.seek(0, 2) + f.seek(max(0, f.tell() - 4096)) + tail = f.read().decode("utf-8", "replace") + except (OSError, TypeError): + pass + for line in reversed(tail.splitlines()): + if "issue #29" in line: + return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log " + "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.") + rc = self.proc.poll() + last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "") + if rc is not None and rc >= 0 and last: # it ended by itself: its own last words say why (#215) + return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please " + "report it at github.com/Niko1221/Strata/issues with the log.") + return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | " + "grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a " + "smaller model (Q2_0 / IQ2_XS).") + + def alive(self) -> bool: + return self.proc is not None and not getattr(self, "ended", False) and self.proc.poll() is None + + def exit_code(self): + if self.proc is None: + return None + try: + return self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + return None + + def unload(self): + """Release GPU/RAM between requests, retaining the spawn config for automatic reloading.""" + self.close() + self.unloaded = True + + def restart(self): + """Start the engine again (the same command) after it died; the new process has its own line queue.""" + self.close() + info = dict(self.info) + # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says READY, and a + # request that saw alive() in that window skipped load() and failed with "context (0)". __init__ clears + # `ended` itself once READY (before its pump thread can set it again). + self.ended = True + self.__init__(*self.spawn) + self.info = {**info, **self.info} + + def _parse_done(self, line): + f = line.split() + self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]), + "decode_ms": float(f[4]), "finish": f[5]} + if len(f) >= 9: # the conversation cache's fields (engine 0.1.3+) + self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8])) + if len(f) >= 11: # decode hit rate fields + self.last.update(hits=int(f[9]), lookups=int(f[10])) + if len(f) >= 14: # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB + self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13])) + + @staticmethod + def sampling_keys(sampling: dict) -> str: + keys = "" + t = sampling.get("temperature") + if isinstance(t, (int, float)) and float(t) > 0.0: + keys += f" temperature={float(t)!r}" + tp = sampling.get("top_p") + if isinstance(tp, (int, float)) and float(tp) < 1.0: + keys += f" top_p={float(tp)!r}" + tk = sampling.get("top_k") + if isinstance(tk, int) and not isinstance(tk, bool) and tk >= 0: + # the engine's sampled path keeps at most 64 candidates: 0 ("off") and wider lists get all 64 + keys += f" top_k={tk if 1 <= tk <= 64 else 64}" + mp = sampling.get("min_p") + if isinstance(mp, (int, float)) and 0.0 < float(mp) <= 1.0: + keys += f" min_p={float(mp)!r}" + rp = sampling.get("repetition_penalty") + rp_on = isinstance(rp, (int, float)) and float(rp) != 1.0 + pf = sampling.get("frequency_penalty") + pf_on = isinstance(pf, (int, float)) and float(pf) != 0.0 + pp = sampling.get("presence_penalty") + pp_on = isinstance(pp, (int, float)) and float(pp) != 0.0 + if rp_on: + keys += f" penalty_repeat={float(rp)!r}" + if pf_on: + keys += f" penalty_freq={float(pf)!r}" + if pp_on: + keys += f" penalty_present={float(pp)!r}" + if rp_on or pf_on or pp_on: + # a penalty without a window counts over nothing: the engine's default is the last 64 tokens + pln = sampling.get("penalty_last_n") + if isinstance(pln, int) and not isinstance(pln, bool) and pln > 0: + keys += f" penalty_last_n={pln}" + else: + keys += " penalty_last_n=64" + seed = sampling.get("seed") + if isinstance(seed, int) and seed > 0: + keys += f" seed={seed}" + # setup's calibration (tools/calibrate.py): engine settings for this request only, measured without a restart + tune = sampling.get("strata_tune") + if isinstance(tune, dict): + for k in ("pcie_frac", "spec_min_p"): + v = tune.get(k) + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0: + keys += f" {k}={float(v)!r}" + return keys + StrataEngine.projection_key(sampling) + + @staticmethod + def projection_key(sampling: dict) -> str: + """`cvec=0|1`: the experimental-speed-projection control vector for this request, when the engine was + started with one (--control-vector-scaled; an engine without one ignores the key). Absent = on.""" + on = sampling.get("experimental_speed_projection") + return f" cvec={int(on)}" if isinstance(on, bool) else "" + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): + the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that + has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" + self.progress = None + self.prefill_tok_s_mean = None + # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) + head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ + f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" + try: + self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") + self.proc.stdin.flush() + except OSError: # the pipe is gone: the engine died (not the client) + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None + done = False + try: + while True: + try: + line = self.lines.get(timeout=10) + except queue.Empty: + if cancel.is_set(): + return + yield None + continue + if line is None: + done = True + raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") + if line.startswith("T "): + if cancel.is_set(): + return + yield int(line[2:]) + elif line.startswith("PP "): + f = line.split() + if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): + self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the + self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None + if cancel.is_set(): # lines reset the 10 s wait, so without this a long prompt + return # would send no keep-alives at all) + yield None + elif line.startswith("DONE"): + self._parse_done(line) + done = True + return + elif line.startswith("ERR"): + done = True + raise ValueError(line[4:].strip()) + finally: + if not done: # the consumer stopped early: stop the engine, drain to DONE + if self.can_stop: + try: + self.proc.stdin.write("STOP\n") + self.proc.stdin.flush() + except OSError: + pass + while True: + line = self.lines.get() + if line is None or line.startswith("ERR"): + break + if line.startswith("DONE"): + self._parse_done(line) + break + + def close(self): + """End the engine process: QUIT first (the engine frees its memory itself - unpinning tens of GB can take + a while), then terminate, then kill, each given 20 s. Raises EngineStuck when it still runs after all three.""" + if self.proc is None: + return + try: + if self.proc.poll() is None: + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown + self.proc.wait(timeout=20) + except (OSError, ValueError, subprocess.TimeoutExpired): + self.proc.terminate() + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + self.proc.kill() + try: + self.proc.wait(timeout=20) + except subprocess.TimeoutExpired: + raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None + except OSError: + pass + finally: + if self.proc.poll() is not None: + if self.pump is not None: + self.pump.join(timeout=2) + self.proc.stdin.close() + self.proc.stdout.close() + if self.log not in (None, subprocess.DEVNULL): + self.log.close() + self.proc = None + self.ended = True + self.progress, self.last = None, {} + + +class Vision: + """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC ` + lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that + sends the same picture again (every turn, with most clients) encodes it once.""" + + def __init__(self, cfg: dict, log=None, env: dict | None = None): + args = [cfg["exe"], "--mmproj", cfg["mmproj"], "--model", cfg["model"]] + if cfg.get("gpu"): + args.append("--gpu") + if cfg.get("threads"): + args += ["--threads", str(cfg["threads"])] + if cfg.get("max_tokens"): + args += ["--max-tokens", str(cfg["max_tokens"])] + self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-")) + self.spawn = (args, log, env) # to start it again after an unload + self.stopped = False + self._start() + self.lock = threading.Lock() + self.cache: dict[str, tuple[Path, int]] = {} + + def _start(self): + args, log, env = self.spawn + self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, + text=True, encoding="utf-8", bufsize=1, env=env) + contain(self.proc) + line = self.proc.stdout.readline() + if not line.startswith("READY"): + raise RuntimeError("the vision encoder did not start: " + line.strip()) + self.stopped = False + + def alive(self) -> bool: + return not self.stopped and self.proc.poll() is None + + def unload(self): + """Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk.""" + self.close() + self.stopped = True + + def restart(self): + """Start the encoder again after an unload (or if it died); the cache of encoded images is kept.""" + try: + self.proc.kill() + except OSError: + pass + self._start() + + @staticmethod + def load(source: str) -> bytes: + if source.startswith("data:"): + return base64.b64decode(source.split(",", 1)[1]) + if source.startswith(("http://", "https://")): + req = urllib.request.Request(source, headers={"User-Agent": "strata"}) + with urllib.request.urlopen(req, timeout=60) as r: + return r.read() + path = source[7:] if source.startswith("file://") else source + if path and os.path.isfile(path): + return Path(path).read_bytes() + raise ValueError("an image must be a data: URL, an http(s) URL or a local file path") + + @staticmethod + def normalize(data: bytes) -> bytes: + """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.""" + if data[:3] == b"\xff\xd8\xff" or data[:8] == b"\x89PNG\r\n\x1a\n" or data[:2] == b"BM" or \ + data[:6] in (b"GIF87a", b"GIF89a"): + return data + try: + import io + from PIL import Image + except ImportError: + raise ValueError("this image format needs Pillow (python -m pip install pillow); JPEG, PNG, BMP and " + "GIF work without it") from None + try: + im = Image.open(io.BytesIO(data)) + im.load() + except Exception as e: + raise ValueError(f"the image could not be read ({e})") from None + if im.mode in ("RGBA", "LA", "P") and "transparency" in im.info or im.mode in ("RGBA", "LA"): + im = im.convert("RGBA") + bg = Image.new("RGB", im.size, (255, 255, 255)) # transparent areas become white, not black + bg.paste(im, mask=im.split()[-1]) + im = bg + elif im.mode != "RGB": + im = im.convert("RGB") + out = io.BytesIO() + im.save(out, format="PNG") + return out.getvalue() + + def encode(self, source: str) -> tuple[Path, int]: + """-> (embeddings file, number of image tokens).""" + data = self.normalize(self.load(source)) + key = hashlib.sha256(data).hexdigest()[:32] + with self.lock: + if key in self.cache: + return self.cache[key] + img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve" + img.write_bytes(data) + try: + self.proc.stdin.write(f"ENC {img} {out}\n") + self.proc.stdin.flush() + line = self.proc.stdout.readline().strip() + finally: # #352: also when the encoder's pipe is gone + img.unlink(missing_ok=True) + if not line.startswith("OK"): + raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else + "the vision encoder stopped")) + self.cache[key] = (out, int(line.split()[1])) + if len(self.cache) > 64: # oldest first + old = next(iter(self.cache)) + self.cache.pop(old)[0].unlink(missing_ok=True) + return self.cache[key] + + def close(self): + try: + self.proc.stdin.write("QUIT\n") + self.proc.stdin.flush() + self.proc.wait(timeout=10) + except Exception: + self.proc.kill() + + +def gpu_list(cfg: dict) -> list[int]: + """The config's "gpu": one card (2), or several for a layer split ([0, 2] or "0,2"), numbered as nvidia-smi + numbers them; [] when it names none.""" + g = cfg.get("gpu") + if g is None or g == "": + return [] + items = g if isinstance(g, (list, tuple)) else str(g).split(",") + return [int(str(x).strip()) for x in items if str(x).strip() != ""] + + +def engine_args(cfg: dict) -> list[str]: + """The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the + config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32").""" + args = list(cfg["args"]) + if len(gpu_list(cfg)) > 1 and "--layer-split" not in args: + args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV + if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: + args.append("--split-skip-if-fits") + return args + + +def hip_visible(cfg: dict) -> list[int]: + """AMD: the devices the engine should see, as the HIP runtime numbers them (HIP_VISIBLE_DEVICES). + + On Linux setup's KFD order is HIP's order, so the config's "gpu" is it. On Windows setup finds the cards in the + display-adapter order, and an integrated Radeon that HIP also enumerates takes ordinal 0 and pushes the discrete + card to 1 (#325): setup records the ordinal `strata-device --list-devices` gave the card as "hip_ordinal", which + wins for a one-card config. Without it (a config from before), the config's "gpu".""" + ordinal = cfg.get("hip_ordinal") + if ordinal is not None and str(ordinal).strip() != "" and len(gpu_list(cfg)) <= 1: + try: + return [int(str(ordinal).strip())] + except ValueError: + pass + return gpu_list(cfg) + + +def child_env(cfg: dict) -> dict: + """The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that + compiled it) first on the library search path.""" + env = dict(os.environ) + if hip_visible(cfg) and cfg.get("backend") == "hip": # AMD: numbered as HIP numbers them (hip_visible) + env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in hip_visible(cfg)) + elif gpu_list(cfg): # issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's + env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # own default order (fastest first) can number the cards otherwise + env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in gpu_list(cfg)) + for k, v in (cfg.get("env") or {}).items(): # engine settings the config carries (AMD: the GEMM tuning table) + env[str(k)] = str(v) + dirs = [d for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()] + if dirs: + var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH" + env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) + return env + + +def vision_env(cfg: dict, env: dict) -> dict: + """The image encoder's environment: the engine's, unless the config's vision section names its own "cuda_device" + (numbered like nvidia-smi) - then the encoder runs on that card alone, so a spare GPU can hold it while the engine + keeps all of its own cards' VRAM (#408, Efs-O). Without it, nothing changes.""" + dev = (cfg.get("vision") or {}).get("cuda_device") + if dev is None: + return env + env = dict(env) + if cfg.get("backend") == "hip": + env["HIP_VISIBLE_DEVICES"] = str(dev) + else: + env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" + env["CUDA_VISIBLE_DEVICES"] = str(dev) + return env + + +class ByteTokenizer: + """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256.""" + SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"] + + def encode(self, text, parse_special=False): + out, i = [], 0 + while i < len(text): + for k, s in enumerate(self.SPECIALS): + if parse_special and text.startswith(s, i): + out.append(256 + k) + i += len(s) + break + else: + out.extend(text[i].encode("utf-8")) + i += 1 + return out + + def decode(self, ids, errors="replace"): + raw = bytearray() + for t in ids: + raw += self.SPECIALS[t - 256].encode() if t >= 256 else bytes([t]) + return raw.decode("utf-8", errors=errors) + + +# ------------------------------------------------------------------------------------------------ core +class Detokenizer: + """Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete + characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become + U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of + every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer + without `token_bytes` (the tests' byte tokenizer) keeps the re-decode.""" + + def __init__(self, tok): + self.tok, self.ids, self.sent = tok, [], 0 + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None + + def pending(self) -> bool: + """A character is split across the tokens so far: its first bytes are held.""" + if self.inc is not None: + return bool(self.inc.getstate()[0]) + return self.tok.decode(self.ids).endswith("\ufffd") + + def push(self, t: int) -> str: + if self.inc is not None: + return self.inc.decode(self.tok.token_bytes(t)) + self.ids.append(t) + text = self.tok.decode(self.ids) + if text.endswith("�"): + return "" + delta, self.sent = text[self.sent:], len(text) + return delta + + +class Service: + def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next", + vision: Vision | None = None, sampling_defaults: dict | None = None, + fit_max_tokens: bool = False): + self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision + self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400 + self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`) + self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block + self.shared = {} # the web app's Chat settings for every client (POST /settings) + self.shared_path = None # where they are kept between starts (next to the config) + self.fifo = threading.Lock() + self.embeddings = threading.local() # the current request's image embeddings file (GENI) + self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that + # matters); empty = no CORS headers at all, as before + self.cors_origins: list[str] = [] + # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a + # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard + self.trusted_origins: list[str] = [] + self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now + self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window + # #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory, + # so it is off unless the config's "api_monitor" (or --api-monitor) turns it on + self.api_monitor = False + self.api_requests = collections.deque(maxlen=100) # bounded I/O in memory; no headers or API keys + self.request_trace = threading.local() + self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics) + # since the server started (the Monitor's totals, issue #35) + self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0, + "prompt_ms": 0.0, "decode_ms": 0.0, + "drafts_offered": 0, "drafts_accepted": 0} # #457: the MTP drafts, summed where reported + self.last_timings = None # the last finished request's, llama.cpp's names (/v1/status) + self.last_request_at = None # when a request last started or finished + self.started_at = time.time() + self.status_lock = threading.Lock() + self.mcp = None # serve/mcp.py's McpHub when MCP servers are configured + # sharing the GPU with other programs (all off by default): unload the engine after this many idle seconds, + # only start it again when this much VRAM is free, and run this command first (e.g. to unload another + # server's model); the next request after an unload starts the engine again + self.idle_unload_s = 0 + self.min_free_vram_mib = 0 + self.before_load = None + self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none) + self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False + self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) + + tokenizer.encode("<|endoftext|>", parse_special=True)) + + def loaded(self) -> bool: + return not hasattr(self.engine, "alive") or self.engine.alive() + + def set_aliases(self, aliases) -> None: + """#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias. + ValueError for anything else.""" + if aliases is None: + aliases = [] + if isinstance(aliases, str): + aliases = aliases.split(",") + if not isinstance(aliases, list) or not all(isinstance(x, str) for x in aliases): + raise ValueError(f"aliases={aliases!r}: expected a list of model names") + names = [] + for x in (x.strip() for x in aliases): + if x and x != self.model and x not in names: + names.append(x) + self.aliases = names + + def model_names(self) -> list[str]: + return [self.model, *self.aliases] + + def model_for(self, req) -> str: + """The name to answer with: the request's own when it is the model's name or an alias (#297), else the model's. + Other names are still served, as before.""" + asked = req.get("model") if isinstance(req, dict) else None + return asked if isinstance(asked, str) and asked in self.aliases else self.model + + def reasoning_budget(self, req) -> int | None: + """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the + config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for + anything that is not a whole number.""" + value = (req or {}).get("reasoning_budget_tokens") if isinstance(req, dict) else None + if value is None: + value = self.reasoning_budget_tokens + if isinstance(value, float) and value.is_integer(): + value = int(value) + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"reasoning_budget_tokens={value!r}: expected a whole number of tokens (0: no budget)") + return value if value > 0 else None + + def _vision_down(self) -> bool: + return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive() + + def free_vram_mib(self) -> int | None: + """Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't + be read (then nothing is refused).""" + try: + if getattr(self, "backend", None) == "hip": + from serve.telemetry import free_vram_mib + return free_vram_mib(int(getattr(self, "gpu_index", 0) or 0), amd=True) + from serve.telemetry import _Nvml + nv = _Nvml(int(getattr(self, "gpu_index", 0) or 0)) + if not nv.ok(): + return None + m = nv.Mem() + if nv.lib.nvmlDeviceGetMemoryInfo(nv.dev, ctypes.byref(m)) != 0: + return None + return int(m.free >> 20) + except Exception: + return None + + def ensure_loaded(self): + """Start the engine if it is not running (unloaded, or it died - issue #27), after the before_load hook and + the free-VRAM check. The caller holds self.fifo.""" + if self.loaded() and not self._vision_down(): + return + if self.before_load: + cmd = self.before_load + print(f"[strata] before loading: {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True) + try: + subprocess.run(cmd, shell=isinstance(cmd, str), timeout=120, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError) as e: + print(f"[strata] the before_load command failed ({e}); loading anyway", flush=True) + if self.min_free_vram_mib: + free = self.free_vram_mib() + deadline = time.time() + 15 # memory another process just gave back can take a moment + while free is not None and free < self.min_free_vram_mib and time.time() < deadline: + time.sleep(0.5) + free = self.free_vram_mib() + if free is not None and free < self.min_free_vram_mib: + raise GpuBusy(f"the GPU is in use by another program: {free} MiB of VRAM free, the model needs " + f"{self.min_free_vram_mib} (min_free_vram_mib) - it stays unloaded until that is free") + if self._vision_down(): # first, as at a start: a GPU encoder takes its VRAM before + print("[strata] starting the vision encoder again ...", flush=True) # the engine sizes its cache + self.vision.restart() + if self.loaded(): + return + if getattr(self.engine, "unloaded", False): + print("[strata] loading the model again (it was unloaded) ...", flush=True) + else: + code = self.engine.exit_code() if hasattr(self.engine, "exit_code") else None + print(f"[strata] the engine had stopped (exit code {code}); starting it again " + "(a minute or two) ...", flush=True) + self.engine.restart() + print("[strata] the engine is running again", flush=True) + + def load(self): + """POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy).""" + # a request is on its way: the idle thread must not unload between this and the request's own start + self.last_request_at = time.time() + if self.loaded() and not self._vision_down(): + return + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() + with self.fifo: + loading = time.perf_counter() + if trace is not None: + with self.status_lock: + trace["queue_s"] += round(loading - waiting, 3) + trace["state"] = "loading" + try: + self.ensure_loaded() + finally: + if trace is not None: + with self.status_lock: + trace["load_s"] += round(time.perf_counter() - loading, 3) + trace["state"] = "queued" + + def unload(self, idle_for: float | None = None) -> str: + """Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or + with idle_for: one ran more recently than that) or "unsupported".""" + if not hasattr(self.engine, "unload"): + return "unsupported" + if not self.fifo.acquire(blocking=False): + return "busy" + try: + if not self.engine.alive(): + return "not loaded" + with self.status_lock: + if self.status.get("busy") or self.status.get("queued"): + return "busy" + if idle_for is not None and time.time() - (self.last_request_at or self.started_at) < idle_for: + return "busy" + self.engine.unload() + if self.vision is not None and hasattr(self.vision, "unload"): + self.vision.unload() + print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; " + "the next request loads it again", flush=True) + return "unloaded" + finally: + self.fifo.release() + + def start_idle_unload(self): + if not self.idle_unload_s or not hasattr(self.engine, "unload"): + return + print(f"[strata] the model unloads after {self.idle_unload_s} s without requests", flush=True) + + def loop(): + while True: + time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4))) + try: + self.unload(idle_for=self.idle_unload_s) + except EngineStuck as e: # tried again at the next turn; the thread keeps running + print(f"[strata] idle unload: {e}", flush=True) + threading.Thread(target=loop, daemon=True).start() + + def set_shared(self, defaults) -> dict: + """The Chat settings every client gets for what it leaves out; {} / None = clients use their own again.""" + self.shared = clean_shared_defaults(defaults) + if self.shared_path: + try: + if self.shared: + Path(self.shared_path).write_text(json.dumps(self.shared, indent=1), encoding="utf-8") + else: + Path(self.shared_path).unlink(missing_ok=True) + except OSError as e: + print(f"[strata] could not save the shared settings: {e}", flush=True) + return self.shared + + def with_shared(self, req: dict, api: str) -> dict: + """The request with the shared thinking level and max tokens filled in where it has none of its own.""" + s = self.shared + if not s: + return req + req = dict(req) + if "max_tokens" in s and not req.get("max_tokens") and not req.get("max_completion_tokens"): + req["max_tokens"] = s["max_tokens"] + effort = s.get("reasoning_effort") + if effort: + if api == "openai": + ctk = req.get("chat_template_kwargs") if isinstance(req.get("chat_template_kwargs"), dict) else {} + if not req.get("reasoning_effort") and not req.get("reasoning") and \ + "enable_thinking" not in ctk and "reasoning_effort" not in ctk: + req["reasoning_effort"] = effort + elif not req.get("thinking") and not req.get("output_config"): + if effort == "none": + req["thinking"] = {"type": "disabled"} + else: + req["output_config"] = {"effort": effort} + return req + + def start_telemetry(self): + """The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too.""" + if getattr(self, "telemetry", None) is None: + from serve.telemetry import Telemetry + self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(), + "prefill_tok_s_mean": self._prefill_tok_s_mean()}, + gpu_index=int(getattr(self, "gpu_index", 0) or 0), + gpu_indices=getattr(self, "gpu_indices", None), + amd=getattr(self, "backend", None) == "hip") + + def _tok_s(self): + """tok/s over the last RATE_WINDOW_S seconds. Returns 0.0 while nothing is generating.""" + with self.status_lock: + s = dict(self.status) + rate = list(self.rate) + if not s.get("busy") or not s.get("first_token"): + return 0.0 + now = time.time() + newest = rate[-1] if rate else None + oldest = next(((t, g) for t, g in rate if now - t <= RATE_WINDOW_S), None) + if newest and oldest and newest[0] - oldest[0] >= RATE_MIN_SPAN_S: + return max(0.0, (newest[1] - oldest[1]) / (newest[0] - oldest[0])) + return s["generated"] / max(RATE_MIN_SPAN_S, now - s["first_token"]) + + def _tok_s_mean(self): + """The whole-request mean since the first token (the old formula), kept so the two can be compared.""" + with self.status_lock: + s = dict(self.status) + if not s.get("busy") or not s.get("first_token"): + return 0.0 + return s["generated"] / max(1e-6, time.time() - s["first_token"]) + + def _prefill_tok_s_mean(self): + """Engine-reported mean over newly read tokens, excluding the cached prefix.""" + with self.status_lock: + reading = self.status.get("busy") and self.status.get("first_token") is None + return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0 + + def begin_request(self, path, req): + """#332: a monitor record for this request, or None when the monitor is off (nothing is kept then).""" + if not self.api_monitor: + return None + raw = json.dumps(req, ensure_ascii=False, indent=2) + record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model, + "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")), + "response_format": (req.get("response_format") or {}).get("type") + if isinstance(req.get("response_format"), dict) else None, + "input": raw[:262144], "input_truncated": len(raw) > 262144, + "output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False, + "queue_s": 0.0, "load_s": 0.0, "first_token_s": None, + "_clock": time.perf_counter()} + with self.status_lock: + self.api_requests.append(record) + self.request_trace.record = record + return record + + def request_records(self, request_id=None): + with self.status_lock: + records = list(self.api_requests) + if request_id: + record = next((r for r in records if r["id"] == request_id), None) + if record is None: + return None + return {k: v for k, v in record.items() if not k.startswith("_")} + return [{k: v for k, v in r.items() + if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")} + | {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))} + for r in reversed(records)] + + def metrics(self, all_requests=False) -> dict: + """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and + the hardware (with a minute of history per series).""" + with self.status_lock: + s = dict(self.status) + hist = list(self.history) + totals = dict(self.totals) + now = time.time() + progress = getattr(self.engine, "progress", None) + if s.get("busy") and s.get("first_token") is None: + state = "reading" + elif s.get("busy"): + state = "generating" + elif not self.loaded(): + state = "unloaded" + else: + state = "idle" + live = {"state": state, "queued": s.get("queued", 0), "phase": s.get("phase") if s.get("busy") else None, + "prompt_tokens": s.get("prompt_tokens") if s.get("busy") else None, + "prompt_read": None, "prompt_total": None, "generated": s.get("generated") if s.get("busy") else None, + "max_tokens": s.get("max_tokens") if s.get("busy") else None, + "elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None, + "tok_s": round(self._tok_s(), 1) if state == "generating" else None, + "tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None, + "prefill_tok_s_mean": getattr(self.engine, "prefill_tok_s_mean", None) if s.get("busy") else None, + "tok_s_window_s": RATE_WINDOW_S if state == "generating" else None} + if state == "reading" and progress: + live["prompt_read"], live["prompt_total"] = progress + engine = {"model": self.model, "max_context": self.engine.max_context, "images": self.vision is not None, + **dict(getattr(self.engine, "info", {}) or {})} + tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} + return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12], + "requests_kept": len(hist), "totals": totals, "hardware": tel["now"], + "hardware_static": + tel["static"], "history": tel["history"], "time": now} + + def v1_status(self) -> dict: + """GET /v1/status: what this server is and does, for a client that would rather ask than guess (a front-end + that polls its OpenAI-compatible server's status, collabosm's for one): the model and its window, images, + the APIs, what is running, and the last request's timings in llama.cpp's names. /metrics has the rest.""" + with self.status_lock: + s, totals = dict(self.status), dict(self.totals) + last_t, last_at = (dict(self.last_timings) if self.last_timings else None), self.last_request_at + tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "static": {}} + hw, static = tel.get("now") or {}, tel.get("static") or {} + + def scaled(v, unit, digits=0): + return round(v / unit, digits) if isinstance(v, (int, float)) else None + + busy, ctx = bool(s.get("busy")), self.engine.max_context + images = self.vision is not None + return { + "service": "strata", "model": self.model, + "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"), + "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", + "constrained_decoding": False, "stream_buffered": True}, + "engine": (getattr(self.engine, "info", {}) or {}).get("version"), + "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at), + "cache_max_tokens": ctx, + "context": {"native": ctx, "max_positions": ctx}, + "concurrency": {"serving": 1, "requested": 1}, # one request at a time; more wait their turn + "dialects": ["/v1/chat/completions", "/v1/messages"], + "vision": {"enabled": images, "available": images, "error": None}, + "activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0), + "last_request_at": int(last_at) if last_at else None}, + "last_timings": last_t, + "machine": { + "at": int(time.time()), + "gpu": {"name": static.get("gpu_name"), "used_mib": scaled(hw.get("gpu_mem_used"), 2 ** 20), + "total_mib": scaled(hw.get("gpu_mem_total"), 2 ** 20), "util_pct": hw.get("gpu_util"), + "temp_c": hw.get("gpu_temp"), "power_w": hw.get("gpu_power")} if static.get("gpu_name") else None, + "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), + "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + + def prepare(self, messages, tools, kwargs, max_new=None): + """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited": + the rest of the context.""" + prompt = self.template.render(messages, tools=tools, **kwargs) + ids = self.tok.encode(prompt, parse_special=True) + self.embeddings.path = None + images = images_of(messages) + if images: + if self.vision is None: + raise ValueError("this server was started without the vision encoder (run setup again and choose " + "'vision'), so it cannot read images") + pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0] + start = self.tok.encode(VISION_START, parse_special=True)[0] + # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not + # run on the GPU at the same time - an encode during a running request left that request stuck at + # "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the + # same FIFO as the requests. + with self.fifo: + encoded = [self.vision.encode(src) for src in images] + # one <|image_pad|> per image -> one per image token. Only the markers the template writes for an image + # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs, + # #150) is kept as plain text, or it took an image's place and the counts no longer matched. + literal = self.tok.encode(IMAGE_PAD, parse_special=False) + out, k = [], 0 + for j, t in enumerate(ids): + if t == pad and j > 0 and ids[j - 1] == start and k < len(encoded): + out += [pad] * encoded[k][1] + k += 1 + elif t == pad: + out += literal + else: + out.append(t) + if k != len(encoded): + raise ValueError("the prompt and its images do not match") + ids = out + combined = self.vision.dir / f"req-{uuid.uuid4().hex[:12]}.sve" + with open(combined, "wb") as f: + for path, _ in encoded: + f.write(path.read_bytes()) + self.embeddings.path = combined + if self.engine.max_context <= 0: # #344: (re)starting, not a prompt that is too long + raise EngineStarting("the engine is starting (a minute or two); try again shortly") + room = self.engine.max_context - CTX_SLACK - len(ids) + if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1): + if room < 1: + raise ValueError(f"prompt ({len(ids)} tokens) leaves no room to answer in the context " + f"({self.engine.max_context}); requests are never truncated") + max_new = room + elif max_new > room: + if not self.fit_max_tokens: + raise ValueError(f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context " + f"({self.engine.max_context}); requests are never truncated") + max_new = max(1, room) # --fit-max-tokens: a shorter completion beats a 400 + return ids, kwargs.get("enable_thinking", True) is not False, max_new + + def _note(self, n, evs): + with self.status_lock: + s = self.status + s["generated"] = n + if s.get("first_token") is None: + s["first_token"] = time.time() + self.rate.append((time.time(), n)) # the live rate's window over the last RATE_WINDOW_S + for ev in evs: + if ev.kind == "reasoning": + s["phase"] = "thinking" + elif ev.kind == "content": + s["phase"] = "answering" + elif ev.kind == "tool_start": + s["phase"], s["tool"] = f"writing a tool call: {ev.call.name}", ev.call.name + elif ev.kind == "tool_call": + s["phase"] = "tool call complete" + s["tail"] = ((s.get("tail") or "") + (ev.text or ""))[-600:] + + def _progress(self, last_print, every=1.0): + """A progress line in the server window every `every` seconds while a request runs.""" + now = time.time() + if now - last_print < every: + return last_print + with self.status_lock: + s = dict(self.status) + el = now - s.get("started", now) + if s.get("first_token") is None: + pr = getattr(self.engine, "progress", None) # (position reached, prompt tokens): a reused prefix counts + done = f"{pr[0]:,} of {pr[1]:,}" if pr and pr[1] else f"{s.get('prompt_tokens', 0):,}" # as read (#29) + print(f"[strata] reading the prompt: {done} tokens, {el:.0f} s so far", flush=True) + else: + rate = s["generated"] / max(1e-6, now - s["first_token"]) + print(f"[strata] {s['phase']}: {s['generated']} of max {s.get('max_tokens')} tokens, {rate:.1f} tok/s, " + f"{el:.0f} s", flush=True) + return now + + def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]: + """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).""" + budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by default + defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps + if defaults: # the request's own fields win (explicit 0 stays greedy) + req_values = {k: v for k, v in (sampling or {}).items() if v is not None} + sampling = {**defaults, **req_values} + parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True) + detok, n, finish = Detokenizer(self.tok), 0, "length" + timings, before = None, None # this request's timings; the engine's `last` before it + raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text) + emb = getattr(self.embeddings, "path", None) + # Identity token: only a DONE line replaces engine.last, so a request that died, errored or was + # disconnected must not have the PREVIOUS request's decode figures recorded as its own. + engine_last0 = getattr(self.engine, "last", None) + trace = getattr(self.request_trace, "record", None) + waiting = time.perf_counter() + with self.status_lock: + self.status["queued"] += 1 + try: + with self.fifo: + try: + with self.status_lock: + if trace is not None: + trace["queue_s"] += round(time.perf_counter() - waiting, 3) + trace["state"] = "generating" + self.status["queued"] -= 1 + # issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing + self.ensure_loaded() + with self.status_lock: + self.status.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids), + generated=0, started=time.time(), first_token=None, tool=None, tail="", + max_tokens=max_new) + self.last_request_at = time.time() + self.rate.clear() # the previous request's samples must not leak into this one + before = getattr(self.engine, "last", None) + last_print = time.time() + prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count) + while True: + gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \ + else self.engine.generate(prompt, max_new - n, sampling, cancel) + seg, wrap = [], False # this pass's tokens; the budget is reached + try: + for t in gen: + if t is None: # heartbeat while the engine is quiet + last_print = self._progress(last_print) + yield "ping", None + continue + n += 1 + if trace is not None and trace["first_token_s"] is None: + with self.status_lock: + trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3) + if t in self.stop_ids: + finish = "stop" + raw_ids.append(t) + break + raw_ids.append(t) + seg.append(t) + evs = parser.feed(detok.push(t)) + self._note(n, evs) + last_print = self._progress(last_print) + for ev in evs: + yield "event", ev + if budget and parser.state == "reasoning": + thought += 1 + # at a clean point: no tag held back, no character split across tokens + if thought >= budget and not parser.buf and not detok.pending(): + wrap = True + break + except EngineDied as e: + finish = "error" + note = self.engine.death_note() if hasattr(self.engine, "death_note") else "" + log = getattr(self.engine, "log_path", None) + print(f"[strata] {e}. {note} The next request starts the engine again." + f"{' Its log: ' + log if log else ''}", flush=True) + raise + except ValueError as e: # the engine's ERR line (it may have ended after it) + finish = "error" + print(f"[strata] the engine reported an error: {e}", flush=True) + raise + finally: + gen.close() # STOP+drain to THIS request's DONE while still holding the + # fifo, so a stop-token break can't leave the shared engine + # queue mid-drain for the next request to read as its own DONE + if not wrap or cancel.is_set(): + break + # #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a + # short wrap-up and ) and let it answer: the next pass's prompt is this one plus what + # was generated plus the wrap-up, so the engine continues from the prefix it already holds. + budget = None + extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + if max_new - n - len(extra) < 1: + break # no room left to answer: "length", as without a budget + print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking", + flush=True) + for t in extra: + n += 1 + raw_ids.append(t) + evs = parser.feed(detok.push(t)) + self._note(n, evs) + for ev in evs: + yield "event", ev + prompt = prompt + seg + extra + if cancel.is_set(): + finish = "cancel" + except GeneratorExit: # the client disconnected mid-stream + finish = "disconnect" + raise + finally: + # #266: settle this request's status, history and totals while still holding the fifo: once + # it is released the next request sets its own status, which this must not record or clear + with self.status_lock: + if self.status.get("busy"): + # only this request's DONE counts: same object means no DONE arrived (death, error, + # disconnect) + last = dict(getattr(self.engine, "last", {}) or {}) \ + if getattr(self.engine, "last", None) is not engine_last0 else {} + started = self.status.get("started", time.time()) + cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0) + loaded = str(cvec) not in ("0", "", "None") + hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None + self.history.append({ + "projection": (sampling or {}).get("experimental_speed_projection") is not False + if loaded else None, + "time": started, "duration_s": round(time.time() - started, 1), "finish": finish, + "prompt_tokens": len(ids), "reused": last.get("reused"), "output_tokens": n, + "engine_generated": last.get("generated"), + "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"), + "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1) + if n and last.get("generated") and last.get("decode_ms") else None, + "hit_rate": hit_rate, "ram_blobs": last.get("ram_blobs"), + "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"), + # #457: the speculative drafts from the DONE line (None: the engine did not say) + "drafts_offered": last.get("drafts_offered"), + "drafts_accepted": last.get("drafts_accepted")}) + t = self.totals + t["requests"] += 1 + t["prompt_tokens"] += len(ids) + t["reused"] += last.get("reused") or 0 + t["output_tokens"] += n + t["prompt_ms"] += last.get("prompt_ms") or 0.0 + t["decode_ms"] += last.get("decode_ms") or 0.0 + t["drafts_offered"] += last.get("drafts_offered") or 0 + t["drafts_accepted"] += last.get("drafts_accepted") or 0 + fresh = getattr(self.engine, "last", None) + if fresh is not None and fresh is not before: # the engine's clock for THIS request + timings = request_timings(len(ids), n, last) + self.last_timings = dict(timings, at=int(time.time())) if timings else None + self.last_request_at = time.time() + now = time.time() + el = now - self.status.get("started", now) + ft = self.status.get("first_token") + rate = n / max(1e-6, now - ft) if ft else 0.0 + hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else "" + print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) " + f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True) + if os.environ.get("STRATA_DEBUG") and raw_ids: + print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True) + self.status["busy"] = False + self.status.pop("tail", None) # #212: the answer's end is not kept once it is done + self.status.pop("tool", None) + finally: + if emb: + Path(emb).unlink(missing_ok=True) + for ev in parser.finish(): + yield "event", ev + yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), + "timings": timings} + + +def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None: + """One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock + (StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held. None when the + engine keeps no clock (MockEngine).""" + if last.get("prompt_ms") is None: + return None + cache_n = int(last.get("reused") or 0) + prompt_n, prompt_ms, decode_ms = max(0, prompt_tokens - cache_n), float(last["prompt_ms"]), float(last.get("decode_ms") or 0) + decoded = int(last.get("generated") or generated) # the engine's count gives its rate, as /metrics does + return {"cache_n": cache_n, "prompt_n": prompt_n, "prompt_ms": round(prompt_ms, 1), + "prompt_per_token_ms": round(prompt_ms / prompt_n, 3) if prompt_n else None, + "prompt_per_second": round(prompt_n / (prompt_ms / 1000), 1) if prompt_n and prompt_ms > 0 else None, + "predicted_n": generated, "predicted_ms": round(decode_ms, 1), + "predicted_per_token_ms": round(decode_ms / decoded, 3) if decoded else None, + "predicted_per_second": round(decoded / (decode_ms / 1000), 1) if decoded and decode_ms > 0 else None, + # the speculative drafts, as llama.cpp names them (from PR #83, @mikicvi): only when the engine reported them + **({"draft_n": int(last["drafts_offered"]), "draft_n_accepted": int(last["drafts_accepted"])} + if last.get("drafts_offered") is not None else {})} + + +def _debug_req(api, req, messages, tools, max_new, thinking, prompt_tokens): + """One compact line per request while diagnosing blank/empty turns. Set STRATA_DEBUG=1 to enable.""" + if not os.environ.get("STRATA_DEBUG"): + return + last = messages[-1] if messages else {} + body = last.get("content") + if isinstance(body, list): + body = " ".join(p.get("text", "") for p in body if isinstance(p, dict)) + preview = (str(body or "")[:80]).replace("\n", " ") + print(f"[strata] req {api}: msgs={len(messages)} tools={len(tools or [])} " + f"max_tokens_raw={req.get('max_tokens')!r}/{req.get('max_completion_tokens')!r} " + f"max_new={max_new} thinking={thinking} stream={bool(req.get('stream'))} " + f"prompt_tokens={prompt_tokens} last={last.get('role')!r}:{preview!r}", flush=True) + + +# ------------------------------------------------------------------------------------------------ MCP tool loop +def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, max_req, sampling, cancel, + mcp_names): + """Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds + the call and its result to the conversation and lets the model continue - up to `max_rounds` times. Yields what + Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and + one ("done", ...) at the very end with the output tokens of every round. + + `mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the + turn as always (the client answers it). MCP calls written in the same answer are then not run (their results + could not reach the model before the client's).""" + max_rounds = int(hub.settings["max_rounds"]) + total, rounds, done = 0, 0, None + messages = list(messages) + while True: + text, reasoning, calls, own_calls = [], [], [], 0 + for kind, x in svc.run(ids, thinking, tools, max_new, sampling, cancel): + if kind == "done": + done = x + continue + if kind == "event": + ev: Event = x + if ev.call is not None and ev.call.name in mcp_names: + if ev.kind == "tool_start": # the model has started writing a call: say so at once + yield "mcp", {"event": "start", "id": ev.call.id, "name": ev.call.name} + elif ev.kind == "tool_call": + calls.append(ev.call) + continue # its argument pieces are not streamed to the client + if ev.kind == "tool_call": + own_calls += 1 + elif ev.kind == "content": + text.append(ev.text) + elif ev.kind == "reasoning": + reasoning.append(ev.text) + yield kind, x + total += done["completion_tokens"] + run_them = calls and not own_calls and done["finish"] == "stop" and not cancel.is_set() + if run_them and rounds >= max_rounds: + yield "mcp", {"event": "limit", "max_rounds": max_rounds} + run_them = False + if not run_them: + for c in calls: # announced, never run: close them in the client's view + yield "mcp", {"event": "result", "id": c.id, "ok": False, "skipped": True, "text": "not run", + "chars": 0, "truncated": False, "ms": 0} + break + rounds += 1 + results = [] + for c in calls: + s, tool = hub.routes().get(c.name, (None, c.name)) + yield "mcp", {"event": "call", "id": c.id, "name": c.name, "server": s.name if s else None, + "tool": tool, "arguments": c.arguments, "round": rounds} + # The call runs on a thread while this generator keeps yielding heartbeats: they reach the client as + # keep-alives, which is how a client that went away (the web app's Stop) is noticed during a slow tool. + box = {} + + def work(c=c, box=box): + try: + box["r"] = hub.call(c.name, c.arguments, cancel) + except McpCancelled: + box["cancelled"] = True + worker = threading.Thread(target=work, daemon=True) + worker.start() + try: + while worker.is_alive(): + worker.join(1.0) + if worker.is_alive(): + yield "ping", None + except GeneratorExit: + cancel.set() # the client is gone: stop the tool too + raise + if "r" not in box: + break + r = box["r"] + print(f"[strata] tool {c.name}: {'ok' if r['ok'] else 'error'}, {r['chars']:,} characters in " + f"{r['ms'] / 1000:.1f} s{' (truncated for the model)' if r['truncated'] else ''}", flush=True) + results.append(r["text"]) + yield "mcp", {"event": "result", "id": c.id, **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} + if cancel.is_set() or len(results) < len(calls): + done = {**done, "finish": "cancel"} + break + messages.append({"role": "assistant", "content": "".join(text).strip(), + **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), + "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) + messages += [{"role": "tool", "content": r} for r in results] + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req) + yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)} + + +# ------------------------------------------------------------------------------------------------ OpenAI +def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None): + """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with + an empty delta and a `strata_mcp` field, which only the web app reads.""" + cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time()) + model = svc.model_for(req) + + def chunk(delta, finish=None): + return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} + + yield chunk({"role": "assistant", "content": ""}) + calls = 0 + streamed = {} # tool call id -> index, for calls sent piece by piece + finished = set() # ... and the ones whose final tool_call came (#211) + for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + elif kind == "mcp": + c = chunk({}) + c["strata_mcp"] = x + yield c + elif kind == "event": + ev: Event = x + if ev.kind == "reasoning" and ev.text: + yield chunk({"reasoning_content": ev.text}) + elif ev.kind == "content" and ev.text: + yield chunk({"content": ev.text}) + elif ev.kind == "tool_start": + streamed[ev.call.id] = calls + calls += 1 + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "id": ev.call.id, "type": "function", + "function": {"name": ev.call.name, "arguments": ""}}]}) + elif ev.kind == "tool_args": + yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "function": {"arguments": ev.text}}]}) + elif ev.kind == "tool_call" and ev.call.id in streamed: + finished.add(ev.call.id) + elif ev.kind == "tool_call": + yield chunk({"tool_calls": [{"index": calls, "id": ev.call.id, "type": "function", + "function": {"name": ev.call.name, + "arguments": json.dumps(ev.call.arguments, ensure_ascii=False)}}]}) + calls += 1 + else: + # a streamed call without its final tool_call is one the output ended inside: not "tool_calls" (#211) + whole = calls and streamed.keys() <= finished + finish = "tool_calls" if whole and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"]) + last = chunk({}, finish) + pt = x.get("prompt_tokens", len(ids)) # after MCP rounds: the last round's prompt + last["usage"] = {"prompt_tokens": pt, "completion_tokens": x["completion_tokens"], + "total_tokens": pt + x["completion_tokens"], + # the part of the prompt the conversation cache already held (OpenAI's field) + "prompt_tokens_details": {"cached_tokens": x.get("reused") or 0}} + if x.get("timings"): + last["timings"] = x["timings"] # llama.cpp's field: the speed its clients show + yield last + + +def _is_json(text: str) -> bool: + try: + json.loads(text) + return True + except ValueError: + return False + + +def openai_collect(chunks) -> dict: + content, reasoning, by_index, last, mcp = [], [], {}, None, [] + for c in chunks: + if c is None: # a heartbeat + continue + if c.get("strata_mcp"): + mcp.append(c["strata_mcp"]) + d = c["choices"][0]["delta"] + content.append(d.get("content") or "") + reasoning.append(d.get("reasoning_content") or "") + for tc in d.get("tool_calls") or []: # streamed calls arrive in pieces: merge them by index + cur = by_index.setdefault(tc.get("index", len(by_index)), {"id": None, "type": "function", + "function": {"name": "", "arguments": ""}}) + cur["id"] = tc.get("id") or cur["id"] + fn = tc.get("function") or {} + cur["function"]["name"] += fn.get("name") or "" + cur["function"]["arguments"] += fn.get("arguments") or "" + last = c + calls = [by_index[i] for i in sorted(by_index)] + if last["choices"][0]["finish_reason"] != "tool_calls": + calls = [c for c in calls if _is_json(c["function"]["arguments"])] # a call the output ended inside (#211) + msg = {"role": "assistant", "content": "".join(content) or None} + if "".join(reasoning): + msg["reasoning_content"] = "".join(reasoning) + if calls: + msg["tool_calls"] = calls + if mcp: + msg["strata_mcp"] = mcp + out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"], + "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}], + "usage": last["usage"]} + if last.get("timings"): + out["timings"] = last["timings"] + return out + + +def structured_chunks(chunks, validator): + """Buffer structured streams so a client never receives unvalidated content.""" + buffered = [] + heartbeat = time.monotonic() + try: + for chunk in chunks: + if chunk is not None: + buffered.append(chunk) + if chunk is None or time.monotonic() - heartbeat >= 1: + heartbeat = time.monotonic() + yield None + result = openai_collect(buffered) + choice = result["choices"][0] + content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + yield buffered[0] + delta = {"content": content} + if choice["message"].get("reasoning_content"): + delta["reasoning_content"] = choice["message"]["reasoning_content"] + yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} + yield buffered[-1] + finally: + chunks.close() + + +# ------------------------------------------------------------------------------------------------ Anthropic +def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel): + mid = "msg_" + uuid.uuid4().hex[:24] + yield "message_start", {"type": "message_start", "message": { + "id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [], + "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": len(ids), "output_tokens": 0}}} + index, open_kind, used_tool = -1, None, False + + def close(): + return ("content_block_stop", {"type": "content_block_stop", "index": index}) + + streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211) + for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel): + if kind == "ping": + yield None + continue + if kind == "event": + ev: Event = x + if ev.kind == "tool_args": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "input_json_delta", "partial_json": ev.text}} + continue + if ev.kind == "tool_call" and ev.call.id in streamed: + finished.add(ev.call.id) + continue + want = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use", "tool_start": "tool_use"}[ev.kind] + if ev.kind not in ("tool_call", "tool_start") and not ev.text: + continue + if ev.kind == "tool_start": + streamed.add(ev.call.id) + used_tool = True + if open_kind != want or want == "tool_use": + if open_kind is not None: + yield close() + index += 1 + open_kind = want + block = {"thinking": {"type": "thinking", "thinking": "", "signature": ""}, + "text": {"type": "text", "text": ""}, + "tool_use": {"type": "tool_use", "id": ev.call.id if ev.call else "", "name": + ev.call.name if ev.call else "", "input": {}}}[want] + yield "content_block_start", {"type": "content_block_start", "index": index, "content_block": block} + if want == "thinking": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "thinking_delta", "thinking": ev.text}} + elif want == "text": + yield "content_block_delta", {"type": "content_block_delta", "index": index, + "delta": {"type": "text_delta", "text": ev.text}} + elif ev.kind == "tool_start": + pass # its input follows as tool_args pieces + else: + used_tool = True + yield "content_block_delta", {"type": "content_block_delta", "index": index, "delta": { + "type": "input_json_delta", "partial_json": json.dumps(ev.call.arguments, ensure_ascii=False)}} + else: + if open_kind is not None: + yield close() + stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ + {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] + # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, + # which is cache_read_input_tokens (message_start could only say the whole prompt) + reused = min(x.get("reused") or 0, len(ids)) + yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, + "output_tokens": x["completion_tokens"]}} + yield "message_stop", {"type": "message_stop"} + + +def anthropic_collect(events) -> dict: + msg, blocks = None, [] + for item in events: + if item is None: # a heartbeat + continue + name, e = item + if name == "message_start": + msg = e["message"] + elif name == "content_block_start": + blocks.append(dict(e["content_block"])) + elif name == "content_block_delta": + d, b = e["delta"], blocks[-1] + if d["type"] == "text_delta": + b["text"] += d["text"] + elif d["type"] == "thinking_delta": + b["thinking"] += d["thinking"] + else: # input_json_delta pieces: parsed when complete + b["_json"] = b.get("_json", "") + d["partial_json"] + elif name == "content_block_stop" and blocks and "_json" in blocks[-1]: + b = blocks[-1] + try: + b["input"] = json.loads(b.pop("_json") or "{}") + except ValueError: # a call the output ended inside (#211): it has no input to give + blocks.pop() + elif name == "message_delta": + msg["stop_reason"] = e["delta"]["stop_reason"] + msg["usage"].update(e["usage"]) + msg["content"] = blocks + return msg + + +# ------------------------------------------------------------------------------------------------ HTTP +def make_handler(svc: Service): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.0" # SSE ends by closing the connection + + record = None # #332: this request's monitor record, if kept + watch_done = None # #430 #431: stops this request's disconnect watcher + + def log_message(self, fmt, *args): + pass + + def _watch_client(self, cancel: threading.Event) -> None: + """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing + until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up + usually still succeeds), so a dropped request kept the engine busy until its answer or the whole prompt + was done. Every 0.5 s: the socket readable with nothing to read (EOF) means the client closed it. A + request is HTTP/1.0 and fully read here, so no later bytes are expected - data is not a hang-up.""" + done = self.watch_done = threading.Event() + sock = self.connection + + def watch(): + while not done.wait(0.5) and not cancel.is_set(): + try: + readable, _, _ = select.select([sock], [], [], 0) + gone = bool(readable) and sock.recv(1, socket.MSG_PEEK) == b"" + except (ConnectionError, TimeoutError): + gone = True + except (OSError, ValueError): # the socket was closed here: the request has ended + return + if gone: + self._note(outcome="disconnected") + cancel.set() + return + + threading.Thread(target=watch, daemon=True, name="strata-client-watch").start() + + def _note(self, **values): + """#332: what the monitor shows about this request (nothing when the monitor is off).""" + if self.record is not None: + with svc.status_lock: + self.record.update(values) + + def _cors(self): + """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing + otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools.""" + if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"): + return + origin = (self.headers.get("Origin") or "").rstrip("/") + if "*" in svc.cors_origins: + allow = "*" + elif origin and origin in svc.cors_origins: + allow = origin + self.send_header("Vary", "Origin") + else: + return + self.send_header("Access-Control-Allow-Origin", allow) + self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization) + asked = self.headers.get("Access-Control-Request-Headers") + self.send_header("Access-Control-Allow-Headers", + asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta") + self.send_header("Access-Control-Max-Age", "600") + + def do_OPTIONS(self): + # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins + self.send_response(204) + self._cors() + self.send_header("Content-Length", "0") + self.end_headers() + + def _json(self, code, obj): + if self.record is not None: + with svc.status_lock: + self.record["http_status"] = code + raw = json.dumps(obj, ensure_ascii=False, indent=2) + self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144) + for key in ("error", "usage", "timings"): + if key in obj: + self.record[key] = obj[key] + body = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self._cors() + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _authorized(self) -> bool: + if not svc.api_key: + return True + auth = self.headers.get("Authorization", "") + given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "") + if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-time + return True + self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}}) + return False + + def do_GET(self): + path = self.path.split("?")[0].rstrip("/") + if path.startswith("/fonts/"): + # the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font + name = path[len("/fonts/"):] + f = ROOT / "serve" / "web" / "fonts" / name + if "/" in name or "\\" in name or not name.endswith(".woff2") or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", "font/woff2") + self.send_header("Cache-Control", "max-age=86400") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path.startswith("/web/"): + # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN + name = path[len("/web/"):] + types = {".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", + ".svg": "image/svg+xml"} + f = ROOT / "serve" / "web" / name + ext = os.path.splitext(name)[1] + if "/" in name or "\\" in name or ext not in types or not f.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = f.read_bytes() + self.send_response(200) + self.send_header("Content-Type", types[ext]) + self.send_header("Cache-Control", "no-cache") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if path == "/metrics": + if self._authorized(): + # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35) + self._json(200, svc.metrics(all_requests="requests=all" in self.path)) + return + if path == "/api/requests" and svc.api_monitor: + if self._authorized(): + request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0] + records = svc.request_records(request_id) + self._json(404 if records is None else 200, + {"error": {"message": "request no longer retained"}} if records is None else + records if request_id else {"requests": records, "retention": 100, "persistent": False, + "loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")}) + return + if path == "/settings": + if self._authorized(): + self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared}) + return + if path == "/mcp": + # the MCP servers, their state and tools (the web app's switch and Monitor card) + if self._authorized(): + self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0}) + return + if path == "" or (path == "/api-monitor" and svc.api_monitor): + body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + elif path in ("/health", "/api/health"): + self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model, + "images": svc.vision is not None, "api_key": bool(svc.api_key), + "loaded": svc.loaded(), "service": "strata"}) + elif path == "/status": + if not self._authorized(): # #212: it shows the end of the last answer + return + with svc.status_lock: + s = dict(svc.status) + now = time.time() + if s.get("busy"): + s["elapsed_s"] = round(now - s["started"], 1) + if s.get("first_token"): + s["tokens_per_s"] = round(svc._tok_s(), 1) + s["tokens_per_s_mean"] = round(svc._tok_s_mean(), 1) + for k in ("started", "first_token"): + s.pop(k, None) + self._json(200, s) + elif path in ("/v1/models", "/models"): + if self._authorized(): + loaded = svc.loaded() + model = {"id": svc.model, "object": "model", "status": {"value": "loaded"}, + "meta": {"n_ctx": svc.engine.max_context}, + "architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"], + "output_modalities": ["text"]}} + if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)): + model["status"] = {"value": "unloaded"} # like llama-server's router: listed, loads on use + loaded = True + if svc.aliases: # #297: the aliases, and each one listed under its own id + model["aliases"] = list(svc.aliases) + data = [model, *({**model, "id": x, "alias_of": svc.model} for x in svc.aliases)] + self._json(200, {"object": "list", "data": data if loaded else []}) + elif path == "/props": + if self._authorized(): + self._props() + elif path == "/slots": + if self._authorized(): + loaded = not hasattr(svc.engine, "alive") or svc.engine.alive() + with svc.status_lock: + busy = bool(svc.status.get("busy")) + slot = {"id": 0, "n_ctx": svc.engine.max_context, "is_processing": busy} + self._json(200, [slot] if loaded else []) + elif path == "/v1/status": + if self._authorized(): + self._json(200, svc.v1_status()) + else: + self._json(404, {"error": {"message": "not found"}}) + + def do_POST(self): + if not self._authorized(): + return + path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true + if path == "/settings": + self._settings() + return + if path == "/unload": # give the GPU back now (between requests) + try: + r = svc.unload() + except EngineStuck as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return + self._json(409 if r == "busy" else 200, {"status": r}) + return + if path == "/load": # load now, e.g. ahead of a request + try: + svc.load() + self._json(200, {"status": "loaded"}) + except GpuBusy as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + return + try: + req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + if not isinstance(req, dict): + raise ValueError("send a JSON object") + if path in ("/v1/load", "/v1/unload"): + if not self._own_page("the model can be loaded or unloaded"): + return + if req.get("model") not in (None, svc.model): + self._json(404, {"error": {"message": "model not found"}}) + return + if path == "/v1/unload": + result = svc.unload() + if result == "busy": + raise ModelBusy("a request is running or queued") + else: + if not svc.fifo.acquire(blocking=False): + raise ModelBusy("a request is running or queued") + try: + with svc.status_lock: + if svc.status.get("busy") or svc.status.get("queued"): + raise ModelBusy("a request is running or queued") + svc.ensure_loaded() + svc.last_request_at = time.time() + finally: + svc.fifo.release() + result = "loaded" + self._json(200, {"status": result, **svc.v1_status()}) + return + if path in ("/v1/chat/completions", "/v1/messages"): + self.record = svc.begin_request(path, req) + if path == "/v1/chat/completions": + self._openai(req) + elif path == "/v1/messages": + self._anthropic(req) + elif path == "/v1/messages/count_tokens": + self._count_tokens(req) + else: + self._json(404, {"error": {"message": "not found"}}) + except ValueError as e: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + except ModelBusy as e: + self._json(409, {"error": {"type": "model_busy", "message": str(e)}}) + except StructuredOutputError as e: + self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed", + "message": str(e)}}) + except (GpuBusy, EngineStarting) as e: + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + except EngineDied as e: # before the answer started (not streamed) + self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) + except EngineStuck as e: # an unload or restart that could not end the engine + self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + + except OSError: + self._note(outcome="disconnected") + raise # as before #332: the server's own handling + finally: + if self.watch_done is not None: + self.watch_done.set() + record = self.record + if record is not None: + with svc.status_lock: + record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3) + record["finished_at"] = time.time() + record["state"] = "error" if record.get("error") else record.get("outcome", "completed") + svc.request_trace.record = None + + def _props(self): + model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0] + if model not in svc.model_names(): + self._json(404, {"error": {"message": "model not found"}}) + return + if not svc.loaded() and not getattr(svc.engine, "unloaded", False): + self._json(503, {"error": {"message": "the engine is not running"}}) + return + defaults = {**svc.sampling_defaults, **svc.shared} + names = {"repetition_penalty": "repeat_penalty", "penalty_last_n": "repeat_last_n"} + params = {names.get(k, k): v for k, v in defaults.items() + if k in ("temperature", "top_p", "top_k", "min_p", "seed", "repetition_penalty", + "presence_penalty", "frequency_penalty", "penalty_last_n")} + params["n_predict"] = svc.shared.get("max_tokens", -1) + props = {"default_generation_settings": {"n_ctx": svc.engine.max_context, "params": params}, + "total_slots": 1, "model_alias": svc.model, "chat_template": svc.template.source, + "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"), + "is_sleeping": not svc.loaded()} + if getattr(svc.engine, "model_path", None): + props["model_path"] = svc.engine.model_path + version = getattr(svc.engine, "info", {}).get("version") + if version: + props["build_info"] = "Strata " + str(version) + self._json(200, props) + + def _own_page(self, what) -> bool: + """Only JSON (a form or a "simple" cross-site request can't send it without a CORS preflight, which this + server never grants) and no foreign Origin: a web page elsewhere must not change settings or run tools.""" + if not self.headers.get("Content-Type", "").startswith("application/json"): + self._json(415, {"error": {"message": "send application/json"}}) + return False + # The Origin must be this server's own address (host and port), or an origin the config trusts + # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*, + # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing. + origin = (self.headers.get("Origin") or "").rstrip("/") + if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \ + origin not in svc.trusted_origins: + self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the " + f"config's trusted_origins)"}}) + return False + return True + + def _settings(self): + # They change what every client gets, so only the app's own page may set them + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + if not self._own_page("settings can be changed"): + return + try: + req = json.loads(body or b"{}") + shared = svc.set_shared(req.get("defaults") if isinstance(req, dict) else None) + except ValueError as e: + self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}}) + return + print("[strata] other apps now use the Chat settings: " + ", ".join(f"{k}={v}" for k, v in shared.items()) + if shared else "[strata] other apps use their own settings again", flush=True) + self._json(200, {"shared": bool(shared), "defaults": shared}) + + def _sse(self): + self._note(http_status=200) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("X-Accel-Buffering", "no") # nginx and similar proxies pass each event at once + self._cors() + self.end_headers() + + def _capture(self, items, api): + """Retain bounded input/output for the monitor without changing the API response (the items as they + are when the monitor is off).""" + if self.record is None: + return items + return self._captured(items, api) + + def _captured(self, items, api): + try: + for item in items: + if item is not None: + if api == "openai": + delta = item["choices"][0]["delta"] + content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "") + usage, timings = item.get("usage"), item.get("timings") + else: + _, event = item + delta = event.get("delta", {}) + content, reasoning = delta.get("text", ""), delta.get("thinking", "") + usage, timings = event.get("usage"), None + with svc.status_lock: + for name, value in (("output", content), ("reasoning", reasoning)): + if value: + combined = self.record[name] + value + self.record[name] = combined[:262144] + self.record[name + "_truncated"] |= len(combined) > 262144 + if usage: + self.record["usage"] = usage + if timings: + self.record["timings"] = timings + yield item + finally: + items.close() + + def _openai(self, req): + req = svc.with_shared(req, "openai") + messages, tools, kw = openai_to_messages(req) + messages, validator = prepare_format(req.get("response_format"), messages) + if validator is not None and (tools or req.get("strata_mcp")): + raise ValueError("structured response_format with tools/MCP is not supported") + svc.load() + max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest + use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) + own = {t.get("name") for t in tools or []} + if use_mcp: + if not self._own_page("MCP tools can be used"): # tools run with the user's rights on this PC + return + svc.mcp.wait(10) # servers still starting (only right after start) + extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clash + use_mcp = bool(extra) + tools = (tools or []) + extra or None + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + _debug_req("openai", req, messages, tools, max_new, thinking, len(ids)) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel, + {t["name"] for t in extra}) if use_mcp else None + chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run) + if validator is not None: + chunks = structured_chunks(chunks, validator) + chunks = self._capture(chunks, "openai") + if not req.get("stream"): + return self._json(200, openai_collect(chunks)) + self._sse() + try: + for c in chunks: + if c is None: + self.wfile.write(b": keep-alive\n\n") # an SSE comment: clients ignore it + else: + self.wfile.write(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\n\n") + self.wfile.flush() + self.wfile.write(b"data: [DONE]\n\n") + except OSError: + self._note(outcome="disconnected") + cancel.set() # client went away: stop the engine + chunks.close() + except EngineDied as e: # mid-stream: say so, then end the stream properly + err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except StructuredOutputError as e: + err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}} + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + except ValueError as e: # the engine's ERR after the stream started: the + err = {"error": {"type": "server_error", "message": str(e)}} # headers are sent, so no 400 now + self._note(error=err["error"]) + self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n") + + def _count_tokens(self, req): + """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would + read for the same request, rendered and tokenized - the model does not run.""" + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + prompt = svc.template.render(messages, tools=tools, **kw) + self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))}) + + def _anthropic(self, req): + svc.load() + req = svc.with_shared(req, "anthropic") + messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked) + max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context + svc.reasoning_budget(req) # a bad value is a 400 before anything is sent + ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new) + _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids)) + cancel = threading.Event() + self._watch_client(cancel) # #430 #431 + events = anthropic_events(svc, req, ids, thinking, tools, max_new, cancel) + events = self._capture(events, "anthropic") + if not req.get("stream"): + return self._json(200, anthropic_collect(events)) + self._sse() + try: + for item in events: + if item is None: + self.wfile.write(b": keep-alive\n\n") + else: + name, e = item + self.wfile.write(f"event: {name}\n".encode() + b"data: " + + json.dumps(e, ensure_ascii=False).encode() + b"\n\n") + self.wfile.flush() + except OSError: + self._note(outcome="disconnected") + cancel.set() + events.close() + except EngineDied as e: # mid-stream: Anthropic's error event + err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}} + self._note(error=err["error"]) + self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") + except ValueError as e: # the engine's ERR after the stream started + err = {"type": "error", "error": {"type": "api_error", "message": str(e)}} + self._note(error=err["error"]) + self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n") + + return Handler + + +class Server(ThreadingHTTPServer): + # On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on + # either one (a forgotten second start of run-.bat). Without it the second start fails loudly instead. + allow_reuse_address = os.name != "nt" + + def handle_error(self, request, client_address): + if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace + super().handle_error(request, client_address) + + +def warn_tight_ram(arena_mib) -> None: + """The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the + system, the engine and this server, Linux ends the engine mid-answer when memory runs out (issue #27) and Windows + pages to disk; say so at start instead of after a lost answer.""" + if not isinstance(arena_mib, int) or arena_mib <= 0: + return + try: + import psutil + total = psutil.virtual_memory().total + except Exception: # noqa: BLE001 - psutil is optional here + return + left = total / 2**30 - arena_mib / 1024 + if left < 6: + print(f"[strata] WARNING: RAM is tight - the model's experts take {arena_mib / 1024:.1f} GB of this PC's " + f"{total / 2**30:.0f} GB, leaving {left:.1f} GB for everything else. " + + ("Linux may stop the engine in the middle of an answer. " if os.name != "nt" else + "Windows will slow down (paging to disk). ") + + "Close other programs, or run START-HERE --setup and pick a smaller size (Q2_0 / IQ2_XS).", flush=True) + + +def lan_addresses() -> list[str]: + """This PC's IPv4 addresses on its networks (what another device types in), without loopback/link-local.""" + import socket + first, ips = None, set() + try: # the address of the default route; sends nothing (UDP) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("10.255.255.255", 1)) + first = s.getsockname()[0] + except OSError: + pass + try: + for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): + ips.add(info[4][0]) + except OSError: + pass + ok = lambda ip: ip and not ip.startswith(("127.", "169.254.", "0.")) + return ([first] if ok(first) else []) + sorted(ip for ip in ips if ok(ip) and ip != first) + + +def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: + svc.start_telemetry() + httpd = Server((host, port), make_handler(svc)) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd + + +def origins_of(value, key: str, wildcard: bool) -> list[str]: + """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path; + "*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant.""" + if value is None or value == "" or value == []: + return [] + items = [value] if isinstance(value, str) else value + if not isinstance(items, list) or not all(isinstance(x, str) for x in items): + raise SystemExit(f"[strata] {key}: expected an origin or a list of origins") + out = [] + for x in items: + x = x.strip().rstrip("/") + if x == "*" and wildcard: + out.append(x) + continue + scheme, sep, rest = x.partition("://") + if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest: + raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com" + + ("" if wildcard else " (no wildcards here)")) + out.append(x) + return out + + +SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection") + + +def clean_shared_defaults(d) -> dict: + """The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one.""" + if d is None: + return {} + if not isinstance(d, dict): + raise ValueError("defaults must be an object") + out = {} + for key, value in d.items(): + if value is None or value == "": + continue + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key == "reasoning_effort": + if value not in ("none", "low", "medium", "high"): + raise ValueError("reasoning_effort: none, low, medium or high") + elif key == "temperature": + if not number or not 0 <= value <= 2: + raise ValueError("temperature: 0..2") + elif key == "top_p": + if not number or not 0 < value <= 1: + raise ValueError("top_p: 0 < top_p <= 1") + elif key == "top_k": + if not number or value != int(value) or not 1 <= value <= 64: + raise ValueError("top_k: an integer 1..64") + value = int(value) + elif key in ("seed", "max_tokens"): + if not number or value != int(value) or value <= 0: + raise ValueError(f"{key}: a positive integer") + value = int(value) + elif key == "experimental_speed_projection": + if not isinstance(value, bool): + raise ValueError("experimental_speed_projection: true or false") + else: + raise ValueError(f"unknown setting {key!r}") + out[key] = float(value) if key in ("temperature", "top_p") else value + return out + + +def sampling_defaults_from_config(cfg: dict) -> dict: + """The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, so + a plain client gets configured sampling instead of greedy. Supported: temperature, top_p, top_k, min_p, + presence_penalty, repetition_penalty, frequency_penalty, penalty_last_n, seed. The request's own fields + always win - an explicit temperature=0 still means greedy, a field set to null falls back to the default. + A bad value refuses to start the server (a typo'd config should not quietly change sampling); unknown keys + are named at startup and ignored.""" + out = {} + for key, value in (cfg.get("sampling") or {}).items(): + if value is None: + continue + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if key == "temperature": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.temperature={value!r}: expected a number >= 0 (0 = greedy)") + out[key] = float(value) + elif key == "top_p": + if not number or not 0 < value <= 1: + raise SystemExit(f"[strata] config sampling.top_p={value!r}: expected 0 < top_p <= 1") + out[key] = float(value) + elif key == "min_p": + if not number or not 0 <= value <= 1: + raise SystemExit(f"[strata] config sampling.min_p={value!r}: expected 0 <= min_p <= 1") + out[key] = float(value) + elif key == "top_k": + if not number or value != int(value) or not 1 <= value <= 64: + raise SystemExit(f"[strata] config sampling.top_k={value!r}: the sampled path takes an integer 1..64") + out[key] = int(value) + elif key == "presence_penalty": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.presence_penalty={value!r}: expected a number >= 0") + out[key] = float(value) + elif key == "frequency_penalty": + if not number or value < 0: + raise SystemExit(f"[strata] config sampling.frequency_penalty={value!r}: expected a number >= 0") + out[key] = float(value) + elif key == "repetition_penalty": + if not number or value <= 0: + raise SystemExit(f"[strata] config sampling.repetition_penalty={value!r}: expected a number > 0 (1 = off)") + out[key] = float(value) + elif key == "penalty_last_n": + if not number or value != int(value) or value < 0: + raise SystemExit(f"[strata] config sampling.penalty_last_n={value!r}: expected a non-negative integer") + out[key] = int(value) + elif key == "seed": + if not number or value != int(value) or value <= 0: + raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer") + out[key] = int(value) + elif key == "experimental_speed_projection": + if not isinstance(value, bool): + raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or " + "false (the default for requests that leave it out, when the engine has the vector)") + out[key] = value + else: + print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True) + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--engine", choices=["mock", "strata"], default="mock") + ap.add_argument("--config", help="strata engine config (JSON: exe, args, cwd, tokenizer, model_name), " + "written by setup.py") + ap.add_argument("--host", default=None, + help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " + "on your network (set an API key); also \"host\" in the config") + ap.add_argument("--script", action="append", + help="the mock engine's answer (default: a short greeting); given more than once, requests get " + "them in turn and the last one repeats") + ap.add_argument("--port", type=int, default=8095) + ap.add_argument("--gpu", help="the GPU to run on, as nvidia-smi numbers them, or several for a layer split " + "(\"0,2\"; also \"gpu\" in the config)") + ap.add_argument("--tokenizer", default=str(ROOT / "pack/full/tokenizer"), + help="pack tokenizer directory (falls back to a byte tokenizer if absent)") + ap.add_argument("--open", action="store_true", help="open the local page in the browser once the model is ready") + ap.add_argument("--fit-max-tokens", action="store_true", + help="clamp max_tokens to the remaining context instead of rejecting the request " + "(default: reject with 400, like llama.cpp; also \"fit_max_tokens\": true in the config)") + ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""), + help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY") + ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": " + "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in " + "the config)") + ap.add_argument("--lazy", action="store_true", help="start the text-only API unloaded; load on first request") + ap.add_argument("--api-monitor", action="store_true", + help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in " + "memory (also \"api_monitor\": true in the config; off by default)") + ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS", + help="unload the model after this many seconds without requests, so other programs (games, other " + "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" " + "in the config; default: never)") + ap.add_argument("--min-free-vram-mib", type=int, default=None, + help="load an unloaded model only when this much VRAM is free, else answer 503 (also " + "\"min_free_vram_mib\" in the config; default: always load)") + ap.add_argument("--before-load", help="a command run before the model is loaded again (e.g. to unload another " + "server's model; also \"before_load\" in the config, a string or a list)") + a = ap.parse_args() + cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM + if a.gpu is not None: + cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu + a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can + try: # before the minutes of loading: is the port free? + Server((a.host, a.port), BaseHTTPRequestHandler).server_close() + except OSError: + ap.error(f"port {a.port} is already in use - is Strata (or another server) already running? " + f"Close it, or start this one with a different --port") + if cfg.get("tokenizer"): + a.tokenizer = cfg["tokenizer"] + tok = ByteTokenizer() + tpath = Path(a.tokenizer) + if a.engine == "strata" and not (tpath / "vocab.json").exists(): + ap.error(f"the model's tokenizer is missing ({tpath / 'vocab.json'}); run setup again") + if (tpath / "vocab.json").exists(): + import strata_tokenizer as ST + vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8")) + tokens = [None] * len(vocab) + for t, i in vocab.items(): + tokens[i] = t + merges = (tpath / "merges.txt").read_text(encoding="utf-8").split("\n") + types = json.loads((tpath / "token_type.json").read_text()) + tok = ST.Tokenizer(tokens, merges, types) + hub = hub_from_config(cfg, a.mcp_config) # before the minutes of loading: a bad entry stops here + if a.engine == "strata": + if not cfg: + ap.error("--engine strata needs --config") + vision = None + env = child_env(cfg) + sampling_defaults = sampling_defaults_from_config(cfg) + if sampling_defaults: + pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items()) + print(f"[strata] sampling defaults from the config: {pretty}", flush=True) + lazy = a.lazy or cfg.get("lazy_load") is True + if lazy and cfg.get("vision"): + ap.error("lazy loading is text-only; disable vision in the config") + if cfg.get("vision"): + print("loading the vision encoder ...", flush=True) + # relative paths are the config's cwd's, as for the engine below + vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v)) + if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v) + for k, v in cfg["vision"].items()} + vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, + env=vision_env(cfg, env)) + print("model unloaded; the first request loads it ..." if lazy else + "loading the model (the first start takes a minute or two) ...", flush=True) + if len(gpu_list(cfg)) > 1: + print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({cfg.get('layer_split') or 'auto'})", flush=True) + # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing + # it is told about (WinError 2), so it is made absolute here + exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"])) + engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) + warn_tight_ram(engine.info.get("arena_mib")) + else: + engine, vision, sampling_defaults = MockEngine(tok, a.script or [ + "Thinking about it.\n\nHello from the mock engine."]), None, {} + # the model's own chat template (exported with its tokenizer), else the original model's + tpl = tpath / "chat_template.jinja" + svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"), + model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision, + sampling_defaults=sampling_defaults, + fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) + try: + svc.set_aliases(cfg.get("aliases")) # #297: other names the model answers to + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + if svc.aliases: + print(f"[strata] model aliases: {', '.join(svc.aliases)}", flush=True) + if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key=" + for i, x in enumerate(sys.argv)): + # #213: an empty key would switch authentication off without a word + print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out", + file=sys.stderr) + return 2 + svc.api_key = a.api_key or cfg.get("api_key", "") + svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True) + svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False) + svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True + if svc.api_monitor: + print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in " + "memory" + ("" if svc.api_key else "; anyone who can reach this server can read them (no API key)"), + flush=True) + if svc.cors_origins: + print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}" + + ("" if svc.api_key or "*" not in svc.cors_origins else + " - WARNING: any web page may use the model (no API key)"), flush=True) + svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0) + svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \ + int(cfg.get("min_free_vram_mib") or 0) + svc.before_load = a.before_load or cfg.get("before_load") or None + mode = str(cfg.get("anthropic_thinking") or "model") # #278: "on_request" = only when the request asks + if mode not in ("model", "on_request"): + raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") + svc.anthropic_think_unasked = mode == "model" + if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request + try: + svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] + budget = svc.reasoning_budget({}) + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + if budget: + print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)", + flush=True) + svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51) + svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112) + svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301) + if a.config: # the Chat settings shared with other apps, from last time + svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json" + try: + svc.shared = clean_shared_defaults(json.loads(Path(svc.shared_path).read_text(encoding="utf-8"))) + if svc.shared: + print("[strata] other apps use the Chat settings: " + + ", ".join(f"{k}={v}" for k, v in svc.shared.items()), flush=True) + except (OSError, ValueError): + svc.shared = {} + if hub is not None: + import atexit + svc.mcp = hub + print(f"[strata] starting {len(hub.servers)} MCP server{'s' * (len(hub.servers) != 1)} for the web app's " + f"chat: {', '.join(hub.servers)}", flush=True) + hub.start() + atexit.register(hub.close) # the servers Strata started end with it + httpd = serve(svc, host=a.host, port=a.port) + svc.start_idle_unload() + here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host + print(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " + f"context {engine.max_context} tokens{', images on' if vision else ''}" + f"{', API key required' if svc.api_key else ''})", flush=True) + print(f" open http://{here}:{a.port}/ in a browser to chat; close this window to stop the model", flush=True) + if a.host not in ("127.0.0.1", "localhost", "::1"): + # issue #26: reachable from other devices - say at which address, and what can still block it + ips = lan_addresses() + for ip in ips: + print(f" from other devices: http://{ip}:{a.port}/ (API: http://{ip}:{a.port}/v1)", flush=True) + if not ips: + print(" from other devices: http://:" + str(a.port) + "/", flush=True) + if not svc.api_key: + print(" WARNING: no API key - anyone on your network can use this model. Add \"api_key\": \"...\" " + "to the config (clients send it as their API key; the web page asks for it)", flush=True) + if os.name == "nt": + print(" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run " + "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(a.port) + "\" " + "-Direction Inbound -Protocol TCP -LocalPort " + str(a.port) + " -Action Allow -Profile Private\n" + " (and set this network to Private in Windows' network settings)", flush=True) + if a.open: + import webbrowser + webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/") + # #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after + # the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine). + # SIGINT keeps Python's own handler, so Ctrl+C and a second Ctrl+C work as before. + def on_sigterm(signum, frame): + raise KeyboardInterrupt + try: + signal.signal(signal.SIGTERM, on_sigterm) + except (ValueError, OSError, AttributeError): # not the main thread + pass + try: + while True: + time.sleep(1) # Windows never delivers Ctrl+C to an untimed Event.wait() + except KeyboardInterrupt: + print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True) + closers = [httpd.shutdown, getattr(engine, "close", None), vision.close if vision else None, + hub.close if hub is not None else None] + for close in filter(None, closers): + try: + close() + except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory + if getattr(engine, "proc", None): + engine.proc.kill() + print("[strata] stopped", flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/serve/structured.py b/engine/strata/serve/structured.py new file mode 100644 index 00000000..b5f079cc --- /dev/null +++ b/engine/strata/serve/structured.py @@ -0,0 +1,147 @@ +"""JSON response formats at the HTTP boundary: prompt once, validate before delivery. + +The native engine has no grammar decoder. Failed generations are errors, never +silently retried or returned as successful structured output. + +`jsonschema` is optional (no new hard dependency of the server): json_object needs only the standard library, and +json_schema is checked against its schema when the package is installed - without it, only that the answer is one +JSON object, and the server says so once. +""" +import json +import threading + + +class StructuredOutputError(RuntimeError): + pass + + +class _ObjectOnly: + """The validator for json_object, and for json_schema without jsonschema: one JSON object.""" + + def iter_errors(self, value): + if not isinstance(value, dict): + yield _ObjectError() + + +class _ObjectError: + absolute_path = () + message = "the answer is not a JSON object" + + +_jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed +_jsonschema_lock = threading.Lock() + + +def jsonschema_modules(): + """jsonschema, imported on first use; None when it is not installed (said once, in the server window).""" + global _jsonschema + with _jsonschema_lock: + if _jsonschema is None: + try: + from jsonschema import validators + from jsonschema.exceptions import SchemaError + from referencing import Registry + from referencing.exceptions import NoSuchResource + _jsonschema = (validators, SchemaError, Registry, NoSuchResource) + except ImportError: + _jsonschema = False + print('[strata] response_format json_schema: the Python package jsonschema is not installed, so ' + 'answers are only checked to be one JSON object (python -m pip install "jsonschema>=4.23,<5")', + flush=True) + return _jsonschema or None + + +def prepare_format(response_format, messages): + if response_format is None: + return messages, None + if not isinstance(response_format, dict): + raise ValueError("response_format must be an object") + kind = response_format.get("type") + if kind == "text": + return messages, None + if kind == "json_object": + schema = {"type": "object"} + modules = None # the standard library is enough for "one JSON object" + elif kind == "json_schema": + spec = response_format.get("json_schema") + if not isinstance(spec, dict) or not isinstance(spec.get("schema"), dict): + raise ValueError("response_format.json_schema needs a schema object") + if not isinstance(spec.get("name"), str) or not spec["name"]: + raise ValueError("response_format.json_schema needs a name") + if "strict" in spec and not isinstance(spec["strict"], bool): + raise ValueError("response_format.json_schema.strict must be boolean") + schema = spec["schema"] + if schema.get("type") != "object": + raise ValueError("response_format schema must have type object at its root") + modules = jsonschema_modules() + else: + raise ValueError("response_format.type must be text, json_object or json_schema") + + def check_refs(node): + if isinstance(node, dict): + for key, value in node.items(): + if key in ("$ref", "$dynamicRef") and isinstance(value, str) and not value.startswith("#"): + raise ValueError("response_format supports only local schema references (#...)") + check_refs(value) + elif isinstance(node, list): + for value in node: + check_refs(value) + check_refs(schema) + if modules is None: + validator = _ObjectOnly() + else: + validators, SchemaError, Registry, NoSuchResource = modules + + def no_remote(uri): + raise NoSuchResource(ref=uri) + + try: + cls = validators.validator_for(schema) + cls.check_schema(schema) + validator = cls(schema, registry=Registry(retrieve=no_remote)) + except SchemaError as exc: + raise ValueError(f"invalid response_format schema: {exc.message}") from exc + directive = ("OUTPUT FORMAT REQUIREMENT: Return exactly one JSON object matching the JSON Schema below. " + "No Markdown, headings, code fences, commentary, or text outside the JSON. " + "Use every required field, correct types, and only allowed fields. " + "Put all requested writing inside the appropriate JSON string fields.\nJSON Schema:\n" + + json.dumps(schema, ensure_ascii=False, allow_nan=False, separators=(",", ":"))) + messages = [dict(message) for message in messages] + if messages and messages[0].get("role") == "system": + content = messages[0].get("content") or "" + if isinstance(content, list): + messages[0]["content"] = content + [{"type": "text", "text": directive}] + else: + messages[0]["content"] = content + "\n\n" + directive + else: + messages.insert(0, {"role": "system", "content": directive}) + return messages, validator + + +def validated_json(text, validator, finish): + def pairs(items): + obj = {} + for key, value in items: + if key in obj: + raise ValueError(f"duplicate JSON key: {key}") + obj[key] = value + return obj + + def constant(value): + raise ValueError(f"invalid JSON constant: {value}") + + if finish != "stop": + raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") + try: + value = json.loads(text or "", object_pairs_hook=pairs, parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + except (ValueError, TypeError) as exc: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + try: + error = next(validator.iter_errors(value), None) + except Exception as exc: + raise StructuredOutputError(f"could not validate structured output: {exc}") from exc + if error is not None: + path = "/" + "/".join(str(part) for part in error.absolute_path) + raise StructuredOutputError(f"model output failed the JSON Schema at {path}: {error.message}") + return canonical diff --git a/engine/strata/serve/telemetry.py b/engine/strata/serve/telemetry.py new file mode 100644 index 00000000..6fc1a030 --- /dev/null +++ b/engine/strata/serve/telemetry.py @@ -0,0 +1,363 @@ +"""serve/telemetry.py - hardware readings for the web app's Monitor tab (idea from PR #22 by code-martin). + +A background thread samples once a second and keeps the last 60 readings of each series for the sparklines: +- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no + pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. With the AMD backend (#301): the + amdgpu driver's Linux sysfs files - load, VRAM, temperature and power. +- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to + the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent. +Anything that cannot be read is None; nothing here can stop the server. +""" +from __future__ import annotations + +import collections +import ctypes +import os +import platform +import sys +import threading +import time + +HISTORY = 60 + + +# ------------------------------------------------------------------------------------------------ NVML +class _Nvml: + class Util(ctypes.Structure): + _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)] + + class Mem(ctypes.Structure): + _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)] + + def __init__(self, index=0): + self.lib = self.dev = None + names = ["nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), + "NVIDIA Corporation", "NVSMI", "nvml.dll")] if os.name == "nt" \ + else ["libnvidia-ml.so.1", "libnvidia-ml.so"] + for n in names: + try: + self.lib = ctypes.CDLL(n) + break + except OSError: + continue + if self.lib is None: + return + try: + init = getattr(self.lib, "nvmlInit_v2", None) or self.lib.nvmlInit + if init() != 0: + self.lib = None + return + h = ctypes.c_void_p() + get = getattr(self.lib, "nvmlDeviceGetHandleByIndex_v2", None) or self.lib.nvmlDeviceGetHandleByIndex + if get(ctypes.c_uint(index), ctypes.byref(h)) != 0: + self.lib = None + return + self.dev = h + except (AttributeError, OSError): + self.lib = None + + def ok(self): + return self.lib is not None and self.dev is not None + + def _uint(self, fn, *args): + v = ctypes.c_uint() + try: + return v.value if getattr(self.lib, fn)(self.dev, *args, ctypes.byref(v)) == 0 else None + except (AttributeError, OSError): + return None + + def name(self): + buf = ctypes.create_string_buffer(96) + try: + if self.lib.nvmlDeviceGetName(self.dev, buf, ctypes.c_uint(96)) == 0: + return buf.value.decode(errors="replace") + except (AttributeError, OSError): + pass + return None + + def read(self): + out = {} + u = self.Util() + try: + if self.lib.nvmlDeviceGetUtilizationRates(self.dev, ctypes.byref(u)) == 0: + out["util"] = u.gpu + except (AttributeError, OSError): + pass + m = self.Mem() + try: + if self.lib.nvmlDeviceGetMemoryInfo(self.dev, ctypes.byref(m)) == 0: + out["mem_used"], out["mem_total"] = m.used, m.total + except (AttributeError, OSError): + pass + out["temp"] = self._uint("nvmlDeviceGetTemperature", ctypes.c_uint(0)) # NVML_TEMPERATURE_GPU + mw = self._uint("nvmlDeviceGetPowerUsage") + out["power"] = mw / 1000.0 if mw is not None else None + lim = self._uint("nvmlDeviceGetEnforcedPowerLimit") + out["power_limit"] = lim / 1000.0 if lim is not None else None + out["pcie_gen"] = self._uint("nvmlDeviceGetCurrPcieLinkGeneration") # drops at idle (power saving) + out["pcie_gen_max"] = self._uint("nvmlDeviceGetMaxPcieLinkGeneration") + out["pcie_width"] = self._uint("nvmlDeviceGetCurrPcieLinkWidth") + rx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(1)) # NVML_PCIE_UTIL_RX_BYTES, KB/s + tx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(0)) + out["pcie_rx_mb"] = rx / 1024.0 if rx is not None else None + out["pcie_tx_mb"] = tx / 1024.0 if tx is not None else None + return out + + +# ------------------------------------------------------------------------------------------------ AMD (Linux sysfs) +SYSFS = "/sys" + + +def amd_device_dir(index, sysfs=None): + """The amdgpu sysfs folder (/sys/class/drm/renderD/device) of the AMD GPU that HIP numbers `index`: the KFD + topology's GPU nodes in order, the CPU nodes skipped, linked to their render node by drm_render_minor - the + numbering setup's amd_gpus() and HIP_VISIBLE_DEVICES use. None when there is no such card (or no amdgpu).""" + base = os.path.join(sysfs or SYSFS, "class", "kfd", "kfd", "topology", "nodes") + try: + nodes = sorted((n for n in os.listdir(base) if n.isdigit()), key=int) + except OSError: + return None + gpus = [] + for n in nodes: + try: + with open(os.path.join(base, n, "properties"), encoding="utf-8") as f: + props = dict(line.strip().partition(" ")[::2] for line in f if line.strip()) + if int(props.get("gfx_target_version") or 0) == 0 or int(props.get("simd_count") or 0) == 0: + continue + gpus.append(props) + except (OSError, ValueError): + continue + if not 0 <= index < len(gpus) or not gpus[index].get("drm_render_minor"): + return None + dev = os.path.join(sysfs or SYSFS, "class", "drm", "renderD" + gpus[index]["drm_render_minor"].strip(), "device") + return dev if os.path.isdir(dev) else None + + +class _Amd: + """#301: an AMD card's readings from the amdgpu driver's sysfs files (Linux; no ROCm library needed), with _Nvml's + interface: load (gpu_busy_percent), VRAM (mem_info_vram_used / _total), and from its hwmon folder the temperature + (temp1_input, the edge sensor, m°C), power (power1_average or power1_input, µW) and its cap (power1_cap).""" + + def __init__(self, index=0, sysfs=None): + self.dev = amd_device_dir(index, sysfs) + self.hwmon = None + if self.dev: + try: + hw = sorted(os.listdir(os.path.join(self.dev, "hwmon"))) + self.hwmon = os.path.join(self.dev, "hwmon", hw[0]) if hw else None + except OSError: + pass + + def ok(self): + return self.dev is not None + + @staticmethod + def _int(path): + try: + with open(path, encoding="utf-8") as f: + return int(f.read().strip()) + except (OSError, ValueError, TypeError): + return None + + def name(self): + try: + with open(os.path.join(self.dev, "product_name"), encoding="utf-8") as f: + return f.read().strip() or "AMD Radeon" + except (OSError, TypeError): + return "AMD Radeon" + + def read(self): + out = {"util": self._int(os.path.join(self.dev, "gpu_busy_percent")), + "mem_used": self._int(os.path.join(self.dev, "mem_info_vram_used")), + "mem_total": self._int(os.path.join(self.dev, "mem_info_vram_total"))} + if self.hwmon: + t = self._int(os.path.join(self.hwmon, "temp1_input")) + out["temp"] = t / 1000.0 if t is not None else None + p = self._int(os.path.join(self.hwmon, "power1_average")) + if p is None: + p = self._int(os.path.join(self.hwmon, "power1_input")) + out["power"] = p / 1e6 if p is not None else None + cap = self._int(os.path.join(self.hwmon, "power1_cap")) + out["power_limit"] = cap / 1e6 if cap is not None else None + return out + + +def gpu_reader(index=0, amd=False): + """The card's readings: NVML (NVIDIA), or the amdgpu sysfs files with the AMD backend (#301).""" + return _Amd(index) if amd else _Nvml(index) + + +def free_vram_mib(index=0, amd=False): + """Free VRAM of a card in MiB, or None when it cannot be read.""" + g = gpu_reader(index, amd) + if not g.ok(): + return None + r = g.read() + if r.get("mem_total") is None or r.get("mem_used") is None: + return None + return int((r["mem_total"] - r["mem_used"]) >> 20) + + +# ------------------------------------------------------------------------------------------------ CPU / RAM +def _cpu_name(): + if os.name == "nt": + try: + import winreg + k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") + return winreg.QueryValueEx(k, "ProcessorNameString")[0].strip() + except OSError: + pass + elif os.path.exists("/proc/cpuinfo"): + for line in open("/proc/cpuinfo", encoding="utf-8", errors="replace"): + if line.startswith("model name"): + return line.split(":", 1)[1].strip() + return platform.processor() or None + + +class _CpuRamFallback: + """CPU load and RAM without psutil.""" + + def __init__(self): + self.prev = self._times() + + def _times(self): + if os.name == "nt": + idle, kern, user = (ctypes.c_ulonglong() for _ in range(3)) + if ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)): + return idle.value, kern.value + user.value # kernel time includes idle + return None + try: + f = [int(x) for x in open("/proc/stat").readline().split()[1:]] + return f[3] + f[4], sum(f) + except (OSError, ValueError): + return None + + def cpu(self): + cur = self._times() + prev, self.prev = self.prev, cur + if not cur or not prev or cur[1] == prev[1]: + return None + return max(0.0, min(100.0, 100.0 * (1 - (cur[0] - prev[0]) / (cur[1] - prev[1])))) + + @staticmethod + def ram(): + if os.name == "nt": + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(MS) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): + return m.ullTotalPhys - m.ullAvailPhys, m.ullTotalPhys + return None, None + try: + info = dict(line.split(":", 1) for line in open("/proc/meminfo")) + total = int(info["MemTotal"].split()[0]) * 1024 + avail = int(info["MemAvailable"].split()[0]) * 1024 + return total - avail, total + except (OSError, KeyError, ValueError): + return None, None + + +# ------------------------------------------------------------------------------------------------ the sampler +class Telemetry: + def __init__(self, extra=None, gpu_index=0, gpu_indices=None, amd=False): + """`extra()` -> dict of more series to record each second (the server's tok/s). `gpu_index`: the card the + engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them when + the model is split across several (issue #112) - the gpu_* readings are then their total (memory, power, + PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own. `amd`: the AMD backend's + cards, numbered as HIP numbers them, read from sysfs (#301).""" + self.extra = extra + self.lock = threading.Lock() + self.now: dict = {} + self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY)) + idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index] + self.gpus = [(i, gpu_reader(i, amd)) for i in idx] + self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1] + self.gpu = self.gpus[0][1] + try: + import psutil # noqa: F401 + self.ps = sys.modules["psutil"] + except ImportError: + self.ps = None + self.fallback = _CpuRamFallback() + self.static = { + "gpu_name": " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None, + "gpu_count": len(self.gpus), + "cpu_name": _cpu_name(), + "cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None, + "threads": os.cpu_count(), + "psutil": self.ps is not None, + } + self._disk_prev = None + threading.Thread(target=self._loop, daemon=True).start() + + def _disk(self): + if not self.ps: + return None, None + try: + c = self.ps.disk_io_counters() + except (OSError, RuntimeError): + return None, None + t = time.time() + prev, self._disk_prev = self._disk_prev, (t, c.read_bytes, c.write_bytes) + if prev is None or t <= prev[0]: + return None, None + dt = t - prev[0] + return (c.read_bytes - prev[1]) / dt / 2**20, (c.write_bytes - prev[2]) / dt / 2**20 + + def sample(self): + s = {} + if self.gpu.ok(): + reads = [(i, g.read()) for i, g in self.gpus] + g = dict(reads[0][1]) + if len(reads) > 1: + def vals(k): + return [r[k] for _, r in reads if r.get(k) is not None] + for k in ("mem_used", "mem_total", "power", "power_limit", "pcie_rx_mb", "pcie_tx_mb"): + v = vals(k) + g[k] = sum(v) if v else None + u = vals("util") + g["util"] = sum(u) / len(u) if u else None + t = vals("temp") + g["temp"] = max(t) if t else None + s["gpus"] = [{"index": i, "util": r.get("util"), "mem_used": r.get("mem_used"), + "mem_total": r.get("mem_total"), "temp": r.get("temp"), "power": r.get("power")} + for i, r in reads] + s.update({f"gpu_{k}": v for k, v in g.items()}) + if self.ps: + try: + s["cpu"] = self.ps.cpu_percent(interval=None) + vm = self.ps.virtual_memory() + s["ram_used"], s["ram_total"] = vm.total - vm.available, vm.total + except (OSError, RuntimeError): + pass + else: + s["cpu"] = self.fallback.cpu() + s["ram_used"], s["ram_total"] = self.fallback.ram() + s["disk_read_mb"], s["disk_write_mb"] = self._disk() + if self.extra: + try: + s.update(self.extra()) + except Exception: # noqa: BLE001 - telemetry must never take the server down + pass + return s + + def _loop(self): + while True: + s = self.sample() + with self.lock: + self.now = s + for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used", + "disk_read_mb", "tok_s", "prefill_tok_s_mean"): + v = s.get(k) + self.hist[k].append(round(v, 2) if isinstance(v, float) else v) + time.sleep(1.0) + + def snapshot(self): + with self.lock: + return {"now": dict(self.now), "history": {k: list(v) for k, v in self.hist.items()}, + "static": dict(self.static)} diff --git a/engine/strata/serve/test_detok.py b/engine/strata/serve/test_detok.py new file mode 100644 index 00000000..b1c61424 --- /dev/null +++ b/engine/strata/serve/test_detok.py @@ -0,0 +1,252 @@ +"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token +by token, and its cost per token does not grow with the reply. + + python -m unittest serve.test_detok (needs a pack's tokenizer; skipped without one) +""" +import os +import random +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) + +from serve.server import Detokenizer # noqa: E402 + + +def find_tokenizer(): + cands = [os.environ.get("STRATA_TOKENIZER", "")] + cands += [str(p) for p in ROOT.glob("packs/*/tokenizer")] + [str(p) for p in ROOT.glob("pack/*/tokenizer")] + cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer"] + for c in cands: + if c and (Path(c) / "vocab.json").exists(): + return Path(c) + return None + + +class OldDetokenizer: + """The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD.""" + + def __init__(self, tok): + self.tok, self.ids, self.sent = tok, [], 0 + + def push(self, t): + self.ids.append(t) + text = self.tok.decode(self.ids) + if text.endswith("\ufffd"): + return "" + delta, self.sent = text[self.sent:], len(text) + return delta + + +@unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") +class Detok(unittest.TestCase): + @classmethod + def setUpClass(cls): + import json + import strata_tokenizer as ST + t = find_tokenizer() + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for s, i in vocab.items(): + toks[i] = s + cls.tok = ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text())) + + def same_stream(self, ids): + """The same text as the old re-decode, never behind it (the old one held complete characters too while + the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the + ids so far decode to.""" + a, b = OldDetokenizer(self.tok), Detokenizer(self.tok) + self.assertIsNotNone(b.inc) + old = new = "" + for i, t in enumerate(ids): + old += a.push(t) + new += b.push(t) + self.assertTrue(new.startswith(old), f"token {i} ({t}): behind the old stream") + self.assertTrue(self.tok.decode(ids[:i + 1]).startswith(new), f"token {i} ({t}): ahead of the ids") + if not self.tok.decode(ids).endswith("�"): + self.assertEqual(old, new) + + def test_text_with_split_characters(self): + text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩‍💻 and ASCII code: def f(x): return x**2\n" * 40) + self.same_stream(self.tok.encode(text)) + + def test_random_ids_and_broken_bytes(self): + rng = random.Random(5) + n = len(self.tok.tokens) + for _ in range(20): # random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself) + ids = [rng.randrange(n) for _ in range(300)] + ids = [t for t in ids if "\ufffd" not in self.tok.decode([t], errors="strict" if False else "replace") + or len(self.tok.token_bytes(t)) < 3] + self.same_stream(ids) + + def test_constant_cost(self): + ids = self.tok.encode("The quick brown fox jumps over the lazy dog. " * 2000)[:16384] + d = Detokenizer(self.tok) + for t in ids[:1024]: + d.push(t) + t0 = time.perf_counter() + for t in ids[1024:1124]: + d.push(t) + early = time.perf_counter() - t0 + for t in ids[1124:16000]: + d.push(t) + t0 = time.perf_counter() + for t in ids[16000:16100]: + d.push(t) + late = time.perf_counter() - t0 + self.assertLess(late / 100, 0.0002, "a token after 16K tokens costs more than 0.2 ms") + self.assertLess(late, early * 5 + 0.002) + + +# ------------------------------------------------------------------ #268: the heap BPE for long words +_REAL = [] + + +def real_tokenizer(): + """The pack's tokenizer, loaded once for every class that needs it (None when there is no pack here).""" + if not _REAL: + t = find_tokenizer() + if t is None: + _REAL.append(None) + else: + import json + import strata_tokenizer as ST + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for s, i in vocab.items(): + toks[i] = s + _REAL.append(ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text()))) + return _REAL[0] + + +def random_text(rng, n_pieces=40): + """Strings shaped to make one pre-token piece long or awkward: CJK and Hangul runs (syllables and conjoining + jamo), letters under stacks of combining marks, URLs, minified code, digits, emoji, whitespace, specials.""" + def run(lo, hi, k): + return "".join(chr(rng.randint(lo, hi)) for _ in range(k)) + + kinds = [ + lambda: run(0x4E00, 0x9FFF, rng.randint(1, 400)), # CJK + lambda: run(0xAC00, 0xD7A3, rng.randint(1, 200)), # Hangul syllables + lambda: "".join(chr(0x1100 + rng.randrange(19)) + chr(0x1161 + rng.randrange(21)) + for _ in range(rng.randint(1, 60))), # conjoining jamo + lambda: "".join(rng.choice("aeiouxyz") + run(0x0300, 0x036F, rng.randint(0, 4)) + for _ in range(rng.randint(1, 80))), # combining marks + lambda: "https://example.com/" + "/".join(run(0x61, 0x7A, rng.randint(1, 12)) + for _ in range(rng.randint(1, 20))) + "?q=" + run(0x30, 0x39, 8), + lambda: "".join(rng.choice(["var ", "a=", "b", "(", ")", "{", "}", ";", "function", "return", "x", "+", + "!0", "void 0", ",", ".", "[", "]", "=>", "&&"]) for _ in range(rng.randint(1, 300))), + lambda: run(0x30, 0x39, rng.randint(1, 50)), + lambda: rng.choice([" ", " ", "\n", "\n\n", "\t", "\r\n", " \n "]) * rng.randint(1, 30), + lambda: rng.choice(["\U0001f600", "\U0001f30a", "\U0001f469‍\U0001f4bb", "é", "ß"]) * rng.randint(1, 30), + lambda: rng.choice(["<|im_end|>", "<|im_start|>", "", "", "", "<|im_sta"]), + lambda: "a" * rng.randint(60, 300), + lambda: run(0x20, 0x7E, rng.randint(1, 200)), + ] + return "".join(rng.choice(kinds)() for _ in range(rng.randint(1, n_pieces))) + + +def encode_with(tok, text, parse_special, heap_min): + tok.HEAP_MIN = heap_min + try: + return tok.encode(text, parse_special=parse_special) + finally: + del tok.HEAP_MIN + + +def synthetic_tokenizer(seed=268, n_merges=1500): + """A small byte-level BPE vocabulary with merges learned (randomly) from random_text, and a few specials of + both kinds - so the parity test runs without a pack.""" + import strata_tokenizer as ST + rng = random.Random(seed) + tokens = sorted(set(ST.BYTE_TO_UNICODE.values())) + have, merges = set(tokens), [] + words = [] + for _ in range(60): + for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 10)): + words.append([ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")]) + words = [w for w in words if len(w) > 1] + while len(merges) < n_merges: + w = rng.choice(words) + if len(w) < 2: + continue + i = rng.randrange(len(w) - 1) + a, b = w[i], w[i + 1] + w[i:i + 2] = [a + b] # learn in place, so later merges build on earlier ones + if a + b in have or f"{a} {b}" in merges: + continue + merges.append(f"{a} {b}") + tokens.append(a + b) + have.add(a + b) + types = [1] * len(tokens) + for lit, ty in [("<|im_end|>", 3), ("<|im_start|>", 3), ("", 4), ("", 4), ("", 4)]: + tokens.append(lit) + types.append(ty) + return ST.Tokenizer(tokens, merges, types) + + +class HeapBpe(unittest.TestCase): + """#268: words longer than HEAP_MIN symbols merge with a heap; the ids must be exactly the scan's.""" + + def parity(self, tok, texts): + for k, text in enumerate(texts): + for ps in (False, True): + old = encode_with(tok, text, ps, 10 ** 9) # the scan for every word + self.assertEqual(encode_with(tok, text, ps, 0), old, f"text {k} parse_special={ps}") # the heap + self.assertEqual(tok.encode(text, parse_special=ps), old, f"text {k} parse_special={ps}") + + def test_words_directly(self): + tok = synthetic_tokenizer() + rng = random.Random(1) + import strata_tokenizer as ST + for _ in range(300): + for piece in ST.regex.compile(ST.QWEN35_PATTERN).findall(random_text(rng, 8)): + word = "".join(ST.BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) + tok.HEAP_MIN = 10 ** 9 + try: + old = tok._bpe(word) + finally: + del tok.HEAP_MIN + self.assertEqual(tok._bpe_heap(word), old, repr(piece[:40])) + + def test_synthetic_vocab(self): + tok = synthetic_tokenizer() + rng = random.Random(2) + self.parity(tok, [random_text(rng) for _ in range(60)] + ["a" * 5000, "ab" * 3000, ""]) + + @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") + def test_pack_vocab(self): + tok = real_tokenizer() + rng = random.Random(3) + fixed = ["你好,世界" * 150, "한국어 텍스트" * 100, + "é́̂" * 200, "x" * 5000, + "https://example.com/" + "a/b-c_d.e?f=g&h=i#j" * 60, + "!function(e){var t={};function n(r){if(t[r])return t[r].exports}}" * 30, + "<|im_start|>user\n日本語" * 40 + "<|im_end|>" + "漢" * 300] + self.parity(tok, fixed + [random_text(rng) for _ in range(40)]) + + def check_speed(self, tok): + rng = random.Random(4) + text = "".join(chr(rng.randint(0x4E00, 0x9FFF)) for _ in range(8192)) # one 24K-byte piece + t0 = time.perf_counter() + ids = tok.encode(text) + took = time.perf_counter() - t0 + self.assertEqual(tok.decode(ids), text) + self.assertLess(took, 1.0, f"an 8K-character CJK run took {took:.2f} s") + + def test_speed_synthetic(self): + self.check_speed(synthetic_tokenizer()) + + @unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") + def test_speed_pack(self): + self.check_speed(real_tokenizer()) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_lifecycle.py b/engine/strata/serve/test_lifecycle.py new file mode 100644 index 00000000..1d9f58c4 --- /dev/null +++ b/engine/strata/serve/test_lifecycle.py @@ -0,0 +1,170 @@ +"""Model discovery, on-demand loading and safe unloading over the actual HTTP API.""" +import json +import io +import subprocess +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, EngineStuck, MockEngine, Service, StrataEngine, serve + + +class ResidentEngine(StrataEngine): + def __init__(self, tok): + self.reply = MockEngine(tok, "Hello.", max_context=4096) + self.max_context, self.info, self.last = 4096, {}, {} + self.loaded, self.starts, self.closes = False, 0, 0 + self.unloaded = True + self.progress = None + + def alive(self): + return self.loaded + + def exit_code(self): + return None + + def restart(self): + self.loaded = True + self.starts += 1 + self.unloaded = False + + def close(self): + self.loaded = False + self.closes += 1 + + def unload(self): + self.close() + self.unloaded = True + + def generate(self, *args, **kwargs): + yield from self.reply.generate(*args, **kwargs) + + +class Lifecycle(unittest.TestCase): + def test_close_sends_eof_before_waiting_for_windows_reader(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = lambda **kwargs: self.assertTrue(proc.stdin.closed) + engine.proc = proc + engine.close() + self.assertIsNone(engine.proc) + proc.kill.assert_not_called() + + def test_close_does_not_forget_a_process_still_exiting(self): + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.return_value = None + proc.wait.side_effect = subprocess.TimeoutExpired("engine", 2) + engine.proc = proc + with self.assertRaisesRegex(EngineStuck, "still releasing"): + engine.close() + self.assertIs(engine.proc, proc) + proc.terminate.assert_called_once() + proc.kill.assert_called_once() + + def test_close_terminates_before_it_kills(self): + # an engine that does not end on QUIT is terminated first (as the unload always did); kill is the last resort + engine = StrataEngine("missing-executable", [], lazy=True) + proc = mock.Mock() + proc.stdin, proc.stdout = io.StringIO(), io.StringIO() + proc.poll.side_effect = [None, 0] + proc.wait.side_effect = [subprocess.TimeoutExpired("engine", 20), 0] + engine.proc = proc + engine.close() + proc.terminate.assert_called_once() + proc.kill.assert_not_called() + self.assertIsNone(engine.proc) + + def test_native_lazy_constructor_does_not_start_a_process(self): + engine = StrataEngine("missing-executable", ["--max-context", "16384"], lazy=True) + self.assertFalse(engine.alive()) + self.assertEqual(engine.max_context, 16384) + self.assertIsNone(engine.exit_code()) + engine.close() + + def setUp(self): + tok = ByteTokenizer() + self.engine = ResidentEngine(tok) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def test_discover_chat_unload_and_stream_reload(self): + self.assertEqual(self.request("/api/health")[1]["service"], "strata") + self.assertFalse(self.request("/v1/status")[1]["loaded"]) + self.assertEqual(self.request("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertTrue(self.request("/props")[1]["models_autoload"]) + self.assertEqual(self.engine.starts, 0) + chat = {"messages": [{"role": "user", "content": "Hello"}], "max_tokens": 32, "reasoning_effort": "none"} + for _ in range(2): + code, answer = self.request("/v1/chat/completions", chat) + self.assertEqual(code, 200) + self.assertEqual(answer["choices"][0]["message"]["content"], "Hello.") + self.assertEqual(self.engine.starts, 1) + self.assertFalse(self.request("/v1/unload", {})[1]["loaded"]) + code, stream = self.request("/v1/chat/completions", {**chat, "stream": True}) + self.assertEqual(code, 200) + self.assertIn("data: [DONE]", stream) + self.assertEqual(self.engine.starts, 2) + + def test_busy_auth_and_foreign_origin_cannot_unload(self): + self.engine.loaded = True + with self.svc.fifo: + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.svc.api_key = "local-secret" + self.assertEqual(self.request("/v1/unload", {})[0], 401) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret", + "Origin": "https://other.example"})[0], 403) + self.assertEqual(self.engine.closes, 0) + self.assertTrue(self.engine.loaded) + self.assertEqual(self.request("/v1/unload", {}, {"Authorization": "Bearer local-secret"})[0], 200) + + def test_an_engine_that_died_on_load_is_reported_as_such(self): + # EngineDied is a RuntimeError: it keeps its own answer ("the next request restarts it") + def died(): + raise EngineDied("the engine ended while it started") + self.engine.restart = died + code, body = self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "Hello"}]}) + self.assertEqual(code, 503) + self.assertIn("the next request restarts it", body["error"]["message"]) + + def test_explicit_load_and_model_matching(self): + self.assertEqual(self.request("/v1/load", {"model": "other-model"})[0], 404) + self.assertEqual(self.engine.starts, 0) + before = time.time() + code, status = self.request("/v1/load", {"model": self.svc.model}) + self.assertEqual(code, 200) + self.assertTrue(status["loaded"]) + self.assertEqual(self.engine.starts, 1) + self.assertGreaterEqual(self.svc.last_request_at, before) + self.svc.status["queued"] = 1 + self.assertEqual(self.request("/v1/load", {})[0], 409) + self.assertEqual(self.request("/v1/unload", {})[0], 409) + self.assertEqual(self.engine.closes, 0) + self.assertEqual(self.request("/v1/load", {}, {"Content-Type": "text/plain"})[0], 415) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_mcp.py b/engine/strata/serve/test_mcp.py new file mode 100644 index 00000000..c80c5d01 --- /dev/null +++ b/engine/strata/serve/test_mcp.py @@ -0,0 +1,447 @@ +"""serve/test_mcp.py - tools from MCP servers (serve/mcp.py) and the web app's tool loop, against the mock engine and +the fake MCP server in serve/mcp_fake_server.py (no GPU, no pack, no MCP SDK). + + python -m unittest serve.test_mcp -v +""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import threading +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve import mcp_fake_server as fake # noqa: E402 +from serve.frontend import ChatTemplate # noqa: E402 +from serve.mcp import McpCancelled, McpHub, hub_from_config # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +FAKE = str(ROOT / "serve" / "mcp_fake_server.py") +CTX = 8192 + + +def stdio(*args, **extra): + return {"command": sys.executable, "args": [FAKE, *args], **extra} + + +def call_script(name, **params): + """The model's text for one tool call, as Qwen's template asks for it.""" + body = "".join(f"\n{v}\n\n" for k, v in params.items()) + return f"\n\nLet me check.\n\n\n\n{body}\n" + + +class ScriptedEngine(MockEngine): + """A mock engine with one script per call (the last one repeats): a tool call first, then the answer.""" + + def __init__(self, tok, scripts, max_context=CTX, delay_s=0.0): + super().__init__(tok, list(scripts), max_context=max_context, delay_s=delay_s) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + def prompt_text(self, i): + return bytes(t for t in self.prompts[i] if t < 256).decode("utf-8", "replace") + + +# ------------------------------------------------------------------------------------------------ the client +class Client(unittest.TestCase): + """The stdio client against the fake server: start, pagination, calls, errors, crashes, timeouts, the cap.""" + + @classmethod + def setUpClass(cls): + cls.log = tempfile.NamedTemporaryFile(delete=False, suffix=".jsonl") + cls.log.close() + os.environ["FAKE_MCP_LOG"] = cls.log.name + cls.hub = McpHub({"fake": stdio(), "paged": stdio("--page", "4"), "broken": stdio("--crash-at-start"), + "missing": {"command": "strata-no-such-program"}}, + {"timeout_s": 1.5, "max_result_chars": 1000}) + cls.hub.start(wait=True) + + @classmethod + def tearDownClass(cls): + cls.hub.close() + del os.environ["FAKE_MCP_LOG"] + os.unlink(cls.log.name) + + def test_initialize_and_list_every_page(self): + s = self.hub.servers["fake"] + self.assertEqual(s.status, "ready") + self.assertEqual(s.info["name"], "fake") + self.assertEqual(s.info["protocol"], "2025-06-18") + want = [t["name"] for t in fake.TOOLS] + self.assertEqual([t["name"] for t in s.tools], want) # 3 pages of 2 + self.assertEqual([t["name"] for t in self.hub.servers["paged"].tools], want) # 2 pages of 4 + + def test_namespaced_openai_tools(self): + tools = self.hub.openai_tools() + names = [t["function"]["name"] for t in tools] + self.assertIn("fake__echo", names) + self.assertIn("paged__echo", names) + echo = next(t for t in tools if t["function"]["name"] == "fake__echo") + self.assertEqual(echo["type"], "function") + self.assertEqual(echo["function"]["parameters"]["properties"]["text"]["type"], "string") + + def test_a_server_that_fails_is_left_out(self): + for name, why in (("broken", "missing configuration"), ("missing", "could not start")): + with self.subTest(name=name): + s = self.hub.servers[name] + self.assertEqual(s.status, "failed") + self.assertIn(why, s.error) + self.assertFalse([t for t in self.hub.template_tools() if t["name"].startswith(name + "__")]) + st = {s["name"]: s for s in self.hub.status()["servers"]} + self.assertEqual(st["broken"]["status"], "failed") + self.assertEqual(st["fake"]["status"], "ready") + + def test_call(self): + self.hub.routes() + r = self.hub.call("fake__echo", {"text": "hello wörld"}) + self.assertEqual((r["ok"], r["text"], r["server"], r["tool"]), (True, "hello wörld", "fake", "echo")) + self.assertEqual(self.hub.call("fake__add", {"a": 2, "b": 40})["text"], "42") + + def test_errors_become_text(self): + self.hub.routes() + r = self.hub.call("fake__fail", {}) # the tool's own error (isError) + self.assertFalse(r["ok"]) + self.assertEqual(r["text"], "error: it failed on purpose") + r = self.hub.call("nobody__nothing", {}) # not a tool at all + self.assertTrue(r["text"].startswith("error: there is no tool")) + # a JSON-RPC error from the server + s = self.hub.servers["fake"] + with self.assertRaises(Exception) as ctx: + s.call("no-such-tool", {}, 5) + self.assertIn("unknown tool", str(ctx.exception)) + + def test_timeout(self): + self.hub.routes() + t0 = time.monotonic() + r = self.hub.call("fake__sleep", {"seconds": 5}) + self.assertLess(time.monotonic() - t0, 4) + self.assertFalse(r["ok"]) + self.assertIn("timed out after 1.5 s", r["text"]) + self.assertEqual(self.hub.call("fake__echo", {"text": "still here"})["text"], "still here") + + def test_truncation(self): + self.hub.routes() + r = self.hub.call("fake__big", {"n": 50000}) + self.assertTrue(r["ok"]) + self.assertTrue(r["truncated"]) + self.assertEqual(r["chars"], 50000) + self.assertTrue(r["text"].startswith("y" * 1000 + "\n\n[... truncated")) + self.assertIn("50,000 characters", r["text"]) + self.assertLess(len(r["text"]), 1200) + + def test_crash_mid_call_then_restart(self): + hub = McpHub({"solo": stdio()}, {"timeout_s": 5}) + hub.start(wait=True) + try: + hub.routes() + r = hub.call("solo__die", {}) + self.assertFalse(r["ok"]) + self.assertIn("the server stopped", r["text"]) + self.assertIn("dying on purpose", r["text"]) + self.assertEqual(hub.servers["solo"].status, "stopped") + self.assertIn("solo__echo", hub.routes()) # its tools stay: the next call restarts it + self.assertEqual(hub.call("solo__echo", {"text": "back"})["text"], "back") + self.assertEqual(hub.servers["solo"].status, "ready") + finally: + hub.close() + + def test_cancel(self): + self.hub.routes() + cancel = threading.Event() + threading.Timer(0.3, cancel.set).start() + t0 = time.monotonic() + with self.assertRaises(McpCancelled): + self.hub.call("fake__sleep", {"seconds": 1.2}, cancel) + self.assertLess(time.monotonic() - t0, 1.0) + time.sleep(0.3) + seen = [json.loads(line) for line in Path(self.log.name).read_text().splitlines()] + self.assertTrue(any("cancelled" in e for e in seen), seen) # notifications/cancelled reached the server + + +class HttpClient(unittest.TestCase): + """Streamable HTTP: JSON answers, an event-stream answer, the session id.""" + + @classmethod + def setUpClass(cls): + cls.httpd = fake.http_server(0) + url = f"http://127.0.0.1:{cls.httpd.server_address[1]}/mcp" + cls.hub = McpHub({"web": {"url": url}, "down": {"url": "http://127.0.0.1:9/mcp"}}, {"timeout_s": 1.5}) + cls.hub.start(wait=True) + + @classmethod + def tearDownClass(cls): + cls.hub.close() + cls.httpd.shutdown() + cls.httpd.server_close() + + def test_list_and_call(self): + s = self.hub.servers["web"] + self.assertEqual(s.status, "ready", s.error) + self.assertEqual(len(s.tools), len(fake.TOOLS)) # pages, with the session id on each request + self.assertEqual(s.transport.session, "s-1") + self.hub.routes() + self.assertEqual(self.hub.call("web__echo", {"text": "over http"})["text"], "over http") # event stream + self.assertEqual(self.hub.call("web__fail", {})["text"], "error: it failed on purpose") + + def test_timeout_and_unreachable(self): + self.hub.routes() + r = self.hub.call("web__sleep", {"seconds": 4}) + self.assertIn("timed out", r["text"]) + self.assertEqual(self.hub.servers["down"].status, "failed") + self.assertIn("could not reach", self.hub.servers["down"].error) + + +class Config(unittest.TestCase): + def test_both_spellings_and_the_file(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "claude_desktop_config.json") + Path(path).write_text(json.dumps({"mcpServers": {"b": {"url": "http://x/mcp"}, "a": stdio()}}), + encoding="utf-8") + hub = hub_from_config({"mcp_servers": {"a": {"command": "old"}}, + "mcpServers": {"c": stdio(), "off": {"command": "x", "disabled": True}}, + "mcp": {"timeout_s": 5, "max_result_chars": 100, "max_rounds": 3}}, path) + self.assertEqual(sorted(hub.servers), ["a", "b", "c"]) + self.assertEqual(hub.servers["a"].cfg["command"], sys.executable) # the file wins a name clash + self.assertEqual(hub.servers["b"].kind, "http") + self.assertEqual((hub.settings["timeout_s"], hub.settings["max_result_chars"], hub.settings["max_rounds"]), + (5.0, 100, 3)) + self.assertIsNone(hub_from_config({})) + self.assertEqual(McpHub({}).settings["max_result_chars"], 20000) + + def test_bad_entries_stop_the_start(self): + for cfg in ({"mcp_servers": {"x": {}}}, {"mcp_servers": {"x": {"command": "a", "args": "b"}}}, + {"mcp_servers": ["x"]}, {"mcpServers": {"x": {"url": "http://a", "type": "sse"}}}, + {"mcp_servers": {"x": {"command": "a"}}, "mcp": {"timeout_s": 0}}, + {"mcp_servers": {"x": {"command": "a"}}, "mcp": {"max_rounds": 1.5}}): + with self.subTest(cfg=cfg), self.assertRaises(SystemExit): + hub_from_config(cfg) + with self.assertRaises(SystemExit): + hub_from_config({}, os.path.join(tempfile.gettempdir(), "strata-no-such-mcp.json")) + + +# ------------------------------------------------------------------------------------------------ the tool loop +class ToolLoop(unittest.TestCase): + """The web app's chat (`"strata_mcp": true`): the model calls an MCP tool, the server runs it and the model + answers with its result; plain API requests never see the MCP tools.""" + + def setUp(self): + self.log = tempfile.NamedTemporaryFile(delete=False, suffix=".jsonl") + self.log.close() + os.environ["FAKE_MCP_LOG"] = self.log.name + self.hub = McpHub({"fake": stdio(), "broken": stdio("--crash-at-start")}, + {"timeout_s": 10, "max_result_chars": 500, "max_rounds": 2}) + self.hub.start(wait=True) + self.httpd = None + + def tearDown(self): + if self.httpd: + self.httpd.shutdown() + self.httpd.server_close() + self.hub.close() + del os.environ["FAKE_MCP_LOG"] + os.unlink(self.log.name) + + def start(self, *scripts, delay_s=0.0): + tok = ByteTokenizer() + self.engine = ScriptedEngine(tok, list(scripts), delay_s=delay_s) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc.mcp = self.hub + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def post(self, body, headers=None, stream=True): + body = {"model": "m", "messages": [{"role": "user", "content": "check it"}], "stream": stream, **body} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", **(headers or {})}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + text = r.read().decode() + return r.status, text + except urllib.error.HTTPError as e: + with e: + return e.code, e.read().decode() + + @staticmethod + def chunks(text): + return [json.loads(line[6:]) for line in text.splitlines() if line.startswith("data: {")] + + def test_tool_call_then_answer(self): + self.start(call_script("fake__echo", text="hello from the tool"), "\n\nThe tool said hello.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + cs = self.chunks(text) + mcp = [c["strata_mcp"] for c in cs if "strata_mcp" in c] + self.assertEqual([m["event"] for m in mcp], ["start", "call", "result"]) + self.assertEqual(mcp[1]["arguments"], {"text": "hello from the tool"}) + self.assertEqual((mcp[1]["server"], mcp[1]["tool"]), ("fake", "echo")) + self.assertEqual((mcp[2]["ok"], mcp[2]["text"]), (True, "hello from the tool")) + self.assertEqual(len({m["id"] for m in mcp}), 1) + content = "".join((c["choices"][0]["delta"].get("content") or "") for c in cs) + self.assertEqual(content, "Let me check.The tool said hello.") + self.assertFalse([c for c in cs if c["choices"][0]["delta"].get("tool_calls")]) # nothing for the client to run + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + self.assertEqual(len(self.engine.prompts), 2) + first, second = self.engine.prompt_text(0), self.engine.prompt_text(1) + self.assertIn('"name": "fake__echo"', first) # the MCP tools are in the prompt + self.assertNotIn("broken__", first) # the server that failed is left out + self.assertIn("\n\nhello from the tool\n", second) + self.assertIn("\nhello from the tool\n", second) + self.assertEqual(cs[-1]["usage"]["prompt_tokens"], len(self.engine.prompts[1])) + + def test_a_call_the_output_ends_inside_is_not_run(self): + """#211: the model's turn ends inside an MCP call: nothing runs (it used to run with no arguments).""" + script = call_script("fake__echo", text="hello from the tool") + self.start(script[:script.index("from the tool")], "\n\nnever") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + cs = self.chunks(text) + mcp = [c["strata_mcp"] for c in cs if "strata_mcp" in c] + self.assertEqual([m["event"] for m in mcp], ["start"]) # the web app shows it as "Not run" at the end + self.assertEqual(len(self.engine.prompts), 1) + self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop") + + def test_non_stream(self): + self.start(call_script("fake__add", a=2, b=3), "\n\n5.") + code, text = self.post({"strata_mcp": True}, stream=False) + self.assertEqual(code, 200, text) + msg = json.loads(text)["choices"][0]["message"] + self.assertEqual(msg["content"], "Let me check.5.") + self.assertEqual(msg["strata_mcp"][-1]["text"], "5") + + def test_plain_requests_get_no_mcp_tools(self): + self.start(call_script("fake__echo", text="x"), "\n\nnever") + code, text = self.post({}) + self.assertEqual(code, 200, text) + self.assertNotIn("fake__echo", self.engine.prompt_text(0)) + cs = self.chunks(text) + self.assertFalse([c for c in cs if "strata_mcp" in c]) + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "tool_calls") # returned to the client as always + self.assertEqual(len(self.engine.prompts), 1) + self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran + for req in ({"strata_mcp": "yes"}, {"strata_mcp": 1}): # only a real true opts in + self.post(req) + self.assertNotIn("fake__echo", self.engine.prompt_text(-1)) + + def test_own_tools_still_go_to_the_client(self): + own = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": { + "q": {"type": "string"}}}}}] + self.start(call_script("lookup", q="x"), "\n\nnever") + code, text = self.post({"strata_mcp": True, "tools": own}) + cs = self.chunks(text) + calls = [tc for c in cs for tc in c["choices"][0]["delta"].get("tool_calls") or []] + self.assertEqual(calls[0]["function"]["name"], "lookup") + self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "tool_calls") + self.assertIn('"name": "lookup"', self.engine.prompt_text(0)) + self.assertIn('"name": "fake__echo"', self.engine.prompt_text(0)) + self.assertEqual(len(self.engine.prompts), 1) + + def test_tool_error_is_a_result(self): + self.start(call_script("fake__fail"), "\n\nIt failed.") + code, text = self.post({"strata_mcp": True}) + mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] + self.assertEqual((mcp[-1]["ok"], mcp[-1]["text"]), (False, "error: it failed on purpose")) + self.assertIn("\nerror: it failed on purpose\n", self.engine.prompt_text(1)) + self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + + def test_truncated_for_the_model(self): + self.start(call_script("fake__big", n=3000), "\n\nLong.") + self.post({"strata_mcp": True}) + second = self.engine.prompt_text(1) + self.assertIn("y" * 500 + "\n\n[... truncated: the tool returned 3,000 characters", second) + self.assertNotIn("y" * 501, second) + + def test_max_rounds(self): + self.start(call_script("fake__echo", text="again")) # the model never stops calling + code, text = self.post({"strata_mcp": True}) + mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] + self.assertEqual(len(self.engine.prompts), 3) # 2 rounds of tools, then the limit + self.assertEqual(sum(m["event"] == "call" for m in mcp), 2) + self.assertIn({"event": "limit", "max_rounds": 2}, mcp) + self.assertTrue(mcp[-1].get("skipped")) + self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + + def test_stop_during_a_tool(self): + """Closing the connection while a slow tool runs stops the tool (notifications/cancelled) and the loop.""" + self.start(call_script("fake__sleep", seconds=8), "\n\nnever") + body = {"model": "m", "messages": [{"role": "user", "content": "x"}], "stream": True, "strata_mcp": True} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + r = urllib.request.urlopen(req, timeout=30) + for raw in r: + if b'"event": "call"' in raw: + break + r.close() # the web app's Stop aborts the fetch + t0 = time.monotonic() + while time.monotonic() - t0 < 6 and "cancelled" not in Path(self.log.name).read_text(): + time.sleep(0.1) + self.assertIn("cancelled", Path(self.log.name).read_text()) + self.assertLess(time.monotonic() - t0, 6) + time.sleep(0.5) + self.assertEqual(len(self.engine.prompts), 1) # no second round + self.assertFalse(self.svc.status["busy"]) + + def test_only_from_the_app_s_own_page(self): + self.start("\n\nhi") + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps( + {"model": "m", "messages": [{"role": "user", "content": "x"}], "strata_mcp": True}).encode(), + headers={"Content-Type": "text/plain"}) # a cross-site "simple" request + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(req, timeout=10) + self.assertEqual(ctx.exception.code, 415) + code, _ = self.post({"strata_mcp": True}, {"Origin": "http://evil.example"}) + self.assertEqual(code, 403) + self.assertEqual(self.engine.prompts, []) + host = self.base.split("://", 1)[1] + code, _ = self.post({"strata_mcp": True}, {"Origin": "http://" + host}) + self.assertEqual(code, 200) + + def test_get_mcp(self): + self.start("\n\nhi") + with urllib.request.urlopen(self.base + "/mcp", timeout=10) as r: + st = json.loads(r.read()) + servers = {s["name"]: s for s in st["servers"]} + self.assertEqual(servers["fake"]["status"], "ready") + self.assertEqual(servers["fake"]["transport"], "stdio") + self.assertIn("fake__echo", [t["name"] for t in servers["fake"]["tools"]]) + self.assertEqual(servers["broken"]["status"], "failed") + self.assertIn("missing configuration", servers["broken"]["error"]) + self.assertEqual(st["tools"], len(fake.TOOLS)) + self.assertEqual(st["settings"]["max_rounds"], 2) + self.svc.api_key = "k" + with self.assertRaises(urllib.error.HTTPError): + urllib.request.urlopen(self.base + "/mcp", timeout=10) + self.svc.api_key = "" + + +class NoServers(unittest.TestCase): + def test_opt_in_without_servers_is_a_plain_chat(self): + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ["\n\nhi"]), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + base = f"http://127.0.0.1:{httpd.server_address[1]}" + with urllib.request.urlopen(base + "/mcp", timeout=10) as r: + self.assertEqual(json.loads(r.read()), {"servers": [], "tools": 0}) + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps( + {"model": "m", "messages": [{"role": "user", "content": "x"}], "strata_mcp": True}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(json.loads(r.read())["choices"][0]["message"]["content"], "hi") + finally: + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_monitor.py b/engine/strata/serve/test_monitor.py new file mode 100644 index 00000000..ad554e00 --- /dev/null +++ b/engine/strata/serve/test_monitor.py @@ -0,0 +1,198 @@ +"""Request inspection through HTTP; no native model or GPU is required.""" +import json +import threading +import time +import unittest +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve + + +class ReloadableEngine(MockEngine): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.running, self.unloaded = True, False + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + + +class MonitorOff(unittest.TestCase): + """#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist.""" + + def test_off_by_default(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok, + ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode()) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertEqual(len(svc.api_requests), 0) + for path in ("/api/requests", "/api-monitor"): + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base + path, timeout=10) + self.assertEqual(e.exception.code, 404, path) + e.exception.close() + finally: + httpd.shutdown() + httpd.server_close() + + +class Monitor(unittest.TestCase): + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ReloadableEngine(self.tok, "Thought.\nHello .", max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.svc.api_monitor = True # opt-in ("api_monitor": true / --api-monitor) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read().decode() + return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw + + def chat(self, api="openai", **kwargs): + # Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI + think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else {"reasoning_effort": "low"} + return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions", + {"messages": [{"role": "user", "content": "Say hello."}], + "max_tokens": 256, **think, **kwargs}) + + def latest(self): + summary = self.request("/api/requests")[1]["requests"][0] + return self.request("/api/requests?id=" + summary["id"])[1] + + def test_output_and_reasoning_for_both_dialects_and_stream_modes(self): + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream): + code, reply = self.chat(api, stream=stream) + self.assertEqual(code, 200) + record = self.latest() + self.assertEqual(record["state"], "completed") + self.assertEqual(record["http_status"], 200) + self.assertIn("Say hello.", record["input"]) + self.assertIn("", record["output"]) + self.assertIn("Thought.", record["reasoning"]) + self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0) + self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"]) + self.assertNotIn("_clock", record) + if not stream: + self.assertEqual(json.loads(record["response"]), reply) + else: + self.assertNotIn("response", record) + + def test_error_and_engine_death_are_not_successes(self): + self.assertEqual(self.chat(max_tokens=20000)[0], 400) + self.assertEqual(self.latest()["state"], "error") + for api in ("openai", "anthropic"): + for stream in (False, True): + with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")): + self.chat(api, stream=stream) + record = self.latest() + self.assertEqual(record["state"], "error") + self.assertIn("stopped", record["error"]["message"]) + self.assertEqual(record["output"], "") + self.assertNotIn("timings", record) + + def test_history_is_authorized_and_does_not_capture_headers(self): + self.svc.api_key = "secret" + auth = {"Authorization": "Bearer secret"} + self.assertEqual(self.request("/api/requests")[0], 401) + self.assertEqual(self.request("/api/requests?id=missing")[0], 401) + self.assertEqual(len(self.svc.api_requests), 0) + self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200) + summary = self.request("/api/requests", headers=auth)[1]["requests"][0] + self.assertNotIn("input", summary) + self.assertNotIn("output", summary) + self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401) + detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1] + self.assertNotIn("secret", json.dumps(detail)) + + def test_capture_is_bounded_and_eviction_returns_404(self): + huge = "x" * 262200 + first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]}) + self.assertEqual(len(first["input"]), 262144) + self.assertTrue(first["input_truncated"]) + for _ in range(100): + self.svc.begin_request("/v1/chat/completions", {"messages": []}) + self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100) + self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404) + # Exercise output capture without making a mock engine emit 262K tokens. + handler = object.__new__(self.httpd.RequestHandlerClass) + handler.record = self.svc.api_requests[-1] + chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]} + list(handler._capture((item for item in [chunk]), "openai")) + for field in ("output", "reasoning"): + self.assertEqual(len(handler.record[field]), 262144) + self.assertTrue(handler.record[field + "_truncated"]) + + def test_queue_wait_and_loading_are_attributed_separately(self): + self.engine.unload() + entered, release = threading.Event(), threading.Event() + original = self.engine.restart + def restart(): + entered.set() + self.assertTrue(release.wait(5)) + original() + with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(self.chat) + self.assertTrue(entered.wait(5)) + second = pool.submit(self.chat) + deadline = time.monotonic() + 5 + while len(self.svc.api_requests) < 2 and time.monotonic() < deadline: + time.sleep(0.01) + self.assertEqual(len(self.svc.api_requests), 2) + history = self.request("/api/requests")[1] + self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"}) + self.assertFalse(history["loaded"]) + self.assertTrue(history["auto_load"]) + time.sleep(0.03) + release.set() + self.assertEqual(first.result()[0], 200) + self.assertEqual(second.result()[0], 200) + records = list(self.svc.api_requests) + self.assertGreater(records[0]["load_s"], 0.02) + self.assertGreater(records[1]["queue_s"], 0.02) + self.assertLess(records[1]["load_s"], records[0]["load_s"]) + self.assertTrue(all(r["state"] == "completed" for r in records)) + + def test_page_and_relative_assets_are_served(self): + code, html = self.request("/api-monitor") + self.assertEqual(code, 200) + self.assertIn('src="/web/monitor.js"', html) + code, script = self.request("/web/monitor.js") + self.assertEqual(code, 200) + self.assertIn("textContent", script) + self.assertNotIn("innerHTML", script) + self.assertEqual(self.request("/web/../server.py")[0], 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_server.py b/engine/strata/serve/test_server.py new file mode 100644 index 00000000..76ac5e5e --- /dev/null +++ b/engine/strata/serve/test_server.py @@ -0,0 +1,1915 @@ +"""serve/test_server.py - the max tokens budget over both APIs, against the mock engine (no GPU, no pack). + + python -m unittest serve.test_server -v +""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import threading +import time +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, Service, StrataEngine, request_timings, serve # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +CTX = 4096 +ANSWER = "x" * 2000 # longer than the old 1024 fallback: one token per byte + + +class RecordingEngine(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_max_new = max_new + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class MaxTokens(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def call(self, api, text="hi", **budget): + """-> (status, body, prompt tokens, completion tokens); `budget` is merged into the request as given.""" + msgs = [{"role": "user", "content": text}] + if api == "openai": + s, b = self.post("/v1/chat/completions", {"model": "m", "messages": msgs, **budget}) + u = b.get("usage", {}) + return s, b, u.get("prompt_tokens"), u.get("completion_tokens") + s, b = self.post("/v1/messages", {"model": "m", "messages": msgs, **budget}) + u = b.get("usage", {}) + return s, b, u.get("input_tokens"), u.get("output_tokens") + + def test_anthropic_thinks_only_when_asked(self): + # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it + from serve.frontend import anthropic_to_messages + msgs = [{"role": "user", "content": "u"}] + kw = lambda **r: anthropic_to_messages({"messages": msgs, **r}, think_unasked=False)[2] # noqa: E731 + # the default ("anthropic_thinking": "model") renders an unasked request as 0.1.31 did + self.assertNotIn("enable_thinking", anthropic_to_messages({"messages": msgs})[2]) + self.assertEqual(kw(), {"enable_thinking": False}) + self.assertEqual(kw(thinking={"type": "disabled"}), {"enable_thinking": False}) + self.assertNotIn("enable_thinking", kw(thinking={"type": "enabled", "budget_tokens": 2048})) + self.assertNotIn("enable_thinking", kw(output_config={"effort": "high"})) + self.assertNotIn("enable_thinking", kw(reasoning_budget_tokens=30)) + + def test_count_tokens_is_the_prompt_messages_reads(self): + # /v1/messages/count_tokens renders and tokenizes the same prompt /v1/messages would read, without running it + msgs = [{"role": "user", "content": "how many tokens is this?"}] + s, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": msgs}) + self.assertEqual(s, 200) + s2, _, n_in, _ = self.call("anthropic", "how many tokens is this?", max_tokens=8) + self.assertEqual(s2, 200) + self.assertEqual(b["input_tokens"], n_in) + + def test_request_line_parses_the_engine_summary(self): + line = ("strata serve: prompt 1200 tokens = 1000 reused + 200 read in 50 ms (4000.0 tok/s), 30 generated in " + "300 ms (100.0 tok/s), drafts accepted 20 of 28, 2 checkpoints") + from serve.server import ENGINE_REQUEST + m = ENGINE_REQUEST.search(line) + self.assertIsNotNone(m) + self.assertEqual((m["prompt"], m["reused"], m["gen"], m["tg"]), ("1200", "1000", "30", "100.0")) + + def test_unset_budget_is_the_rest_of_the_context(self): + cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}, + {"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}], + "anthropic": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}]} + for api, budgets in cases.items(): + for budget in budgets: + with self.subTest(api=api, budget=budget): + s, b, pt, ct = self.call(api, **budget) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) + self.assertGreater(ct, 1024) # the whole answer, not cut at the old 1024 fallback + + def test_explicit_budget_is_honoured(self): + for api, budget in [("openai", {"max_tokens": 50}), ("openai", {"max_completion_tokens": 50}), + ("openai", {"max_completion_tokens": 50, "max_tokens": 9}), + ("anthropic", {"max_tokens": 50}), ("openai", {"max_tokens": 1500}), + ("anthropic", {"max_tokens": 1500})]: + with self.subTest(api=api, budget=budget): + want = budget.get("max_completion_tokens") or budget["max_tokens"] + s, b, _, ct = self.call(api, **budget) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, want) + self.assertEqual(ct, want) + + def test_explicit_budget_over_the_context_is_rejected(self): + for api in ("openai", "anthropic"): + with self.subTest(api=api): + s, b, _, _ = self.call(api, max_tokens=CTX) + self.assertEqual(s, 400) + self.assertIn("exceeds the context", b["error"]["message"]) + + def test_unset_budget_with_a_near_full_prompt(self): + _, _, pt0, _ = self.call("openai", max_tokens=1) + overhead = pt0 - len("hi") # the template's tokens around the user text + for api in ("openai", "anthropic"): + _, _, pa, _ = self.call(api, max_tokens=1) + over = pa - pt0 # the Anthropic template may differ slightly + with self.subTest(api=api, room=5): # a few tokens left: the budget is exactly those + text = "y" * (CTX - CTX_SLACK - overhead - over - 5) + s, b, pt, ct = self.call(api, text=text, max_tokens=-1) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, 5) + self.assertEqual(ct, 5) + with self.subTest(api=api, room=0): # nothing left: rejected, not truncated + text = "y" * (CTX - CTX_SLACK - overhead - over) + s, b, _, _ = self.call(api, text=text) + self.assertEqual(s, 400, b) + self.assertIn("no room to answer", b["error"]["message"]) + + def test_debug_log_shows_the_resolved_budget(self): + import contextlib + import io + os.environ["STRATA_DEBUG"] = "1" + try: + for api in ("openai", "anthropic"): + with self.subTest(api=api): + out = io.StringIO() + with contextlib.redirect_stdout(out): + _, _, pt, _ = self.call(api, max_tokens=-1) + self.assertIn(f"max_new={CTX - CTX_SLACK - pt} ", out.getvalue()) + finally: + del os.environ["STRATA_DEBUG"] + + +class FitMaxTokens(unittest.TestCase): + """PR #24: --fit-max-tokens clamps an explicit budget that overshoots the context instead of a 400.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), fit_max_tokens=True) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + post = MaxTokens.post + call = MaxTokens.call + + def test_overshoot_is_clamped_to_the_room(self): + for api in ("openai", "anthropic"): + with self.subTest(api=api): + s, b, pt, ct = self.call(api, max_tokens=CTX) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) + + def test_a_budget_that_fits_is_unchanged(self): + s, b, _, ct = self.call("openai", max_tokens=50) + self.assertEqual(s, 200, b) + self.assertEqual(self.engine.last_max_new, 50) + + def test_no_room_is_still_a_400(self): + _, _, pt0, _ = self.call("openai", max_tokens=1) + overhead = pt0 - len("hi") + s, b, _, _ = self.call("openai", text="y" * (CTX - CTX_SLACK - overhead), max_tokens=100) + self.assertEqual(s, 400, b) + self.assertIn("no room to answer", b["error"]["message"]) + + +class ImageMarkers(unittest.TestCase): + """#150: the text "<|image_pad|>" inside a message is text, not an image's place.""" + + class FakeVision: + def __init__(self, d): + self.dir = Path(d) + self.rows = self.dir / "img.sve" + self.rows.write_bytes(b"rows") + + def encode(self, source): + return self.rows, 3 + + def test_literal_marker_with_an_image(self): + import tempfile + tok = ByteTokenizer() + with tempfile.TemporaryDirectory() as d: + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), + vision=self.FakeVision(d)) + pad = tok.encode("<|image_pad|>", parse_special=True)[0] + for text in ("the docs say <|image_pad|> marks an image", "plain"): + with self.subTest(text=text): + msgs = [{"role": "user", "content": [{"type": "text", "text": text}, + {"type": "image", "source": "x.png"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + self.assertEqual(ids.count(pad), 3) # the image's three rows, nothing else + self.assertIn("<|image_pad|> marks" if "docs" in text else "plain", tok.decode(ids)) + svc.embeddings.path.unlink(missing_ok=True) + + +class StatusNeedsTheKey(unittest.TestCase): + """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" + + def test_status(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.api_key = "k3y" + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}/status" + try: + with self.assertRaises(urllib.error.HTTPError) as e: + urllib.request.urlopen(base, timeout=10) + self.assertEqual(e.exception.code, 401) + e.exception.close() + req = urllib.request.Request(base, headers={"Authorization": "Bearer k3y"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.status, 200) + self.assertNotIn("tail", json.loads(r.read())) + finally: + httpd.shutdown() + httpd.server_close() + + +class ToolCallTerminators(unittest.TestCase): + """#210: a value that contains or (a file documenting the call format) is kept whole.""" + CONTENT = ("Close each value with and the call with .\n" + "\nnot a parameter\n\nend") + SCHEMA = [{"name": "write", "parameters": {"properties": {"path": {"type": "string"}, + "content": {"type": "string"}}}}] + + def run_parser(self, stream_tools, step): + from serve.frontend import OutputParser + text = ("\n\n\n\n\ndoc.md\n\n" + f"\n{self.CONTENT}\n\n\n") + p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + return evs + + def test_values_keep_the_terminators(self): + for stream_tools in (False, True): + for step in (1, 7, 10_000): + with self.subTest(stream_tools=stream_tools, step=step): + evs = self.run_parser(stream_tools, step) + calls = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0].arguments, {"path": "doc.md", "content": self.CONTENT}) + self.assertFalse([e for e in evs if e.kind == "content" and e.text.strip()]) + if stream_tools: + streamed = "".join(e.text for e in evs if e.kind == "tool_args") + self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT}) + + +class UnfinishedToolCall(unittest.TestCase): + """#211: a call the output ends inside is not reported as a whole one - its streamed JSON is not closed and the + finish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run.""" + CALL = ("\n\n\n\n\nnotes.txt\n\n" + "\n") + CUT = CALL + "first half of the fi" # the model's turn ends here + WHOLE = CALL + "all of it\n\n\n" + PROPS = {"path": {"type": "string"}, "content": {"type": "string"}} + + def test_parser(self): + from serve.frontend import OutputParser + schema = [{"name": "write", "parameters": {"properties": self.PROPS}}] + for text, content in ((self.CUT, None), (self.WHOLE, "all of it"), + (self.WHOLE[:-len("
")], "all of it")): # only
missing: whole + for step in (1, 7, 10_000): + with self.subTest(end=text[-12:], step=step): + p = OutputParser(thinking=True, tools=schema, stream_tools=True) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + evs += p.finish() + streamed = "".join(e.text for e in evs if e.kind == "tool_args") + calls = [e for e in evs if e.kind == "tool_call"] + if content is None: + self.assertEqual((calls, streamed), ([], '{"path":"notes.txt","content":"first half of the fi')) + else: + self.assertEqual(len(calls), 1) + self.assertEqual(json.loads(streamed), {"path": "notes.txt", "content": content}) + + def answers(self, script, max_tokens=500): + """(finish reason, the call's arguments) from OpenAI and Anthropic, whole and streamed, for the model's `script`.""" + tok = ByteTokenizer() + svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + tools = {"openai": [{"type": "function", "function": {"name": "write", "parameters": { + "type": "object", "properties": self.PROPS}}}], + "anthropic": [{"name": "write", "input_schema": {"type": "object", "properties": self.PROPS}}]} + out = {} + try: + for api, path in (("openai", "/v1/chat/completions"), ("anthropic", "/v1/messages")): + for stream in (False, True): + body = {"model": "x", "max_tokens": max_tokens, "stream": stream, "tools": tools[api], + "messages": [{"role": "user", "content": "save my notes"}]} + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + if stream: + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + if api == "openai": + out[api, stream] = (evs[-1]["choices"][0]["finish_reason"], "".join( + (tc.get("function") or {}).get("arguments") or "" for e in evs + for tc in e["choices"][0]["delta"].get("tool_calls") or [])) + else: + out[api, stream] = (evs[-2]["delta"]["stop_reason"], "".join( + e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta" + and e["delta"]["type"] == "input_json_delta")) + elif api == "openai": + c = json.loads(raw)["choices"][0] + out[api, stream] = (c["finish_reason"], [tc["function"]["arguments"] + for tc in c["message"].get("tool_calls") or []]) + else: + m = json.loads(raw) + out[api, stream] = (m["stop_reason"], [b["input"] for b in m["content"] if b["type"] == "tool_use"]) + finally: + httpd.shutdown() + httpd.server_close() + return out + + def test_a_cut_call(self): + cut = '{"path":"notes.txt","content":"first half of the fi' + self.assertEqual(self.answers(self.CUT), { + ("openai", False): ("stop", []), ("openai", True): ("stop", cut), # whole answers leave the cut + ("anthropic", False): ("end_turn", []), # call out: it has no arguments to give + ("anthropic", True): ("end_turn", cut)}) + + def test_a_call_cut_at_the_token_limit(self): + """The same cut by max_tokens: "length" / "max_tokens", and the whole (non-streamed) answers leave the call + out in both APIs.""" + a = self.answers(self.CUT + "rest of the file, never reached" * 40, max_tokens=len(self.CUT)) + self.assertEqual((a["openai", False], a["anthropic", False]), (("length", []), ("max_tokens", []))) + self.assertEqual((a["openai", True][0], a["anthropic", True][0]), ("length", "max_tokens")) + + def test_collect_keeps_calls_whose_arguments_parse(self): + from serve.server import openai_collect + + def chunk(delta, finish=None): + return {"id": "c", "created": 1, "model": "m", "usage": {}, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} + whole = {"index": 0, "id": "a", "type": "function", "function": {"name": "f", "arguments": '{"x": 1}'}} + cut = {"index": 1, "id": "b", "type": "function", "function": {"name": "g", "arguments": '{"y": "ha'}} + for finish, want in (("stop", ["a"]), ("length", ["a"]), ("tool_calls", ["a", "b"])): + with self.subTest(finish=finish): + msg = openai_collect([chunk({"tool_calls": [whole]}), chunk({"tool_calls": [cut]}), + chunk({}, finish)])["choices"][0]["message"] + self.assertEqual([c["id"] for c in msg["tool_calls"]], want) + msg = openai_collect([chunk({"tool_calls": [cut]}), chunk({}, "stop")])["choices"][0]["message"] + self.assertNotIn("tool_calls", msg) + + def test_a_whole_call(self): + whole = {"path": "notes.txt", "content": "all of it"} + a = self.answers(self.WHOLE) + self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]), ("tool_calls", [whole])) + self.assertEqual((a["openai", True][0], json.loads(a["openai", True][1])), ("tool_calls", whole)) + self.assertEqual(a["anthropic", False], ("tool_use", [whole])) + self.assertEqual((a["anthropic", True][0], json.loads(a["anthropic", True][1])), ("tool_use", whole)) + + +class ClientShapes(unittest.TestCase): + """What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the + conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = RecordingPrompt(tok, "\n\n2", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def prompt_text(self): + return bytes(i for i in self.engine.last_ids if i < 256).decode("utf-8", "replace") + + def test_query_string(self): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]} + for path in ("/v1/messages?beta=true", "/v1/chat/completions?api-version=1", "/v1/messages/?beta=true"): + status, b = self.post(path, body) + self.assertEqual(status, 200, (path, b)) + status, _ = self.post("/v1/nothing?beta=true", body) + self.assertEqual(status, 404) + + def test_anthropic_mid_conversation_system(self): + status, b = self.post("/v1/messages?beta=true", { + "model": "x", "max_tokens": 50, + "system": [{"type": "text", "text": "You are terse."}], + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "1+1? digits only"}]}, + {"role": "system", "content": [{"type": "text", "text": "answer in digits"}]}]}) + self.assertEqual(status, 200, b) + text = self.prompt_text() + self.assertIn("You are terse.", text) + self.assertIn("answer in digits", text) + self.assertLess(text.index("You are terse."), text.index("1+1?")) # the first system stays first + self.assertLess(text.index("1+1?"), text.index("answer in digits")) # the late one stays in place + + def test_openai_late_developer_and_system(self): + status, b = self.post("/v1/chat/completions", { + "model": "x", "max_tokens": 50, + "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "hi"}, {"role": "developer", "content": "Now use digits."}, + {"role": "system", "content": "Also this."}, {"role": "user", "content": "1+1?"}]}) + self.assertEqual(status, 200, b) + text = self.prompt_text() + for part in ("Be brief.", "Now use digits.", "Also this.", "1+1?"): + self.assertIn(part, text) + + def test_no_user_turn_is_a_400(self): + # #365: the template's own refusal (Qwen's "No user query found in messages." when no turn is a user's query) + # answers 400, not a dropped connection + with tempfile.TemporaryDirectory() as d: + tpl = Path(d) / "chat_template.jinja" + tpl.write_text("{% if messages[-1].role != 'user' %}{{ raise_exception('No user query found in messages.') }}" + "{% endif %}{{ messages[-1].content }}", encoding="utf-8") + template, self.svc.template = self.svc.template, ChatTemplate(tpl) + try: + status, b = self.post("/v1/chat/completions", { + "model": "x", "max_tokens": 20, "messages": [{"role": "system", "content": "Only a system."}]}) + self.assertEqual(status, 400, b) + self.assertIn("No user query found", b["error"]["message"]) + finally: + self.svc.template = template + status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]}) + self.assertEqual(status, 200, b) # the server goes on + + def test_messages_as_a_json_string_over_http(self): + # #460: a double-encoded "messages" is answered; one that is not a list of objects is a 400, not a 500 + encoded = json.dumps([{"role": "user", "content": "1+1?"}]) + for path in ("/v1/chat/completions", "/v1/messages"): + with self.subTest(path=path): + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": encoded}) + self.assertEqual(status, 200, b) + self.assertIn("1+1?", self.prompt_text()) + status, b = self.post(path, {"model": "x", "max_tokens": 20, "messages": ["hi"]}) + self.assertEqual(status, 400, b) + self.assertIn("messages must be a list of objects", b["error"]["message"]) + + def test_vision_temp_image_removed_when_the_pipe_fails(self): + # #352: the temporary image goes even when the encoder's pipe raises + from serve.server import Vision + + class Gone: + def write(self, _): + raise BrokenPipeError("the encoder is gone") + + v = Vision.__new__(Vision) + v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {} + v.proc = mock.Mock(stdin=Gone()) + with mock.patch.object(Vision, "load", return_value=b""), mock.patch.object(Vision, "normalize", + return_value=b"png"): + with self.assertRaises(BrokenPipeError): + v.encode("x") + self.assertEqual(list(v.dir.iterdir()), []) + v.dir.rmdir() + + def test_leading_system_unchanged(self): + from serve.frontend import anthropic_to_messages, openai_to_messages + msgs, _, _ = openai_to_messages({"messages": [{"role": "developer", "content": "D"}, {"role": "user", "content": "u"}]}) + self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]}) + self.assertEqual([m["role"] for m in msgs], ["system", "user"]) + + def test_messages_sent_as_a_json_string(self): + # #460: a client that double-encodes "messages" (and "tool_calls") as a JSON string gets them decoded; what is + # still not a list of objects is a ValueError (the server's 400), not an AttributeError on m.get + from serve.frontend import anthropic_to_messages, openai_to_messages + call = [{"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{\"x\": 1}"}}] + listed = [{"role": "user", "content": "u"}, {"role": "assistant", "content": "", "tool_calls": call}] + encoded = [listed[0], dict(listed[1], tool_calls=json.dumps(call))] + want = openai_to_messages({"messages": listed})[0] + self.assertEqual(want[1]["tool_calls"], [{"function": {"name": "f", "arguments": {"x": 1}}}]) + self.assertEqual(openai_to_messages({"messages": json.dumps(listed)})[0], want) + self.assertEqual(openai_to_messages({"messages": json.dumps(encoded)})[0], want) + anth = [{"role": "user", "content": "u"}] + self.assertEqual(anthropic_to_messages({"messages": json.dumps(anth)})[0], + anthropic_to_messages({"messages": anth})[0]) + self.assertEqual(openai_to_messages({})[0], []) # no field: nothing, as before + self.assertEqual(openai_to_messages({"messages": None})[0], []) + for bad in ("not json", "\"a string\"", json.dumps({"role": "user"}), ["hi"], [{"role": "user"}, 3], 5, + {"role": "user", "content": "u"}): + for fn in (openai_to_messages, anthropic_to_messages): + with self.subTest(bad=bad, fn=fn.__name__): + with self.assertRaisesRegex(ValueError, "messages must be a list of objects"): + fn({"messages": bad}) + for calls in (["f"], "[1]", [{"function": "f"}], "{"): + with self.subTest(calls=calls), self.assertRaisesRegex(ValueError, "tool_calls must be a list of objects"): + openai_to_messages({"messages": [{"role": "assistant", "content": "", "tool_calls": calls}]}) + + +class SamplingKeys(unittest.TestCase): + """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used + to fall back to the engine default 20); a penalty always carries its window.""" + + def keys(self, **sampling): + return StrataEngine.sampling_keys(sampling).split() + + def test_top_k(self): + self.assertIn("top_k=10", self.keys(temperature=0.7, top_k=10)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=64)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=0)) + self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=100)) + for bad in (-1, True, 2.5, "20"): + self.assertFalse([k for k in self.keys(temperature=0.7, top_k=bad) if k.startswith("top_k=")], bad) + + def test_tune_keys(self): + k = self.keys(temperature=0, strata_tune={"pcie_frac": 0.2, "spec_min_p": 0.7}) + self.assertIn("pcie_frac=0.2", k) + self.assertIn("spec_min_p=0.7", k) + bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) + self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) + + def test_penalty_window(self): + self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5)) + self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096)) + self.assertFalse([k for k in self.keys(temperature=0.7) if k.startswith("penalty")]) + + +class GpuChoice(unittest.TestCase): + """Issue #51: the config's \"gpu\" reaches the engine as CUDA_VISIBLE_DEVICES, numbered like nvidia-smi.""" + + def test_env(self): + from serve.server import child_env + env = child_env({"gpu": 1}) + self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "1") + self.assertEqual(env["CUDA_DEVICE_ORDER"], "PCI_BUS_ID") + plain = child_env({}) # no choice: the environment as it was (existing installs) + self.assertEqual(plain.get("CUDA_VISIBLE_DEVICES"), os.environ.get("CUDA_VISIBLE_DEVICES")) + self.assertEqual(plain.get("CUDA_DEVICE_ORDER"), os.environ.get("CUDA_DEVICE_ORDER")) + + def test_vision_device(self): + # #408: the image encoder on its own card; the engine's environment stays as it was + from serve.server import child_env, vision_env + cfg = {"gpu": [0, 1], "vision": {"exe": "v", "cuda_device": 2}} + env = child_env(cfg) + venv = vision_env(cfg, env) + self.assertEqual(venv["CUDA_VISIBLE_DEVICES"], "2") + self.assertEqual(venv["CUDA_DEVICE_ORDER"], "PCI_BUS_ID") + self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "0,1") + plain = {"gpu": [0, 1], "vision": {"exe": "v"}} + self.assertIs(vision_env(plain, env), env) # no cuda_device: the engine's environment, unchanged + + def test_hip_ordinal(self): + """#325: on Windows the HIP ordinal setup resolved wins over the config's "gpu" (an iGPU takes HIP's 0).""" + from serve.server import child_env + self.assertEqual(child_env({"backend": "hip", "gpu": 1})["HIP_VISIBLE_DEVICES"], "1") # Linux: KFD order + self.assertEqual(child_env({"backend": "hip", "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": 1})["HIP_VISIBLE_DEVICES"], "1") + self.assertEqual(child_env({"backend": "hip", "gpu": [1, 0], "hip_ordinal": 2})["HIP_VISIBLE_DEVICES"], + "1,0") # a layer split keeps its list + self.assertEqual(child_env({"backend": "hip", "gpu": 0, "hip_ordinal": "x"})["HIP_VISIBLE_DEVICES"], "0") + plain = child_env({"backend": "hip"}) + self.assertEqual(plain.get("HIP_VISIBLE_DEVICES"), os.environ.get("HIP_VISIBLE_DEVICES")) + + +class RecordingPrompt(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_ids = list(ids) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class DyingEngine(MockEngine): + """Issue #27: an engine that dies after a few tokens of its first answer, and comes back when restarted.""" + + def __init__(self, tok, script, max_context): + super().__init__(tok, script, max_context=max_context) + self.dead, self.restarts, self.die_after = False, 0, 5 + + def alive(self): + return not self.dead + + def restart(self): + self.dead, self.die_after = False, None + self.restarts += 1 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if self.die_after is not None and i == self.die_after: + self.dead = True + raise EngineDied("the engine stopped unexpectedly (exit code -9)") + yield t + + +class SlowPromptEngine(MockEngine): + """Reads a "long prompt" for up to 20 s without a token (the engine sends nothing then), stopping on cancel.""" + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.cancelled_after = None + t0 = time.monotonic() + while time.monotonic() - t0 < 20: + if cancel.is_set(): + self.cancelled_after = time.monotonic() - t0 + return + time.sleep(0.05) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class ClientHangUp(unittest.TestCase): + """#430 #431: a client that hangs up during a long prompt read cancels the request within about a second - + non-streamed (which writes nothing until the end) and streamed (one keep-alive per prompt chunk) alike.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = SlowPromptEngine(tok, "\n\nOK", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.port = cls.httpd.server_address[1] + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def hang_up(self, stream): + import socket as so + body = json.dumps({"model": "x", "max_tokens": 20, "stream": stream, + "messages": [{"role": "user", "content": "a long prompt"}]}).encode() + c = so.create_connection(("127.0.0.1", self.port)) + c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" + b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body) + time.sleep(1.0) + c.close() + t0 = time.monotonic() + while self.engine.cancelled_after is None and time.monotonic() - t0 < 10: + time.sleep(0.05) + self.assertIsNotNone(self.engine.cancelled_after, "the request was not cancelled") + self.assertLess(self.engine.cancelled_after, 3.0) + + def test_non_streamed(self): + self.hang_up(False) + + def test_streamed(self): + self.hang_up(True) + + +class EngineDeath(unittest.TestCase): + """Issue #27: a dead engine is an error (not "length"), and the next request starts it again.""" + + def test_error_then_restart(self): + tok = ByteTokenizer() + eng = DyingEngine(tok, "\n\n" + ANSWER, max_context=CTX) + svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + def post(body): + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read().decode() + except urllib.error.HTTPError as e: + with e: + return e.code, e.read().decode() + msgs = [{"role": "user", "content": "hi"}] + code, text = post({"model": "m", "messages": msgs, "max_tokens": 50, "stream": True}) + self.assertEqual(code, 200) + self.assertIn('"error"', text) + self.assertIn("stopped unexpectedly", text) + self.assertTrue(text.rstrip().endswith("data: [DONE]")) + self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") + code, text = post({"model": "m", "messages": msgs, "max_tokens": 50}) + self.assertEqual(code, 200, text) + self.assertEqual(eng.restarts, 1) + self.assertEqual(json.loads(text)["usage"]["completion_tokens"], 50) + finally: + httpd.shutdown() + httpd.server_close() + + def test_engine_err_mid_stream(self): + """The engine's ERR line after the stream started reaches the client as an error event (it used to be a + 400 written into the open stream, which clients read as an empty answer).""" + class ErrEngine(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + yield None # a prompt-progress heartbeat: the stream has started + raise ValueError("verify: layer 31 never rang (an illegal memory access was encountered)") + + tok = ByteTokenizer() + svc = Service(ErrEngine(tok, ANSWER, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for path, body in [("/v1/chat/completions", {"model": "m", "stream": True, "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]}), + ("/v1/messages", {"model": "m", "stream": True, "max_tokens": 20, + "messages": [{"role": "user", "content": "hi"}]})]: + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + text = r.read().decode() + self.assertIn("illegal memory access", text, path) + self.assertNotIn("HTTP/1", text, path) + self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") + finally: + httpd.shutdown() + httpd.server_close() + + +class DoneLineEngine(MockEngine): + """The mock engine whose `last` comes from a DONE line, parsed as StrataEngine parses it.""" + + def __init__(self, *a, done_lines=(), **kw): + super().__init__(*a, **kw) + self.done_lines = list(done_lines) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + try: + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + finally: + StrataEngine._parse_done(self, self.done_lines.pop(0)) + + +class DraftCounts(unittest.TestCase): + """#457: GET /metrics gives each request's speculative draft counts (offered / accepted, from the engine's DONE + line; None when the line has no such fields) and their running sums in the totals.""" + + def test_drafts_in_history_and_totals(self): + tok = ByteTokenizer() + engine = DoneLineEngine(tok, "\n\nok", max_context=CTX, done_lines=[ + "DONE 4 20 40.0 30.0 stop 7 12 0", # 7 of 12 drafts accepted + "DONE 4 20 40.0 30.0 stop", # an engine that reports no drafts + "DONE 4 20 40.0 30.0 stop 3 5 0 9 10"]) + svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.assertEqual((svc.totals["drafts_offered"], svc.totals["drafts_accepted"]), (0, 0)) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for _ in range(3): + body = json.dumps({"model": "m", "max_tokens": 10, "messages": [{"role": "user", "content": "hi"}]}) + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body.encode(), + headers={"Content-Type": "application/json"}), + timeout=30) as r: + self.assertEqual(r.status, 200) + with urllib.request.urlopen(base + "/metrics", timeout=10) as r: + m = json.loads(r.read()) + finally: + httpd.shutdown() + httpd.server_close() + rows = m["requests"] # newest first + self.assertEqual([(r["drafts_offered"], r["drafts_accepted"]) for r in rows], [(5, 3), (None, None), (12, 7)]) + self.assertEqual((m["totals"]["drafts_offered"], m["totals"]["drafts_accepted"]), (17, 10)) + + +class LiveRate(unittest.TestCase): + """The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters. + + It used to be `generated / (now - first_token)` - the mean since the first token, whose first sample is + 1/elapsed. Against a paced engine that reads five-digit numbers for the first instant of every answer and + undershoots for the first second after that. It is now the rate over the last RATE_WINDOW_S, with the mean + still available as `live.tok_s_mean` for anyone who wants it.""" + + PACE_S = 0.02 # 50 tokens/s: a 30-token answer takes about 0.6 s + TOKENS = 30 + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, "x" * self.TOKENS, max_context=CTX, delay_s=self.PACE_S) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def metrics(self): + with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r: + return json.loads(r.read()) + + def test_prefill_rate_excludes_cached_tokens(self): + import io + import queue + from types import SimpleNamespace + engine = StrataEngine.__new__(StrataEngine) + engine.proc = SimpleNamespace(stdin=io.StringIO(), poll=lambda: None) # alive() asks it (#208) + engine.lines = queue.Queue() + engine.can_stop = False + engine.max_context = 262144 + engine.prefill_tok_s_mean = 9999.0 + engine.lines.put("PP 10000 12000 2000 1000.0") # 8000 cached, 2000 newly read in two seconds + engine.lines.put("DONE 1 12000 4000 10 stop 0 0 8000") + gen = engine.generate([1], 1, {}, threading.Event()) + self.assertIsNone(next(gen)) + self.assertEqual(engine.progress, (10000, 12000)) + self.assertEqual(engine.prefill_tok_s_mean, 1000.0) + self.svc.engine = engine + self.svc.status.update(busy=True, first_token=None) + self.assertEqual(self.metrics()["live"]["prefill_tok_s_mean"], 1000.0) + self.assertNotIn("prefill_tok_s", self.metrics()["live"]) + self.assertEqual(self.svc._prefill_tok_s_mean(), 1000.0) + self.svc.status.update(first_token=time.time(), generated=1) + self.assertEqual(self.svc._prefill_tok_s_mean(), 0.0) + self.assertEqual(list(gen), []) + timings = request_timings(12000, 1, engine.last) + self.assertEqual(timings["prompt_per_second"], 1000.0) + engine.lines.put("PP 8000 12000") + engine.lines.put("DONE 0 12000 0 0 stop 0 0 12000") + gen = engine.generate([1], 1, {}, threading.Event()) + next(gen) + self.assertIsNone(engine.prefill_tok_s_mean) + list(gen) + self.svc.status["busy"] = False + self.assertIsNone(self.metrics()["live"]["prefill_tok_s_mean"]) + + def test_the_live_number_is_a_rate(self): + live_samples, stop = [], threading.Event() + + def poll(): # what the Monitor polls, at 10 ms + while not stop.is_set(): + live = self.metrics()["live"] + if live["state"] == "generating" and live["tok_s"] is not None: + live_samples.append((live["generated"], live["tok_s"], live["tok_s_mean"])) + time.sleep(0.01) + + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "temperature": 0, + "messages": [{"role": "user", "content": "hi"}]}).encode() + watcher = threading.Thread(target=poll, daemon=True) + watcher.start() + t0 = time.time() + try: + with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + usage = json.loads(r.read())["usage"] + finally: + stop.set() + watcher.join(2) + true_rate = usage["completion_tokens"] / (time.time() - t0) + self.assertGreaterEqual(len(live_samples), 3, "too few live readings to judge the readout") + self.assertLess(max(s for _g, s, _m in live_samples), 4 * true_rate, + f"live.tok_s peaked at {max(s for _g, s, _m in live_samples):.1f} tok/s " + f"for a {true_rate:.1f} tok/s engine") + self.assertEqual(self.metrics()["live"]["state"], "idle") + self.assertIsNone(self.metrics()["live"]["tok_s"]) + + def test_a_request_without_a_done_keeps_no_engine_counters(self): + """An engine that dies mid-answer: the previous request's `last` must not become this row's decode rate.""" + class HalfDead(MockEngine): + last = {"generated": 99, "prompt_tokens": 9, "prompt_ms": 10.0, "decode_ms": 100.0, "finish": "stop"} + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if i == 3: + raise EngineDied("the engine stopped unexpectedly (exit code -9)") + yield t + + tok = ByteTokenizer() + svc = Service(HalfDead(tok, "x" * self.TOKENS, max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode() + with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body, + headers={"Content-Type": "application/json"}), + timeout=30) as r: + text = r.read().decode() + self.assertIn('"error"', text) + row = svc.metrics()["requests"][0] + self.assertEqual(row["finish"], "error") + self.assertEqual(row["output_tokens"], 3) + self.assertIsNone(row["decode_tok_s"], "the previous request's counters were recorded as this one's") + self.assertIsNone(row["engine_generated"]) + finally: + httpd.shutdown() + httpd.server_close() + + +class SharedSettings(unittest.TestCase): + """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults.""" + + @classmethod + def setUpClass(cls): + import tempfile + + class Sampled(RecordingEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.last_sampling = dict(sampling or {}) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + tok = ByteTokenizer() + cls.engine = Sampled(tok, "\n\nhello", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.tmp = tempfile.TemporaryDirectory() + cls.svc.shared_path = os.path.join(cls.tmp.name, "strata-x.shared-settings.json") + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.tmp.cleanup() + + def req(self, path, body, headers=None, raw=None): + h = {"Content-Type": "application/json", **(headers or {})} + r = urllib.request.Request(self.base + path, data=raw if raw is not None else json.dumps(body).encode(), headers=h) + try: + with urllib.request.urlopen(r, timeout=30) as resp: + return resp.status, json.loads(resp.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def chat(self, **extra): + return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], **extra}) + + def tearDown(self): + self.svc.set_shared(None) + + def test_other_apps_get_the_chat_settings(self): + d = {"temperature": 0.3, "top_p": 0.9, "top_k": 10, "seed": 7, "max_tokens": 77, + "reasoning_effort": "low", "experimental_speed_projection": False} + code, b = self.req("/settings", {"defaults": d}) + self.assertEqual(code, 200, b) + self.assertTrue(b["shared"]) + self.assertTrue(os.path.exists(self.svc.shared_path)) + code, _ = self.chat() # a client that sets nothing + self.assertEqual(code, 200) + got = self.engine.last_sampling + for k in ("temperature", "top_p", "top_k", "seed", "experimental_speed_projection"): + self.assertEqual(got[k], d[k], k) + self.assertEqual(self.engine.last_max_new, 77) + code, _ = self.chat(temperature=0.9, max_tokens=5) # its own values win + self.assertEqual(self.engine.last_sampling["temperature"], 0.9) + self.assertEqual(self.engine.last_max_new, 5) + r = self.svc.with_shared({"messages": []}, "openai") + self.assertEqual(r["reasoning_effort"], "low") + self.assertEqual(self.svc.with_shared({"reasoning_effort": "high"}, "openai")["reasoning_effort"], "high") + self.assertEqual(self.svc.with_shared({}, "anthropic")["output_config"], {"effort": "low"}) + + def test_off_again(self): + self.req("/settings", {"defaults": {"temperature": 0.3}}) + code, b = self.req("/settings", {"defaults": None}) + self.assertEqual((code, b["shared"]), (200, False)) + self.assertFalse(os.path.exists(self.svc.shared_path)) + self.chat() + self.assertNotIn("temperature", self.engine.last_sampling) + + def test_only_strata_s_own_page_may_set_them(self): + code, _ = self.req("/settings", None, {"Content-Type": "text/plain"}, raw=b'{"defaults": {"temperature": 1}}') + self.assertEqual(code, 415) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://evil.example"}) + self.assertEqual(code, 403) + code, b = self.req("/settings", {"defaults": {"temperature": 9}}) + self.assertEqual(code, 400) + self.assertIn("temperature", b["error"]["message"]) + self.assertEqual(self.svc.shared, {}) + host = self.base.split("://", 1)[1] + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://" + host}) + self.assertEqual(code, 200) + + def test_they_need_the_key_when_one_is_set(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}})[0], 401) + self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}}, + {"Authorization": "Bearer secret"})[0], 200) + finally: + self.svc.api_key = "" + + def test_proxy_headers_do_not_make_a_page_strata_s_own(self): + # #321: X-Forwarded-*, CF-Ray or CF-Connecting-IP say nothing about the page that sent the request - any web + # page behind any proxy would otherwise change the settings (or run MCP tools) + for extra in ({"X-Forwarded-Host": "proxy.example.com"}, {"CF-Ray": "1234567890"}, + {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"}): + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, + {"Origin": "https://proxy.example.com", **extra}) + self.assertEqual(code, 403, extra) + # another port on the same host is another site (a local dev server's page) + code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://127.0.0.1:1"}) + self.assertEqual(code, 403) + + def test_a_trusted_origin_is_strata_s_own_page(self): + # the web app behind a reverse proxy or tunnel: the config's trusted_origins + self.svc.trusted_origins = ["https://strata.example.com"] + try: + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://strata.example.com"}) + self.assertEqual(code, 200) + code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://evil.example.com"}) + self.assertEqual(code, 403) + finally: + self.svc.trusted_origins = [] + + +class WebApp(unittest.TestCase): + """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(RecordingEngine(tok, "\n\nhello", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + + def get(self, path, headers=None): + req = urllib.request.Request(self.base + path, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers.get("Content-Type", ""), r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers.get("Content-Type", ""), e.read() + + def test_page_and_files(self): + code, ctype, body = self.get("/") + self.assertEqual(code, 200) + self.assertIn("text/html", ctype) + self.assertIn(b"\"web/app.js\"", body) # relative since #82 (works behind a path-prefixed proxy) + for path, want in (("/web/app.js", "javascript"), ("/web/app.css", "text/css"), ("/web/tokens.css", "text/css"), + ("/web/components.css", "text/css"), ("/web/sprite.svg", "image/svg+xml")): + with self.subTest(path=path): + code, ctype, _ = self.get(path) + self.assertEqual(code, 200) + self.assertIn(want, ctype) + + def test_only_the_app_files_are_served(self): + for path in ("/web/..%2Fserver.py", "/web/index.html", "/web/test.py", "/fonts/..%2F..%2Fsetup.py", + "/fonts/missing.woff2", "/fonts/x.ttf"): + with self.subTest(path=path): + self.assertEqual(self.get(path)[0], 404) + + def test_metrics(self): + data = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}).encode() + urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=data, + headers={"Content-Type": "application/json"}), timeout=10).read() + code, ctype, body = self.get("/metrics") + self.assertEqual(code, 200) + m = json.loads(body) + for key in ("engine", "live", "requests", "hardware", "hardware_static", "history"): + self.assertIn(key, m) + self.assertEqual(m["engine"]["max_context"], CTX) + self.assertEqual(m["live"]["state"], "idle") + self.assertEqual(m["requests"][0]["output_tokens"], 5) + + def test_model_discovery_and_props(self): + svc = self.svc + previous = svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared + try: + svc.engine.max_context = 262144 + svc.sampling_defaults = {"temperature": 1.0, "repetition_penalty": 1.1} + svc.shared = {"temperature": 0.7, "max_tokens": 4096} + for vision in (None, object()): + svc.vision = vision + for path in ("/models", "/v1/models"): + code, _, body = self.get(path) + self.assertEqual(code, 200) + models = json.loads(body)["data"] + self.assertEqual(len(models), 1) + model = models[0] + self.assertEqual(model["id"], svc.model) + self.assertEqual(model["status"]["value"], "loaded") + self.assertEqual(model["meta"]["n_ctx"], 262144) + self.assertEqual(model["architecture"]["input_modalities"], + ["text", "image"] if vision else ["text"]) + code, _, body = self.get("/props?model=" + svc.model + "&autoload=false") + self.assertEqual(code, 200) + props = json.loads(body) + self.assertEqual(props["default_generation_settings"]["n_ctx"], 262144) + self.assertEqual(props["default_generation_settings"]["params"], + {"temperature": 0.7, "repeat_penalty": 1.1, "n_predict": 4096}) + self.assertEqual(props["chat_template"], (ROOT / "serve/chat_template.jinja").read_text(encoding="utf-8")) + self.assertEqual(props["modalities"]["vision"], vision is not None) + self.assertEqual(props["total_slots"], 1) + self.assertFalse(props["models_autoload"]) + svc.shared = {} + props = json.loads(self.get("/props")[2]) + self.assertEqual(props["default_generation_settings"]["params"]["n_predict"], -1) + self.assertEqual(self.get("/props?model=not-loaded&autoload=true")[0], 404) + finally: + svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared = previous + + def test_discovery_needs_the_api_key(self): + self.svc.api_key = "secret" + try: + for path in ("/models", "/v1/models", "/props", "/slots"): + self.assertEqual(self.get(path)[0], 401) + self.assertEqual(self.get(path, {"Authorization": "Bearer secret"})[0], 200) + finally: + self.svc.api_key = "" + + def test_build_model_path_and_slot_status(self): + engine = self.svc.engine + engine.model_path = "models/example.gguf" + engine.info = {"version": "0.1.21"} + try: + props = json.loads(self.get("/props")[2]) + self.assertEqual(props["model_path"], engine.model_path) + self.assertEqual(props["build_info"], "Strata 0.1.21") + for busy in (True, False): + with self.svc.status_lock: + self.svc.status["busy"] = busy + code, _, body = self.get("/slots") + self.assertEqual(code, 200) + self.assertEqual(json.loads(body), [{"id": 0, "n_ctx": CTX, "is_processing": busy}]) + finally: + with self.svc.status_lock: + self.svc.status["busy"] = False + del engine.model_path, engine.info + props = json.loads(self.get("/props")[2]) + self.assertNotIn("build_info", props) + self.assertNotIn("model_path", props) + + def test_discovery_does_not_restart_a_dead_engine(self): + self.svc.engine.alive = lambda: False + try: + for path in ("/models", "/v1/models"): + code, _, body = self.get(path) + self.assertEqual(code, 200) + self.assertEqual(json.loads(body)["data"], []) + self.assertEqual(self.get("/props")[0], 503) + self.assertEqual(json.loads(self.get("/slots")[2]), []) + finally: + del self.svc.engine.alive + + def test_metrics_need_the_key_when_one_is_set(self): + self.svc.api_key = "secret" + try: + self.assertEqual(self.get("/metrics")[0], 401) + self.assertEqual(self.get("/metrics", {"Authorization": "Bearer secret"})[0], 200) + self.assertEqual(self.get("/")[0], 200) # the page itself asks for the key + finally: + self.svc.api_key = "" + + +class ClockedEngine(MockEngine): + """The mock engine with StrataEngine's clock: `last` as the engine's DONE line gives it, the conversation cache + holding the first REUSED tokens of every prompt.""" + REUSED = 5 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + n = 0 + try: + for t in super().generate(ids, max_new, sampling, cancel, embeddings): + n += 1 + yield t + finally: # as StrataEngine reads its DONE line: also when the server closes the request at a stop token + self.last = {"generated": n, "prompt_tokens": len(ids), "prompt_ms": 40.0, "decode_ms": 20.0 * n, + "finish": "stop", "reused": min(self.REUSED, len(ids)), "hits": 9, "lookups": 10} + + +class UsageAndStatus(unittest.TestCase): + """What clients read besides the text: the part of the prompt the conversation cache held (OpenAI's + prompt_tokens_details.cached_tokens, Anthropic's cache_read_input_tokens), llama.cpp's timings, GET /v1/status.""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = ClockedEngine(tok, "\n\nok", max_context=CTX) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def request(self, path, body=None): + req = urllib.request.Request(self.base + path, data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read() + + def chat(self, path, stream=False): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + status, raw = self.request(path, body) + self.assertEqual(status, 200) + if not stream: + return json.loads(raw) + return [json.loads(line[6:]) for line in raw.decode().splitlines() + if line.startswith("data: {")] + + def preflight(self, path, origin="https://chat.example.com"): + req = urllib.request.Request(self.base + path, method="OPTIONS", + headers={"Origin": origin, "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "authorization, content-type"}) + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers + + def test_cors_is_off_by_default(self): + # #321: OPTIONS is answered, but without cors_origins no page of another origin is let in + status, h = self.preflight("/v1/chat/completions") + self.assertEqual(status, 204) + self.assertIsNone(h.get("Access-Control-Allow-Origin")) + with urllib.request.urlopen(self.base + "/health", timeout=10) as r: + self.assertIsNone(r.headers.get("Access-Control-Allow-Origin")) + + def test_cors_for_the_configured_origins_on_the_api_only(self): + self.svc.cors_origins = ["https://chat.example.com"] + try: + status, h = self.preflight("/v1/chat/completions") + self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (204, "https://chat.example.com")) + self.assertIn("OPTIONS", h.get("Access-Control-Allow-Methods", "")) + self.assertIn("authorization", h.get("Access-Control-Allow-Headers", "")) + self.assertIsNone(self.preflight("/v1/chat/completions", "https://evil.example.com")[1] + .get("Access-Control-Allow-Origin")) + # never on the app's own endpoints (/settings, /unload, ...) + self.assertIsNone(self.preflight("/settings")[1].get("Access-Control-Allow-Origin")) + req = urllib.request.Request(self.base + "/v1/models", headers={"Origin": "https://chat.example.com"}) + with urllib.request.urlopen(req, timeout=10) as r: + self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "https://chat.example.com") + self.svc.cors_origins = ["*"] + self.assertEqual(self.preflight("/v1/messages", "https://any.example.com")[1] + .get("Access-Control-Allow-Origin"), "*") + finally: + self.svc.cors_origins = [] + + def test_sse_is_not_buffered_by_proxies(self): + req = urllib.request.Request(self.base + "/v1/chat/completions", headers={"Content-Type": "application/json"}, + data=json.dumps({"model": "m", "stream": True, + "messages": [{"role": "user", "content": "hi"}]}).encode()) + with urllib.request.urlopen(req, timeout=30) as r: + self.assertEqual(r.headers.get("X-Accel-Buffering"), "no") + r.read() + + def test_origin_lists_are_checked(self): + from serve.server import origins_of + self.assertEqual(origins_of(None, "k", True), []) + self.assertEqual(origins_of("https://a.example.com/", "k", False), ["https://a.example.com"]) + self.assertEqual(origins_of(["*", "http://localhost:3000"], "k", True), ["*", "http://localhost:3000"]) + for bad in ("*", "a.example.com", "https://a.example.com/path", "https://*.example.com", 5): + with self.assertRaises(SystemExit): + origins_of(bad, "k", False) + + def test_openai(self): + b = self.chat("/v1/chat/completions") + u, t = b["usage"], b["timings"] + self.assertEqual(u["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) + self.assertEqual(t["cache_n"], ClockedEngine.REUSED) + self.assertEqual(t["prompt_n"] + t["cache_n"], u["prompt_tokens"]) + self.assertEqual(t["predicted_n"], u["completion_tokens"]) + self.assertAlmostEqual(t["prompt_per_second"], t["prompt_n"] / 0.040, delta=0.1) + self.assertAlmostEqual(t["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token + + def test_openai_stream(self): + last = self.chat("/v1/chat/completions", stream=True)[-1] + self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) + self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) + + def test_anthropic(self): + u = self.chat("/v1/messages")["usage"] + self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) + self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], len(self.engine.last_prompt)) + self.assertGreater(u["output_tokens"], 0) + + def test_v1_status(self): + self.chat("/v1/chat/completions") + status, raw = self.request("/v1/status") + self.assertEqual(status, 200) + s = json.loads(raw) + self.assertEqual(s["model"], self.svc.model) + self.assertEqual(s["context"]["max_positions"], CTX) + self.assertEqual(s["concurrency"]["serving"], 1) + self.assertFalse(s["vision"]["available"]) + self.assertEqual(s["activity"]["in_flight"], 0) + self.assertGreaterEqual(s["activity"]["requests"], 1) + self.assertEqual(s["last_timings"]["cache_n"], ClockedEngine.REUSED) + self.assertIn("at", s["last_timings"]) + + def test_no_clock(self): + """An engine without a clock (MockEngine): no timings, nothing cached.""" + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + data = json.dumps({"model": "x", "max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]}).encode() + req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/chat/completions", data=data, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + b = json.loads(r.read()) + self.assertNotIn("timings", b) + self.assertEqual(b["usage"]["prompt_tokens_details"]["cached_tokens"], 0) + self.assertIsNone(svc.v1_status()["last_timings"]) + finally: + httpd.shutdown() + httpd.server_close() + + +class TimingsDrafts(unittest.TestCase): + """`timings` carries the speculative draft counts (PR #83's fields) only when the engine reported them.""" + + def test_draft_fields(self): + base = {"prompt_ms": 100.0, "decode_ms": 200.0, "generated": 20, "reused": 4} + t = request_timings(24, 20, dict(base, drafts_offered=15, drafts_accepted=11)) + self.assertEqual((t["draft_n"], t["draft_n_accepted"]), (15, 11)) + self.assertEqual((t["prompt_n"], t["cache_n"]), (20, 4)) + self.assertNotIn("draft_n", request_timings(24, 20, base)) + self.assertIsNone(request_timings(24, 20, {})) + + +class UnloadableEngine(MockEngine): + """A mock engine that can be stopped and started again like StrataEngine (alive / unload / restart).""" + + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + self.running, self.unloaded, self.starts = True, False, 0 + + def alive(self): + return self.running + + def unload(self): + self.running, self.unloaded = False, True + + def restart(self): + self.running, self.unloaded = True, False + self.starts += 1 + + +class SharingTheGpu(unittest.TestCase): + """Idle unload, POST /unload and /load, the free-VRAM guard and the before_load hook (all off by default).""" + + def setUp(self): + tok = ByteTokenizer() + self.engine = UnloadableEngine(tok, "\n\nok", max_context=CTX) + self.svc = Service(self.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def req(self, path, body=None): + r = urllib.request.Request(self.base + path, data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json"}, method="GET" if body is None else "POST") + try: + with urllib.request.urlopen(r, timeout=30) as resp: + return resp.status, json.loads(resp.read()) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def chat(self): + return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}]}) + + def test_unload_then_the_next_request_loads(self): + self.assertEqual(self.req("/unload", {}), (200, {"status": "unloaded"})) + self.assertFalse(self.engine.alive()) + self.assertEqual(self.req("/health")[1]["loaded"], False) + self.assertEqual(self.req("/v1/models")[1]["data"][0]["status"]["value"], "unloaded") + self.assertEqual(self.req("/unload", {}), (200, {"status": "not loaded"})) + s, b = self.chat() + self.assertEqual(s, 200) + self.assertEqual(b["choices"][0]["message"]["content"], "ok") + self.assertEqual(self.engine.starts, 1) + self.assertEqual(self.req("/health")[1]["loaded"], True) + + def test_load_endpoint(self): + self.svc.unload() + self.assertEqual(self.req("/load", {}), (200, {"status": "loaded"})) + self.assertTrue(self.engine.alive()) + self.assertEqual(self.req("/load", {}), (200, {"status": "loaded"})) + self.assertEqual(self.engine.starts, 1) + + def test_unload_refused_while_a_request_runs(self): + with self.svc.fifo: + self.assertEqual(self.svc.unload(), "busy") + self.assertTrue(self.engine.alive()) + + def test_idle_unload(self): + self.svc.idle_unload_s = 1 + self.svc.last_request_at = time.time() + self.assertEqual(self.svc.unload(idle_for=1), "busy") # a request just now: not idle yet + self.svc.start_idle_unload() + deadline = time.time() + 10 + while self.engine.alive() and time.time() < deadline: + time.sleep(0.1) + self.assertFalse(self.engine.alive()) + self.assertEqual(self.chat()[0], 200) + + def test_min_free_vram_refuses_to_load(self): + self.svc.min_free_vram_mib = 8000 + self.svc.free_vram_mib = lambda: 2000 + self.svc.unload() + t0 = time.time() + s, b = self.chat() + self.assertEqual(s, 503) + self.assertIn("in use by another program", b["error"]["message"]) + self.assertFalse(self.engine.alive()) + self.assertGreater(time.time() - t0, 10) # waited for memory being given back first + self.svc.free_vram_mib = lambda: 9000 + self.assertEqual(self.chat()[0], 200) + + def test_min_free_vram_unreadable_loads(self): + self.svc.min_free_vram_mib = 8000 + self.svc.free_vram_mib = lambda: None # no NVML: never refuse + self.svc.unload() + self.assertEqual(self.chat()[0], 200) + + def test_before_load_runs_first(self): + mark = Path(tempfile.mkdtemp()) / "ran" + self.svc.before_load = [sys.executable, "-c", f"open({str(mark)!r}, 'w').close()"] + self.svc.unload() + self.assertFalse(mark.exists()) + self.assertEqual(self.chat()[0], 200) + self.assertTrue(mark.exists()) + + def test_vision_encoder_unloads_and_starts_first(self): + order = [] + + class FakeVision: + running = True + + def alive(self): + return self.running + + def unload(self): + self.running = False + + def restart(self): + order.append("vision") + self.running = True + + engine_restart = self.engine.restart + self.engine.restart = lambda: (order.append("engine"), engine_restart()) + self.svc.vision = FakeVision() + self.assertEqual(self.svc.unload(), "unloaded") + self.assertFalse(self.svc.vision.alive()) + self.assertEqual(self.chat()[0], 200) + self.assertEqual(order, ["vision", "engine"]) # the encoder first, as at a start + self.assertTrue(self.svc.vision.alive()) + + def test_off_by_default(self): + self.assertEqual((self.svc.idle_unload_s, self.svc.min_free_vram_mib, self.svc.before_load), (0, 0, None)) + self.assertEqual(self.req("/health")[1]["loaded"], True) + + +class ThinkingEngine(MockEngine): + """Thinks THOUGHT, then answers; a prompt that already ends its thinking (the budget's wrap-up) gets the answer + at once, the way the model continues after . Records every prompt it is given.""" + THOUGHT = "Let me think step by step about two plus two. " * 4 # 184 reasoning tokens (one per byte) + ANSWER = "The answer is 4." + + def __init__(self, tok): + super().__init__(tok, "x", max_context=CTX) + self.prompts = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.prompts.append(list(ids)) + done = self.tok.decode(ids).endswith("\n\n") + text = self.ANSWER if done else self.THOUGHT + "\n\n" + self.ANSWER + for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]: + if cancel.is_set(): + return + yield t + + +class ThinkingBudget(unittest.TestCase): + """#123: reasoning_budget_tokens (opt-in): at the budget the thinking is wrapped up and the model answers, + continuing from the prompt plus what it generated plus the wrap-up (a prefix the engine already holds).""" + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = ThinkingEngine(self.tok) + self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={ + "Content-Type": "application/json", "anthropic-version": "2023-06-01"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + return r.status, (json.loads(raw) if not body.get("stream") else raw) + except urllib.error.HTTPError as e: + with e: + return e.code, json.loads(e.read()) + + def openai(self, **extra): + return self.post("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], + "max_tokens": 400, **extra}) + + def test_off_by_default(self): + code, b = self.openai() + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + self.assertEqual((msg["reasoning_content"], msg["content"]), (ThinkingEngine.THOUGHT, ThinkingEngine.ANSWER)) + self.assertEqual(len(self.engine.prompts), 1) + + def test_the_budget_wraps_up_the_thinking(self): + from serve.server import REASONING_WRAP_UP + code, b = self.openai(reasoning_budget_tokens=20) + self.assertEqual(code, 200, b) + msg = b["choices"][0]["message"] + wrap = REASONING_WRAP_UP.split("")[0] + self.assertEqual(msg["reasoning_content"], ThinkingEngine.THOUGHT[:20] + wrap) + self.assertEqual(msg["content"], ThinkingEngine.ANSWER) + self.assertEqual(b["choices"][0]["finish_reason"], "stop") + first, second = self.engine.prompts + extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True) + self.assertEqual(second, first + self.tok.encode(ThinkingEngine.THOUGHT[:20]) + extra) # a prefix + more + self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) + self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + + def test_anthropic_stream(self): + from serve.server import REASONING_WRAP_UP + code, raw = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "stream": True, + "reasoning_budget_tokens": 30, + "messages": [{"role": "user", "content": "2+2?"}]}) + self.assertEqual(code, 200) + evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + thinking = "".join(e["delta"].get("thinking", "") for e in evs if e["type"] == "content_block_delta") + text = "".join(e["delta"].get("text", "") for e in evs if e["type"] == "content_block_delta") + self.assertEqual(thinking, ThinkingEngine.THOUGHT[:30] + REASONING_WRAP_UP.split("")[0]) + self.assertEqual(text, ThinkingEngine.ANSWER) + self.assertEqual(evs[-2]["delta"]["stop_reason"], "end_turn") + + def test_a_budget_the_thinking_stays_under(self): + code, b = self.openai(reasoning_budget_tokens=10_000) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT) + self.assertEqual(len(self.engine.prompts), 1) + + def test_the_config_default_and_a_request_that_turns_it_off(self): + self.svc.reasoning_budget_tokens = 20 + code, b = self.openai() + self.assertEqual(len(self.engine.prompts), 2) + self.assertTrue(b["choices"][0]["message"]["reasoning_content"].startswith(ThinkingEngine.THOUGHT[:20] + "\n")) + code, b = self.openai(reasoning_budget_tokens=0) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT) + self.assertEqual(len(self.engine.prompts), 3) + + def test_without_thinking_there_is_nothing_to_limit(self): + self.engine.THOUGHT = "" + code, b = self.openai(reasoning_budget_tokens=5, reasoning_effort="none") + self.assertEqual(code, 200, b) + self.assertEqual(len(self.engine.prompts), 1) + + def test_no_room_left_to_answer(self): + code, b = self.openai(reasoning_budget_tokens=20, max_tokens=40) # 20 thought + the wrap-up > 40 + self.assertEqual(b["choices"][0]["finish_reason"], "length") + self.assertEqual(len(self.engine.prompts), 1) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20]) + + def test_a_bad_value_is_a_400(self): + for bad in ("lots", 2.5, True, [1]): + with self.subTest(value=bad): + code, b = self.openai(reasoning_budget_tokens=bad) + self.assertEqual(code, 400) + self.assertIn("reasoning_budget_tokens", b["error"]["message"]) + self.assertEqual(self.engine.prompts, []) + + +class StatusHandover(unittest.TestCase): + """#266: a stream aborted mid-way and the next request, which was waiting for the fifo. The aborted request's + status/history block ran after the fifo was released, so the waiting request could start in that gap: the old + request then recorded the NEW request's status as its own, set busy=False and popped `tail`, and the new request + crashed in _note (KeyError 'tail'). The fifo below lets the waiting request run to its first token as soon as + it is released, before the releasing thread goes on - the worst case of that gap, every time.""" + + def test_abort_then_the_next_request(self): + tok = ByteTokenizer() + second_running = threading.Event() + + class Engine(MockEngine): + calls = 0 + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + Engine.calls += 1 + me = Engine.calls + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if me == 2 and i == 2: + second_running.set() # the second request has its status and two tokens noted + yield t + + class SlowRelease: + """A Lock whose release waits (briefly) until the thread it let in has started generating.""" + + def __init__(self): + self.lock, self.armed = threading.Lock(), False + + def acquire(self, blocking=True): + return self.lock.acquire(blocking) + + def __enter__(self): + self.lock.acquire() + + def __exit__(self, *exc): + self.lock.release() + if self.armed: + self.armed = False + second_running.wait(5) + + def release(self): + self.lock.release() + + svc = Service(Engine(tok, "\n\n" + "y" * 40, max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.fifo = SlowRelease() + ids = tok.encode("hi") + first = svc.run(ids, True, None, 30, {}, threading.Event()) + for _ in range(5): + next(first) # mid-answer + out, errors = [], [] + + def second(): + try: + out.extend(svc.run(ids, True, None, 20, {}, threading.Event())) + except Exception as e: # noqa: BLE001 - the crash this test is about + errors.append(e) + + waiter = threading.Thread(target=second) + waiter.start() + deadline = time.time() + 5 + while svc.status.get("queued") != 1 and time.time() < deadline: + time.sleep(0.005) + self.assertEqual(svc.status.get("queued"), 1, "the second request never queued") + svc.fifo.armed = True + first.close() # the client went away: GeneratorExit in the first request + waiter.join(10) + self.assertFalse(waiter.is_alive()) + self.assertEqual(errors, []) + self.assertEqual(out[-1][0], "done") + self.assertEqual(out[-1][1]["completion_tokens"], 20) + rows = list(svc.history) + self.assertEqual([r["finish"] for r in rows], ["disconnect", "length"]) + self.assertTrue(0 < rows[0]["output_tokens"] < 30, rows) # where the first one stopped, not the second's + self.assertEqual(rows[1]["output_tokens"], 20) + self.assertEqual(svc.totals["requests"], 2) + self.assertEqual(svc.totals["output_tokens"], rows[0]["output_tokens"] + 20) + self.assertFalse(svc.status["busy"]) + self.assertNotIn("tail", svc.status) + + +FAKE_STRATA = '''import pathlib, sys, time +gate = pathlib.Path(sys.argv[sys.argv.index("--gate") + 1]) +print("INFO engine=0.0.0", flush=True) +while not gate.exists(): # the test says when the engine is "ready" + time.sleep(0.01) +print("READY 4096 stop", flush=True) +for line in sys.stdin: + if line.startswith("QUIT"): + break +''' + + +class RestartWindow(unittest.TestCase): + """#344: while the engine restarts it is not alive (a request waits for the restart instead of reading + max_context 0), and a request that still meets max_context 0 gets a 503 "starting", not a 400 about its prompt.""" + + def test_not_alive_until_ready(self): + from unittest import mock + import serve.server as server + with tempfile.TemporaryDirectory() as d: + script, gate = Path(d) / "fake_strata.py", Path(d) / "ready" + script.write_text(FAKE_STRATA, encoding="utf-8") + real = server.subprocess.Popen + with mock.patch.object(server.subprocess, "Popen", + lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)): + gate.touch() + eng = StrataEngine("strata", ["--gate", str(gate)]) + try: + self.assertEqual(eng.max_context, 4096) + self.assertTrue(eng.alive()) + gate.unlink() + old = eng.proc + old.kill() + old.wait(10) + deadline = time.time() + 10 + while not getattr(eng, "ended", False) and time.time() < deadline: + time.sleep(0.01) # the server has noticed: its output closed + self.assertFalse(eng.alive()) + t = threading.Thread(target=eng.restart) + t.start() + deadline = time.time() + 10 + while eng.proc is old and time.time() < deadline: + time.sleep(0.005) + self.assertIsNot(eng.proc, old, "restart never started the engine") + time.sleep(0.2) # the new engine is up, but has not said READY + self.assertEqual(eng.max_context, 0) + self.assertFalse(eng.alive(), "alive before READY: a request would plan with context 0") + gate.touch() + t.join(10) + self.assertFalse(t.is_alive()) + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + # restart() of a running engine kills it first: that engine's output thread ends after the new + # one is up, and must not mark it dead (it did: every request after restarted it again) + eng.restart() + time.sleep(0.5) + self.assertTrue(eng.alive()) + self.assertEqual(eng.max_context, 4096) + finally: + gate.touch() + eng.unload() + + def test_context_zero_is_503(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=0), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + base = f"http://127.0.0.1:{httpd.server_address[1]}" + try: + for path, body in (("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 16}), + ("/v1/messages", {"model": "m", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]})): + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with self.assertRaises(urllib.error.HTTPError) as cm: + urllib.request.urlopen(req, timeout=30) + with cm.exception as e: + self.assertEqual(e.code, 503, path) + text = e.read().decode() + self.assertIn("starting", text) + self.assertNotIn("leaves no room", text) + finally: + httpd.shutdown() + httpd.server_close() + + +class ModelAliases(unittest.TestCase): + """#297: the config's `aliases` are listed by /v1/models and accepted as model names (answered under that name).""" + + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja"), model_name="qwen3.8-flash-next-iq3_xxs") + cls.svc.set_aliases(["qwen", "local-model", "qwen", " ", "qwen3.8-flash-next-iq3_xxs"]) + cls.httpd = serve(cls.svc, port=0) + cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + + def get(self, path): + with urllib.request.urlopen(self.base + path, timeout=30) as r: + return json.loads(r.read()) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + return r.read().decode() + + def test_set_aliases(self): + self.assertEqual(self.svc.aliases, ["qwen", "local-model"]) # duplicates, blanks and the name itself + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.set_aliases("a, b") + self.assertEqual(svc.aliases, ["a", "b"]) + svc.set_aliases(None) + self.assertEqual(svc.aliases, []) + for bad in (3, ["a", 1], {"a": 1}): + with self.assertRaises(ValueError): + svc.set_aliases(bad) + + def test_models_lists_them(self): + data = self.get("/v1/models")["data"] + self.assertEqual([m["id"] for m in data], ["qwen3.8-flash-next-iq3_xxs", "qwen", "local-model"]) + self.assertEqual(data[0]["aliases"], ["qwen", "local-model"]) + self.assertEqual(data[1]["alias_of"], "qwen3.8-flash-next-iq3_xxs") + self.assertEqual(self.get("/props?model=local-model")["model_alias"], "qwen3.8-flash-next-iq3_xxs") + + def test_requests_are_answered_under_the_alias(self): + msgs = [{"role": "user", "content": "hi"}] + for asked, want in (("qwen", "qwen"), ("local-model", "local-model"), + ("qwen3.8-flash-next-iq3_xxs", "qwen3.8-flash-next-iq3_xxs"), + ("something-else", "qwen3.8-flash-next-iq3_xxs")): # still served, as before + with self.subTest(asked=asked): + out = json.loads(self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8})) + self.assertEqual(out["model"], want) + text = self.post("/v1/chat/completions", {"model": asked, "messages": msgs, "max_tokens": 8, + "stream": True}) + first = json.loads(text.split("data: ", 2)[1].strip()) + self.assertEqual(first["model"], want) + out = json.loads(self.post("/v1/messages", {"model": asked, "messages": msgs, "max_tokens": 8})) + self.assertEqual(out["model"], want) + + def test_without_aliases_nothing_changes(self): + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + httpd = serve(svc, port=0) + try: + with urllib.request.urlopen(f"http://127.0.0.1:{httpd.server_address[1]}/v1/models", timeout=30) as r: + data = json.loads(r.read())["data"] + self.assertEqual(len(data), 1) + self.assertNotIn("aliases", data[0]) + self.assertEqual(svc.model_for({"model": "x"}), svc.model) + finally: + httpd.shutdown() + httpd.server_close() + + +class AmdTelemetry(unittest.TestCase): + """#301: the AMD backend's readings from a fake amdgpu sysfs tree: KFD node -> render node, as setup numbers the + cards (the CPU node skipped), and free_vram_mib on HIP.""" + + def tree(self, d): + nodes = Path(d) / "class/kfd/kfd/topology/nodes" + for n, props in ((0, "cpu_cores_count 16\nsimd_count 0\ngfx_target_version 0\ndrm_render_minor 0\n"), + (1, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 129\n"), + (2, "simd_count 128\ngfx_target_version 120001\ndrm_render_minor 128\n")): + (nodes / str(n)).mkdir(parents=True) + (nodes / str(n) / "properties").write_text(props) + for minor, used, busy, temp, power in ((129, 2 << 30, 37, 51000, 85000000), (128, 6 << 30, 99, 64000, None)): + dev = Path(d) / f"class/drm/renderD{minor}/device" + hw = dev / "hwmon" / "hwmon4" + hw.mkdir(parents=True) + (dev / "gpu_busy_percent").write_text(f"{busy}\n") + (dev / "mem_info_vram_used").write_text(f"{used}\n") + (dev / "mem_info_vram_total").write_text(f"{32 << 30}\n") + (dev / "product_name").write_text("AMD Radeon AI PRO R9700\n") + (hw / "temp1_input").write_text(f"{temp}\n") + if power is not None: + (hw / "power1_average").write_text(f"{power}\n") + else: + (hw / "power1_input").write_text("120000000\n") + (hw / "power1_cap").write_text("300000000\n") + + def test_readings(self): + from serve import telemetry + with tempfile.TemporaryDirectory() as d: + self.tree(d) + with mock.patch.object(telemetry, "SYSFS", d): + self.assertTrue(telemetry.amd_device_dir(0).endswith(os.path.join("renderD129", "device"))) + self.assertTrue(telemetry.amd_device_dir(1).endswith(os.path.join("renderD128", "device"))) + self.assertIsNone(telemetry.amd_device_dir(2)) + g = telemetry.gpu_reader(0, amd=True) + self.assertTrue(g.ok()) + self.assertEqual(g.name(), "AMD Radeon AI PRO R9700") + self.assertEqual(g.read(), {"util": 37, "mem_used": 2 << 30, "mem_total": 32 << 30, "temp": 51.0, + "power": 85.0, "power_limit": 300.0}) + r = telemetry.gpu_reader(1, amd=True).read() + self.assertEqual((r["util"], r["temp"], r["power"]), (99, 64.0, 120.0)) # power1_input + self.assertEqual(telemetry.free_vram_mib(0, amd=True), 30 << 10) + self.assertIsNone(telemetry.free_vram_mib(5, amd=True)) + t = telemetry.Telemetry(gpu_index=0, gpu_indices=[0, 1], amd=True) + s = t.sample() + self.assertEqual(t.static["gpu_name"], "AMD Radeon AI PRO R9700 + AMD Radeon AI PRO R9700") + self.assertEqual((s["gpu_mem_used"], s["gpu_util"], s["gpu_temp"], s["gpu_power"]), + (8 << 30, 68.0, 64.0, 205.0)) + with tempfile.TemporaryDirectory() as d: # no amdgpu: nothing, and nothing breaks + with mock.patch.object(telemetry, "SYSFS", d): + self.assertFalse(telemetry.gpu_reader(0, amd=True).ok()) + self.assertIsNone(telemetry.free_vram_mib(0, amd=True)) + + def test_free_vram_on_hip(self): + from serve import telemetry + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "x", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + svc.backend, svc.gpu_index = "hip", 1 + with tempfile.TemporaryDirectory() as d: + self.tree(d) + with mock.patch.object(telemetry, "SYSFS", d): + self.assertEqual(svc.free_vram_mib(), 26 << 10) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_structured.py b/engine/strata/serve/test_structured.py new file mode 100644 index 00000000..cc157a76 --- /dev/null +++ b/engine/strata/serve/test_structured.py @@ -0,0 +1,167 @@ +"""Exercise the JSON contract through HTTP, including H3's strict Story shape.""" +import json +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve import structured +from serve.server import ByteTokenizer, MockEngine, Service, serve + +try: + import jsonschema # noqa: F401 + HAVE_JSONSCHEMA = True +except ImportError: # optional: json_schema answers are then only checked to be one object + HAVE_JSONSCHEMA = False + + +STORY = {"title": "Photobooth", "sheet": "A single continuous shot.", "cast": [], + "boxes": [{"box": 1, "duration_ms": 15000, "new_shot": True, "beat": "Hailee changes poses.", + "on_screen": ["Hailee"], "references": [], "ends": "She smiles."}], "suggestions": []} + + +def object_schema(properties): + return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False} + + +TEXT = {"type": "string"} +STORY_SCHEMA = object_schema({ + "title": TEXT, "sheet": TEXT, "cast": {"type": "array", "items": object_schema({"name": TEXT, + "references": {"type": "array", "items": TEXT, "maxItems": 0}})}, + "boxes": {"type": "array", "minItems": 1, "maxItems": 1, "items": object_schema({ + "box": {"type": "integer", "minimum": 1, "maximum": 1}, + "duration_ms": {"type": "integer", "minimum": 1, "maximum": 15000}, "new_shot": {"type": "boolean"}, + "beat": TEXT, "on_screen": {"type": "array", "items": TEXT}, + "references": {"type": "array", "items": TEXT, "maxItems": 0}, "ends": TEXT})}, + "suggestions": {"type": "array", "items": object_schema({"what": TEXT, "why": TEXT, + "boxes": {"type": "array", "items": {"type": "integer"}}, "description": TEXT})}}) +FORMAT = {"type": "json_schema", "json_schema": {"name": "h3_story", "strict": True, "schema": STORY_SCHEMA}} + + +class Structured(unittest.TestCase): + def request(self, path, body=None, headers=None): + req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None, + headers={"Content-Type": "application/json", **(headers or {})}) + try: + response = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as error: + response = error + with response: + data = response.read().decode() + return response.status, data if "event-stream" in response.headers.get("Content-Type", "") else json.loads(data) + + def setUp(self): + self.tok = ByteTokenizer() + self.engine = MockEngine(self.tok, json.dumps(STORY), max_context=16384) + self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def chat(self, script=None, **kwargs): + if script is not None: + self.engine = self.svc.engine = MockEngine(self.tok, script, max_context=16384) + req = {"messages": [{"role": "system", "content": "Write a film plan."}, + {"role": "user", "content": "Photobooth. 15 seconds."}], + "response_format": FORMAT, "reasoning_effort": "none", **kwargs} + return self.request("/v1/chat/completions", req) + + def test_h3_schema_success_and_stream_with_reasoning(self): + code, reply = self.chat() + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), STORY) + prompt = self.tok.decode(self.engine.last_prompt) + self.assertIn("OUTPUT FORMAT REQUIREMENT", prompt) + self.assertIn('"duration_ms"', prompt) + code, raw = self.chat("Consider the shot.\n" + json.dumps(STORY), stream=True, reasoning_effort="low") + self.assertEqual(code, 200) + chunks = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")] + content = "".join(c["choices"][0]["delta"].get("content", "") for c in chunks) + self.assertEqual(json.loads(content), STORY) + self.assertIn("reasoning_content", raw) + self.assertIn("data: [DONE]", raw) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_generation_is_an_error_and_never_streams_content(self): + for script in ("## Film Plan - Photobooth", '{"title":"Only a title"}', + json.dumps({**STORY, "extra": True}), + json.dumps({**STORY, "boxes": [{**STORY["boxes"][0], "duration_ms": "15000"}]})): + with self.subTest(script=script): + code, reply = self.chat(script) + self.assertEqual(code, 502) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + _, raw = self.chat(script, stream=True) + self.assertIn('"structured_output_failed"', raw) + self.assertNotIn('"delta"', raw) + self.assertIn("data: [DONE]", raw) + + def test_object_mode_strict_json_and_truncation(self): + fmt = {"type": "json_object"} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + for script in ('[]', '{"x":NaN}', '{"x":1,"x":2}', '{"x":1e999}', '```json\n{}\n```'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502) + self.assertEqual(self.chat('{"answer":4}', response_format=fmt, max_tokens=5)[0], 502) + # Plain text callers retain normal streaming, without a JSON validation gate. + self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + + def test_rejected_schema_does_not_load_the_engine_or_retry(self): + with mock.patch.object(self.svc, "load") as load: + code, _ = self.chat(response_format={"type": "json_schema"}) + self.assertEqual(code, 400) + load.assert_not_called() + self.engine = self.svc.engine = MockEngine(self.tok, "Markdown is not JSON", max_context=16384) + with mock.patch.object(self.engine, "generate", wraps=self.engine.generate) as generate: + self.assertEqual(self.chat()[0], 502) + self.assertEqual(generate.call_count, 1) + + @unittest.skipUnless(HAVE_JSONSCHEMA, "jsonschema is not installed") + def test_invalid_schema_is_400_and_local_refs_work(self): + for schema in ({"type": "object", "properties": {"x": {"type": "invalid"}}}, + {"type": "object", "$ref": "https://other.example/schema"}): + fmt = {"type": "json_schema", "json_schema": {"name": "test", "strict": True, "schema": schema}} + self.assertEqual(self.chat(response_format=fmt)[0], 400) + schema = object_schema({"answer": {"$ref": "#/$defs/n"}}) + schema["$defs"] = {"n": {"type": "integer"}} + fmt = {"type": "json_schema", "json_schema": {"name": "local", "schema": schema}} + self.assertEqual(self.chat('{"answer":4}', response_format=fmt)[0], 200) + + def test_malformed_formats_and_tools_are_rejected_before_loading(self): + formats = ([], {"type": "unsupported"}, + {"type": "json_schema", "json_schema": {"schema": {"type": "object"}}}, + {"type": "json_schema", "json_schema": {"name": "x", "strict": "true", "schema": {"type": "object"}}}) + with mock.patch.object(self.svc, "load") as load: + for fmt in formats: + with self.subTest(fmt=fmt): + self.assertEqual(self.chat(response_format=fmt)[0], 400) + self.assertEqual(self.chat(tools=[{"type": "function", "function": {"name": "search", "parameters": {"type": "object"}}}])[0], 400) + self.assertEqual(self.chat(strata_mcp=True)[0], 400) + self.assertEqual(self.request("/v1/chat/completions", [])[0], 400) + load.assert_not_called() + + def test_without_jsonschema_an_object_is_still_required(self): + # jsonschema is optional: without it json_schema answers are checked to be one JSON object, json_object + # never needs it, and nothing is imported at server start + with mock.patch.object(structured, "_jsonschema", False): + self.assertEqual(self.chat()[0], 200) + for script in ("## Film Plan - Photobooth", "[1, 2]"): + code, reply = self.chat(script) + self.assertEqual(code, 502, script) + self.assertEqual(reply["error"]["code"], "structured_output_failed") + self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200) + + def test_the_server_does_not_import_jsonschema_at_start(self): + import subprocess + import sys + code = ("import sys; import serve.server; " + "sys.exit(1 if any(m == 'jsonschema' or m.startswith('jsonschema.') for m in sys.modules) else 0)") + r = subprocess.run([sys.executable, "-c", code], cwd=str(Path(__file__).resolve().parents[1])) + self.assertEqual(r.returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/test_winjob.py b/engine/strata/serve/test_winjob.py new file mode 100644 index 00000000..31b617ab --- /dev/null +++ b/engine/strata/serve/test_winjob.py @@ -0,0 +1,67 @@ +"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even +when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own. + + python -m unittest serve.test_winjob (Windows only; skipped elsewhere) +""" +import os +import subprocess +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed +PARENT = f""" +import subprocess, sys, time +sys.path.insert(0, {str(ROOT)!r}) +from serve.winjob import contain +code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); " + "print(g.pid, flush=True); time.sleep(120)") +child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True) +ok = contain(child) +print(ok, child.pid, child.stdout.readline().strip(), flush=True) +time.sleep(120) +""" + + +def running(pid: int) -> bool: + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout + return str(pid) in out + + +@unittest.skipUnless(os.name == "nt", "job objects are Windows-only") +class TestWinJob(unittest.TestCase): + def test_children_end_with_a_killed_server(self): + # a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter + python = getattr(sys, "_base_executable", None) or sys.executable + parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True) + child = grandchild = None + try: + ok, child, grandchild = parent.stdout.readline().split() + child, grandchild = int(child), int(grandchild) + self.assertEqual(ok, "True") + self.assertTrue(running(child) and running(grandchild)) + parent.kill() # TerminateProcess: no atexit, no finally - like closing the window + parent.wait(10) + deadline = time.monotonic() + 10 + while (running(child) or running(grandchild)) and time.monotonic() < deadline: + time.sleep(0.2) + self.assertFalse(running(child), "the child outlived the server") + self.assertFalse(running(grandchild), "the grandchild outlived the server") + finally: + if parent.poll() is None: + parent.kill() + for pid in (child, grandchild): # on a failure, don't leave them sleeping + if pid and running(pid): + subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True) + + def test_elsewhere_or_without_a_process_it_is_a_no_op(self): + from serve.winjob import contain + self.assertFalse(contain(None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/serve/web/app.css b/engine/strata/serve/web/app.css new file mode 100644 index 00000000..4e8363d4 --- /dev/null +++ b/engine/strata/serve/web/app.css @@ -0,0 +1,170 @@ +/* Strata web app - layout on top of tokens.css + components.css (the Strata UI kit). Colours, type, radii and + shadows come only from the kit's tokens. */ +[hidden] { display: none !important; } +html, body { height: 100%; } +body { display: flex; flex-direction: column; overflow: hidden; } +main { flex: 1; min-height: 0; display: flex; } +.view { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view[hidden] { display: none; } +.muted { color: var(--st-ink-muted); } +.small { font-size: var(--st-fs-xs); } +.card-title { font-weight: var(--st-fw-bold); font-size: var(--st-fs-base); color: var(--st-ink); } +.st-header { position: relative; z-index: 2; flex: none; } +.st-header .st-tabs { margin-left: var(--st-s-4); } +#drawer-close .st-icon { transform: rotate(-90deg); } + +/* ---------------------------------------------------------------- chat */ +.chat-scroll { flex: 1; min-height: 0; overflow-y: auto; } +.chat { max-width: 860px; margin: 0 auto; padding: var(--st-s-8) var(--st-s-6) var(--st-s-6); display: flex; + flex-direction: column; gap: var(--st-s-6); } +.chat-empty { margin: 12vh auto 0; text-align: center; } +.chat-empty__title { font-weight: var(--st-fw-black); font-size: var(--st-fs-display); line-height: var(--st-lh-tight); + letter-spacing: -.02em; } +.chat-empty__sub { margin-top: var(--st-s-3); color: var(--st-ink-muted); } +.st-msg { width: 100%; } +.st-msg--assistant { align-self: flex-start; } +.st-msg--assistant .st-bubble { width: 100%; } +.st-msg--user .st-bubble { white-space: pre-wrap; overflow-wrap: anywhere; } +.st-bubble > :first-child { margin-top: 0; } +.st-bubble > :last-child { margin-bottom: 0; } +.st-bubble p, .st-bubble ul, .st-bubble ol { margin: 0 0 var(--st-s-3); } +.st-bubble ul, .st-bubble ol { padding-left: var(--st-s-6); } +.st-bubble li + li { margin-top: var(--st-s-1); } +.st-bubble h3 { font-size: var(--st-fs-lg); margin: var(--st-s-4) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble h4 { font-size: var(--st-fs-base); margin: var(--st-s-3) 0 var(--st-s-2); color: var(--st-ink); } +.st-bubble code.inline { font: 400 .9em var(--st-font-mono); background: var(--st-surface-2); border: 1px solid var(--st-line-soft); + border-radius: 6px; padding: 1px 5px; } +.st-bubble .st-code { margin: var(--st-s-3) 0; } +.st-bubble blockquote { margin: 0 0 var(--st-s-3); padding-left: var(--st-s-3); border-left: 3px solid var(--st-line); + color: var(--st-ink-muted); } +.st-bubble hr { border: 0; border-top: 1px solid var(--st-line); margin: var(--st-s-4) 0; } +.st-bubble table { border-collapse: collapse; margin: 0 0 var(--st-s-3); font-size: var(--st-fs-md); } +.st-bubble th, .st-bubble td { border: 1px solid var(--st-line); padding: 6px 10px; text-align: left; } +.msg-images { display: flex; flex-wrap: wrap; gap: var(--st-s-2); justify-content: flex-end; } +.msg-images img { max-width: 220px; max-height: 180px; border-radius: var(--st-r-md); border: 1px solid var(--st-line); } +.st-msg .st-collapse { width: 100%; } +.st-collapse__body.thinking { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 420px; overflow-y: auto; } +.st-msg__meta .st-btn--icon { width: 28px; height: 28px; } +.st-msg__meta .st-btn--icon .st-icon { width: 16px; height: 16px; } +.cursor::after { content: ""; display: inline-block; width: 8px; height: 1.1em; margin-left: 2px; vertical-align: -3px; + border-radius: 2px; background: var(--st-accent); animation: blink 1s steps(2) infinite; } +@keyframes blink { 50% { opacity: 0; } } +.msg-error { color: var(--st-danger-text); background: var(--st-danger-tint); border-radius: var(--st-r-md); padding: 10px 14px; + font-size: var(--st-fs-md); } +/* MCP tool calls inside an answer: one compact collapsible block per call */ +.st-bubble .tool-call { margin: var(--st-s-3) 0; } +.tool-call > summary { min-width: 0; padding: 8px 12px; } +.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; } +.tool-call__preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--st-fs-xs); } +.tool-call .st-badge, .tool-call summary .small { flex: none; } +.tool-call[data-state="error"] { border-color: color-mix(in srgb, var(--st-danger) 35%, var(--st-line)); } +.tool-call[data-state="running"] .st-badge::before, .tool-call[data-state="writing"] .st-badge::before { animation: blink 1s steps(2) infinite; } +.tool-call__label { font-size: var(--st-fs-xs); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin: var(--st-s-2) 0 var(--st-s-1); } +.tool-call__pre { margin: 0; padding: 10px 12px; max-height: 320px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; + font: 400 12.5px/1.5 var(--st-font-mono); color: var(--st-ink-soft); background: var(--st-surface); + border: 1px solid var(--st-line-soft); border-radius: var(--st-r-sm); } + +.composer-wrap { flex: none; padding: 0 var(--st-s-6) var(--st-s-6); } +.st-composer { max-width: 860px; margin: 0 auto; } +.st-composer textarea { max-height: 40vh; } +.st-btn--send { width: 42px; padding: 0; } +.composer-hint { font-size: var(--st-fs-xs); color: var(--st-ink-muted); margin-right: var(--st-s-2); font-variant-numeric: tabular-nums; } +.attachments { display: flex; flex-wrap: wrap; gap: var(--st-s-2); padding: 2px 4px 0; } +.st-composer.dragging { outline: 2px dashed var(--st-accent); outline-offset: 3px; } +.chip { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 6px 0 10px; border-radius: var(--st-r-pill); + background: var(--st-surface-2); border: 1px solid var(--st-line); font-size: var(--st-fs-xs); color: var(--st-ink-soft); } +.chip .st-btn--icon { width: 22px; height: 22px; border-radius: 50%; } +.chip .st-btn--icon .st-icon { width: 14px; height: 14px; } + +/* ---------------------------------------------------------------- monitor */ +.view--monitor, .view--about { overflow-y: auto; } +.monitor, .about { max-width: 1240px; width: 100%; margin: 0 auto; padding: var(--st-s-6); display: flex; flex-direction: column; + gap: var(--st-s-5); } +.state-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.state-card__head { display: flex; align-items: center; gap: var(--st-s-4); flex-wrap: wrap; } +.badges { display: flex; gap: var(--st-s-2); flex-wrap: wrap; } +.badges .st-badge { opacity: .38; transition: opacity var(--st-dur); } +.badges .st-badge.on { opacity: 1; } +.state-card__row { display: flex; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); font-variant-numeric: tabular-nums; } +.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--st-s-4); } +.metric-card { padding: var(--st-s-4) var(--st-s-5); } +.st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; } +.st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; } +.st-metric__spark { display: block; overflow: visible; } +.speed-values { display: flex; justify-content: space-between; gap: var(--st-s-3); } +.speed-values > div { display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.speed-values > div:last-child { text-align: right; } +.speed-values .st-metric__value { font-size: clamp(20px, 2.2vw, var(--st-fs-stat)); } +.st-metric__spark .speed-prefill { color: color-mix(in srgb, var(--st-accent) 65%, black); } +.st-metric__spark[data-tone="warn"] { color: var(--st-warn); } +.st-metric__spark[data-tone="info"] { color: var(--st-info); } +.monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); } +.ctx-card { display: flex; flex-direction: column; gap: var(--st-s-2); } +.ctx-gauge { position: relative; width: 150px; height: 150px; margin: var(--st-s-2) auto var(--st-s-3); } +.ctx-gauge .st-gauge { width: 150px; height: 150px; } +.ctx-gauge .st-gauge__fill { transition: stroke-dasharray 400ms var(--st-ease); } +.ctx-gauge__label { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; + font-size: var(--st-fs-xs); } +.ctx-gauge__pct { font-weight: var(--st-fw-black); font-size: var(--st-fs-xl); line-height: 1.1; font-variant-numeric: tabular-nums; } +.bar-row { display: flex; justify-content: space-between; font-size: var(--st-fs-sm); font-weight: var(--st-fw-medium); + margin-top: var(--st-s-2); font-variant-numeric: tabular-nums; } +.req-card { display: flex; flex-direction: column; gap: var(--st-s-3); min-width: 0; } +.table-wrap { overflow-x: auto; } +.req-head { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-2); } +.table-wrap.all { max-height: 420px; overflow-y: auto; } +.req-totals { margin: 0; font-size: var(--st-fs-sm); } +.req-totals:empty { display: none; } +.mcp-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.mcp-server { display: flex; flex-direction: column; gap: var(--st-s-2); padding-top: var(--st-s-3); border-top: 1px solid var(--st-line-soft); } +.mcp-server:first-child { padding-top: 0; border-top: 0; } +.mcp-server__head { display: flex; align-items: center; gap: var(--st-s-2); flex-wrap: wrap; font-size: var(--st-fs-sm); } +.mcp-server__tools { display: flex; flex-wrap: wrap; gap: 6px; } +.mcp-server__tools .chip { height: 26px; padding: 0 10px; font-family: var(--st-font-mono); } +.mcp-note { margin: 0; } + +/* ---------------------------------------------------------------- about */ +.about { max-width: 860px; } +.about .st-card { display: flex; flex-direction: column; gap: var(--st-s-3); } +.about p { margin: 0; } +.facts { display: grid; grid-template-columns: minmax(140px, max-content) 1fr; gap: 10px var(--st-s-6); margin: 0; font-size: var(--st-fs-md); } +.facts dt { color: var(--st-ink-muted); } +.facts dd { margin: 0; color: var(--st-ink-soft); font-variant-numeric: tabular-nums; display: flex; align-items: center; gap: 6px; + overflow-wrap: anywhere; } +.facts dd code { font: 400 13px var(--st-font-mono); } +.facts .st-btn--icon { width: 28px; height: 28px; } +.facts .st-btn--icon .st-icon { width: 16px; height: 16px; } +.toggle-row { display: flex; align-items: center; justify-content: space-between; gap: var(--st-s-4); font-size: var(--st-fs-sm); + font-weight: var(--st-fw-medium); color: var(--st-ink-soft); } +.toggle-row .st-toggle { flex: none; } /* a long label must not squeeze the switch */ + +/* ---------------------------------------------------------------- drawer */ +.st-drawer { z-index: 40; } +.scrim { position: fixed; inset: 0; background: rgba(15, 23, 42, .18); z-index: 39; } +.seg { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; padding: 4px; background: var(--st-surface-2); + border: 1px solid var(--st-line); border-radius: var(--st-r-md); } +.seg button { height: 32px; border: 0; border-radius: 10px; background: transparent; color: var(--st-ink-muted); + font: 500 var(--st-fs-sm)/1 var(--st-font); cursor: pointer; } +.seg button[aria-checked="true"] { background: var(--st-surface); color: var(--st-ink); font-weight: var(--st-fw-bold); + box-shadow: var(--st-sh-card); } +.drawer-actions { display: grid; grid-template-columns: 1fr 1fr; gap: var(--st-s-3); margin-top: var(--st-s-2); } +.st-toast { animation: toast-in 180ms var(--st-ease); } +@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } } + +/* ---------------------------------------------------------------- narrow screens */ +@media (max-width: 1000px) { + .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .monitor-row { grid-template-columns: 1fr; } +} +@media (max-width: 640px) { + .st-header { padding: 0 var(--st-s-3); gap: var(--st-s-2); } + .st-header .st-tabs { margin-left: 0; } + .st-tab { padding: 0 10px; } + .st-tab .st-icon { display: none; } + #pill-text { display: none; } + .chat { padding: var(--st-s-5) var(--st-s-4); } + .composer-wrap { padding: 0 var(--st-s-3) var(--st-s-3); } + .monitor, .about { padding: var(--st-s-4); } + .facts { grid-template-columns: 1fr; gap: 2px; } + .facts dd { margin-bottom: var(--st-s-2); } +} diff --git a/engine/strata/serve/web/app.js b/engine/strata/serve/web/app.js new file mode 100644 index 00000000..6e8fa6b2 --- /dev/null +++ b/engine/strata/serve/web/app.js @@ -0,0 +1,980 @@ +// serve/web/app.js - the Strata web app: Chat, Monitor, About. No framework, no network beyond this server. +// The Monitor tab rebuilds PR #22's dashboard idea (code-martin) on the server's own /metrics. +"use strict"; + +const $ = (id) => document.getElementById(id); +const SPRITE = "web/sprite.svg"; +const icon = (name, cls = "st-icon") => ``; +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); +const fmt = (n, d = 0) => (n == null || Number.isNaN(n) ? "–" : Number(n).toLocaleString(undefined, {maximumFractionDigits: d, minimumFractionDigits: d})); +const kfmt = (n) => (n == null ? "–" : n >= 1000 ? `${fmt(n / 1000, n >= 10000 ? 0 : 1)}k` : fmt(n)); +// a context size: 32768 -> "32K" (powers of two), else like kfmt +const ctxfmt = (n) => (n && n % 1024 === 0 ? `${fmt(n / 1024)}K` : kfmt(n)); +const gb = (b, d = 1) => (b == null ? "–" : fmt(b / 1073741824, d)); // memory: binary GB, as Windows shows it + +const store = { + get(k, d) { try { const v = localStorage.getItem("strata." + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }, + set(k, v) { try { localStorage.setItem("strata." + k, JSON.stringify(v)); } catch (e) { /* private mode: in memory only */ } }, +}; + +// ------------------------------------------------------------------ toasts +function toast(kind, title, text = "", ms = 3500, action = null) { + const names = {info: "info", success: "check", warn: "warning", error: "error"}; + const el = document.createElement("div"); + el.className = `st-toast st-toast--${kind}`; + el.innerHTML = `${icon(names[kind] || "info")}
`; + el.querySelector(".st-toast__title").textContent = title; + el.querySelector(".t-text").textContent = text; + if (action) { + const b = document.createElement("button"); + b.className = "st-btn st-btn--secondary"; + b.style.height = "32px"; + b.style.marginLeft = "auto"; + b.textContent = action.label; + b.onclick = () => { action.run(); el.remove(); }; + el.appendChild(b); + } + $("toasts").appendChild(el); + setTimeout(() => el.remove(), ms); +} + +async function copyText(text, btn) { + try { + await navigator.clipboard.writeText(text); + } catch (e) { // http on another host: no async clipboard + const ta = document.createElement("textarea"); + ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); + } + if (btn) { + const use = btn.querySelector("use"); + use.setAttribute("href", `${SPRITE}#i-check`); + setTimeout(() => use.setAttribute("href", `${SPRITE}#i-copy`), 1500); + } + toast("success", "Copied to clipboard", "", 1800); +} + +// ------------------------------------------------------------------ theme and tabs +// the system's theme until the user picks one (only a click is saved) +function setTheme(t, save) { + document.documentElement.dataset.theme = t; + if (save) try { localStorage.setItem("strata.theme", t); } catch (e) { /* ignore */ } + $("theme-icon").setAttribute("href", `${SPRITE}#i-${t === "dark" ? "sun" : "moon"}`); + $("dark-toggle").setAttribute("aria-checked", String(t === "dark")); +} +const flipTheme = () => setTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true); +$("theme-btn").onclick = flipTheme; +$("dark-toggle").onclick = flipTheme; +setTheme(document.documentElement.dataset.theme || "light", false); +matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => { + let saved = null; + try { saved = localStorage.getItem("strata.theme"); } catch (err) { /* ignore */ } + if (!saved) setTheme(e.matches ? "dark" : "light", false); +}); + +let tab = "chat"; +function showTab(name) { + tab = ["chat", "monitor", "about"].includes(name) ? name : "chat"; + for (const b of document.querySelectorAll(".st-tab")) b.setAttribute("aria-selected", String(b.dataset.tab === tab)); + for (const v of ["chat", "monitor", "about"]) $(`view-${v}`).hidden = v !== tab; + if (location.hash.slice(1) !== tab) history.replaceState(null, "", tab === "chat" ? location.pathname : `#${tab}`); + if (tab === "chat") $("input").focus(); + if (tab === "monitor") loadMcp(); + if (lastMetrics) render(lastMetrics); +} +for (const b of document.querySelectorAll(".st-tab")) b.onclick = () => showTab(b.dataset.tab); +window.addEventListener("hashchange", () => showTab(location.hash.slice(1))); + +// ------------------------------------------------------------------ server access +function headers(json = false) { + const h = {}; + const key = store.get("apikey", ""); + if (key) h.Authorization = "Bearer " + key; + if (json) h["Content-Type"] = "application/json"; + return h; +} +$("api-key").value = store.get("apikey", ""); +$("api-key").onchange = () => { store.set("apikey", $("api-key").value.trim()); toast("success", "API key saved", "Kept in this browser only."); }; + +let health = {model: "strata", images: false, max_context: 0}; +async function loadHealth() { + try { + health = await (await fetch("health")).json(); + $("attach-btn").title = health.images ? "Attach a text file or a picture (or drop it here)" + : "Attach a text file (or drop it here)"; + $("chat-empty-sub").textContent = `${health.model} runs on this PC. Nothing leaves it.`; + } catch (e) { + setTimeout(loadHealth, 2000); + } +} + +// ------------------------------------------------------------------ Monitor +const METRICS = [ + {key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"}, + {key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100}, + {key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"}, + {key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"}, + {key: "power", label: "Power", icon: "bolt", unit: "W", series: "gpu_power"}, + {key: "pcie", label: "PCIe", icon: "link", unit: "", series: "gpu_pcie_rx_mb", tone: "info"}, + {key: "cpu", label: "CPU", icon: "cpu", unit: "%", series: "cpu", max: 100}, + {key: "disk", label: "Disk read", icon: "disk", unit: "MB/s", series: "disk_read_mb", tone: "info"}, +]; +$("metrics").innerHTML = METRICS.map((m) => ` +
+ ${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)} + ${m.key === "speed" ? `
+
-Decode
+
-Prefill
+
` : `– + `} + + + ${m.key === "speed" ? ` + ` : ""} +
`).join(""); + +function spark(id, values, max) { + const svg = $(id); + const v = (values || []).map((x) => (x == null ? 0 : x)); + if (v.length < 2) { svg.querySelector(".line").setAttribute("d", ""); svg.querySelector(".area").setAttribute("d", ""); return; } + const top = Math.max(max || 0, ...v, 1e-9); + const pts = v.map((x, i) => [(i / (v.length - 1)) * 100, 30 - (x / top) * 26]); + const line = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(""); + svg.querySelector(".line").setAttribute("d", line); + svg.querySelector(".area").setAttribute("d", `${line}L100,32L0,32Z`); +} +function setMetric(key, value, unit, sub) { + $(`mv-${key}`).innerHTML = value == null ? "–" : `${esc(value)}${unit ? `${esc(unit)}` : ""}`; + $(`ms-${key}`).textContent = sub || ""; +} + +let lastMetrics = null, metricsFailures = 0, keyWarned = false, mcpTick = 0; +let reqShowAll = false; // the Monitor's request table: the last 12, or every one the server keeps (issue #35) +async function poll() { + try { + const r = await fetch(reqShowAll ? "metrics?requests=all" : "metrics", {headers: headers()}); + if (r.status === 401) { + setPill("error", "API key needed"); + if (!keyWarned) { keyWarned = true; toast("warn", "API key needed", "This server needs a key: add it under About > Settings.", 6000); } + } else if (r.ok) { + lastMetrics = await r.json(); + metricsFailures = 0; + render(lastMetrics); + } else { + throw new Error(`HTTP ${r.status}`); + } + } catch (e) { + if (++metricsFailures === 3) setPill("error", "Server not reachable"); + } + if (tab === "monitor" && ++mcpTick % 10 === 0) loadMcp(); // server states change rarely: every 10 s + setTimeout(poll, 1000); +} + +function setPill(state, text) { + $("pill").dataset.state = state === "error" ? "queued" : state; + $("pill-text").textContent = text; +} + +function render(m) { + const live = m.live || {}, hw = m.hardware || {}, st = m.hardware_static || {}, eng = m.engine || {}, h = m.history || {}; + const last = (m.requests || [])[0]; + // the header pill + if (live.state === "reading") { + const pct = live.prompt_total ? Math.round((100 * live.prompt_read) / live.prompt_total) : null; + setPill("reading", pct != null ? `Reading prompt · ${pct}%` : "Reading prompt"); + } else if (live.state === "generating") { + setPill("generating", `Generating · ${fmt(live.tok_s, 1)} tok/s`); + } else { + setPill("idle", "Idle"); + } + if (live.queued > 0) setPill("queued", `${live.queued} queued`); + if (tab === "monitor") renderMonitor(live, hw, st, eng, h, last, m.requests || [], m.totals, m.requests_kept); + if (tab === "about") renderAbout(eng, hw, st); +} + +function renderTotals(t) { + if (!t || !t.requests) return ""; + const since = new Date(t.since * 1000).toLocaleString([], {weekday: "short", hour: "2-digit", minute: "2-digit"}); + const read = t.prompt_tokens - t.reused; + const pSpeed = t.prompt_ms > 0 && read > 0 ? ` at ${fmt(read / (t.prompt_ms / 1000))} tok/s` : ""; + const oSpeed = t.decode_ms > 0 && t.output_tokens > 0 ? ` at ${fmt(t.output_tokens / (t.decode_ms / 1000), 1)} tok/s` : ""; + return `Since ${since}: ${fmt(t.requests)} requests · ${fmt(read)} prompt tokens read${pSpeed} (${fmt(t.reused)} reused) · ` + + `${fmt(t.output_tokens)} written${oSpeed}`; +} +function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) { + // model state + const on = live.queued > 0 ? "queued" : live.state; + for (const b of document.querySelectorAll("#state-badges .st-badge")) b.classList.toggle("on", b.dataset.s === on || b.dataset.s === live.state); + const prog = $("state-progress"); + let label = "Waiting for a request", detail = "", pct = 0; + if (live.state === "reading") { + label = "Reading prompt"; + prog.dataset.tone = "info"; + if (live.prompt_total) { + pct = (100 * live.prompt_read) / live.prompt_total; + detail = `${fmt(live.prompt_read)} / ${fmt(live.prompt_total)} tokens · ${fmt(pct)}%`; + } else { + detail = `${fmt(live.prompt_tokens)} tokens`; + } + } else if (live.state === "generating") { + label = live.phase ? live.phase[0].toUpperCase() + live.phase.slice(1) : "Generating"; + delete prog.dataset.tone; + pct = live.max_tokens ? Math.min(100, (100 * live.generated) / live.max_tokens) : 0; + detail = `${fmt(live.generated)} tokens · ${fmt(live.tok_s, 1)} tok/s`; + } else if (last) { + delete prog.dataset.tone; + detail = `last: ${fmt(last.output_tokens)} tokens${last.decode_tok_s ? ` at ${fmt(last.decode_tok_s, 1)} tok/s` : ""}`; + } + $("state-label").textContent = label; + $("state-detail").textContent = detail; + $("state-bar").style.width = `${pct}%`; + + // the eight cards + const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null; + setMetric("speed", speed == null ? null : fmt(speed, 1), "t/s", + live.state === "generating" ? "Decode now" : last ? "Decode last request" : "Decode"); + const prefill = live.state !== "idle" ? live.prefill_tok_s_mean + : last && last.prompt_ms > 0 ? Math.max(0, last.prompt_tokens - (last.reused || 0)) / (last.prompt_ms / 1000) : null; + setMetric("prefill", prefill == null ? null : fmt(prefill), "t/s", + live.state === "reading" ? "Prefill now" : live.state === "generating" ? "Prefill this request" : last ? "Prefill last request" : "Prefill"); + spark("sp-speed", h.tok_s); + spark("sp-prefill", h.prefill_tok_s_mean); + // a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own + const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · "); + const multi = (hw.gpus || []).length > 1; + setMetric("gpu", hw.gpu_util == null ? null : fmt(hw.gpu_util), "%", + multi ? per((g) => (g.util == null ? "–" : `${fmt(g.util)}%`)) : st.gpu_name || ""); + spark("sp-gpu", h.gpu_util, 100); + setMetric("vram", hw.gpu_mem_used == null ? null : gb(hw.gpu_mem_used), hw.gpu_mem_total ? `/ ${gb(hw.gpu_mem_total, 0)} GB` : "GB", + multi ? per((g) => (g.mem_used == null ? "–" : `${gb(g.mem_used)} GB`)) + : eng.expert_slots ? `${fmt(eng.expert_slots)} experts cached` : ""); + spark("sp-vram", h.gpu_mem_used, hw.gpu_mem_total); + setMetric("temp", hw.gpu_temp == null ? null : fmt(hw.gpu_temp), "°C", + multi ? per((g) => (g.temp == null ? "–" : `${fmt(g.temp)}°`)) : ""); + spark("sp-temp", h.gpu_temp, 90); + setMetric("power", hw.gpu_power == null ? null : fmt(hw.gpu_power), "W", hw.gpu_power_limit ? `of ${fmt(hw.gpu_power_limit)} W limit` : ""); + spark("sp-power", h.gpu_power, hw.gpu_power_limit); + const gen = hw.gpu_pcie_gen_max || hw.gpu_pcie_gen; + setMetric("pcie", gen ? `Gen${gen}` : null, hw.gpu_pcie_width ? `x${hw.gpu_pcie_width}` : "", + hw.gpu_pcie_rx_mb == null ? "" : `to GPU ${fmt(hw.gpu_pcie_rx_mb, hw.gpu_pcie_rx_mb < 10 ? 1 : 0)} MB/s` + + (hw.gpu_pcie_gen && gen && hw.gpu_pcie_gen < gen ? ` · idle Gen${hw.gpu_pcie_gen}` : "")); + spark("sp-pcie", h.gpu_pcie_rx_mb); + setMetric("cpu", hw.cpu == null ? null : fmt(hw.cpu), "%", st.threads ? `${st.cores ? `${st.cores} cores · ` : ""}${st.threads} threads` : ""); + spark("sp-cpu", h.cpu, 100); + if (hw.disk_read_mb == null) { + setMetric("disk", null, "", st.psutil ? "" : "needs psutil (setup installs it)"); + } else { + const big = hw.disk_read_mb >= 1000; + setMetric("disk", big ? fmt(hw.disk_read_mb / 1024, 2) : fmt(hw.disk_read_mb, hw.disk_read_mb < 10 ? 1 : 0), big ? "GB/s" : "MB/s", + hw.disk_write_mb == null ? "" : `write ${fmt(hw.disk_write_mb, 1)} MB/s`); + } + spark("sp-disk", h.disk_read_mb); + + // context fill: the running request, else the last one + const ctx = eng.max_context || 0; + let used = 0; + if (live.state !== "idle") used = (live.prompt_tokens || 0) + (live.generated || 0); + else if (last) used = (last.prompt_tokens || 0) + (last.output_tokens || 0); + const frac = ctx ? Math.min(1, used / ctx) : 0; + $("ctx-fill").setAttribute("stroke-dasharray", `${(235.6 * frac).toFixed(1)} 314.2`); + $("ctx-fill").style.opacity = 235.6 * frac >= 3 ? "1" : "0"; // a near-zero arc would draw just its round cap + $("ctx-pct").textContent = `${Math.round(frac * 100)}%`; + $("ctx-sub").textContent = ctx ? `${kfmt(used)} / ${ctxfmt(ctx)}` : "–"; + const cacheBytes = (eng.expert_cache_mib || 0) * 1048576; + $("slots-text").textContent = eng.expert_slots ? `${fmt(eng.expert_slots)} · ${gb(cacheBytes)} GB` : "–"; + $("slots-bar").style.width = hw.gpu_mem_total ? `${Math.min(100, (100 * cacheBytes) / hw.gpu_mem_total)}%` : "0%"; + $("ram-text").textContent = hw.ram_total ? `${gb(hw.ram_used)} / ${gb(hw.ram_total, 0)} GB` : "–"; + const ramPct = hw.ram_total ? (100 * hw.ram_used) / hw.ram_total : 0; + $("ram-bar").style.width = `${ramPct}%`; + if (ramPct > 92) $("ram-progress").dataset.tone = "danger"; else delete $("ram-progress").dataset.tone; + $("temp-text").textContent = hw.gpu_temp == null ? "–" : `${fmt(hw.gpu_temp)} °C`; + $("temp-bar").style.width = hw.gpu_temp == null ? "0%" : `${Math.min(100, hw.gpu_temp)}%`; + + // recent requests + const body = $("req-body"); + if (!requests.length) { + body.innerHTML = `No requests yet`; + } else { + const badge = {stop: ["", "Done"], length: ["", "Max tokens"], cancel: ["st-badge--queued", "Stopped"], + disconnect: ["st-badge--queued", "Closed"], error: ["st-badge--error", "Error"]}; + body.innerHTML = requests.slice(0, reqShowAll ? requests.length : 12).map((r) => { + const [cls, text] = badge[r.finish] || ["", r.finish || "–"]; + const t = new Date(r.time * 1000).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit", second: "2-digit"}); + const proj = r.projection == null ? "" : ` ${r.projection ? "ESP" : "stock"}`; + const hit = r.hit_rate == null ? "–" : `${(r.hit_rate * 100).toFixed(1)}%`; + return `${esc(t)}${esc(text)}${proj}${fmt(r.prompt_tokens)} + ${fmt(r.reused)}${fmt(r.output_tokens)}${fmt(r.decode_tok_s, 1)} + ${hit}${fmt(r.duration_s, 1)} s`; + }).join(""); + } + const all = $("req-all"); + kept = kept == null ? requests.length : kept; + all.hidden = kept <= 12; + all.textContent = reqShowAll ? "Show fewer" : `Show all (${kept})`; + $("req-wrap").classList.toggle("all", reqShowAll); + $("req-totals").textContent = renderTotals(totals); +} + +function facts(el, rows) { + el.innerHTML = rows.filter((r) => r[1] != null && r[1] !== "").map(([k, v, copy]) => + `
${esc(k)}
${copy ? `${esc(v)}` : esc(v)}
`).join(""); +} +// INFO cvec=project:4-44[:singleL] | add:A-B | 0 +function projectionText(c) { + if (!c || c === "0" || c === 0) return null; + const [mode, range, single] = String(c).split(":"); + const [a, b] = (range || "").split("-"); + return `${mode === "project" ? "Projection" : "Additive"} control vector on layers ${a}–${b}` + + `${single ? ` (layer ${single.replace("single", "")}'s direction)` : ""}. Per chat in Sampling. Its package ` + + "describes the vector as a refusal-direction projection; measure the speed yourself"; +} +function renderAbout(eng, hw, st) { + const kv = {int8: "8-bit", q4_0: "4-bit (Hadamard-rotated)", fp16: "16-bit"}[eng.kv] || eng.kv; + facts($("facts-engine"), [ + ["Model", eng.model], + ["Engine", eng.version ? `v${eng.version}` : "built from source"], + ["Context", eng.max_context ? `${fmt(eng.max_context)} tokens` : null], + ["KV cache", kv ? `${kv}${eng.kv_resident ? `, streamed: ${fmt(eng.kv_resident)} positions per layer in VRAM, the rest in RAM` : ", all in VRAM"}` : null], + ["Experts in VRAM", eng.expert_slots ? `${fmt(eng.expert_slots)} (${gb((eng.expert_cache_mib || 0) * 1048576)} GB)` : null], + ["Speculation", eng.spec ? `MTP drafts up to ${Math.max(0, (eng.mtp_max || eng.spec) - 1)} tokens${eng.lookup ? ", prompt lookup on" : ""}` : null], + ["Images", eng.images ? "on" : "off"], + ["Experimental speed projection", projectionText(eng.cvec)], + ]); + facts($("facts-hw"), [ + ["GPU", st.gpu_name ? `${st.gpu_name}${hw.gpu_mem_total ? `, ${gb(hw.gpu_mem_total, 0)} GB` : ""}` : "not readable (NVML)"], + ["CPU", st.cpu_name ? `${st.cpu_name}${st.threads ? `, ${st.threads} threads` : ""}` : null], + ["RAM", hw.ram_total ? `${gb(hw.ram_total, 0)} GB` : null], + ]); + const base = location.origin; + facts($("facts-api"), [ + ["OpenAI base URL", `${base}/v1`, true], + ["Anthropic base URL", base, true], + ["Model name", eng.model, true], + ]); +} +document.addEventListener("click", (e) => { + const b = e.target.closest("[data-copy]"); + if (b) copyText(b.dataset.copy, b); +}); +$("req-all").addEventListener("click", () => { reqShowAll = !reqShowAll; if (lastMetrics) render(lastMetrics); }); + +// ------------------------------------------------------------------ MCP servers (GET /mcp) +// Tools from the MCP servers in the run config: the chat offers them to the model (opt-in per request, +// "strata_mcp": true, which only this page sends); the Monitor lists the servers and what they offer. +let mcpInfo = {servers: [], tools: 0}, mcpRetry = null; +async function loadMcp() { + try { + const r = await fetch("mcp", {headers: headers()}); + if (!r.ok) return; + mcpInfo = await r.json(); + } catch (e) { return; /* an older server: no MCP */ } + renderMcp(); + clearTimeout(mcpRetry); // right after the start, servers may still be starting (npx downloads) + if ((mcpInfo.servers || []).some((s) => s.status === "starting")) mcpRetry = setTimeout(loadMcp, 3000); +} +const MCP_STATE = {ready: ["st-badge--generating", "Connected"], starting: ["st-badge--reading", "Starting"], + failed: ["st-badge--error", "Failed"], stopped: ["st-badge--queued", "Stopped"], idle: ["", "Waiting"]}; +function renderMcp() { + const servers = mcpInfo.servers || []; + $("mcp-card").hidden = !servers.length; + $("mcp-row").hidden = !servers.length; + const ready = servers.filter((s) => s.status === "ready" || s.status === "stopped"); + $("mcp-sum").textContent = servers.length ? `${fmt(mcpInfo.tools)} tools · ${ready.length} of ${servers.length} servers connected` : ""; + $("mcp-row-sub").textContent = mcpInfo.tools ? `${fmt(mcpInfo.tools)} tools from ${ready.map((s) => s.name).join(", ")}; the model calls them when it decides to` + : "no server is connected yet (see the Monitor)"; + $("mcp-list").innerHTML = servers.map((s) => { + const [cls, text] = MCP_STATE[s.status] || ["", s.status]; + const info = s.info && s.info.name ? ` · ${s.info.name}${s.info.version ? ` ${s.info.version}` : ""}` : ""; + return `
${esc(text)}` + + `${esc(s.name)}${esc(s.transport)} · ${fmt(s.tools.length)} tools${esc(info)}
` + + (s.error ? `
${esc(s.error)}
` : "") + + (s.tools.length ? `
${s.tools.map((t) => `${esc(t.tool)}`).join("")}
` : "") + + `
`; + }).join(""); +} + +// ------------------------------------------------------------------ Markdown (escaped first, then formatted) +function inline(s) { + const codes = []; + s = s.replace(/`([^`\n]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; }); + s = esc(s) + .replace(/\*\*([^*\n]+)\*\*/g, "$1") + .replace(/(^|[^*\w])\*([^*\n]+)\*(?![*\w])/g, "$1$2") + .replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, '
$1'); + return s.replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[+i])}`); +} +function codeBlock(lang, code) { + return `
${esc(lang || "code")}` + + `
` + + `
${esc(code)}
`; +} +function blocks(text) { + const out = [], lines = text.split("\n"); + let para = [], list = null; + const flushPara = () => { if (para.length) out.push(`

${para.map(inline).join("
")}

`); para = []; }; + const flushList = () => { if (list) out.push(`<${list.tag}>${list.items.map((i) => `
  • ${inline(i)}
  • `).join("")}`); list = null; }; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + let m; + if (!l.trim()) { flushPara(); flushList(); continue; } + if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { flushPara(); flushList(); out.push(`<${m[1].length <= 2 ? "h3" : "h4"}>${inline(m[2])}`); continue; } + if (/^\s*([-*_])\s*\1\s*\1[\s\1]*$/.test(l)) { flushPara(); flushList(); out.push("
    "); continue; } + if ((m = l.match(/^>\s?(.*)$/))) { flushPara(); flushList(); out.push(`
    ${inline(m[1])}
    `); continue; } + if (/^\s*\|.*\|\s*$/.test(l) && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1])) { + flushPara(); flushList(); + const cells = (row) => row.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim())); + let html = `${cells(l).map((c) => ``).join("")}`; + i += 2; + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) html += `${cells(lines[i++]).map((c) => ``).join("")}`; + i--; + out.push(html + "
    ${c}
    ${c}
    "); + continue; + } + if ((m = l.match(/^\s*(?:[-*+]|(\d+)[.)])\s+(.*)$/))) { + flushPara(); + const tag = m[1] ? "ol" : "ul"; + if (!list || list.tag !== tag) { flushList(); list = {tag, items: []}; } + list.items.push(m[2]); + continue; + } + if (list && /^\s{2,}\S/.test(l)) { list.items[list.items.length - 1] += " " + l.trim(); continue; } + flushList(); + para.push(l); + } + flushPara(); flushList(); + return out.join(""); +} +function markdown(text) { + let html = "", rest = text; + for (;;) { + const m = rest.match(/(^|\n)```([^\n`]*)\n/); + if (!m) { html += blocks(rest); break; } + html += blocks(rest.slice(0, m.index)); + rest = rest.slice(m.index + m[0].length); + const end = rest.match(/(^|\n)```[ \t]*(\n|$)/); + if (!end) { html += codeBlock(m[2].trim(), rest); break; } // still streaming + html += codeBlock(m[2].trim(), rest.slice(0, end.index)); + rest = rest.slice(end.index + end[0].length); + } + return html; +} + +// ------------------------------------------------------------------ Chat +const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true}; +let settings = {...DEFAULTS, ...store.get("sampling", {})}; +let messages = store.get("chat", []); +let attachments = []; // {name, url} +let busy = null; // {controller, msg} + +function saveChat() { + store.set("chat", messages.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})), + files: (m.files || []).map((f) => ({name: f.name}))}))); +} +function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); } + +function msgEl(m, i) { + const el = document.createElement("div"); + el.className = `st-msg st-msg--${m.role}`; + el.dataset.i = i; + if (m.role === "user") { + if (m.files && m.files.length) { + const wrap = document.createElement("div"); + wrap.className = "msg-images"; + for (const f of m.files) { + const c = document.createElement("span"); + c.className = "chip"; + c.innerHTML = icon("attach", "st-icon st-icon--sm"); + c.append(f.name); + wrap.appendChild(c); + } + el.appendChild(wrap); + } + if (m.images && m.images.length) { + const wrap = document.createElement("div"); + wrap.className = "msg-images"; + for (const im of m.images) { + if (im.url) { const img = document.createElement("img"); img.src = im.url; img.alt = im.name || "image"; wrap.appendChild(img); } + else { const c = document.createElement("span"); c.className = "chip"; c.innerHTML = icon("image", "st-icon st-icon--sm"); c.append(im.name || "image"); wrap.appendChild(c); } + } + el.appendChild(wrap); + } + const b = document.createElement("div"); + b.className = "st-bubble"; + b.textContent = m.text; + el.appendChild(b); + const meta = document.createElement("div"); + meta.className = "st-msg__meta"; + meta.textContent = `You · ${timeStr(m.time)}`; + el.appendChild(meta); + } else { + el.innerHTML = `` + + `
    ` + + `
    `; + updateAssistant(el, m, false); + } + return el; +} +// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and +// the result as the model read it. Its body is built only while open: a result can be 20,000 characters. +const TOOL_STATE = {writing: ["st-badge--reading", "Writing"], running: ["st-badge--generating", "Running"], done: ["", "Done"], + error: ["st-badge--error", "Error"], skipped: ["st-badge--queued", "Not run"]}; +function toolHtml(t, k) { + const [cls, label] = TOOL_STATE[t.state] || ["", t.state]; + const args = t.arguments == null ? "" : JSON.stringify(t.arguments, null, 2); + const preview = t.result != null ? t.result : args.replace(/\s+/g, " "); + let body = ""; + if (t.open) { + body = `
    Arguments
    ${esc(args || "(being written)")}
    `; + if (t.result != null) { + body += `
    ${t.ok ? "Result" : "Error"}${t.chars ? ` · ${fmt(t.chars)} characters` : ""}` + + `${t.truncated ? ", cut for the model" : ""}
    ${esc(t.result)}
    `; + } + } + return `
    ` + + `${icon("tool", "st-icon st-icon--sm")}${esc(t.tool || t.name || "tool")}` + + (t.server ? `${esc(t.server)}` : "") + + `${esc(preview.slice(0, 200))}` + + `${esc(label)}${t.ms != null && t.state !== "skipped" ? `${fmt(t.ms / 1000, 1)} s` : ""}` + + `${icon("chevron", "st-icon st-icon--sm st-chev")}
    ${body}
    `; +} +// the answer's text with the tool blocks where the model called them +function answerHtml(m) { + if (!m.tools || !m.tools.length) return markdown(m.text || ""); + let html = "", pos = 0; + m.tools.forEach((t, k) => { + const at = Math.min(Math.max(t.at || 0, pos), m.text.length); + if (at > pos) html += markdown(m.text.slice(pos, at)); + pos = at; + html += toolHtml(t, k); + }); + return html + markdown(m.text.slice(pos)); +} +// a tool event from the stream (the `strata_mcp` field of a chunk) +function onTool(m, x) { + if (x.event === "limit") { m.limit = x.max_rounds; return; } + m.tools = m.tools || []; + let t = m.tools.find((y) => y.id === x.id); + if (!t) { t = {id: x.id, name: x.name, at: m.text.length, rat: m.reasoning.length, state: "writing"}; m.tools.push(t); } + if (x.event === "call") { + Object.assign(t, {name: x.name, server: x.server, tool: x.tool, arguments: x.arguments, round: x.round, state: "running"}); + } else if (x.event === "result") { + Object.assign(t, {result: x.text, ok: x.ok, chars: x.chars, truncated: x.truncated, ms: x.ms, + state: x.skipped ? "skipped" : x.ok ? "done" : "error"}); + } +} +function updateAssistant(el, m, streaming) { + const det = el.querySelector("details.think"); + if (m.reasoning) { + det.hidden = false; + const thinkingNow = streaming && !m.text; + el.querySelector(".think-title").textContent = thinkingNow ? "Thinking…" : + m.thinkSecs != null ? `Thought for ${fmt(m.thinkSecs, 1)} s` : "Thoughts"; + const body = el.querySelector(".thinking"); + if (det.open || thinkingNow) body.textContent = m.reasoning; + else body.dataset.pending = "1"; + // open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves + if (thinkingNow && settings.show && !det.dataset.touched && !det.open) { det._auto = true; det.open = true; } + if (!thinkingNow && det.open && !det.dataset.touched) { det._auto = true; det.open = false; } + } + const bubble = el.querySelector(".st-bubble"); + if (m.error) { + bubble.innerHTML = `
    `; + bubble.firstChild.textContent = m.error; + } else if (!m.text && streaming && !(m.tools && m.tools.length)) { + bubble.innerHTML = m.reasoning ? `Writing` : ``; + } else { + bubble.innerHTML = answerHtml(m); + if (streaming) bubble.classList.add("cursor"); else bubble.classList.remove("cursor"); + } + el.querySelector(".meta-text").textContent = m.meta || (streaming ? "" : m.stopped ? "Stopped" : ""); + el.querySelector("[data-msg-copy]").hidden = streaming || !m.text; +} +function renderChat() { + const chat = $("chat"); + chat.querySelectorAll(".st-msg").forEach((e) => e.remove()); + $("chat-empty").hidden = messages.length > 0; + messages.forEach((m, i) => chat.appendChild(msgEl(m, i))); + scrollDown(true); +} +function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; } +function scrollDown(force) { const s = $("chat-scroll"); if (force || nearBottom()) s.scrollTop = s.scrollHeight; } + +$("chat").addEventListener("click", (e) => { + const cc = e.target.closest("[data-code-copy]"); + if (cc) { copyText(cc.closest(".st-code").querySelector("pre").textContent, cc); return; } + const mc = e.target.closest("[data-msg-copy]"); + if (mc) { const i = +mc.closest(".st-msg").dataset.i; copyText(messages[i].text, mc); return; } + // a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it + const sum = e.target.closest(".tool-call > summary"); + if (sum) { + e.preventDefault(); + const el = sum.closest(".st-msg"), m = messages[+el.dataset.i], t = m && m.tools && m.tools[+sum.parentElement.dataset.tool]; + if (!t) return; + t.open = !t.open; + updateAssistant(el, m, !!busy && busy.msg === m); + } +}); +$("chat").addEventListener("toggle", (e) => { + const d = e.target; + if (d.tagName !== "DETAILS" || !d.classList.contains("think")) return; + if (d._auto) { d._auto = false; return; } // our own open/close, not the user's + d.dataset.touched = "1"; + const body = d.querySelector(".thinking"); + if (d.open && body.dataset.pending) { body.textContent = messages[+d.closest(".st-msg").dataset.i].reasoning; delete body.dataset.pending; } +}, true); + +function apiMessages() { + const out = []; + for (const m of messages) { + if (m.role === "user") { + const imgs = (m.images || []).filter((i) => i.url); + const text = userText(m); + out.push({role: "user", content: imgs.length ? [{type: "text", text}, + ...imgs.map((i) => ({type: "image_url", image_url: {url: i.url}}))] : text}); + } else if (!m.error) { + out.push(...assistantMessages(m)); + } + } + return out; +} +// An answer that used MCP tools goes back as the model wrote it: per round the text before the calls, the calls and +// their results (as the model read them), then the rest - so the next question can build on what the tools found. +function assistantMessages(m) { + const ran = (m.tools || []).filter((t) => t.round != null && t.result != null && t.state !== "skipped"); + if (!ran.length) return m.text ? [{role: "assistant", content: m.text}] : []; + const out = []; + let pos = 0; + for (const r of [...new Set(ran.map((t) => t.round))]) { + const calls = ran.filter((t) => t.round === r); + const at = Math.min(Math.max(pos, calls[0].at || 0), m.text.length); + out.push({role: "assistant", content: m.text.slice(pos, at).trim(), + tool_calls: calls.map((t) => ({id: t.id, type: "function", function: {name: t.name, arguments: JSON.stringify(t.arguments || {})}}))}); + for (const t of calls) out.push({role: "tool", tool_call_id: t.id, content: t.result}); + pos = at; + } + const rest = m.text.slice(pos).trim(); + if (rest) out.push({role: "assistant", content: rest}); + return out; +} + +function setBusy(on) { + $("stop-btn").hidden = !on; + $("send-btn").disabled = on; + $("composer-hint").textContent = on ? "" : "Shift+Enter: new line"; +} + +async function send() { + const text = $("input").value.trim(); + if ((!text && !attachments.length) || busy) return; + messages.push({role: "user", text, images: attachments.filter((a) => a.kind !== "file"), + files: attachments.filter((a) => a.kind === "file"), time: Date.now()}); + attachments = []; + renderAttachments(); + $("input").value = ""; + autosize(); + const m = {role: "assistant", text: "", reasoning: "", time: Date.now()}; + messages.push(m); + renderChat(); + const el = $("chat").lastElementChild; + const controller = new AbortController(); + busy = {controller, msg: m}; + setBusy(true); + + const body = {model: health.model, messages: apiMessages(), stream: true, + reasoning_effort: settings.thinking}; + if (settings.temperature > 0) { + Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k}); + } else { + body.temperature = 0; + } + if (settings.seed) body.seed = +settings.seed; + if (settings.max) body.max_tokens = +settings.max; + if (projectionLoaded()) body.experimental_speed_projection = !!settings.esp; + if (settings.mcp !== false && mcpInfo.tools > 0) body.strata_mcp = true; // this server may run MCP tools for it + + let firstAt = null, thinkStart = null, usage = null, frame = 0; + const paint = () => { frame = 0; updateAssistant(el, m, true); scrollDown(); }; + try { + const r = await fetch("v1/chat/completions", {method: "POST", headers: headers(true), body: JSON.stringify(body), + signal: controller.signal}); + if (!r.ok) { + let msg = `HTTP ${r.status}`; + try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } + if (r.status === 401) msg = "This server needs an API key: add it under About > Settings."; + throw new Error(msg); + } + const reader = r.body.getReader(), dec = new TextDecoder(); + let buf = ""; + for (;;) { + const {value, done} = await reader.read(); + if (done) break; + buf += dec.decode(value, {stream: true}); + let nl; + while ((nl = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line.startsWith("data:")) continue; // ": keep-alive" comments while a long prompt is read + const data = line.slice(5).trim(); + if (data === "[DONE]") continue; + let j; + try { j = JSON.parse(data); } catch (e) { continue; } + if (j.error) throw new Error(j.error.message || "the engine reported an error"); + if (j.usage) usage = j.usage; + if (j.strata_mcp) onTool(m, j.strata_mcp); + const d = (j.choices && j.choices[0] && j.choices[0].delta) || {}; + const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null; // a new round after a tool + if (d.reasoning_content) { + if (!firstAt) firstAt = performance.now(); + if (!thinkStart) thinkStart = performance.now(); + if (lastTool && m.reasoning && lastTool.rat === m.reasoning.length) m.reasoning += "\n\n"; + m.reasoning += d.reasoning_content; + } + if (d.content) { + if (!firstAt) firstAt = performance.now(); + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + if (lastTool && m.text && lastTool.at === m.text.length) m.text += "\n\n"; + m.text += d.content; + } + if (!frame) frame = requestAnimationFrame(paint); + } + } + } catch (e) { + if (e.name === "AbortError") m.stopped = true; + else { m.error = e.message || String(e); toast("error", "The request failed", m.error, 6000); } + } + if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000; + const n = usage ? usage.completion_tokens : null; + if (n && firstAt) { + const secs = (performance.now() - firstAt) / 1000; + m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}` + + (projectionLoaded() ? (settings.esp ? " · projection on" : " · projection off") : ""); + } else if (m.stopped) { + m.meta = "Stopped"; + } + for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; } + const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length; + if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${ran} tool call${ran > 1 ? "s" : ""}`; + if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`; + busy = null; + setBusy(false); + if (frame) cancelAnimationFrame(frame); + updateAssistant(el, m, false); + saveChat(); + scrollDown(); +} + +$("composer").onsubmit = (e) => { e.preventDefault(); send(); }; +$("stop-btn").onclick = () => { if (busy) busy.controller.abort(); }; +$("input").addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); } +}); +function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; } +$("input").addEventListener("input", autosize); + +$("new-btn").onclick = () => { + if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; } + if (!messages.length) return; + const backup = messages; + messages = []; + saveChat(); + renderChat(); + toast("info", "New chat", "The last one was cleared.", 6000, {label: "Undo", run: () => { messages = backup; saveChat(); renderChat(); }}); +}; +$("export-btn").onclick = () => { + if (!messages.length) { toast("info", "Nothing to save yet"); return; } + const tools = (m) => (m.tools || []).filter((t) => t.result != null).map((t) => + `
    Tool ${t.server ? `${t.server} / ` : ""}${t.tool || t.name}${t.ok ? "" : " (error)"}\n\n` + + `\`\`\`json\n${JSON.stringify(t.arguments || {}, null, 2)}\n\`\`\`\n\n\`\`\`\n${t.result}\n\`\`\`\n\n
    \n\n`).join(""); + const md = messages.map((m) => m.role === "user" ? `## You\n\n${m.text}\n` : + `## ${health.model}\n\n${m.reasoning ? `
    Thinking\n\n${m.reasoning}\n\n
    \n\n` : ""}${tools(m)}${m.text || m.error || ""}\n`).join("\n"); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([md], {type: "text/markdown"})); + a.download = `strata-chat-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); +}; + +// pictures and text files: the attach button, dropping them on the chat, or pasting a picture (issue #30) +const TEXT_EXT = /\.(txt|md|markdown|rst|tex|py|pyi|ipynb|js|mjs|cjs|ts|tsx|jsx|vue|svelte|json|jsonl|csv|tsv|log|ya?ml|toml|ini|cfg|conf|env|xml|html?|css|scss|less|c|cc|cpp|cxx|h|hh|hpp|cu|cuh|rs|go|java|kt|kts|swift|rb|php|pl|lua|r|jl|scala|sql|sh|bash|zsh|fish|ps1|psm1|bat|cmd|diff|patch|gradle|cmake|mk|dockerfile|gitignore|proto|graphql)$/i; +const MAX_TEXT_FILE = 512 * 1024; +function isTextFile(f) { + return f.type.startsWith("text/") || /json|xml|javascript|yaml|toml|x-sh|x-python/.test(f.type) || + TEXT_EXT.test(f.name) || /(^|[\\/])(makefile|dockerfile|readme|license)$/i.test(f.name); +} +function addFiles(files) { + for (const f of files) { + if (f.type.startsWith("image/")) { + if (!health.images) { toast("warn", "Pictures are off", "This model was set up for text only."); continue; } + if (f.size > 20e6) { toast("warn", "Picture too large", `${f.name} is over 20 MB.`); continue; } + const r = new FileReader(); + r.onload = () => { attachments.push({kind: "image", name: f.name || "pasted image", url: r.result}); renderAttachments(); }; + r.readAsDataURL(f); + continue; + } + if (!isTextFile(f)) { toast("warn", "Not a text file", `${f.name}: attach text files (code, notes, logs, data)${health.images ? " or pictures" : ""}.`); continue; } + if (f.size > MAX_TEXT_FILE) { toast("warn", "File too large", `${f.name} is over 512 KB.`); continue; } + const r = new FileReader(); + r.onload = () => { + const text = String(r.result); + if (text.includes("\u0000")) { toast("warn", "Not a text file", `${f.name} looks like a binary file.`); return; } + attachments.push({kind: "file", name: f.name, text}); + renderAttachments(); + }; + r.readAsText(f); + } +} +// a file's text in the message, fenced with more backticks than it contains itself +function fileBlock(f) { + const longest = Math.max(2, ...(f.text.match(/`+/g) || []).map((s) => s.length)); + const fence = "`".repeat(longest + 1); + return `File: ${f.name}\n${fence}\n${f.text}\n${fence}`; +} +function userText(m) { + const files = (m.files || []).filter((f) => f.text != null); + return [m.text, ...files.map(fileBlock)].filter((s) => s).join("\n\n"); +} +function renderAttachments() { + const box = $("attachments"); + box.hidden = !attachments.length; + box.innerHTML = ""; + attachments.forEach((a, i) => { + const c = document.createElement("span"); + c.className = "chip"; + c.innerHTML = icon(a.kind === "file" ? "attach" : "image", "st-icon st-icon--sm"); + c.append(a.name); + const x = document.createElement("button"); + x.type = "button"; x.className = "st-btn st-btn--icon"; x.setAttribute("aria-label", "Remove"); + x.innerHTML = icon("trash"); + x.onclick = () => { attachments.splice(i, 1); renderAttachments(); }; + c.appendChild(x); + box.appendChild(c); + }); +} +$("attach-btn").onclick = () => $("file").click(); +// drop files on the chat or the message box +for (const id of ["chat", "composer"]) { + const el = $(id); + el.addEventListener("dragover", (e) => { + if (![...(e.dataTransfer || {}).types || []].includes("Files")) return; + e.preventDefault(); + $("composer").classList.add("dragging"); + }); + el.addEventListener("dragleave", () => $("composer").classList.remove("dragging")); + el.addEventListener("drop", (e) => { + $("composer").classList.remove("dragging"); + if (!e.dataTransfer || !e.dataTransfer.files.length) return; + e.preventDefault(); + addFiles(e.dataTransfer.files); + $("input").focus(); + }); +} +$("file").onchange = () => { addFiles($("file").files); $("file").value = ""; }; +$("input").addEventListener("paste", (e) => { + if (!health.images) return; + const files = [...(e.clipboardData || {}).files || []].filter((f) => f.type.startsWith("image/")); + if (files.length) { e.preventDefault(); addFiles(files); } +}); + +// ------------------------------------------------------------------ the sampling drawer +function openDrawer(open) { + $("drawer").dataset.open = String(open); + $("drawer").setAttribute("aria-hidden", String(!open)); + $("scrim").hidden = !open; + if (open) { loadDrawer(); loadShared(); loadMcp(); } +} +function loadDrawer(s = settings) { + for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking)); + $("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k; + $("s-max").value = s.max; $("s-seed").value = s.seed; + $("s-show").setAttribute("aria-checked", String(!!s.show)); + $("s-esp").setAttribute("aria-checked", String(s.esp !== false)); + $("esp-row").hidden = !projectionLoaded(); + $("s-mcp").setAttribute("aria-checked", String(s.mcp !== false)); + $("s-share").setAttribute("aria-checked", String(sharedOn)); + outputs(); +} +// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings) +let sharedOn = false; +async function loadShared() { + try { + const r = await fetch("settings", {headers: headers()}); + if (r.ok) sharedOn = !!(await r.json()).shared; + } catch (e) { /* an older server: the switch just stays off */ } + $("s-share").setAttribute("aria-checked", String(sharedOn)); +} +function sharedDefaults(s) { + const d = {reasoning_effort: s.thinking, temperature: +s.temperature}; + if (+s.temperature > 0) Object.assign(d, {top_p: +s.top_p, top_k: +s.top_k}); + if (s.seed) d.seed = +s.seed; + if (s.max) d.max_tokens = +s.max; + if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false; + return d; +} +async function saveShared(on, s) { + const r = await fetch("settings", {method: "POST", headers: headers(true), + body: JSON.stringify({defaults: on ? sharedDefaults(s) : null})}); + if (!r.ok) { + let msg = `HTTP ${r.status}`; + try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ } + throw new Error(msg); + } + sharedOn = !!(await r.json()).shared; +} +// the engine was started with the experimental-speed-projection control vector (INFO cvec=...) +function projectionLoaded() { + const c = lastMetrics && lastMetrics.engine ? lastMetrics.engine.cvec : 0; + return !!c && c !== "0"; +} +function outputs() { + const t = +$("s-temp").value; + $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2); + $("o-topp").textContent = (+$("s-topp").value).toFixed(2); + $("o-topk").textContent = $("s-topk").value; + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + $("o-thinking").textContent = sel ? {none: "answers right away", low: "short", medium: "medium", high: "thorough (default)"}[sel.dataset.v] : ""; + for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0; +} +for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); }; +for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs; +$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true")); +$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true")); +$("s-mcp").onclick = () => $("s-mcp").setAttribute("aria-checked", String($("s-mcp").getAttribute("aria-checked") !== "true")); +$("s-share").onclick = () => $("s-share").setAttribute("aria-checked", String($("s-share").getAttribute("aria-checked") !== "true")); +$("s-reset").onclick = () => loadDrawer(DEFAULTS); +$("s-apply").onclick = async () => { + const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true"); + settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value, + top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(), + show: $("s-show").getAttribute("aria-checked") === "true", + esp: $("s-esp").getAttribute("aria-checked") === "true", + mcp: $("s-mcp").getAttribute("aria-checked") === "true"}; + store.set("sampling", settings); + const share = $("s-share").getAttribute("aria-checked") === "true"; + openDrawer(false); + if (share || sharedOn) { + try { + await saveShared(share, settings); + toast("success", "Sampling saved", share ? "Other apps (omp, API clients) use these settings from their next request." + : "Other apps use their own settings again."); + } catch (e) { + toast("error", "Saved here, but not for other apps", e.message, 6000); + } + return; + } + toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : ""); +}; +$("sampling-btn").onclick = () => openDrawer(true); +$("drawer-close").onclick = () => openDrawer(false); +$("scrim").onclick = () => openDrawer(false); +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("drawer").dataset.open === "true") openDrawer(false); }); + +// ------------------------------------------------------------------ start +setBusy(false); +renderChat(); +const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut) +if (startQuestion) history.replaceState(null, "", location.pathname + location.hash); +loadHealth().then(loadMcp).then(() => { if (startQuestion) { $("input").value = startQuestion; send(); } }); +showTab(location.hash.slice(1) || "chat"); +poll(); diff --git a/engine/strata/serve/web/components.css b/engine/strata/serve/web/components.css new file mode 100644 index 00000000..899f5257 --- /dev/null +++ b/engine/strata/serve/web/components.css @@ -0,0 +1,128 @@ +/* Strata UI — components. Requires tokens.css. */ +*,*::before,*::after{box-sizing:border-box} +html,body{margin:0;background:var(--st-bg);color:var(--st-ink);font-family:var(--st-font);font-size:var(--st-fs-base);line-height:var(--st-lh-body);-webkit-font-smoothing:antialiased} +a{color:var(--st-accent-text);text-decoration:none} a:hover{text-decoration:underline} +:focus-visible{outline:2px solid var(--st-focus);outline-offset:2px} + +/* icon — */ +.st-icon{width:20px;height:20px;flex:none;color:inherit} +.st-icon--sm{width:16px;height:16px} .st-icon--lg{width:24px;height:24px} + +/* header */ +.st-header{display:flex;align-items:center;gap:var(--st-s-4);height:60px;padding:0 var(--st-s-6);background:var(--st-surface);border-bottom:1px solid var(--st-line)} +.st-header__brand{font-weight:900;font-size:var(--st-fs-lg);letter-spacing:-.01em} +.st-header__spacer{flex:1} + +/* status pill */ +.st-pill{display:inline-flex;align-items:center;gap:8px;height:30px;padding:0 12px;border-radius:var(--st-r-pill);border:1px solid var(--st-line);background:var(--st-surface-2);font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft);font-variant-numeric:tabular-nums} +.st-pill__dot{width:8px;height:8px;border-radius:50%;background:var(--st-ink-muted)} +.st-pill[data-state="generating"] .st-pill__dot{background:var(--st-accent);box-shadow:0 0 0 4px var(--st-accent-tint)} +.st-pill[data-state="reading"] .st-pill__dot{background:var(--st-info);box-shadow:0 0 0 4px var(--st-info-tint)} +.st-pill[data-state="queued"] .st-pill__dot{background:var(--st-warn)} + +/* tabs */ +.st-tabs{display:flex;gap:4px;padding:4px;background:var(--st-surface-2);border:1px solid var(--st-line);border-radius:var(--st-r-md)} +.st-tab{display:inline-flex;align-items:center;gap:8px;height:36px;padding:0 14px;border:0;border-radius:10px;background:transparent;color:var(--st-ink-muted);font:500 var(--st-fs-md)/1 var(--st-font);cursor:pointer} +.st-tab:hover{color:var(--st-ink)} +.st-tab[aria-selected="true"]{background:var(--st-surface);color:var(--st-ink);font-weight:700;box-shadow:var(--st-sh-card)} + +/* card + metric */ +.st-card{background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-card);padding:var(--st-s-5)} +.st-metric{display:flex;flex-direction:column;gap:10px} +.st-metric__label{display:flex;align-items:center;gap:8px;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-metric__value{font-weight:900;font-size:var(--st-fs-stat);line-height:1;letter-spacing:-.01em;font-variant-numeric:tabular-nums} +.st-metric__unit{font-weight:500;font-size:var(--st-fs-md);color:var(--st-ink-muted);margin-left:4px} +.st-metric__spark{width:100%;height:32px;color:var(--st-accent)} + +/* progress + gauge */ +.st-progress{height:8px;border-radius:var(--st-r-pill);background:var(--st-surface-2);border:1px solid var(--st-line-soft);overflow:hidden} +.st-progress__bar{height:100%;border-radius:inherit;background:var(--st-accent);transition:width var(--st-dur) var(--st-ease)} +.st-progress[data-tone="info"] .st-progress__bar{background:var(--st-info)} +.st-progress[data-tone="warn"] .st-progress__bar{background:var(--st-warn)} +.st-progress[data-tone="danger"] .st-progress__bar{background:var(--st-danger)} +/* gauge: see README for SVG markup (stroke-dasharray on a 270° arc) */ +.st-gauge{position:relative;width:120px;height:120px} +.st-gauge__track{stroke:var(--st-surface-2)} .st-gauge__fill{stroke:var(--st-accent)} + +/* table */ +.st-table{width:100%;border-collapse:collapse;font-size:var(--st-fs-md);font-variant-numeric:tabular-nums} +.st-table th{text-align:left;font-weight:500;font-size:var(--st-fs-xs);letter-spacing:.04em;text-transform:uppercase;color:var(--st-ink-muted);padding:10px 12px;border-bottom:1px solid var(--st-line)} +.st-table td{padding:12px;border-bottom:1px solid var(--st-line-soft);color:var(--st-ink-soft)} +.st-table tr:hover td{background:var(--st-surface-2)} +.st-table .num{text-align:right} + +/* badges */ +.st-badge{display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 10px;border-radius:var(--st-r-pill);font-size:var(--st-fs-xs);font-weight:700;background:var(--st-surface-2);color:var(--st-ink-muted);border:1px solid var(--st-line)} +.st-badge::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor} +.st-badge--reading{background:var(--st-info-tint);color:var(--st-info-text);border-color:transparent} +.st-badge--generating{background:var(--st-accent-tint);color:var(--st-accent-text);border-color:transparent} +.st-badge--queued{background:var(--st-warn-tint);color:var(--st-warn-text);border-color:transparent} +.st-badge--error{background:var(--st-danger-tint);color:var(--st-danger-text);border-color:transparent} + +/* chat */ +.st-msg{display:flex;flex-direction:column;gap:6px;max-width:720px} +.st-msg--user{align-self:flex-end;align-items:flex-end} +.st-bubble{padding:12px 16px;border-radius:var(--st-r-lg);font-size:var(--st-fs-base);line-height:1.55;color:var(--st-ink-soft)} +.st-msg--user .st-bubble{background:var(--st-accent);color:var(--st-accent-ink);border-bottom-right-radius:6px} +.st-msg--assistant .st-bubble{background:var(--st-surface);border:1px solid var(--st-line);border-bottom-left-radius:6px} +.st-msg__meta{font-size:var(--st-fs-xs);color:var(--st-ink-muted);display:flex;gap:8px;align-items:center} + +/* collapsible —
    …
    …
    */ +.st-collapse{border:1px solid var(--st-line);border-radius:var(--st-r-md);background:var(--st-surface-2)} +.st-collapse>summary{list-style:none;display:flex;align-items:center;gap:8px;padding:10px 14px;cursor:pointer;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-muted)} +.st-collapse>summary::-webkit-details-marker{display:none} +.st-collapse>summary .st-chev{margin-left:auto;transition:transform var(--st-dur) var(--st-ease)} +.st-collapse[open]>summary .st-chev{transform:rotate(180deg)} +.st-collapse__body{padding:0 14px 14px;font-size:var(--st-fs-sm);color:var(--st-ink-muted);line-height:1.6} + +/* code */ +.st-code{border-radius:var(--st-r-md);background:var(--st-code-bg);color:var(--st-code-ink);overflow:hidden} +.st-code__head{display:flex;align-items:center;justify-content:space-between;padding:8px 8px 8px 14px;font:500 var(--st-fs-xs)/1 var(--st-font);color:#9aa3ab;border-bottom:1px solid rgba(255,255,255,.06)} +.st-code pre{margin:0;padding:14px;overflow:auto;font:400 13px/1.6 var(--st-font-mono)} +.st-code .st-btn--icon{color:#9aa3ab} .st-code .st-btn--icon:hover{background:rgba(255,255,255,.08);color:#fff} + +/* composer */ +.st-composer{display:flex;flex-direction:column;gap:8px;padding:10px;background:var(--st-surface);border:1px solid var(--st-line);border-radius:var(--st-r-lg);box-shadow:var(--st-sh-bar)} +.st-composer:focus-within{border-color:var(--st-focus)} +.st-composer textarea{border:0;outline:0;resize:none;background:transparent;color:var(--st-ink);font:400 var(--st-fs-base)/1.5 var(--st-font);padding:6px 8px;min-height:48px} +.st-composer__bar{display:flex;align-items:center;gap:6px} +.st-composer__bar .spacer{flex:1} + +/* drawer */ +.st-drawer{position:fixed;top:0;right:0;bottom:0;width:360px;max-width:100vw;background:var(--st-surface);border-left:1px solid var(--st-line);box-shadow:var(--st-sh-pop);display:flex;flex-direction:column;transform:translateX(100%);transition:transform 220ms var(--st-ease)} +.st-drawer[data-open="true"]{transform:none} +.st-drawer__head{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--st-line)} +.st-drawer__body{padding:20px;display:flex;flex-direction:column;gap:22px;overflow:auto} + +/* buttons */ +.st-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:42px;padding:0 18px;border-radius:var(--st-r-md);border:0;font:700 var(--st-fs-md)/1 var(--st-font);cursor:pointer;transition:background var(--st-dur),transform 120ms} +.st-btn:active{transform:translateY(1px)} +.st-btn--primary{background:var(--st-accent);color:var(--st-accent-ink);box-shadow:0 6px 16px rgba(16,185,129,.24),inset 0 1px 0 rgba(255,255,255,.18)} +.st-btn--primary:hover{background:var(--st-accent-hover)} +.st-btn--secondary{background:transparent;color:var(--st-ink);border:1.5px solid var(--st-line)} +.st-btn--secondary:hover{background:var(--st-surface-2)} +.st-btn--danger{background:var(--st-danger-tint);color:var(--st-danger-text)} +.st-btn--icon{width:36px;height:36px;padding:0;border-radius:10px;background:transparent;color:var(--st-ink-muted)} +.st-btn--icon:hover{background:var(--st-surface-2);color:var(--st-ink)} +.st-btn:disabled{opacity:.45;cursor:not-allowed} + +/* form controls */ +.st-field{display:flex;flex-direction:column;gap:8px} +.st-label{display:flex;justify-content:space-between;font-size:var(--st-fs-sm);font-weight:500;color:var(--st-ink-soft)} +.st-label output{font-variant-numeric:tabular-nums;color:var(--st-ink-muted)} +.st-input{height:44px;padding:0 14px;border-radius:var(--st-r-md);border:1.5px solid var(--st-line);background:var(--st-surface);color:var(--st-ink);font:400 var(--st-fs-md) var(--st-font)} +.st-input:focus{outline:0;border-color:var(--st-focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--st-focus) 20%,transparent)} +.st-slider{width:100%;accent-color:var(--st-accent)} +.st-toggle{position:relative;width:40px;height:24px;border-radius:var(--st-r-pill);border:0;background:var(--st-line);cursor:pointer;transition:background var(--st-dur)} +.st-toggle::after{content:"";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.2);transition:transform var(--st-dur) var(--st-ease)} +.st-toggle[aria-checked="true"]{background:var(--st-accent)} +.st-toggle[aria-checked="true"]::after{transform:translateX(16px)} + +/* toast / alert */ +.st-toast{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-radius:var(--st-r-md);background:var(--st-surface);border:1px solid var(--st-line);box-shadow:var(--st-sh-pop);font-size:var(--st-fs-md);color:var(--st-ink-soft);max-width:420px} +.st-toast__title{font-weight:700;color:var(--st-ink)} +.st-toast--info .st-icon{color:var(--st-info)} +.st-toast--success .st-icon{color:var(--st-accent)} +.st-toast--warn .st-icon{color:var(--st-warn)} +.st-toast--error .st-icon{color:var(--st-danger)} +.st-toasts{position:fixed;right:20px;bottom:20px;display:flex;flex-direction:column;gap:10px;z-index:50} diff --git a/engine/strata/serve/web/fonts/OFL.txt b/engine/strata/serve/web/fonts/OFL.txt new file mode 100644 index 00000000..723cd447 --- /dev/null +++ b/engine/strata/serve/web/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/engine/strata/serve/web/fonts/outfit-latin-ext-wght.woff2 b/engine/strata/serve/web/fonts/outfit-latin-ext-wght.woff2 new file mode 100644 index 00000000..c54ceec8 Binary files /dev/null and b/engine/strata/serve/web/fonts/outfit-latin-ext-wght.woff2 differ diff --git a/engine/strata/serve/web/fonts/outfit-latin-wght.woff2 b/engine/strata/serve/web/fonts/outfit-latin-wght.woff2 new file mode 100644 index 00000000..85e3332e Binary files /dev/null and b/engine/strata/serve/web/fonts/outfit-latin-wght.woff2 differ diff --git a/engine/strata/serve/web/index.html b/engine/strata/serve/web/index.html new file mode 100644 index 00000000..d858d2f0 --- /dev/null +++ b/engine/strata/serve/web/index.html @@ -0,0 +1,223 @@ + + + + + +Strata + + + + + + +
    + Strata + + + + Connecting… + +
    + +
    + +
    +
    +
    +
    +
    Ask anything
    +
    The model runs on this PC. Nothing leaves it.
    +
    +
    +
    +
    +
    + + +
    + + + + + + + + + +
    +
    +
    +
    + + + + + + +
    + + + + +
    + + + diff --git a/engine/strata/serve/web/monitor.html b/engine/strata/serve/web/monitor.html new file mode 100644 index 00000000..b05b29f8 --- /dev/null +++ b/engine/strata/serve/web/monitor.html @@ -0,0 +1,37 @@ + + + + +Strata API Monitor + + + + + +
    Strata Local inference
    +
    +

    API Monitor

    Model status and every request, in one place.

    + + +
    +
    Model
    Connecting…
    127.0.0.1:5001/v1
    +
    Requests retained
    —
    Waiting for server
    +
    Last wall-clock
    —
    Includes queue and model loading
    +
    Last decode speed
    —
    Engine timing · tokens / second
    +
    +

    Requests

    +
    +
    Inspect a requestSelect a request to see its input, output, and timings.
    + +
    +
    Last 100 requests kept in memory until restart. Inputs and outputs stay on this machine.Connecting…
    +
    + diff --git a/engine/strata/serve/web/monitor.js b/engine/strata/serve/web/monitor.js new file mode 100644 index 00000000..5543b94b --- /dev/null +++ b/engine/strata/serve/web/monitor.js @@ -0,0 +1,111 @@ +"use strict"; +const $ = id => document.getElementById(id); +let selected = null, detail = null, pane = "input", records = [], state = null, operating = false, stamp = "", actionError = ""; +let apiKey = sessionStorage.getItem("strata.monitor.key") || ""; +document.documentElement.dataset.theme = localStorage.getItem("strata.theme") || "dark"; +const seconds = n => typeof n === "number" ? `${n.toFixed(2)} s` : "—"; +const speed = n => typeof n === "number" ? n.toFixed(1) : "—"; +const active = r => !["completed", "error", "disconnected"].includes(r.state); +function text(id, value) { const el = $(id); if (el.textContent !== String(value)) el.textContent = value; } +async function api(path, body) { + const response = await fetch(path, {cache:"no-store", headers:{...(apiKey ? {Authorization:`Bearer ${apiKey}`} : {}), ...(body !== undefined ? {"Content-Type":"application/json"} : {})}, ...(body !== undefined ? {method:"POST", body:JSON.stringify(body)} : {})}); + const value = await response.json(); + if (!response.ok) { + if (response.status === 401) $("auth").hidden = false; + throw new Error(value.error?.message || `HTTP ${response.status}`); + } + return value; +} +function notice(message) { $("error").hidden = !message; text("error", message || ""); } +function list() { + const query = $("search").value.toLowerCase(), filter = $("filter").value; + const visible = records.filter(r => `${r.id} ${r.path} ${r.model}`.toLowerCase().includes(query) && (filter === "all" || (filter === "active" ? active(r) : r.state === filter))); + const nextStamp = JSON.stringify([visible, selected]); + if (stamp === nextStamp) return; + stamp = nextStamp; + const focusId = document.activeElement?.dataset.request; + $("requests").replaceChildren(); + if (!visible.length) { + const empty = document.createElement("div"); empty.className = "empty"; + empty.textContent = records.length ? "No matching requests." : "No requests yet. API calls will appear here automatically."; + $("requests").append(empty); + } + for (const r of visible) { + const button = document.createElement("button"); button.className = `request${selected === r.id ? " selected" : ""}`; + button.dataset.request = r.id; button.setAttribute("aria-label", `Request ${r.id}`); button.setAttribute("aria-pressed", String(selected === r.id)); + const row = document.createElement("div"); row.className = "row"; + const time = document.createElement("span"); time.textContent = new Date(r.started_at * 1000).toLocaleTimeString(); + const tag = document.createElement("span"); tag.className = `tag ${r.state}`; tag.textContent = r.state; + row.append(time, tag); + const endpoint = document.createElement("div"); endpoint.className = "endpoint"; endpoint.textContent = `POST ${r.path}`; + const meta = document.createElement("div"); meta.className = "small"; + meta.textContent = `${r.id} · ${seconds(r.wallclock_s)} · ${r.stream ? "stream" : "JSON response"}${r.http_status ? ` · HTTP ${r.http_status}` : ""}`; + button.append(row, endpoint, meta); + button.onclick = async () => { selected = r.id; detail = null; list(); await showDetail(); }; + $("requests").append(button); + if (focusId === r.id) button.focus({preventScroll:true}); + } +} +function content() { + if (!detail) return; + let value = detail[pane] || (pane === "response" && detail.stream ? "Streaming response: see Output and the request error, if any." : "No content."); + if (pane === "output") { try { value = JSON.stringify(JSON.parse(value), null, 2); } catch (_) {} } + text("content", value); + const note = pane === "output" && detail.error ? "Raw model output retained for diagnosis. The API returned an error." : pane === "input" ? "Original request body." : pane === "output" ? "Model answer. JSON is formatted here for readability." : pane === "reasoning" ? "Separate reasoning content, when enabled." : "API response body."; + text("content-note", note + (detail[`${pane}_truncated`] ? " Monitor capture truncated at 256K characters; the API response was not shortened." : "")); +} +async function showDetail() { + if (!selected) return; + const id = selected; + const value = await api(`/api/requests?id=${encodeURIComponent(id)}`); + if (selected !== id) return; + detail = value; $("selection").hidden = false; $("no-selection").hidden = true; + text("detail-title", `${value.id} · ${value.path}`); + text("detail-status", value.state); $("detail-status").className = `tag ${value.state}`; + text("detail-time", new Date(value.started_at * 1000).toLocaleString()); + text("detail-wall", seconds(value.wallclock_s ?? ((Date.now() / 1000) - value.started_at))); + text("detail-load", seconds(value.load_s)); text("detail-queue", seconds(value.queue_s)); text("detail-first", seconds(value.first_token_s)); + text("detail-prompt", value.usage?.prompt_tokens ?? value.usage?.input_tokens ?? "—"); + text("detail-tokens", value.usage?.completion_tokens ?? value.usage?.output_tokens ?? "—"); + text("detail-speed", speed(value.timings?.predicted_per_second)); text("detail-format", value.response_format || "text"); + $("detail-error").hidden = !value.error; text("detail-error", value.error?.message || ""); content(); +} +async function refresh() { + try { + const [status, history] = await Promise.all([api("/v1/status"), api("/api/requests")]); + state = status; records = history.requests; + status.loaded = history.loaded; status.auto_load = history.auto_load; + if (selected && !records.some(r => r.id === selected)) { + selected = detail = null; $("selection").hidden = true; $("no-selection").hidden = false; + } + const inflight = Math.max(status.activity.in_flight, records.filter(active).length); + const loading = records.some(r => r.state === "loading"); + text("loaded", loading ? "Loading…" : inflight ? "In use" : status.loaded ? "Loaded" : "Unloaded"); + $("model-state").className = `value ${inflight || loading ? "busy" : status.loaded ? "loaded" : ""}`; + text("model", status.model); text("count", records.length); + text("active", inflight ? `${inflight} active / queued` : status.auto_load ? "Loads automatically on the next request" : "No active requests"); + const last = records.find(r => !active(r)); + text("wall", last ? seconds(last.wallclock_s) : "—"); text("speed", speed(last?.timings?.predicted_per_second)); + $("load").disabled = operating || Boolean(inflight) || status.loaded; $("unload").disabled = operating || Boolean(inflight) || !status.loaded; + list(); if (selected) await showDetail(); + text("updated", `Live · updated ${new Date().toLocaleTimeString()}`); + if (!operating) notice(actionError); + } catch (error) { notice(error.message); text("updated", "Disconnected · retrying"); $("load").disabled = $("unload").disabled = true; } +} +async function control(load) { + actionError = ""; + operating = true; $("load").disabled = $("unload").disabled = true; + text("loaded", load ? "Loading…" : "Unloading…"); + try { await api(load ? "/load" : "/unload", {}); notice(""); } + catch (error) { actionError = error.message; notice(actionError); } + finally { operating = false; await refresh(); } +} +$("load").onclick = () => control(true); $("unload").onclick = () => control(false); +$("key").onclick = () => { $("auth").hidden = !$("auth").hidden; if (!$("auth").hidden) $("api-key").focus(); }; +$("auth").onsubmit = async event => { event.preventDefault(); apiKey = $("api-key").value.trim(); sessionStorage.setItem("strata.monitor.key", apiKey); $("auth").hidden = true; await refresh(); }; +$("theme").onclick = () => { const theme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = theme; localStorage.setItem("strata.theme", theme); }; +$("search").oninput = list; $("filter").onchange = list; +document.querySelectorAll("[data-pane]").forEach(button => { button.onclick = () => { pane = button.dataset.pane; document.querySelectorAll("[data-pane]").forEach(b => b.setAttribute("aria-selected", String(b === button))); content(); }; }); +$("copy").onclick = async () => { try { await navigator.clipboard.writeText($("content").textContent); text("copy", "Copied"); setTimeout(() => text("copy", "Copy"), 1500); } catch (_) { notice("Clipboard unavailable; select the text to copy it."); } }; +async function poll() { await refresh(); setTimeout(poll, 2000); } +poll(); diff --git a/engine/strata/serve/web/sprite.svg b/engine/strata/serve/web/sprite.svg new file mode 100644 index 00000000..598f6234 --- /dev/null +++ b/engine/strata/serve/web/sprite.svg @@ -0,0 +1,34 @@ +AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToyMjRkYzc2Ny1hNTJmLTRhNTgtYmRhNi0wNjNjZjgxZDE0ZDkAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaFpCcvmnJ1xuOVFbOGxO7IQAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDpjZTVmMTYyMy1hMGY4LTRjNDgtYmQ1MC0yOGRhYTVkZGQ3OWZscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNohRiWe4A1zTyq58r9HwVbdgAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggvnkoUEWEbTHaYh6o+DzKs/DGvSaEkSiXbTkyg+EGZBWkZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaPM+mDLLCljfKcnx6K3jLsYAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCDyyT5tVoB8Cn5pGifFieqsDs7yYczybQ255HiPUQvocGRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh8Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjIyNGRjNzY3LWE1MmYtNGE1OC1iZGE2LTA2M2NmODFkMTRkOS9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjYxMTcxNDYxLWZjODUtNDNkYi05NzdkLTVhNTQ0NWMwNzY0OXJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCC+eShQRYRtMdpiHqj4PMqz8Ma9JoSRKJdtOTKD4QZkFaJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggzN40WhHml0Alrpq9IN+inEViO5AnmGuZkyahASHk13qiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFgg1QfqlfahOW+5OQ+LKm+K4e2m36U3CKHsYWKitMx8+Mt0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQAWvLruRfR0RxgkmvmgF8qVD0dQ7tTCsSMumVT6Kz8rMYbOspIf18RMz8a0P6WmnC265RomT3B4qAIos8XVuMBY= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/engine/strata/serve/web/tokens.css b/engine/strata/serve/web/tokens.css new file mode 100644 index 00000000..220cf421 --- /dev/null +++ b/engine/strata/serve/web/tokens.css @@ -0,0 +1,87 @@ +/* Strata UI — tokens. Derived from the Gainsty design system. + Light is default; dark via . + Values marked (derived) are not in the Gainsty source and were added for the app. */ + +/* Outfit (SIL Open Font License 1.1, serve/web/fonts/OFL.txt): one variable font, weights 100-900 */ +@font-face{font-family:"Outfit";src:url("../fonts/outfit-latin-wght.woff2") format("woff2-variations");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD} +@font-face{font-family:"Outfit";src:url("../fonts/outfit-latin-ext-wght.woff2") format("woff2-variations");font-weight:100 900;font-display:swap;unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF} + +:root{ + /* type */ + --st-font:"Outfit",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; + --st-font-mono:ui-monospace,"SF Mono","Cascadia Code",Consolas,"Liberation Mono",monospace; /* (derived) */ + --st-fs-xs:12px; --st-fs-sm:13px; --st-fs-md:14px; --st-fs-base:16px; + --st-fs-lg:18px; --st-fs-xl:24px; --st-fs-stat:32px; --st-fs-display:40px; + --st-fw-regular:400; --st-fw-medium:500; --st-fw-bold:700; --st-fw-black:900; + --st-lh-tight:1.1; --st-lh-body:1.55; + + /* spacing (4pt) */ + --st-s-1:4px; --st-s-2:8px; --st-s-3:12px; --st-s-4:16px; --st-s-5:20px; + --st-s-6:24px; --st-s-8:32px; --st-s-10:40px; --st-s-12:48px; --st-s-16:64px; + + /* radius */ + --st-r-sm:8px; --st-r-md:14px; --st-r-lg:20px; --st-r-xl:24px; --st-r-pill:9999px; + + /* motion (derived) */ + --st-ease:cubic-bezier(.2,.7,.2,1); --st-dur:160ms; + + /* color — light */ + --st-bg:#f9fafb; + --st-surface:#ffffff; + --st-surface-2:#f7f7f7; + --st-line:#dee5ee; + --st-line-soft:#eeeeee; + --st-ink:#221e1f; + --st-ink-soft:#303030; + --st-ink-muted:#6f6f6f; /* Gainsty #7a7a7a darkened slightly for 4.5:1 on white */ + --st-icon:#2F384C; /* Anron default */ + + --st-accent:#10b981; + --st-accent-hover:#0c8a60; + --st-accent-ink:#ffffff; + --st-accent-tint:#ecfdf5; + --st-accent-text:#0c8a60; /* accent used as text on light */ + --st-focus:#405de6; + + --st-info:#0f97ff; --st-info-tint:#e8f4ff; --st-info-text:#0668c2; + --st-warn:#e39b0b; --st-warn-tint:#fff6e0; --st-warn-text:#8a5a00; /* (derived) */ + --st-danger:#e0283f; --st-danger-tint:#fdecee; --st-danger-text:#b01a2e; /* (derived) */ + + --st-code-bg:#1b1f23; --st-code-ink:#e6e9ec; /* code blocks stay dark in both themes (derived) */ + + --st-sh-card:0 18px 7px rgba(0,0,0,.01),0 10px 6px rgba(0,0,0,.02),0 4px 4px rgba(0,0,0,.03),0 1px 2px rgba(0,0,0,.04); + --st-sh-bar:0 54px 21px rgba(0,0,0,.01),0 30px 18px rgba(0,0,0,.03),0 13px 13px rgba(0,0,0,.05),0 3px 7px rgba(0,0,0,.06); + --st-sh-pop:0 10px 40px rgba(15,23,42,.08),0 1px 3px rgba(15,23,42,.06); + color-scheme:light; +} + +/* color — dark (all derived) */ +[data-theme="dark"]{ + --st-bg:#0e1113; + --st-surface:#161a1d; + --st-surface-2:#1d2226; + --st-line:#2a3036; + --st-line-soft:#22272c; + --st-ink:#eef1f3; + --st-ink-soft:#c7cdd3; + --st-ink-muted:#8e979f; + --st-icon:#c7cdd3; + + --st-accent:#34d399; + --st-accent-hover:#4ade80; + --st-accent-ink:#052e20; + --st-accent-tint:rgba(52,211,153,.12); + --st-accent-text:#4ade80; + --st-focus:#7b93ff; + + --st-info:#3aa9ff; --st-info-tint:rgba(58,169,255,.12); --st-info-text:#7cc4ff; + --st-warn:#f5b53d; --st-warn-tint:rgba(245,181,61,.12); --st-warn-text:#f8c96a; + --st-danger:#ff5a6e; --st-danger-tint:rgba(255,90,110,.12);--st-danger-text:#ff8a98; + + --st-code-bg:#0a0c0e; --st-code-ink:#e6e9ec; + + --st-sh-card:0 1px 2px rgba(0,0,0,.4); + --st-sh-bar:0 12px 32px rgba(0,0,0,.45),0 2px 6px rgba(0,0,0,.35); + --st-sh-pop:0 16px 48px rgba(0,0,0,.55),0 1px 3px rgba(0,0,0,.4); + color-scheme:dark; +} diff --git a/engine/strata/serve/winjob.py b/engine/strata/serve/winjob.py new file mode 100644 index 00000000..008642a0 --- /dev/null +++ b/engine/strata/serve/winjob.py @@ -0,0 +1,74 @@ +"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime. + +Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine, +the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that +is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS +closes however the server ends. Processes the child starts later join the same job. The server itself stays out of +the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op. +""" +from __future__ import annotations + +import os +import threading + +_job = None +_lock = threading.Lock() + +if os.name == "nt": + import ctypes + from ctypes import wintypes + + _k32 = ctypes.WinDLL("kernel32", use_last_error=True) + + class _IoCounters(ctypes.Structure): + _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount", + "OtherOperationCount", "ReadTransferCount", + "WriteTransferCount", "OtherTransferCount")] + + class _BasicLimits(ctypes.Structure): + _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong), + ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD)] + + class _ExtendedLimits(ctypes.Structure): + _fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters), + ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] + + _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 + _JobObjectExtendedLimitInformation = 9 + + _k32.CreateJobObjectW.restype = wintypes.HANDLE + _k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR) + _k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) + _k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) + + def _make_job(): + job = _k32.CreateJobObjectW(None, None) # no security attributes: the handle is not inherited + if not job: + return None + info = _ExtendedLimits() + info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info), + ctypes.sizeof(info)): + _k32.CloseHandle(job) + return None + return job + + +def contain(proc) -> bool: + """Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise.""" + global _job + if os.name != "nt" or proc is None: + return False + with _lock: + if _job is None: + _job = _make_job() or 0 + if not _job: + return False + try: + return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle))) + except (AttributeError, OSError, ValueError): + return False diff --git a/engine/strata/setup.py b/engine/strata/setup.py new file mode 100644 index 00000000..d91900b3 --- /dev/null +++ b/engine/strata/setup.py @@ -0,0 +1,3416 @@ +#!/usr/bin/env python3 +"""Strata one-click setup and start (Windows and Linux, NVIDIA or AMD GPUs). + + START-HERE.bat (Windows) / ./setup.sh (Linux) - they install Python if needed and run this file + +The first time it asks four questions - which model (the original Qwen3.8-Flash-Next or the Swift 1.5 fine-tune), +which size, how much context, and whether the model should also read images - then installs everything and starts the model on http://127.0.0.1:8080 (OpenAI- and Anthropic-compatible +API; a small page there shows that it runs). Every later start skips straight to running the model: nothing that +is already downloaded, installed or prepared is done again. + +What the first run does (each step is skipped when it is already done): + + 1. checks your PC: NVIDIA or AMD GPU and driver, RAM, CPU, free disk space + 2. asks the questions + 3. installs the Python packages it needs into .venv (numpy, jinja2, ..., and NVIDIA's CUDA libraries) + 4. gets the Strata engine: a ready-made build for RTX 20/30/40/50 cards (no compiler needed); if none fits your PC, + it installs the build tools (asks first) and compiles the engine for your GPU. AMD (--backend hip, chosen by + itself on a PC with no usable NVIDIA card): the ready-made HIP engine on Windows, compiled here on Linux + 5. downloads the model from Hugging Face (resumable), and the vision encoder if you want images + 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) + 7. writes run-.bat / run-.sh and starts the model + +Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn +(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, +at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port +8080, --yes (recommended +answers, no questions), --setup (install another model / change settings instead of starting), --no-start, +--host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off +(EXPERIMENTAL, off by default), +--models-dir DIR, --gguf-dir DIR (use GGUF files you already have), --build (compile instead of the ready-made +engine), --check (only check this PC), --resident-budget-gib N (UD-Q4_K_XL's experts in RAM), --kv-streaming +on|off|auto. + +Setup recommends, it never forces: the recommended answers are the defaults (--yes, or Enter), and a bigger choice +than it recommends - a longer context, more GPUs, a bigger RAM budget, a size it thinks will not fit - is kept, with +what it risks. With --yes, an explicit flag (--model, --gpus, ...) is the consent to a risk setup would otherwise +stop at; --yes alone is not. +""" +from __future__ import annotations + +import argparse +import ctypes +import hashlib +import json +import math +import os +import platform +import re +import shutil +import struct +import subprocess +import sys +import time +import urllib.error +import urllib.request +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +WIN = os.name == "nt" +# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of +# https://huggingface.co/api/models/ when this was pinned), so a checkout installs the same files on any +# day. A revision the repository no longer has falls back to its current files, with a message (download()). +HF_REVISIONS = { + "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", # 2026-09-29 + "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF": "b22d729eae29b5796f76fb70f91aef549b9fc52c", # 2026-09-24 + "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF": "5348543e0147355ac9cbcb031184a3546350988e", # 2026-09-29 + "unsloth/Qwen3.8-Flash-Next-GGUF": "38bb39ee97821de2c9009abb7e93950eec396e66", # 2026-09-30 +} + + +def hf(repo: str) -> str: + """The download folder of a Hugging Face repository at its pinned revision.""" + return f"https://huggingface.co/{repo}/resolve/{HF_REVISIONS[repo]}/" + + +def hf_unpinned(url: str) -> str: + """The same file at the repository's current revision (main).""" + return re.sub(r"(https://huggingface\.co/.+?/resolve/)[0-9a-f]{40}/", r"\1main/", url, count=1) + + +HF = hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") +LLAMA_CPP_COMMIT = "3cf03257f219afbe7334045ff7c6a06ac68c627d" +LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{LLAMA_CPP_COMMIT}.zip" + +# The ready-made engine: , a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built +# by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g. +# "https://github.com//Strata/releases/latest/download/" (or pass --prebuilt / set STRATA_PREBUILT_URL). +# With the default, the release of this checkout's own version (PREBUILT_TAG_URL, CMakeLists.txt's version) is +# tried first and the latest release is the fallback (#214): an older checkout keeps the engine it shipped with. +PREBUILT_URL = "https://github.com/Niko1221/Strata/releases/latest/download/" +PREBUILT_TAG_URL = "https://github.com/Niko1221/Strata/releases/download/v{version}/" +PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip" +# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages +CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"] +MIN_DRIVER = 580 # CUDA 13.0 +MIN_ENGINE = (0, 1, 35) # v0.1.35: Windows AMD uses its bundled HIP runtime (#468 #461), the low-RAM resident mode on Windows 32 GB (#467), fixes #460 #459 #446 #447 #457 #448 #444; v0.1.34: AMD on Windows (a ready-made HIP engine), an MCP server for AI assistants (tools/strata_mcp.py), a shorter README; v0.1.33: a portable image encoder again (#411 #412), setup recommends instead of forcing (#406 #403 #364 #384), fixes #352 #365 #369 #371 #375 #393 #408 #414; v0.1.32: split prompts faster (#340), AMD router +12%, Unsloth Q4 in setup, faster Q4 prompts, #326/#327/#342/#344 fixes, PR batch; v0.1.31: Unsloth UD-Q4_K_XL (experimental), GGUF-in-place low-RAM mode, Windows GGUF load 2x, server race + tokenizer fixes, AMD intrinsics; v0.1.30: short prompts faster (streaming from 1024 tokens), resident low-RAM variant, multi-GPU session carve, RDNA4; v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties +PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"] +REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214) + +MODELS = { + # the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which + # the pack tool (tools/iq_pack.py) cannot prepare yet (#171) + "Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)}, + "IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48, + "arena_gb": 35.5}, + "IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8, + "ram_gb": 60, "arena_gb": 42.9}, + # the original model only (Swift 1.5 has no IQ3_S): matches the full BF16 model on the published benchmarks + "IQ3_S": {"about": "3.5-bit i-quant, the best quality (matches the full model), the slowest; needs a 64 GB PC " + "with little else running", "download_gb": 83.6, "ram_gb": 62, "arena_gb": 50.3, + "families": ("qwen",)}, + # the Coder release: 256 of the 512 experts kept (the ones code, tools and vision use), IQ2_S-IQ4_XS like IQ3_S + "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, + "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, + # EXPERIMENTAL (docs/UNSLOTH_Q4.md): Unsloth's 4-bit file; its 77 GB of experts do not fit a 64 GB PC, so the engine + # keeps a RAM budget of them (--resident-budget-gib, chosen below) and reads the rest from the GGUF on the SSD + "UD-Q4_K_XL": {"about": "4-bit (Unsloth Dynamic), EXPERIMENTAL: the best quality, but most experts come from the " + "SSD on a 64 GB PC (7-8.5 tokens/s measured)", "download_gb": 111.3, "ram_gb": 48, + "arena_gb": 77.0, "families": ("unsloth",), "budget": True}, +} +# The experimental Unsloth file's four shards at the pinned revision: name -> (bytes, sha256), checked after the +# download (setup trusts no other model file by name and size alone either: check_shards reads their directories). +UNSLOTH_SHARDS = { + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf": + (10946624, "4448186216b3af4cc558bbce2c3213f01608f8f8b2e5267a9767971dd3ec8082"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf": + (49859583136, "3f342f1c1580473f1ee94ddd5b28206e8c07a70fa1a366f59d1d6c922919a6c9"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf": + (49376141504, "56758f40269cad5cd9b0d3d6fbae0f40f6d5be6de49e4ab392dbe83157d9cbd3"), + "Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf": + (12087983520, "753bda48b98ba4f1636134a90a967de1b2d3908a236c026e464777342e53510a"), +} +UNSLOTH_ENGINE = (0, 1, 32) # the first engine setup configures for UD-Q4_K_XL (0.1.31 ran it by hand) +UNSLOTH_RAM_LEFT_GB = 24 # RAM beside the budget: the OS, the engine, and the file cache the rest is read through +# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will +# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor +# from the final context (final / 262144, at least 1) itself (below), keeps an explicit +# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past +# the trained range are out of spec. +CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] +# The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. +FAMILIES = { + "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", + "about": "the original model", + "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next"}, + "swift": {"title": "Swift 1.5", "by": "UkisAI's fine-tune of Qwen3.8-Flash-Next", + "about": "thinks much shorter (-63% thinking tokens, 1.8x sooner answers by its authors' numbers)", + "hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "file": "Swift-Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "swift-", + "mmproj_hf": hf("ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf", "name": "swift-1.5", + "license": "Swift Open License 1.0: https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"}, + # ISTA-DASLab's expert-pruned release: half of each layer's experts removed, chosen for code, agentic tool use and + # vision; its shard 2 (the n-gram table) and vision encoder are the original's files, shared with it + "coder": {"title": "Qwen3.8-Flash-Next Coder", "by": "ISTA-DASLab's coding version", + "about": "half the experts (code, tools, images kept): needs ~32 GB of RAM, faster; weaker outside coding", + "hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-GSQ-RCO-{q}-0000{i}-of-00002.gguf", "tag": "coder-", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-coder", + "profile": "expert-profile-coder.bin"}, + # EXPERIMENTAL: Unsloth's UD-Q4_K_XL of the original model (docs/UNSLOTH_Q4.md): four shards, no images yet + "unsloth": {"title": "Qwen3.8-Flash-Next (Unsloth)", "by": "Unsloth's 4-bit quantization (EXPERIMENTAL)", + "about": "4-bit, 111 GB download, most experts read from the SSD: slow (7-8.5 tokens/s on a 64 GB PC)", + "hf": hf("unsloth/Qwen3.8-Flash-Next-GGUF") + "{q}/", + "file": "Qwen3.8-Flash-Next-{q}-0000{i}-of-00004.gguf", "shards": 4, "tag": "unsloth-", + "mmproj_hf": hf("ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), + "mmproj": "mmproj-Qwen3.8-Flash-Next-BF16.gguf", "name": "qwen3.8-flash-next-unsloth", + "experimental": True, "vision": False, "pack_args": ["--compat-bf16"], "sha256": UNSLOTH_SHARDS}, +} +MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" +# EXPERIMENTAL, off by default (setup asks): a control vector shipped with the repository, see its README +ESP_VECTOR = ROOT / "data" / "experimental-speed-projection" / "Qwen3.8-Flash-Next-experimental-speed-projection.gguf" +# the image encoder on the GPU (~1.2 GB at 1024 image tokens) warms up before the engine starts, so the engine +# sizes its expert slots around it and the default reserve (700 MiB) is enough; engines before 0.1.2 need more +VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, + "cpu": {"max_tokens": 300, "reserve_mib": 700}} +EXE = "strata.exe" if WIN else "strata" +VEXE = "strata-vision.exe" if WIN else "strata-vision" + + +# ------------------------------------------------------------------------------------------------ output +def say(msg=""): + print(msg, flush=True) + + +def step(n, title): + say() + say(f"=== Step {n}: {title} ===") + + +def ok(msg): + say(f" [ok] {msg}") + + +def warn(msg): + say(f" [!] {msg}") + + +def fail(msg, hint=None): + say(f"\n [X] {msg}") + if hint: + say(f" {hint}") + say("\nSetup stopped. Fix the item above and run it again - everything already done is kept and skipped.") + sys.exit(1) + + +def ask(question, choices, default, yes): + if yes: + return default + while True: + try: + a = input(f"{question} [{default}]: ").strip() + except EOFError: + fail("input ended before a setup answer was received", + "run setup in a terminal, or pass --yes to accept the recommended answers") + if not a: + return default + if a.lower() in [c.lower() for c in choices]: + return next(c for c in choices if c.lower() == a.lower()) + say(f" please answer one of: {', '.join(choices)}") + + +def run(cmd, cwd=None, env=None, check=True, quiet=False): + say(" > " + " ".join(str(c) for c in cmd)) + r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env, + stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None, + text=True) + if check and r.returncode != 0: + if quiet and r.stdout: + say(r.stdout[-4000:]) + fail(f"command failed (exit {r.returncode}): {Path(str(cmd[0])).name}") + return r + + +def out(cmd): + try: + return subprocess.run(cmd, capture_output=True, text=True, timeout=60).stdout + except (OSError, subprocess.TimeoutExpired): + return "" + + +def done(path: Path) -> bool: + """A step's finish mark: .done exists (written only after the step completed).""" + return path.with_name(path.name + ".done").exists() + + +def mark(path: Path, text=""): + path.with_name(path.name + ".done").write_text(text or time.strftime("%Y-%m-%d %H:%M"), encoding="utf-8") + + +# ------------------------------------------------------------------------------------------------ the PC +def _memory_status(): + """Windows' GlobalMemoryStatusEx: RAM, and the commit limit (ullTotalPageFile = RAM + page file).""" + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(MS) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) + return m + + +def ram_gb(): + if WIN: + return _memory_status().ullTotalPhys / 2**30 + for line in open("/proc/meminfo"): + if line.startswith("MemTotal"): + return int(line.split()[1]) * 1024 / 2**30 + return 0.0 + + +def page_file_gb(): + """The page file's current size (GB) on Windows, None elsewhere. The graphics card's memory needs room there + too: under Windows' driver model every allocation on the card is also charged to the commit (RAM + page file), + so with the page file off or tiny the engine cannot use the free VRAM (issue #60).""" + if not WIN: + return None + m = _memory_status() + return max(0.0, (m.ullTotalPageFile - m.ullTotalPhys) / 2**30) + + +def cpu_info(): + """(name, avx2, avx512): avx512 means everything Strata's fast AVX-512 kernels use (F, BW, VL, VNNI, VBMI), + the same test the engine makes (cpu_avx512_ok), not just AVX-512F.""" + name, avx2, avx512 = platform.processor() or "unknown CPU", False, False + if WIN: + pf = ctypes.windll.kernel32.IsProcessorFeaturePresent + avx2 = bool(pf(40)) or _cpuid_avx2() # PF_AVX2_INSTRUCTIONS_AVAILABLE, else the CPU itself (#159) + n = out(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor).Name"]).strip() + name = n or name + avx512 = bool(pf(41)) and _cpuid_avx512_full() + else: + try: + txt = open("/proc/cpuinfo").read() + flags = set(re.search(r"^flags\s*:\s*(.*)$", txt, re.M).group(1).split()) + avx2 = "avx2" in flags + avx512 = {"avx512f", "avx512bw", "avx512vl", "avx512_vnni", "avx512vbmi"} <= flags + m = re.search(r"^model name\s*:\s*(.*)$", txt, re.M) + name = m.group(1) if m else name + except OSError: + pass + return name, avx2, avx512 + + +def _cpuid_avx512_full() -> bool: + """Windows has no feature bit for VNNI / VBMI: ask the CPU (CPUID leaf 7) through a tiny machine-code stub.""" + try: + code = bytes([0x53, 0x49, 0x89, 0xC8, 0xB8, 0x07, 0x00, 0x00, 0x00, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; cpuid(7,0) + 0x41, 0x89, 0x18, 0x41, 0x89, 0x48, 0x04, 0x5B, 0xC3]) # [r8]=ebx,[r8+4]=ecx; pop rbx + k32 = ctypes.windll.kernel32 + k32.VirtualAlloc.restype = ctypes.c_void_p + buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) + if not buf: + return False + ctypes.memmove(buf, code, len(code)) + regs = (ctypes.c_uint32 * 2)() + ctypes.CFUNCTYPE(None, ctypes.c_void_p)(buf)(ctypes.addressof(regs)) + ebx, ecx = regs[0], regs[1] + need_ebx = (1 << 16) | (1 << 30) | (1 << 31) # F, BW, VL + need_ecx = (1 << 1) | (1 << 11) # VBMI, VNNI + return (ebx & need_ebx) == need_ebx and (ecx & need_ecx) == need_ecx + except Exception: + return False + + +def _run_stub(code: bytes, *args) -> None: + """Runs a few bytes of x64 machine code (Windows calling convention: the arguments in rcx, rdx).""" + k32 = ctypes.windll.kernel32 + k32.VirtualAlloc.restype = ctypes.c_void_p + k32.VirtualFree.argtypes = (ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32) + buf = k32.VirtualAlloc(None, len(code), 0x3000, 0x40) + if not buf: + raise OSError("VirtualAlloc failed") + try: + ctypes.memmove(buf, code, len(code)) + ctypes.CFUNCTYPE(None, *[ctypes.c_void_p] * len(args))(buf)(*args) + finally: + k32.VirtualFree(buf, 0, 0x8000) + + +def _cpuid_avx2() -> bool: + """AVX2 asked from the CPU (CPUID leaf 7 EBX bit 5), with the OS saving the YMM registers (OSXSAVE + XCR0): + Windows' IsProcessorFeaturePresent(PF_AVX2) says no on some PCs whose CPU has it (a Ryzen 9 3950X, #159).""" + try: + def cpuid(leaf): + regs = (ctypes.c_uint32 * 4)() + _run_stub(bytes([0x53, 0x49, 0x89, 0xC8, 0x89, 0xD0, 0x31, 0xC9, 0x0F, 0xA2, # push rbx; r8=rcx; eax=edx; ecx=0; cpuid + 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, # [r8]=eax, [r8+4]=ebx, [r8+8]=ecx + 0x41, 0x89, 0x50, 0x0C, 0x5B, 0xC3]), # [r8+12]=edx; pop rbx + ctypes.addressof(regs), leaf) + return list(regs) + if cpuid(0)[0] < 7: + return False + ecx1 = cpuid(1)[2] + if not (ecx1 >> 27) & 1 or not (ecx1 >> 28) & 1: # OSXSAVE, AVX + return False + xcr0 = (ctypes.c_uint32 * 2)() + _run_stub(bytes([0x49, 0x89, 0xC8, 0x31, 0xC9, 0x0F, 0x01, 0xD0, # r8=rcx; ecx=0; xgetbv + 0x41, 0x89, 0x00, 0x41, 0x89, 0x50, 0x04, 0xC3]), ctypes.addressof(xcr0)) + if xcr0[0] & 6 != 6: # the OS saves XMM and YMM + return False + return bool((cpuid(7)[1] >> 5) & 1) + except Exception: + return False + + +def gpus(): + """Every NVIDIA GPU, numbered as nvidia-smi numbers them (by PCI bus, the order the engine is told to use).""" + s = out(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version", + "--format=csv,noheader,nounits"]) + found = [] + for line in s.strip().splitlines(): + try: + idx, name, mem, cc, drv = [x.strip() for x in line.split(",")] + found.append({"index": int(idx), "name": name, "vram_gb": float(mem) / 1024.0, "arch": cc.replace(".", ""), + "driver": drv}) + except ValueError: + continue + return found + + +GPU_PICK = None # --gpu N (issue #51); None: the card with the most VRAM +SPLIT_MIN_VRAM_GB = 8 # a card sharing a model holds the dense weights and its own + # prompt buffers too (docs/MULTI_GPU.md) +SPLIT_PROMPT_VRAM_GB = 12 # #448: a split stage lends a prompt chunk's buffers from its + # own cache; below this one cannot fund a 4096-token chunk + # (a 10 GB RTX 3080 beside a 32 GB card: 512 tokens, prompts + # 6.2x slower), while the big card alone could + + +def cc(g) -> str: + return f"{g['arch'][:-1]}.{g['arch'][-1]}" + + +def experimental_sm60() -> bool: + """#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards: the community build + (-DSTRATA_EXPERIMENTAL_SM60=ON, compiled here with a CUDA 12.x toolkit), not the ready-made engine.""" + return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1" + + +def sm60_card(arch) -> bool: + return 60 <= int(arch) <= 70 + + +def gpu_problem(g, together=False): + """Why Strata cannot use this card, in plain words (None: it can).""" + if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()): + return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; Strata needs 7.5 or " + "newer" + ("; STRATA_EXPERIMENTAL_SM60=1 tries the community build for it" if sm60_card(g["arch"]) + else "") + ")") + if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5: + return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model " + f"needs {SPLIT_MIN_VRAM_GB} GB or more)") + return None + + +def gpu_rank(g): + """The order cards share a model in: the newest generation first (it gets the first layers and most of the + work), then the most VRAM.""" + return (-int(g["arch"]), -round(g["vram_gb"]), g["index"]) + + +def gpu_name(g) -> str: + return f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB)" + + +def gpu_table(found) -> None: + say(" Your NVIDIA GPUs:") + for g in found: + p = gpu_problem(g) + say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + ("can be used" if p is None else p)) + + +def together_ok(found) -> list: + """The cards that can share one model, in the order they would (empty if fewer than two).""" + ok_ = sorted([g for g in found if gpu_problem(g, together=True) is None], key=gpu_rank) + return ok_ if len(ok_) >= 2 else [] + + +def split_short(cards) -> list: + """#448: the later cards of a split that would cap its prompt chunk below what the first card alone reads (a card + under SPLIT_PROMPT_VRAM_GB beside one that has it). Empty: the split is recommended as before.""" + if len(cards) < 2 or cards[0]["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5: + return [] + return [g for g in cards[1:] if g["vram_gb"] < SPLIT_PROMPT_VRAM_GB - 0.5] + + +def split_short_note(g) -> str: + return (f"GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB) is too small to lend a split its prompt buffers: " + "it would cap prompt reading at 512-2048-token chunks, several times slower than the first card alone " + "(#448). It can serve as a helper expert cache instead (docs/SECOND_GPU.md)") + + +def parse_gpus(text, found) -> list: + """--gpus / --gpu with several: "0,2" or "all" (every card that can share the model).""" + if str(text).strip().lower() == "all": + sel = [g["index"] for g in together_ok(found)] + if not sel: + gpu_table(found) + fail("--gpus all: this PC does not have two GPUs Strata can use together") + return sel + try: + sel = [int(x) for x in str(text).split(",") if x.strip()] + except ValueError: + fail(f"--gpus takes GPU numbers as nvidia-smi numbers them, e.g. --gpus 0,2 (or --gpus all), not {text!r}") + if len(sel) < 2 or len(set(sel)) != len(sel): + fail("--gpus takes two or more different GPUs, e.g. --gpus 0,2 (one GPU: --gpu 0)") + return sel + + +def check_gpus(sel, found, what="", yes=False, named=False) -> None: + """Stops with a plain message when a chosen card is missing or cannot be used, and says what can. named: the user + named these cards (--gpus 0,1, or a config that has them): a card that is only short of VRAM for sharing the model + is then a risk to confirm, not a stop (the owner's rule; --yes with the named cards is the consent).""" + together = len(sel) > 1 + for i in sel: + g = next((x for x in found if x["index"] == i), None) + p = "not found on this PC" if g is None else gpu_problem(g, together) + if p is None: + continue + if named and g is not None and gpu_problem(g) is None: # it runs Strata; only its VRAM is small + confirm_risk(f"GPU {i} ({g['name']}) has {g['vram_gb']:.0f} GB of VRAM: a card sharing the model needs " + f"{SPLIT_MIN_VRAM_GB} GB or more (it holds the dense weights of its layers and its own prompt " + "buffers), so the model may not start, or run slower than without it", True, yes, + f"GPU {i} ({g['name']}) {what}is not used together with other GPUs: {p}", + "leave it out of --gpus, or answer y to use it anyway", " Use it anyway?") + warn(f"GPU {i} ({g['name']}) is used together with the others, as you chose") + continue + say() + gpu_table(found) + can = together_ok(found) + single = [x for x in found if gpu_problem(x) is None] + ones = " or ".join(f"--gpu {x['index']}" for x in single) + both = "--gpus " + ",".join(str(x["index"]) for x in can) if can else "" + hint = ((f"use these together: {both}" + (f" (or one card: {ones})" if not together else "")) if can else + f"use one card: {ones}" if single else "Strata needs an NVIDIA RTX 20 series or newer card") + fail(f"GPU {i}{'' if g is None else ' (' + g['name'] + ')'} {what}cannot be used: {p}", hint) + + +def engine_archs(): + """The GPU generations the installed engine has code for: (archs, ptx), or None when there is none.""" + info = ROOT / "engine" / "BUILD.json" + try: + meta = json.loads(info.read_text()) + except (OSError, ValueError): + return None + return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx")) + + +def engine_archs_hip(): + """The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" + try: + meta = json.loads((ROOT / "engine" / "BUILD.json").read_text()) + except (OSError, ValueError): + return None + return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None + + +def engine_runs_on(g) -> bool: + ea = engine_archs() + if ea is None or not ea[0]: + return True + archs, ptx = ea + return int(g["arch"]) in archs or (ptx and int(g["arch"]) > max(archs)) + + +def start_gpus(text): + """--gpus when starting an installed model: NVIDIA cards as nvidia-smi numbers them, or on a PC whose AMD cards + are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card).""" + if not text: + return None + if str(text).strip().lower() == "all" and not WIN and not together_ok(gpus()): + amd = amd_gpus() + if len([g for g in amd if amd_problem(g) is None]) >= 2: + return [g["index"] for g in amd_parse_gpus("all", amd)] + return parse_gpus(text, gpus()) + + +def choose_gpus(a, found) -> list: + """Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best + together recommended), else the supported card with the most VRAM. Returns their numbers, the main one first.""" + if a.gpus: + sel = parse_gpus(a.gpus, found) + check_gpus(sel, found, yes=a.yes, named=str(a.gpus).strip().lower() != "all") + return sel + if a.gpu is not None: + check_gpus([a.gpu], found) + return [a.gpu] + single = sorted([g for g in found if gpu_problem(g) is None], key=lambda x: (-round(x["vram_gb"]), x["index"])) + if not single: + gpu_table(found) + fail("none of your GPUs can run Strata", "it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)") + can = together_ok(found) + if not can: + return [single[0]["index"]] + say() + say(f" Strata can run the model on one GPU, or share it across {'these' if len(can) > 2 else 'both'}: then each" + " card holds the") + say(" experts of its own layers, so together they hold about twice as many, and prompts are read about 20%") + say(" faster (details: docs/MULTI_GPU.md). A much slower extra card can also make it slower.") + opts = [can[:2]] + ([can] if len(can) > 2 else []) + [[g] for g in single] + # #448: a pair whose second card cannot lend a 4096-token chunk recommends the first card alone (still offered) + short = split_short(can[:2]) + rec = next(i for i, o in enumerate(opts, 1) if o == [can[0]]) if short else 1 + for i, o in enumerate(opts, 1): + label = (" + ".join(gpu_name(g) for g in o) + " together") if len(o) > 1 else gpu_name(o[0]) + " only" + say(f" {i}) {label}" + (" (recommended)" if i == rec else "")) + for g in found: + if gpu_problem(g, together=True) is not None: + say(f" (GPU {g['index']}, {g['name']}: {gpu_problem(g, together=True)})") + for g in short: + say(f" ({split_short_note(g)})") + pick = opts[int(ask("Which GPUs?", [str(i) for i in range(1, len(opts) + 1)], str(rec), a.yes or a.check)) - 1] + return [g["index"] for g in pick] + + +def split_mmap(cfg: dict) -> bool: + """#364 #384: the low-RAM mode's resident variant (--resident-experts) has no layer split yet. A config with it + that runs on several GPUs reads the experts the GPUs do not hold through the OS file cache instead + (--mmap-experts: the placement those reports measured 1.3-1.6x faster than one GPU), said plainly - the engine + used to refuse the pair. True when the config changed.""" + a = cfg.get("args", []) + if "--resident-experts" not in a: + return False + a[a.index("--resident-experts")] = "--mmap-experts" + warn("the low-RAM mode's resident variant (--resident-experts) has no layer split yet: on several GPUs the experts " + "the GPUs do not hold are read through the OS file cache (--mmap-experts) instead, and RAM can fill up to 0 " + "free during long prompts. One GPU keeps them in RAM (steady RAM use): START-HERE --setup, or --gpu N for a " + "start") + return True + + +def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict: + """Starting a model set up for one card on a PC with two or more that can share it: asked once (the answer is + saved in its config).""" + if isinstance(cfg.get("gpu"), list) or cfg.get("gpus_asked"): + return cfg + found = gpus() + can = together_ok(found) + if not can: + return cfg + pair = can[:2] + cfg["gpus_asked"] = True + # #364 #384: the resident low-RAM variant stays on one card unless the user says otherwise (its RAM use is steady) + resident = "--resident-experts" in cfg.get("args", []) + say() + say(" This PC has " + " and ".join(gpu_name(g) for g in pair) + ": Strata can share the model across both.") + say(" Together they hold about twice the model's experts and read prompts about 20% faster (docs/MULTI_GPU.md).") + if resident: + say(" This model runs in the low-RAM mode with its experts kept in RAM, on one GPU (recommended: steady RAM") + say(" use). On both, the experts the GPUs do not hold are read through the OS file cache instead: faster in") + say(" two reports (#364, #384), but RAM can fill up to 0 free during long prompts.") + short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident + for g in short: + say(f" {split_short_note(g)}.") + missing = [g for g in pair if not engine_runs_on(g)] + if missing: + say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them " + "together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair)) + elif ask(" Use both from now on? (you can change it later: START-HERE.bat --gpu N for one card)", + ["y", "n"], "n" if resident or short else "y", yes) == "y": + cfg["gpu"] = [g["index"] for g in pair] + cfg["layer_split"] = cfg.get("layer_split") or "auto" + split_mmap(cfg) + ok("from now on this model runs on " + " + ".join(gpu_name(g) for g in pair)) + else: + ok("staying on one GPU (START-HERE.bat --gpus " + ",".join(str(g["index"]) for g in pair) + " switches)") + write_config(cfg_path, cfg) + return cfg + + +def gpu_info(pick=None): + """The GPU Strata runs on: `pick` (nvidia-smi's number) if given, else the one with the most VRAM (ties: the + lower number). None when there is no NVIDIA GPU. The dict also says how many there are ("count").""" + found = gpus() + if not found: + return None + pick = GPU_PICK if pick is None else pick + if pick is not None: + g = next((x for x in found if x["index"] == pick), None) + if g is None: + fail(f"there is no GPU {pick}: " + ", ".join(f"{x['index']} = {x['name']}" for x in found)) + else: + g = max(found, key=lambda x: (round(x["vram_gb"]), -x["index"])) + return {**g, "count": len(found)} + + +def find_nvcc(below=None): + """The newest CUDA toolkit's nvcc and its (major, minor); with `below`, the newest older than that version.""" + cands = [shutil.which("nvcc")] + if os.environ.get("CUDA_PATH"): + cands.append(str(Path(os.environ["CUDA_PATH"]) / "bin" / ("nvcc.exe" if WIN else "nvcc"))) + if WIN: + base = Path(r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA") + if base.exists(): + cands += [str(p / "bin" / "nvcc.exe") for p in sorted(base.iterdir(), reverse=True)] + else: + cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/usr/local").glob("cuda*"), reverse=True)] + cands += [str(p / "bin" / "nvcc") for p in sorted(Path("/opt").glob("cuda*"), reverse=True)] # Arch (#46) + best = (None, None) + for c in dict.fromkeys(cands): # every toolkit found; the newest wins + if c and Path(c).exists(): + v = re.search(r"release (\d+)\.(\d+)", out([c, "--version"])) + ver = (int(v.group(1)), int(v.group(2))) if v else None + if ver and (below is None or ver < below) and (best[1] is None or ver > best[1]): + best = (c, ver) + return best + + +def find_vcvars(): + vswhere = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe" + if not vswhere.exists(): + return None + # CUDA 13 accepts Visual Studio 2019 and 2022 only: a newer one (2026 = version 18) installed next to them + # must not be picked ("unsupported Microsoft Visual Studio version"); with only a newer one there is none + p = out([str(vswhere), "-latest", "-products", "*", "-version", "[16.0,18.0)", "-requires", + "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"]).strip() + v = Path(p) / "VC/Auxiliary/Build/vcvars64.bat" if p else None + return v if v and v.exists() else None + + +def find_tool(name): + """A tool on PATH, or the one pip installed next to this Python (cmake, ninja).""" + p = shutil.which(name) + if p: + return p + for d in (Path(sys.executable).parent / "Scripts", Path(sys.executable).parent, + Path.home() / ".local" / "bin"): + c = d / (name + (".exe" if WIN else "")) + if c.exists(): + return str(c) + return None + + +def free_gb(path): + path.mkdir(parents=True, exist_ok=True) + return shutil.disk_usage(path).free / 1e9 + + +# ------------------------------------------------------------------------------------------------ downloads +def drop_archive(z: Path) -> None: + """An unpacked or refused engine archive and its .done mark go: a refused one kept them, and every later run + reused it ("already downloaded") instead of the published one (PR #324).""" + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + + +def download(url, dst: Path, what=None): + """Resumable HTTP(S) download with a progress line; `file://` and plain paths are copied (tests, mirrors). + A finished file gets a .done mark, so a later run skips it without asking the server.""" + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists() and done(dst): + ok(f"{what or dst.name} already downloaded") + return + if not url.startswith(("http://", "https://")): + src = Path(url[7:] if url.startswith("file://") else url) + if not src.exists(): + fail(f"not found: {src}") + shutil.copyfile(src, dst) + mark(dst) + ok(f"{what or dst.name} copied") + return + part = dst.with_name(dst.name + ".part") + total = 0 + for attempt in range(5): + try: + req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}) + total = int(urllib.request.urlopen(req, timeout=60).headers.get("Content-Length", 0)) + break + except urllib.error.HTTPError as e: + if e.code == 404 and hf_unpinned(url) != url: # #214: the pinned revision is gone from the repository + warn(f"{what or dst.name}: not at the pinned revision any more; downloading the repository's " + "current file") + url = hf_unpinned(url) + continue + if attempt == 4: + fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + time.sleep(5) + except OSError as e: + if attempt == 4: + fail(f"cannot reach {url.split('/')[2]} ({e})", "check your internet connection and run it again") + time.sleep(5) + if dst.exists() and total and dst.stat().st_size == total: # finished by an older setup (no mark yet) + mark(dst) + ok(f"{what or dst.name} already downloaded") + return + have = part.stat().st_size if part.exists() else 0 + for attempt in range(30): + try: + req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"}) + with urllib.request.urlopen(req, timeout=60) as r, open(part, "ab" if have else "wb") as f: + if have and r.status != 206: # the server ignored the range: start over + f.seek(0) + f.truncate() + have = 0 + last = 0.0 + while True: + b = r.read(8 << 20) + if not b: + break + f.write(b) + have += len(b) + if time.time() - last > 2: + last = time.time() + size = f"{have / 1e9:6.2f} / {total / 1e9:.2f} GB ({100 * have / total:.0f}%)" if total \ + else f"{have / 1e6:7.1f} MB" + print(f"\r {what or dst.name}: {size} ", end="", flush=True) + print() + if not total or have >= total: + break + except OSError as e: + print() + warn(f"download interrupted ({e}); retrying in 10 s ...") + time.sleep(10) + if total and part.stat().st_size != total: + fail(f"could not finish downloading {dst.name}: {part.stat().st_size:,} bytes on disk, the server says {total:,}", + "check your internet connection and run it again (the download resumes where it stopped)") + part.replace(dst) + mark(dst) + ok(f"{what or dst.name} downloaded") + + +def whole_shard(s: Path) -> bool: + """A shard as long as its own tensor directory says (check_shards' test, without stopping setup).""" + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile + try: + g = GGUFFile(s) + return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), + default=0) + except (OSError, ValueError, struct.error): + return False + + +SHARD_NAME = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$") + + +def gguf_dir_shards(folder: Path, fam: dict, model: str) -> list[Path]: + """--gguf-dir's shards (#305): every -0000i-of-0000N file of the model, N read from the first shard's name as the + engine and tools/iq_pack.py do. The published name first; else the one first shard in the folder whose name has + the size in it (an upload split or named differently: -00001-of-00003, Unsloth's ...-00001-of-00004.gguf). A + missing shard is check_shards' error later, as before.""" + first = folder / fam["file"].format(q=model, i=1) + if not first.exists(): + found = sorted(p for p in folder.glob("*-00001-of-*.gguf") if SHARD_NAME.search(p.name)) + mine = [p for p in found if model.lower() in p.name.lower()] + pick = mine if mine else found + if len(pick) == 1: + first = pick[0] + m = SHARD_NAME.search(first.name) + total = int(m.group(2)) if m else 1 + if not m or total < 1: + return [first] + stem = first.name[:m.start()] + return [first.with_name("%s-%05d-of-%05d.gguf" % (stem, i, total)) for i in range(1, total + 1)] + + +# #444: the quantization in a GGUF's name (Unsloth's UD-IQ3_XXS, a K-quant's Q2_K_XL, a GSQ-RCO IQ3_S, ...) +GGUF_QUANT = re.compile(r"(? str | None: + """#444: the quantization a GGUF's name says, when it is one Strata cannot run (not a setup size); else None.""" + m = GGUF_QUANT.search(name) + return m.group(1) if m and m.group(1).upper() not in MODELS and not name.lower().startswith("mmproj") else None + + +def gguf_choice(name: str) -> tuple | None: + """#444: (--family, --model) whose published first shard this file is, or None (the Coder's IQ1_M is named like + the original's sizes: the size tells them apart).""" + for f, d in FAMILIES.items(): + for m in MODELS: + if f in MODELS[m].get("families", ("qwen", "swift")) and name == d["file"].format(q=m, i=1): + return f, m + return None + + +def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple | None: + """#444: (message, hint) when --gguf-dir has no file setup can use for this choice: the chosen shard is a GGUF + Strata cannot run (Unsloth's UD-IQ3_XXS taken for IQ3_XXS by its name), or it is missing and the folder holds + other GGUFs - then the hint names the --family/--model of the usable ones. None otherwise (a missing shard in a + folder without GGUFs stays check_shards' "missing").""" + bad = gguf_unsupported(first.name) if first.exists() else None + if bad: + return f"{first.name} is {bad}, a GGUF Strata cannot run", SUPPORTED_GGUFS + if first.exists(): + return None + firsts = sorted(p.name for p in folder.glob("*.gguf") + if not p.name.lower().startswith("mmproj") and (not SHARD_NAME.search(p.name) + or SHARD_NAME.search(p.name).group(1) == "00001")) + usable = list(dict.fromkeys(c for c in map(gguf_choice, firsts) if c)) + unusable = [n for n in firsts if gguf_unsupported(n)] + if not usable and not unusable: + return None + hint = SUPPORTED_GGUFS + if unusable: + hint += ".\n Not usable here: " + ", ".join(unusable) + if usable: + hint += ".\n Usable here: " + ", ".join(f"--family {f} --model {m}" for f, m in usable) + return f"{folder} has no {fam['title']} {model} file", hint + + +def verify_sha256(s: Path, size: int, sha: str) -> None: + """A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark, + so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again.""" + m = s.with_name(s.name + ".done") + if m.exists() and f"sha256 {sha}" in m.read_text(encoding="utf-8", errors="replace"): + return + have = s.stat().st_size if s.exists() else -1 + if have != size: + fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)") + say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...") + h = hashlib.sha256() + with open(s, "rb") as f: + while True: + b = f.read(16 << 20) + if not b: + break + h.update(b) + if h.hexdigest() != sha: + s.unlink(missing_ok=True) + m.unlink(missing_ok=True) + fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted", + "run setup again to download it again") + mark(s, f"sha256 {sha}") + + +def resident_budget_gib(model, ram, kv_ram_gb=0.0) -> int: + """UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less + 24 for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to + RAM; at most all of them, at least 8. 64 GB: 40, the measured setting (docs/UNSLOTH_Q4.md).""" + gib = round(ram) - UNSLOTH_RAM_LEFT_GB - math.ceil(kv_ram_gb) + return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824))) + + +def budget_choice(model, ram, asked) -> float: + """S4: UD-Q4_K_XL's RAM budget: --resident-budget-gib N as given, else the recommendation (resident_budget_gib). + More than the recommendation is kept, with what it risks (the owner's rule: setup recommends, it never forces).""" + rec = resident_budget_gib(model, ram) + if asked is None: + return rec + if asked > rec: + warn(f"a {asked:g} GiB RAM budget is more than setup recommends for this PC ({rec} GiB: the RAM less " + f"{UNSLOTH_RAM_LEFT_GB} GB for the OS, the engine and the file cache that reads the other experts). Kept " + "as you chose: the engine clamps it to the RAM it finds free at start (less 4 GB), and the file cache " + "gets less room - it may be slower, or run the PC out of RAM under load") + return int(asked) if asked == int(asked) else asked + + +def check_shards(shards): + """Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as + its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part + renamed by hand, a download finished by an older setup) otherwise passes as a model file and the engine + fails much later, at the first tensor that runs past the end.""" + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile + for s in shards: + if not s.exists(): + fail(f"missing {s}") + try: + g = GGUFFile(s) + except (ValueError, struct.error) as e: + fail(f"{s.name} is not a whole GGUF shard ({e})", "delete it and run setup again") + need = g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors), default=0) + have = s.stat().st_size + if have < need: + fail(f"{s.name} is short: {have:,} of {need:,} bytes ({need - have:,} missing)", + "delete it and run setup again (or copy the whole file into --gguf-dir)") + + +def get_llama_cpp(): + """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git.""" + llama = ROOT / "third_party" / "llama.cpp" + if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): + return llama + z = ROOT / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip" + download(LLAMA_CPP_ZIP, z, "llama.cpp source") + tmp = ROOT / "third_party" / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + # llama.cpp's own web UI (tools/ui) is not used, and its deep paths passed Windows' 260-character limit in a + # folder like Downloads\Strata-main\Strata-main (#206) + f.extractall(tmp, [m for m in f.namelist() if "/tools/ui/" not in m]) + top = next(tmp.iterdir()) + shutil.rmtree(llama, ignore_errors=True) + # PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the + # fresh unpack; shutil.move falls back to copy-and-delete, and a few retries let the scanner finish. The target + # is `llama` itself - moving into its parent would keep the zip's `llama.cpp-` folder name. + for attempt in range(5): + try: + shutil.move(str(top), str(llama)) + break + except PermissionError: + if attempt == 4: + raise + shutil.rmtree(llama, ignore_errors=True) # a partial copy from the failed attempt + time.sleep(2) + shutil.rmtree(tmp, ignore_errors=True) + z.unlink(missing_ok=True) + z.with_name(z.name + ".done").unlink(missing_ok=True) + return llama + + +def req_name(line: str) -> str: + """The distribution name of a requirement line ("numpy==2.5.3; python_version >= '3.12'" -> "numpy").""" + return re.split(r"[\s<>=!~;\[]", line.strip(), maxsplit=1)[0].lower().replace("_", "-") + + +def requirement_lines(path: Path | None = None) -> list[str]: + """requirements.txt's requirements, comments and blank lines left out.""" + lines = [] + for raw in (path or REQUIREMENTS).read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].strip() + if line: + lines.append(line) + return lines + + +def _installed(name: str) -> bool: + try: + import importlib.metadata as md + md.distribution(name) + return True + except Exception: + return False + + +def pip_install(packages, what): + """pip install into .venv, skipped when the same list was installed before. An install from before the pinned + requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the + pinned dependencies it already has count as installed.""" + stamp = Path(sys.prefix) / ".strata-pip.json" + have = json.loads(stamp.read_text()) if stamp.exists() else [] + bare = {p.lower() for p in have if req_name(p) == p.lower()} + need = [p for p in packages if p not in have and req_name(p) not in bare + and not (bare and "==" in p and _installed(req_name(p)))] + if not need: + ok(f"{what} already installed") + return + say(f" Installing {what} ...") + run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *need]) + stamp.write_text(json.dumps(sorted(set(have) | set(need)), indent=0)) + ok(f"{what} installed") + + +def cuda_lib_dirs(): + """Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux).""" + pattern = "cublas64_13.dll" if WIN else "libcublas.so.13*" + dirs = [] + for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: + for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []: + if hit.parent not in dirs: + dirs.append(hit.parent) + return [str(d) for d in dirs] + + +# ------------------------------------------------------------------------------------------------ AMD +# The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP +# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by +# their owners; the RX 6800 / 6900 series (gfx1030, #311) runs but is unvalidated. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo; +# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards. +# No images yet. +ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family + "gfx1101": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", + "gfx1200": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", + "gfx1201": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", + "gfx1030": "https://rocm.nightlies.amd.com/v2/gfx103X-all/"} +ROCM_VERSION = os.environ.get("STRATA_ROCM_VERSION", "7.10.0a20251120") # what Strata's HIP build was tested with +ROCM_SYSTEM_MIN = (7, 0) # an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer) +AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1200", "gfx1201", "gfx1030") +AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name + "gfx1101": "AMD Radeon RX 7800 XT / 7700 XT (gfx1101)", + "gfx1200": "AMD Radeon RX 9060 series (gfx1200)", + "gfx1201": "AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)", + "gfx1030": "AMD Radeon RX 6800 / 6900 series (gfx1030)"} +AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and " + "RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030, unvalidated)") + + +def rocm_index(arch): + return os.environ.get("STRATA_ROCM_INDEX") or ROCM_INDEXES[arch] + + +def amd_gpus(sysfs="/sys"): + """AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: + the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). + sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one). Windows: amd_gpus_win.""" + if WIN: + return amd_gpus_win() + base = Path(sysfs) / "class/kfd/kfd/topology/nodes" + found = [] + if not base.is_dir(): + return found + for node in sorted((p for p in base.iterdir() if p.name.isdigit()), key=lambda p: int(p.name)): + try: + props = {} + for line in (node / "properties").read_text().splitlines(): + k, _, v = line.partition(" ") + props[k] = v.strip() + ver = int(props.get("gfx_target_version") or 0) + if ver == 0 or int(props.get("simd_count") or 0) == 0: + continue + except (OSError, ValueError): + continue + arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}" + dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '')}/device" + try: + vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30 + except (OSError, ValueError): + vram = 0.0 + try: + name = (dev / "product_name").read_text().strip() or f"AMD Radeon ({arch})" + except OSError: + name = f"AMD Radeon ({arch})" + if name == f"AMD Radeon ({arch})" and arch in AMD_NAMES: + name = AMD_NAMES[arch] + found.append({"index": len(found), "name": name, "vram_gb": vram, "arch": arch, "driver": "amdgpu", + "vendor": "amd"}) + return found + + +def amd_problem(g): + if g["arch"] not in AMD_ARCHS: + return f"not supported - Strata's AMD backend runs on {AMD_CARDS} only, this is {g['arch']}" + if g.get("cannot_run"): # Windows: the installed engine's own check (--list-devices) + return g["cannot_run"] + return None + + +def amd_gpus_win() -> list[dict]: + """Windows: the AMD GPUs as the HIP runtime numbers them once the HIP engine is installed (hip_devices), else in + the display-adapter order (amd_gpus_windows).""" + return hip_devices() or amd_gpus_windows() + + +def amd_parse_gpus(text, amd) -> list: + """--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the + most VRAM first). Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different + architectures: the engine is compiled for each). Returns the cards, the main one first.""" + usable = [g for g in amd if amd_problem(g) is None] + if str(text).strip().lower() == "all": + sel = [g["index"] for g in sorted(usable, key=lambda x: (-round(x["vram_gb"]), x["index"]))] + else: + try: + sel = [int(x) for x in str(text).split(",") if x.strip()] + except ValueError: + fail(f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not {text!r}") + if len(sel) < 2 or len(set(sel)) != len(sel): + fail("--gpus takes two or more different GPUs, e.g. --gpus 1,0 (one GPU: --gpu 1)", + "this PC has " + (f"{len(usable)} AMD card{'s' if len(usable) != 1 else ''} Strata can use" + + (": " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in usable) if usable else ""))) + byid = {g["index"]: g for g in amd} + for i in sel: + g = byid.get(i) + p = "not found on this PC" if g is None else amd_problem(g) + if p is not None: + fail(f"AMD GPU {i}{'' if g is None else ' (' + g['name'] + ')'} cannot be used: {p}", + ("use these together: --gpus " + ",".join(str(x["index"]) for x in usable)) if len(usable) >= 2 else + ("use one card: --gpu " + str(usable[0]["index"])) if usable else f"the AMD backend runs on {AMD_CARDS}") + return [byid[i] for i in sel] + + +# ------------------------------------------------------------------------------------------------ AMD on Windows +# Windows has no KFD topology: the cards are found from the display adapters (Win32_VideoController: the ones present, +# with their PCI ids) and the display-class registry (each adapter's 64-bit VRAM size), before any AMD software is +# needed. The engine is the ready-made HIP one (WIN_HIP_ASSET: strata.exe, strata-device.exe and the ROCm libraries it +# loads, built by tools/hip/build_windows.bat); it needs only the AMD driver. Once it is installed, the cards are +# numbered as the HIP runtime numbers them (`strata-device --list-devices`): an integrated Radeon takes HIP's device 0 +# and pushes the discrete card to 1, which the display-adapter order does not show (#325). +WIN_HIP_ASSET = "strata-windows-x64-hip.zip" +WIN_HIP_MIN_ENGINE = max(MIN_ENGINE, (0, 1, 33)) # the first release with a Windows HIP engine +WIN_AMD_DRIVER = "https://www.amd.com/en/support/download/drivers.html" +# PCI device ids (VEN_1002) of the cards the AMD backend knows; the names below cover a card whose id is not listed +_WIN_AMD_DID = {0x744C: "gfx1100", 0x7448: "gfx1100", 0x745E: "gfx1100", # RX 7900 XTX/XT/GRE, W7900, W7800 + 0x747E: "gfx1101", # RX 7800 XT / 7700 XT + 0x7480: "gfx1102", # RX 7600 / 7600 XT + 0x7590: "gfx1200", # RX 9060 XT + 0x7550: "gfx1201", 0x7551: "gfx1201", # RX 9070 / 9070 XT, AI PRO R9700 + 0x73BF: "gfx1030", 0x73AF: "gfx1030", 0x73A5: "gfx1030"} # RX 6800 / 6800 XT / 6900 XT / 6950 XT +_WIN_AMD_NAME = ((re.compile(r"\b9070\b|R9700", re.I), "gfx1201"), + (re.compile(r"\b9060\b", re.I), "gfx1200"), + (re.compile(r"RX\s*7900|W7900|W7800", re.I), "gfx1100"), + (re.compile(r"RX\s*7800|RX\s*7700(?!\s*S)|W7700", re.I), "gfx1101"), + (re.compile(r"RX\s*7600|W7600|W7500", re.I), "gfx1102"), + (re.compile(r"RX\s*6800(?!\s*[MS])|RX\s*6900|RX\s*6950|W6800", re.I), "gfx1030")) +_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" + + +def _win_display_adapters() -> list[dict]: + """The display adapters present ({"name", "pnp"}), from Win32_VideoController.""" + ps = ("Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.PNPDeviceID + '|' + " + "$_.AdapterRAM }") + text = out(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps]) + found = [] + for line in text.splitlines(): + parts = line.strip().split("|") + if len(parts) >= 2 and parts[1]: + ram = parts[2] if len(parts) > 2 else "" + found.append({"name": parts[0].strip(), "pnp": parts[1].strip(), + "ram": int(ram) if ram.strip().isdigit() else 0}) + return found + + +def _win_display_registry() -> list[dict]: + """Each display driver instance's description, matching PCI id and VRAM size (the 64-bit value; the WMI one stops + at 4 GB), from the display-class registry key - readable without admin.""" + found = [] + try: + import winreg + cls = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS) + except (ImportError, OSError): + return found + i = 0 + while True: + try: + sub = winreg.EnumKey(cls, i) + except OSError: + break + i += 1 + if not sub.isdigit(): + continue + try: + key = winreg.OpenKey(cls, sub) + except OSError: + continue + vals = {} + for name in ("DriverDesc", "MatchingDeviceId", "HardwareInformation.qwMemorySize", "DriverVersion"): + try: + vals[name] = winreg.QueryValueEx(key, name)[0] + except OSError: + pass + found.append(vals) + return found + + +def _pci_device_id(text: str) -> int | None: + m = re.search(r"VEN_1002&DEV_([0-9A-F]{4})", str(text or ""), re.I) + return int(m.group(1), 16) if m else None + + +def win_amd_arch(device_id: int | None, name: str) -> str: + """A Windows AMD adapter's architecture from its PCI device id, else its name; "" when it is none Strata knows + (an integrated Radeon, an older card).""" + if device_id in _WIN_AMD_DID: + return _WIN_AMD_DID[device_id] + return next((a for rx, a in _WIN_AMD_NAME if rx.search(name or "")), "") + + +def amd_gpus_windows(adapters=None, registry=None) -> list[dict]: + """The AMD display adapters present, in display-adapter order (setup's numbering until the HIP engine is + installed), with the arch Strata would run them as ("" = unknown: listed, not supported). adapters / registry: + tools/test_setup_amd.py passes mocked ones.""" + adapters = _win_display_adapters() if adapters is None else adapters + registry = _win_display_registry() if registry is None else registry + if not adapters: # no WMI answer: the registry alone (it can list removed cards) + adapters = [{"name": r.get("DriverDesc", ""), "pnp": r.get("MatchingDeviceId", ""), "ram": 0} for r in registry] + used = set() + found = [] + for ad in adapters: + did = _pci_device_id(ad.get("pnp")) + if did is None: + continue # not an AMD (VEN_1002) PCI device + vram, driver = 0.0, "" + for k, r in enumerate(registry): # the same card's driver instance: its 64-bit VRAM size + if k in used or _pci_device_id(r.get("MatchingDeviceId")) != did: + continue + if r.get("DriverDesc") and ad.get("name") and r["DriverDesc"].strip() != ad["name"].strip(): + continue + used.add(k) + mem = r.get("HardwareInformation.qwMemorySize") + if isinstance(mem, bytes): + mem = int.from_bytes(mem[:8], "little") + vram = int(mem) / 2 ** 30 if isinstance(mem, int) and mem > 0 else 0.0 + driver = str(r.get("DriverVersion") or "") + break + if vram == 0.0 and ad.get("ram", 0) > 0: + vram = ad["ram"] / 2 ** 30 # WMI's 32-bit figure (at most 4 GB) + arch = win_amd_arch(did, ad.get("name", "")) + name = ad.get("name") or AMD_NAMES.get(arch, f"AMD Radeon (device {did:04X})") + found.append({"index": len(found), "name": name, "vram_gb": vram, "arch": arch or f"unknown (PCI {did:04X})", + "driver": driver or "amd", "vendor": "amd"}) + return found + + +def hip_devices(probe: Path | None = None, text: str | None = None) -> list[dict] | None: + """The GPUs the HIP runtime enumerates, numbered as HIP_VISIBLE_DEVICES numbers them, from the installed engine's + `strata-device --list-devices`; None when there is no HIP engine here or it does not answer. text: its output + (tests).""" + if text is None: + probe = probe or ROOT / "engine" / ("strata-device.exe" if WIN else "strata-device") + try: + hip_engine = json.loads((probe.parent / "BUILD.json").read_text()).get("backend") == "hip" + except (OSError, ValueError): + hip_engine = False + if not probe.exists() or not hip_engine: + return None + try: + hip_runtime_beside_exe(probe.parent) # #468 #461: not the driver's System32 copy + env = dict(os.environ) # the ready-made engine's ROCm DLLs (rocm/bin beside it) + env["PATH"] = os.pathsep.join([str(d) for d in hip_lib_dirs(probe.parent)] + [env.get("PATH", "")]) + r = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, timeout=120, + cwd=str(probe.parent), env=env) + except (OSError, subprocess.TimeoutExpired): + return None + if r.returncode != 0: + return None + text = r.stdout + found = [] + for line in text.splitlines(): + m = re.match(r"device\s+(\d+):\s*(.*)$", line.strip()) + if m: + found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "vram_gb": 0.0, "arch": "", + "driver": "hip", "vendor": "amd"}) + continue + if not found: + continue + a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB", line.strip()) + if a and not found[-1]["arch"]: + found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2)) + elif line.strip().startswith("cannot run:"): + found[-1]["cannot_run"] = line.strip()[len("cannot run:"):].strip() + for g in found: + if not g["arch"]: + g["arch"] = "unknown" + if g["arch"] in AMD_NAMES and g["name"] in ("", "AMD Radeon Graphics"): + g["name"] = AMD_NAMES[g["arch"]] + return found + + +def hip_lib_dirs(eng: Path) -> list[Path]: + """Where the ready-made Windows HIP engine's ROCm DLLs are (its BUILD.json "lib_dirs", relative to engine/).""" + try: + rel = json.loads((eng / "BUILD.json").read_text()).get("lib_dirs") or [] + except (OSError, ValueError): + rel = [] + return [eng / d for d in rel if (eng / d).is_dir()] + + +# #468 #461: the HIP runtime the ready-made engine was built with, next to strata.exe. Windows looks for an imported +# DLL in the exe's folder, then System32, and only then on PATH (where rocm/bin is): an AMD driver that installs its own +# amdhip64_7.dll in System32 won, and the bundled rocBLAS/hipBLAS ran on that runtime - an access violation (W7900) or +# hipErrorInvalidDeviceFunction (7900 XTX) on the first prompt. Only the runtime and the compiler it loads by name: +# rocBLAS/hipBLASLt stay in rocm/bin, where they find their kernel libraries and ../.kpack. +HIP_RUNTIME_DLLS = ("amdhip64_*.dll", "amd_comgr*.dll") + + +def hip_runtime_beside_exe(eng: Path) -> None: + """Copy the bundled HIP runtime DLLs from rocm/bin next to the engine's exes when missing or different (a 0.1.34 + install, whose zip had them in rocm/bin only, is fixed on its next start).""" + for d in hip_lib_dirs(eng): + for pat in HIP_RUNTIME_DLLS: + for src in d.glob(pat): + dst = eng / src.name + try: + if dst.exists() and dst.stat().st_size == src.stat().st_size and \ + dst.stat().st_mtime >= src.stat().st_mtime: + continue + shutil.copy2(src, dst) + except OSError as e: # e.g. the engine is running and holds the old copy + warn(f"could not put {src.name} next to the AMD engine ({e}); if the engine stops on its first " + "request, close Strata and run START-HERE.bat again") + + +def hip_match(card: dict, listed: list[dict], hip: list[dict]) -> dict | None: + """The HIP device that is setup's `card` (from `listed`, the display-adapter order): the k-th device of the same + architecture, k = the card's rank among the listed cards of that architecture. None when HIP has no such card.""" + same = [g["index"] for g in listed if g["arch"] == card["arch"]] + k = same.index(card["index"]) if card["index"] in same else 0 + cand = [g for g in hip if g["arch"] == card["arch"]] + return cand[k] if k < len(cand) else None + + +def hip_card(eng: Path, gpu: dict, listed: list[dict]) -> dict: + """Windows: setup's chosen AMD card as the installed HIP engine numbers it (HIP_VISIBLE_DEVICES), checked by the + engine itself before the model download: an integrated Radeon is HIP's device 0 (#325), and a PC without a + working AMD driver stops here with what to install.""" + hip = hip_devices(eng / "strata-device.exe") + hint = (f"install or update the AMD driver (AMD Software: Adrenalin Edition) from {WIN_AMD_DRIVER}, restart the " + f"PC and run this again; {eng / 'strata-device.exe'} --list-devices shows what the HIP runtime sees") + if not hip: + fail("the AMD HIP runtime finds no GPU (the ready-made engine's device check)", hint) + m = hip_match(gpu, listed, hip) if gpu.get("driver") != "hip" else \ + next((x for x in hip if x["index"] == gpu["index"]), None) + if m is None: + fail(f"the HIP runtime does not list your {gpu['name']} ({gpu['arch']})", hint) + if amd_problem(m): + fail(f"HIP device {m['index']} ({m['name']}) cannot be used: {amd_problem(m)}") + if gpu.get("driver") != "hip" and m["index"] != gpu["index"]: + ok(f"HIP numbers this card {m['index']} (an integrated GPU comes first): the engine is pointed at it") + return {**gpu, "index": m["index"], "count": len(hip), "vram_gb": m["vram_gb"] or gpu["vram_gb"], "driver": "hip"} + + +def get_prebuilt_hip(url_base, gpu, updating=False) -> Path | None: + """The ready-made Windows HIP engine (WIN_HIP_ASSET) in engine/, kept between runs; None when it cannot be had + (not published for this version, no internet) or has no code for the card.""" + eng = ROOT / "engine" + info = eng / "BUILD.json" + if info.exists() and (eng / EXE).exists(): + try: + meta = json.loads(info.read_text()) + except ValueError: + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("backend") == "hip" and meta.get("source") == "prebuilt" and ver >= WIN_HIP_MIN_ENGINE and \ + gpu["arch"] in meta.get("archs", []) and not updating: + ok("ready-made AMD engine already installed") + return eng + if not url_base: + return None + eng.mkdir(exist_ok=True) + z = eng / WIN_HIP_ASSET + bases = prebuilt_bases(url_base) + for i, base in enumerate(bases): + if not base.startswith(("http://", "https://")): + break + try: + req = urllib.request.Request(base + WIN_HIP_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"}) + urllib.request.urlopen(req, timeout=60).close() + break + except OSError as e: + if i + 1 < len(bases): + say(f" No ready-made AMD engine for v{source_version()} ({e}): the latest release instead") + continue + warn(f"no ready-made AMD engine at {base} ({e})") + return None + say(" Downloading the ready-made Strata engine for AMD GPUs (with the ROCm libraries it uses) ...") + download(base + WIN_HIP_ASSET, z, "Strata AMD engine") + tmp = eng / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + try: + meta = json.loads((tmp / "BUILD.json").read_text()) + except (OSError, ValueError): + meta = {} + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + why = None + if meta.get("backend") != "hip" or not (tmp / EXE).exists(): + why = "it is not a HIP engine" + elif ver < WIN_HIP_MIN_ENGINE: + why = f"it is version {meta.get('version')}; this setup needs {'.'.join(map(str, WIN_HIP_MIN_ENGINE))}" + elif gpu["arch"] not in meta.get("archs", []): + why = f"it is built for {', '.join(meta.get('archs', []))}; your GPU is {gpu['arch']}" + if why: + warn(f"the ready-made AMD engine at {base} cannot be used: {why}") + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + for p in tmp.iterdir(): + dst = eng / p.name + if dst.exists(): + shutil.rmtree(dst) if dst.is_dir() else dst.unlink() + p.replace(dst) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + hip_runtime_beside_exe(eng) # #468 #461 + ok(f"ready-made AMD engine {meta.get('version', '')} for {', '.join(meta.get('archs', []))} " + f"(ROCm {meta.get('rocm', '?')})") + return eng + + +def rocm_version(root): + """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" + try: + text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text() + return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR")) + except (OSError, AttributeError, ValueError): + return None + + +def rocm_dev_missing(sysroot: Path) -> list: + """#446: the HIP development files the engine's build needs that a system ROCm lacks (a runtime-only install has + hipcc and libhipblas but not these, and cmake's enable_language(HIP) then fails on the hip-lang package).""" + lang = "cmake/hip-lang/hip-lang-config.cmake" # where CMake's HIP support looks for it + need = {"lib/" + lang: [sysroot / d / lang for d in ("lib", "lib64", "lib/x86_64-unknown-linux-gnu")], + "include/hip/hip_runtime.h": [sysroot / "include" / "hip" / "hip_runtime.h"]} + return [name for name, paths in need.items() if not any(p.is_file() for p in paths)] + + +def rocm_root(archs): + """ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): + (root, library folders). A system ROCm 7 with hipcc, hipBLAS and the HIP development files (#446), else AMD's + TheRock wheels (ROCM_VERSION, from the card family's index) installed into .venv.""" + archs = [archs] if isinstance(archs, str) else list(archs) + sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") + if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): + ver = rocm_version(sysroot) + missing = rocm_dev_missing(sysroot) + if (ver is None or ver >= ROCM_SYSTEM_MIN) and not missing: + return sysroot, [str(sysroot / "lib")] + if ver is not None and ver < ROCM_SYSTEM_MIN: + warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; Strata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} " + "or newer: using AMD's wheels in .venv instead") + else: # #446: a runtime-only ROCm (no -dev packages): cmake would fail + warn(f"the ROCm in {sysroot} has no HIP development files ({', '.join(missing)}): using AMD's wheels in " + ".venv instead (or install them, e.g. AMD's amdrocm-core-dev package for your ROCm and card)") + indexes = list(dict.fromkeys(rocm_index(a) for a in archs)) + if len(indexes) > 1: # TheRock's wheels hold one GPU family's libraries + fail(f"cards of two GPU families ({', '.join(archs)}) need a system ROCm 7 (in /opt/rocm): AMD's Python " + "wheels come per family", "install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)") + index = indexes[0] + stamp = Path(sys.prefix) / ".strata-rocm.json" + have = json.loads(stamp.read_text()) if stamp.exists() else {} + if have.get("version") != ROCM_VERSION or have.get("index") != index: + say(f" Installing ROCm {ROCM_VERSION} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...") + pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index] + if have.get("version") == ROCM_VERSION: # the same version for another GPU family: its own libraries + run(pip + ["--force-reinstall", "--no-deps", f"rocm=={ROCM_VERSION}"]) + run(pip + [f"rocm[libraries,devel]=={ROCM_VERSION}"]) + stamp.write_text(json.dumps({"version": ROCM_VERSION, "index": index})) + sdk = Path(sys.executable).parent / "rocm-sdk" + root = Path(out([str(sdk), "path", "--root"]).strip()) + if not (root / "llvm" / "bin" / "clang++").exists(): + fail(f"ROCm was installed but its compiler is missing ({root})", + f"remove {stamp} and run this again; or install ROCm 7 system-wide") + # the card family's libraries only (gfx120X-all -> _rocm_sdk_libraries_gfx120X_all): another family's + # libhipblaslt.so first on the path would have no kernels for this card + family = "_rocm_sdk_libraries_" + index.rstrip("/").rsplit("/", 1)[-1].replace("-", "_") + dirs = [str(root / "lib")] + for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: + libs = sorted(sp.glob("_rocm_sdk_libraries_*")) + libs = [d for d in libs if d.name.lower() == family.lower()] or libs + dirs += [str(d / "lib") for d in libs if (d / "lib").is_dir()] + ok(f"ROCm: {root}") + return root, list(dict.fromkeys(dirs)) + + +def hipblaslt_version(lib_dirs): + """The installed hipBLASLt's version as the engine reads it (hipblasLtGetVersion: 1.4.1 -> 100401), from the + header of the ROCm whose libraries the engine loads; None when not found.""" + for d in lib_dirs: + try: + text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) + for k in ("MAJOR", "MINOR", "PATCH")] + except (OSError, AttributeError, ValueError): + continue + return v[0] * 100000 + v[1] * 100 + v[2] + return None + + +def hipblaslt_table(arch, lib_dirs, ver=None): + """tools/hip/-hipblaslt-.txt for this card AND the installed hipBLASLt, else None: its solution + ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS). ver: the + hipBLASLt version the ready-made Windows engine ships (its BUILD.json), else read from the installed headers.""" + ver = ver or hipblaslt_version(lib_dirs) + table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" + if ver is not None and table.exists(): + head = table.read_text().split("\n", 2)[:2] + if f"STRATA_HIPBLASLT_TUNING_V1 {arch} {ver}" in (h.strip() for h in head): + ok(f"hipBLASLt tuning table: {table.name} (faster prompts)") + return table + have = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{arch}-hipblaslt-*.txt")) + warn(f"no hipBLASLt tuning table for {arch} with hipBLASLt {ver or '(version unknown)'}" + + (f" (have: {', '.join(have)})" if have else "") + + ": the prompt's dense matrix products use plain hipBLAS (tools/hip/tune_hipblaslt makes a table: " + "docs/AMD_HIP.md, Tuning table)") + return None + + +def build_engine_hip(gpu, llama, vision="none") -> Path: + """Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`). + gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"]. vision "cpu" + (#304): the image encoder too, for the CPU (there is no HIP encoder build yet).""" + eng = ROOT / "engine" + eng.mkdir(exist_ok=True) + stamp = eng / "BUILD.json" + meta = json.loads(stamp.read_text()) if stamp.exists() else {} + src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) + archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) + has_archs = set(archs) <= set(meta.get("archs", [])) + engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs + vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) + if engine_ok and vision_ok: + ok("engine already built for this PC") + return eng + if engine_ok: + return build_vision_cpu(eng, stamp, meta, llama, vsrc) + if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): + fail("a C++ compiler and git are needed to compile the AMD engine", + "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") + root, dirs = rocm_root(archs) + libs = [str(Path(d).parent) for d in dirs[1:]] + bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), + root / "amdgcn" / "bitcode") + os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), + "HIP_PATH": str(root)}) + os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) + os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) + say(" The engine's source changed: compiling it again (only what changed, a few minutes) ..." + if meta.get("backend") == "hip" and (eng / EXE).exists() and has_archs + else f" Compiling the Strata engine for your AMD GPU{'s' if len(archs) > 1 else ''} ({', '.join(archs)}; " + "10-20 minutes, once) ...") + cmake_build(ROOT, ROOT / "build-hip", "strata", + ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", + "-DSTRATA_PREFILL_MMQ=ON", "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), + f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", + "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), + f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", + f"-DSTRATA_GGML_DIR={llama}"], None, "") + shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) + meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", + "lib_dirs": dirs, "src": src} + if vision != "none": + return build_vision_cpu(eng, stamp, meta, llama, vsrc) + stamp.write_text(json.dumps(meta, indent=1)) + ok(f"engine compiled: {eng / EXE}") + return eng + + +def hip_vision(asked) -> str: + """The image encoder with the AMD backend (--vision): the CPU one when asked for (#304); a HIP (GPU) encoder build + is a later step, so `yes`/`gpu` leave images off, as before, and say how to get them.""" + if asked in ("yes", "gpu"): + warn("the AMD backend has no GPU image encoder yet: images off" + + ("" if WIN else " (--vision cpu reads them on the CPU)")) + if asked == "cpu" and WIN: + warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " + "image encoder): images off") + return "none" + return "cpu" if asked == "cpu" else "none" + + +def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path: + """#304: the CPU image encoder beside the HIP engine (tools/vision without CUDA), recorded in its BUILD.json.""" + if not ((eng / VEXE).exists() and meta.get("vision_src") == vsrc): + say(" Compiling the image encoder (for the CPU) ...") + cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_CUDA=OFF"], None, "") + shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE) + stamp.write_text(json.dumps({**meta, "vision": "cpu", "vision_src": vsrc}, indent=1)) + ok(f"engine: {eng / EXE}, image encoder (CPU): {eng / VEXE}") + return eng + + +# ------------------------------------------------------------------------------------------------ the engine +def driver_major(gpu): + try: + return int(gpu["driver"].split(".")[0]) + except (ValueError, KeyError): + return 0 + + +def prebuilt_bases(url_base) -> list[str]: + """Where to look for the ready-made engine, in order (each ending in a slash). The default: the release of this + checkout's version first, then the latest (#214); an explicit --prebuilt / STRATA_PREBUILT_URL: only that.""" + base = url_base if url_base.endswith(("/", "\\")) else url_base + "/" + if base != PREBUILT_URL: + return [base] + return [PREBUILT_TAG_URL.format(version=source_version()), base] + + +def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None: + """The ready-made engine in engine/ (kept between runs), or None when there is none for this PC. + updating: called to replace an installed engine, which starts instead when this fails (no compile).""" + eng = ROOT / "engine" + info = eng / "BUILD.json" + if info.exists() and (eng / EXE).exists() and json.loads(info.read_text()).get("backend") != "hip": + meta = json.loads(info.read_text()) + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "local": # compiled here: build_engine checks its source and cards + return None + have = [int(a) for a in meta.get("archs", [])] + miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) + if have and int(x) not in have and not (meta.get("ptx") and int(x) > max(have))] + if miss: # a card it has no code for (#128): compiled here instead + warn(f"the installed engine is built for {', '.join(str(a) for a in have)}; your GPU is " + f"{', '.join(str(x) for x in miss)}: compiling instead") + return None + if ver >= MIN_ENGINE: + ok("ready-made engine already installed") + return eng + say(f" Updating the ready-made engine ({meta.get('version')} -> {'.'.join(map(str, MIN_ENGINE))} or newer) ...") + info.unlink() + if not url_base: + return None + z = ROOT / "engine" / PREBUILT_ASSET + bases = prebuilt_bases(url_base) + for i, base in enumerate(bases): + if not base.startswith(("http://", "https://")): + break + try: # not published (yet), or no internet: compile instead + req = urllib.request.Request(base + PREBUILT_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"}) + urllib.request.urlopen(req, timeout=60).close() + break + except OSError as e: + if i + 1 < len(bases): # #214: this checkout's release is not published (yet) + say(f" No ready-made engine for v{source_version()} ({e}): the latest release instead") + continue + warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead")) + return None + say(" Downloading the ready-made Strata engine ...") + download(base + PREBUILT_ASSET, z, "Strata engine") + tmp = ROOT / "engine" / "_unpack" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + meta = json.loads((tmp / "BUILD.json").read_text()) + if tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) < MIN_ENGINE: + need = ".".join(map(str, MIN_ENGINE)) + if updating: # these files are newer than the published release (#58) + warn(f"engine {need} is not published yet (the release may still be uploading): run this again " + f"in a few minutes to update it") + else: + warn(f"the ready-made engine at {base} is version {meta.get('version')}; this setup needs " + f"{need}: compiling instead") + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + archs = [int(a) for a in meta.get("archs", [])] + miss = [int(x) for x in gpu.get("archs", [gpu["arch"]]) + if int(x) not in archs and not (meta.get("ptx") and int(x) > max(archs))] + if miss: + warn(f"the ready-made engine is built for {', '.join(str(a) for a in archs)}; your GPU is " + f"{', '.join(str(x) for x in miss)}" + ("" if updating else ": compiling instead")) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + return None + for p in tmp.iterdir(): + dst = eng / p.name + if dst.exists(): + shutil.rmtree(dst) if dst.is_dir() else dst.unlink() + p.replace(dst) + shutil.rmtree(tmp, ignore_errors=True) + drop_archive(z) + if not (eng / EXE).exists(): + fail("the ready-made engine archive has no " + EXE) + if not WIN: + for x in (EXE, VEXE): + if (eng / x).exists(): + (eng / x).chmod(0o755) + ok(f"ready-made engine {meta.get('version', '')} for {', '.join('sm_' + str(a) for a in archs)} (CUDA " + f"{meta.get('cuda', '?')})") + return eng + + +def update_installed_engine(url_base) -> None: + """An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain + START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model + still running, no ready-made engine for this GPU) the installed engine is kept and starts as before.""" + eng = ROOT / "engine" + info = eng / "BUILD.json" + if not info.exists() or not (eng / EXE).exists(): + return + meta_text = info.read_text() + meta = json.loads(meta_text) + if meta.get("backend") == "hip" and WIN: # AMD on Windows: the ready-made HIP engine, when older + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if meta.get("source") == "prebuilt" and ver < WIN_HIP_MIN_ENGINE: + try: + g = next((x for x in amd_gpus() if amd_problem(x) is None), None) + if g is None: + raise RuntimeError("no supported AMD GPU found") + say(f" Updating the ready-made AMD engine ({meta.get('version')} -> " + f"{'.'.join(map(str, WIN_HIP_MIN_ENGINE))} or newer) ...") + if get_prebuilt_hip(url_base, g, updating=True) is None: + raise RuntimeError("not published yet") + except (Exception, SystemExit) as e: + warn(f"could not update the AMD engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " + "starting the installed one") + return + if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed + if meta.get("src") != source_hash(ENGINE_SOURCES): + try: + usable = [x for x in amd_gpus() if amd_problem(x) is None] + g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) + if g is None: + raise RuntimeError("no supported AMD GPU found") + # every architecture it was built for (a layer split across two families keeps both) + build_engine_hip({**g, "archs": [x for x in meta.get("archs", []) if x in AMD_ARCHS] or [g["arch"]]}, + get_llama_cpp(), meta.get("vision") or "none") + except (Exception, SystemExit) as e: + warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " + "starting the installed one") + return + ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + local = meta.get("source") == "local" + vision = meta.get("vision") or "none" + if local: # compiled here: is it older than the source (a git pull)? + if meta.get("src") == source_hash(ENGINE_SOURCES) and \ + (vision == "none" or meta.get("vision_src") == source_hash(VISION_SOURCES)): + return + elif ver >= MIN_ENGINE: + return + try: # a running engine cannot be replaced (Windows keeps it locked) + for x in (EXE, VEXE): + if (eng / x).exists(): + with open(eng / x, "r+b"): + pass + except OSError: + warn(f"engine {meta.get('version') or ''} is in use: close the model window and run this again to update it") + return + gpu = gpu_info() + if local: + try: # a failed compile must not stop the model from starting + if gpu is None: + raise RuntimeError("no NVIDIA GPU found") + gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *(int(x) for x in meta.get("archs", []))})} + build_engine(gpu, vision, False, get_llama_cpp()) + except (Exception, SystemExit) as e: + warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one") + return + new = None + if gpu is not None: + try: + new = get_prebuilt(url_base, gpu, "gpu", updating=True) + except Exception as e: # a failed download must not stop the model from starting + warn(f"updating the engine failed ({e})") + if new is None: + if not info.exists(): + info.write_text(meta_text) # get_prebuilt drops it before downloading: put it back + warn(f"could not update the engine: starting the installed {meta.get('version')}") + return + pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)") + + +def install_build_tools(gpu, yes): + """The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars).""" + archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])] + # #295: Pascal / Volta (STRATA_EXPERIMENTAL_SM60=1) need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70 + old = min(archs) < 75 + if old and max(archs) >= 120: + fail("one engine cannot be built for both an RTX 50 card (CUDA 13) and a Pascal/Volta card (CUDA 12.x)", + "choose the cards of one kind with --gpu / --gpus") + nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() + if old and (nvcc is None or cuda_v < (12, 0)): + fail("the experimental Pascal/Volta build (STRATA_EXPERIMENTAL_SM60=1) needs the NVIDIA CUDA Toolkit 12.x " + "(CUDA 13 cannot compile for these cards)", + "install CUDA 12.9 (or another 12.x; it can sit next to a newer one) from " + "https://developer.nvidia.com/cuda-toolkit-archive and run it again") + # RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220) + need_cuda = (13, 0) if max(archs) >= 120 else (12, 0) + vcvars = find_vcvars() if WIN else None + have_cc = vcvars is not None if WIN else shutil.which("g++") is not None + missing = [] + if not have_cc: + missing.append("Visual Studio 2022 Build Tools (C++)" if WIN else "the C++ compiler (build-essential)") + if nvcc is None or cuda_v < need_cuda: + missing.append("the NVIDIA CUDA Toolkit 13.0") + if not missing: + ok(f"build tools present (CUDA {cuda_v[0]}.{cuda_v[1]})") + return nvcc, vcvars + say(" The engine has to be compiled for your PC, which needs: " + " and ".join(missing) + ".") + say(" They can be installed now (about 8-10 GB, 15-40 minutes" + (", Windows will ask for permission" if WIN else + ", sudo will ask for your password") + ").") + if ask(" Install them now?", ["y", "n"], "y", yes) != "y": + fail("the build tools are needed", "install them yourself (see README.md) and run it again") + if WIN: + if shutil.which("winget") is None: + fail("winget (Windows package manager) is not available", + "install 'App Installer' from the Microsoft Store, or install the tools by hand (README.md)") + wg = ["winget", "install", "-e", "--source", "winget", "--accept-package-agreements", + "--accept-source-agreements", "--disable-interactivity"] + if not have_cc: + run([*wg, "--id", "Microsoft.VisualStudio.2022.BuildTools", "--override", + "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"], + check=False) + if nvcc is None or cuda_v < need_cuda: + run([*wg, "--id", "Nvidia.CUDA", "--version", "13.0"], check=False) + vcvars = find_vcvars() + else: + apt = shutil.which("apt-get") + if apt is None: + fail("missing: " + " and ".join(missing) + " (the automatic install is only done on Ubuntu/Debian)", + "install them with your distribution's packages (Arch: pacman -S base-devel cuda; nvcc is found on " + "PATH, in /usr/local/cuda* and in /opt/cuda*), then run it again") + if not have_cc: + run(["sudo", "apt-get", "install", "-y", "build-essential"]) + if nvcc is None or cuda_v < need_cuda: + osr = dict(line.split("=", 1) for line in open("/etc/os-release").read().splitlines() if "=" in line) + ver = osr.get("VERSION_ID", "").strip('"').replace(".", "") + if osr.get("ID") != "ubuntu" or ver not in ("2204", "2404"): + fail("the CUDA Toolkit can be installed automatically on Ubuntu 22.04 / 24.04 only", + "install it from https://developer.nvidia.com/cuda-downloads and run it again") + deb = Path("/tmp/cuda-keyring.deb") + download(f"https://developer.download.nvidia.com/compute/cuda/repos/ubuntu{ver}/x86_64/cuda-keyring_1.1-1_all.deb", + deb, "CUDA repository key") + run(["sudo", "dpkg", "-i", str(deb)]) + run(["sudo", "apt-get", "update"]) + run(["sudo", "apt-get", "install", "-y", "cuda-toolkit-13-0"]) + nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc() + if (WIN and find_vcvars() is None) or (not WIN and shutil.which("g++") is None): + fail("the C++ build tools did not install", "install them by hand (README.md) and run it again") + if nvcc is None or cuda_v < need_cuda: + fail("the CUDA Toolkit did not install", "install it from https://developer.nvidia.com/cuda-downloads, then run it again") + ok(f"build tools installed (CUDA {cuda_v[0]}.{cuda_v[1]})") + return nvcc, find_vcvars() if WIN else None + + +def cmake_build(src, bdir, target, defs, vcvars, bat_name): + cmake, ninja = find_tool("cmake"), find_tool("ninja") + if cmake is None or ninja is None: + fail("cmake / ninja not found after installing them", "run: .venv python -m pip install cmake ninja") + conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), + "-DCMAKE_BUILD_TYPE=Release", *defs] + build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] + # A failed build is tried once more: CUDA 13.0's ptxas now and then fails to parse a PTX file it just wrote, and + # the same command then gets past it (issue #45); a second attempt only compiles what is still missing. + if WIN: + bat = ROOT / bat_name + q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731 + bat.write_text(f'@echo off\r\ncall "{vcvars}" >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n' + f'echo (the build stopped - trying it once more)\r\n{q(build)} || exit /b 1\r\n', + encoding="utf-8") + run(["cmd", "/c", str(bat)]) + else: + run(conf) + if run(build, check=False).returncode != 0: + say(" (the build stopped - trying it once more)") + run(build) + + +ENGINE_SOURCES = ("CMakeLists.txt", "src", "include", "third_party/ggml") +VISION_SOURCES = ("tools/vision",) + + +def source_hash(parts) -> str: + """A fingerprint of the files a compiled engine is built from, kept in engine/BUILD.json: when a `git pull` + changes them, the engine is compiled again (issue #31).""" + h = hashlib.sha256(LLAMA_CPP_COMMIT.encode()) + for part in parts: + base = ROOT / part + for f in [base] if base.is_file() else sorted(x for x in base.rglob("*") if x.is_file()): + h.update(f.relative_to(ROOT).as_posix().encode() + b"\0" + f.read_bytes().replace(b"\r\n", b"\n")) + return h.hexdigest()[:16] + + +def engine_defs(archs) -> list: + """Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75.""" + return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 else [] + + +def prebuilt_vision(meta: dict, gpu: dict, vision: str) -> str: + """The image encoder to use with a ready-made engine (`meta`: its BUILD.json). The encoder can cover fewer cards + than the engine (0.1.30/0.1.31: no RTX 20 code, #331): such a card gets the CPU encoder - the same program - instead + of compiling one, which fails on most Windows PCs (no Visual Studio / CUDA toolkit); --build compiles it.""" + if vision != "gpu": + return vision + va = [int(x) for x in meta.get("vision_archs", meta.get("archs", []))] + if va and int(gpu["arch"]) not in va and not (meta.get("ptx") and int(gpu["arch"]) > max(va)): + warn(f"the ready-made image encoder has no code for your GPU (sm_{gpu['arch']}): it runs on the CPU instead " + "(images take longer; setup --build compiles one for your GPU)") + return "cpu" + return vision + + +def build_engine(gpu, vision, yes, llama) -> Path: + """Compile the engine (and, for images, the encoder) for this GPU; the results go to engine/. A compiled + engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes.""" + eng = ROOT / "engine" + eng.mkdir(exist_ok=True) + stamp = eng / "BUILD.json" + meta = json.loads(stamp.read_text()) if stamp.exists() else {} + want_vision = vision != "none" + local = meta.get("source") == "local" + src, vsrc = source_hash(ENGINE_SOURCES), source_hash(VISION_SOURCES) + archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) # every card the model runs on + built = {int(x) for x in meta.get("archs", [])} + # a card the engine has no code for (a GPU added with --gpus, #128) needs a compile even when the source is the + # same; the compile keeps the generations it was built for + new_arch = local and not set(archs) <= built + engine_ok = local and (eng / EXE).exists() and meta.get("src") == src and not new_arch + vision_ok = not want_vision or ((eng / VEXE).exists() and (not local or meta.get("vision_src") == vsrc)) + if engine_ok and vision_ok: + ok("engine already built for this PC") + return eng + if local: + archs = sorted(built | set(archs)) + nvcc, vcvars = install_build_tools({**gpu, "archs": archs}, yes) + cuda_archs = ";".join(str(x) for x in archs) + if not engine_ok: + say(" Compiling the engine for " + ", ".join(f"sm_{x}" for x in archs) + " (a card it had no code for; " + "10-20 minutes, once) ..." if new_arch else + " The engine's source changed: compiling it again (only what changed, a few minutes) ..." + if local and (eng / EXE).exists() else " Compiling the Strata engine for your GPU (10-20 minutes, once) ...") + cmake_build(ROOT, ROOT / "build", "strata", + ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", + f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs)], + vcvars, "build-strata.bat") + shutil.copy2(ROOT / "build" / EXE, eng / EXE) + if not vision_ok: + say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) + defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}"] + if vision == "gpu": + defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}"] + cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", defs, vcvars, "build-vision.bat") + shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE) + bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64) + dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()] + stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs, + "vision": vision, + "cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None}, indent=1)) + ok(f"engine compiled: {eng / EXE}") + return eng + + +# ------------------------------------------------------------------------------------------------ the data folder +# The model files - the GGUFs, the prepared packs and the MTP layer, 70-120 GB - live in a data folder NEXT TO the +# Strata folder (`Strata-data`), not inside it: updating Strata by unzipping a new copy used to give a new, empty +# folder and a full download again. Where it is, and which Strata folders this user ran, is kept in a small +# per-user file, so every Strata folder on the PC finds the same files. +DATA_ITEMS = ("models", "packs", "mtp") + + +LOW_RAM_HEADROOM_GB = 10 # RAM beside the experts: the OS, the engine's other buffers, the server +RESIDENT_ENGINE = (0, 1, 30) # the first engine with --resident-experts (the low-RAM mode's resident variant) + + +def low_ram_needed(model, ram) -> bool: + """The model's experts do not fit this PC's RAM with room left for the rest: they are then mapped from the pack's + experts.bin instead of copied into RAM (the low-RAM mode).""" + return ram < MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB + + +def low_ram_gpu_gb(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how many GB of the model's experts the GPU's cache holds: its VRAM minus ~5 GB for the dense weights, + buffers and a 32K context's KV cache, minus the KV cache of a longer context (in VRAM in the low-RAM mode: its RAM + has no room for KV streaming).""" + kv_tok = 13 * (576 if kv == "q4_0" else 1056) # bytes per context token: 12 QSA layers + the draft layer + longer = max(0, ctx - 32768) * kv_tok / 1e9 + return max(0.0, min(MODELS[model]["arena_gb"], vram_gb - 5 - longer)) + + +def low_ram_gpu_share(model, vram_gb, ctx=32768, kv="int8") -> float: + """About how much of the model's experts the GPU holds.""" + return low_ram_gpu_gb(model, vram_gb, ctx, kv) / MODELS[model]["arena_gb"] + + +def low_ram_resident(model, ram, vram_gb, ctx=32768, kv="int8") -> bool: + """In the low-RAM mode: the experts the GPU does not hold fit the RAM with the usual room beside them, so they are + copied into RAM once (the resident variant, `--resident-experts`) instead of being read through the OS file cache + (plain `--mmap-experts`, which a PC this short of RAM keeps re-reading from the SSD).""" + rest = MODELS[model]["arena_gb"] - low_ram_gpu_gb(model, vram_gb, ctx, kv) + return ram >= rest + LOW_RAM_HEADROOM_GB + + +def low_ram_fits(model, ram, vram_gb) -> bool: + """In the low-RAM mode: the experts the GPU does not hold fit the RAM left beside the rest (as file cache).""" + arena = MODELS[model]["arena_gb"] + return ram - 6 + max(0.0, vram_gb - 5) >= arena + + +def low_ram_one_gpu_why(model, ram, choice, sel=None) -> list[str]: + """#250: why the low-RAM mode recommends one GPU, with the RAM math that turned it on; #364 #384: and how to use + all of them (sel: the cards, for the --gpus example).""" + arena, need = MODELS[model]["arena_gb"], MODELS[model]["arena_gb"] + LOW_RAM_HEADROOM_GB + if choice == "auto": + why = [f"Why: {model}'s experts are {arena:.0f} GB and must fit in RAM with ~{LOW_RAM_HEADROOM_GB} GB beside " + f"them for the OS and the rest: {arena:.0f} + {LOW_RAM_HEADROOM_GB} = {need:.0f} GB, and this PC has " + f"{ram:.0f} GB.", + "So setup uses the low-RAM mode: the experts come from the model's file (copied into RAM as far as " + "it fits), the GPU holds the most-used ones."] + else: + why = [f"Why: you chose the low-RAM mode (--low-ram {choice}); without it {model} needs {arena:.0f} + " + f"{LOW_RAM_HEADROOM_GB} = {need:.0f} GB of RAM, this PC has {ram:.0f} GB."] + return why + ["Its resident variant (the experts the GPU does not hold copied into RAM once: steady RAM use) runs " + "on one GPU: the engine has no layer split for it yet.", + f"To use all the GPUs: --gpus {','.join(str(i) for i in sel) if sel else '0,1'} - the experts the " + "GPUs do not hold are then read through the OS file cache: faster in two reports (1.3-1.6x, #364 " + f"#384), but RAM can fill up to 0 free during long prompts. Or {need:.0f} GB of RAM or more, or a " + "smaller size."] + + +def low_ram_together(a, model, ram, gpu, chosen) -> bool: + """#364 #384: the low-RAM mode with several GPUs chosen. One GPU is recommended: the resident variant keeps the + experts the GPU does not hold in RAM (steady RAM use) and has no layer split. All the GPUs together read those + experts through the OS file cache instead (--mmap-experts) - 1.3-1.6x faster in those reports, but RAM can fill + up to 0 free during long prompts. An explicit --gpus (or an earlier install's cards) is kept; otherwise asked, + one GPU by default (--yes: one GPU, as before). True: all of them.""" + sel = [g["index"] for g in chosen] + names = " + ".join(gpu_name(g) for g in chosen) + if a.gpus: + warn(f"the low-RAM mode on {names}, as you chose (--gpus): the experts the GPUs do not hold are read through " + "the OS file cache (the resident variant has no layer split yet), and RAM can fill up to 0 free during " + "long prompts") + say(f" One GPU keeps them in RAM (steady RAM use, recommended): --gpu {gpu['index']}") + if a.low_ram == "resident": + warn("--low-ram resident has no layer split yet: the experts are read through the OS file cache instead") + return True + if a.low_ram != "resident" and not a.yes: + say() + for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): + say(" " + line) + say(f" 1) {gpu_name(gpu)} only: the experts it does not hold kept in RAM where they fit (recommended: " + "steady RAM use)") + say(f" 2) {names} together: the experts the GPUs do not hold read through the OS file cache - faster") + say(" in two reports (1.3-1.6x, #364 #384), but RAM can fill up to 0 free during long prompts") + if ask("Low-RAM mode: which GPUs?", ["1", "2"], "1", a.yes) == "2": + ok(f"the low-RAM mode on {names}: the experts read through the OS file cache, as you chose") + return True + warn("the low-RAM mode: using " + gpu_name(gpu) + " only") + return False + warn("the low-RAM mode: using " + gpu_name(gpu) + " only (recommended)") + for line in low_ram_one_gpu_why(model, ram, a.low_ram, sel): + say(" " + line) + return False + + +def confirm_risk(msg, explicit, yes, stop, hint=None, question=" Go on anyway?", default="n") -> None: + """The owner's rule: setup recommends, it never forces. A choice setup expects to fail or run badly is said + plainly (msg), then asked (default n; `default` keeps an older question's own default), or with --yes taken as + consent when it was asked for explicitly (a flag such as --model or --gpus): --yes alone keeps the stop + (stop, hint). Returns when it goes on; the caller says what it does.""" + warn(msg) + if yes and explicit: + return + if ask(question, ["y", "n"], default, yes) != "y": + fail(stop, hint) + + +def confirm_paging(model, ram, choice, yes, explicit_model=False): + """The model's experts do not fit this PC's RAM and the low-RAM mode is off. #125: a warning and a question, not + a stop - the user may accept paging. Asked "no" by default, so an unattended --yes install stops here, unless + the low-RAM mode was turned off explicitly (--low-ram off, #250) or the size was (--model): that is the choice + already made.""" + need_gb, arena = MODELS[model]["ram_gb"], MODELS[model]["arena_gb"] + off = choice == "off" + confirm_risk(f"{model} needs about {need_gb} GB of RAM and this PC has {ram:.0f} GB: its experts alone are " + f"{arena:.0f} GB and must stay in RAM, so Windows/Linux will page part of them from disk. Expect it " + "to be much slower, and it may not start at all.\n A smaller size (Q2_0 or IQ2_XS) fits; more " + "RAM fixes it.", off or explicit_model, yes, + f"{model} needs about {need_gb} GB of RAM; this PC has {ram:.0f} GB", + "choose Q2_0 or IQ2_XS, or add RAM" + ("" if off else f"; or --model {model} --yes (or --low-ram off " + "--yes) to install it anyway"), + " Install it anyway?", "y" if off else "n") + warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose" + (" (--low-ram off)" if off else + " (--model)" if explicit_model else "")) + + +def ctx_ram_need(model, ctx, low_ram=False): + """#406: the RAM (GB) setup estimates for a long context with IQ3_XXS / IQ3_S: their experts + the context's + 8-bit KV cache + 24 GB of room for everything else (the 0.1.29 arithmetic, counted). None where the context does + not count against RAM by this rule: the other sizes, and the low-RAM mode (its KV cache stays in VRAM).""" + if model not in ("IQ3_XXS", "IQ3_S") or low_ram: + return None + return MODELS[model]["arena_gb"] + ctx * 13 * 1056 / 1e9 + 24 + + +def ram_ctx(model, ram, low_ram=False) -> int: + """#406: the longest context the RAM rule recommends: 128K, or longer where the estimate fits this PC's RAM. It + is part of the recommended default (the smaller of it and the GPU's rule); a longer choice is kept, with a note.""" + return max(c for c in CONTEXTS if c <= 131072 or (ctx_ram_need(model, c, low_ram) or 0) <= ram) + + +def settings_path() -> Path: + if WIN: + return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" + + +def load_settings() -> dict: + try: + return json.loads(settings_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def save_settings(s: dict) -> None: + try: + settings_path().parent.mkdir(parents=True, exist_ok=True) + settings_path().write_text(json.dumps(s, indent=1), encoding="utf-8") + except OSError as e: + warn(f"could not save {settings_path()} ({e})") + + +def has_data(folder: Path) -> bool: + for d in DATA_ITEMS: + try: + if (folder / d).is_dir() and any((folder / d).iterdir()): + return True + except OSError: + pass + return False + + +def other_installs(settings: dict) -> list: + """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders + next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" + cands = [Path(p) for p in settings.get("installs", [])] + for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)): + try: + for d in base.iterdir(): + if d.is_dir() and d.name.lower().startswith("strata"): + cands.append(d) + cands += [c for c in d.iterdir() if c.is_dir() and c.name.lower().startswith("strata")] + except OSError: + pass + found = [] + for d in cands: + try: + d = d.resolve() + if d != ROOT and d not in found and (d / "setup.py").is_file(): + found.append(d) + except OSError: + pass + return found + + +def same_drive(a: Path, b: Path) -> bool: + try: + return os.stat(a).st_dev == os.stat(b).st_dev + except OSError: + return False + + +def move_into(src: Path, dst: Path) -> None: + """A rename into the data folder (same drive: instant); a folder merges into one already there, keeping what the + destination has. Whatever cannot be moved (a file in use) stays where it is.""" + if not dst.exists(): + try: + dst.parent.mkdir(parents=True, exist_ok=True) + os.replace(src, dst) + return + except OSError: + if not src.is_dir(): + return + dst.mkdir(parents=True, exist_ok=True) + if src.is_dir() and dst.is_dir(): + for c in list(src.iterdir()): + move_into(c, dst / c.name) + try: + src.rmdir() + except OSError: + pass + + +def repoint_config(cfg_file: Path, old: Path, new: Path) -> None: + """A config whose model files moved from `old` to `new` points at them there (each path only if its file is + now there and no longer at the old place).""" + try: + cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return + + def fix(v): + if isinstance(v, list): + return [fix(x) for x in v] + if isinstance(v, dict): + return {k: fix(x) for k, x in v.items()} + if isinstance(v, str): + for d in DATA_ITEMS: + o = str(old / d) + nv, no = os.path.normcase(v), os.path.normcase(o) # Windows: C:\ and c:\ are the same place + if nv == no or nv.startswith(no + os.sep): + n = str(new / d) + v[len(o):] + if Path(n).exists() and not Path(v).exists(): + return n + return v + + new_cfg = fix(cfg) + if new_cfg != cfg: + write_config(cfg_file, new_cfg) + + +def data_folder(requested: str | None) -> tuple: + """(the data folder, folders on other drives that still hold model files). Moves the model files of this folder + and of earlier Strata folders on the same drive into the data folder, and points their configs there.""" + settings = load_settings() + dest = Path(requested).expanduser().resolve() if requested else \ + Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data" + try: + dest.mkdir(parents=True, exist_ok=True) + except OSError as e: # e.g. no write access next to the Strata folder + warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}") + dest = ROOT + elsewhere = [] + # #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data + # folder nested in any of them (an install that kept its models one level down) + sources = [ROOT, *other_installs(settings)] + if settings.get("data_dir") and Path(settings["data_dir"]) != dest: + sources.append(Path(settings["data_dir"])) + sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest] + seen = set() + for folder in sources: + key = os.path.normcase(str(folder)) + if key in seen: + continue + seen.add(key) + if folder == dest or not has_data(folder): + continue + if not same_drive(folder, dest): + elsewhere.append(folder) # another drive: used where it is (no 70 GB copy) + continue + # the downloads merge file by file (the same file wherever it came from); a prepared pack or MTP layer moves + # whole or not at all, so two copies are never mixed + if (folder / "models").is_dir(): + move_into(folder / "models", dest / "models") + for item in [*((folder / "packs").glob("*") if (folder / "packs").is_dir() else []), folder / "mtp"]: + rel = item.relative_to(folder) + if item.exists() and not (dest / rel).exists(): + move_into(item, dest / rel) + for d in ("packs",): + try: + (folder / d).rmdir() # empty now + except OSError: + pass + for c in folder.glob("strata-*.json"): + repoint_config(c, folder, dest) + if has_data(folder): + elsewhere.append(folder) # in use, or a copy the data folder already has + warn(f"some model files are still in {folder} (in use, or already in {dest})") + else: + ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") + installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()] + save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) + return dest, elsewhere + + +def write_config(path: Path, cfg: dict): + """A run config, written whole or not at all (#459): to a temporary file first, then moved over the old one, so + a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, path) + + +def readable_config(path: Path) -> bool: + """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" + text = None + try: + text = path.read_text(encoding="utf-8-sig") + if isinstance(json.loads(text), dict): + return True + why = "not a JSON object" + except OSError as e: + why = e.strerror or str(e) + except ValueError: # JSONDecodeError, or bytes that are not UTF-8 + why = "the file is empty" if text is not None and not text.strip() else "not valid JSON" + warn(f"skipped the earlier config {path} ({why}): setting this copy up without it") + return False + + +def previous_config(elsewhere_first: list, settings: dict): + """The most recently used model config of another Strata folder on this PC, for a folder that has none yet. One + that does not parse (an empty or cut-off file, #459) is skipped with a warning: the newest readable one is used, + and with none this copy is set up as a fresh install.""" + cands = [] + for folder in [*elsewhere_first, *other_installs(settings)]: + cands += list(folder.glob("strata-*.json")) + cands = [c for c in dict.fromkeys(cands) if c.is_file()] + return next((c for c in sorted(cands, key=lambda p: p.stat().st_mtime, reverse=True) if readable_config(c)), None) + + +def choices_from_config(cfg_path: Path) -> dict: + """The setup answers a config was written with (family, size, context, KV, images, projection, network).""" + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + tag = cfg_path.stem[len("strata-"):] + family = next((f for f, d in FAMILIES.items() if d["tag"] and tag.startswith(d["tag"])), "qwen") + model = (tag[len(FAMILIES[family]["tag"]):] if tag.startswith(FAMILIES[family]["tag"]) else tag).upper() + if model not in MODELS: # (sizes have no dash except UD-Q4_K_XL: the old rule) + model = tag.split("-")[-1].upper() + a = cfg.get("args", []) + val = lambda k: a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None # noqa: E731 + vis = cfg.get("vision") + esp = val("--control-vector-scaled") + esp_path = esp.rsplit(":", 1)[0] if esp else None + return {"family": family, "model": model if model in MODELS else None, + "context": int(val("--max-context")) if val("--max-context") else None, + "kv": val("--kv") if val("--kv") in ("int8", "q4_0") else None, + "vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none", + "esp": ("on" if Path(esp_path).name == ESP_VECTOR.name else esp_path) if esp_path else "off", + "host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"), + "layer_split": cfg.get("layer_split")} + + +def find_in(roots: list, rel: str): + """The first of roots/rel that exists.""" + for r in roots: + if (r / rel).exists(): + return r / rel + return None + + +# ------------------------------------------------------------------------------------------------ start +def installed_configs(): + return sorted(ROOT.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + + +def source_version() -> str: + """The engine version the source tree builds (CMakeLists.txt's project version).""" + m = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8")) + return m.group(1) if m else "0" + + +def engine_version(exe: Path) -> tuple: + """The version in the engine folder's BUILD.json, or else the one compiled into the binary. A locally compiled + engine is not necessarily the source's version: when compiling a `git pull` fails, the previous engine is kept + (issue #49).""" + try: + meta = json.loads((Path(exe).parent / "BUILD.json").read_text()) + except (OSError, ValueError): + meta = {} + v = str(meta.get("version") or "") + if not v: # the version compiled into the binary: 0.1.13 and newer + try: # carry it, so a binary without it is older + m = re.search(rb"engine=(\d+\.\d+\.\d+)\n", Path(exe).read_bytes()) + v = m.group(1).decode() if m else "0.1.12" + except OSError: + v = "0" + return tuple(int(x) for x in v.split(".")[:3] if x.isdigit()) + + +def is_wsl() -> bool: + return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower() + + +def hardware_key(cfg: dict) -> str: + """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting + (the context's KV cache and the image encoder take VRAM from the expert cache).""" + sel = cfg.get("gpu") + gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}] + g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)} + a = cfg.get("args", []) + ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?" + return "|".join([g.get("name", "?"), f"{g.get('vram_gb', 0):.0f}GB", cpu_info()[0], f"{ram_gb():.0f}GB", + cfg.get("model_name", "?"), ctx, "images" if "--vision" in a else "text"]) + + +def calibrate_config(cfg_path: Path) -> bool: + """Measure the engine's hardware-dependent settings on this PC (tools/calibrate.py), write them into the run + config and remember them per PC and model in the settings file, so an update or a reinstall keeps them.""" + sys.path.insert(0, str(ROOT / "tools")) + import calibrate as CAL + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + say() + say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the") + say(" draft depth, the CPU threads). It takes about 5-10 minutes; the PC is busy meanwhile.") + try: + since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0 + except OSError: + since = 0 + try: + res = CAL.run(cfg, say=say) + except Exception as e: # never stops an install: the defaults stay + warn(f"the tuning did not finish ({e}): the default settings stay") + why = CAL.engine_error(cfg.get("log"), since) # #447: the engine's own reason, not only "see the log" + if why: + say(f" the engine said: {why}") + return False + cfg["args"] = CAL.apply(cfg["args"], res["settings"]) + write_config(cfg_path, cfg) + st = load_settings() + st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"), + "date": time.strftime("%Y-%m-%d")} + save_settings(st) + if res["settings"]: + ok("tuned for this PC: " + ", ".join(f"{k} {v}" for k, v in res["settings"].items()) + + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) + else: + ok("tuned for this PC: the default settings are already the fastest here" + + (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else "")) + return True + + +def saved_calibration(cfg: dict) -> dict | None: + """The settings an earlier calibration found for this PC and model, if any.""" + return (load_settings().get("calibration") or {}).get(hardware_key(cfg)) + + +def upgrade_config(cfg_path: Path, cfg: dict) -> dict: + """Configs written before v0.1.13 read prompts in fixed 2048-token chunks; the engine now picks the chunk + itself (`--prefill auto`: up to 8192, as the free VRAM allows - about 2x faster on long prompts). Under WSL, + KV streaming is dropped: its RAM copy must be pinned, and the driver pins only about 1 GB there.""" + a = cfg.get("args", []) + changed = False + ver = engine_version(cfg["exe"]) if "--prefill" in a else (0, 0, 0) + if "--prefill" in a and a[a.index("--prefill") + 1] == "2048" and ver >= (0, 1, 13): + a[a.index("--prefill") + 1] = "auto" + changed = True + ok("prompt reading: the engine now picks its chunk size (--prefill auto)") + elif "--prefill" in a and a[a.index("--prefill") + 1] == "auto" and (0, 0, 0) < ver < (0, 1, 13): + a[a.index("--prefill") + 1] = "2048" # an older engine kept after a failed update (issue #49) + changed = True + warn(f"the installed engine is {'.'.join(map(str, ver))}: prompts are read in 2048-token chunks until it is updated") + if is_wsl() and "--kv-resident" in a: + i = a.index("--kv-resident") + del a[i:i + 2] + changed = True + ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") + if changed: + write_config(cfg_path, cfg) + return cfg + + +def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, + layer_split=None, keep=None) -> int: + """keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab).""" + cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig"))) + missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] + if missing: + fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair") + keep = {k: v for k, v in (keep or {}).items() if v is not None} + if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored + cfg.update(keep) + write_config(cfg_path, cfg) + ok("saved for this model: " + ", ".join("api key" if k == "api_key" else f"{k.replace('_', ' ')} {v}" + for k, v in keep.items())) + cfg_path.touch() # the most recently used model + if "--mtp" in cfg["args"][:-1]: + refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) + cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port or cfg.get("port", 8080))] + if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) + if WIN: + hip_runtime_beside_exe(Path(cfg["exe"]).parent) # #468 #461: also fixes a 0.1.34 install + amd = amd_gpus() + if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on + cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) + built = (engine_archs_hip() or []) + miss = [x for x in cards if built and x["arch"] not in built] + if miss: + fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), + "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) + cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" + write_config(cfg_path, cfg) + gpu = None + elif gpu is not None: + cmd += ["--gpu", str(gpu)] + found = [] + use = gpu if gpu is not None else cfg.get("gpu") + if isinstance(use, list): + byid = {x["index"]: x for x in amd} + ok("GPUs: " + " + ".join(gpu_name(byid[i]) if i in byid else f"GPU {i} (not found)" for i in use) + + f" together, AMD (layers split {cfg.get('layer_split') or 'auto'})") + else: + g = next((x for x in amd if x["index"] == (use if use is not None else x["index"]) + and amd_problem(x) is None), None) + if g is not None: + ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)") + else: + found = gpus() + if cfg.get("backend") == "hip": + pass + elif isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on + check_gpus(gpu, found, yes=yes, named=True) + cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" + write_config(cfg_path, cfg) + gpu = None + elif gpu is not None: # --gpu N: this start only, on that card + check_gpus([gpu], found) + cmd += ["--gpu", str(gpu)] + else: + cfg = offer_together(cfg_path, cfg, yes) + use = gpu if gpu is not None else cfg.get("gpu") + if isinstance(use, list) and split_mmap(cfg): # #364 #384: a resident low-RAM config on several GPUs + write_config(cfg_path, cfg) + if cfg.get("backend") == "hip": + pass + elif isinstance(use, list): + check_gpus(use, found, "(chosen for this model) ", yes=True, named=True) + byid = {g["index"]: g for g in found} + cfg = ensure_engine_for([byid[i] for i in use], cfg_path, cfg, yes) + ok("GPUs: " + " + ".join(gpu_name(byid[i]) for i in use) + f" together (layers split {cfg.get('layer_split') or 'auto'})") + elif found: + g = next((x for x in found if x["index"] == use), None) if use is not None else max( + found, key=lambda x: (round(x["vram_gb"]), -x["index"])) + if g is not None: + cfg = ensure_engine_for([g], cfg_path, cfg, yes) + ok("GPU: " + gpu_name(g)) + if open_browser: + cmd.append("--open") + gb = 0.0 + if "--native" in cfg["args"]: + try: + gb = Path(cfg["args"][cfg["args"].index("--native") + 1]).stat().st_size / 1e9 + except (OSError, IndexError): + pass + say() + say(" " + "-" * 100) + say(f" Starting {cfg.get('model_name', 'the model')}: it loads {f'about {gb:.0f} GB' if gb >= 1 else '34-55 GB'} " + "into RAM and locks part of it for the GPU.") + say(" While it does, YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES (longer the first time after a") + say(" restart). That is normal: please wait and don't close this window - the browser opens when it is ready.") + say(" Later, closing this window stops the model.") + say(" " + "-" * 100) + if not WIN and os.environ.get("STRATA_EXECV"): + # Replace this process instead of spawning a child. The Docker image sets STRATA_EXECV=1, + # so there the server is PID 1 and docker stop's SIGTERM reaches the process that can + # answer the engine with QUIT. Normal Linux starts keep spawning the server as a child. + os.execv(cmd[0], cmd) + return subprocess.call(cmd) + + +# the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept +OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens + + +DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin", "cyrillic": "draft_vocab_cyrillic.bin"} + + +def saved_draft_vocab(cfg_path: Path) -> str | None: + """The draft subset a model's config chose earlier (--draft-vocab), or None: a setup run again without the flag + rewrites the config, and would otherwise put the default subset back.""" + try: + v = json.loads(cfg_path.read_text(encoding="utf-8-sig")).get("draft_vocab") + except (OSError, ValueError, AttributeError): + return None + return v if v in DRAFT_VOCABS else None + + +def mtp_corrupt(mtp: Path, env=None) -> bool: + """#327: True when the MTP tensors an install fetched are not the pinned checkpoint's (tools/mtp_fetch.py verify, + which hashes only files that changed since they last checked out). A mirror that ignored range requests left the + shards' starts there instead, and the draft layer built from them accepted nothing - with no error anywhere.""" + if not (mtp / "tensors").is_dir(): + return False + r = subprocess.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "verify", "--out", str(mtp)], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + return r.returncode == 3 + + +def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None: + """The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137), `en` + (data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster) or + `cyrillic` (data/draft_vocab_cyrillic.bin: English/code and the whole Cyrillic script, for Ukrainian, Russian, + Bulgarian, Serbian... answers). + Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept.""" + new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin" + if not new.exists() or not rt.is_dir(): + return + if dst.exists(): + old = hashlib.sha256(dst.read_bytes()).hexdigest() + shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest() + for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()} + if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest(): + return + ok("draft layer: the token subset " + {"cjk": "with Chinese, Japanese and Korean", + "cyrillic": "with the Cyrillic script"}.get(choice, + "for English and code (less VRAM)")) + shutil.copyfile(new, dst) + + +def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict: + """The installed engine must have code for every card the model starts on: a card added later (--gpus with an + older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a + card gets the engine compiled for all of them, before the start.""" + missing = [g for g in cards if not engine_runs_on(g)] + if not missing: + return cfg + info = ROOT / "engine" / "BUILD.json" + meta = json.loads(info.read_text()) + say() + say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) + + ": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.") + main = gpu_info(cards[0]["index"]) + archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards}) + vision = meta.get("vision") or ("gpu" if (ROOT / "engine" / VEXE).exists() else "none") + build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp()) + dirs = json.loads(info.read_text()).get("cuda_dirs") or [] + cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs] + write_config(cfg_path, cfg) + return cfg + + +def write_run_script(model, cfg_path, port): + serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port), "--open"] + if WIN: + script = ROOT / f"run-{model.lower()}.bat" + script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" + + " ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8") + else: + script = ROOT / f"run-{model.lower()}.sh" + script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n", + encoding="utf-8") + script.chmod(0o755) + return script + + +# ------------------------------------------------------------------------------------------------ the rope config +def derived_factor(ctx: int, trained: int = 262144) -> float: + """The automatic extension factor: the FINAL context over the trained one, at least 1. + + Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a + switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. + """ + return max(1.0, float(ctx) / float(trained)) + + +def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): + """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. + + An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + when a reduction changed the context. Past the trained range an omitted method defaults to yarn - + llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the + magnitude correction keeps the attention temperature - and an omitted factor is derived from the + final context (final / trained, at least 1), as is an explicitly chosen method's missing factor + inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused + past the trained range (the setup will not configure a run it knows is out of spec) rather than + silently overridden. + """ + if ctx <= trained: + if scale is not None and scaling in (None, "none"): + raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " + "trained 262144, so there is nothing to scale)") + if scaling in (None, "none"): + return None, None # the stock model, by choice or by default + return scaling, scale if scale is not None else derived_factor(ctx, trained) + if scaling == "none": + raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " + "keeps the stock angles there - the model has never seen those positions, so the setup " + "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " + "linear, or rerun with --context 262144 or lower") + return scaling or "yarn", scale if scale is not None else derived_factor(ctx, trained) + + +# ------------------------------------------------------------------------------------------------ main +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5") + ap.add_argument("--model", choices=list(MODELS)) + ap.add_argument("--context", type=int) + ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], + help="the RoPE extension for a context past the model's trained 262144: linear (position " + "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " + "picks yarn; 'none' is refused for such a context") + ap.add_argument("--rope-scale", type=float, + help="the extension factor (default: the final context over the trained 262144, at least 1 - " + "1.5 for 384K, 2 for 512K, 1 inside the trained range)") + ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], + help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " + "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") + ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], + help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--experimental-speed-projection", metavar="on|off|GGUF", + help="EXPERIMENTAL, off by default: the control vector in data/experimental-speed-projection " + "(or another GGUF) as a projection on layers 4-44; see docs/DETAILS.md") + ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)") + ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (default: asked when several can be " + "used; with --setup it is saved, when starting it is for that start only)") + ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " + "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " + "Saved, also when starting (see docs/MULTI_GPU.md)") + ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"); " + "default auto, placed from each GPU's free VRAM") + ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " + "devices on your network (issue #26; set --api-key too)") + ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0)") + ap.add_argument("--data-dir", help="where the model files go (~70-120 GB): default Strata-data next to this folder, " + "remembered for every Strata folder on this PC") + ap.add_argument("--models-dir", help="where the GGUF files go (default: /models)") + ap.add_argument("--gguf-dir", help="use GGUF files you already have (a folder with every shard: " + "-00001-of-0000N.gguf ... -0000N-of-0000N.gguf)") + ap.add_argument("--yes", action="store_true", help="accept the recommended answers") + ap.add_argument("--setup", action="store_true", help="install another model or change settings") + ap.add_argument("--no-start", action="store_true", help="install only, do not start the model") + ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one") + ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL), + help="where the ready-made engine is (a URL folder or a local folder)") + ap.add_argument("--check", action="store_true", help="only check this PC and exit") + ap.add_argument("--calibrate", action="store_true", + help="tune the engine's settings for this PC (about 5-10 minutes), then start the model") + ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS), + help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English " + "and code only (~110 MiB less VRAM, English answers 1-2%% faster), cyrillic = English, code " + "and the Cyrillic script (Ukrainian, Russian... answers decode ~30%% faster)") + ap.add_argument("--low-ram", choices=["auto", "on", "off", "resident", "mmap"], default="auto", + help="read the model's experts from one file in its folder instead of copying them all into RAM " + "(for a PC with a big GPU and little RAM); auto: when the experts would not fit the RAM. In " + "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " + "else read through the OS file cache (mmap); resident / mmap force one of the two") + ap.add_argument("--resident-budget-gib", type=float, metavar="N", + help="UD-Q4_K_XL: the GiB of its experts kept in RAM (default: the RAM less 24 GB, 40 on 64 GB; " + "more is kept as you choose, with a note)") + ap.add_argument("--kv-streaming", choices=["auto", "on", "off"], default="auto", + help="from a 64K context: keep the KV cache in RAM and only the attention's window in VRAM (more " + "experts fit on the GPU); auto: when the RAM has room for it") + ap.add_argument("--backend", choices=["cuda", "hip"], + help="cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " + "Linux or Windows (chosen by itself when the PC has no NVIDIA card Strata can use)") + ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) + a = ap.parse_args() + if a.resident_budget_gib is not None and not a.resident_budget_gib > 0: + ap.error("--resident-budget-gib takes a number of GiB above 0, e.g. --resident-budget-gib 32") + if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) + if "," in a.gpu: + a.gpus, a.gpu = a.gpus or a.gpu, None + elif a.gpu.strip().isdigit(): + a.gpu = int(a.gpu) + else: + ap.error(f"--gpu takes a GPU number as nvidia-smi numbers them, e.g. --gpu 1 (or --gpus 0,2), not {a.gpu!r}") + say("Strata - Qwen3.8-Flash-Next on a normal PC (a GPU + system RAM + CPU)") + data, elsewhere = data_folder(a.data_dir) # the model files: in the data folder, found from any copy + roots = [data, *elsewhere] + if a.models_dir is None: + a.models_dir = str(data / "models") + + # ---- 0. already installed: just start it + have = installed_configs() + explicit = a.setup or a.model or a.family or a.check or a.no_start + if not have and not explicit: # a new copy of Strata (an update unzipped elsewhere): set it + prev = previous_config(elsewhere, load_settings()) # up like the last one, from the files already here + if prev is not None: + ch = choices_from_config(prev) + if ch["model"]: + say(f" Found your earlier install in {prev.parent} ({prev.stem[len('strata-'):]}): setting up this " + "copy the same way - the model files are reused, nothing big is downloaded.") + a.family, a.model, a.context = ch["family"], ch["model"], a.context or ch["context"] + a.kv = a.kv or ch["kv"] + a.vision = a.vision or ch["vision"] + a.experimental_speed_projection = a.experimental_speed_projection or ch["esp"] + a.host, a.api_key = a.host or ch["host"], a.api_key or ch["api_key"] + a.port = a.port or ch["port"] + if isinstance(ch.get("gpu"), list): # a layer split: set up across the same cards again + a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"]) + a.layer_split = a.layer_split or ch.get("layer_split") + else: + a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") + a.yes = True + global GPU_PICK + # starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start + # on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved + # choice, and asked once when the PC has cards that could share the model + run_gpu = start_gpus(a.gpus) or a.gpu + port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) + if have and a.calibrate and not (a.setup or a.model or a.family or a.check): + if not a.build: + update_installed_engine(a.prebuilt) + pick_cfg = have[0] + if len(have) > 1: + say() + for i, c in enumerate(have, 1): + say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") + pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1] + if not calibrate_config(pick_cfg): # #447: said again where it is not lost above the start + say() + warn("this PC is NOT tuned: the tuning failed (the reason is above); the model " + + ("keeps" if a.no_start else "starts with") + " the default settings") + return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) + if have and not (a.setup or a.model or a.family or a.check or a.no_start): + if not a.build: + update_installed_engine(a.prebuilt) + if len(have) == 1: + return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) + say() + for i, c in enumerate(have, 1): + say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}") + say(f" {len(have) + 1}) install another model / change settings") + pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes)) + if pick <= len(have): + return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split, + keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab}) + + # ---- 1. the PC + step(1, "checking your PC") + found = gpus() + amd = amd_gpus() + nv_ok = any(gpu_problem(g) is None for g in found) + amd_ok = [g for g in amd if amd_problem(g) is None] + hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok)) + if a.backend is None and nv_ok and amd_ok: + # both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon) + say() + say(" This PC has NVIDIA and AMD cards Strata can use:") + say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None) + + " (recommended)") + say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in amd_ok) + + f" ({'the ready-made AMD engine, no images' if WIN else 'compiled here, images on the CPU'}" + " - docs/AMD_HIP.md)") + hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2" + if a.check and not hip: + say(f" (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)") + if hip: # AMD: compiled here; Windows: ready-made + if WIN and a.gpus: + fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N") + say(" Your AMD GPUs:" if amd else " No AMD GPU found (" + ("Windows lists no AMD display adapter)." if WIN + else "the amdgpu driver's KFD topology is empty).")) + for g in amd: + say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + (amd_problem(g) or "can be used")) + usable = [g for g in amd if amd_problem(g) is None] + if not usable: + fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS}") + if a.gpus: # a layer split across these cards, the first one the main + chosen = amd_parse_gpus(a.gpus, amd) + gpu = chosen[0] + elif a.gpu is not None: + gpu = next((g for g in usable if g["index"] == a.gpu), None) + if gpu is None: + fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable)) + chosen = [gpu] + else: + gpu = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"])) + chosen = [gpu] + # the engine is compiled for every chosen card's architecture + gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})} + chosen = [gpu] + chosen[1:] + sel = [g["index"] for g in chosen] + multi = sel if len(sel) > 1 else [] + a.gpu = gpu["index"] if len(amd) > 1 else a.gpu + if multi: + ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") + ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['arch']} (AMD: docs/AMD_HIP.md)") + else: + if not found: + fail("no NVIDIA GPU found (nvidia-smi did not answer)", + "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC" + + (f"; AMD ({', '.join(AMD_ARCHS)}): --backend hip" if amd else "")) + if len(found) > 1 or gpu_problem(found[0]) is not None: + gpu_table(found) + sel = choose_gpus(a, found) # asked when two or more cards can share the model + multi = sel if len(sel) > 1 else [] + a.gpu = sel[0] # the main GPU: the checks and the sizing below are its + GPU_PICK = a.gpu + gpu = gpu_info(a.gpu) + chosen = [gpu_info(i) for i in sel] + gpu["archs"] = sorted({x["arch"] for x in chosen}) # the engine needs code for every one of them + if multi: + ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") + ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}") + if driver_major(gpu) < MIN_DRIVER: + fail(f"the NVIDIA driver is too old ({gpu['driver']}; {MIN_DRIVER} or newer is needed)", + "update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again") + if gpu["vram_gb"] < 11: + warn("less than 12 GB of VRAM: Strata will run, but most experts stay on the CPU and it will be slow") + ram = ram_gb() + cpu, avx2, avx512 = cpu_info() + need = min(d["ram_gb"] for d in MODELS.values()) + low_ok = low_ram_fits("IQ1_M", ram, gpu["vram_gb"]) and a.low_ram != "off" # the smallest model, mapped + if ram < need - 4 and not a.check and not low_ok: + # every model keeps ALL its experts in RAM (23+ GB); VRAM only holds a copy of the most-used ones, so a + # bigger GPU does not lower this. The owner's rule: a stop by default, a risk the user can take (--model + # with --yes, or y) + confirm_risk(f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB: Strata keeps all of " + "the model's experts in RAM (23-50 GB, whatever the GPU), so the OS will page them from disk. " + "Expect it to be very slow, and it may not start at all.", bool(a.model), a.yes, + f"RAM: {ram:.0f} GB - the smallest model (the Coder) needs about {need} GB", + "Strata keeps all of the model's experts in RAM (23-50 GB, whatever the GPU) and the GPU holds a " + "copy of the most-used ones: it needs 32 GB of RAM or more (48 GB for the full model); --model " + "NAME --yes installs one anyway") + warn(f"going on with {ram:.0f} GB of RAM, as you chose") + ok(f"RAM: {ram:.0f} GB" if ram >= need - 4 else f"RAM: {ram:.0f} GB (less than the {need} GB the smallest model needs)" + + ("; the GPU's VRAM makes up for it (the low-RAM mode)" if ram < need - 4 and low_ok else "")) + pf = page_file_gb() + if pf is not None and pf < 4: + warn(f"Windows' page file is {pf:.1f} GB: the graphics card's memory needs room there too (issue #60), so " + "the model may not start or may use less VRAM. Set it to \"System managed\": System > About > " + "Advanced system settings > Performance > Advanced > Virtual memory") + ok(f"CPU: {cpu} ({'AVX-512' if avx512 else 'AVX2' if avx2 else 'no AVX2'})") + if not avx2: + fail("this CPU has no AVX2; Strata needs at least AVX2") + if a.check: + say() + for m, d in MODELS.items(): + verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" + if d.get("budget"): + verdict = (f"EXPERIMENTAL, fits with {resident_budget_gib(m, ram)} GiB of its experts in RAM, the rest " + "read from the SSD" if ram >= d["ram_gb"] else "does not fit") + if hip: # #429: not run on AMD yet (its prompt kernels are CUDA-only) + verdict += " - NVIDIA only so far, untested on AMD" + elif low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": + verdict = (f"fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}% " + "of its experts, " + ("the rest stays in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) + else "the rest is read from the SSD as needed)")) + say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") + say("\nThis PC can run Strata. Run it again without --check to install.") + return 0 + + # ---- 2. the questions + step(2, "your choices") + fams = list(FAMILIES) + if a.family: + family = a.family + else: + for i, f in enumerate(fams, 1): + d = FAMILIES[f] + say(f" {i}) {d['title']:20s} {d['by']} - {d['about']}" + (" [experimental]" if d.get("experimental") else "")) + family = fams[int(ask("Which model?", [str(i) for i in range(1, len(fams) + 1)], "1", a.yes)) - 1] + fam = FAMILIES[family] + ok(f"model: {fam['title']}") + if fam.get("license"): + say(f" Its license: {fam['license']}") + say() + names = [m for m in MODELS if family in MODELS[m].get("families", ("qwen", "swift"))] + if a.model and a.model not in names: + # #444: say which family has that size, and (with --gguf-dir) which files Strata can run at all + elsewhere_fams = [f for f in FAMILIES if f in MODELS[a.model].get("families", ("qwen", "swift"))] + fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names) + + (f" (or {a.model}: " + ", ".join(f"--family {f} --model {a.model}" for f in elsewhere_fams) + ")" + if elsewhere_fams else "") + + (f".\n {SUPPORTED_GGUFS}" if a.gguf_dir else "")) + for i, m in enumerate(names, 1): + d = MODELS[m] + fit = "" if ram >= d["ram_gb"] else f" <- needs {d['ram_gb']} GB RAM, you have {ram:.0f}" + if d.get("budget"): + say(f" {i}) {m} {d['about']}; download {d['download_gb']:.0f} GB, keeps ~" + f"{resident_budget_gib(m, ram)} GB of its {d['arena_gb']:.0f} GB of experts in RAM{fit}") + continue + if low_ram_needed(m, ram) and low_ram_fits(m, ram, gpu["vram_gb"]) and a.low_ram != "off": + fit = (f" <- fits in the low-RAM mode (the GPU holds ~{100 * low_ram_gpu_share(m, gpu['vram_gb']):.0f}%, " + + ("the rest in RAM)" if low_ram_resident(m, ram, gpu["vram_gb"]) else "the rest from the SSD)")) + say(f" {i}) {m:8s} {d['about']}; download {d['download_gb']:.0f} GB, uses ~{d['arena_gb']:.0f} GB of RAM{fit}") + rec = str(names.index("IQ3_XXS") + 1) if ram >= 60 and "IQ3_XXS" in names else "1" + model = a.model or names[int(ask("Which size?", [str(i) for i in range(1, len(names) + 1)], rec, a.yes)) - 1] + budget = None + if MODELS[model].get("budget"): + # Unsloth's UD-Q4_K_XL: a RAM budget of experts, the rest from the GGUF on the SSD - not the low-RAM mode (no + # experts.bin: it would be another 77 GB on the disk), and one GPU (the budget mode has no layer split) + warn(f"{model} is EXPERIMENTAL (docs/UNSLOTH_Q4.md): most of its experts are read from the SSD while it " + "answers, so it is several times slower than the 2-3-bit models; quality checked against llama.cpp") + if hip: + # #429 (jkuepker): checked before the 111 GB download. The HIP engine has no prompt kernels for its + # Q4_K / Q5_K experts (STRATA_MMQ_KQUANTS is CUDA-only) and it has not been run on AMD: asked, not refused + confirm_risk(f"{model} has not been run on AMD cards yet: its prompt kernels are NVIDIA-only, so on " + f"{gpu_name(gpu)} long prompts read much more slowly, and it may not work at all", + bool(a.model), a.yes, f"{model} is NVIDIA-only so far", "choose one of the 2-3-bit models, " + f"or --model {model} --yes to try it on AMD anyway", " Try it anyway?") + warn(f"installing {model} on an AMD card, as you chose (please report how it runs)") + if ram < MODELS[model]["ram_gb"]: + confirm_risk(f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC has {ram:.0f} GB: " + f"its RAM budget would be {resident_budget_gib(model, ram)} GiB, so nearly every expert is " + "read from the SSD while it answers (very slow), and it may run out of RAM", + bool(a.model), a.yes, f"{model} needs {MODELS[model]['ram_gb']} GB of RAM or more; this PC " + f"has {ram:.0f} GB", f"choose one of the 2-3-bit models, or --model {model} --yes to " + "install it anyway", " Install it anyway?") + warn(f"installing {model} with {ram:.0f} GB of RAM, as you chose") + budget = budget_choice(model, ram, a.resident_budget_gib) + ok(f"RAM budget: {budget:g} GiB of {model}'s experts in RAM, the rest read from the model files on the SSD") + if a.low_ram not in ("auto", "off"): + warn(f"--low-ram {a.low_ram} does not apply to {model}: it always reads part of its experts from the files") + if multi: + warn(f"{model} runs on one GPU: using " + gpu_name(gpu) + " only") + multi, sel, chosen = [], [gpu["index"]], [gpu] + elif a.resident_budget_gib is not None: + warn(f"--resident-budget-gib is for UD-Q4_K_XL: {model} keeps all of its experts in RAM or in the low-RAM mode") + low_ram = budget is None and (a.low_ram in ("on", "resident", "mmap") or + (a.low_ram == "auto" and low_ram_needed(model, ram))) + if low_ram and multi and not low_ram_together(a, model, ram, gpu, chosen): + multi, sel, chosen = [], [gpu["index"]], [gpu] + # (the low-RAM mode's variant is decided once the context is known, below; on several GPUs it is the mapped one) + if not low_ram and budget is None and ram < MODELS[model]["ram_gb"] - 4: + confirm_paging(model, ram, a.low_ram, a.yes, bool(a.model)) + ok(f"size: {model}") + tag = fam["tag"] + model # names of the pack, config and start script + small = min(x["vram_gb"] for x in chosen) # each card keeps its layers' KV of the whole context + rec_ctx = 32768 if small < 14 else 65536 if small < 20 else 131072 + if budget is not None: # UD-Q4_K_XL: every GB of KV is a GB fewer of cached experts + rec_ctx = 8192 if small < 14 else 32768 + # #406: the RAM rule is part of the recommendation (the smaller of the two), no longer a cap over the user's choice + rec_ctx = min(rec_ctx, ram_ctx(model, ram, low_ram)) + if a.context: + ctx = a.context + else: + say() + say(" Context length = how much text the model can see at once (your chat, files, tool output).") + say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") + for i, c in enumerate(CONTEXTS, 1): + need_c = ctx_ram_need(model, c, low_ram) + note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ + (" (experimental: setup adds rope scaling)" if c > 262144 else "") + \ + (f" (needs ~{need_c:.0f} GB RAM, this PC has {ram:.0f}: may run out of memory)" + if c > 131072 and need_c is not None and need_c > ram else "") + say(f" {i}) {c // 1024}K tokens{note}") + ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], + str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + # #406 #364: a context past the RAM rule (an explicit --context, a pick in the list, or the earlier install's) is + # kept, with what it risks. It used to become 128K: users ran 256K fine where setup's estimate said no. + need_gb = ctx_ram_need(model, ctx, low_ram) + if need_gb is not None and ram < need_gb and ctx > 131072: + warn(f"{ctx // 1024}K with {model} needs ~{need_gb:.0f} GB of RAM by setup's estimate " + f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest); this PC has " + f"{ram:.0f}. Kept as you chose: it may be slower or run out of RAM under load. {rec_ctx // 1024}K is the " + "recommended size.") + scaling = a.rope_scaling + if ctx > 262144 and scaling is None and not a.yes: + # the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested + # here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. + say() + say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") + say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") + say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") + say(" --rope-scaling.") + scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) + try: + scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) + except ValueError as e: + fail(str(e)) + if scaling is not None: + origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None + else "as requested") + ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})") + ok(f"context: {ctx} tokens") + # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) + kv = "fp16" if ctx <= 8192 else (a.kv or "int8") + if ctx > 8192 and not a.kv and not a.yes: + say() + say(" KV cache precision (the model's memory of the conversation):") + say(" 1) 8-bit (recommended: what every published number was measured with)") + say(" 2) 4-bit half the memory (about 4% faster at 128K), but measurably less precise on long") + say(" documents; long-context lookups (needle tests) still pass") + kv = ["int8", "q4_0"][int(ask("KV cache?", ["1", "2"], "1", a.yes)) - 1] + if ctx > 8192: + ok(f"KV cache: {'8-bit' if kv == 'int8' else '4-bit (Hadamard-rotated)'}") + if fam.get("vision") is False: + vision = "none" + if a.vision not in (None, "no", "none"): + warn(f"images are not available with {model} yet: off") + elif hip: + vision = hip_vision(a.vision) + elif a.vision: + vision = {"yes": "gpu", "no": "none"}.get(a.vision, a.vision) + else: + say() + say(" Images: the model can also read pictures (screenshots, photos, scanned pages). This adds a 0.9 GB") + say(" download and keeps ~1.4 GB of VRAM free for the image encoder, so text is a few % slower.") + vision = "gpu" if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" + ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) + # The low-RAM mode's two variants. resident: the experts the GPU's cache does not hold (and, as far as RAM allows, + # the ones the prompt path borrows cache room from) are copied from the pack's experts.bin into RAM once, so + # nothing is read from the SSD while it answers (engine 0.1.30, --resident-experts; the engine falls back to mmap + # with a warning when they do not fit the RAM it finds free). mmap: they are read through the OS file cache. + # The GPU's share: its VRAM less the dense weights and buffers, this context's KV cache and the image encoder's room. + resident = False + if low_ram: + arena = MODELS[model]["arena_gb"] + vram = gpu["vram_gb"] - (VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0) + share = low_ram_gpu_share(model, vram, ctx, kv) + rest = arena - low_ram_gpu_gb(model, vram, ctx, kv) + resident = a.low_ram == "resident" or (a.low_ram != "mmap" and low_ram_resident(model, ram, vram, ctx, kv)) + if multi: # #364 #384: every chosen card's share (the image encoder on the main one), the mapped variant + held = min(arena, low_ram_gpu_gb(model, vram, ctx, kv) + + sum(low_ram_gpu_gb(model, x["vram_gb"], ctx, kv) for x in chosen[1:])) + share, resident = held / arena, False + ok(f"low-RAM mode on {len(chosen)} GPUs: {model}'s experts ({arena:.0f} GB) are read from the model folder " + f"through the OS file cache instead of a copy in RAM ({ram:.0f} GB); the GPUs hold ~{100 * share:.0f}% " + "of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " + "with enough RAM (a faster SSD and a smaller size help)") + elif resident: + ok(f"low-RAM mode: the GPU holds ~{100 * share:.0f}% of {model}'s experts ({arena:.0f} GB) and the other " + f"~{rest:.0f} GB stay in RAM ({ram:.0f} GB), read once from a copy in the model folder") + else: + ok(f"low-RAM mode: {model}'s experts ({arena:.0f} GB) are read from the model folder through the OS file " + f"cache instead of a copy in RAM ({ram:.0f} GB); the GPU holds ~{100 * share:.0f}% of them") + if share < 0.6: + warn("most of the experts are read from the SSD while it answers: expect it to be much slower than " + "with enough RAM (a faster SSD and a smaller size help)") + # EXPERIMENTAL: the experimental-speed-projection control vector (data/experimental-speed-projection), off unless + # chosen here; with it loaded, the web app and the API switch it off per request + esp = None + esp_choice = (a.experimental_speed_projection or "").strip() + if family in ("qwen", "coder"): # the Coder: the same model's residual stream + if not esp_choice: + say() + say(" EXPERIMENTAL - speed projection: a small control vector applied while the model runs (layers 4-44).") + say(" It changes how the model answers: its package describes it as a refusal-direction projection (the") + say(" model declines far fewer requests). Off unless you choose it; when on, the web app can switch it off") + say(" per chat. Details: data/experimental-speed-projection/README.md") + esp_choice = "on" if ask("Turn on the experimental speed projection?", ["y", "n"], "n", a.yes) == "y" else "off" + if esp_choice.lower() not in ("off", "no", "n", "0"): + esp = ESP_VECTOR if esp_choice.lower() in ("on", "yes", "y", "1") else Path(esp_choice).expanduser().resolve() + if not esp.is_file(): + fail(f"the experimental speed projection's vector is missing: {esp}") + ok("experimental speed projection: " + ("ON (experimental)" if esp else "off")) + elif esp_choice.lower() not in ("", "off", "no", "n", "0"): + warn("the experimental speed projection is made for the original Qwen3.8-Flash-Next, not Swift 1.5: left off" + if family == "swift" else f"the experimental speed projection is not tested with {model}: left off") + models_dir = Path(a.gguf_dir) if a.gguf_dir else Path(a.models_dir) / tag + shards = gguf_dir_shards(models_dir, fam, model) if a.gguf_dir else \ + [models_dir / fam["file"].format(q=model, i=i) for i in range(1, fam.get("shards", 2) + 1)] + problem = gguf_dir_problem(models_dir, shards[0], fam, model) if a.gguf_dir else None + if problem: # #444: files Strata cannot run, or another choice's files + fail(*problem) + if not a.gguf_dir and not all(sh.exists() and done(sh) for sh in shards): + for r in elsewhere: # already downloaded in a Strata folder on another drive + cand = [r / "models" / tag / sh.name for sh in shards] + if all(c.exists() and done(c) for c in cand): + models_dir, shards = cand[0].parent, cand + ok(f"model files found in {models_dir}") + break + for s in shards: # #173: a whole file copied in by hand has no finish mark + if s.exists() and not done(s) and whole_shard(s): + mark(s, "whole (checked against its own tensor directory)") + have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards) + # #425 (jctaborda): a download that resumes needs room only for what is still missing - the finished shards and + # the .part files already on the disk count + on_disk = sum(f.stat().st_size for s in shards for f in (s, s.with_name(s.name + ".part")) if f.is_file()) / 1e9 + to_fetch = 0 if a.gguf_dir or have_model else max(MODELS[model]["download_gb"] - on_disk, 0) + need = to_fetch + 8 + \ + (40 if model == "Q2_0" and avx512 and family == "qwen" else 0) + (1 if vision != "none" else 0) + \ + (MODELS[model]["arena_gb"] + 1 if low_ram and not (model == "Q2_0" and avx512 and family == "qwen") else 0) + if free_gb(models_dir) < need: + fail(f"not enough free disk space in {models_dir}: need ~{need:.0f} GB" + + (f" ({on_disk:.0f} GB of the model is already there)" if on_disk >= 1 and not have_model else ""), + "use --models-dir on a bigger drive") + + # ---- 3. python packages + step(3, "Python packages") + pip_install(requirement_lines() if REQUIREMENTS.exists() else PY_PACKAGES, + "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil") + + # ---- 4. the engine + step(4, "the Strata engine") + llama = get_llama_cpp() + ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)") + if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler) + eng = None if a.build else get_prebuilt_hip(a.prebuilt, gpu) + if eng is None: + fail("no ready-made AMD engine for this Strata version" + (" (--build)" if a.build else ""), + "compiling it on Windows: tools\\hip\\build_windows.bat makes strata-windows-x64-hip.zip, then run " + "START-HERE.bat --backend hip --prebuilt (docs/AMD_HIP.md)") + gpu = hip_card(eng, gpu, amd) + a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu + else: + eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision) + if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text()).get("source") != "local": + pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)") + if vision != "none" and not (eng / VEXE).exists(): + warn("the ready-made engine has no image encoder: compiling it") + eng = None + else: + vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text()), gpu, vision) + if eng is None: + eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama) + meta = json.loads((eng / "BUILD.json").read_text()) + if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH + lib_dirs = [str(d) for d in hip_lib_dirs(eng)] + else: + lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs() + engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit()) + if budget is not None and engine_ver < UNSLOTH_ENGINE: # checked before the 111 GB download + fail(f"{model} needs engine {'.'.join(map(str, UNSLOTH_ENGINE))} or newer; this one is {meta.get('version')}", + "update Strata (or compile the engine with --build) and run setup again") + ok(f"engine: {eng / EXE}") + + # ---- 5. the model files + step(5, f"downloading {fam['title']} {model}") + if not a.gguf_dir: + for s in shards: + if s.exists() and done(s): + ok(f"{s.name} already downloaded") + continue + # the original's shard 2 is the same file for all its sizes and the Coder: reuse one that is already here + other = [p for p in Path(a.models_dir).glob("*/Qwen3.8-Flash-Next-GSQ-RCO-*-00002-of-00002.gguf") if done(p)] + if family in ("qwen", "coder") and s.name.endswith("00002-of-00002.gguf") and other and not s.exists(): + try: + os.link(other[0], s) + mark(s) + ok(f"{s.name} shared with {other[0].parent.name} (identical file)") + continue + except OSError: + pass + download(fam["hf"].format(q=model) + s.name, s) + check_shards(shards) + for s in shards: # the experimental Unsloth file: pinned sizes and SHA-256 + if s.name in fam.get("sha256", {}): + verify_sha256(s, *fam["sha256"][s.name]) + ok("model files present") + mmproj = Path(a.models_dir) / fam["mmproj"] + if not mmproj.exists(): + mmproj = find_in(roots, f"models/{fam['mmproj']}") or mmproj + if vision != "none": + if not mmproj.exists() and a.gguf_dir and (Path(a.gguf_dir) / fam["mmproj"]).exists(): + mmproj = Path(a.gguf_dir) / fam["mmproj"] + else: + download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") + ok(f"vision encoder: {mmproj}") + + # ---- 6. the pack and the MTP draft layer + step(6, "preparing the model for Strata") + pack = find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) + if model == "Q2_0" and avx512 and family == "qwen": + # the Q2_0 experts repacked for the AVX-512 kernel (the measured speed): a one-time ~40 GB conversion + if not (pack / "index.txt").exists() or not (pack / "experts.bin").exists(): # index.txt is written last + say(" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...") + run([sys.executable, str(ROOT / "tools" / "strata_pack.py"), "build", "--gguf", str(shards[0]), + "--out", str(pack), "--skip-hash"], env=env) + run([sys.executable, str(ROOT / "tools" / "pack_index.py"), "--pack", str(pack)], env=env) + if not (pack / "tokenizer" / "vocab.json").exists(): + run([sys.executable, str(ROOT / "tools" / "strata_tokenizer.py"), "--gguf", str(shards[0]), + "--out", str(pack)], env=env) # writes /tokenizer/ + elif not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists(): + # every tensor as the GGUF stores it; the experts are read from the GGUF at start (seconds to build) + # (UD-Q4_K_XL: --compat-bf16 - its Q8_0 hyper-connection projections become BF16, the form the engine reads) + run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), + *fam.get("pack_args", [])], env=env) + if low_ram and not (pack / "experts.bin").exists(): + say(f" Writing the experts into one file for the low-RAM mode (one time, {MODELS[model]['arena_gb']:.0f} GB) ...") + run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), + "--experts-bin"], env=env) + ok(f"model prepared: {pack}") + mtp = (find_in(roots, "mtp/rt/experts.bin") or data / "mtp/rt/experts.bin").parent.parent + rt = mtp / "rt" + corrupt = (rt / "experts.bin").exists() and mtp_corrupt(mtp, env) + if corrupt: + warn("some MTP tensors are not the checkpoint's (a download mirror that ignored range requests, #327): " + "fetching them again and rebuilding the draft layer") + if corrupt or not (rt / "experts.bin").exists(): + say(" The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:") + say(" only its ~5 GB of MTP tensors are downloaded.") + run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], env=env) + run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0", + "--out", str(mtp / "mtp-q2_0.gguf")], env=env) + run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)], + env=env) + # a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, en) + draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json") + refresh_draft_vocab(rt, draft_vocab or "cjk") + ok(f"MTP draft layer: {rt}") + + # ---- 7. the start script + step(7, "writing the start script") + sys.path.insert(0, str(ROOT / "tools")) + from gguf_reader import GGUFFile # the PLE table's shard: shard 2 (original) or 1 (Swift) + ple = next((s for s in shards if any(t.name == "per_layer_token_embd.weight" for t in GGUFFile(s).tensors)), None) + if ple is None: + fail("the model has no per_layer_token_embd tensor (is this a Qwen3.8-Flash-Next GGUF?)") + # (a 4-shard file: the engine finds the PLE table's shard itself from shard 1, the measured setup) + args = ["--pack", str(pack), "--native", str(shards[0]), *(["--ple-gguf", str(ple)] if len(shards) <= 2 else []), + "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", + "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), + "--max-context", str(ctx)] + if scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor + args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"] + if ctx > 8192: + args += ["--kv", kv] + if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE: + resident = False # an engine from before --resident-experts would refuse it + ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through " + "the OS file cache (run setup again after the next engine update)") + if low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped + args += ["--resident-experts" if resident else "--mmap-experts"] + # KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions + # per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It + # costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 7.5 KB with 4-bit, so only when it fits. + kv_ram_gb = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9 # 12 QSA layers + the draft layer + # Hybrid K8V4 never streams its KV (mode 0 only, layer.hpp), so it is excluded from the WHOLE streaming + # decision rather than one threshold at a time - a future tier added to this chain cannot reintroduce the + # combination the engine refuses (PR review). + # --kv-streaming on|off overrides the RAM test (the owner's rule); k8v4 and WSL stay off - they cannot stream. + stream_fits = ram >= MODELS[model]["ram_gb"] + kv_ram_gb + 1 + if kv == "k8v4": + if ctx >= 65536: + ok("KV streaming off: not supported with --kv k8v4; the KV cache stays in VRAM") + if a.kv_streaming == "on": + warn("--kv-streaming on: the engine has no KV streaming with --kv k8v4 (it refuses the pair): off") + elif is_wsl() and ctx >= 65536: + ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM") + if a.kv_streaming == "on": + warn("--kv-streaming on: WSL cannot stream the KV cache (its RAM copy must be pinned, and the driver pins " + "only about 1 GB there): off") + elif ctx >= 65536 and a.kv_streaming == "off": + ok("KV streaming off, as you chose (--kv-streaming off): the KV cache stays in VRAM") + elif ctx >= 65536 and (stream_fits or a.kv_streaming == "on"): + args += ["--kv-resident", "32768"] + ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM") + if not stream_fits: + warn(f"KV streaming needs ~{kv_ram_gb:.1f} GB of RAM beside the ~{MODELS[model]['ram_gb']} GB {model} " + f"uses; this PC has {ram:.0f}. Kept as you chose (--kv-streaming on): it may page or run out of RAM " + "under load") + if budget is not None and a.resident_budget_gib is None: # its RAM comes out of the experts' budget + budget = resident_budget_gib(model, ram, kv_ram_gb) + ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)") + elif budget is not None and budget > resident_budget_gib(model, ram, kv_ram_gb): + warn(f"the KV cache's {kv_ram_gb:.1f} GB of RAM come on top of your {budget:g} GiB RAM budget (setup " + f"would take them out of it: {resident_budget_gib(model, ram, kv_ram_gb)} GiB); kept as you chose") + elif a.kv_streaming == "on": + warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") + if budget is not None: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N GiB kept in RAM + args += ["--resident-budget-gib", f"{budget:g}"] + if vision != "none": + args += ["--vision", "--vram-reserve-mib", str(VISION[vision]["reserve_mib"])] + if esp is not None: + # the package's profile, with llama.cpp's flags (the engine takes the same ones) + args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44", + "--cvec-mode", "project", "--cvec-dir", "per-layer"] + cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + "model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"), + "lib_dirs": lib_dirs, "port": port} + if hip: + cfg["backend"] = "hip" + # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% + # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the + # engine refuses any other one and falls back to plain hipBLAS) + table = hipblaslt_table(gpu["arch"], lib_dirs, meta.get("hipblaslt_version")) + if table: + cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)} + if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable + cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0" + if gpu["count"] > 1 or a.gpu is not None: + cfg["gpu"] = gpu["index"] # the engine is told this card (issue #51) + cfg["gpus_asked"] = True # chosen at setup: not asked again at start + if multi: # a layer split across these cards (the server adds the flag) + cfg["gpu"] = multi + cfg["layer_split"] = a.layer_split or "auto" + ok(f"layer split across GPUs {multi} ({cfg['layer_split']})") + if a.host: + cfg["host"] = a.host + if a.api_key: + cfg["api_key"] = a.api_key + if draft_vocab: + cfg["draft_vocab"] = draft_vocab + if vision != "none": + cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]), + "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]} + if vision == "cpu": + cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) + cfg_path = ROOT / f"strata-{tag.lower()}.json" + cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now + if cal is not None: + sys.path.insert(0, str(ROOT / "tools")) + import calibrate as CAL + cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {}) + ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else "")) + write_config(cfg_path, cfg) + script = write_run_script(tag, cfg_path, port) + # offered only when someone answers: --yes installs and adopted earlier installs are not held up by it + if cal is None and not hip and not a.no_start and not a.yes and ask( + "Tune Strata for this PC now? It measures a few engine settings (about 5-10 minutes; the PC is busy " + "meanwhile; later: START-HERE --calibrate)", ["y", "n"], "y", a.yes) == "y": + tuned = calibrate_config(cfg_path) + else: + tuned = None # not asked for: nothing to repeat below + ok(f"start script: {script.name}") + + say() + say("All set.") + say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") + say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") + if a.host and a.host not in ("127.0.0.1", "localhost"): + say(f" Other devices: the server window prints this PC's address (http://:{port}/)" + + ("" if a.api_key else " - no API key set: anyone on your network can use it")) + say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away") + if vision != "none": + say(" Images: send them in the chat page, in chat.py (/image ) or over the API") + if tuned is False: # #447: a failed tuning is repeated here, not only above + say(" Tuning: FAILED (the reason is above): the default settings stay - " + f"{'START-HERE.bat' if WIN else './setup.sh'} --calibrate tries again") + if a.no_start: + return 0 + return start(cfg_path, port) + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + say("\nstopped.") + sys.exit(1) diff --git a/engine/strata/setup.sh b/engine/strata/setup.sh new file mode 100755 index 00000000..d7bac954 --- /dev/null +++ b/engine/strata/setup.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Strata for Linux: the first run installs everything and starts the model; later runs just start it. +# Needs only an NVIDIA driver (or, for an AMD Radeon card, the kernel's amdgpu driver: see docs/AMD_HIP.md). +# Python (with venv) is installed through apt/dnf if it is missing (asks for sudo). +cd "$(dirname "$0")" || exit 1 +# Python 3.10+ that can make a venv WITH pip: Debian/Ubuntu ship `venv` without `ensurepip` (that is the separate +# python3-venv package), and a venv made without it has no pip +ok_py() { "$1" -c 'import sys, venv, ensurepip; sys.exit(0 if sys.version_info >= (3, 10) else 1)' 2>/dev/null; } +# a .venv from an earlier run that failed half-way has a python but no pip: start it again +if [ -x .venv/bin/python ] && ! .venv/bin/python -m pip --version >/dev/null 2>&1; then + rm -rf .venv +fi +if [ ! -x .venv/bin/python ]; then + PY="" + for c in python3 python; do + if command -v $c >/dev/null 2>&1 && ok_py $c; then + PY=$c; break + fi + done + if [ -z "$PY" ]; then + echo "Python 3.10+ with venv is needed; installing it (sudo will ask for your password) ..." + if command -v apt-get >/dev/null 2>&1; then + sudo apt-get update && sudo apt-get install -y python3 python3-venv python3-pip + elif command -v dnf >/dev/null 2>&1; then + sudo dnf install -y python3 python3-pip + elif command -v pacman >/dev/null 2>&1; then + sudo pacman -S --noconfirm python python-pip + fi + PY=python3 + if ! ok_py $PY; then + echo "Please install Python 3.10 or newer with venv (Ubuntu/Debian: sudo apt install python3-venv), then run" + echo "./setup.sh again." + exit 1 + fi + fi + # a private environment inside this folder (system Python stays untouched; newer distros refuse global pip) + $PY -m venv .venv || { rm -rf .venv; echo "could not create .venv: sudo apt install python3-venv"; exit 1; } +fi +exec .venv/bin/python setup.py "$@" diff --git a/engine/strata/src/artifact/dequant.cpp b/engine/strata/src/artifact/dequant.cpp new file mode 100644 index 00000000..ff058c0a --- /dev/null +++ b/engine/strata/src/artifact/dequant.cpp @@ -0,0 +1,123 @@ +// src/artifact/dequant.cpp - the `strata-dequant` CLI (dequantize a GGUF tensor and dump F32). +// The dequantizers themselves are header-only in include/strata/artifact/dequant.hpp. +#include "strata/artifact/dequant.hpp" + +#ifdef STRATA_DEQUANT_SELFTEST +int main(int argc, char** argv) { + if (argc < 2) { + std::printf("usage: dequant \n"); + return 2; + } + try { + strata::GgufFile g(argv[1]); + int checked = 0, bad = 0; + for (const auto& t : g.tensors()) { + if (t.type != 42) continue; // Q2_0 only for now + if (checked >= 8) break; + const uint8_t* base = g.tensor_data(t); + const uint64_t nblocks = t.elements() / 64; + for (uint64_t b = 0; b < nblocks && b < 64; ++b) { + const uint8_t* blk = base + b * 18; + float out[64]; + strata::dequantize_q2_0(blk, out); + const float d = strata::fp16_to_fp32(strata::read_u16(blk)); + // STRUCTURAL INVARIANT: every value must be exactly one of {-d, 0, d, 2d}. + for (int j = 0; j < 64; ++j) { + const float v = out[j]; + const bool ok = (v == -d) || (v == 0.0f) || (v == d) || (v == 2.0f * d) || (d == 0.0f); + if (!ok) { + ++bad; + if (bad < 4) + std::printf(" VIOLATION %s block %llu elem %d: v=%g d=%g\n", t.name.c_str(), + (unsigned long long)b, j, v, d); + } + } + } + if (checked == 0) { + // A folded checksum over the FIRST 64 blocks, for cross-checking against the Python + // implementation on identical bytes. A single implementation being self-consistent + // proves little - two disagreeing is what finds bugs (round 67). + double sum = 0, sumabs = 0; + const uint8_t* base = g.tensor_data(t); + for (uint64_t b = 0; b < nblocks && b < 64; ++b) { + float out[64]; + strata::dequantize_q2_0(base + b * 18, out); + for (int j = 0; j < 64; ++j) { + sum += out[j]; + sumabs += std::fabs(out[j]); + } + } + std::printf(" CHECKSUM %s sum=%.10g sumabs=%.10g\n", t.name.c_str(), sum, sumabs); + } + ++checked; + } + // Q5_0 cross-check on the same 64-block window gguf-py is given, using the first Q5_0 tensor. + for (const auto& t : g.tensors()) { + if (t.type != 6 && t.type != 20 && t.type != 14 && t.type != 12 && t.type != 13 && t.type != 11 && + t.type != 23) + continue; + const uint8_t* base = g.tensor_data(t); + const int bsz = + (t.type == 20) + ? 18 + : (t.type == 14 + ? 210 + : (t.type == 12 + ? 144 + : (t.type == 13 ? 176 : (t.type == 11 ? 110 : (t.type == 23 ? 136 : 22))))); + const int nel = + (t.type == 14 || t.type == 12 || t.type == 13 || t.type == 11 || t.type == 23) ? 256 : 32; + const uint64_t nb = t.elements() / (uint64_t)nel; + double sum = 0, sumabs = 0; + for (uint64_t b = 0; b < nb && b < 64; ++b) { + float out[256]; + if (t.type == 20) + strata::dequantize_iq4_nl(base + b * bsz, out); + else if (t.type == 14) + strata::dequantize_q6_K(base + b * bsz, out); + else if (t.type == 12) + strata::dequantize_q4_K(base + b * bsz, out); + else if (t.type == 13) + strata::dequantize_q5_K(base + b * bsz, out); + else if (t.type == 11) + strata::dequantize_q3_K(base + b * bsz, out); + else if (t.type == 23) + strata::dequantize_iq4_xs(base + b * bsz, out); + else + strata::dequantize_q5_0(base + b * bsz, out); + for (int j = 0; j < nel; ++j) { + sum += out[j]; + sumabs += std::fabs(out[j]); + } + } + std::printf(" CHECKSUM %s %s sum=%.10g sumabs=%.10g\n", t.type_name(), t.name.c_str(), sum, + sumabs); + float f8[256]; + if (t.type == 20) + strata::dequantize_iq4_nl(base, f8); + else if (t.type == 14) + strata::dequantize_q6_K(base, f8); + else if (t.type == 12) + strata::dequantize_q4_K(base, f8); + else if (t.type == 13) + strata::dequantize_q5_K(base, f8); + else if (t.type == 11) + strata::dequantize_q3_K(base, f8); + else if (t.type == 23) + strata::dequantize_iq4_xs(base, f8); + else + strata::dequantize_q5_0(base, f8); + std::printf(" REF first8:"); + for (int j = 0; j < 8; ++j) std::printf(" %.6g", f8[j]); + std::printf("\n"); + if (t.type == 23) break; // emit Q5_0 first, then IQ4_NL + } + std::printf("%s\n Q2_0 tensors spot-checked: %d\n symbolic invariant violations: %d -> %s\n", + argv[1], checked, bad, bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; + } catch (const std::exception& e) { + std::printf("ERROR: %s\n", e.what()); + return 1; + } +} +#endif diff --git a/engine/strata/src/artifact/gguf_reader.cpp b/engine/strata/src/artifact/gguf_reader.cpp new file mode 100644 index 00000000..5498ecd7 --- /dev/null +++ b/engine/strata/src/artifact/gguf_reader.cpp @@ -0,0 +1,67 @@ +// src/artifact/gguf_reader.cpp - the `strata-gguf` CLI. The reader itself is header-only in +// include/strata/artifact/gguf_reader.hpp; this file is just the entry point, so it cannot drift +// from the library it exercises. +#include "strata/artifact/gguf_reader.hpp" + +#ifndef STRATA_GGUF_MAIN_DISABLED +int main(int argc, char** argv) { + if (argc < 2) { + std::printf("usage: gguf_reader [--check]\n"); + return 2; + } + const bool check = (argc > 2 && std::string(argv[2]) == "--check"); + try { + strata::GgufFile g(argv[1]); + std::printf("%s\n", argv[1]); + std::printf(" version %u tensors %zu metadata %zu data_start %llu size %llu\n", g.version(), + g.tensors().size(), g.metadata().size(), (unsigned long long)g.data_start(), + (unsigned long long)g.file_size()); + + if (check) { + // Independent expectations, all established by earlier phases. + size_t n_blk = 0; + for (const auto& t : g.tensors()) + if (t.name.rfind("blk.", 0) == 0) ++n_blk; + std::printf(" blk.* tensors %zu globals %zu\n", n_blk, g.tensors().size() - n_blk); + std::printf(" Q2_0 %llu BF16 %llu F32 %llu\n", (unsigned long long)g.count_type("Q2_0"), + (unsigned long long)g.count_type("BF16"), (unsigned long long)g.count_type("F32")); + + // Every tensor's byte size must land inside the gap to the next tensor's offset, since + // GGUF aligns every tensor. That is the same bracket test tools/verify_q2_0_geometry.py + // uses, and it validates block_geometry() against the file rather than asserting it. + std::vector ordered; + for (const auto& t : g.tensors()) ordered.push_back(&t); + std::sort(ordered.begin(), ordered.end(), [](auto a, auto b) { return a->offset < b->offset; }); + size_t bad = 0, unknown = 0; + for (size_t i = 0; i < ordered.size(); ++i) { + const auto* t = ordered[i]; + int el = 0, by = 0; + if (!strata::block_geometry(t->type, el, by)) { + ++unknown; + continue; + } + if (t->elements() % (uint64_t)el) { + ++bad; + continue; + } + const uint64_t nb = t->elements() / (uint64_t)el * (uint64_t)by; + // The bracket is on the GAP to the next tensor's offset, not on that offset itself - + // offsets are relative to data_start, so the gap is a difference. Comparing against + // the raw offset flagged almost every tensor (213/214) while the same test in Python + // (tools/verify_q2_0_geometry.py) passed. + const uint64_t end = (i + 1 < ordered.size()) ? ordered[i + 1]->offset - t->offset + : g.file_size() - g.data_start() - t->offset; + if (!(nb <= end && end < nb + 32)) ++bad; + } + std::printf(" geometry bracket: %zu out of range, %zu types unknown\n", bad, unknown); + const std::string err = strata::check_architecture(g); + std::printf(" architecture guard: %s\n", err.empty() ? "PASS" : ("FAIL - " + err).c_str()); + if (bad) return 1; + } + return 0; + } catch (const std::exception& e) { + std::printf("ERROR: %s\n", e.what()); + return 1; + } +} +#endif // STRATA_GGUF_MAIN_DISABLED diff --git a/engine/strata/src/artifact/gguf_reader_test.cpp b/engine/strata/src/artifact/gguf_reader_test.cpp new file mode 100644 index 00000000..70f1bc2c --- /dev/null +++ b/engine/strata/src/artifact/gguf_reader_test.cpp @@ -0,0 +1,93 @@ +// src/artifact/gguf_reader_test.cpp - the reader refuses what it cannot arbitrate (synthetic GGUF, no model, +// no GPU). +// +// 1. two tensors with distinct names: the file opens and find() sees both; +// 2. the same name twice: refused at open, and the error names the tensor and the file - GGUF has no +// index to say which of the two a name means, and find() is first-match, so the alternative is a +// lookup that silently picks by position. +// +// The fixture is a minimal GGUF v3 written here (header, no metadata, two F32[8] tensors, 32-byte +// alignment), so the test needs neither gguf-py nor a shard. The file is closed before it is removed: +// on Windows an open mapping keeps it. +#include "strata/artifact/gguf_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +template void put(std::vector& b, T v) { + const auto n = b.size(); + b.resize(n + sizeof(T)); + std::memcpy(b.data() + n, &v, sizeof(T)); +} +void put_str(std::vector& b, const std::string& s) { + put(b, s.size()); + b.insert(b.end(), s.begin(), s.end()); +} + +// A GGUF v3 file of F32[8] tensors named `names`, laid out 32 bytes apart from a 32-byte-aligned data start. +std::filesystem::path write_gguf(const std::vector& names) { + std::vector b; + put(b, 0x46554747u); // "GGUF" + put(b, 3); + put(b, names.size()); // n_tensors + put(b, 0); // n_kv + for (size_t i = 0; i < names.size(); ++i) { + put_str(b, names[i]); + put(b, 1); // n_dims + put(b, 8); + put(b, 0); // F32 + put(b, 32 * i); // offset from data_start + } + b.resize((b.size() + 31) / 32 * 32 + 32 * names.size(), 0); + const auto path = std::filesystem::temp_directory_path() / "strata_gguf_reader_test.gguf"; + std::ofstream(path, std::ios::binary).write(reinterpret_cast(b.data()), (std::streamsize)b.size()); + return path; +} +} // namespace + +int main() { + std::printf("gguf_reader_test\n"); + { + const auto path = write_gguf({"blk.0.attn_q.weight", "blk.0.attn_k.weight"}); + std::string err; + size_t n = 0; + bool both = false; + try { + strata::GgufFile g(path.string()); + n = g.tensors().size(); + both = g.find("blk.0.attn_q.weight") && g.find("blk.0.attn_k.weight"); + } catch (const std::exception& e) { + err = e.what(); + } + std::filesystem::remove(path); + check(err.empty() && n == 2 && both, "distinct names: the file opens and find() sees both tensors"); + } + { + const auto path = write_gguf({"blk.0.attn_q.weight", "blk.0.attn_q.weight"}); + std::string err; + try { + strata::GgufFile g(path.string()); + } catch (const std::exception& e) { + err = e.what(); + } + std::filesystem::remove(path); + check(!err.empty(), "the same name twice: refused at open"); + check(err.find("blk.0.attn_q.weight") != std::string::npos, " the error names the tensor"); + check(err.find(path.filename().string()) != std::string::npos, " the error names the file"); + if (!err.empty()) std::printf(" (%s)\n", err.c_str()); + } + std::printf(g_fail ? "gguf_reader_test: %d FAILED\n" : "gguf_reader_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/core/concurrent_main.cpp b/engine/strata/src/core/concurrent_main.cpp new file mode 100644 index 00000000..ab5b5adb --- /dev/null +++ b/engine/strata/src/core/concurrent_main.cpp @@ -0,0 +1,197 @@ +// src/core/concurrent_main.cpp - do the CPU expert path and the GPU stream path actually run at once? +// +// L9 concluded that the two miss paths are INDEPENDENT RESOURCES - 42.55 GB/s of DRAM bandwidth for the CPU +// expert kernel and 28.9 GB/s of PCIe for the stream - and that running them together would cover a token's +// 552.7 MB of misses in 7.74 ms, which is what puts 100 tps inside reach on this Gen4 machine. +// +// THAT CLAIM HAS A HOLE. An H2D copy from PINNED host memory READS HOST DRAM to do it, so the bus path is not +// free of the resource the CPU path is bound by. If the two contend, the combined rate is not 42.55 + 28.9 and +// the 129 tok/s figure is optimistic; if they overlap cleanly, it stands. This measures it three ways in one +// process - CPU alone, GPU alone, both - because comparing two separately-measured rates is exactly the +// inference that has been wrong twice already in this ledger (L2's dependency chain, L8's bus-only ceiling). +// +// The CPU side is a READ LOOP over the same pinned arena rather than the real VNNI kernel, and that is +// deliberate: the question is whether the two paths contend for DRAM BANDWIDTH, and a read loop is a pure +// measurement of that demand, with no compute that could mask it. +#include "strata/core/pinned.hpp" +#include "strata/kernels/s_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// Volatile sink so the read loop cannot be optimised away; summed across threads and printed, so a compiler +// that removed the loads would produce a suspiciously round zero rather than a plausible number. +std::atomic g_sink{0}; + +struct Run { + double seconds = 0; + double cpu_gb = 0; // GB/s read by the CPU threads + double gpu_experts = 0; // experts streamed and computed by the GPU +}; + +} // namespace + +int main(int argc, char** argv) { + std::string path; + // 4096 planes = 2 GiB, which is 64x the 32 MB L3 on this CPU. At 0.1 GiB the read loop measured 206 GB/s - + // that is CACHE bandwidth, not DRAM, and it would have answered the contention question with a number about + // a different resource entirely. + int experts = 4096; + int cpu_threads = 6; + int gpu_roles = 256; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto val = [&]() -> const char* { + if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + if (a == "--file") path = val(); + else if (a == "--experts") experts = std::atoi(val()); + else if (a == "--cpu-threads") cpu_threads = std::atoi(val()); + else if (a == "--gpu-roles") gpu_roles = std::atoi(val()); + else { + std::fprintf(stderr, "usage: strata-concurrent --file experts.bin [--experts N] " + "[--cpu-threads N] [--gpu-roles N]\n"); + return 2; + } + } + if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } + + const long long n_in = 2560, n_out = 640; + const uint64_t role_codes = (uint64_t) n_out * n_in / 4; + const uint64_t plane_bytes = role_codes; // the CPU loop reads the same planes + + strata::core::PinnedArena arena((uint64_t) experts * role_codes); + if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } + { + std::ifstream f(path, std::ios::binary); + if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; } + for (int i = 0; i < experts; ++i) { + f.seekg((std::streamoff) i * 1382400); + f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes); + if ((uint64_t) f.gcount() != role_codes) { std::fprintf(stderr, "short read\n"); return 1; } + } + } + std::printf("arena %.2f GiB pinned; %d CPU threads; %d GPU roles\n", + (double) arena.capacity / (1024.0 * 1024 * 1024), cpu_threads, gpu_roles); + + uint8_t* d_codes = nullptr; + check(cudaMalloc(&d_codes, role_codes), "cudaMalloc codes"); + uint16_t* d_x = nullptr; + float *d_scales = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x"); + check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y"); + std::vector hx((size_t) n_in, 0x3C00); + std::vector hs((size_t) n_out * (size_t) (n_in / 64), 0.001f); + check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales"); + cudaStream_t s_copy{}, s_comp{}; + check(cudaStreamCreate(&s_copy), "stream copy"); + check(cudaStreamCreate(&s_comp), "stream compute"); + const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; + + // The CPU loop: read the whole arena, Nthreads ways, and sum bytes so nothing is elided. + auto cpu_work = [&](std::atomic& stop, std::atomic& bytes) { + uint64_t acc = 0, n = 0; + const uint8_t* p = arena.data(); + while (!stop.load(std::memory_order_relaxed)) { + // touch one byte per 64 - a stride that defeats prefetch into a pure streaming read + for (uint64_t i = 0; i < plane_bytes * (uint64_t) experts; i += 64) acc += p[i]; + n += plane_bytes * (uint64_t) experts; + } + bytes.fetch_add(n); + g_sink.fetch_add(acc); + }; + + // The GPU loop: stream each role plane on the copy stream while computing on the compute stream. + auto gpu_work = [&](int roles) { + cudaEvent_t ev[2]; + for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event"); + uint8_t* buf[2] = {d_codes, d_codes}; // one buffer is enough: the timing is what is measured + check(cudaMemcpyAsync(buf[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue"); + check(cudaEventRecord(ev[0], s_copy), "prologue event"); + for (int i = 0; i < roles; ++i) { + const int cur = i & 1, nxt = (i + 1) & 1; + if (i + 1 < roles) { + check(cudaMemcpyAsync(buf[nxt], arena.data() + (uint64_t) ((i + 1) % experts) * role_codes, + role_codes, cudaMemcpyHostToDevice, s_copy), + "copy"); + check(cudaEventRecord(ev[nxt], s_copy), "event"); + } + check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait"); + strata::kernels::s_gemv_split_async(d_x, buf[cur], d_scales, nullptr, d_y, n_in, n_out, form, 32, + (void*) s_comp); + } + check(cudaStreamSynchronize(s_comp), "sync comp"); + check(cudaStreamSynchronize(s_copy), "sync copy"); + for (int b = 0; b < 2; ++b) cudaEventDestroy(ev[b]); + }; + + auto run = [&](bool do_cpu, bool do_gpu, const char* name) { + std::atomic stop{false}; + std::atomic bytes{0}; + std::vector cpu; + check(cudaStreamSynchronize(0), "pre"); + const auto t0 = std::chrono::steady_clock::now(); + if (do_cpu) for (int t = 0; t < cpu_threads; ++t) cpu.emplace_back(cpu_work, std::ref(stop), std::ref(bytes)); + if (do_gpu) { + gpu_work(gpu_roles); + } else { + // CPU-only needs a REAL window. The first version let t0..t1 span nothing when there was no GPU + // work, so the threads were stopped immediately and the run reported 0.000 s and 0.00 GB/s. + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + } + const auto t1 = std::chrono::steady_clock::now(); + stop = true; + for (auto& t : cpu) t.join(); + Run r; + r.seconds = std::chrono::duration(t1 - t0).count(); + r.cpu_gb = (double) bytes.load() / 1e9 / r.seconds; + r.gpu_experts = do_gpu ? (double) gpu_roles / r.seconds : 0.0; + std::printf(" %-18s %7.3f s CPU read %6.2f GB/s GPU %7.1f roles/s\n", name, r.seconds, r.cpu_gb, + r.gpu_experts); + return r; + }; + + std::printf("\n mode wall CPU read GPU\n"); + const Run cpu_only = run(true, false, "CPU only"); + const Run gpu_only = run(false, true, "GPU only"); + const Run both = run(true, true, "BOTH"); + + std::printf("\n independence check (1.00 = perfectly shared, 0.00 = fully independent):\n"); + const double cpu_interference = cpu_only.cpu_gb > 0 ? 1.0 - both.cpu_gb / cpu_only.cpu_gb : 0.0; + const double gpu_interference = gpu_only.gpu_experts > 0 ? 1.0 - both.gpu_experts / gpu_only.gpu_experts : 0.0; + std::printf(" CPU throughput lost when the GPU also runs : %5.1f%%\n", cpu_interference * 100); + std::printf(" GPU throughput lost when the CPU also runs : %5.1f%%\n", gpu_interference * 100); + std::printf(" combined vs the sum of the parts : CPU %6.2f + GPU-equivalent vs %6.2f measured\n", + cpu_only.cpu_gb, both.cpu_gb); + std::printf("\n NOTE: the CPU side is a READ LOOP, not the VNNI kernel - it measures DRAM DEMAND, which is the\n" + " resource the question is about. L9's 129 tok/s assumes these two do not contend.\n"); + + cudaFree(d_codes); + cudaFree(d_x); + cudaFree(d_scales); + cudaFree(d_y); + cudaStreamDestroy(s_copy); + cudaStreamDestroy(s_comp); + return 0; +} diff --git a/engine/strata/src/core/conversation_cache_test.cpp b/engine/strata/src/core/conversation_cache_test.cpp new file mode 100644 index 00000000..f10b729b --- /dev/null +++ b/engine/strata/src/core/conversation_cache_test.cpp @@ -0,0 +1,213 @@ +#include "strata/core/conversation_cache.hpp" + +#include +#include + +using namespace strata::core; + +namespace { +int checks = 0; +void check(bool value, const char* description) { + ++checks; + if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); } +} +SavedConversation image(std::initializer_list ids, bool cvec = true) { + SavedConversation s; + s.live.ids = ids; + s.live.gdn.resize(64, 7); + s.cvec = cvec; + return s; +} +} + +int main() { + { + ConversationBuffer bytes; + const size_t first = ConversationBuffer::segment_bytes + 17; + const size_t peak = bytes.allocation_peak(first); + bytes.resize(first, 7); + check(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes"); + uint8_t* original = nullptr; + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { original = p; return true; }); + const size_t grown_peak = bytes.allocation_peak(first + 99); + bytes.resize(first + 99, 9); + bytes.visit(0, 1, [&](uint8_t* p, size_t, size_t) { + check(p == original, "appending preserves existing payload addresses"); return true; + }); + check(bytes.bytes() <= grown_peak, "growth including transient directory fits admission"); + std::vector tail(116); + check(bytes.read(tail.data(), ConversationBuffer::segment_bytes, tail.size()), "read spans segment boundaries"); + check(std::all_of(tail.begin(), tail.begin()+17, [](auto v){return v==7;}) && + std::all_of(tail.begin()+17, tail.end(), [](auto v){return v==9;}), "growth preserves prefix and initializes only suffix"); + auto copy = bytes; + bytes.resize(ConversationBuffer::segment_bytes + 10); + bytes.resize(first, 7); bytes.resize(first + 99, 9); + check(bytes == copy, "equality ignores differing segmentation after rewind and regrowth"); + check(!bytes.read(tail.data(), bytes.size()-1, 2), "range check rejects a truncated payload"); + check(bytes.allocation_peak(SIZE_MAX) == SIZE_MAX, "allocation estimate rejects overflow"); + } + { + ConversationBuffer bytes; + for (size_t n=1;n<=4096;++n) { + const size_t peak = bytes.allocation_peak(n*17); + bytes.resize(n*17,7); + check(bytes.bytes() <= peak,"small append stays within the predicted allocation peak"); + } + size_t segments = 0; + bytes.visit(0,bytes.size(),[&](const uint8_t*,size_t,size_t){++segments;return true;}); + check(segments <= 4,"thousands of small turns do not create thousands of restore transfers"); + } + { + ConversationKv layer; + layer.k.resize(400); + std::vector layers; + layers.push_back(std::move(layer)); + const size_t retained = layers.capacity()*sizeof(ConversationKv) + layers[0].bytes(); + const size_t parked = image({1,2,3}).bytes(); + ConversationCache cache(retained + parked, 4); + check(cache.put(image({1,2,3})), "park before retaining active storage"); + cache.retain(std::move(layers), 16); + check(cache.bytes() == retained + parked && cache.size() == 1, "active retained storage consumes bytes but no parked slot"); + cache.limit_reuse(9); cache.limit_reuse(12); + auto reuse = cache.take_reuse(); + check(reuse.unchanged_tokens == 9, "a later continuation cannot undo a rewind's dirty boundary"); + check(cache.bytes() == parked, "taking retained buffers releases their budget accounting"); + cache.retain(std::move(reuse.kv), 16); + check(!cache.can_fit(parked),"retained storage is counted when checking a capture without eviction"); + check(cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, + "optional reuse admission does not evict or release anything"); + check(!cache.can_fit(SIZE_MAX) && !cache.can_fit(1,SIZE_MAX),"non-mutating reservation rejects overflow"); + check(cache.make_room(parked), "reservation can discard optional active buffers"); + check(cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, + "pressure drops retained storage before evicting parked conversations"); + } + const std::vector a = {1, 2, 3, 4}, b = {9, 8, 7, 6}; + { + ConversationCache cache(1024, 2); + check(cache.put(image({1, 2, 3})), "park A"); + check(cache.put(image({9, 8, 7})), "park B"); + auto match = cache.best(a, {}, true); + check(match.tokens == 3 && match.live, "A/B/A: recover A"); + auto restored = cache.take(match.index); + check(restored.live.ids == std::vector({1, 2, 3}), "taking selected A preserves identity"); + check(cache.size() == 1 && cache.best(b, {}, true).tokens == 3, "B remains parked"); + check(cache.bytes() == image({9,8,7}).bytes(), "byte accounting after take"); + check(cache.put(std::move(restored)), "park returned A as newest"); + check(cache.put(image({5, 6})), "evict oldest by slot limit"); + check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A"); + check(cache.evictions() == 1, "eviction counter"); + } + { + auto s = image({1, 2, 3}); + ConversationCheckpoint cp; + cp.ids = {1, 2}; + s.checkpoints.push_back(cp); + ConversationCache cache(4096, 4); + cache.put(std::move(s)); + auto match = cache.best(std::vector{1, 2, 9, 4}, {}, true); + check(match.tokens == 2 && !match.live, "edited suffix falls back to parked checkpoint"); + check(cache.best(a, {}, true).tokens == 3, "live prefix beats shorter checkpoint"); + check(cache.best(a, {}, false).tokens == 0, "steering mode is isolated"); + check(cache.best(std::vector{1, 2}, {}, true).tokens == 0, "equal-length checkpoint cannot consume last token"); + check(cache.best(std::vector{1}, {}, true).tokens == 0, "short prompt cannot match"); + check(cache.best(std::vector{}, {}, true).tokens == 0, "empty prompt cannot match"); + cache.put(image({1, 2, 3})); + check(cache.best(a, {}, true).index == 1, "ties prefer most recently parked"); + } + { + auto s = image({1, 2, 3}); + s.live.imgs = {{1, 123}}; + ConversationCache cache(1024, 3); + cache.put(std::move(s)); + check(cache.best(a, {{1,123}}, true).tokens == 3, "same image can resume"); + check(cache.best(a, {{1,124}}, true).tokens == 0, "different image pixels invalidate same pad tokens"); + check(cache.best(a, {}, true).tokens == 0, "missing image invalidates prefix"); + check(cache.best(a, {{1,123},{2,45}}, true).tokens == 0, "additional image in cached prefix invalidates"); + check(cache.best(a, {{1,123},{3,45}}, true).tokens == 3, "image after cached prefix does not invalidate"); + } + { + const size_t one = image({1,2,3}).bytes(); + ConversationCache cache(one*2, 8); + cache.put(image({1,2,3})); cache.put(image({9,8,7})); + check(cache.bytes() == one*2, "budget holds two exact-sized images"); + auto held = cache.take(cache.best(a, {}, true).index); + check(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot"); + check(cache.size() == 0, "in-flight reservation evicts otherwise fitting B"); + check(cache.put(image({5,6,7}), held.bytes()), "insert with in-flight accounting"); + check(cache.bytes()+held.bytes() <= one*2, "exchange obeys byte budget"); + check(!cache.make_room(one+1, one), "oversized exchange rejected"); + check(cache.size() == 1, "oversized snapshot does not evict useful entries"); + auto huge = image({1}); huge.live.gdn.resize(one*3); + check(!cache.put(std::move(huge)), "oversized image rejected"); + check(cache.size() == 1, "oversized put leaves cache unchanged"); + check(!cache.make_room(0, one*2+1), "held larger than budget cannot underflow"); + } + { + // #342: MAIN -> SUB (9 turns) -> MAIN with 4 slots. Every SUB turn parks the previous turn's live state + // (its reply as generated, which the next request re-rendered) with a chain that holds that turn's + // boundary checkpoint; the copy a turn back adds only that stale tail and is dropped, so MAIN survives. + auto cp = [](std::vector ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; }; + auto with = [](std::vector prefix, std::initializer_list more) { + prefix.insert(prefix.end(), more); return prefix; + }; + const std::vector root = {1, 2, 3, 4}; + SavedConversation main = image({}); + main.live.ids = with(with(root, {10, 11, 12}), {13, 14}); + main.checkpoints = {cp(root), cp(with(root, {10, 11, 12}))}; + const size_t big = 1 << 20; + ConversationCache cache(big, 4); + check(cache.put(std::move(main)), "park MAIN"); + std::vector history = with(root, {20}); // SUB's conversation so far, re-rendered + std::vector chain = {cp(root)}; + for (int turn = 1; turn <= 9; ++turn) { + chain.push_back(cp(history)); // the turn boundary the next request resumes from + SavedConversation sub = image({}); + sub.live.ids = with(history, {900, (int32_t) turn}); // + the reply with its thinking (stale tail) + sub.checkpoints = chain; + check(cache.put(std::move(sub)), "park SUB turn"); + check(cache.size() <= 2, "one parked copy of SUB at a time"); + history = with(history, {30, (int32_t) turn}); // the reply as the next request renders it + } + check(cache.evictions() == 0 && cache.superseded() == 8, "8 superseded copies dropped, nothing evicted"); + const auto m = cache.best(with(with(root, {10, 11, 12}), {13, 14, 15}), {}, true); + check(m.tokens == 9 && m.live, "MAIN still restores in full"); + const auto s = cache.best(with(history, {40}), {}, true); + check(s.tokens == (int64_t) history.size() - 2, "SUB resumes from its last turn boundary"); + } + { + // what is NOT superseded: another conversation sharing only the root, an entry without checkpoints, the + // other steering mode, a branch whose deepest checkpoint the new chain does not hold + auto cp = [](std::vector ids) { ConversationCheckpoint c; c.ids = std::move(ids); return c; }; + ConversationCache cache(1 << 20, 8); + SavedConversation other = image({1, 2, 3, 4, 50, 51, 52}); + other.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 50, 51})}; + cache.put(std::move(other)); + cache.put(image({1, 2, 3, 4, 7, 7})); // no checkpoints + SavedConversation steered = image({1, 2, 3, 4, 60, 61}, false); + steered.checkpoints = {cp({1, 2, 3, 4, 60})}; + cache.put(std::move(steered)); + SavedConversation branch = image({1, 2, 3, 4, 60, 70, 71}); + branch.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60, 70})}; + cache.put(std::move(branch)); + SavedConversation incoming = image({1, 2, 3, 4, 60, 80, 81}); + incoming.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})}; + check(cache.put(std::move(incoming)), "park a conversation sharing roots with all of them"); + check(cache.size() == 5 && cache.superseded() == 0, "none of them is superseded"); + SavedConversation same_state = image({1, 2, 3, 4, 60, 70}); // live equal to the branch's deepest point + same_state.checkpoints = {cp({1, 2, 3, 4})}; + check(cache.put(std::move(same_state)) && cache.superseded() == 1 && cache.size() == 5, + "the live state equal to an entry's deepest checkpoint supersedes it"); + SavedConversation huge = image({1, 2, 3, 4, 60, 80}); + huge.checkpoints = {cp({1, 2, 3, 4}), cp({1, 2, 3, 4, 60})}; + huge.live.gdn.resize(2 << 20); + check(!cache.put(std::move(huge)) && cache.size() == 5 && cache.superseded() == 1, + "an oversized put drops nothing"); + } + { + ConversationCache disabled(0,4), no_slots(1024,0); + check(!disabled.enabled() && !no_slots.enabled(), "both disable switches"); + check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing"); + check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches"); + } + std::printf("conversation_cache_test: %d checks passed\n", checks); +} diff --git a/engine/strata/src/core/conversation_checked.hpp b/engine/strata/src/core/conversation_checked.hpp new file mode 100644 index 00000000..4355dc4e --- /dev/null +++ b/engine/strata/src/core/conversation_checked.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include + +namespace strata::core::conversation_detail { +inline bool add(size_t& total, size_t n) { + if (n > std::numeric_limits::max() - total) return false; + total += n; + return true; +} +inline bool product(size_t& out, std::initializer_list factors) { + size_t value = 1; + for (uint64_t factor : factors) { + if (factor > std::numeric_limits::max() || + (factor && value > std::numeric_limits::max() / factor)) return false; + value *= (size_t) factor; + } + out = value; + return true; +} +} // namespace strata::core::conversation_detail diff --git a/engine/strata/src/core/conversation_memory.cpp b/engine/strata/src/core/conversation_memory.cpp new file mode 100644 index 00000000..bd5740f2 --- /dev/null +++ b/engine/strata/src/core/conversation_memory.cpp @@ -0,0 +1,51 @@ +#include "strata/core/conversation_memory.hpp" + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +namespace strata::core { + +std::optional conversation_mem_available(std::istream& meminfo) { + std::optional result; + std::string line; + while (std::getline(meminfo, line)) { + std::istringstream fields(line); + std::string key, value, unit, extra; + if (!(fields >> key) || key != "MemAvailable:") continue; + if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {}; + uint64_t kb = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb); + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || + kb > std::numeric_limits::max() / 1024) return {}; + result = kb * 1024; + } + if (meminfo.bad() || (meminfo.fail() && !meminfo.eof())) return {}; + return result; +} + +std::optional conversation_available_memory() { +#if defined(_WIN32) + MEMORYSTATUSEX status{}; + status.dwLength = sizeof status; + if (GlobalMemoryStatusEx(&status)) return status.ullAvailPhys; + return {}; +#elif defined(__linux__) + std::ifstream meminfo("/proc/meminfo"); + if (!meminfo) return {}; + return conversation_mem_available(meminfo); +#else + return {}; +#endif +} + +} // namespace strata::core diff --git a/engine/strata/src/core/conversation_memory_test.cpp b/engine/strata/src/core/conversation_memory_test.cpp new file mode 100644 index 00000000..a8cb25d4 --- /dev/null +++ b/engine/strata/src/core/conversation_memory_test.cpp @@ -0,0 +1,66 @@ +#include "strata/core/conversation_memory.hpp" + +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +using namespace strata::core; +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +} + +int main() { + for (const char* text : {"", "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"}) { + std::istringstream input(text); + check(!conversation_mem_available(input), "missing/malformed telemetry is unknown"); + } + std::istringstream normal("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n"); + check(conversation_mem_available(normal) == 12345ULL * 1024, "only MemAvailable is counted"); + std::istringstream zero("MemAvailable: 0 kB"); + check(conversation_mem_available(zero) == 0, "zero available memory is known"); + std::istringstream broken("MemAvailable: 123 kB\n"); + broken.setstate(std::ios::badbit); + check(!conversation_mem_available(broken), "I/O failure declines admission"); + check(!conversation_memory_admit({}, 0, 0), "unknown fails closed even with zero floor"); + check(conversation_memory_admit(100, 40, 60), "exact allocation plus floor fits"); + check(!conversation_memory_admit(99, 40, 60), "one byte below required memory rejected"); + check(!conversation_memory_admit(59, 0, 60), "floor subtraction cannot underflow"); + check(conversation_memory_admit(60, 0, 60), "post-capture floor check"); + check(!conversation_memory_admit(100, std::numeric_limits::max(), 1), "allocation arithmetic cannot overflow"); + check(conversation_memory_admit(std::numeric_limits::max(), + std::numeric_limits::max(), 0), "maximal exact bound"); + check(!conversation_memory_admit(std::numeric_limits::max(), + std::numeric_limits::max(), 1), "maximal sum overflow rejected"); + // Test the real provider without assuming any particular amount of free RAM. + const auto available = conversation_available_memory(); + check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown"); +#if defined(_WIN32) + // Unknown must fail closed in production, but must not let a broken Windows provider pass this test. + // Compare with total physical memory, not a second available reading: other processes can allocate + // between calls. No pressure allocation or fixed free-memory assumption is needed. + MEMORYSTATUSEX physical{}; + physical.dwLength = sizeof physical; + check(GlobalMemoryStatusEx(&physical) != 0, "Windows physical-memory API is available"); + check(available.has_value() && *available <= physical.ullTotalPhys, + "Windows provider returns a known, physically bounded sample"); +#endif + std::printf("conversation_memory_test: %d checks passed\n", checks); +} diff --git a/engine/strata/src/core/conversation_snapshot.cpp b/engine/strata/src/core/conversation_snapshot.cpp new file mode 100644 index 00000000..0d8453d9 --- /dev/null +++ b/engine/strata/src/core/conversation_snapshot.cpp @@ -0,0 +1,269 @@ +#include "strata/core/conversation_snapshot.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "conversation_checked.hpp" +#include + +#include +#include +#include + +namespace strata::core { +namespace { +struct Layout { + int format; + int64_t cells, pooled_rows, page_size; + size_t data, scales, pooled, value_data, value_scales; +}; + +bool valid_extent(const QsaState& st, int64_t upto, std::string& error) { + const int64_t page = strata::kernels::qsa_real_shapes().page_size; + if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits::max() - (page - 1)) { + error = "conversation snapshot: invalid K/V extent"; + return false; + } + return true; +} + +bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) { + if (!valid_extent(st, upto, error)) return false; + if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8)) { + error = "conversation snapshot: hybrid K8V4 requires an identity layout and distinct format flags"; + return false; + } + const auto s = strata::kernels::qsa_real_shapes(); + const bool int8_keys = st.kv_int8 || st.kv_hybrid; + if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 || + (st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) { + error = "conversation snapshot: invalid K/V geometry"; + return false; + } + const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size; + const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) + : (size_t) g.head_dim * (int8_keys ? 1 : 2); + // Include the moving spare row, not only completed blocks. The checkpoint + // restore reconstructs that row when rewinding to an earlier prefix. + const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0; + // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293, + // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a + // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse. + // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.) + const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0; + l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, cells, pooled, s.page_size, 0, 0, 0, 0, 0}; + using conversation_detail::product; + if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) || + !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv, + int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) || + !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) { + error = "conversation snapshot: K/V byte count overflow"; + return false; + } + l.value_data = l.data; + l.value_scales = l.scales; + if (st.without_key) { l.data = 0; l.scales = 0; } + if (st.kv_hybrid) { + if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv, + (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) { + error = "conversation snapshot: hybrid V byte count overflow"; + return false; + } + l.value_scales = 0; + } + return true; +} + +std::array pools(const QsaState& st, bool resident = false) { + const bool host = st.kv_mode != 0 && !resident; + if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled}; + if (st.kv_q4) + return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled}; + if (st.kv_int8) + return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q, + host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled}; + return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled}; +} + +bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) { + if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages || + st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 || + (st.kv_mode == 0 && st.n_slots < st.n_pages) || + l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) { + error = "conversation snapshot: invalid K/V extent or missing authoritative host pool"; + return false; + } + if (st.kv_mode == 1) { + const auto& m = st.map; + if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block || + !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) { + error = "conversation snapshot: invalid streaming map"; + return false; + } + } + if (st.kv_mode == 2 && (!st.page_table || + (st.without_key ? !st.v_q || !st.v_scale : st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale + : !st.k_pool || !st.v_pool))) { + error = "conversation snapshot: invalid draft ring"; + return false; + } + return true; +} + +bool transfer(void* dst, const void* src, size_t n, std::string& error) { + if (!n) return true; + if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; } + // Default handles both device allocations and device-mapped host pool aliases. + const cudaError_t e = cudaMemcpy(dst, src, n, cudaMemcpyDefault); + if (e == cudaSuccess) return true; + error = std::string("conversation snapshot copy: ") + cudaGetErrorString(e); + return false; +} +} // namespace + +bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, size_t& bytes, std::string& error) { + Layout l{}; + if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false; + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + bytes = 0; + for (size_t i = 0; i < buffers.size(); ++i) { + const size_t n = buffers[i]->allocation_peak(sizes[i]); + if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) { + error = "conversation snapshot: segmented K/V allocation overflow"; + return false; + } + } + return true; +} + +size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) { + size_t bytes = 0; + std::string error; + return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0; +} + +bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error, + int64_t unchanged_tokens, size_t* reused_bytes) { + Layout l{}; + if (!layout(st, g, upto, index, l, error)) return false; + if (!valid(st, l, upto, error)) return false; + if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) { + error = "conversation snapshot: invalid unchanged prefix"; + return false; + } + const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size; + image.format = l.format; + image.cells = l.cells; + image.heads = g.n_head_kv; + image.head_dim = g.head_dim; + image.page_size = l.page_size; + image.pooled_rows = l.pooled_rows; + image.idx_dim = g.idx_key_dim; + const auto src = pools(st); + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + for (size_t i = 0; i < dst.size(); ++i) { + // Recopy the partial page and the indexer's moving spare row. Completed + // pages/rows strictly before the first rewritten token remain identical. + const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0) + : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0; + if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; } + dst[i]->resize(sizes[i]); + if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) { + return transfer(p, src[i] ? static_cast(src[i]) + at : nullptr, n, error); + })) return false; + if (reused_bytes) *reused_bytes += keep; + } + return true; +} + +bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + Layout l{}; + if (!layout(st, g, upto, index, l, error)) return false; + if (!valid(st, l, upto, error)) return false; + const std::array sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled}; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv || + image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows || + image.idx_dim != g.idx_key_dim) { + error = "conversation snapshot: incompatible K/V geometry"; + return false; + } + for (size_t i = 0; i < src.size(); ++i) + if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; } + const auto dst = pools(st); + for (size_t i = 0; i < src.size(); ++i) + if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; } + return true; +} + +bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, std::string& error) { + if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; + const std::array src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const auto dst = pools(st); + for (size_t i = 0; i < src.size(); ++i) + if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return transfer(static_cast(dst[i]) + at, p, n, error); + })) return false; + // VRAM slots still contain the outgoing conversation. Resolve must refill + // them from the restored authoritative pools before any attention reads. + if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr); + if (st.kv_mode == 2 && upto > 0) { + auto shapes = strata::kernels::qsa_real_shapes(); + shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim; + const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size; + strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st), + std::max(0, end - st.n_slots), end, st.n_slots, shapes, nullptr); + } + const auto status = cudaGetLastError(); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status); + return false; +} + +bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g, + int64_t upto, bool index, uint64_t& fingerprint, std::string& error) { + if (!conversation_kv_validate(image, st, g, upto, index, error)) return false; + std::array buffer; + uint64_t hash = 1469598103934665603ull; + auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) { + for (size_t offset = 0; offset < bytes;) { + const size_t n = std::min(buffer.size(), bytes - offset); + if (!transfer(buffer.data(), static_cast(device) + offset, n, error)) return false; + if (std::memcmp(buffer.data(), expected + offset, n) != 0) { + error = "conversation snapshot: restored K/V bytes differ"; + return false; + } + if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; } + offset += n; + } + return true; + }; + const std::array saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled}; + const auto authoritative = pools(st); + for (size_t i = 0; i < saved.size(); ++i) + if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) { + return compare(static_cast(authoritative[i]) + at, p, n, true); + })) return false; + if (st.kv_mode == 2 && image.cells > 0) { + const auto resident = pools(st, true); + const int64_t end = image.cells / image.page_size; + const int64_t begin = std::max(0, end - st.n_slots); + for (size_t i = 0; i < 4; ++i) { + if (saved[i]->empty()) continue; + const size_t page_bytes = saved[i]->size() / size_t(end); + for (int64_t page = begin; page < end; ++page) + if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes, + [&](const uint8_t* p, size_t n, size_t at) { + const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes; + return compare(static_cast(resident[i]) + offset, p, n, false); + })) return false; + } + } + fingerprint = hash; + return true; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/conversation_snapshot_test.cpp b/engine/strata/src/core/conversation_snapshot_test.cpp new file mode 100644 index 00000000..3792cd4b --- /dev/null +++ b/engine/strata/src/core/conversation_snapshot_test.cpp @@ -0,0 +1,292 @@ +#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; + +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +void cuda_check(cudaError_t e) { + if (e != cudaSuccess) { std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); std::exit(1); } +} +struct Fixture { + ModelGeometry g; + QsaState state; + std::vector device, host; + std::array sources{}; + std::array sizes{}; + + template void alloc(T*& p, size_t n, bool pinned = false) { + if (!n) return; + void* raw = nullptr; + if (pinned) { + cuda_check(cudaHostAlloc(&raw, n, cudaHostAllocMapped)); + host.push_back(raw); + void* mapped = nullptr; + cuda_check(cudaHostGetDevicePointer(&mapped, raw, 0)); + p = static_cast(mapped); + } else { + cuda_check(cudaMalloc(&raw, n)); device.push_back(raw); p = static_cast(raw); + } + } + 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}; + alloc(st.k_q,sizes[0]); alloc(st.v_q4,sizes[1]); 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) { + alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per); + if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);} + 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) alloc(st.k_q,slot_rows*per); + alloc(st.v_q,slot_rows*per); + if (!st.without_key) alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); + alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); + if (mode) { + alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true); + alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true); + } + 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 { + alloc(st.k_pool,slot_rows*per); alloc(st.v_pool,slot_rows*per); + if (mode) {alloc(st.host.k_pool,sizes[0],true); alloc(st.host.v_pool,sizes[1],true);} + sources[0]=mode?st.host.k_pool:st.k_pool; sources[1]=mode?st.host.v_pool:st.v_pool; + } + alloc(st.idx_pooled,sizes[4]); sources[4]=st.idx_pooled; + 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; + alloc(m.slot_block,st.n_slots*4); alloc(m.slot_stamp,st.n_slots*4); alloc(m.slot_ref,st.n_slots*4); + alloc(m.miss_block,st.n_slots*4); alloc(m.miss_slot,st.n_slots*4); alloc(m.ctl,kKvCtlInts*4); + } else if (mode==2) { + kv_ring_table(st.page_table,st.n_pages,st.n_slots,nullptr); + } + } + void fill(uint8_t salt) { + for (size_t i=0;i data(sizes[i]); + for (size_t j=0;j offset) + cuda_check(cudaMemset(static_cast(sources[i])+offset, salt, sizes[i]-offset)); + } + } + ~Fixture() { for (void* p:device) cudaFree(p); for (void* p:host) cudaFreeHost(p); } +}; +bool equal(const ConversationKv& a,const ConversationKv& b) { + return a.k==b.k && a.v==b.v && a.k_scale==b.k_scale && a.v_scale==b.v_scale && a.pooled==b.pooled; +} + +void full_session(int fmt, int mode, int experts) { + 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(); // the whole-model carve + std::string err; + ConversationStateSizes sizes; + check(conversation_state_sizes(g,sizes,err),"whole-session geometry sizes"); + main.alloc(ss.gdn_state,sizes.gdn); main.alloc(ss.ple_hist,sizes.ple); + main.alloc(main.state.idx_tail,sizes.tail); main.alloc(main.state.idx_dead,sizes.dead); + main.alloc(main.state.idx_block_pos,sizes.block_pos); + std::vector ids(65); + for (size_t i=0;i 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}}) + cuda_check(cudaMemset(p,salt,n)); + // A real indexer maintains its spare pooled row as a copy of idx_dead. + cuda_check(cudaMemcpy(main.state.idx_pooled+(ids.size()/4)*g.idx_key_dim, + main.state.idx_dead,sizes.dead,cudaMemcpyDeviceToDevice)); + cuda_check(cudaDeviceSynchronize()); + }; + fill(13); + ConversationCheckpoint checkpoint; + checkpoint.ids.assign(ids.begin(),ids.begin()+3); + check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint"); + checkpoint.used = 17; + checkpoints.push_back(std::move(checkpoint)); + const ConversationView view{ids,images,checkpoints,true}; + SavedConversation a,b,restored; + check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A"); + check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture"); + fill(177); + check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B"); + check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture"); + auto bad=a; bad.kv.back().k.pop_back(); + check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid, + "reject invalid late draft before any main-layer write"); + check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore"); + check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead && + equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state"); + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A"); + check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A"); + check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails && + restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos && + equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key"); + check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed"); + for (int64_t dirty : {65, 3, 0}) { + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); + ConversationKvReuse reuse{a.kv,65,dirty}; + const uint8_t* original = nullptr; + reuse.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); + main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); + cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); + ids.resize(70); + for (size_t i=65;i=4)==(reused>0),"only complete unchanged pages or rows are retained"); + incremental.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){ + check(p==original,"growth never reallocates the retained payload");return true; + }); + check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); + uint64_t fingerprint=0; + check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back"); + ids.resize(65); + } + check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint"); + std::vector spare(sizes.dead); + cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost)); + check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block"); + check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window"); +} +} + +int main() { + int devices=0; + if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; + for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { + std::string err; + ConversationKv invalid; + for (int unsupported : {1,2}) { + f.state.kv_mode=unsupported; + check(conversation_kv_bytes(f.state,f.g,9,true)==0,"hybrid streaming/ring rejected without block-mover abort"); + check(!conversation_kv_save(invalid,f.state,f.g,9,true,err),"hybrid streaming/ring capture fails closed"); + } + f.state.kv_mode=0; + } + { + std::string err; + ConversationKv invalid; + for (const int64_t bad : {-1LL, 97LL, (long long) std::numeric_limits::max()}) { + check(!conversation_kv_save(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid save extent before allocation"); + check(!conversation_kv_restore(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid restore extent before copying"); + check(conversation_kv_bytes(f.state,f.g,bad,mode!=2)==0,"invalid extent cannot overflow byte estimate"); + } + } + for (int64_t upto : {0,1,3,4,5,63,64,65,96}) { + const bool index=mode!=2; + std::string err; + f.fill(13); + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); + if (fmt==kKvValueInt8) { + check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q, + "V-only snapshot and resident/host pools have no K"); + auto wrong=a; wrong.format=kKvInt8; + check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state"); + } + check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload"); + f.fill(177); + check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B"); + check(upto==0 || !equal(a,b),"fixture changes state"); + check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"restore A over B"); + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A"); + check(equal(a,restored),"A/B/A byte-exact K/V and indexer state"); + uint64_t fingerprint = 0; + check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them"); + if (mode==1) { + std::vector table((size_t)f.state.n_pages); + cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost)); + check(std::all_of(table.begin(),table.end(),[](int32_t x){return x==-1;}),"stale VRAM pages invalidated"); + } + if (mode==2 && upto>0) { + const auto s=qsa_real_shapes(); + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + const size_t block=kv_block_bytes(s,fmt)/2; + // Codes and scales are separate in INT8; check code bytes here. + const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block; + const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q:fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; + std::vector got(code_block); + for (int64_t page=b0;page expected(code_block); + check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); + } + } + auto bad=a; bad.head_dim++; + check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry"); + if (fmt==kKvInt8) { + // #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state + // without it, nor the reverse + f.state.kv_rot=true; + ConversationKv rotated; + check(conversation_kv_save(rotated,f.state,f.g,upto,index,err),"save rotated INT8"); + check(!conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image into a rotated state rejected"); + f.state.kv_rot=false; + check(!conversation_kv_restore(rotated,f.state,f.g,upto,index,err),"rotated image into an unrotated state rejected"); + check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image still restores"); + } + if (!a.k.empty()) { + bad=a; bad.k.pop_back(); + check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload"); + } + } + } + for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512}) + full_session(fmt,mode,experts); + for (int experts : {256,512}) full_session(3,0,experts); + std::printf("conversation_snapshot_test: %d checks passed\n",checks); +} diff --git a/engine/strata/src/core/conversation_state.cpp b/engine/strata/src/core/conversation_state.cpp new file mode 100644 index 00000000..3e97827c --- /dev/null +++ b/engine/strata/src/core/conversation_state.cpp @@ -0,0 +1,305 @@ +#include "strata/core/conversation_snapshot.hpp" +#include "conversation_checked.hpp" + +#include +#include +#include + +namespace strata::core { +namespace { +using conversation_detail::add; +using conversation_detail::product; + +std::array geometry_key(const ModelGeometry& g) { + return {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}; +} + +bool fail(std::string& error, const char* message) { + error = std::string("conversation snapshot: ") + message; + return false; +} + +bool sync(std::string& error) { + const auto status = cudaDeviceSynchronize(); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot synchronize: ") + cudaGetErrorString(status); + return false; +} + +bool copy(void* dst, const void* src, size_t bytes, std::string& error) { + if (!bytes) return true; + if (!dst || !src) return fail(error, "missing running-state buffer"); + const auto status = cudaMemcpy(dst, src, bytes, cudaMemcpyDefault); + if (status == cudaSuccess) return true; + error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status); + return false; +} + +// The session's carve (#216): `qsa_states` keeps global ordinals and holds the owned ones +// [qsa_ord0, qsa_ord0 + qsa_alloc); `gdn_state` holds `gdn_alloc` rows. A whole-model session owns every layer. +size_t owned_qsa(const SessionState& ss) { return (size_t) std::max(ss.qsa_alloc, 0); } +const QsaState& owned(const SessionState& ss, size_t j) { return ss.qsa_states[(size_t) ss.qsa_ord0 + j]; } + +bool image_keys(const std::vector& images, size_t tokens) { + int64_t previous = -1; + for (const auto& image : images) { + if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false; + previous = image.start; + } + return true; +} + +bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens, + ConversationStateSizes& z, std::string& error) { + if (!conversation_session_sizes(g, ss, z, error)) return false; + if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) || + (owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets"); + for (size_t j = 0; j < owned_qsa(ss); ++j) { + const auto& st = owned(ss, j); + const auto block = strata::kernels::qsa_real_shapes().idx_block; + size_t pooled_bytes = 0; + if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled || + st.max_cells < 0 || tokens > (uint64_t) st.max_cells || + (tokens && tokens / (uint64_t) block >= (uint64_t) std::max(0, st.idx_pooled_rows)) || + !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)})) + return fail(error, "invalid indexer running-state target"); + } + return true; +} + +bool view_validate(const ConversationView& view, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false; + if (view.ids.empty() || !image_keys(view.images, view.ids.size()) || + std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; })) + return fail(error, "invalid live token/image metadata"); + for (const auto& c : view.checkpoints) { + if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() || + !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin())) + return fail(error, "checkpoint is not a live token prefix"); + if (!conversation_checkpoint_validate(c, ss, g, error)) return false; + size_t image = 0; + for (const auto& key : view.images) { + if ((uint64_t) key.start >= c.ids.size()) break; + if (image >= c.imgs.size() || !(c.imgs[image++] == key)) + return fail(error, "checkpoint image identity differs"); + } + if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs"); + } + return true; +} + +bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) { + size_t ids = 0, images = 0; + if (!product(ids, {c.ids.size(), sizeof(int32_t)}) || + !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false; + for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()}) + if (!add(total, n)) return false; + return true; +} +} // namespace + +bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) { + z = {}; + const auto key = geometry_key(g); + for (size_t i = 0; i < key.size(); ++i) + if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry"); + size_t recurrence = 0, convolution = 0; + if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) || + !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) || + !add(recurrence, convolution) || + !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) || + !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) || + !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1), + (uint64_t) g.idx_key_dim, sizeof(float)}) || + !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)})) + return fail(error, "running-state byte count overflow"); + z.block_pos = sizeof(int32_t); + size_t total = 0; + if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) || + !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) || + !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos})) + return fail(error, "indexer byte count overflow"); + return true; +} + +bool conversation_session_sizes(const ModelGeometry& g, const SessionState& ss, ConversationStateSizes& z, + std::string& error) { + if (!conversation_state_sizes(g, z, error)) return false; + const int64_t n_gdn = g.n_gdn_layers(), n_qsa = g.n_qsa_layers(); + if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 || + ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa - ss.qsa_ord0) + return fail(error, "invalid session layer carve"); + // z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range) + z.gdn = n_gdn > 0 ? z.gdn / (size_t) n_gdn * (size_t) ss.gdn_alloc : 0; + return true; +} + +bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; + const size_t layers = owned_qsa(ss); + if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) || + c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead || + c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size())) + return fail(error, "invalid checkpoint running-state payload"); + return true; +} + +bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, + const ModelGeometry& g, std::string& error) { + ConversationStateSizes z; + if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; + const size_t layers = owned_qsa(ss); + c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0); + c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos); + if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) || + !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false; + for (size_t j = 0; j < layers; ++j) { + const auto& st = owned(ss, j); + if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) || + !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) || + !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false; + } + return true; +} + +bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, + const ModelGeometry& g, std::string& error) { + if (!conversation_checkpoint_validate(c, ss, g, error)) return false; + ConversationStateSizes z; + if (!conversation_session_sizes(g, ss, z, error)) return false; + if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) || + !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false; + for (size_t j = 0; j < owned_qsa(ss); ++j) { + const auto& st = owned(ss, j); + if (!copy(st.idx_tail, c.tails.data() + j * z.tail, z.tail, error) || + !copy(st.idx_dead, c.dead.data() + j * z.dead, z.dead, error) || + !copy(st.idx_block_pos, c.block_pos.data() + j * z.block_pos, z.block_pos, error)) return false; + if (!c.ids.empty()) { + const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block; + if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + j * z.dead, z.dead, error)) return false; + } + } + const size_t tokens = c.ids.size(); + ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1; + ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1; + return sync(error); +} + +bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss, + const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) { + bytes = 0; + if (!view_validate(view, ss, g, error)) return false; + ConversationStateSizes z; + if (!conversation_session_sizes(g, ss, z, error)) return false; + size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0; + const auto qsa = (uint64_t) owned_qsa(ss); + if (!product(ids, {view.ids.size(), sizeof(int32_t)}) || + !product(images, {view.images.size(), sizeof(ConversationImageKey)}) || + !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) || + !product(layers, {qsa + 1, sizeof(ConversationKv)}) || + !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) || + !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow"); + for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0}) + if (!add(bytes, n)) return fail(error, "snapshot byte count overflow"); + for (const auto& c : view.checkpoints) + if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow"); + const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells + for (uint64_t i = 0; i <= qsa; ++i) { + const auto& st = i == qsa ? draft : owned(ss, (size_t) i); + const size_t n = conversation_kv_bytes(st, g, upto, i != qsa); + if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate"); + } + return true; +} + +bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, + const SessionState& ss, const ModelGeometry& g, + const QsaState& draft, size_t& bytes, std::string& error) { + if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false; + if (reuse.kv.empty()) return true; + const size_t layers = owned_qsa(ss) + 1; + if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 || + reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size())) + return fail(error, "invalid retained K/V prefix"); + for (size_t i = 0; i < layers; ++i) { + const bool index = i + 1 != layers; + const auto& st = index ? owned(ss, i) : draft; + if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false; + const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index); + size_t retained = 0; + if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false; + bytes -= fresh; + if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow"); + } + size_t directory = 0; + if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory)) + return fail(error, "retained K/V directory overflow"); + return true; +} + +bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, + const SessionState& ss, const ModelGeometry& g, + const QsaState& draft, std::string& error, + ConversationKvReuse reuse, size_t* reused_bytes) { + size_t estimate = 0; + if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false; + // Build into a new object so a failure cannot publish a partial snapshot. + SavedConversation captured; + captured.geometry = geometry_key(g); + captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi; + captured.live.ids = view.ids; captured.live.imgs = view.images; + captured.cvec = view.cvec; captured.checkpoints = view.checkpoints; + const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens; + captured.kv = std::move(reuse.kv); + const size_t layers = owned_qsa(ss); + captured.kv.resize(layers + 1); + if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false; + const int64_t upto = (int64_t) view.ids.size(); + for (size_t j = 0; j < layers; ++j) + if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error, + unchanged, reused_bytes)) return false; + // The draft's final cell may not have been computed when the output cap was + // reached. Refresh that page even when the main prefix continued unchanged. + if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error, + std::max(0, unchanged - 1), reused_bytes)) return false; + image = std::move(captured); + return true; +} + +bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss, + const ModelGeometry& g, const QsaState& draft, std::string& error) { + if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported"); + if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry"); + // an image holds exactly one carve's running state and K/V: same layer range or nothing + if (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi) + return fail(error, "snapshot from another session layer range"); + const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec}; + if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false; + const size_t layers = owned_qsa(ss); + if (image.kv.size() != layers + 1) return fail(error, "invalid K/V layer count"); + const int64_t upto = (int64_t) image.live.ids.size(); + for (size_t j = 0; j < layers; ++j) + if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false; + return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error); +} + +ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss, + const ModelGeometry& g, const QsaState& draft, std::string& error) { + if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid; + if (!sync(error)) return ConversationRestore::transfer_failed; + const int64_t upto = (int64_t) image.live.ids.size(); + for (size_t j = 0; j < owned_qsa(ss); ++j) + if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error)) + return ConversationRestore::transfer_failed; + if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) || + !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed; + return ConversationRestore::restored; +} +} // namespace strata::core diff --git a/engine/strata/src/core/conversation_validation_test.cpp b/engine/strata/src/core/conversation_validation_test.cpp new file mode 100644 index 00000000..f993eeb4 --- /dev/null +++ b/engine/strata/src/core/conversation_validation_test.cpp @@ -0,0 +1,239 @@ +// Host-only validation fixtures. CUDA is linked but must never be initialized: +// invalid restores must return before the first CUDA call or destination write. +#include "strata/core/conversation_snapshot.hpp" +#include "strata/kernels/kv_q4.hpp" + +#include +#include +#include +#include +#include + +#if defined(CONVERSATION_TEST_TRANSFERS) +// GNU/ELF link wrapping exercises the actual restore control flow without +// initializing CUDA or deliberately poisoning a real device context. This is +// host-backend fault injection, not a claim of hardware-failure recovery. +namespace { +int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0; +size_t copied_bytes = 0; +} +extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { + if (++copy_calls == fail_copy) return cudaErrorInvalidValue; + copied_bytes += n; + std::memcpy(dst, src, n); + return cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaDeviceSynchronize() { + return ++sync_calls == fail_sync ? cudaErrorUnknown : cudaSuccess; +} +extern "C" cudaError_t __wrap_cudaGetLastError() { return cudaSuccess; } +#endif + +using namespace strata::core; +namespace { +int checks = 0; +void check(bool ok, const char* label) { + ++checks; + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); } +} +struct Pools { + QsaState st; + std::array, 8> data; + Pools(const ModelGeometry& g, int format) { + st.max_cells = 96; st.n_pages = st.n_slots = 24; st.idx_pooled_rows = 26; + st.kv_int8 = format == 1; st.kv_q4 = format == 2; + const size_t per = format == 2 ? strata::kernels::kv_q4_bytes_per_head((int) g.head_dim) + : g.head_dim * (format == 1 ? 1 : 2); + data[0].resize(96 * g.n_head_kv * per, 0xa5); data[1] = data[0]; + data[2].resize(format == 1 ? 96 * g.n_head_kv * (g.head_dim / 64) * 2 : 0, 0xa5); data[3] = data[2]; + data[4].resize(26 * g.idx_key_dim * 4, 0xa5); + data[5].resize(3 * g.idx_key_dim * 4, 0xa5); + data[6].resize(g.idx_key_dim * 4, 0xa5); data[7].resize(4, 0xa5); + if (format == 2) { st.k_q4 = data[0].data(); st.v_q4 = data[1].data(); } + else if (format == 1) { + st.k_q = (int8_t*) data[0].data(); st.v_q = (int8_t*) data[1].data(); + st.k_scale = (uint16_t*) data[2].data(); st.v_scale = (uint16_t*) data[3].data(); + } else { st.k_pool = (uint16_t*) data[0].data(); st.v_pool = (uint16_t*) data[1].data(); } + st.idx_pooled = (float*) data[4].data(); st.idx_tail = (float*) data[5].data(); + st.idx_dead = (float*) data[6].data(); st.idx_block_pos = (int32_t*) data[7].data(); + } + ConversationKv image(const ModelGeometry& g, bool index) const { + ConversationKv k; + k.format = qsa_kv_format(st); k.cells = 12; k.page_size = 4; + k.heads = g.n_head_kv; k.head_dim = g.head_dim; k.idx_dim = g.idx_key_dim; + k.pooled_rows = index ? 3 : 0; + k.k.resize(data[0].size() / 8, 13); k.v = k.k; + k.k_scale.resize(data[2].size() / 8, 13); k.v_scale = k.k_scale; + k.pooled.resize(k.pooled_rows * g.idx_key_dim * 4, 13); + return k; + } +}; + +void fixture(int format, int experts, bool zero_qsa, bool ple) { + ModelGeometry g; + g.n_layers = zero_qsa ? 3 : 8; g.n_expert = experts; + g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8; + g.n_head_kv = 1; g.head_dim = 64; g.idx_key_dim = 8; + std::string error; + ConversationStateSizes z; + check(conversation_state_sizes(g, z, error), "checked canonical/pruned/zero-QSA sizing"); + Pools first(g, format), last(g, format), draft(g, format); + std::array layers{first.st, last.st}; + std::vector gdn(z.gdn, 0xa5), history(ple ? z.ple : 0, 0xa5); + SessionState ss; + ss.max_cells = 96; ss.gdn_state = (float*) gdn.data(); + // the whole-model carve, as session_init leaves a one-GPU session + ss.layer_hi = g.n_layers; ss.gdn_alloc = g.n_gdn_layers(); ss.qsa_alloc = g.n_qsa_layers(); + ss.ple_hist = ple ? (float*) history.data() : nullptr; + ss.qsa_states = zero_qsa ? nullptr : layers.data(); + SavedConversation image; + image.geometry = {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}; + image.layer_hi = g.n_layers; + auto checkpoint = [&](size_t tokens) { + ConversationCheckpoint c; + c.ids.resize(tokens); + for (size_t i = 0; i < tokens; ++i) c.ids[i] = (int32_t) i + 1; + c.imgs = {{1, 44}}; + c.gdn.resize(z.gdn, 13); c.ple.resize(ple ? z.ple : 0, 13); + c.tails.resize(g.n_qsa_layers() * z.tail, 13); c.dead.resize(g.n_qsa_layers() * z.dead, 13); + c.block_pos.resize(g.n_qsa_layers() * z.block_pos, 13); + return c; + }; + image.live = checkpoint(9); image.checkpoints.push_back(checkpoint(5)); + image.kv.reserve((size_t) g.n_qsa_layers() + 1); + if (!zero_qsa) { image.kv.push_back(first.image(g, true)); image.kv.push_back(last.image(g, true)); } + image.kv.push_back(draft.image(g, false)); + check(conversation_snapshot_validate(image, ss, g, draft.st, error), "complete image validates without CUDA"); + size_t estimate = 0; + check(conversation_snapshot_bytes({image.live.ids,image.live.imgs,image.checkpoints,true},ss,g,draft.st,estimate,error), + "capture estimate works without CUDA"); + check(estimate == image.bytes(), "estimate covers checkpoint/indexer/spare payloads"); + auto unchanged = [&] { + auto pristine = [](const auto& bytes) { return std::all_of(bytes.begin(),bytes.end(),[](uint8_t b){return b==0xa5;}); }; + if (!pristine(gdn) || !pristine(history) || ss.ple_prev[0] != -1 || ss.ple_prev[1] != -1) return false; + for (const auto* p : {&first,&last,&draft}) for (const auto& bytes : p->data) if (!pristine(bytes)) return false; + return true; + }; + auto reject = [&](const std::function& mutate, const char* label) { + auto bad = image; mutate(bad); + check(conversation_snapshot_restore(bad,ss,g,draft.st,error) == ConversationRestore::invalid,label); + check(unchanged(), "invalid restore did not touch any layer or running-state buffer"); + }; + reject([](auto& s){s.kv.back().k.pop_back();}, "late draft corruption rejected before first layer write"); + reject([](auto& s){s.geometry[16] = 128;}, "different expert geometry rejected"); + reject([](auto& s){s.live.stage_parts.emplace_back();}, "layer-split live state rejected before writes"); + reject([](auto& s){s.checkpoints[0].stage_parts.emplace_back();}, "layer-split checkpoint rejected before writes"); + reject([](auto& s){s.kv.pop_back();}, "missing KV layer rejected"); + reject([](auto& s){s.live.gdn.pop_back();}, "bad live recurrence rejected"); + reject([](auto& s){s.checkpoints.back().gdn.pop_back();}, "bad retained checkpoint rejected"); + reject([](auto& s){s.checkpoints.back().ids[0] = 99;}, "foreign checkpoint prefix rejected"); + reject([](auto& s){s.checkpoints.back().imgs[0].hash++;}, "foreign checkpoint image rejected"); + reject([](auto& s){s.live.imgs[0].start = -1;}, "negative image position rejected"); + reject([](auto& s){s.live.ids[0] = -1;}, "negative live token rejected"); + reject([](auto& s){s.live.ple.push_back(0);}, "PLE size/enabled mismatch rejected"); + reject([](auto& s){s.live.tails.push_back(0);}, "tail size/zero-QSA mismatch rejected"); + if (!zero_qsa) { + reject([](auto& s){s.kv[1].pooled.pop_back();}, "late indexer spare row corruption rejected"); + reject([](auto& s){s.live.dead.pop_back();}, "missing indexer spare key rejected"); + reject([](auto& s){s.live.block_pos.pop_back();}, "missing indexer metadata rejected"); + ss.qsa_states = nullptr; + check(!conversation_snapshot_validate(image,ss,g,draft.st,error), "missing QSA targets rejected"); + ss.qsa_states = layers.data(); + reject([](auto& s){s.layer_lo = 4;}, "snapshot from another layer range rejected"); + // #216's carve: a split stage owning layers [4, 8) holds GDN rows 3..5 and QSA ordinal 1 only + SessionState stage = ss; + stage.layer_lo = 4; stage.gdn_alloc = 3; stage.qsa_ord0 = 1; stage.qsa_alloc = 1; + ConversationStateSizes zs; + check(conversation_session_sizes(g,stage,zs,error) && zs.gdn == z.gdn / 6 * 3 && zs.tail == z.tail, + "carved session sizes cover the owned rows only"); + check(!conversation_checkpoint_validate(image.live,stage,g,error), "whole-model checkpoint rejected by a carve"); + ConversationCheckpoint part = image.live; + part.gdn.resize(zs.gdn); part.tails.resize(zs.tail); part.dead.resize(zs.dead); + part.block_pos.resize(zs.block_pos); + check(conversation_checkpoint_validate(part,stage,g,error), "carve-sized checkpoint validates"); + check(!conversation_snapshot_validate(image,stage,g,draft.st,error), "whole-model snapshot rejected by a carve"); + stage.qsa_alloc = 2; + check(!conversation_session_sizes(g,stage,zs,error), "carve past the last QSA ordinal rejected"); + stage.qsa_alloc = 1; stage.gdn_alloc = 7; + check(!conversation_session_sizes(g,stage,zs,error), "carve past the GDN rows rejected"); + } + auto bad_geometry = g; bad_geometry.ssm_state_size = std::numeric_limits::max(); + check(!conversation_state_sizes(bad_geometry,z,error), "running-state arithmetic overflow rejected"); + bad_geometry = g; bad_geometry.qsa_interval = 0; + check(!conversation_state_sizes(bad_geometry,z,error), "zero layer interval rejected before division"); + bad_geometry = g; bad_geometry.n_head_kv = std::numeric_limits::max(); + check(conversation_kv_bytes(draft.st,bad_geometry,9,false)==0, "KV byte overflow rejected"); +#if defined(CONVERSATION_TEST_TRANSFERS) + auto reset = [&] { + for (auto* p : {&first,&last,&draft}) for (auto& bytes : p->data) std::fill(bytes.begin(),bytes.end(),0xa5); + std::fill(gdn.begin(),gdn.end(),0xa5); std::fill(history.begin(),history.end(),0xa5); + ss.ple_prev[0] = ss.ple_prev[1] = -1; + copy_calls = sync_calls = fail_copy = fail_sync = 0; + }; + reset(); fail_sync = 1; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "pre-transfer CUDA synchronization failure is fatal"); + check(copy_calls==0 && unchanged(), "pre-sync failure did not mutate state"); + reset(); fail_copy = 1; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "first CUDA transfer failure is fatal"); + check(unchanged(), "first-copy failure did not mutate state"); + reset(); fail_copy = 2; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "partial CUDA transfer failure is fatal, not an invalid-image fallback"); + check(!unchanged(), "fault fixture genuinely produced partial state"); + reset(); fail_sync = 2; + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed, + "post-transfer CUDA synchronization failure is fatal"); + check(copy_calls>0 && !unchanged(), "post-sync failure occurred after state writes"); + reset(); + check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::restored, + "injected host transfer backend completes a valid restore"); + check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9, + "successful restore publishes correct running state and PLE window"); + uint64_t fingerprint = 0; + check(conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back verifies complete draft payload"); + draft.data[0][0] ^= 1; + check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back detects corrupted draft byte"); + draft.data[0][0] ^= 1; + fail_copy = copy_calls + 1; + check(!conversation_kv_verify(image.kv.back(),draft.st,g,9,false,fingerprint,error), "read-back transfer failure is not a successful fingerprint"); + reset(); copied_bytes = 0; + const ConversationView view{image.live.ids,image.live.imgs,image.checkpoints,true}; + SavedConversation full,incremental; + check(conversation_snapshot_save(full,view,ss,g,draft.st,error), "full capture through host transfer backend"); + const size_t full_copies = copied_bytes; + ConversationKvReuse reuse{full.kv,9,9}; + size_t peak = 0, reused = 0; + check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.st,peak,error), "incremental capture admission without transfers"); + copied_bytes = 0; + const bool saved_incrementally = conversation_snapshot_save(incremental,view,ss,g,draft.st,error,std::move(reuse),&reused); + if (!saved_incrementally) std::fprintf(stderr,"capture error: %s\n",error.c_str()); + check(saved_incrementally, "incremental capture through host backend"); + check(reused > 0 && copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted"); + check(incremental.bytes() <= peak && incremental.live.gdn == full.live.gdn, "running state refreshed within admitted allocation"); + for (size_t i=0;i +#include +#include + +using namespace strata::core; + +namespace { +int g_fail = 0; +int64_t g_checks = 0; +void check(bool ok, const char* what, long long a = 0, long long b = 0) { + ++g_checks; + if (!ok) { + if (++g_fail <= 20) std::printf(" FAIL %s (%lld vs %lld)\n", what, a, b); + } +} + +// verify.cpp run(): sp.counter = pos0, and the kernel draws row t with sp.counter + t +uint64_t verify_row_counter(int64_t pos0, int t) { return (uint64_t) pos0 + (uint64_t) t; } + +// The counters and positions of a chain of `n` drafts made after a window at `p` with `a` accepted (draft()), or for +// draft_first (cell0 = p - 1, a = 0), checked against the next window at `p_next`. +void check_chain(int64_t p, int a, int n, int64_t p_next) { + for (int j = 0; j < n; ++j) { + const int64_t cell = coupled_draft_cell(p, a, j); + // mtp.hpp: cell c predicts the token at c + 2; the next window's row j + 1 holds position p_next + j + 1 + check(cell + 2 == p_next + j + 1, "draft position = its row in the next window", cell + 2, p_next + j + 1); + // row j + 1 is kept iff it equals row j's pick, drawn at p_next + j + check(coupled_draft_counter(cell) == verify_row_counter(p_next, j), "draft counter = verifying row's counter", + (long long) coupled_draft_counter(cell), (long long) verify_row_counter(p_next, j)); + } +} + +// The device ring for one chain: base staged at [cap - h, cap) by the host, draft i at cap + i; draft j's window is +// [coupled_hist_start(cap, j, h), + h). Compared with penalty_rows over (consumed, [next, drafts...]). +void check_history(std::mt19937& rng, int cap, int h, int n_consumed, int n_drafts) { + std::uniform_int_distribution tok(0, 999); + std::vector consumed((size_t) n_consumed), drafts((size_t) n_drafts); + for (auto& t : consumed) t = tok(rng); + for (auto& t : drafts) t = tok(rng); + const int32_t next = tok(rng); + std::vector mapped((size_t) cap, 777777), ring((size_t) (cap + n_drafts), 888888); + coupled_hist_base(consumed.data(), (int64_t) consumed.size(), next, h, mapped.data() + (cap - h)); // set_draft_history + for (int i = cap - h; i < cap; ++i) ring[(size_t) i] = mapped[(size_t) i]; // coupled_stage_kernel + // the next window: [next, drafts...], T = n_drafts + 1 rows; row j checks draft j (row j + 1) + std::vector window; + window.push_back(next); + window.insert(window.end(), drafts.begin(), drafts.end()); + const int T = (int) window.size(); + std::vector rows((size_t) T * (size_t) h); + strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T, h, rows.data()); + for (int j = 0; j < n_drafts; ++j) { + const int s = coupled_hist_start(cap, j, h); + check(s >= 0 && s + h <= cap + n_drafts, "the window lies inside the ring", s, cap + n_drafts); + for (int i = 0; i < h; ++i) + check(ring[(size_t) (s + i)] == rows[(size_t) j * (size_t) h + (size_t) i], "draft history = verify row history", + ring[(size_t) (s + i)], rows[(size_t) j * (size_t) h + (size_t) i]); + ring[(size_t) (cap + j)] = drafts[(size_t) j]; // coupled_merge_kernel appends the draft after sampling it + } +} +} // namespace + +int main() { + std::printf("coupled_draft_test\n"); + std::mt19937 rng(20260930); + // ---- 1 + 2: a serve-style decode (the first window is the last prompt token alone, then MTP windows) + for (int run = 0; run < 200; ++run) { + std::uniform_int_distribution tdist(1, 8); + int64_t p = 100 + run * 37; // n - 1 + int T = 1; + for (int round = 0; round < 300; ++round) { + std::uniform_int_distribution adist(0, T - 1); + const int a = adist(rng); + const int64_t p_next = p + a + 1; + const int n = 7; // the chain makes up to max_t - 1 drafts, whatever T the next window takes + check_chain(p, a, n, p_next); + p = p_next; + T = tdist(rng); // --spec-min-p / the draft policy choose the next window's size + } + } + // the CLI's draft_first: the first window at p, drafts from cell p - 1 with a = 0 + for (int64_t p = 1; p < 5000; p += 13) check_chain(p - 1, 0, 7, p); + // ---- 3: the penalty ring against penalty_rows + for (int cap : {8, 64, kCoupledHistCap}) { + for (int h : {1, 3, 8}) { + if (h > cap) continue; + for (int n_consumed : {0, 1, 2, 5, 7, 20, 100}) + for (int n_drafts : {1, 3, 7}) check_history(rng, cap, h, n_consumed, n_drafts); + } + check_history(rng, cap, cap, 3, 7); // the window is the whole ring base + check_history(rng, cap, cap, 5000, 7); + } + // ---- 4: the window length the target uses: min(penalty_last_n, history_len) with history_len = + // min(penalty_last_n, 4096) in serve (0 = off) + for (int pln : {-1, 0, 1, 64, 4095, 4096, 4097, 100000}) { + const int hist_n = std::min(std::max(pln, 0), 4096); + const int target = hist_n > 0 ? std::min(pln, hist_n) : 0; + check(coupled_hist_len(pln, kCoupledHistCap) == target, "penalty window length = the target's", + coupled_hist_len(pln, kCoupledHistCap), target); + } + std::printf(" %lld checks, %d failed\n", (long long) g_checks, g_fail); + std::printf("%s\n", g_fail == 0 ? "PASS" : "FAIL"); + return g_fail == 0 ? 0 : 1; +} diff --git a/engine/strata/src/core/device.cu b/engine/strata/src/core/device.cu new file mode 100644 index 00000000..721028c9 --- /dev/null +++ b/engine/strata/src/core/device.cu @@ -0,0 +1,243 @@ +// src/core/device.cu - P2.S1: the CUDA side of the runtime core. +#include "strata/core/device.hpp" + +#include + +#include +#include + +namespace strata::core { + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + throw CudaError(std::string(what) + ": " + cudaGetErrorString(e), (int) e); + } +} + +// A NaN pattern, not zero. Zeros read from uninitialised memory are indistinguishable from real zeros in a +// dequantized weight or a masked attention score, which is exactly the kind of wrong-but-plausible value the +// Phase 1 harnesses kept catching. +__global__ void poison_kernel(float* p, uint64_t n_floats) { + const uint64_t i = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n_floats) p[i] = __int_as_float(0x7fc00000); +} + +#if defined(STRATA_USE_HIP) +#if !defined(STRATA_HIP_ARCHS) +#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake" +#endif +// "gfx1201:sramecc-:xnack-" -> "gfx1201" +std::string base_arch(const char* gcn_arch_name) { + std::string arch(gcn_arch_name); + const size_t colon = arch.find(':'); + if (colon != std::string::npos) arch.resize(colon); + return arch; +} + +bool compiled_for(const std::string& arch) { + const std::string list = STRATA_HIP_ARCHS; + size_t a = 0; + while (a <= list.size()) { + size_t b = list.find(',', a); + if (b == std::string::npos) b = list.size(); + if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true; + a = b + 1; + } + return false; +} + +std::string arch_problem(const cudaDeviceProp& p, int ordinal) { + const std::string arch = base_arch(p.gcnArchName); + const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")"; + if (!compiled_for(arch)) { + return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS + + "); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch + + ", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES"; + } + if (p.warpSize != 32) { + return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32"; + } + return ""; +} +#endif + +} // namespace + +const char* compiled_gpu_archs() { +#if defined(STRATA_USE_HIP) + return STRATA_HIP_ARCHS; +#else + return ""; +#endif +} + +int device_count() { + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess) { // HIP without a usable device reports an error, not 0 + cudaGetLastError(); + return 0; + } + return count < 0 ? 0 : count; +} + +bool device_summary(int ordinal, std::string& name, std::string& detail) { + cudaDeviceProp p{}; + if (ordinal < 0 || ordinal >= device_count() || cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { + cudaGetLastError(); + return false; + } + char buf[160]; +#if defined(STRATA_USE_HIP) + std::snprintf(buf, sizeof(buf), "arch %s, %.1f GiB, wave%d", base_arch(p.gcnArchName).c_str(), + (double) p.totalGlobalMem / (1024.0 * 1024 * 1024), p.warpSize); +#else + std::snprintf(buf, sizeof(buf), "compute capability %d.%d, %.1f GiB", p.major, p.minor, + (double) p.totalGlobalMem / (1024.0 * 1024 * 1024)); +#endif + name = p.name; + detail = buf; + return true; +} + +std::string gpu_arch_problem(int ordinal) { +#if defined(STRATA_USE_HIP) + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) { + cudaGetLastError(); + return ""; + } + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { + cudaGetLastError(); + return ""; + } + return arch_problem(p, ordinal); +#else + (void) ordinal; + return ""; +#endif +} + +std::string device_code_error() { +#if defined(STRATA_USE_HIP) + return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point +#else + // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all + cudaFuncAttributes a{}; + const cudaError_t e = cudaFuncGetAttributes(&a, poison_kernel); + if (e == cudaSuccess) return {}; + cudaGetLastError(); + return cudaGetErrorString(e); +#endif +} + +DeviceInfo device_info(int ordinal) { + int count = 0; + check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); + if (count == 0) { +#if defined(STRATA_USE_HIP) + throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1); +#else + throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1); +#endif + } + if (ordinal < 0 || ordinal >= count) { + throw CudaError("device ordinal " + std::to_string(ordinal) + " is out of range (have " + + std::to_string(count) + ")", + -1); + } + DeviceInfo d; + d.ordinal = ordinal; + check(cudaSetDevice(ordinal), "cudaSetDevice"); + + cudaDeviceProp p{}; + check(cudaGetDeviceProperties(&p, ordinal), "cudaGetDeviceProperties"); + d.name = p.name; + d.cc_major = p.major; + d.cc_minor = p.minor; + d.multi_processor_count = p.multiProcessorCount; + + size_t free_b = 0, total_b = 0; + check(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + d.free_bytes = free_b; + d.total_bytes = total_b; + + check(cudaDriverGetVersion(&d.driver_version), "cudaDriverGetVersion"); + check(cudaRuntimeGetVersion(&d.runtime_version), "cudaRuntimeGetVersion"); + + // The engine supports compute capability 7.5 and newer (Turing: the QSA scorer's tf32 mma has a portable + // fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a + // supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried + // to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP + // backend checks the card against the architectures the binary was compiled for (and wave32). +#if defined(STRATA_USE_HIP) + d.arch = base_arch(p.gcnArchName); + if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1); +#else + // #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it + // was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5 +#if defined(STRATA_EXPERIMENTAL_SM60) + constexpr int kMinCc = 60; + const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)"; +#else + constexpr int kMinCc = 75; + const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)"; +#endif + if (d.cc_major * 10 + d.cc_minor < kMinCc) { + throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) + + "." + std::to_string(d.cc_minor) + "; Strata needs compute capability " + kNeed, + -1); + } +#endif + return d; +} + +DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) + : capacity_(bytes), ordinal_(ordinal), poison_(poison) { + if (bytes == 0) throw CudaError("DeviceArena of 0 bytes", -1); + check(cudaSetDevice(ordinal), "cudaSetDevice"); + // One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it + // happens once, here, before anything depends on it. + check(cudaMalloc(&base_, (size_t) bytes), "cudaMalloc"); + if (poison_) { + const int threads = 256; + const uint64_t n = bytes / sizeof(float); + const uint64_t blocks = (n + threads - 1) / threads; + // gridDim.x is 32-bit, so a large region needs a loop. 12 GB of floats is 3e9 elements = 1.2e7 + // blocks, which fits, but the loop keeps it correct for any size rather than for today's sizes. + const uint64_t max_blocks = 0x7FFFFFFFull; + for (uint64_t b = 0; b < blocks; b += max_blocks) { + const uint64_t chunk = (blocks - b < max_blocks) ? (blocks - b) : max_blocks; + poison_kernel<<<(unsigned) chunk, threads>>>((float*) base_ + b * threads, n - b * threads); + check(cudaGetLastError(), "poison_kernel"); + } + check(cudaDeviceSynchronize(), "poison sync"); + } +} + +DeviceArena::~DeviceArena() { + if (base_) cudaFree(base_); // best effort: a destructor must not throw +} + +void* DeviceArena::alloc(uint64_t bytes, uint64_t align) { + if (bytes == 0) return nullptr; + if (align == 0 || (align & (align - 1)) != 0) { + throw CudaError("DeviceArena::alloc alignment must be a power of two", -1); + } + const uint64_t start = (used_ + align - 1) & ~(align - 1); + if (start + bytes > capacity_) { + char msg[256]; + std::snprintf(msg, sizeof(msg), + "DeviceArena out of memory: asked for %llu B at offset %llu (align %llu) in a %llu B " + "region - the plan from P1.S9 did not close", + (unsigned long long) bytes, (unsigned long long) start, (unsigned long long) align, + (unsigned long long) capacity_); + throw CudaError(msg, -1); + } + used_ = start + bytes; + return (char*) base_ + start; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/device_main.cpp b/engine/strata/src/core/device_main.cpp new file mode 100644 index 00000000..c6872afc --- /dev/null +++ b/engine/strata/src/core/device_main.cpp @@ -0,0 +1,122 @@ +// src/core/device_main.cpp - `strata-device`: report the GPU, the plan, and exercise the arena. +// +// This is P2.S1's "startup prints the memory plan vs actual cudaMemGetInfo" bullet, on its own so it can run +// without the model. It is also the run-time half of the sm_120 policy: CMake refuses to COMPILE for another +// architecture, and this refuses to RUN on one. +#include "strata/core/device.hpp" +#include "strata/plan/plan.hpp" + +#include +#include +#include +#if defined(STRATA_USE_HIP) && defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +static std::string human(uint64_t b) { + char buf[64]; + std::snprintf(buf, sizeof(buf), "%.3f GiB (%llu B)", (double) b / (1024.0 * 1024 * 1024), + (unsigned long long) b); + return buf; +} + +int main(int argc, char** argv) { + bool selftest = false; + bool list_devices = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; + else if (std::strcmp(argv[i], "--list-devices") == 0) list_devices = true; + else if (std::strcmp(argv[i], "--help") == 0 || std::strcmp(argv[i], "-h") == 0) { + std::printf("usage: strata-device [--selftest] [--list-devices]\n" + " --list-devices every GPU the runtime enumerates, numbered as HIP_VISIBLE_DEVICES /\n" + " CUDA_VISIBLE_DEVICES number them, and whether this binary can run it\n"); + return 0; + } else { + std::fprintf(stderr, "unknown argument: %s\n", argv[i]); + return 2; + } + } + + // The runtime's numbering, which setup needs on Windows: there an integrated Radeon is HIP device 0 and pushes the + // discrete card to 1, while setup finds the cards in the display-adapter order (#325). No arch check here - the + // cards this binary has no code for are part of the answer. Format (setup.py's hip_devices parses it): + // device N: + // arch gfx1201, 15.9 GiB, wave32 (CUDA: compute capability 12.0, 11.9 GiB) + // cannot run: (only for a card this binary cannot run) + if (list_devices) { + const int count = strata::core::device_count(); + if (count == 0) std::printf("(no GPU device)\n"); + for (int ordinal = 0; ordinal < count; ++ordinal) { + std::string name, detail; + if (!strata::core::device_summary(ordinal, name, detail)) { + std::printf("device %d: (the runtime cannot describe it)\n", ordinal); + continue; + } + std::printf("device %d: %s\n %s\n", ordinal, name.c_str(), detail.c_str()); + if (const std::string why = strata::core::gpu_arch_problem(ordinal); !why.empty()) + std::printf(" cannot run: %s\n", why.c_str()); + } + return 0; + } + + try { + const strata::core::DeviceInfo d = strata::core::device_info(0); + std::printf("device %d: %s\n", d.ordinal, d.name.c_str()); +#if defined(STRATA_USE_HIP) + std::printf(" HIP arch %s wave32 (compiled for %s)\n", d.arch.c_str(), + strata::core::compiled_gpu_archs()); +#else + std::printf(" compute capability %d.%d (sm_%d%d)\n", d.cc_major, d.cc_minor, d.cc_major, d.cc_minor); +#endif + std::printf(" multiprocessors %d\n", d.multi_processor_count); + std::printf(" VRAM total / free %s / %s\n", human(d.total_bytes).c_str(), human(d.free_bytes).c_str()); + std::printf(" driver / runtime %d / %d\n", d.driver_version, d.runtime_version); +#if defined(STRATA_USE_HIP) && defined(_WIN32) + // #468 #461: which HIP runtime this process loaded - the one beside the exe, or an AMD driver's System32 copy + if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) { + char path[MAX_PATH] = {}; + if (GetModuleFileNameA(h, path, MAX_PATH) > 0) std::printf(" HIP runtime %s\n", path); + } +#endif + + // The planner's view against the card's. A plan that does not fit in what is actually FREE is the + // failure this print exists to make visible at startup rather than at token 4000. + const auto plan = strata::plan::make_plan(20480, strata::plan::Geometry{}, strata::plan::Costs{}); + std::printf("\n%s", strata::plan::to_string(plan).c_str()); + std::printf(" card free %s\n", human(d.free_bytes).c_str()); + std::printf(" plan + KV vs free %s\n", + plan.vram_budget <= d.free_bytes ? "FITS" : "*** DOES NOT FIT ***"); + + if (selftest) { + // Exercise the arena for real: allocate, write from the host, read back, and check the poison + // path leaves NaNs rather than zeros. A GPU test that only asks the driver for its name does not + // test the runtime this file exists to provide. + const uint64_t bytes = 64ull << 20; // 64 MiB, small enough to be safe on any card + strata::core::DeviceArena arena(bytes, 0, /*poison=*/true); + void* a = arena.alloc(1 << 20, 256); + void* b = arena.alloc(1 << 20, 4096); + if (((uintptr_t) a % 256) || ((uintptr_t) b % 4096)) { + std::fprintf(stderr, "selftest: alignment not honoured\n"); + return 1; + } + std::printf("\nselftest: arena %s, used %s after two 1 MiB allocations\n", human(arena.capacity()).c_str(), + human(arena.used()).c_str()); + // and the arena must REFUSE rather than wrap + try { + arena.alloc(bytes * 2); + std::fprintf(stderr, "selftest: over-allocation did NOT throw\n"); + return 1; + } catch (const strata::core::CudaError&) { + std::printf("selftest: over-allocation refused as required\n"); + } + std::printf("strata-device selftest OK\n"); + } + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "strata-device: %s\n", e.what()); + return 1; + } +} diff --git a/engine/strata/src/core/expert_cache.cpp b/engine/strata/src/core/expert_cache.cpp new file mode 100644 index 00000000..3588cd5d --- /dev/null +++ b/engine/strata/src/core/expert_cache.cpp @@ -0,0 +1,374 @@ +// src/core/expert_cache.cpp - R4's slot storage and residency table. Read the header first. +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +namespace strata::core { + +bool read_expert_profile(const std::string& path, int64_t n_layers, int64_t n_expert, + std::vector>& ranked, int64_t& slots, std::string& err) { + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (f == nullptr) { + err = "read_expert_profile: cannot open " + path; + return false; + } + char magic[4] = {0, 0, 0, 0}; + uint32_t hdr[5] = {0, 0, 0, 0, 0}; + if (std::fread(magic, 1, 4, f) != 4 || std::fread(hdr, 4, 5, f) != 5) { + std::fclose(f); + err = "read_expert_profile: " + path + " is too short to hold a header"; + return false; + } + if (std::memcmp(magic, "STRP", 4) != 0) { + std::fclose(f); + err = "read_expert_profile: " + path + " does not start with STRP"; + return false; + } + const uint32_t version = hdr[0], nl = hdr[1], ne = hdr[2], want = hdr[3], n_ranked = hdr[4]; + if ((int64_t) nl != n_layers || (int64_t) ne != n_expert) { + std::fclose(f); + char buf[256]; + std::snprintf(buf, sizeof buf, + "read_expert_profile: %s is %ux%u but this model is %lldx%lld - it is a profile for a " + "different artifact", path.c_str(), nl, ne, (long long) n_layers, (long long) n_expert); + err = buf; + return false; + } + if (n_ranked > want) { + std::fclose(f); + err = "read_expert_profile: the header claims more ranked pairs than slots"; + return false; + } + ranked.assign(n_ranked, {0, 0}); + std::vector raw((size_t) n_ranked * 2); + if (n_ranked > 0 && std::fread(raw.data(), 2, (size_t) n_ranked * 2, f) != (size_t) n_ranked * 2) { + std::fclose(f); + err = "read_expert_profile: the ranked list is truncated"; + return false; + } + std::fclose(f); + for (uint32_t i = 0; i < n_ranked; ++i) { + const int32_t l = (int32_t) raw[(size_t) i * 2], e = (int32_t) raw[(size_t) i * 2 + 1]; + if (l < 0 || l >= n_layers || e < 0 || e >= n_expert) { + char buf[256]; + std::snprintf(buf, sizeof buf, "read_expert_profile: pair %u is (layer %d, expert %d), out of range", + i, l, e); + err = buf; + return false; + } + ranked[(size_t) i] = {l, e}; + } + slots = (int64_t) want; + (void) version; // a future format bumps it; the layout check above is what protects this reader today + return true; +} + +ExpertCache::~ExpertCache() { close(); } + +#if defined(STRATA_USE_HIP) +bool ExpertCache::ensure_blocking_staging(std::size_t bytes, std::string& err) { + if (bytes <= blocking_staging_bytes_) return true; + void* next = nullptr; + const cudaError_t status = cudaHostAlloc(&next, bytes, cudaHostAllocDefault); + if (status != cudaSuccess) { + err = std::string("ExpertCache: HIP blocking staging allocation: ") + cudaGetErrorString(status); + return false; + } + if (blocking_staging_) (void) cudaFreeHost(blocking_staging_); + blocking_staging_ = static_cast(next); + blocking_staging_bytes_ = bytes; + return true; +} +#endif + +bool ExpertCache::open(int64_t n_slots, int64_t n_layers, int64_t n_expert, int64_t blob_bytes, + std::string& err) { + close(); + if (n_slots <= 0) { + err = "ExpertCache: n_slots must be positive"; + return false; + } + if (n_layers <= 0 || n_expert <= 0 || blob_bytes <= 0) { + err = "ExpertCache: n_layers, n_expert and blob_bytes must all be positive"; + return false; + } + + const uint64_t want = (uint64_t) n_slots * (uint64_t) blob_bytes; + + // ---- **THE ALLOCATION IS CHECKED AGAINST THE CARD, NOT AGAINST THE REQUEST.** + // + // `cudaMalloc` failing is the easy case. The one that matters is a machine where the weights already own + // most of VRAM: the cache then takes what is left and `slots()` would report the number ASKED FOR while + // `device_slot()` walks off the end. So the free-VRAM figure is read and compared BEFORE the allocation, + // and the two numbers are named in the refusal. + size_t free_b = 0, total_b = 0; + if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess) { + if ((uint64_t) free_b < want) { + char buf[320]; + std::snprintf(buf, sizeof buf, + "ExpertCache: %lld slots x %lld B = %.2f GiB, but only %.2f GiB of VRAM is free " + "(%.2f GiB of %.2f GiB total). Lower --expert-cache.", + (long long) n_slots, (long long) blob_bytes, (double) want / 1073741824.0, + (double) free_b / 1073741824.0, (double) (total_b - free_b) / 1073741824.0, + (double) total_b / 1073741824.0); + err = buf; + return false; + } + } + + if (cudaMalloc((void**) &base_, (size_t) want) != cudaSuccess) { + base_ = nullptr; + char buf[256]; + std::snprintf(buf, sizeof buf, "ExpertCache: cudaMalloc(%.2f GiB) failed: %s", + (double) want / 1073741824.0, cudaGetErrorString(cudaGetLastError())); + err = buf; + return false; + } + // Zeroed so a slot read before it is filled is a DETERMINISTIC wrong answer rather than whatever the + // allocator handed back. A stale block of a previous process's memory would still sum to finite floats. + if (cudaMemset(base_, 0, (size_t) want) != cudaSuccess) { + err = "ExpertCache: cudaMemset of the slot arena failed"; + close(); + return false; + } + + residency_.assign((size_t) (n_layers * n_expert), kNotResident); + slots_ = n_slots; + n_layers_ = n_layers; + n_expert_ = n_expert; + blob_ = blob_bytes; +#if defined(STRATA_USE_HIP) + if (!ensure_blocking_staging((std::size_t) blob_, err)) { + close(); + return false; + } +#endif + next_free_ = 0; + fills_ = 0; + admitted_ = 0; + // R4.2g: each layer starts at the bottom of its own range. Built here rather than lazily so `admit` + // stays allocation-free on the token path. + layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0); + for (int64_t l = 0; l < n_layers; ++l) { + int64_t lo = 0, hi = 0; + layer_slot_range(l, lo, hi); + layer_next_[(size_t) l] = (int32_t) lo; + } + return true; +} + +bool ExpertCache::open_sized(const std::vector& slot_bytes, int64_t n_layers, int64_t n_expert, + std::string& err) { + if (slot_bytes.empty()) { err = "ExpertCache: no slots"; return false; } + int64_t mx = 0; + std::vector off(slot_bytes.size() + 1, 0); + for (size_t i = 0; i < slot_bytes.size(); ++i) { + // 256-byte aligned slots, so every blob starts where the kernels' vector loads expect it + off[i + 1] = off[i] + ((uint64_t) slot_bytes[i] + 255) / 256 * 256; + mx = slot_bytes[i] > mx ? slot_bytes[i] : mx; + } + // one allocation of the summed size, through the uniform path's checks: n "slots" of 1 byte + if (!open((int64_t) off.back(), n_layers, n_expert, 1, err)) return false; + slots_ = (int64_t) slot_bytes.size(); + blob_ = mx; + off_ = std::move(off); +#if defined(STRATA_USE_HIP) + if (!ensure_blocking_staging((std::size_t) blob_, err)) { + close(); + return false; + } +#endif + // #369: each layer's cursor at the bottom of its own range, as open() seeds it - open() above ran on byte-sized + // "slots", so its seeds are not slot indices + layer_next_.assign((size_t) (n_layers > 0 ? n_layers : 0), 0); + for (int64_t l = 0; l < n_layers; ++l) { + int64_t lo = 0, hi = 0; + layer_slot_range(l, lo, hi); + layer_next_[(size_t) l] = (int32_t) lo; + } + return true; +} + +void ExpertCache::close() { +#if defined(STRATA_USE_HIP) + if (blocking_staging_) (void) cudaFreeHost(blocking_staging_); + blocking_staging_ = nullptr; + blocking_staging_bytes_ = 0; +#endif + off_.clear(); + if (base_ != nullptr) { + cudaFree(base_); + base_ = nullptr; + } + residency_.clear(); + slots_ = 0; + n_layers_ = 0; + n_expert_ = 0; + blob_ = 0; + next_free_ = 0; + fills_ = 0; + admitted_ = 0; + layer_next_.clear(); +} + +/// R4.2g. Layer `l` owns `[l*q, (l+1)*q)` with `q = slots_ / n_layers_`; the LAST layer takes whatever is +/// left over, so the ranges always cover `0..slots_` exactly and no slot is orphaned by the division. +void ExpertCache::layer_slot_range(int64_t layer, int64_t& lo, int64_t& hi) const { + lo = 0; + hi = 0; + if (n_layers_ <= 0 || slots_ <= 0 || layer < 0 || layer >= n_layers_) return; + const int64_t q = slots_ / n_layers_; + lo = layer * q; + hi = (layer == n_layers_ - 1) ? slots_ : (layer + 1) * q; +} + +int32_t ExpertCache::slot_of(int64_t layer, int64_t expert) const { + if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; + return residency_[(size_t) (layer * n_expert_ + expert)]; +} + +int32_t ExpertCache::admit(int64_t layer, int64_t expert) { + if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return kNotResident; + const size_t at = (size_t) (layer * n_expert_ + expert); + if (residency_[at] != kNotResident) return residency_[at]; + // R4.2g: THE PER-LAYER PATH. Same "no eviction" rule, but the ceiling is this layer's own range rather + // than one counter shared by all 48 - which is what confined the measured hit rate to 2.97%. + if (per_layer_) { + if (layer_next_.empty()) return kNotResident; + int64_t lo = 0, hi = 0; + layer_slot_range(layer, lo, hi); + if ((int64_t) layer_next_[(size_t) layer] >= hi) return kNotResident; // this layer's quota is full + residency_[at] = layer_next_[(size_t) layer]++; + ++admitted_; + return residency_[at]; + } + if (next_free_ >= slots_) return kNotResident; // full: no eviction, deliberately - see the header + residency_[at] = (int32_t) next_free_; + return (int32_t) next_free_++; +} + +uint8_t* ExpertCache::device_slot(int32_t slot) { + if (slot < 0 || slot >= slots_) return nullptr; + if (!off_.empty()) return base_ + off_[(size_t) slot]; + return base_ + (size_t) slot * (size_t) blob_; +} + +const uint8_t* ExpertCache::device_slot(int32_t slot) const { + if (slot < 0 || slot >= slots_) return nullptr; + if (!off_.empty()) return base_ + off_[(size_t) slot]; + return base_ + (size_t) slot * (size_t) blob_; +} + +bool ExpertCache::fill_slot(int32_t slot, const uint8_t* host_blob, void* stream, std::string& err, int64_t bytes) { + const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); + uint8_t* dst = device_slot(slot); + if (dst == nullptr) { + err = "ExpertCache::fill_slot: slot " + std::to_string(slot) + " is outside 0.." + + std::to_string(slots_ - 1); + return false; + } + if (host_blob == nullptr) { + err = "ExpertCache::fill_slot: the host blob is null"; + return false; + } + const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, + (cudaStream_t) stream); + if (e != cudaSuccess) { + err = std::string("ExpertCache::fill_slot: ") + cudaGetErrorString(e); + return false; + } + ++fills_; + return true; +} + +bool ExpertCache::fill_slot_blocking(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); + uint8_t* dst = device_slot(slot); + if (dst == nullptr) { + err = "ExpertCache::fill_slot_blocking: slot outside the arena"; + return false; + } + if (host_blob == nullptr) { + err = "ExpertCache::fill_slot_blocking: the host blob is null"; + return false; + } +#if defined(STRATA_USE_HIP) + // Bound HIP's pageable-source staging to one expert instead of repeatedly + // registering regions of the mmap. The blocking copy completes before reuse. + if (!blocking_staging_ || n > blocking_staging_bytes_) { + err = "ExpertCache::fill_slot_blocking: HIP staging buffer is too small"; + return false; + } + std::memcpy(blocking_staging_, host_blob, n); + const cudaError_t e = cudaMemcpy(dst, blocking_staging_, n, cudaMemcpyHostToDevice); +#else + const cudaError_t e = cudaMemcpy(dst, host_blob, n, cudaMemcpyHostToDevice); +#endif + if (e != cudaSuccess) { + err = std::string("ExpertCache::fill_slot_blocking: ") + cudaGetErrorString(e); + return false; + } + ++fills_; + return true; +} + +bool ExpertCache::fill_slot_queued(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + const size_t n = (size_t) (bytes > 0 && bytes <= blob_ ? bytes : blob_); + uint8_t* dst = device_slot(slot); + if (dst == nullptr || host_blob == nullptr) { + err = dst == nullptr ? "ExpertCache::fill_slot_queued: slot outside the arena" + : "ExpertCache::fill_slot_queued: the host blob is null"; + return false; + } + const cudaError_t e = cudaMemcpyAsync(dst, host_blob, n, cudaMemcpyHostToDevice, (cudaStream_t) 0); + if (e != cudaSuccess) { + err = std::string("ExpertCache::fill_slot_queued: ") + cudaGetErrorString(e); + return false; + } + ++fills_; + return true; +} + +bool ExpertCache::sync_queued(std::string& err) { + const cudaError_t e = cudaStreamSynchronize((cudaStream_t) 0); + if (e != cudaSuccess) { + err = std::string("ExpertCache::sync_queued: ") + cudaGetErrorString(e); + return false; + } + return true; +} + +bool ExpertCache::verify_slot(int32_t slot, const uint8_t* host_blob, std::string& err, int64_t bytes) { + const int64_t nb = bytes > 0 && bytes <= blob_ ? bytes : blob_; + const uint8_t* src = device_slot(slot); + if (src == nullptr) { + err = "ExpertCache::verify_slot: slot outside the arena"; + return false; + } + // `cudaMemcpy` and not `cudaMemcpyAsync`: this is a startup check, and a check that can be read before it + // has happened is not a check. It also synchronises the fills queued before it, which is what makes the + // comparison meaningful. + std::vector got((size_t) nb); + const cudaError_t e = cudaMemcpy(got.data(), src, (size_t) nb, cudaMemcpyDeviceToHost); + if (e != cudaSuccess) { + err = std::string("ExpertCache::verify_slot: ") + cudaGetErrorString(e); + return false; + } + if (std::memcmp(got.data(), host_blob, (size_t) nb) != 0) { + size_t first = 0; + while (first < (size_t) nb && got[first] == host_blob[first]) ++first; + char buf[256]; + std::snprintf(buf, sizeof buf, + "ExpertCache::verify_slot: slot %d differs from the arena at byte %llu (of %lld)", + (int) slot, (unsigned long long) first, (long long) blob_); + err = buf; + return false; + } + return true; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/expert_source.cpp b/engine/strata/src/core/expert_source.cpp new file mode 100644 index 00000000..4d3cb759 --- /dev/null +++ b/engine/strata/src/core/expert_source.cpp @@ -0,0 +1,2333 @@ +// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. +#include "strata/core/expert_source.hpp" +#include "strata/core/remote_experts.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/artifact/gguf_reader.hpp" + +#include "strata/core/pinned.hpp" +#include "strata/platform/memory.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX // std::numeric_limits::max() below +#endif +#include +#else +#include +#include +#include +#include +#endif + +// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform +#ifndef STRATA_FSEEK64 +#ifdef _WIN32 +#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET) +#else +#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET) +#endif +#endif + +namespace strata::core { + +namespace detail { + +bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) { + bytes = 0; + if (!stat.valid) return false; + + // memory.stat's inactive_file can race memory.current, so bound it to charged usage first. + uint64_t reclaimable = std::min(stat.inactive_file, stat.current); + reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty; + reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback; + + // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read. + const uint64_t usage_after_reclaim = stat.current - reclaimable; + bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0; + return true; +} + +bool make_cache_complement_plan( + int64_t n_layers, int64_t n_expert, const std::vector& layer_blob_bytes, + const std::vector>& primary_gpu_pairs, + const std::vector>& additional_gpu_pairs, + std::vector& offsets, uint64_t& bytes, std::string& err) { + offsets.clear(); + bytes = 0; + err.clear(); + if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) { + err = "FileExpertSource: invalid geometry for the cache complement plan"; + return false; + } + if ((uint64_t) n_layers > (uint64_t) std::numeric_limits::max() / (uint64_t) n_expert) { + err = "FileExpertSource: cache complement index table is too large"; + return false; + } + const size_t count = (size_t) n_layers * (size_t) n_expert; + std::vector omitted(count, 0); + auto mark_pairs = [&](const std::vector>& pairs, uint8_t bit, + const char* label) -> bool { + for (const auto& pair : pairs) { + if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) { + err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry"; + return false; + } + const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second; + if ((omitted[index] & bit) != 0) { + err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan"; + return false; + } + if (bit == 2 && (omitted[index] & 1) != 0) { + err = "FileExpertSource: the primary and additional GPU expert tiers overlap"; + return false; + } + omitted[index] |= bit; + } + return true; + }; + if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") || + !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false; + for (uint64_t blob_bytes : layer_blob_bytes) { + if (blob_bytes == 0) { + err = "FileExpertSource: cache complement layer has zero-sized expert blobs"; + return false; + } + } + + offsets.assign(count, kNoCacheComplement); + for (int64_t layer = 0; layer < n_layers; ++layer) { + const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer]; + for (int64_t expert = 0; expert < n_expert; ++expert) { + const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert; + if (omitted[index] != 0) continue; + if (bytes > std::numeric_limits::max() - blob_bytes) { + offsets.clear(); + bytes = 0; + err = "FileExpertSource: cache complement size overflows"; + return false; + } + offsets[index] = bytes; + bytes += blob_bytes; + } + } + if (bytes > (uint64_t) std::numeric_limits::max()) { + offsets.clear(); + bytes = 0; + err = "FileExpertSource: cache complement exceeds the host address space"; + return false; + } + return true; +} + +const uint8_t* cache_complement_blob_or_fallback( + size_t index, const std::vector& offsets, const uint8_t* complement_host, + const uint8_t* mapped_fallback) { + if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement) + return complement_host + (size_t) offsets[index]; + return mapped_fallback; +} + +int64_t choose_resident_keep_from(const std::vector& slot_bytes, uint64_t base_bytes, uint64_t budget, + int64_t lend_from) { + if (base_bytes > budget) return -1; + const int64_t slots = (int64_t) slot_bytes.size(); + if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds + int64_t keep = slots; + uint64_t bytes = base_bytes; + while (keep > lend_from) { + const uint64_t b = slot_bytes[(size_t) keep - 1]; + if (b > budget - bytes) break; + bytes += b; + --keep; + } + return keep; +} + +bool exchange_cache_complement(std::vector& offsets, size_t in, size_t out) { + if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement || + offsets[out] != kNoCacheComplement) return false; + offsets[out] = offsets[in]; + offsets[in] = kNoCacheComplement; + return true; +} + +} // namespace detail + +namespace { + +#if defined(__linux__) +bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current, + detail::CgroupMemoryStat& stat) { + std::ifstream input(path / "memory.stat"); + if (!input) return false; + + bool inactive_file = false, file_dirty = false, file_writeback = false; + std::string line; + while (std::getline(input, line)) { + std::istringstream fields(line); + std::string key; + uint64_t value = 0; + if (!(fields >> key >> value)) return false; + fields >> std::ws; + if (!fields.eof()) return false; + + if (key == "inactive_file") { + if (inactive_file) return false; + inactive_file = true; + stat.inactive_file = value; + } else if (key == "file_dirty") { + if (file_dirty) return false; + file_dirty = true; + stat.file_dirty = value; + } else if (key == "file_writeback") { + if (file_writeback) return false; + file_writeback = true; + stat.file_writeback = value; + } + } + if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false; + stat.current = current; + stat.valid = true; + return true; +} +#endif + +bool available_memory_bytes(uint64_t& bytes) { +#if defined(_WIN32) + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (!GlobalMemoryStatusEx(&status)) return false; + bytes = (uint64_t) status.ullAvailPhys; + return bytes > 0; +#elif defined(__linux__) + // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES. + std::ifstream info("/proc/meminfo"); + std::string line; + bytes = 0; + while (std::getline(info, line)) { + std::istringstream fields(line); + std::string key, unit; + uint64_t value = 0; + if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" && + value <= std::numeric_limits::max() / 1024) bytes = value * 1024; + } + if (bytes == 0) return false; + // Account for the tightest cgroup-v2 ancestor limit when its normal mount is visible. + // This is a point-in-time guard, not a reservation against concurrent allocations. + std::ifstream groups("/proc/self/cgroup"); + if (!groups) return false; + bool resolved_v2 = false; + while (std::getline(groups, line)) { + if (line.rfind("0::/", 0) != 0) continue; + const std::filesystem::path root("/sys/fs/cgroup"); + auto path = (root / line.substr(4)).lexically_normal(); + if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false; + resolved_v2 = true; + while (path.string().rfind(root.string(), 0) == 0) { + std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current"); + std::string limit; + uint64_t current = 0; + const bool readable = bool(limit_file >> limit) && bool(current_file >> current); + // The host's root cgroup has no memory.max; ordinary child groups must expose their limits. + if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") && + std::filesystem::exists(path / "cgroup.controllers"))) return false; + if (readable && limit != "max") { + try { + size_t consumed = 0; + const uint64_t cap = std::stoull(limit, &consumed); + if (consumed != limit.size()) return false; + detail::CgroupMemoryStat stat; + if (!read_cgroup_memory_stat(path, current, stat)) return false; + uint64_t cgroup_available = 0; + if (!detail::cgroup_available_bytes(cap, stat, cgroup_available)) return false; + bytes = std::min(bytes, cgroup_available); + } catch (...) { return false; } + } + if (path == root) break; + path = path.parent_path(); + } + } + return resolved_v2; +#else + const long pages = sysconf(_SC_AVPHYS_PAGES); + const long page_bytes = sysconf(_SC_PAGESIZE); + if (pages <= 0 || page_bytes <= 0 || + (uint64_t) pages > std::numeric_limits::max() / (uint64_t) page_bytes) return false; + bytes = (uint64_t) pages * (uint64_t) page_bytes; + return bytes > 0; +#endif +} + +} // namespace + +// ================================ THE FILE-BACKED SOURCE ================================ + +FileExpertSource::~FileExpertSource() { close(); } + +bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) { + close(); + if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; } + const auto& layout = strata::kernels::cpu::expert_layout(); + if (layout.n_layers != n_layers || layout.n_expert != n_expert) { + err = "FileExpertSource: the requested geometry does not match the loaded expert layout"; + return false; + } + if ((uint64_t) n_layers > (uint64_t) std::numeric_limits::max() / (uint64_t) n_expert) { + err = "FileExpertSource: the expert count overflows"; + return false; + } + const uint64_t blob_count = (uint64_t) n_layers * (uint64_t) n_expert; + if (blob_count > (uint64_t) std::numeric_limits::max() || + (uint64_t) n_layers > (uint64_t) std::numeric_limits::max()) { + err = "FileExpertSource: the expert count overflows"; + return false; + } + + std::vector layer_offsets((size_t) n_layers), layer_blob_bytes((size_t) n_layers); + const uint64_t want = layout.total; + if (want == 0 || want > (uint64_t) std::numeric_limits::max()) { + err = "FileExpertSource: the loaded expert layout has an invalid size"; + return false; + } + if (!layout.native) { + if (blob_count > std::numeric_limits::max() / (uint64_t) strata::kernels::cpu::BLOB) { + err = "FileExpertSource: the canonical expert size overflows"; + return false; + } + const uint64_t canonical_size = blob_count * (uint64_t) strata::kernels::cpu::BLOB; + if (want != canonical_size) { + err = "FileExpertSource: the canonical expert layout has an inconsistent size"; + return false; + } + const uint64_t bytes = (uint64_t) strata::kernels::cpu::BLOB; + const uint64_t layer_bytes = (uint64_t) n_expert * bytes; + for (int64_t layer = 0; layer < n_layers; ++layer) { + layer_offsets[(size_t) layer] = (uint64_t) layer * layer_bytes; + layer_blob_bytes[(size_t) layer] = bytes; + } + } else { + if (layout.offset.size() != (size_t) n_layers || layout.bytes.size() != (size_t) n_layers || + layout.fmt.size() != (size_t) n_layers) { + err = "FileExpertSource: the native expert layout is incomplete"; + return false; + } + uint64_t at = 0; + for (int64_t layer = 0; layer < n_layers; ++layer) { + const size_t i = (size_t) layer; + const uint64_t bytes = (uint64_t) layout.fmt[i].bytes; + if (layout.offset[i] != at || bytes == 0 || layout.bytes[i] != bytes || + bytes > std::numeric_limits::max() / (uint64_t) n_expert) { + err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string(layer); + return false; + } + const uint64_t layer_bytes = bytes * (uint64_t) n_expert; + if (at > want || layer_bytes > want - at) { + err = "FileExpertSource: the native expert layout exceeds its declared size at layer " + + std::to_string(layer); + return false; + } + layer_offsets[i] = layout.offset[i]; + layer_blob_bytes[i] = bytes; + at += layer_bytes; + } + if (at != want) { + err = "FileExpertSource: the native expert layout has an inconsistent size"; + return false; + } + } + const std::string path = pack_dir + "/experts.bin"; + if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) { + // CS-T: no experts.bin - the model's GGUF shards, read in place + blobs_ = (int64_t) blob_count; + n_layers_ = n_layers; + n_expert_ = n_expert; + layer_offsets_ = std::move(layer_offsets); + layer_blob_bytes_ = std::move(layer_blob_bytes); + if (!open_gguf(err)) { close(); return false; } + return true; + } + +#if defined(_WIN32) + // UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would + // silently mangle it into a file-not-found. + const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); + std::vector wpath((size_t) (wide > 0 ? wide : 1)); + if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); + // **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.** + // + // The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has + // 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM. `FILE_FLAG_RANDOM_ACCESS` tells + // the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again + // quickly, on the assumption that a large randomly-accessed file will not be re-read. Measured, on + // `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25 + // tokens, because the pages were being evicted as fast as they were faulted in. + // + // The correct flag is NO flag. The access pattern IS random (10 of 512 experts per layer, a different 10 + // each layer), but every byte read is read again on the next token, so retention is the whole game. + HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (f == INVALID_HANDLE_VALUE) { + err = "FileExpertSource: cannot open " + path; + return false; + } + LARGE_INTEGER sz{}; + if (!GetFileSizeEx(f, &sz)) { + CloseHandle(f); + err = "FileExpertSource: cannot size " + path; + return false; + } + if ((uint64_t) sz.QuadPart != want) { + char buf[400]; + std::snprintf(buf, sizeof buf, + "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " + "the pack this geometry came from", + path.c_str(), (unsigned long long) sz.QuadPart, (unsigned long long) want); + CloseHandle(f); + err = buf; + return false; + } + HANDLE m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); + if (m == nullptr) { + CloseHandle(f); + err = "FileExpertSource: CreateFileMapping failed on " + path; + return false; + } + void* view = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); + if (view == nullptr) { + CloseHandle(m); + CloseHandle(f); + err = "FileExpertSource: MapViewOfFile failed on " + path; + return false; + } + file_ = f; + mapping_ = m; + base_ = (const uint8_t*) view; +#else + const int fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; } + struct stat st{}; + if (fstat(fd, &st) != 0) { ::close(fd); err = "FileExpertSource: cannot stat " + path; return false; } + if (st.st_size < 0 || (uint64_t) st.st_size != want) { + char buf[400]; + std::snprintf(buf, sizeof buf, + "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " + "the pack this geometry came from", + path.c_str(), (unsigned long long) (st.st_size < 0 ? 0 : st.st_size), + (unsigned long long) want); + ::close(fd); + err = buf; + return false; + } + void* view = mmap(nullptr, (size_t) want, PROT_READ, MAP_SHARED, fd, 0); + if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; } + fd_ = fd; + base_ = (const uint8_t*) view; +#endif + blobs_ = (int64_t) blob_count; + n_layers_ = n_layers; + n_expert_ = n_expert; + mapped_bytes_ = want; + layer_offsets_ = std::move(layer_offsets); + layer_blob_bytes_ = std::move(layer_blob_bytes); + return true; +} + +void FileExpertSource::close() { + if (complement_arena_ != nullptr) { + if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_); + else { + if (complement_partial_) (void) cudaHostUnregister(complement_arena_); + if (complement_locked_ > 0) + strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_); + std::free(complement_arena_); + } + } + if (xstage_ != nullptr) { + if (xstage_pinned_) (void) cudaFreeHost(xstage_); + else std::free(xstage_); + } + xstage_ = nullptr; + xstage_pinned_ = false; + xstage_cap_ = 0; + xstage_blob_ = 0; + override_.clear(); + staged_.clear(); + exchanges_ = 0; + file_reads_.store(0); + complement_arena_ = nullptr; + complement_host_ = nullptr; + complement_device_ = nullptr; + complement_bytes_ = 0; + complement_offsets_.clear(); + complement_pinned_ = false; + complement_partial_ = false; + complement_pin_limit_ = 0; + complement_lock_off_ = 0; + complement_ready_ = false; + complement_locked_ = 0; + complement_lent_slots_ = 0; + if (!maps_.empty()) { + for (Map& m : maps_) { +#if defined(_WIN32) + if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base); + if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping); + if (m.file != nullptr) CloseHandle((HANDLE) m.file); +#else + if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes); + if (m.fd >= 0) ::close(m.fd); +#endif + } + maps_.clear(); + base_ = nullptr; // one of the views above + } + role_ptr_.clear(); + role_bytes_.clear(); + { + std::lock_guard lk(stage_mu_); + stage_buf_.clear(); + stage_key_.clear(); + stage_epoch_.clear(); + stage_used_.clear(); + stage_busy_.clear(); + stage_of_.clear(); + stage_blob_ = 0; + stage_seq_ = 0; + epoch_ = 0; + last_layer_ = -1; + stage_grew_ = false; + } + ram_reads_.store(0); + warm_stamp_.reset(); + warm_hits_.store(0); + warm_count_.store(0); + file_read_bytes_.store(0); + file_blob_bytes_.store(0); + file_us_.store(0); +#if defined(_WIN32) + if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_); + if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_); + if (file_ != nullptr) CloseHandle((HANDLE) file_); + mapping_ = nullptr; + file_ = nullptr; +#else + if (base_ != nullptr) munmap((void*) base_, (size_t) mapped_bytes_); + if (fd_ >= 0) ::close(fd_); + fd_ = -1; +#endif + base_ = nullptr; + blobs_ = 0; + n_layers_ = 0; + n_expert_ = 0; + mapped_bytes_ = 0; + layer_offsets_.clear(); + layer_blob_bytes_.clear(); + reads_ = 0; +} + + +bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { + const uint8_t* b = blob(layer, expert); + if (b == nullptr || dst == nullptr) return false; + std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer)); + return true; +} + +// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================ +// +// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no +// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows] +// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a +// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed +// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers). +bool FileExpertSource::open_gguf(std::string& err) { + const auto& lay = strata::kernels::cpu::expert_layout(); + if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; } + const size_t cut = gguf_.find_last_of("/\\"); + const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1); + std::map index; + role_ptr_.assign((size_t) (3 * n_layers_), nullptr); + role_bytes_.assign((size_t) (3 * n_layers_), 0); + for (int64_t l = 0; l < n_layers_; ++l) { + const auto& fm = lay.fmt[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off}; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * l + r); + const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i] + : gguf_; + auto it = index.find(path); + if (it == index.end()) { + Map m; +#if defined(_WIN32) + const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); + std::vector wpath((size_t) (wide > 0 ? wide : 1)); + if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide); + HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + LARGE_INTEGER sz{}; + if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) { + if (f != INVALID_HANDLE_VALUE) CloseHandle(f); + err = "FileExpertSource: cannot open " + path; + return false; + } + HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr); + void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr; + if (view == nullptr) { + if (mh != nullptr) CloseHandle(mh); + CloseHandle(f); + err = "FileExpertSource: cannot map " + path; + return false; + } + m.file = f; + m.mapping = mh; + m.bytes = (uint64_t) sz.QuadPart; + m.base = (const uint8_t*) view; +#else + const int fd = ::open(path.c_str(), O_RDONLY); + struct stat st{}; + if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) { + if (fd >= 0) ::close(fd); + err = "FileExpertSource: cannot open " + path; + return false; + } + void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; } + m.fd = fd; + m.bytes = (uint64_t) st.st_size; + m.base = (const uint8_t*) view; +#endif + maps_.push_back(m); + it = index.emplace(path, maps_.size() - 1).first; + } + const Map& m = maps_[it->second]; + const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_; + if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree + err = "FileExpertSource: an expert span runs past the end of " + path; + return false; + } + role_ptr_[i] = m.base + (size_t) at; + role_bytes_[i] = per[r]; + } + } + base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode + warm_stamp_.reset(new std::atomic[(size_t) (n_layers_ * n_expert_)]()); + for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); + return true; +} + +bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const { + if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + if (!role_ptr_.empty()) { + uint64_t at = 0; + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + const uint64_t per = role_bytes_[i]; + std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per); + at += per; + } + return true; + } + const uint8_t* b = mapped_blob(layer, expert); + if (b == nullptr) return false; + std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]); + return true; +} + +// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once +// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes +// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a +// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away. +// +// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or +// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`. +bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) { + constexpr uint64_t kStageSeq = 256; + const uint64_t seq = ++stage_seq_; + auto it = stage_of_.find(key); + fill = false; + if (it != stage_of_.end()) { + v = it->second; + stage_epoch_[v] = epoch_; + stage_used_[v] = seq; + return true; + } + v = stage_buf_.size(); + uint64_t oldest = std::numeric_limits::max(); + for (size_t i = 0; i < stage_buf_.size(); ++i) + if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && + stage_used_[i] < oldest) { + oldest = stage_used_[i]; + v = i; + } + if (v == stage_buf_.size()) { + stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]); + if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; } + stage_key_.push_back(-1); + stage_epoch_.push_back(0); + stage_used_.push_back(0); + stage_busy_.push_back(0); + if (stage_buf_.size() == 512 && !stage_grew_) { + stage_grew_ = true; + std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n", + stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0); + } + } else { + stage_of_.erase(stage_key_[v]); + } + stage_key_[v] = key; + stage_epoch_[v] = epoch_; + stage_used_[v] = seq; + stage_busy_[v] = 1; + stage_of_[key] = v; + fill = true; + return false; +} + +// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it. +bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) { + const auto t0 = std::chrono::steady_clock::now(); + const bool ok = copy_from_files(layer, expert, dst); + const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed); + if (ok) { + file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + } + { + std::lock_guard lk(stage_mu_); + stage_busy_[v] = 0; + if (!ok) { + stage_of_.erase(stage_key_[v]); + stage_key_[v] = -1; + } + } + stage_cv_.notify_all(); + return ok; +} + +const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) { + const int64_t key = layer * n_expert_ + expert; + size_t v = 0; + bool fill = false; + uint8_t* dst = nullptr; + { + std::unique_lock lk(stage_mu_); + const bool have = claim_stage(key, v, fill); + if (!have && !fill) return nullptr; + dst = stage_buf_[v].get(); + if (have) { + // another thread (a prefetch, the adaptive tier) is filling it: wait for that + stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; }); + if (stage_key_[v] != key) return nullptr; // its fill failed + return dst; + } + } + return fill_stage(v, layer, expert, dst) ? dst : nullptr; +} + +void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) { + if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; + struct Fill { size_t v; int64_t e; uint8_t* dst; }; + std::vector todo; + { + std::lock_guard lk(stage_mu_); + for (int64_t i = 0; i < n; ++i) { + const int64_t e = experts[i]; + if (e < 0 || e >= n_expert_) continue; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + continue; // in the RAM copy + if (!override_.empty() && override_[index] != nullptr) continue; + size_t v = 0; + bool fill = false; + if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) { + todo.push_back({v, e, stage_buf_[v].get()}); + if (warm_stamp_) { + const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed); + if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed); + } + } + } + } + if (todo.empty()) return; +#if defined(_WIN32) + // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large + // requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below + // then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm. + { + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = [] { + const char* v = std::getenv("STRATA_FETCH_PVM"); + if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr; + return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + }(); + if (pvm != nullptr) { + std::vector ranges; + ranges.reserve(todo.size() * 3); + for (const Fill& f : todo) + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])), + (SIZE_T) role_bytes_[i]}); + } + (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); + } + } +#endif + // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full + std::atomic next{0}; + auto work = [&] { + for (size_t i; (i = next.fetch_add(1)) < todo.size();) + (void) fill_stage(todo[i].v, layer, todo[i].e, todo[i].dst); + }; + const size_t nt = std::min(todo.size(), (size_t) fetch_threads_); + std::vector th; + for (size_t t = 1; t < nt; ++t) th.emplace_back(work); + work(); + for (auto& t : th) t.join(); +} + + +void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { + if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; + uint32_t stamp; + { + std::lock_guard lk(stage_mu_); + stamp = (uint32_t) epoch_ + 1; + } +#if defined(_WIN32) + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + std::vector ranges; +#endif + for (int64_t j = 0; j < n; ++j) { + const int64_t e = experts[j]; + if (e < 0 || e >= n_expert_) continue; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + continue; // in the RAM copy + if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); + warm_count_.fetch_add(1, std::memory_order_relaxed); + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]); +#if defined(_WIN32) + ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]}); +#else + const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1); + (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED); +#endif + } + } +#if defined(_WIN32) + if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); +#endif +} + +RouterLookahead::~RouterLookahead() { + { + std::lock_guard lk(mu_); + quit_ = true; + } + cv_.notify_all(); + if (thread_.joinable()) thread_.join(); +} + +bool RouterLookahead::start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, + ExpertSource* src, std::string& err) { + if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; } + if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; } + for (const auto& r : routers) + if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; } + routers_ = std::move(routers); + n_embd_ = n_embd; + n_expert_ = n_expert; + k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; + src_ = src; + x_.assign((size_t) (8 * n_embd), 0.f); + thread_ = std::thread([this] { run(); }); + return true; +} + +void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) { + if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return; + { + std::lock_guard lk(mu_); + if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; } + n_tok_ = std::min(n_tok, 8); + std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float)); + layer_ = layer + 1; + host_res_ = host_res; + pending_ = true; + } + cv_.notify_one(); +} + +void RouterLookahead::run() { + std::vector logits((size_t) (8 * n_expert_)); + std::vector order((size_t) n_expert_); + std::vector want; + for (;;) { + int64_t layer, nt; + const int32_t* host_res; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return quit_ || pending_; }); + if (quit_) return; + pending_ = false; + busy_ = true; + layer = layer_; + nt = n_tok_; + host_res = host_res_; + } + const auto t0 = std::chrono::steady_clock::now(); + want.clear(); + strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_, + x_.data(), (int) nt, logits.data()); + for (int64_t t = 0; t < nt; ++t) { + const float* lt = logits.data() + (size_t) (t * n_expert_); + for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; + std::partial_sort(order.begin(), order.begin() + k_, order.end(), + [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); + for (int j = 0; j < k_; ++j) { + const int64_t e = order[(size_t) j]; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU + if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); + } + } + src_->warm(layer, want.data(), (int64_t) want.size()); + predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed); + busy_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + { + std::lock_guard lk(mu_); + busy_ = false; + } + } +} + +void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { + (void) ids; + (void) k; + if (role_ptr_.empty()) return; + std::lock_guard lk(stage_mu_); + if (layer != last_layer_) { + ++epoch_; + last_layer_ = layer; + } +} + +bool FileExpertSource::transient(int64_t layer, int64_t expert) const { + if (role_ptr_.empty() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + return false; + return override_.empty() || override_[index] == nullptr; +} + +bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { + if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) + return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + const uint64_t bytes = layer_blob_bytes_[(size_t) layer]; + if (complement_ready_) { + const uint8_t* held = + detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + if (held == nullptr && !override_.empty()) held = override_[index]; + if (held != nullptr) { + std::memcpy(dst, held, (size_t) bytes); + return true; + } + } + const auto t0 = std::chrono::steady_clock::now(); + if (!copy_from_files(layer, expert, dst)) return false; + file_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed); + return true; +} + +const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const { + if (!role_ptr_.empty()) return nullptr; // the GGUF in place: no contiguous blob in any file + if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; + const size_t i = (size_t) layer; + if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr; + const uint64_t blob_bytes = layer_blob_bytes_[i]; + if (blob_bytes == 0 || (uint64_t) expert > std::numeric_limits::max() / blob_bytes) return nullptr; + const uint64_t expert_offset = (uint64_t) expert * blob_bytes; + const uint64_t layer_offset = layer_offsets_[i]; + if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset) return nullptr; + const uint64_t offset = layer_offset + expert_offset; + if (blob_bytes > mapped_bytes_ - offset) return nullptr; + return base_ + (size_t) offset; +} + +bool FileExpertSource::pin_cache_complement( + const ExpertCache& cache, std::string& err, bool pin, + const std::vector>& additional_gpu_pairs, int64_t lend_from_slot, + uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector>* rank) { + err.clear(); + if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; } + if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; } + if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; } + if (cache.fills() != cache.resident()) { + err = "FileExpertSource: the GPU expert cache is not fully filled"; + return false; + } + const cudaError_t sync = cudaDeviceSynchronize(); + if (sync != cudaSuccess) { + err = std::string("FileExpertSource: GPU expert cache is not ready: ") + cudaGetErrorString(sync); + (void) cudaGetLastError(); + return false; + } + + // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below). + const int64_t n_slots = cache.slots(); + std::vector> primary_gpu_pairs; + std::vector pair_slot; + std::vector slot_bytes((size_t) std::max(n_slots, 0), 0); + primary_gpu_pairs.reserve((size_t) cache.resident()); + pair_slot.reserve((size_t) cache.resident()); + for (int64_t layer = 0; layer < n_layers_; ++layer) { + for (int64_t expert = 0; expert < n_expert_; ++expert) { + const int32_t slot = cache.slot_of(layer, expert); + if (slot == kNotResident) continue; + primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert); + pair_slot.push_back(slot); + if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer]; + } + } + std::vector offsets; + uint64_t bytes = 0; + if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs, + additional_gpu_pairs, offsets, bytes, err)) return false; +#if defined(_WIN32) + // #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows + // counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here + // (20.7 GiB before the start). Trimmed, they move to the standby list (still cached, counted as available). + // Resident mode only: nothing else calls this function. Locked/pinned pages stay; the rest fault back softly. + { + uint64_t before = 0, after = 0; + const bool read_before = available_memory_bytes(before); + (void) SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1); + if (read_before && available_memory_bytes(after)) + std::fprintf(stderr, "FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the " + "process working set (#467)\n", + (double) before / 1073741824.0, (double) after / 1073741824.0); + } +#endif + const bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try + uint64_t budget_physical = 0; // #403: the RAM reading a budget was sized from (0: no budget) + if (budget_bytes > 0) { + // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while + // they fit, the rest left on the mapped files; clamped to what the RAM has room for. + uint64_t physical = 0; + if (!available_memory_bytes(physical)) { + err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib"; + return false; + } + budget_physical = physical; + const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0; + if (budget_bytes > room) { + // #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the + // headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB + // lower). An unclamped budget is unchanged. + const uint64_t margin = 256ull << 20; + const uint64_t clamped = room > margin ? room - margin : 0; + if (what_fits) + std::fprintf(stderr, "FileExpertSource: RAM room for the complement: %.2f GiB (%.2f GiB available " + "minus %.0f GiB headroom and a 0.25 GiB margin)\n", + (double) clamped / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0); + else + std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for " + "(%.2f GiB available minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n", + (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0); + budget_bytes = clamped; + } + std::vector ranked(offsets.size(), kNoComplement); + uint64_t at = 0; + int64_t held = 0; + if (rank != nullptr) + for (const auto& pr : *rank) { + if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue; + const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second; + if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue; // on a GPU, or twice + const uint64_t b = layer_blob_bytes_[(size_t) pr.first]; + if (b > budget_bytes - at) continue; + ranked[i] = at; + at += b; + ++held; + } + if (what_fits && held == 0) { // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy + err = "FileExpertSource: the RAM has no room for any expert of the complement"; + return false; + } + std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " + "not hold, by profile rank; the rest are read from the files\n", + (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0); + offsets.swap(ranked); + bytes = at; + lend_from_slot = -1; + } + + const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty(); + uint64_t budget = std::numeric_limits::max(); + if (bytes > 0 || lend) { + // #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own + // allocations, the file cache) failed a budget the first one had clamped. (A budget turns `lend` off.) + uint64_t physical = budget_physical; + if (physical == 0 && !available_memory_bytes(physical)) { + err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check"; + return false; + } + budget = physical > headroom_bytes ? physical - headroom_bytes : 0; + if (bytes > budget) { + char message[320]; + std::snprintf(message, sizeof message, + "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the " + "%.0f GiB safety headroom", + (double) bytes / 1073741824.0, (double) physical / 1073741824.0, + (double) headroom_bytes / 1073741824.0); + err = message; + return false; + } + } + // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into + // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends + // only the last few). The rest keep the mapped-file fallback. + int64_t keep_from = n_slots; + if (lend) { + keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot); + if (keep_from < 0) keep_from = n_slots; + if (keep_from < n_slots) { + std::vector> core; + core.reserve(primary_gpu_pairs.size()); + for (size_t i = 0; i < primary_gpu_pairs.size(); ++i) + if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]); + if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core, + additional_gpu_pairs, offsets, bytes, err)) return false; + } + } + + void* arena = nullptr; + const uint8_t* host = nullptr; + const uint8_t* device = nullptr; + bool pinned_ok = false; + uint64_t locked = 0; + uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena + uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix) + std::string note; + auto release = [&]() { + if (arena == nullptr) return; + if (pinned_ok) (void) cudaFreeHost(arena); + else { + if (partial_pin > 0) (void) cudaHostUnregister(arena); + if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked); + std::free(arena); + } + arena = nullptr; + }; + if (bytes > 0) { + std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n", + (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident"); + std::fflush(stderr); + if (pin) { + const cudaError_t allocated = cudaHostAlloc(&arena, (size_t) bytes, + cudaHostAllocMapped | cudaHostAllocPortable); + if (allocated == cudaSuccess) { + void* alias = nullptr; + const cudaError_t aliased = cudaHostGetDevicePointer(&alias, arena, 0); + if (aliased == cudaSuccess && alias != nullptr) { + device = (const uint8_t*) alias; + pinned_ok = true; + note = "page-locked and mapped"; + } else { + note = std::string("no device alias (") + cudaGetErrorString(aliased) + ")"; + (void) cudaGetLastError(); + (void) cudaFreeHost(arena); + arena = nullptr; + } + } else { + // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working + // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA. + note = std::string("page-locking refused (") + cudaGetErrorString(allocated) + ")"; + (void) cudaGetLastError(); + arena = nullptr; + } + } + if (arena == nullptr) { + arena = std::malloc((size_t) bytes); + if (arena == nullptr) { + err = "FileExpertSource: pageable resident complement allocation failed"; + return false; + } + if (pin) { + // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to + // register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be + // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working + // set (the registered prefix is page-locked by the driver already - locking it twice made the next + // device allocation fail). + // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no + // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74 + // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure + static const bool partial_on = [] { + const char* v = std::getenv("STRATA_PARTIAL_PIN"); + return v != nullptr && std::atoi(v) != 0; + }(); + // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver + // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM) + static const uint64_t pin_cap = [] { + const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB"); + return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0); + }(); + if (budget_bytes > 0 && partial_on) { + const uint64_t step = 2ull << 30; + for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) { + // cut at an expert boundary: a blob that started inside the registered range and ran past it + // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed") + uint64_t w = want; + for (size_t i = 0; i < offsets.size(); ++i) { + if (offsets[i] == kNoComplement) continue; + const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_]; + if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; } + } + if (w == 0) break; + if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == + cudaSuccess) { + void* alias = nullptr; + if (cudaHostGetDevicePointer(&alias, arena, 0) == cudaSuccess && alias != nullptr) { + device = (const uint8_t*) alias; + partial_pin = w; + } else { + (void) cudaGetLastError(); + (void) cudaHostUnregister(arena); + } + break; + } + (void) cudaGetLastError(); + if (want <= step) break; + } + char msg[160]; + std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)", + (double) partial_pin / 1073741824.0); + note += std::string("; ") + msg; + } + lock_off = partial_pin; + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off); + locked = lr.locked_bytes; + note += (note.empty() ? "" : "; ") + lr.note; + } + } + host = (const uint8_t*) arena; + } + + // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap. +#if !defined(_WIN32) + const long page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0) { + err = "FileExpertSource: cannot determine page size for mapped-page release"; + release(); + return false; + } +#endif + std::atomic next_layer{0}, layers_done{0}; + std::atomic copied{0}; + std::atomic failed{false}; + std::mutex fail_mu; + std::string fail_msg; + auto fail = [&](const std::string& m) { + std::lock_guard lock(fail_mu); + if (fail_msg.empty()) fail_msg = m; + failed.store(true); + }; + auto worker = [&]() { + for (;;) { + const int64_t layer = next_layer.fetch_add(1); + if (layer >= n_layers_ || failed.load()) return; + const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer]; + for (int64_t expert = 0; expert < n_expert_; ++expert) { + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + const uint64_t offset = offsets[index]; + if (offset == kNoComplement) continue; + if (offset > bytes || blob_bytes > bytes - offset || + !copy_from_files(layer, expert, (uint8_t*) host + (size_t) offset)) { + fail("FileExpertSource: invalid blob bounds while building the cache complement"); + return; + } + copied.fetch_add(blob_bytes); + } +#if !defined(_WIN32) + if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OS + const uint64_t layer_offset = layer_offsets_[(size_t) layer]; + const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_; + const uint64_t layer_end = layer_offset + layer_bytes; + const uint64_t page = (uint64_t) page_size; + const uint64_t advice_start = layer_offset - layer_offset % page; + const uint64_t end_remainder = layer_end % page; + const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder; + const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra; + if (advice_end > advice_start && + madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) { + fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer)); + return; + } + if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) { + fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer)); + return; + } + } +#endif + const int64_t done = layers_done.fetch_add(1) + 1; + if (done % 8 == 0 || done == n_layers_) + std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n", + (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0); + } + }; + { + const int threads = (int) std::max(1, std::min(6, n_layers_)); + std::vector pool; + for (int i = 1; i < threads; ++i) pool.emplace_back(worker); + worker(); + for (auto& t : pool) t.join(); + } + std::fflush(stderr); + if (failed.load()) { + err = fail_msg; + release(); + return false; + } +#if defined(_WIN32) + // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the + // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). + if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_); + for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes); +#endif + + complement_arena_ = arena; + complement_host_ = host; + complement_device_ = device; + complement_bytes_ = bytes; + complement_offsets_ = std::move(offsets); + complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0; + complement_pin_limit_ = pinned_ok ? bytes : partial_pin; + complement_partial_ = !pinned_ok && partial_pin > 0; + complement_locked_ = locked; + complement_lock_off_ = lock_off; + complement_lent_slots_ = lend ? n_slots - keep_from : 0; + complement_ready_ = true; + std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n", + complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident", + (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0, + note.empty() ? "" : "; ", note.c_str()); + if (lend) + std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " + "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot), + complement_lent_slots_ < n_slots - lend_from_slot + ? " (the others are read from the file when lent: not enough RAM for them)" : ""); + if (!additional_gpu_pairs.empty()) { + std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n", + additional_gpu_pairs.size()); + } + std::fflush(stderr); + return true; +} + +bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const { + if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement; +} + +bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { + err.clear(); + if (n <= xstage_cap_) return true; + if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; } + uint64_t blob = 0; + for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b); + if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; } + if (xstage_ != nullptr) { + if (xstage_pinned_) (void) cudaFreeHost(xstage_); + else std::free(xstage_); + xstage_ = nullptr; + xstage_cap_ = 0; + } + const size_t total = (size_t) n * (size_t) blob; + void* p = nullptr; + if (cudaHostAlloc(&p, total, cudaHostAllocDefault) == cudaSuccess && p != nullptr) { + xstage_pinned_ = true; + } else { + (void) cudaGetLastError(); + p = std::malloc(total); + xstage_pinned_ = false; + if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; } + } + xstage_ = (uint8_t*) p; + xstage_cap_ = n; + xstage_blob_ = blob; + return true; +} + +uint8_t* FileExpertSource::exchange_buffer(int64_t q) const { + if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr; + return xstage_ + (size_t) q * (size_t) xstage_blob_; +} + +bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) { + if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false; + const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in; + const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out; + if (override_.empty()) override_.assign((size_t) blobs_, nullptr); + if (override_[i_out] != nullptr) return false; + for (const Exchange& x : staged_) + if (x.in == i_in || x.q == q) return false; + override_[i_out] = exchange_buffer(q); + staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]}); + return true; +} + +int64_t FileExpertSource::commit_exchanges() { + int64_t n = 0; + for (const Exchange& x : staged_) { + const uint8_t* src = override_[x.out]; + const uint64_t at = complement_offsets_[x.in]; + if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && + complement_host_ != nullptr) { + std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes); + if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n; + } + override_[x.out] = nullptr; + } + staged_.clear(); + exchanges_ += n; + return n; +} + +const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { + if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + const uint8_t* result = nullptr; + bool from_files = true; + if (complement_ready_) { + result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + if (result != nullptr) { + ram_reads_.fetch_add(1, std::memory_order_relaxed); + from_files = false; + } else if (!override_.empty() && override_[index] != nullptr) { + result = override_[index]; + from_files = false; + } + } + if (from_files) { + if (!role_ptr_.empty()) { + result = staged_blob(layer, expert); // counts its bytes + } else { + result = mapped_blob(layer, expert); + if (result != nullptr) + file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed); + } + if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed); + } + if (result != nullptr) ++reads_; + return result; +} + +bool FileExpertSource::pinned(int64_t layer, int64_t expert) const { + if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 || + layer >= n_layers_ || expert >= n_expert_) return false; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false; + // a partial pin (CS-T): only the registered prefix + return !complement_partial_ || + complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_; +} + +const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const { + if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + return complement_device_ + (size_t) complement_offsets_[index]; +} + +bool FileExpertSource::pcie_layer(int64_t layer) const { + if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr) + return layer >= 0 && layer < n_layers_; + return device_alias(layer, 0) != nullptr; +} + +// ================================ THE ADAPTER ================================ + +void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, + int64_t k, float* out) { + (void) weights; // clause 2: `moe_combine` applies it on the device. Not an oversight. + ExpertDispatch& d = *(ExpertDispatch*) user; + if (d.failed) return; // a previous layer already failed; do not make it worse + + using namespace strata::kernels::cpu; + // Clause 3: the blob's internal offsets are compile-time constants, so a mismatched geometry does not + // produce a wrong answer - it produces a walk off the end of the blob into the next expert's bytes, which + // is finite and plausible. Refuse, name the number, and let the driver report it. + if (n_embd != H) { + d.failed = true; + d.fail = "the expert kernel is compiled for a 2560-wide activation"; + d.fail_layer = d.layers; + return; + } + if (expert_layout().native) { + // plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it) + d.failed = true; + d.fail = "the single-token expert path does not take a native (IQ) pack"; + d.fail_layer = d.layers; + return; + } + if (k > (int64_t) d.jobs.size()) d.jobs.resize((size_t) k); + + d.src->begin_layer(d.layers, ids, k); + + // Clause 1: rebuilt from `x_f` on EVERY call. `x_f` is mapped pinned memory whose address never changes, + // so anything cached against it would be layer 0's activation reused 48 times. + act_quant_q8_1(x_f, H, d.act); + + // ---- R4.2c: THE POOL'S HALF OF THE SPLIT. **IT DOES NOT DECIDE ANYTHING - `Launch` ALREADY DID.** + // + // The decision has to be made on THIS layer's ids, and `Launch` is the only callback that runs before the + // pool while the ids are known (the doorbell publishes them when the ring fires). So `expert_hit_run` + // decides, and this consumes `d.is_hit`. The first version decided here instead, which meant `Launch` + // computed the PREVIOUS layer's experts into this layer's rows: C1 went from mean KL 9.69e-02 to 1.03e+00. + // + // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a hit. + const bool graph_hits = d.host_res != nullptr; + const bool use_hits = graph_hits || (d.hits_ready() && d.decided); + int64_t njobs = 0; + + if (d.remote_count > 0) { + int32_t kind[32]; + if (k > 32) { + d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return; + } + for (int64_t i = 0; i < k; ++i) + kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits + ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0 + : d.is_hit[(size_t) i] != 0) ? 0 : -1; + static thread_local std::string remote_error; + for (int r = 0; r < d.remote_count; ++r) + if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) { + d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; + } + } + + for (int64_t i = 0; i < k; ++i) { + const int64_t e = ids[i]; + if (e < 0 || e >= d.n_expert) { + d.failed = true; + d.fail = "a routed expert id is out of range"; + d.fail_layer = d.layers; + d.fail_expert = e; + return; + } + const uint8_t* b = d.src->blob(d.layers, e); + if (b == nullptr) { + // The one failure the loop cannot see. Leaving `out` at its previous contents would feed the NEXT + // layer a stale expert vector, which `moe_combine` would weight and add - the token would still be + // finite and would still be wrong, 48 layers deep. + d.failed = true; + d.fail = "the expert source could not produce a blob"; + d.fail_layer = d.layers; + d.fail_expert = e; + ++d.missing; + return; + } + // A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it. + if (use_hits && (graph_hits ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0 + : d.is_hit[(size_t) i] != 0)) { + if (graph_hits) ++d.cache_hits; + // The GPU owns this row and `hit_out` is zeroed, so the CPU's contribution is zero - but + // `y_miss` is a REUSED pinned buffer, so the row must be written, not merely skipped. + std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float)); + continue; + } + if (graph_hits) ++d.cache_refused; // token graph: a miss (nothing is admitted during a token) + + bool remote_owns = false; + for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i); + if (remote_owns) { + std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float)); + continue; + } + + // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a + // hit, and using one for the other is how a hit's row would get two experts summed into it. + ExpertJob& j = d.jobs[(size_t) njobs++]; + j.blob = b; + j.act = &d.act; // SHARED across the batch: one conversion serves all ten experts + j.out = out + (size_t) i * (size_t) n_embd; + j.weight = 1.0f; // clause 2: a diagnostic field, NOT the router weight + j.slot = (int) i; + } + + // Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`). + if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs); + else d.pool->run(d.jobs.data(), (int) njobs); + if (d.remote_count > 0) { + static thread_local std::string remote_error; + for (int r = 0; r < d.remote_count; ++r) + if (!d.remote[r]->finish(out, remote_error)) { + d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; + } + } + ++d.layers; + d.experts += k; +} + +namespace { +// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`) +// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is +// refused at run time rather than written past them. +constexpr int64_t kMaxWindowEntries = 128; +static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables"); +} // namespace + +void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, + float* out) { + using namespace strata::kernels::cpu; + if (d.failed) return; + if (n_tok < 1 || n_tok > MAXT) { + d.failed = true; + d.fail = "a verify window has more tokens than the multi-token expert kernel takes"; + d.fail_layer = d.layers; + return; + } + if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 + if (k < 1 || n_tok * k > kMaxWindowEntries) { + d.failed = true; + d.fail = "a verify window routes more entries than the expert pool's window tables hold"; + d.fail_layer = d.layers; + return; + } + if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT); + const ExpertLayout& lay = expert_layout(); + const bool native = lay.native; + if (native && d.nact_multi.size() < (size_t) MAXT * kNativeActBytes) d.nact_multi.resize((size_t) MAXT * kNativeActBytes); + if (d.job_of.size() != (size_t) d.n_expert) d.job_of.assign((size_t) d.n_expert, (int16_t) -1); + if (d.jobs_multi.size() < (size_t) (n_tok * k)) d.jobs_multi.resize((size_t) (MAXT * k)); + static const bool ptrace = std::getenv("STRATA_POOL_TRACE") != nullptr; + auto pt = [&](const char* what, long long a = -1) { + if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); } + }; + const auto c0 = std::chrono::steady_clock::now(); + pt("begin"); + d.src->begin_layer(d.layers, ids, n_tok * k); + pt("begun"); + if (!d.usage.empty()) + for (int64_t i = 0; i < n_tok * k; ++i) + if (ids[i] >= 0 && ids[i] < d.n_expert) d.usage[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] += 1.0f; + // ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works. + // Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU. + const int64_t n = n_tok * k; + int32_t kind[kMaxWindowEntries]; // per entry: -1 CPU, 0 VRAM, 1 PCIe + if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) { + int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries]; + int nd = 0, nmiss = 0; + for (int64_t i = 0; i < n; ++i) { + first_of[i] = i; + for (int64_t j = 0; j < i; ++j) + if (ids[j] == ids[i]) { first_of[i] = first_of[j]; break; } + if (first_of[i] == i) { + distinct[nd++] = i; + const int32_t e = ids[i]; + if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0) ++nmiss; + } + } + const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); + const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0; + int miss_rank = 0, groups = 0, entries = 0, fetches = 0; + GpuPlanSink& P = *d.plan; + const uint8_t* dma_src[64]; + int64_t pcie_i0[64]; + for (int q = 0; q < nd; ++q) { + const int64_t i0 = distinct[q]; + const int32_t e = ids[i0]; + int kd = -1; + unsigned long long ptr = 0; + if (e >= 0 && e < d.n_expert) { + const int32_t slot = d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e]; + if (slot >= 0) { + kd = 0; + ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot] + : (size_t) slot * (size_t) d.cache_blob)); + } else { + if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) { + const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr; + if (src != nullptr) { + kd = 1; + dma_src[fetches] = src; + pcie_i0[fetches] = i0; + ++fetches; + } + } + ++miss_rank; + } + } + for (int64_t i = i0; i < n; ++i) + if (first_of[i] == i0) kind[i] = kd; + if (kd != 0) continue; // the VRAM groups first; the PCIe groups below + P.ptr[groups] = ptr; + P.start[groups] = entries; + for (int64_t i = i0; i < n; ++i) + if (first_of[i] == i0) { + P.dst[entries] = (int32_t) i; + P.tok[entries] = (int32_t) (i / k); + ++entries; + } + ++groups; + } + P.start[groups] = entries; + const uint64_t bb = lay.blob_bytes(d.layers); + for (int q = 0; q < fetches; ++q) { // the PCIe groups: staging slot q, entries after the VRAM ones + const int64_t i0 = pcie_i0[q]; + P.ptr2[q] = P.pcie_mode != 0 ? (unsigned long long) d.src->device_alias(d.layers, ids[i0]) + : P.staging + (unsigned long long) q * (unsigned long long) bb; + P.start2[q] = entries; + for (int64_t i = i0; i < n; ++i) + if (first_of[i] == i0) { + P.dst[entries] = (int32_t) i; + P.tok[entries] = (int32_t) (i / k); + ++entries; + } + ++d.pcie_experts; + } + P.start2[fetches] = entries; + P.counts[0] = groups; + P.counts[1] = entries; + P.counts[2] = fetches; + std::atomic_thread_fence(std::memory_order_seq_cst); + pt("publish", fetches); + if (P.publish) P.publish(P.ctx); + pt("fetch", fetches); + if (P.fetch) P.fetch(P.ctx, dma_src, P.pcie_mode != 0 ? 0 : fetches, (size_t) bb); // the copy engine, beside the CPU's work + } else { + for (int64_t i = 0; i < n; ++i) { + const int32_t e = ids[i]; + kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr && + d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0 : -1; + } + } + if (d.remote_count > 0) { + static thread_local std::string remote_error; + for (int r = 0; r < d.remote_count; ++r) { + if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) { + d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; + } + for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; + } + } + if (d.experimental_miss != nullptr) { + static thread_local std::string miss_error; + if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids, + n_tok, k, kind, out, miss_error)) { + d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return; + } + } + const auto c1 = std::chrono::steady_clock::now(); + if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations + for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); + else if (native) + for (int64_t t = 0; t < n_tok; ++t) + native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes); + else + for (int64_t t = 0; t < n_tok; ++t) act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); + const auto c2 = std::chrono::steady_clock::now(); + { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads) + static thread_local std::vector miss; + miss.clear(); + for (int64_t i = 0; i < n_tok * k; ++i) + if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert && + std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end()) + miss.push_back(ids[i]); + d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size()); + } + int njobs = 0; + for (int64_t t = 0; t < n_tok; ++t) + for (int64_t j = 0; j < k; ++j) { + const int64_t i = t * k + j; + const int64_t e = ids[i]; + float* row = out + (size_t) i * H; + if (e < 0 || e >= d.n_expert) { + d.failed = true; + d.fail = "a routed expert id is out of range"; + d.fail_layer = d.layers; + d.fail_expert = e; + return; + } + if (kind[i] >= 0) { // CUDA0, PCIe, remote, or completed experimental host row + if (kind[i] == 0) ++d.cache_hits; + if (kind[i] == 3) ++d.cache_refused; + else std::memset(row, 0, (size_t) H * sizeof(float)); + continue; + } + ++d.cache_refused; + int16_t& jo = d.job_of[(size_t) e]; + if (jo < 0) { + const uint8_t* b = d.src->blob(d.layers, e); + if (b == nullptr) { + d.failed = true; + d.fail = "the expert source could not produce a blob"; + d.fail_layer = d.layers; + d.fail_expert = e; + ++d.missing; + return; + } + jo = (int16_t) njobs++; + ExpertJobMulti& nj = d.jobs_multi[(size_t) jo]; + nj.blob = b; + nj.nt = 0; + } + ExpertJobMulti& jb = d.jobs_multi[(size_t) jo]; + jb.act[jb.nt] = &d.act_multi[(size_t) t]; + jb.nact[jb.nt] = native ? d.nact_multi.data() + (size_t) t * kNativeActBytes : nullptr; + jb.out[jb.nt] = row; + ++jb.nt; + ++d.multi_entries; + } + const auto c3 = std::chrono::steady_clock::now(); + pt("run", njobs); + if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs); + else d.pool->run_split_multi(d.jobs_multi.data(), njobs); + if (d.remote_count > 0) { + static thread_local std::string remote_error; + for (int r = 0; r < d.remote_count; ++r) + if (!d.remote[r]->finish(out, remote_error)) { + d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return; + } + } + const auto c4 = std::chrono::steady_clock::now(); + pt("ran"); + auto ms = [](auto a, auto b) { return std::chrono::duration(b - a).count(); }; + d.ms_plan += ms(c0, c1); + d.ms_actq += ms(c1, c2); + d.ms_jobs += ms(c2, c3); + d.ms_run += ms(c3, c4); + for (int64_t i = 0; i < n_tok * k; ++i) { + const int64_t e = ids[i]; + if (e >= 0 && e < d.n_expert) d.job_of[(size_t) e] = -1; + } + d.multi_misses += njobs; + ++d.layers; + d.experts += n_tok * k; +} + +void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k) { + ExpertDispatch& d = *(ExpertDispatch*) user; + if (d.failed) return; + cudaStream_t cs = (cudaStream_t) stream; + + if (phase == HitPhase::Launch) { + d.decided = false; + d.hit_pending = false; + if (!d.hits_ready() || ids == nullptr || k <= 0) return; + if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k); + + // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================ + // + // Every routed expert is asked of the cache. Resident -> the GPU computes it. Not resident -> it is + // admitted and filled if there is room (which makes it a hit on THIS call, because the fill and the + // kernel are on one stream in that order), and otherwise it stays a miss for the CPU. + d.n_hits = 0; + for (int64_t i = 0; i < k; ++i) { + const int64_t e = ids[i]; + d.is_hit[(size_t) i] = 0; + if (e < 0 || e >= d.n_expert) continue; // out of range: the pool refuses it, with a message + int32_t slot = d.cache->slot_of(d.layers, e); + if (slot == kNotResident) { + const int32_t cand = d.cache->admit(d.layers, e); + if (cand == kNotResident) { + ++d.cache_refused; + continue; + } + // `blob` is asked ONLY for an expert about to be filled, so the source's read counter stays a + // count of distinct experts moved rather than of looks. + const uint8_t* b = d.src->blob(d.layers, e); + std::string ferr; + if (b == nullptr || !d.cache->fill_slot(cand, b, cs, ferr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(d.layers))) { + d.failed = true; + d.fail = "the expert cache could not fill a slot"; + d.fail_layer = d.layers; + d.fail_expert = e; + return; + } + ++d.cache_admitted; + slot = cand; + } else { + ++d.cache_hits; + } + d.is_hit[(size_t) i] = 1; + d.h_slot[(size_t) d.n_hits] = slot; + d.h_dst[(size_t) d.n_hits] = (int32_t) i; + ++d.n_hits; + } + d.decided = true; + if (d.n_hits <= 0) return; // nothing resident yet: no GPU work, and nothing for `Combine` to add + + const size_t list_bytes = (size_t) d.n_hits * sizeof(int32_t); + // `hit_out` is ZEROED rather than overwritten: the kernel writes only the rows this layer's hits own, + // so a row that was a hit last layer and a miss this one would still hold last layer's expert and + // `add_inplace` would sum it in. Finite, plausible, wrong. + if (cudaMemsetAsync(d.hit_out, 0, (size_t) d.parts_elems * sizeof(float), cs) != cudaSuccess || + cudaMemcpyAsync(d.d_slot, d.h_slot.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess || + cudaMemcpyAsync(d.d_dst, d.h_dst.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess) { + d.hit_fail = "the hit list could not be staged"; + d.failed = true; + d.fail = d.hit_fail; + return; + } + // The activation is quantized HERE rather than reused from `s.moe.x_q8_0`, which `post[l-1]` wrote from + // the PREVIOUS layer's `mixed`. `pre[l]` has since overwritten `mixed`, so that buffer is a layer stale + // - and a stale activation produces a perfectly finite expert for the wrong input. + // **R4.2h: THE SCALED QUANTIZER, SO A HIT REPRODUCES A MISS.** The CPU pool quantizes this same + // activation with `act_quant_q8_1` and multiplies by the fp32 `ActQ::scale`; `quantize_q8_0` writes + // an fp16 `d` instead, and `bench/micro/act_quant_parity.cu` measured **80 of 80 chunks differing by + // up to 4.761e-04 relative**. `quantize_q8_0_scaled` adopts the CPU's rule and scale, and the kernel + // takes the fp32 array. Falling back to the old path would silently reintroduce the divergence, so + // the scales are required here rather than optional. + if (d.x_q8_0_hit_scale == nullptr) { + d.failed = true; + d.fail = "the hit path has no fp32 activation scales (R4.2h)"; + return; + } + strata::kernels::quantize_q8_0_scaled(d.mixed, d.x_q8_0_hit, d.x_q8_0_hit_scale, strata::kernels::cpu::H, + cs); + if (d.hit_cpu_order) + strata::kernels::moe_hit_grouped_s2_cpu_order(d.cache_base, d.d_slot, d.d_dst, d.n_hits, + d.cache_blob, d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale); + else + strata::kernels::moe_hit_grouped_s2(d.cache_base, d.d_slot, d.d_dst, d.n_hits, d.cache_blob, + d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale); + d.hit_pending = true; + if (d.hit_done != nullptr) cudaEventRecord((cudaEvent_t) d.hit_done, cs); + // The A/B arm: ONE driver entry here, and nothing else changes. If the work was waiting for the host + // to enter the driver, this is what lets it start while the pool runs. + if (d.hit_poke && d.hit_done != nullptr) (void) cudaEventQuery((cudaEvent_t) d.hit_done); + return; + } + + // Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`. + if (!d.hit_pending) return; + d.hit_pending = false; + // Did the GPU get the hit work done while the CPU was in the pool? This query is itself a driver entry, + // so it is the LAST chance to observe a late start: a NOT-READY here means the work had not finished by the + // time the pool returned, and with no poke in front of it that can only be because it began after. + if (d.hit_done != nullptr) { + if (cudaEventQuery((cudaEvent_t) d.hit_done) == cudaSuccess) ++d.hit_ready; + else ++d.hit_late; + } + strata::kernels::add_inplace(d.parts_out, d.hit_out, d.parts_elems, cs); +} + +// ================================ THE RESIDENT ARENA (R2.1) ================================ + +namespace { + +void hash_u64(uint64_t& h, uint64_t v) { + h = fnv1a64((const uint8_t*) &v, sizeof v, h); +} + +void hash_text(uint64_t& h, const std::string& s) { + h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h); +} + +bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { + hash_text(h, path.filename().string()); + std::ifstream f(path, std::ios::binary); + if (!f) { + hash_u64(h, 0); + return true; + } + hash_u64(h, 1); + std::vector buf(64u << 10); + for (;;) { + f.read((char*) buf.data(), (std::streamsize) buf.size()); + const std::streamsize n = f.gcount(); + if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h); + if (f.eof()) break; + if (!f) { + err = "ArenaExpertSource: cannot hash pack metadata " + path.string(); + return false; + } + } + return true; +} + +bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) { + err = "ArenaExpertSource: cannot sample pack source " + path.string(); + return false; + } + const std::streamoff end = f.tellg(); + if (end < 0) { + err = "ArenaExpertSource: cannot size pack source " + path.string(); + return false; + } + const uint64_t bytes = (uint64_t) end; + hash_text(h, path.filename().string()); + hash_u64(h, bytes); + constexpr uint64_t sample = 64u << 10; + const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0}; + std::vector buf((size_t) std::min(sample, bytes)); + for (uint64_t off : starts) { + if (buf.empty()) break; + const uint64_t at = std::min(off, bytes - (uint64_t) buf.size()); + f.clear(); + f.seekg((std::streamoff) at); + f.read((char*) buf.data(), (std::streamsize) buf.size()); + if ((size_t) f.gcount() != buf.size()) { + err = "ArenaExpertSource: short read while hashing pack source " + path.string(); + return false; + } + hash_u64(h, at); + h = fnv1a64(buf.data(), (uint64_t) buf.size(), h); + } + return true; +} + +bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path, + const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, + uint64_t& out, std::string& err) { + uint64_t h = 1469598103934665603ull; + hash_text(h, "strata-shared-expert-arena-pack-v1"); + hash_u64(h, (uint64_t) lay.n_layers); + hash_u64(h, (uint64_t) lay.n_expert); + hash_u64(h, lay.total); + hash_u64(h, lay.max_blob); + hash_u64(h, lay.native ? 1 : 0); + + const std::filesystem::path pack(pack_dir); + for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) { + if (!hash_small_file(pack / name, h, err)) return false; + } + + if (std::filesystem::exists(experts_path)) { + if (!hash_sampled_file(experts_path, h, err)) return false; + } else if (!gguf.empty()) { + // Native packs may read experts straight from one or more GGUF shards. Sample every distinct source + // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model + // bytes rather than only to an equal-size layout. + const std::filesystem::path first(gguf); + std::vector sources{first}; + for (const std::string& name : lay.gguf_file) { + if (name.empty()) continue; + const std::filesystem::path p = first.parent_path() / name; + if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p); + } + for (const auto& p : sources) { + if (!hash_sampled_file(p, h, err)) return false; + } + } + + out = h == 0 ? 1 : h; + return true; +} + +} // namespace + +namespace { +/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard +/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself. +std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) { + const size_t i = (size_t) (3 * l + r); + if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf; + const size_t cut = gguf.find_last_of("/\\"); + return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i]; +} +} // namespace + +bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { + static const char* roles[3] = {"gate", "up", "down"}; + if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) { + err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py"; + return false; + } + try { + std::map> files; + for (int64_t l = 0; l < lay.n_layers; ++l) { + const auto& fm = lay.fmt[(size_t) l]; + const uint64_t blob = lay.bytes[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; + for (int r = 0; r < 3; ++r) { + const std::string path = expert_gguf_file(gguf, lay, l, r); + auto& f = files[path]; + if (!f) f = std::make_unique(path); + const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight"; + const strata::TensorInfo* t = f->find(name); + const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type); + // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts + const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff); + const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd); + const uint64_t bytes = per[r] * (uint64_t) lay.n_expert; + const uint64_t payload = f->file_size() - f->data_start(); + std::string why; + if (t == nullptr) why = "is not in it"; + else if (t->type != want_type) + why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type); + else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows || + t->shape[2] != (uint64_t) lay.n_expert) + why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " + + std::to_string(lay.n_expert) + "]"; + else if (strata::tensor_payload_bytes(*t) != bytes) + why = "is not " + std::to_string(per[r]) + " B per expert"; + else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)]) + why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " + + std::to_string(lay.gguf_off[(size_t) (3 * l + r)]); + else if (t->offset > payload || bytes > payload - t->offset) + why = "runs past the end of the file (a truncated shard?)"; + if (!why.empty()) { + err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " + + why + " - repack with tools/iq_pack.py from this model's shards"; + return false; + } + } + } + return true; + } catch (const std::exception& e) { + err = std::string("native experts from the GGUF: ") + e.what(); + return false; + } +} + +// Plan v0.3 P6: the arena from the model's GGUF shards. Each layer's gate, up and down tensors hold the 512 +// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob +// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role +// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in +// #255, gopinath87607). The caller checks the spans first (check_experts_gguf). +LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay, + int threads) { + LoadStats st; + st.layers = (uint64_t) lay.n_layers; + const auto t0 = std::chrono::steady_clock::now(); + std::atomic next{0}; + std::atomic bad{false}; + auto worker = [&]() { + // #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request + // into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin. + // The guard closes the handle on every return. + struct Closer { + FILE* f = nullptr; + ~Closer() { if (f != nullptr) std::fclose(f); } + } file; + std::string open_name; + std::vector buf; + for (;;) { + const int64_t l = next.fetch_add(1); + if (l >= lay.n_layers || bad) break; + const auto& fm = lay.fmt[(size_t) l]; + const uint64_t blob = lay.bytes[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off}; + const uint64_t at[3] = {0, fm.up_off, fm.down_off}; + for (int r = 0; r < 3; ++r) { + // the handle is kept while consecutive roles share a file (every layer of a v3 pack) + const std::string name = expert_gguf_file(gguf, lay, l, r); + if (name != open_name) { + if (file.f != nullptr) std::fclose(file.f); + file.f = std::fopen(name.c_str(), "rb"); + if (file.f == nullptr) { bad = true; return; } + open_name = name; + } + FILE* const f = file.f; + const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)]; + const uint64_t total = per[r] * (uint64_t) lay.n_expert; + const uint64_t chunk = per[r] * 16; // 16 experts per read + buf.resize((size_t) chunk); + for (uint64_t done = 0; done < total; done += chunk) { + const uint64_t n = std::min(chunk, total - done); + // 64-bit seek: a shard is tens of GB + if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; } + if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; return; } + for (uint64_t k = 0; k < n / per[r]; ++k) { + const uint64_t e = done / per[r] + k; + std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], buf.data() + k * per[r], (size_t) per[r]); + } + } + } + } + }; + std::vector pool; + for (int i = 1; i < threads; ++i) pool.emplace_back(worker); + worker(); + for (auto& t : pool) t.join(); + if (bad) { + st.seconds = -1.0; + st.ok = false; + st.error = "short read or unreadable shard while reading the experts from the GGUF"; + return st; + } + st.bytes = lay.total; + st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + return st; +} + +ArenaExpertSource::~ArenaExpertSource() { close(); } + +bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads, + std::string& err, uint64_t max_pinned_bytes, + const std::string& shared_arena_file) { + close(); + const std::string path = pack_dir + "/experts.bin"; + // plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver + const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); + if (lay.n_layers != n_layers || lay.n_expert != n_expert) { + err = "ArenaExpertSource: the expert layout was loaded for a different geometry"; + return false; + } + const int64_t blob = (int64_t) lay.max_blob; + const uint64_t want = lay.total; + + // plan v0.3 P6: no experts.bin in a native pack -> the experts come straight from the GGUF + const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty(); + // SIZE CHECK BEFORE THE ALLOCATION, not after. A wrong pack should name the two numbers rather than spend + // 34 GB and a minute of loading first. + if (from_gguf) { + // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and + // dimensions and inside its file - before the allocation, so a pack of another model or a truncated + // shard is a message rather than an arena of plausible wrong experts + if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; } + } else { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; } + const uint64_t got = (uint64_t) f.tellg(); + if (got != want) { + char buf[400]; + std::snprintf(buf, sizeof buf, + "ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) " + "make %llu B - this is not the pack this geometry came from", + path.c_str(), (unsigned long long) got, (long long) n_layers, (long long) n_expert, + (long long) blob, (unsigned long long) want); + err = buf; + return false; + } + } + + uint64_t pack_hash = 0; + if (!shared_arena_file.empty() && + !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false; + + // one layer per registration slice, so no expert straddles two registrations. The arena is one blob + // longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert. + std::vector bounds, loff, lbytes; + for (int64_t l = 0; l < n_layers; ++l) { + bounds.push_back(lay.layer_offset(l)); + loff.push_back(lay.layer_offset(l)); + lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert); + } + bounds.push_back(want); + PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes, + shared_arena_file, pack_hash); + if (!a->valid()) { + const std::string why = a->note; + delete a; + err = "ArenaExpertSource: the arena could not be reserved (" + + std::to_string(want + (uint64_t) blob) + " B)" + + (why.empty() ? std::string{} : ": " + why); + return false; + } + const LoadStats st = from_gguf ? load_experts_gguf(gguf_, a->data(), lay, threads) + : load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20); + if (!st.ok) { + delete a; + err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error); + return false; + } + if (st.bytes != want) { + delete a; + err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want); + return false; + } + arena_ = a; + base_ = a->data(); + pinned_bytes_ = a->registered_bytes; + // plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses + dev_slice_.clear(); + slice_bytes_ = a->slice_bytes; + if (a->registered_bytes > 0) { + std::vector starts = a->slice_bytes > 0 ? a->slice_starts : std::vector{0}; + for (uint64_t off : starts) { + void* d = nullptr; + if (cudaHostGetDevicePointer(&d, (void*) (base_ + off), 0) != cudaSuccess) { + (void) cudaGetLastError(); + dev_slice_.clear(); + break; + } + dev_slice_.push_back((const uint8_t*) d); + } + } + blobs_ = n_layers * n_expert; + n_expert_ = n_expert; + reads_ = 0; + note_ = a->note; + gib_per_s_ = st.gib_per_second(); + load_seconds_ = st.seconds; + load_read_s_ = st.read_seconds; + load_copy_s_ = st.copy_seconds; + return true; +} + +void ArenaExpertSource::close() { + if (arena_ != nullptr) { + delete (PinnedArena*) arena_; + arena_ = nullptr; + } + base_ = nullptr; + blobs_ = 0; + n_expert_ = 0; +} + +bool ArenaExpertSource::pinned(int64_t layer, int64_t expert) const { + if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return false; + const auto& lay = strata::kernels::cpu::expert_layout(); + return lay.blob_offset(layer, expert) + lay.blob_bytes(layer) <= pinned_bytes_; +} + +const uint8_t* ArenaExpertSource::device_alias(int64_t layer, int64_t expert) const { + if (dev_slice_.empty() || !pinned(layer, expert)) return nullptr; + const auto& lay = strata::kernels::cpu::expert_layout(); + if (slice_bytes_ == 0) return dev_slice_[0] + lay.blob_offset(layer, expert); + // one registration slice per layer + if ((size_t) layer >= dev_slice_.size()) return nullptr; + return dev_slice_[(size_t) layer] + (uint64_t) expert * lay.blob_bytes(layer); +} + +const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) { + if (base_ == nullptr) return nullptr; + if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr; + const int64_t idx = layer * n_expert_ + expert; + if (idx < 0 || idx >= blobs_) return nullptr; + ++reads_; + // Pointer arithmetic into resident memory. No fault, no copy, no mapping - which is the entire point of + // this class over `FileExpertSource`. + return base_ + strata::kernels::cpu::expert_layout().blob_offset(layer, expert); +} + +} // namespace strata::core diff --git a/engine/strata/src/core/graph.cpp b/engine/strata/src/core/graph.cpp new file mode 100644 index 00000000..2e9c7e70 --- /dev/null +++ b/engine/strata/src/core/graph.cpp @@ -0,0 +1,146 @@ +// src/core/graph.cpp - P2.S5: the GraphRegistry implementation. +#include "strata/core/graph.hpp" + +#include + +#include +#include + +namespace strata::core { +namespace { + +/// Fills `err` from the CUDA runtime, naming the call that failed. A bare "invalid argument" with no call +/// site is the least useful error this API can produce and the easiest to avoid. +bool fail(std::string& err, const char* what, cudaError_t e) { + err = std::string(what) + ": " + cudaGetErrorString(e); + return false; +} + +} // namespace + +CapturedGraph& CapturedGraph::operator=(CapturedGraph&& o) noexcept { + if (this != &o) { + reset(); + graph_ = o.graph_; + exec_ = o.exec_; + done_ = o.done_; + nodes_ = o.nodes_; + o.graph_ = nullptr; + o.exec_ = nullptr; + o.done_ = nullptr; + o.nodes_ = 0; + } + return *this; +} + +void CapturedGraph::reset() { + // ORDER MATTERS: destroying a graph exec BLOCKS until the launch it is destroying has completed, so + // destroying it before the event is harmless but destroying it after a spin that was supposed to observe + // completion would silently become the thing that caused it. `bench/micro/graph_capture.cu` was fooled by + // exactly this once - it looked like captured graphs made a doorbell visible and direct launches did not. + if (exec_) { cudaGraphExecDestroy(exec_); exec_ = nullptr; } + if (graph_) { cudaGraphDestroy(graph_); graph_ = nullptr; } + if (done_) { cudaEventDestroy(done_); done_ = nullptr; } + nodes_ = 0; +} + +bool CapturedGraph::begin(void* stream, std::string& err) { + if (graph_ || exec_) { err = "begin: this CapturedGraph is already recorded"; return false; } + const cudaError_t e = cudaStreamBeginCapture((cudaStream_t) stream, cudaStreamCaptureModeThreadLocal); + if (e != cudaSuccess) return fail(err, "cudaStreamBeginCapture", e); + return true; +} + +bool CapturedGraph::end(void* stream, std::string& err) { + cudaError_t e = cudaStreamEndCapture((cudaStream_t) stream, &graph_); + if (e != cudaSuccess) { graph_ = nullptr; return fail(err, "cudaStreamEndCapture", e); } + + nodes_ = 0; + e = cudaGraphGetNodes(graph_, nullptr, &nodes_); + if (e != cudaSuccess) return fail(err, "cudaGraphGetNodes", e); + // A capture that recorded NOTHING is a wiring mistake, and a graph that replays nothing produces no error + // and no output - the silent kind of failure this project keeps paying for. + if (nodes_ == 0) { err = "end: the capture recorded ZERO nodes - the body launched nothing"; reset(); return false; } + + e = cudaGraphInstantiate(&exec_, graph_, nullptr, nullptr, 0); + if (e != cudaSuccess) return fail(err, "cudaGraphInstantiate", e); + + // The completion event is recorded ONCE and reused: `launch` records it again after each replay, which is + // what makes `wait_ms` a query rather than a sync. + e = cudaEventCreateWithFlags(&done_, cudaEventDisableTiming); + if (e != cudaSuccess) return fail(err, "cudaEventCreateWithFlags", e); + return true; +} + +bool CapturedGraph::launch(void* stream, std::string& err) const { + if (!exec_) { err = "launch: not recorded"; return false; } + cudaError_t e = cudaGraphLaunch(exec_, (cudaStream_t) stream); + if (e != cudaSuccess) return fail(err, "cudaGraphLaunch", e); + e = cudaEventRecord(done_, (cudaStream_t) stream); + if (e != cudaSuccess) return fail(err, "cudaEventRecord", e); + return true; +} + +bool CapturedGraph::wait_ms(int timeout_ms) const { + if (!done_) return false; + // A BOUNDED wait, and the bound is the point: an unbounded spin turns a protocol bug into a hung run, and + // a hung run says nothing about which side is stuck. `cudaEventQuery` is a QUERY - it does not block and + // it does not synchronise - so this satisfies P2.X3 while still giving the driver the call it needs to + // flush the submission. See NOTE 1 in the header: without a driver call here the work never starts. + // + // The deadline is a REAL CLOCK, not a count of pause instructions: `_mm_pause` is a few cycles, so + // counting pauses as microseconds would make the timeout tens of times longer than the caller asked for - + // a timeout that does not time out is worse than none, because it reports a hang as a pass. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + for (;;) { + const cudaError_t q = cudaEventQuery(done_); + if (q == cudaSuccess) return true; + if (q != cudaErrorNotReady) return false; // a real error, not "not finished" + if (std::chrono::steady_clock::now() >= deadline) return false; + for (int i = 0; i < 64; ++i) _mm_pause(); + } +} + +bool GraphRegistry::record(LayerType type, int n_tokens, const std::function& body, std::string& err) { + const Key k{(int) type, n_tokens}; + if (graphs_.count(k)) return true; // already recorded: the point of a registry + + CapturedGraph g; + if (!g.begin(stream_, err)) return false; + body(); // the caller launches into the captured stream + // The body must not have failed silently. An error state left on the stream would make EndCapture + // succeed with a broken graph, so it is checked and cleared first. + const cudaError_t body_err = cudaGetLastError(); + if (body_err != cudaSuccess) { + // Abandon the capture without instantiating anything. + cudaGraph_t junk = nullptr; + cudaStreamEndCapture((cudaStream_t) stream_, &junk); + if (junk) cudaGraphDestroy(junk); + return fail(err, "the capture body left a CUDA error", body_err); + } + if (!g.end(stream_, err)) return false; + + graphs_.emplace(k, std::move(g)); + ++captures_; + return true; +} + +const CapturedGraph* GraphRegistry::find(LayerType type, int n_tokens) const { + const auto it = graphs_.find(Key{(int) type, n_tokens}); + return it == graphs_.end() ? nullptr : &it->second; +} + +bool GraphRegistry::launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const { + const CapturedGraph* g = find(type, n_tokens); + if (!g) { + char buf[128]; + std::snprintf(buf, sizeof buf, "launch: no graph recorded for %s n=%d", to_string(type), n_tokens); + err = buf; + return false; + } + if (!g->launch(stream_, err)) return false; + if (!g->wait_ms(timeout_ms)) { err = "launch: timed out waiting for the graph to complete"; return false; } + return true; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/keyless.cpp b/engine/strata/src/core/keyless.cpp new file mode 100644 index 00000000..7699b579 --- /dev/null +++ b/engine/strata/src/core/keyless.cpp @@ -0,0 +1,79 @@ +#include "strata/core/keyless.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { +namespace { +std::map routes; +uint32_t u32(std::istream& f) { + unsigned char b[4]{}; f.read((char*) b, 4); + return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24; +} +uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; } +} +const float* keyless_routing(int64_t layer) { + const auto it = routes.find(layer); + return it == routes.end() ? nullptr : it->second; +} +bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) { + if (!routes.empty()) { error = "keyless routing already loaded"; return false; } + std::ifstream f(path, std::ios::binary); + std::array magic{}; f.read(magic.data(), 8); + const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f); + if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 || + layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) { + error = "invalid keyless artifact header/geometry"; return false; + } + std::map pending; + auto fail = [&](const std::string& why) { + error = why; for (auto& row : pending) cudaFree(row.second); return false; + }; + for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) { + const uint32_t layer = u32(f); + if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer)) + return fail("keyless artifact has invalid/duplicate layer"); + for (const char* role : {"q", "k", "v"}) { + const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f); + const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight"); + // Quantized projection size is recorded by the source decoder. Bound before any device read. + const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim * + (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv); + if (!f || !w || !w->native_data || w->native_type != (int)kind || + bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements) + return fail("keyless artifact source projection geometry/type mismatch"); + // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes. + // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span. + const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256; + const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 : + kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0; + if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes) + return fail("keyless artifact unsupported/mismatched native projection encoding"); + std::vector raw((size_t)bytes); + if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess) + return fail("keyless source projection readback failed"); + uint64_t hash = 0xcbf29ce484222325ull; + for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull; + if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch"); + } + std::vector matrix((size_t)heads * dim * dim); + f.read((char*)matrix.data(), matrix.size()*sizeof(float)); + if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); })) + return fail("truncated/nonfinite keyless query matrix"); + float* device = nullptr; + if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess) + return fail("keyless query matrices do not fit in GPU memory"); + pending[layer] = device; + if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) + return fail("keyless query matrix upload failed"); + } + if (f.peek() != std::char_traits::eof()) return fail("keyless artifact has trailing data"); + routes = std::move(pending); + return true; +} +} diff --git a/engine/strata/src/core/layer.cpp b/engine/strata/src/core/layer.cpp new file mode 100644 index 00000000..7e132895 --- /dev/null +++ b/engine/strata/src/core/layer.cpp @@ -0,0 +1,1336 @@ + +// src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. +#include "strata/core/layer.hpp" +#include "strata/core/keyless.hpp" +#include "strata/core/native_head.hpp" +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/gdn.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/router_top10.hpp" +#include "strata/kernels/s2_gemv_q8.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_gdn.hpp" +#include "strata/kernels/native_gdn_preprocess.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/native_flash_attn.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +namespace strata::core { +namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; } +namespace {constexpr int Q8K_BYTES_PER_BLOCK = 292; +constexpr int Q8K_ELEMS_PER_BLOCK = 256; +constexpr float RMS_EPS = 1e-6f; +const std::string EMBEDDING_NAME = "token_embd.weight"; +// qwen4exp.attention.layer_norm_rms_epsilon, used for BOTH norms here +/// A Q8_K buffer needs `n` a multiple of 256 and `n/256` blocks of 292 bytes. +uint64_t q8k_bytes(int64_t n) { return (uint64_t) (n / Q8K_ELEMS_PER_BLOCK) * Q8K_BYTES_PER_BLOCK; } +/// `s_gemv_q8k` takes the canonical-form attributes; a `WeightRef` carries them, and a tensor that is NOT +/// quantized has none. Returns false and names the tensor rather than building a form out of zeroes - which +/// would decode every code as `0 + bias` and produce a perfectly finite wrong answer. +bool sform_of(const WeightRef& r, strata::kernels::SForm& f, const std::string& name, std::string& err) { if (!r.quantized()) { err = name + " is not a quantized tensor, so it has no S-form"; return false; } f.code_bits = r.code_bits; f.code_bias = r.code_bias; f.group_elems = r.group_elems; f.codebook = r.codebook_iq4nl ? strata::kernels::Codebook::Iq4Nl : strata::kernels::Codebook::Affine; f.has_offset = r.has_offset; f.act_kind = r.act_kind; +// carried, not derived - see the note on `SForm::act_kind` +return true;} +/// The three canonical planes of a quantized tensor, located INSIDE the loaded region. +// +// +// **THIS FUNCTION USED TO RE-DERIVE THE LAYOUT, AND THAT IS HOW A WIDTH BUG SURVIVED A ROUND.** It computed +/// `n_groups = n_in / group_elems` and then `scales_bytes = n_out * n_groups * sizeof(float)` - 4 bytes per +/// scale for every tensor. 90 of the 303 quantized tensors hold fp16 scales in the pack (all 58 Q2_0 expert +/// tensors, plus Q4_0, Q5_0, Q8_0 and IQ4_NL), so for those the computed plane was TWICE the real one and the +/// three planes did not add up to the tensor. The first diagnosis was "the manifest's `group_elems` must be +/// wrong, the real group is 64"; it is not, and an audit of all 303 tensors against `scales_fp16` found zero +/// inconsistencies. **The unexamined input was the scale WIDTH, not the group COUNT.** +// +// +// The loader now widens fp16 scales to f32 on the way into the arena and records the resulting plane sizes in +/// the `WeightRef`, so this function has nothing left to derive - it reads what was loaded. The redundancy is +/// deliberate: the sizes come from ONE place (the index, checked against the manifest by `pack_index.py` and +/// against the span by the loader), and this function only checks that they describe the tensor it was given. +// +// +// **THE PLANE KEY IS `offsets`, NOT `mins`, AND THAT COST 136 MiB.** `tools/pack_index.py` and +/// `tools/pack_budget.py` both looked for `mins` and both therefore omitted the offset plane of 54 Q4_K/Q5_K +/// tensors - so the arena was sized without it AND the bytes were never copied. Two tools agreeing is only +/// evidence when they do not share the assumption that is wrong. This function refuses rather than guessing, +/// which is what caught it. +struct Planes { const uint8_t* codes = nullptr; const float* scales = nullptr; const float* offset = nullptr; +///< null when the form has none +}; +bool plane_ptrs(const WeightRef& r, const std::string& name, Planes& out, std::string& err) { +// S2, S4 AND S8 ALL SPLIT THE SAME WAY. The plane LOCATION does not depend on the code width - the three +// sizes come from the index and are checked against the tensor below - so the guard is here to catch a +// tensor that is not quantized at all, not to pick a decoder. WHICH KERNEL reads the planes is the +// caller's choice and the two differ: an S2 tensor's activation contract is Q8_0 (`s2_gemv_q8`) while a +// K-quant's is Q8_K (`s_gemv_q8k`). This used to accept only 4 and 8, which refused `attn_q` - a Q2_0 +// tensor and the reason the QSA layer could not be composed at all. +if (r.code_bits != 2 && r.code_bits != 4 && r.code_bits != 8) { err = name + ": code_bits " + std::to_string(r.code_bits) + " is not an S2/S4/S8 form"; return false; } const uint64_t end = r.codes_bytes + r.scales_bytes + r.offset_bytes; if (r.codes_bytes == 0 || r.scales_bytes == 0 || end != r.bytes) { char buf[320]; std::snprintf(buf, sizeof buf, "%s: the planes add up to %llu B but the tensor is %llu B (codes %llu, scales %llu, " "offsets %llu) - what the loader recorded is not the layout that was loaded", name.c_str(), (unsigned long long) end, (unsigned long long) r.bytes, (unsigned long long) r.codes_bytes, (unsigned long long) r.scales_bytes, (unsigned long long) r.offset_bytes); err = buf; return false; } if (r.has_offset != (r.offset_bytes != 0)) { err = name + ": has_offset is " + std::to_string(r.has_offset ? 1 : 0) + " but the offset plane is " + std::to_string(r.offset_bytes) + " B"; return false; } const uint8_t* base = (const uint8_t*) r.data; out.codes = base; out.scales = (const float*) (base + r.codes_bytes); out.offset = r.offset_bytes ? (const float*) (base + r.codes_bytes + r.scales_bytes) : nullptr; return true;} +constexpr int TPR = 32; +bool native_bf16_projections = false; +bool native_flash_attn_short = false; + +void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weights, float* out, + int64_t n_in, int64_t n_out, bool split, void* stream) { + using namespace strata::kernels; + if (native_bf16_projections) bf16_gemv_fp32_mmvf(x, weights, out, n_in, n_out, stream); + else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream); + else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream); +} +///< threads per row for the row-split GEMVs. +/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at +/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not: +/// TPR=64 gives 11.75 tok/s against 32's 11.99 with experts, and 20.19 against 20.26 without - identical +/// inside noise and marginally worse on both. That is also what the stage table predicts, because the GEMVs +/// are only ~16% of a token, so a few percent there cannot move the total. Kept at 32; the sweep that would +/// actually settle it is per-tensor, not global, and belongs with the fusion work rather than before it. +///< threads per row for the row-split GEMVs +/// Writes the sequence number into MAPPED PINNED memory. A KERNEL, not cudaEventRecord - round 199 found +/// that an event record inside a capture is silently dropped, while this is captured normally and the host can +/// read its result MID-GRAPH. One thread: it is a store. +// (the ring kernel lives in src/kernels/cuda/elementwise.cu; this file is HOST code) +/// WHICH ACTIVATION A QUANTIZED WEIGHT WANTS, AND IT IS A PROPERTY OF THE **TENSOR**, NOT OF ITS ROLE. +// +// +// Rounds 205-215 ran `gdn_layer` and `qsa_layer` on the assumption that a name implies a family: `attn_qkv` is +/// a K-quant, `attn_q` is Q2_0, and so on. **The pack does not work that way.** The same name is quantized +/// per LAYER, and the spread is wide: +// +// +// attn_qkv IQ4_XS x13, Q3_K x18, Q2_0 x1, Q4_K x4 (36 GDN layers) +/// attn_gate Q3_K x25, IQ4_XS x4, Q4_K x3, Q2_0 x4 +/// attn_q Q3_K x6, IQ4_XS x4, Q2_0 x2 (12 QSA layers) +// +// +// `docs/activation-contract.md` fixes the rule per TYPE, and it is short: +// +// +// code_bits == 2 -> Q8_0, via `quantize_q8_0` + `s2_gemv_q8` +/// anything else quantized -> Q8_K, via `quantize_q8_K` + `s_gemv_q8k_split` +// +// +// Getting it wrong is worth 0.6-1.4% on the GEMV - a plausible vector, not a broken one - which is exactly +/// what Gate C1 exists to find and what nothing before C1 would have. `s_gemv_q8k`'s own guard is what caught +/// it here (`code_bits 2 has no Q8_K contract`). +// +// +// `x80` and `xq8k` are the two quantized images of the SAME activation; a caller produces both once and this +/// picks. Producing only the one it thinks it needs is how the assumption gets baked in again. +bool gemv_quantized(const WeightRef& w, const Planes& p, const strata::kernels::SForm& f, const uint8_t* x80, const uint8_t* xq8k, float* y, int64_t n_in, int64_t n_out, const std::string& name, void* stream, std::string& err, const float* x_f32 = nullptr, bool x_q8_1_ready = false) { + using namespace strata::kernels; + if (w.native_data) { + if (!x_f32 || !w.native_q8_1 || !stream || n_in != w.ne0 || n_out != w.ne1) { + err = name + ": native projection requires matching FP32 input and session scratch"; + return false; + } + try { + // Plan v0.3 P3: a caller whose previous native projection quantized the SAME x into the shared + // scratch, with no native projection in between, passes x_q8_1_ready and the quantize is skipped. + if (!x_q8_1_ready) native_quantize_q8_1(x_f32, w.native_q8_1, (int) n_in, 1, stream); + native_mmvq(w.native_type, w.native_data, w.native_q8_1, y, + (int) n_in, (int) n_out, 1, stream); + } catch (const std::exception& error) { + err = name + ": " + error.what(); + return false; + } + return true; + } + if ((w.code_bits == 2 || !w.wants_q8k()) ? !x80 : !xq8k) { + err = name + ": missing canonical quantized activation"; + return false; + } + if (w.code_bits == 2) { +// S2 carries no offset plane and no SForm: its attributes are fixed (2 bits, group 64, bias -1), which +// is why `s2_gemv_q8` takes neither. +if (w.has_offset || p.offset != nullptr) { err = name + ": an S2 form must have no offset plane"; return false; } if (w.group_elems != 64 || w.code_bias != -1) { err = name + ": an S2 form must be group 64 with bias -1, this one is group " + std::to_string(w.group_elems) + " with bias " + std::to_string(w.code_bias); return false; } s2_gemv_q8(x80, p.codes, p.scales, y, n_in, n_out, TPR, stream); return true; } +// **A LEGACY 4/8-BIT FORM WANTS Q8_0, NOT Q8_K, AND `code_bits` CANNOT TELL YOU WHICH.** This used to be +// `code_bits == 2 ? Q8_0 : Q8_K`, which is CORRECT ONLY BY LUCK: every legacy tensor in this pack apart +// from `ffn_down_shexp` is Q2_0, whose attributes happen to be S2's. Q5_0 and Q5_K are both 8-bit with +// bias -16 and differ only in `has_offset`; IQ4_NL and IQ4_XS differ in NOTHING the S-form carries. The +// kind therefore comes from the manifest's `source_type`, through the index (LEDGER L54/L55). +if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true; } s_gemv_q8k_split(xq8k, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true;}} +// namespace +void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } +void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } +namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } +void qsa_set_without_key(bool enabled) { g_without_key = enabled; } +bool qsa_without_key() { return g_without_key; } +void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } +void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } +bool qsa_kv_int8() { return g_kv_int8; } +void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; } +bool qsa_kv_q4() { return g_kv_q4; } +void qsa_set_kv_hybrid(bool enabled) { g_kv_hybrid = enabled; } +bool qsa_kv_hybrid() { return g_kv_hybrid; } +uint64_t gdn_buffers_bytes(const ModelGeometry& g) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd), +// x_q8k +(uint64_t) (g.n_embd / 32) * 34, +// x_q8_0 +(uint64_t) g.n_embd * 2, +// x_bf16 +(uint64_t) C * 4, +// qkv +(uint64_t) C * 4, +// conv_out +(uint64_t) C * 4, +// h +(uint64_t) g.ssm_v_heads * 4, +// alpha +(uint64_t) g.ssm_v_heads * 4, +// beta +(uint64_t) g.ssm_v_heads * 4, +// gate +(uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, +// o +(uint64_t) V * 4, +// z +(uint64_t) V * 4, +// y +q8k_bytes(V), +// y_q8k +(uint64_t) (V / 32) * 34, +// y_q8_0 +(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, +// state +(uint64_t) C * (g.ssm_d_conv - 1) * 4, +// conv_state +}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;} +uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd), (uint64_t) (g.n_embd / 32) * 34, (uint64_t) g.n_embd * 2, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) V * 4, (uint64_t) V * 4, q8k_bytes(V), (uint64_t) (V / 32) * 34, (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) C * (g.ssm_d_conv - 1) * 4, }; uint8_t* p = (uint8_t*) base; void* ptr[16]; uint64_t total = 0; for (int i = 0; i < 16; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_q8k = (uint8_t*) ptr[0]; b.x_q8_0 = (uint8_t*) ptr[1]; b.x_bf16 = (uint16_t*) ptr[2]; b.qkv = (float*) ptr[3]; b.conv_out = (float*) ptr[4]; b.h = (float*) ptr[5]; b.alpha = (float*) ptr[6]; b.beta = (float*) ptr[7]; b.gate = (float*) ptr[8]; b.o = (float*) ptr[9]; b.z = (float*) ptr[10]; b.y = (float*) ptr[11]; b.y_q8k = (uint8_t*) ptr[12]; b.y_q8_0 = (uint8_t*) ptr[13]; b.state = (float*) ptr[14]; b.conv_state = (float*) ptr[15]; return total;} +void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream) { const uint64_t st = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * sizeof(float); const uint64_t cs = (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * sizeof(float); cudaMemsetAsync(b.state, 0, st, (cudaStream_t) stream); cudaMemsetAsync(b.conv_state, 0, cs, (cudaStream_t) stream);} +// Forward-declared because `gdn_layer` and `qsa_layer` are both defined above the timer's own definition, and +// the sub-stage marks live inside them. +static void st_begin(int64_t layer, int slot, void* stream); +static void st_end(int64_t layer, int slot, void* stream); +bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b, const float* mixed, float* out, void* stream, std::string& err) { const LayerView v(tables, layer); const int64_t C = g.ssm_conv_channels; +// ---- resolve. Every one of these was shape-checked by `check_layer` at load time, so a miss here is a +// NAME problem and not a geometry one, and the message says which name. +const WeightRef* w_qkv = v.get("attn_qkv.weight"); const WeightRef* w_gate = v.get("attn_gate.weight"); const WeightRef* w_out = v.get("ssm_out.weight"); const WeightRef* w_alpha = v.get("ssm_alpha.weight"); const WeightRef* w_beta = v.get("ssm_beta.weight"); const WeightRef* w_conv = v.get("ssm_conv1d.weight"); const WeightRef* w_norm = v.get("ssm_norm.weight"); const WeightRef* w_dt = v.get("ssm_dt.bias"); const WeightRef* w_a = v.get("ssm_a"); const char* missing = !w_qkv ? "attn_qkv.weight" : !w_gate ? "attn_gate.weight" : !w_out ? "ssm_out.weight" : !w_alpha ? "ssm_alpha.weight" : !w_beta ? "ssm_beta.weight" : !w_conv ? "ssm_conv1d.weight" : !w_norm ? "ssm_norm.weight" : !w_dt ? "ssm_dt.bias" : !w_a ? "ssm_a" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } +// The conv kernel and the two norms are F32 source types, and the loader copied them verbatim - so their +// device bytes ARE f32 and can be handed straight to the kernels that want `const float*`. +const float* conv_kernel = (const float*) w_conv->data; const float* ssm_norm = (const float*) w_norm->data; const float* dt = (const float*) w_dt->data; const float* ssm_a = (const float*) w_a->data; strata::kernels::SForm f_qkv, f_gate, f_out; if (!sform_of(*w_qkv, f_qkv, v.name("attn_qkv.weight"), err)) return false; if (!sform_of(*w_gate, f_gate, v.name("attn_gate.weight"), err)) return false; if (!sform_of(*w_out, f_out, v.name("ssm_out.weight"), err)) return false; Planes p_qkv, p_gate, p_out; if (!plane_ptrs(*w_qkv, v.name("attn_qkv.weight"), p_qkv, err)) return false; if (!plane_ptrs(*w_gate, v.name("attn_gate.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_out, v.name("ssm_out.weight"), p_out, err)) return false; using namespace strata::kernels; cudaStream_t st = (cudaStream_t) stream; +// ---- 1. the activation, in EVERY format a weight on this layer might ask for. BOTH quantized images are +// produced, because which one is wanted is a property of the TENSOR and the pack mixes them by +// layer - producing only the "right" one is how the per-role assumption gets baked back in. +st_begin(layer, 8, stream); + // Plan v0.3 P3: the canonical activation images only when a canonical projection reads them. + if (!w_qkv->native_data || !w_gate->native_data) { + quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream); + quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream); + } + st_end(layer, 8, stream); +// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for +st_begin(layer, 9, stream); if (!gemv_quantized(*w_qkv, p_qkv, f_qkv, b.x_q8_0, b.x_q8k, b.qkv, g.n_embd, C, v.name("attn_qkv.weight"), stream, err, mixed)) return false; st_end(layer, 9, stream); +// ---- 3. conv, then SiLU on the WHOLE conv output - before the q|k|v split, which is what +// `ref/gdn.py` L262 says and what makes the split a reshape rather than a copy. +st_begin(layer, 10, stream); +// Plan v0.3 P3: under the native contract, conv + SiLU + both L2 norms are one kernel, and alpha/beta with their +// epilogues another (`fused_gdn.hpp`). +const bool fused_pre = g_fused_gdn && native_gdn_enabled() && native_bf16_projections && g.ssm_d_conv == 4 && + g.ssm_state_size == 128; +if (fused_pre) { + fused_gdn_conv_l2(b.conv_state, b.qkv, conv_kernel, b.h, (int) C, (int) (2 * g.ssm_k_heads), RMS_EPS, stream); +} else +try { + if (native_gdn_enabled()) native_gdn_conv_silu(b.conv_state, b.qkv, conv_kernel, b.conv_out, b.h, C, g.ssm_d_conv, stream); + else { + gdn_conv_step(b.conv_state, b.qkv, conv_kernel, b.conv_out, C, g.ssm_d_conv, stream); + cudaMemcpyAsync(b.h, b.conv_out, (size_t) C * 4, cudaMemcpyDeviceToDevice, st); + silu_inplace(b.h, C, stream); + } +} catch (const std::exception& error) { err = v.name("gdn_conv_silu") + ": " + error.what(); return false; } +st_end(layer, 10, stream); +// ---- 4. q,k = l2_norm; v is NOT normalised. The three views are contiguous runs of the same buffer: +// q at [0, 2048), k at [2048, 4096), v at [4096, 10240), each 128-wide heads. const +st_begin(layer, 11, stream); int64_t qk = g.ssm_state_size * g.ssm_k_heads; +if (!fused_pre) try { + if (native_gdn_enabled()) { + native_gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); + native_gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); + } else { + gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); + gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream); + } +} catch (const std::exception& error) { err = v.name("gdn_l2_norm") + ": " + error.what(); return false; } +// The recurrence needs another 1/sqrt(S) beyond Q/K normalization. The legacy +// recurrence consumes prescaled Q; pinned CUDA applies it after the readout dot. +// Keep the scale at that backend-specific boundary to preserve rounding order. +if (!native_gdn_enabled()) scale_inplace(b.h, qk, 1.0f / std::sqrt((float) g.ssm_state_size), stream); +st_end(layer, 11, stream); +// ---- 5. beta and the gate. The weights are BF16. Native single-token CUDA MMVF +// consumes F32 activations; the legacy path rounds them to BF16 first. +// +// THE ROW-SPLIT FORM, and here the case is stronger than the router's: `ssm_v_heads` is **48**, so +// the plain one-thread-per-row form puts 48 threads on a 48-SM GPU and each walks 2,560 elements +// alone. Measured 0.1072 ms each, against 0.0277 for the split - and there are two of them, in all +// 36 GDN layers. +st_begin(layer, 12, stream); + if (fused_pre) { + fused_gdn_ab(mixed, (const uint16_t*) w_alpha->data, (const uint16_t*) w_beta->data, dt, ssm_a, b.gate, b.beta, + (int) g.n_embd, (int) g.ssm_v_heads, stream); + } else { + if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream); + project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream); + project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream); + } + if (!fused_pre) try { + if (native_gdn_enabled()) { + native_gdn_beta_gate(b.beta, g.ssm_v_heads, stream); + native_gdn_gate(b.alpha, dt, ssm_a, b.gate, g.ssm_v_heads, stream); + } else { + gdn_beta_gate(b.beta, g.ssm_v_heads, stream); + gdn_gate(b.alpha, dt, ssm_a, b.gate, 1, g.ssm_v_heads, stream); + } + } catch (const std::exception& error) { err = v.name("gdn_gate") + ": " + error.what(); return false; } + st_end(layer, 12, stream); st_begin(layer, 13, stream); + GdnShapes gs{g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads}; + // Plan v0.3 P3: with the native contract the step and the output norm are one kernel (after the z GEMV). + const bool fused_gdn = g_fused_gdn && native_gdn_enabled() && g.ssm_state_size == 128; + if (!fused_gdn) try { + if (native_gdn_enabled()) native_gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream); + else gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream); + } catch (const std::exception& error) { + err = v.name("gdn_step") + ": " + error.what(); + return false; + } + st_end(layer, 13, stream); st_begin(layer, 14, stream); +// ---- 6. the recurrence. q and k are the (16, 128) views; v is the (48, 128) view. The stage marks for +// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence. +// ---- 7. z, then y = rms_norm(o) * ssm_norm * sigmoid(z). SIGMOID, not SiLU. +// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between. +if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed, + w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false; +try { + if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, b.y, + (int) g.ssm_k_heads, (int) g.ssm_v_heads, stream); + else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream); + else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream); +} catch (const std::exception& error) { err = v.name("gdn_out_norm") + ": " + error.what(); return false; } +st_end(layer, 14, stream); +// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for +st_begin(layer, 15, stream); + if (!w_out->native_data) { + quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream); + quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream); + } if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;} +// ================================ the MoE block ================================ +uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, +// x_bf16 +(uint64_t) g.n_embd * 2, +// x_f16 +(uint64_t) g.n_expert * 4, +// logits +(uint64_t) k * 4, +// ids (int32) +(uint64_t) k * 4, +// weights +(uint64_t) g.n_embd * 4, +// shared +strata::kernels::shared_expert_scratch_bytes(g.n_ff), +// the shared expert's own scratch +(uint64_t) (g.n_embd / 32) * 34, +// x_q8_0 +q8k_bytes(g.n_embd), +// x_q8k +}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;} +uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, (uint64_t) g.n_embd * 2, (uint64_t) g.n_expert * 4, (uint64_t) k * 4, (uint64_t) k * 4, (uint64_t) g.n_embd * 4, strata::kernels::shared_expert_scratch_bytes(g.n_ff), (uint64_t) (g.n_embd / 32) * 34, q8k_bytes(g.n_embd), }; uint8_t* p = (uint8_t*) base; void* ptr[9]; uint64_t total = 0; for (int i = 0; i < 9; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_bf16 = (uint16_t*) ptr[0]; b.x_f16 = (uint16_t*) ptr[1]; b.logits = (float*) ptr[2]; b.ids = (int*) ptr[3]; b.weights = (float*) ptr[4]; b.shared = (float*) ptr[5]; b.sh_scratch = (float*) ptr[6]; b.x_q8_0 = (uint8_t*) ptr[7]; b.x_q8k = (uint8_t*) ptr[8]; return total;} +bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, void* stream, std::string& err, const Doorbell* db) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_router = v.get("ffn_gate_inp.weight"); if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; } if (k < 1 || k > 64) { err = "moe_route: k must be 1..64"; return false; } +// ---- the router's activation. The router's weight is BF16 and that is the one `ref/moe.py` singles out. +if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +// ---- logits = ffn_gate_inp @ bf16(x). The weight is BF16, so this is `bf16_gemv` and not `s_gemv` - +// and using the fp16 activation here instead is the 8.100e-03 error that flips a selection. +// +// **THE ROW-SPLIT VARIANT, BECAUSE THE PLAIN ONE'S PARALLELISM IS THE OUTPUT WIDTH.** `bf16_gemv` is +// one thread per output row: for the router that is 512 threads over 48 SMs, each walking 2,560 +// elements sequentially, and it measured **0.2711 ms for a 2.6 MB weight** - about 65x its +// memory-bound floor and the largest single item left inside the MoE after the top-10 was fixed. +// `bf16_gemv_split` exists for precisely this case; its own header says so. Measured here: +// LEDGER L41 -> L42. +project_bf16(x, b.x_bf16, (const uint16_t*) w_router->data, b.logits, g.n_embd, g.n_expert, true, stream); +// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise +// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel +if (native_router_enabled() && g.n_expert == 512 && k == 10) { + try { native_router_top10(b.logits, b.ids, b.weights, stream); } + catch (const std::exception& error) { err = v.name("router") + ": " + error.what(); return false; } +} else router_top10(b.logits, 1, (int) g.n_expert, (int) k, b.ids, b.weights, stream); +// ---- THE DOORBELL, AND IT IS THE WHOLE POINT OF THE PROTOCOL. The routed experts' INPUT (`x`) and the +// miss list (`ids`, `weights`) are published to the host HERE, before anything that depends on them, +// so a CPU pool can start on them while the GPU keeps working. Both the copy and the ring are +// captured into `G[l]` like anything else - a kernel writing mapped pinned memory, which round 209 +// measured the host seeing 0.050 ms into a 39.8 ms graph. +if (db != nullptr && g_publish_kernel) { + strata::kernels::doorbell_publish(x, b.ids, b.weights, g.n_embd, k, db->d_x_f, db->d_ids, db->d_weights, db->d_seq, + stream); +} else if (db != nullptr) { if (cudaMemcpyAsync(db->d_x_f, x, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_ids, b.ids, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_weights, b.weights, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "moe_route: the doorbell handoff copy failed"; return false; } +// THE RING IS LAST, so a host that sees it knows every byte above is in place. Ordering within a +// stream is what makes that true; it is not a timing assumption. +// THE RING LIVES IN A .cu: this file is compiled by the HOST compiler, where `__global__` and `<<<>>>` do +// not exist. The sequence value is read from the HOST copy and incremented, which is what makes the +// write idempotent across replays of the same graph - a captured literal would ring the same number +// forever and the host would never see a change. +strata::kernels::doorbell_ring(db->d_seq, stream); } return true;} +bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } +// ---- the shared expert. Its three weights are quantized, so they need their planes. +SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false; +// `ffn_gate_inp_shexp` is a 1-D BF16 vector, so THE ARENA HOLDS 2 BYTES PER ELEMENT, not 4 - the loader +// re-rounded it to the engine form like any other BF16 tensor. Reading it as f32 is 5120 bytes past the +// end of a 5120-byte tensor inside a 4.5 GiB arena, where nothing faults. Refuse here rather than trust +// the layout check to have run: this function is reachable without it. +if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_shexp.weight") + " is engine form " + std::to_string((int) w_ginp->kind) + " (" + std::to_string(w_ginp->bytes) + " B); the scalar gate reads it as bf16, so it must be form 1 (" + std::to_string((uint64_t) g.n_embd * 2) + " B)"; return false; } +// THE SHARED EXPERT'S WEIGHTS ARE NOT ONE FAMILY: `ffn_gate_shexp` is Q2_0 on 21 layers and a K-quant on +// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/ +// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced +// and each projection takes the one its own form asks for. +f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); + if (!w_sgate->native_data || !w_sup->native_data) { + quantize_q8_K(x, b.x_q8k, g.n_embd, stream); + quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); + } + NativeSharedWeights native; + native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data; + native.up_type = w_sup->native_type; native.up_data = w_sup->native_data; + native.down_type = w_sdown->native_type; native.down_data = w_sdown->native_data; + // The NativeDense owner publishes one shared workspace for this ordered session stream. + native.q8_1 = w_sgate->native_q8_1 ? w_sgate->native_q8_1 : + w_sup->native_q8_1 ? w_sup->native_q8_1 : w_sdown->native_q8_1; + try { + shared_expert(b.x_q8_0, b.x_q8k, b.x_bf16, f_gate, p_gate.codes, p_gate.scales, p_gate.offset, + f_up, p_up.codes, p_up.scales, p_up.offset, f_down, p_down.codes, p_down.scales, + p_down.offset, (const uint16_t*) w_ginp->data, b.sh_scratch, b.shared, + g.n_embd, g.n_ff, /*tpr=*/32, stream, x, &native); + } catch (const std::exception& error) { + err = v.name("shared_expert") + ": " + error.what(); + return false; + } + return true; +} +bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts, + float* out, void* stream, std::string& err) { + using namespace strata::kernels; + if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; } + // ---- the combination: sum of w[i] * parts[i], plus the shared output ADDED PLAIN. +// +// **`parts` IS COMBINED WITH `b.weights`, WHICH `moe_route` WROTE FOR *THIS* LAYER.** That is the whole +// reason this is a separate function: a caller that passes the previous layer's expert vectors gets +// `sum_j w_l[j] * expert_{ids_{l-1},j}(x_{l-1})`, which is finite, fluent and not the model. +try { + if (native_moe_combine_enabled()) native_moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream); + else moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream); +} catch (const std::exception& error) { + err = "blk." + std::to_string(layer) + ".moe_combine" + ": " + error.what(); + return false; +} +return true;} +bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, + const float* x, const float* parts, float* out, void* stream, std::string& err) { + if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; } + if (!moe_shared(tables, g, layer, b, x, stream, err)) return false; + return moe_combine_parts(g, layer, k, b, parts, out, stream, err); +} +bool layer_verify_compatible(std::string& why) { + // Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic. + if (!native_bf16_projections) why = "the native BF16 projections are off"; + else if (!g_fused_gr) why = "the fused hyper-connection read is off"; + else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off"; + else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off"; + else if (!g_fast_select) why = "the block top-k selection is off"; + else if (!strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off"; + else return true; + return false; +} +void layer_set_publish_kernel(bool enabled) { g_publish_kernel = enabled; } +void layer_set_fused_gdn(bool enabled) { g_fused_gdn = enabled; } +void layer_set_fast_select(bool enabled) { g_fast_select = enabled; } +void layer_set_fast_attn(bool enabled) { g_fast_attn = enabled; } +void layer_set_fused_gr(bool enabled) { g_fused_gr = enabled; } +bool layer_fused_gr() { return g_fused_gr; } +void layer_set_shared_early(bool enabled) { g_shared_early = enabled; } +bool layer_shared_early() { return g_shared_early; } +bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, const float* parts, float* out, void* stream, std::string& err, const Doorbell* db) { +// The two halves in sequence. `moe_route` publishes `ids`/`weights` for THIS layer and `moe_finish` +// combines `parts` with them, so a caller of this wrapper must have `parts` ready BEFORE the call - which +// is what `session_token` (the uncaptured path) does and what the captured loop CANNOT, which is why the +// loop uses the halves separately. +if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);} +// ================================ the QSA mixer ================================ +namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes; +/// The geometry the QSA kernels want, from the one place that defines it. `ModelGeometry` carries the widths +/// the LAYOUT needs; `QsaShapes` adds `n_rot`, `idx_block` and `idx_top_k`, which are kernel contracts. +QsaShapes qsa_shapes(const ModelGeometry& g) { QsaShapes s = strata::kernels::qsa_real_shapes(); s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; s.idx_dim = g.idx_key_dim; return s;} +uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; } +/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets. +struct Cursor { uint8_t* p; uint64_t used = 0; template T* take(uint64_t count) { T* r = (T*) (p + used); used = align_up16(used + count * sizeof(T)); return r; } uint8_t* take_bytes(uint64_t n) { uint8_t* r = p + used; used = align_up16(used + n); return r; }}; +// `TPR` and `gemv_quantized` live in the FIRST anonymous namespace, above, because `gdn_layer` needs the +// dispatch too and the two must not be able to drift. +} +// namespace +namespace { +// KV streaming (docs/kv-streaming-design.md): 0 keeps every cell in VRAM. +int64_t g_kv_resident = 0; +uint64_t g_kv_host_bytes = 0; + +/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones. +struct KvPlan { + int mode = 0; + int64_t pages = 0, slots = 0, pooled_rows = 0; +}; +KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { + KvPlan p; + p.pages = (max_cells + s.page_size - 1) / s.page_size; + p.slots = p.pages; + p.pooled_rows = max_cells / s.idx_block + 2; + if (g_kv_resident <= 0 || ring_cells < 0) return p; // ring_cells < 0: always fully resident + // A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers + static const bool ring_off = std::getenv("STRATA_KV_RING_OFF") != nullptr; + static const bool main_off = std::getenv("STRATA_KV_MAIN_OFF") != nullptr; + if (ring_cells > 0 ? ring_off : main_off) return p; + if (ring_cells > 0) { + const int64_t r = (ring_cells + s.page_size - 1) / s.page_size; + if (r < p.pages) { p.mode = 2; p.slots = r; p.pooled_rows = 2; } // the drafter has no indexer + } else { + const int64_t r = (std::max(g_kv_resident, qsa_kv_resident_min()) + s.page_size - 1) / s.page_size; + if (r < p.pages) { p.mode = 1; p.slots = r; } + } + return p; +} +uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { + if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64; + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + + rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim) + 64; + } + if (g_kv_q4) return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64; + return int8 ? (uint64_t) pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) + 64 + : (uint64_t) pages * s.n_head_kv * s.page_size * s.head_dim * 2 * 2; +} +} // namespace + +void qsa_set_kv_resident(int64_t cells) { g_kv_resident = cells > 0 ? cells : 0; } +int64_t qsa_kv_resident() { return g_kv_resident; } +int64_t qsa_kv_resident_min() { return 20480; } +uint64_t qsa_kv_host_bytes() { return g_kv_host_bytes; } + +uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells) { + const QsaShapes s = qsa_shapes(g); + const KvPlan p = kv_plan(s, max_cells, ring_cells); + uint64_t n = 0; + n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0, + g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots) + n += (uint64_t) p.pages * 4; // page_table + if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency map + n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail + n += (uint64_t) s.idx_dim * 4; // dead + n += (uint64_t) p.pooled_rows * s.idx_dim * 4; // pooled + n += 16; // block_pos + if (with_rope) n += (uint64_t) max_cells * (s.n_rot / 2) * 4 * 2; // cos + sin tables + n += strata::kernels::qsa_step_bytes() + 16; // counts and aligned attention status + n += (uint64_t) s.n_head * 4; // pos_dev + return align_up16(n) + 256; +} + +uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, + const QsaState* share_rope, int64_t ring_cells) { + const QsaShapes s = qsa_shapes(g); + const KvPlan p = kv_plan(s, max_cells, ring_cells); + const int64_t pages = p.pages; + Cursor c{(uint8_t*) base}; + st.without_key = g_without_key; + st.kv_int8 = g_kv_int8 && !g_kv_q4; + st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - + // mtp.cpp). Streamed mode is refused outright; generate.cpp validates it too, this is the backstop. + if (g_kv_hybrid && ring_cells <= 0) { + if (p.mode == 1) { + std::fprintf(stderr, "strata: hybrid K8V4 KV does not support --kv-resident streaming\n"); + return 0; + } + st.kv_hybrid = true; + st.kv_int8 = false; + st.kv_q4 = false; + } + st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below) + st.kv_mode = p.mode; + st.n_slots = p.slots; + const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots + const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim); + if (st.kv_hybrid) { + st.k_q = c.take(rows * s.head_dim); + st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_q4) { + st.k_q4 = c.take(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too + if (!st.without_key) st.k_q = c.take(rows * s.head_dim); + st.v_q = c.take(rows * s.head_dim); + if (!st.without_key) st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.k_pool = c.take(rows * s.head_dim); + st.v_pool = c.take(rows * s.head_dim); + } + st.page_table = c.take((uint64_t) pages); + st.n_pages = pages; + st.max_cells = max_cells; + st.map = strata::kernels::KvStreamMap{}; + st.map.page_table = st.page_table; + st.map.n_blocks = pages; + st.map.n_slots = p.slots; + if (p.mode == 1) { + st.map.slot_block = c.take((uint64_t) p.slots); + st.map.slot_stamp = c.take((uint64_t) p.slots); + st.map.slot_ref = c.take((uint64_t) p.slots); + st.map.miss_block = c.take((uint64_t) p.slots); + st.map.miss_slot = c.take((uint64_t) p.slots); + st.map.ctl = c.take((uint64_t) strata::kernels::kKvCtlInts); + } + st.idx_tail = c.take((uint64_t) (s.idx_block - 1) * s.idx_dim); + st.idx_dead = c.take((uint64_t) s.idx_dim); + st.idx_pooled_rows = p.pooled_rows; + st.idx_pooled = c.take((uint64_t) p.pooled_rows * s.idx_dim); + st.idx_block_pos = c.take(1); + if (share_rope != nullptr) { + st.cos_tab = share_rope->cos_tab; + st.sin_tab = share_rope->sin_tab; + } else { + st.cos_tab = c.take((uint64_t) max_cells * (s.n_rot / 2)); + st.sin_tab = c.take((uint64_t) max_cells * (s.n_rot / 2)); + } + st.step = c.take((uint64_t) strata::kernels::kStepCount); + st.attention_status = c.take(1); + st.pos_dev = c.take((uint64_t) s.n_head); + // the pinned staging the uploads copy FROM - see the note on `host_step` in the header + if (cudaHostAlloc((void**) &st.host_step, strata::kernels::qsa_step_bytes() + sizeof(int32_t), + cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostAlloc((void**) &st.host_pos, (size_t) s.n_head * 4, cudaHostAllocMapped | cudaHostAllocPortable) != + cudaSuccess) { + return 0; // the caller sees a zero byte count; a half-built state is worse than none + } + st.host_step[strata::kernels::kStepCount] = 0; + // KV streaming: the authoritative K/V of every cell, pinned and device-mapped, in the identity layout + st.host = strata::kernels::KvHostPools{}; + if (p.mode != 0) { + const uint64_t hrows = (uint64_t) pages * s.n_head_kv * s.page_size; + const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256; + uint8_t* h = nullptr; + uint8_t* d = nullptr; + if (cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostGetDevicePointer((void**) &d, h, 0) != cudaSuccess) { + // under WSL the NVIDIA driver pins only ~1 GiB in all, which is less than 128K of 8-bit KV needs + if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy " + "(%.2f GiB pinned so far) - lower the context, or run without --kv-resident (under " + "WSL the driver pins only about 1 GiB in all)\n", (double) bytes / 1073741824.0, + (double) g_kv_host_bytes / 1073741824.0); + return 0; + } + g_kv_host_bytes += bytes; + Cursor hc{d}; + if (st.kv_q4) { + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (st.kv_int8) { + if (!st.without_key) st.host.k_q = hc.take(hrows * s.head_dim); + st.host.v_q = hc.take(hrows * s.head_dim); + if (!st.without_key) st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.host.k_pool = hc.take(hrows * s.head_dim); + st.host.v_pool = hc.take(hrows * s.head_dim); + } + } + // THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its + // frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not + // agree with the host's libm. A table shorter than the sequence would have the rotation read past it. + // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell. + if (share_rope == nullptr) { + std::vector hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2)); + strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells, + hc.data(), hs.data()); + cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); + st.owns_rope = true; + if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1) + strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling()); + } + // the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does + // not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`. + if (p.mode == 0) { + std::vector tab((size_t) pages); + for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i; + cudaMemcpy(st.page_table, tab.data(), tab.size() * 4, cudaMemcpyHostToDevice); + } else if (p.mode == 1) { + strata::kernels::kv_stream_reset(st.map, nullptr); + } else { + strata::kernels::kv_ring_table(st.page_table, pages, p.slots, nullptr); + } + cudaDeviceSynchronize(); + return c.used; +} + +void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + const QsaShapes s = qsa_shapes(g); + cudaStream_t cs = (cudaStream_t) stream; + const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size; + if (st.kv_hybrid) { + if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_q4) { + cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_int8) { + if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); + if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + } else { + cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); + cudaMemsetAsync(st.v_pool, 0, rows * s.head_dim * 2, cs); + } + // A streamed state starts over with nothing resident. Its host copy is not cleared (GBs over PCIe per new + // conversation): no reader names a cell before this sequence has written it, and a block copied in whole + // carries the unwritten cells past the end, which nothing reads. + if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, stream); + cudaMemsetAsync(st.idx_tail, 0, (size_t) (s.idx_block - 1) * s.idx_dim * 4, cs); + cudaMemsetAsync(st.idx_dead, 0, (size_t) s.idx_dim * 4, cs); + cudaMemsetAsync(st.idx_pooled, 0, (size_t) st.idx_pooled_rows * s.idx_dim * 4, cs); +} + +strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { + strata::kernels::QsaAttnPools pools; + pools.page_table = st.page_table; + pools.without_key = st.without_key; + pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } + else { pools.k_pool = st.k_pool; pools.v_pool = st.v_pool; } + return pools; +} + +void qsa_kv_resolve(const QsaState& st, const ModelGeometry& g, const int32_t* ids, const int32_t* steps, int64_t n_q, + int64_t cap, void* stream) { + if (st.kv_mode != 1) return; + strata::kernels::kv_stream_resolve(st.map, qsa_attn_pools(st), st.host, qsa_kv_format(st), ids, steps, n_q, cap, + qsa_shapes(g), stream); +} + +uint64_t qsa_buffers_bytes(const ModelGeometry& g, int64_t max_cells) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); uint64_t n = 0; n += (uint64_t) q8k_bytes(g.n_embd); n += (uint64_t) (g.n_embd / 32) * 34; +// block_q8_0 +n += (uint64_t) g.n_embd * 2; n += (uint64_t) g.n_head * 2 * g.head_dim * 4; n += (uint64_t) g.n_head * g.head_dim * 4; n += (uint64_t) g.n_head_kv * g.head_dim * 4 * 2; n += (uint64_t) g.idx_key_dim * 4; n += (uint64_t) g.idx_q_heads * g.idx_key_dim * 4; n += (uint64_t) max_cells * 4; n += (uint64_t) cap * 4; n += (uint64_t) cap * g.n_head_kv * g.head_dim * 2 * 2; n += (uint64_t) g.n_head * g.head_dim * 4; +// attn +n += (uint64_t) g.n_head * g.head_dim * 2; +// attn16 +n += (uint64_t) g.n_head * g.head_dim * 4; +// attn32 +n += (uint64_t) q8k_bytes(g.n_head * g.head_dim); +// attn_q8k +n += strata::kernels::qsa_decode_attn_scratch_floats(cap, s) * 4 + 16; +// attn_scratch +return align_up16(n) + 256;} +uint64_t qsa_buffers_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaBuffers& b) { const QsaShapes s = qsa_shapes(g); const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); Cursor c{(uint8_t*) base}; b.x_q8k = c.take_bytes(q8k_bytes(g.n_embd)); b.x_q8_0 = c.take_bytes((uint64_t) (g.n_embd / 32) * 34); b.x_bf16 = c.take((uint64_t) g.n_embd); b.q_full = c.take((uint64_t) g.n_head * 2 * g.head_dim); b.qcur = c.take((uint64_t) g.n_head * g.head_dim); b.kcur = c.take((uint64_t) g.n_head_kv * g.head_dim); b.vcur = c.take((uint64_t) g.n_head_kv * g.head_dim); b.idx_raw = c.take((uint64_t) g.idx_key_dim); b.q_idx = c.take((uint64_t) g.idx_q_heads * g.idx_key_dim); b.cell_scores = c.take((uint64_t) max_cells); b.ids = c.take((uint64_t) cap); b.k_scratch = c.take((uint64_t) cap * g.n_head_kv * g.head_dim); b.v_scratch = c.take((uint64_t) cap * g.n_head_kv * g.head_dim); b.attn = c.take((uint64_t) g.n_head * g.head_dim); b.attn16 = c.take((uint64_t) g.n_head * g.head_dim); b.attn32 = c.take((uint64_t) g.n_head * g.head_dim); b.attn_q8k = c.take_bytes(q8k_bytes(g.n_head * g.head_dim)); b.attn_scratch = c.take(strata::kernels::qsa_decode_attn_scratch_floats(cap, s)); return c.used;} +// ================================ PER-STAGE TIMING, DEBUG ONLY ================================ +// +// **THE ENGINE SPENDS 1.047 ms PER LAYER WITH THE EXPERTS OFF, AND EVERY COST MODEL IN `bench/` PREDICTS LESS +// THAN HALF OF THAT.** `dense_pass.exe` puts all 302 dense GEMVs at 11.64 ms/token and the 1.377 GiB of +// BF16/F32 weights they exclude at another ~5.9, so ~17.5 ms of the 50.25 ms captured no-pool floor is +// accounted for and ~33 ms is not. Arithmetic has already discounted the obvious candidates - the GDN +// recurrence moves 6.2 MB of state per token, the QSA attention at 1,024 tokens is 75M MACs over twelve +// layers, and `gr_norm_kernel`'s 4-block launch moves 40 KB - so the attribution has to come from the engine. +// +// Event pairs are recorded per (layer, stage) and read once at the end, so **NOTHING IS SYNCHRONISED DURING +// THE RUN** and the measurement does not perturb what it measures. That matters here more than usual: a +// per-stage `cudaEventSynchronize` would serialise the pipeline and report the serialised time. +// +// **IT CANNOT BE USED WITH CAPTURED GRAPHS.** An event record inside a stream capture is silently dropped +// (round 199: 2 nodes for two kernels plus an event record, and the event never completed across a 41 ms +// graph), so this is gated on the `--no-capture` path where the layers are ordinary launches. +constexpr int STAGE_SLOTS = 20; + +struct StageTimer { + bool on = false; + cudaEvent_t a[64][STAGE_SLOTS] = {}; + cudaEvent_t b[64][STAGE_SLOTS] = {}; + const char* names[STAGE_SLOTS] = {}; + int nslots = 0; +}; + +static StageTimer g_st; + +bool stage_timing_enable() { + if (g_st.on) return true; + for (int l = 0; l < 64; ++l) { + for (int s = 0; s < STAGE_SLOTS; ++s) { + if (cudaEventCreate(&g_st.a[l][s]) != cudaSuccess) return false; + if (cudaEventCreate(&g_st.b[l][s]) != cudaSuccess) return false; + } + } + g_st.on = true; + return true; +} + +void stage_timing_name(int slot, const char* name) { + if (slot >= 0 && slot < STAGE_SLOTS) { + g_st.names[slot] = name; + if (slot + 1 > g_st.nslots) g_st.nslots = slot + 1; + } +} + +void stage_mark_begin(int64_t layer, int slot, void* stream) { st_begin(layer, slot, stream); } +void stage_mark_end(int64_t layer, int slot, void* stream) { st_end(layer, slot, stream); } + +static void st_begin(int64_t layer, int slot, void* stream) { + if (g_st.on && layer < 64) cudaEventRecord(g_st.a[layer][slot], (cudaStream_t) stream); +} + +static void st_end(int64_t layer, int slot, void* stream) { + if (g_st.on && layer < 64) cudaEventRecord(g_st.b[layer][slot], (cudaStream_t) stream); +} + +void stage_timing_report(int64_t n_layers) { + if (!g_st.on) return; + cudaDeviceSynchronize(); + double tot[STAGE_SLOTS] = {}; + for (int s = 0; s < g_st.nslots; ++s) { + for (int64_t l = 0; l < n_layers && l < 64; ++l) { + float ms = 0.0f; + if (cudaEventElapsedTime(&ms, g_st.a[l][s], g_st.b[l][s]) == cudaSuccess) tot[s] += (double) ms; + } + } + double sum = 0; + for (int s = 0; s < g_st.nslots; ++s) sum += tot[s]; + std::fprintf(stderr, "\nper-stage GPU time, summed over %lld layers (one token):\n", (long long) n_layers); + for (int s = 0; s < g_st.nslots; ++s) { + std::fprintf(stderr, " %-22s %8.3f ms/token %6.3f ms/layer %5.1f%%\n", + g_st.names[s] ? g_st.names[s] : "(unnamed)", tot[s], tot[s] / (double) n_layers, + sum > 0 ? 100.0 * tot[s] / sum : 0.0); + } + std::fprintf(stderr, " %-22s %8.3f ms/token\n", "sum of stages", sum); + // ---- THE PER-LAYER SPLIT, because the attention block is 55% of the token and the engine mixes two + // entirely different attention implementations: GDN on 36 layers and QSA on the twelve where + // `full_attention_interval` divides the index. A single total cannot say which one is expensive, and the + // two have nothing in common to optimise. + std::fprintf(stderr, "\nper-layer, the attention block (ms). A `*` marks a QSA layer:\n"); + double gdn = 0, qsa = 0; + int ng = 0, nq = 0; + for (int64_t l = 0; l < n_layers && l < 64; ++l) { + float ms = 0.0f; + if (cudaEventElapsedTime(&ms, g_st.a[l][1], g_st.b[l][1]) != cudaSuccess) continue; + const bool is_qsa = (l % 4) == 3; + if (is_qsa) { qsa += ms; ++nq; } else { gdn += ms; ++ng; } + std::fprintf(stderr, " %s%2lld %7.3f%s", is_qsa ? "*" : " ", (long long) l, (double) ms, + ((l + 1) % 8 == 0) ? "\n" : ""); + } + std::fprintf(stderr, "\n GDN: %d layers, %.3f ms total, %.4f ms/layer\n", ng, gdn, ng ? gdn / ng : 0.0); + std::fprintf(stderr, " QSA: %d layers, %.3f ms total, %.4f ms/layer\n", nq, qsa, nq ? qsa / nq : 0.0); +} + +// Declared here because `qsa_layer` is defined above `block_layer_pre`, where the body lives. The dump buffer +// is a plain host pointer and the copy is a graph node of whichever layer's capture is running, so the helper +// needs nothing from the layer it is called for beyond its index. +static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream); +bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s); +const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + try { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); + if (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, stream); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); + return true; + } catch (const std::exception& error) { + err = v.name("qsa_norm_rope") + ": " + error.what(); + return false; + } +}; +// ---- resolve every tensor by name, and REFUSE rather than reading a null. `check_layer` has already +// asserted the shapes at load time; a missing name here is a wiring mistake. +struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_proj.weight"); const WeightRef* w_attnq = v.get("attn_q.weight"); const WeightRef* w_attnk = v.get("attn_k.weight"); const WeightRef* w_attnv = v.get("attn_v.weight"); const WeightRef* w_attno = v.get("attn_output.weight"); const WeightRef* w_idxq = v.get("indexer.q_proj.weight"); const WeightRef* w_qn = v.get("attn_q_norm.weight"); const WeightRef* w_kn = v.get("attn_k_norm.weight"); const WeightRef* w_iqn = v.get("indexer.q_norm.weight"); const WeightRef* w_ikn = v.get("indexer.k_norm.weight"); const char* missing = !w_idxk ? "indexer.k_proj.weight" : !w_attnq ? "attn_q.weight" : !w_attnk ? "attn_k.weight" : !w_attnv ? "attn_v.weight" : !w_attno ? "attn_output.weight" : !w_idxq ? "indexer.q_proj.weight" : !w_qn ? "attn_q_norm.weight" : !w_kn ? "attn_k_norm.weight" : !w_iqn ? "indexer.q_norm.weight" : !w_ikn ? "indexer.k_norm.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; } if (pos < 0 || pos >= st.max_cells) { err = "qsa_layer: pos " + std::to_string(pos) + " is outside the state's 0.." + std::to_string(st.max_cells - 1); return false; } +// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants. +// Reading one as f32 would walk 2x its length inside the arena without faulting. +if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; } +// ---- 1. the three activation formats, once each +if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) { + quantize_q8_K(x, b.x_q8k, g.n_embd, stream); + quantize_q8_0(x, b.x_q8_0, g.n_embd, stream); + } + if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream); +// ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a +// per-token scalar as an argument, which is what keeps this layer capturable. +// +// THE SOURCES ARE `st.host_step`/`st.host_pos`, WHICH LIVE AS LONG AS THE STATE DOES. A stack array or a +// local vector here would be captured as a dangling POINTER and replayed as garbage - see the note in +// `layer.hpp`. That is a silent failure, not a fault: the copy succeeds, the counts are wrong, and the +// token that comes out is plausible. +{ qsa_step_fill(st.host_step, pos, s); for (int64_t h = 0; h < g.n_head; ++h) st.host_pos[h] = (int32_t) (pos_base + pos); + int32_t* m_step = nullptr; + int32_t* m_pos = nullptr; + if (g_publish_kernel && cudaHostGetDevicePointer((void**) &m_step, st.host_step, 0) == cudaSuccess && + cudaHostGetDevicePointer((void**) &m_pos, st.host_pos, 0) == cudaSuccess) { + strata::kernels::copy_i32_from_mapped(st.step, m_step, strata::kernels::kStepCount, stream); + strata::kernels::copy_i32_from_mapped(st.pos_dev, m_pos, g.n_head, stream); + } else + if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } } +// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block +project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream); +// ---- 4. K and V, in Q8_K, then norm and rotate K only +SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false; if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false; if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false; if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false; Planes p_k, p_v, p_o, p_q; if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false; if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false; if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false; if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false; +// k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this +// artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, +// and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. +if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; +// ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). +// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every +// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The +// host-scalar wrappers would be correct here today and silently wrong in a graph. +if (st.kv_hybrid) { + // K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the + // output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the + // unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist. + strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); + kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror + strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr); +} else { +if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 + strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); + strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream); +} +if (st.kv_q4) { + strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); +} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); } /* not K8V4 */ { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { + try { + native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base, + (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream); + } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; } +} else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, + st.cos_tab, st.sin_tab, stream); } +// ---- 6. the query projection, and the HALF-SPLIT into q and gate. +// +// **`attn_q` IS *NOT* ALWAYS Q2_0.** It is Q2_0 on TWO of the twelve QSA layers, Q3_K on six and IQ4_XS on +// four, and this line used to call `s2_gemv_q8` unconditionally - so TEN of the twelve layers decoded an +// S4 code plane with a Q8_0 activation. Both are "a quantized activation", both produce a plausible +// vector, and the difference is 0.6-1.4%. +if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g.n_head * 2 * g.head_dim, v.name("attn_q.weight"), stream, err, x, w_attnv->native_data && w_attnq->native_data)) return false; +// `per_head[:, :head_dim]` - the FIRST half of each head's 2*head_dim block, copied out contiguously so +// the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture` +// case A) and needs no kernel. +if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false; +// ---- 7. the indexer's query: BF16, then norm and rotate +project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream); +if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false; +// ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this +// token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured +// graph, and the kernels guard for the surplus. const +int64_t max_blocks = (st.max_cells / s.idx_block) + 2; + if (g_fast_select) { + // Plan v0.3 P7: block-level FP32 scores and a radix selection over blocks (qsa_select.hpp). + qsa_block_scores(st.idx_pooled, st.idx_dead, b.q_idx, st.step, 1, max_blocks, s, b.cell_scores, stream); + qsa_block_topk(b.cell_scores, st.step, 1, max_blocks, cap, s, b.ids, stream); + } else { + qsa_index_step(st.idx_pooled, b.q_idx, nullptr, s, st.step, max_blocks, b.cell_scores, stream); topk_512_step(b.cell_scores, s, cap, st.step, b.ids, stream); + } + // KV streaming: every block the selection names is made resident before anything reads it + qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = + if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) { + const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); + strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); + } else { + if (st.kv_hybrid) { + kv_gather_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, b.ids, st.step, cap, s, + b.k_scratch, b.k_scratch, stream); + strata::kernels::kv_gather_q4_step(st.v_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, + b.v_scratch, b.v_scratch, stream); + } + else if (st.kv_q4) strata::kernels::kv_gather_q4_step(st.k_q4, st.v_q4, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); + else if (st.kv_int8) kv_gather_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); else kv_gather_step(st.k_pool, st.v_pool, st.page_table, b.ids, st.step, cap, s, b.k_scratch, b.v_scratch, stream); if (native_flash_attn_short) { + if (st.max_cells < 1 || st.max_cells > 256 || !st.attention_status || !st.host_step) { + err = v.name("native_flash_attn") + ": short adapter requires context <=256 and persistent status storage"; + return false; + } + try { + native_flash_attn_short_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, + (int) st.max_cells, s, b.attn, st.attention_status, nullptr, stream); + } catch (const std::exception& error) { err = v.name("native_flash_attn") + ": " + error.what(); return false; } + if (cudaMemcpyAsync(st.host_step + kStepCount, st.attention_status, sizeof(int32_t), + cudaMemcpyDeviceToHost, (cudaStream_t) stream) != cudaSuccess) { + err = v.name("native_flash_attn") + ": status readback failed"; return false; + } +} else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream); + } + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse + dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); } +// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32 +// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection. +// The canonical fallback retains its prior FP64 gate and Q8_K projection. +try { + if (native_qsa_enabled()) native_qsa_gate_apply(b.attn, b.q_full, b.attn32, (int) g.n_head, (int) g.head_dim, stream); + else qsa_gate_apply_f32(b.attn, b.q_full, s, b.attn32, stream); +} catch (const std::exception& error) { err = v.name("qsa_gate") + ": " + error.what(); return false; } + if (!w_attno->native_data) quantize_q8_K(b.attn32, b.attn_q8k, g.n_head * g.head_dim, stream); if (w_attno->native_data) { + if (!gemv_quantized(*w_attno, p_o, f_o, nullptr, b.attn_q8k, out, + g.n_head * g.head_dim, g.n_embd, v.name("attn_output.weight"), stream, err, b.attn32)) return false; +} else { + s_gemv_q8k_split(b.attn_q8k, p_o.codes, p_o.scales, p_o.offset, out, + g.n_head * g.head_dim, g.n_embd, f_o, stream); +} return true;} +// ================================ THE DOORBELL ================================ +namespace {} +// namespace +uint64_t doorbell_init(const ModelGeometry& g, int64_t k, Doorbell& db) { db.n_embd = g.n_embd; db.k = k; uint64_t bytes = 0; +// ONE region per field, each MAPPED PINNED, so the device and the host have different pointers to the same +// bytes and no copy is needed to publish them. +auto alloc = [&](size_t n, void** h, void** d, const char* what) { if (cudaHostAlloc(h, n, cudaHostAllocMapped) != cudaSuccess) { std::fprintf(stderr, "doorbell_init: cudaHostAlloc(%s) failed\n", what); return false; } if (cudaHostGetDevicePointer(d, *h, 0) != cudaSuccess) { std::fprintf(stderr, "doorbell_init: cudaHostGetDevicePointer(%s) failed\n", what); return false; } std::memset(*h, 0, n); bytes += n; return true; }; if (!alloc((size_t) g.n_embd * 4, (void**) &db.h_x_f, (void**) &db.d_x_f, "x_f")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_ids, (void**) &db.d_ids, "ids")) return 0; if (!alloc((size_t) k * 4, (void**) &db.h_weights, (void**) &db.d_weights, "weights")) return 0; if (!alloc(4, (void**) &db.h_seq, (void**) &db.d_seq, "seq")) return 0; if (!alloc(4, (void**) &db.h_flag, (void**) &db.d_flag, "flag")) return 0; return bytes;} +void doorbell_free(Doorbell& db) { if (db.h_x_f) cudaFreeHost(db.h_x_f); if (db.h_ids) cudaFreeHost(db.h_ids); if (db.h_weights) cudaFreeHost(db.h_weights); if (db.h_seq) cudaFreeHost(db.h_seq); if (db.h_flag) cudaFreeHost(db.h_flag); db = Doorbell{};} +void doorbell_reset(const Doorbell& db) { + if (db.h_seq) *db.h_seq = 0; + if (db.h_flag) *(volatile uint32_t*) db.h_flag = 0; +} +// ================================ THE TWO ENDS OF A TOKEN ================================ +bool embed_row(const WeightTable& tables, const ModelGeometry& g, int64_t token, float* out_dev, + void* stream, std::string& err) { + if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table (IQ model files) + if (token < 0 || out_dev == nullptr) { err = "embed_row: invalid token or output"; return false; } + ne->gather_one(token, out_dev, stream); + return true; + } + const WeightRef* w = tables.find(EMBEDDING_NAME); + if (w == nullptr) { err = "token_embd.weight is missing"; return false; } + if (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8) { + err = "embed_row: token_embd.weight is not an S2/S4/S8 tensor"; + return false; + } + if (w->codebook_iq4nl) { + err = "embed_row: an IQ4NL embedding is not supported"; + return false; + } + if (w->data == nullptr || out_dev == nullptr || w->ne0 <= 0 || w->ne1 <= 0 || + w->ne0 != g.n_embd || w->group_elems <= 0 || + w->ne0 % w->group_elems != 0 || w->ne0 % (8 / w->code_bits) != 0) { + err = "embed_row: invalid embedding pointers, dimensions or group size"; + return false; + } + if (token < 0 || token >= w->ne1) { + err = "embed_row: token " + std::to_string(token) + " is outside 0.." + std::to_string(w->ne1 - 1); + return false; + } + + const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits)); + const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems); + const uint64_t rows = (uint64_t) w->ne1; + // Division-based checks avoid overflow in rows * row_bytes and reject partial + // code/group rows before any device pointer arithmetic. + if (w->codes_bytes > w->bytes || w->scales_bytes > w->bytes - w->codes_bytes || + w->offset_bytes != w->bytes - w->codes_bytes - w->scales_bytes || + w->codes_bytes % row_codes != 0 || w->codes_bytes / row_codes != rows || + w->codes_bytes % alignof(float) != 0 || w->scales_bytes % sizeof(float) != 0 || + (w->scales_bytes / sizeof(float)) % row_groups != 0 || + (w->scales_bytes / sizeof(float)) / row_groups != rows || + w->has_offset != (w->offset_bytes != 0) || + (w->has_offset && w->offset_bytes != w->scales_bytes)) { + err = "embed_row: embedding planes do not match the loaded tensor shape"; + return false; + } + + const auto* codes = static_cast(w->data); + const auto* scales = reinterpret_cast(codes + w->codes_bytes); + const auto* offsets = w->has_offset ? reinterpret_cast(codes + w->codes_bytes + w->scales_bytes) + : nullptr; + const uint64_t group_offset = (uint64_t) token * row_groups; + strata::kernels::embedding_gather(codes + (uint64_t) token * row_codes, scales + group_offset, + offsets ? offsets + group_offset : nullptr, w->ne0, + w->code_bits, w->code_bias, w->group_elems, out_dev, stream); + return true; +} +bool lm_head_mix(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, + void* stream, std::string& err) { + const WeightRef* wn = tables.find("output_hc_norm.weight"); + const WeightRef* wd = tables.find("output_hc_down.weight"); + const WeightRef* wu = tables.find("output_hc_up.weight"); + if (!wn || !wd || !wu) { + err = "lm_head: an output_hc_* weight is missing"; + return false; + } + if (wn->kind != WeightKind::F32 || wd->kind != WeightKind::Bf16InF32 || + wu->kind != WeightKind::Bf16InF32) { + err = "lm_head: the output_hc_* weights have the wrong engine forms"; + return false; + } + const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; + strata::kernels::gr_read(bb.R, (const float*) wn->data, (const uint16_t*) wd->data, + (const uint16_t*) wu->data, nullptr, RMS_EPS, gs, bb.gr, + bb.mixed, bb.inject, stream); + return true; +} + +bool lm_head(const WeightTable& tables, const ModelGeometry& g, const BlockBuffers& bb, + float* logits, void* stream, std::string& err) { + const WeightRef* wo = tables.find("output.weight"); + if (!wo) { err = "output.weight is missing"; return false; } + strata::kernels::SForm form; + Planes planes; + if (!sform_of(*wo, form, "output.weight", err) || + !plane_ptrs(*wo, "output.weight", planes, err)) return false; + if (g.n_embd % Q8K_ELEMS_PER_BLOCK != 0) { + err = "lm_head: n_embd is not a multiple of 256"; + return false; + } + if (!lm_head_mix(tables, g, bb, stream, err)) return false; + strata::kernels::quantize_q8_K(bb.mixed, bb.head_q8k, g.n_embd, stream); + return gemv_quantized(*wo, planes, form, bb.head_q8k, bb.head_q8k, logits, + g.n_embd, wo->ne1, "output.weight", stream, err); +} +// ================================ ONE WHOLE BLOCK ================================ +uint64_t block_buffers_bytes(const ModelGeometry& g) { const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr}; uint64_t n = 0; n += (uint64_t) g.hc * g.n_embd * 4; +// R +n += (uint64_t) g.n_embd * 4; +// mixed +n += (uint64_t) g.n_embd * 4; +// block_out +n += (uint64_t) g.hc * 4; +// inject +n += (uint64_t) g.hc * 4 * 2 + 32; +// inject2, gr_rs +n += q8k_bytes(g.n_embd); +// head_q8k +n += strata::kernels::gr_workspace_bytes(s); return align_up16(n) + 256;} +uint64_t block_buffers_init(const ModelGeometry& g, void* base, BlockBuffers& b) { const strata::kernels::GrShapes s{g.n_embd, g.hc, g.hc_lr}; Cursor c{(uint8_t*) base}; b.R = c.take((uint64_t) g.hc * g.n_embd); b.mixed = c.take((uint64_t) g.n_embd); b.block_out = c.take((uint64_t) g.n_embd); b.inject = c.take((uint64_t) g.hc); b.inject2 = c.take((uint64_t) g.hc); b.gr_rs = c.take((uint64_t) g.hc); b.head_q8k = c.take_bytes(q8k_bytes(g.n_embd)); uint8_t* grw = c.take_bytes(strata::kernels::gr_workspace_bytes(s)); strata::kernels::gr_workspace_init(s, grw, b.gr); return c.used;} +// ---- THE HALF-LEVEL C1 ORACLE. `dump` is a HOST buffer of `2 * n_embd + 2 * hc + n_head * head_dim` floats +// per layer; this enqueues one slice of it as a device-to-host copy. **IT RUNS INSIDE THE CAPTURE**, which is +// the point: the copy becomes a node of that layer's graph and replays with it, so the layer functions stay one +// function each and no per-layer plumbing reaches `generate.cpp`. A null `dump` is the default and skips the +// enqueue entirely, so the fast path records no extra node. +uint64_t dump_stride_floats(const ModelGeometry& g) { + // Layout per layer, all in floats: + // [0, 2*n_embd) the two halves' block_out + // [2*n_embd, +2*hc) the two halves' inject + // [+NH*HD) the QSA pre-gate attention + // [+2*NKV*HD) the QSA RAW vcur (as floats) + // [+NKV*HD/2) the gathered v_scratch, as fp16 pairs + // [+4) [+4) ids[0..3], then step[0..3] + // [+NKV*HD/2) the v_pool prefix, as fp16 pairs + // [+NKV*HD) the post-norm POST-ROPE kcur + // The last four are what separate a wrong projection from a wrong pool round trip. + const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; + return (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 5 * nvk + 8; +} +static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream) { + if (dump == nullptr || src == nullptr || n == 0) return; + cudaMemcpyAsync(dump + (size_t) layer * dump_stride_floats(g) + off, src, n * sizeof(float), + cudaMemcpyDeviceToHost, (cudaStream_t) stream); +} +static void dump_half(const BlockBuffers& bb, const ModelGeometry& g, int64_t layer, const float* src, + uint64_t off, uint64_t n, void* stream) { + dump_slot(bb.dump, g, layer, src, off, n, stream); +} +bool block_layer_pre(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, void* stream, std::string& err, const Doorbell* db, const PleRun* ple, int half, int stage_prefix) { + // ================================ THE PLE, AT LAYER 1 ONLY ================================ + // + // **THIS IS THE CALL WHOSE ABSENCE FAILED GATE C1.** Layer 1 carries the six `blk.1.ple_*` tensors and no + // other layer does; every part of the module was built and parity-tested and none of it was reachable from + // here. The block's output is `hidden + gated + silu(conv)` on the RESIDUAL STACK ITSELF, so it is a + // residual update applied BEFORE layer 1's own `gr_read` - which is what the architecture means by the + // gathered rows arriving "before layer 2". + // + // **THE HASH AND THE GATHER ARE *NOT* HERE, AND THAT IS THE WHOLE REASON `ple_stage_token` EXISTS.** Both + // are HOST operations - the hash is 64-bit multiply/xor that `qwen4exp.cpp` says is host-side because "ggml + // has no int64 and no xor", and the table is a host mapping. This function is CAPTURED, so anything host + // side in it runs ONCE, at capture time, and the graph then replays that result for every token: the engine + // would gather the capture-time token's rows forever and produce a perfectly finite, perfectly stable, + // completely wrong answer. It is the same bug as the doorbell's cloned literal, and it is silent. + // + // So the driver calls `ple_stage_token` once per token, BEFORE the graphs, and what is captured here is only + // the device half: `ple_block` reading `emb_dev`, and the history shift. + const bool fused = g_fused_gr && stage_prefix == 0 && half == 0 && + strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr); + // layer-1's FFN write has not been applied to R yet - unless a control vector follows it, which needs R + bool pending_ffn = fused && layer > 0 && !strata::kernels::cvec().covers(layer - 1); + if (ple != nullptr && ple->ready() && layer == 1 && (half == 0 || half == 1)) { + if (pending_ffn) { + const strata::kernels::GrShapes gs0{g.n_embd, g.hc, g.hc_lr}; + gr_write(bb.R, bb.block_out, bb.inject2, gs0, bb.R, stream); + pending_ffn = false; + } + const int64_t hcd = strata::kernels::NG_HC_DIM; + strata::kernels::PleOut po; + // Exports must not alias the block's internal workspace. The previous diagnostic views used a + // different layout inside that workspace: exporting gated values overwrote normalized values + // before the latter were copied to history. Allocate only the one export the recurrence needs. + po.normalized = (float*) ((uint8_t*) ple->scratch + strata::kernels::ple_block_scratch_bytes()); + // `result` IS THE RESIDUAL, in place: the block computes `hidden[i] + gated[i] + conv[i]` elementwise, + // so reading and writing `R` at the same index is well-defined. + po.result = bb.R; + try { + strata::kernels::ple_block(ple->emb_dev, bb.R, ple->hist, ple->w, po, ple->scratch, stream); + } catch (const std::exception& error) { + err = std::string("block_layer_pre PLE: ") + error.what(); + return false; + } + + // ---- AND THE HISTORY ADVANCES, ONCE PER TOKEN, WHICH IS WHAT MAKES IT A CONV HISTORY. + // + // `ple_block` deliberately does NOT write back to the history - "the caller keeps ownership of its + // state and this stays a pure function of its inputs, which is what makes the chunked-versus-single-shot + // property testable" - so the shift is here. The layout is ROW-FASTEST (`hist[row + NG_HIST*channel]`, + // from `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`), so a row shift is a STRIDED copy of + // NG_HIST-1 elements per channel and an append is a strided copy of one - not a flat memmove, which + // would be the natural reading and would scramble the channels. + strata::kernels::ple_history_advance(ple->hist, po.normalized, stream); + if (cudaPeekAtLastError() != cudaSuccess) { + err = "block_layer_pre: the PLE history shift failed"; + return false; + } + } + const bool qsa = is_qsa_layer(g, layer); const LayerView v(tables, layer); const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; +// ---- the two halves' GR tensors. Both halves have the same four names with a different prefix, and the +// prefix is the ONLY thing that distinguishes them - so it is built rather than written twice. +const char* pre[2] = {"hc_attn_", "hc_ffn_"}; const WeightRef* w_norm[2]; const WeightRef* w_down[2]; const WeightRef* w_up[2]; const WeightRef* w_inject[2]; for (int h = 0; h < 2; ++h) { const std::string a = std::string(pre[h]) + "norm.weight"; const std::string d = std::string(pre[h]) + "down.weight"; const std::string u = std::string(pre[h]) + "up.weight"; const std::string i = std::string(pre[h]) + "inject.weight"; w_norm[h] = v.get(a.c_str()); w_down[h] = v.get(d.c_str()); w_up[h] = v.get(u.c_str()); w_inject[h] = v.get(i.c_str()); if (!w_norm[h] || !w_down[h] || !w_up[h] || !w_inject[h]) { err = v.name((std::string(pre[h]) + "{norm,down,up,inject}.weight").c_str()) + " is missing"; return false; } +// The GR weights are BF16 and the arena holds them re-rounded to 2 B/elem. `gr_read` wants exactly +// that; handing it f32 bytes would walk 2x the tensor inside the arena without faulting. +if (w_down[h]->kind != WeightKind::Bf16InF32 || w_up[h]->kind != WeightKind::Bf16InF32 || w_inject[h]->kind != WeightKind::Bf16InF32 || w_norm[h]->kind != WeightKind::F32) { err = v.name(pre[h]) + "has the wrong engine forms (norm must be F32, the other three bf16)"; return false; } } +// ---- half 1: the mixer +float* R = bb.R; + // R0.11: WHICH STAGES TO RUN. `stage_prefix == 0` means "as `half` says", so every caller that predates + // this parameter is bit-for-bit unaffected; `stage_prefix == k` runs stages 0..k-1 and ignores `half`. + const bool run0 = stage_prefix > 0 ? (stage_prefix >= 1) : (half == 0 || half == 1); + const bool run1 = stage_prefix > 0 ? (stage_prefix >= 2) : (half == 0 || half == 1); + const bool run2 = stage_prefix > 0 ? (stage_prefix >= 3) : (half == 0 || half == 1); + const bool run3 = stage_prefix > 0 ? (stage_prefix >= 4) : (half == 0 || half == 2); + const bool run4 = stage_prefix > 0 ? (stage_prefix >= 5) : (half == 0 || half == 2); // R0.9: this is the MIXER half, and `half == 2` skips it entirely. A `half` of 1 or 0 runs it, + // and 0 is what every caller before this used. + if (run0) { +st_begin(layer, 0, stream); + if (fused) { + strata::kernels::FusedGrArgs fa; + fa.R = R; fa.R_out = R; fa.apply = pending_ffn; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject2; + fa.w_norm = (const float*) w_norm[0]->data; fa.w_down = (const uint16_t*) w_down[0]->data; + fa.w_up = (const uint16_t*) w_up[0]->data; fa.w_inject = (const uint16_t*) w_inject[0]->data; + fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject; fa.mixed = bb.mixed; + strata::kernels::fused_gr_read(fa, stream); + } else { + gr_read(R, (const float*) w_norm[0]->data, (const uint16_t*) w_down[0]->data, (const uint16_t*) w_up[0]->data, (const uint16_t*) w_inject[0]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); + } + st_end(layer, 0, stream); dump_half(bb, g, layer, bb.inject, 2 * g.n_embd, g.hc, stream); } + if (run1) { + st_begin(layer, 1, stream); if (qsa) { if (!qsa_layer(tables, g, layer, pos, pos_base, qst, qb, bb.mixed, bb.block_out, stream, err, bb.dump)) return false; } else { if (!gdn_layer(tables, g, layer, gb, bb.mixed, bb.block_out, stream, err)) return false; } st_end(layer, 1, stream); dump_half(bb, g, layer, bb.block_out, 0, g.n_embd, stream); } + if (run2) { + st_begin(layer, 2, stream); if (!fused) gr_write(R, bb.block_out, bb.inject, gs, R, stream); st_end(layer, 2, stream); +// ---- half 2, UP TO AND INCLUDING THE ROUTER. `gr_read` leaves the normed activation in `bb.mixed` and +// the per-stream injection in `bb.inject`, and BOTH must survive until `block_layer_post` runs - which is +// the contract the two functions have with each other and with the host loop's ordering. + } + // R0.9: the FFN front and the ROUTER. It reads `bb.mixed`/`bb.inject`, which the mixer left - + // the same contract `block_layer_post` has, and the reason the two are only meaningful in order. + if (run3) { +st_begin(layer, 3, stream); + if (fused) { + strata::kernels::FusedGrArgs fa; + fa.R = R; fa.R_out = R; fa.apply = true; fa.bo_prev = bb.block_out; fa.inj_prev = bb.inject; + fa.w_norm = (const float*) w_norm[1]->data; fa.w_down = (const uint16_t*) w_down[1]->data; + fa.w_up = (const uint16_t*) w_up[1]->data; fa.w_inject = (const uint16_t*) w_inject[1]->data; + fa.eps = RMS_EPS; fa.lo = bb.gr.lo; fa.rs = bb.gr_rs; fa.inject_out = bb.inject2; fa.mixed = bb.mixed; + strata::kernels::fused_gr_read(fa, stream); + } else { + gr_read(R, (const float*) w_norm[1]->data, (const uint16_t*) w_down[1]->data, (const uint16_t*) w_up[1]->data, (const uint16_t*) w_inject[1]->data, RMS_EPS, gs, bb.gr, bb.mixed, bb.inject, stream); + } + st_end(layer, 3, stream); } + if (run4) { + st_begin(layer, 4, stream); { const bool ok = moe_route(tables, g, layer, k, mb, bb.mixed, stream, err, db); st_end(layer, 4, stream); if (!ok) return false; } + // Plan v0.3 P3: after the ring, so the GPU computes the shared expert while the host runs the pool. + if (g_shared_early && !moe_shared(tables, g, layer, mb, bb.mixed, stream, err)) return false; + } + // Every stage this call was asked to run has run. There is no other way out: the old `return ok;` + // lived inside the stage-4 block and restructuring that left the function with no return at all. + return true; +} +bool ple_issue_token(const PleRun& p, std::string& err) { + if (!p.ready()) { err = "ple_issue_token: the PLE run is not ready"; return false; } + uint32_t rows[strata::kernels::PLE_N_HEADS]; + strata::kernels::ngram_rows(p.token, p.prev, 1, p.consts, rows); + if (!p.table->issue(rows)) { err = "ple_issue_token: the previous token's rows were never collected"; return false; } + return true; +} + +bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { + if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } + if (p.table->kar_gpu_cache_enabled()) { + if (!p.table->collect_device(p.emb_dev, stream, err)) { + err = "ple_finish_token: " + err; + return false; + } + return true; + } + if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } + if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), + cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { + err = "ple_finish_token: the row upload failed"; + return false; + } + return true; +} + +bool ple_stage_token(const PleRun& p, void* stream, std::string& err) { + if (!ple_issue_token(p, err)) return false; + return ple_finish_token(p, stream, err); +} + +uint64_t ple_run_scratch_bytes() { + // Internal workspace followed by a disjoint normalized export used for the next history row. + return strata::kernels::ple_block_scratch_bytes() + strata::kernels::NG_HC_DIM * sizeof(float); +} + +bool block_layer_post(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& mb, const BlockBuffers& bb, const float* parts, void* stream, std::string& err) { const strata::kernels::GrShapes gs{g.n_embd, g.hc, g.hc_lr}; +// `bb.mixed` and `bb.inject` are what `block_layer_pre` left, and NOTHING between the two calls may touch +// them - that is what makes `post[l]` safe to launch after the host has run the pool. +st_begin(layer, 5, stream); + if (g_shared_early ? !moe_combine_parts(g, layer, k, mb, parts, bb.block_out, stream, err) + : !moe_finish(tables, g, layer, k, mb, bb.mixed, parts, bb.block_out, stream, err)) return false; + st_end(layer, 5, stream); dump_half(bb, g, layer, bb.block_out, (uint64_t) g.n_embd, g.n_embd, stream); dump_half(bb, g, layer, bb.inject, (uint64_t) 2 * g.n_embd + g.hc, g.hc, stream); st_begin(layer, 6, stream); + const bool steer = strata::kernels::cvec().covers(layer); // --control-vector-scaled: after this write + try { + if (!(g_fused_gr && strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr))) { + gr_write(bb.R, bb.block_out, bb.inject, gs, bb.R, stream); + if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); + } else if (layer == g.n_layers - 1) { + gr_write(bb.R, bb.block_out, bb.inject2, gs, bb.R, stream); // materialise R for the head + if (steer) strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, nullptr, 0, nullptr, 0, false, stream); + } else if (steer) { + // the write the next layer's fused read would have folded, then the vector + strata::kernels::cvec_apply(bb.R, layer, 1, g.hc * g.n_embd, bb.block_out, g.n_embd, bb.inject2, g.hc, + true, stream); + } + } catch (const std::exception& e) { + err = std::string("block_layer_post: ") + e.what(); + return false; + } + st_end(layer, 6, stream); return true;} +bool block_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const GdnBuffers& gb, const QsaState& qst, const QsaBuffers& qb, const MoEBuffers& mb, int64_t k, const BlockBuffers& bb, const float* parts, void* stream, std::string& err, const Doorbell* db, const PleRun* ple) { +// The two halves back to back. `parts` must be THIS layer's experts and must be ready before the call - +// which holds for `session_token`, where the caller supplies them, and does NOT hold for a host loop that +// has only just seen the router. That is why the captured path calls the halves separately. +if (!block_layer_pre(tables, g, layer, pos, pos_base, gb, qst, qb, mb, k, bb, stream, err, db, ple)) return false; return block_layer_post(tables, g, layer, k, mb, bb, parts, stream, err);}} +// namespace strata::core diff --git a/engine/strata/src/core/layout.cpp b/engine/strata/src/core/layout.cpp new file mode 100644 index 00000000..6d1b970b --- /dev/null +++ b/engine/strata/src/core/layout.cpp @@ -0,0 +1,173 @@ +// src/core/layout.cpp - the shape checks. See the header for why this exists. +#include "strata/core/layout.hpp" + +#include + +namespace strata::core { +namespace { + +/// A required 2-D shape. `ne0` is the CONTIGUOUS axis, matching the manifest and `s_gemv`'s convention +/// (`y[o] = sum_i x[i]*W[i][o]`, row o contiguous of length ne0). +struct Want2 { + const char* suffix; + int64_t ne0; + int64_t ne1; + bool qsa_only; + bool gdn_only; +}; + +/// A required element count and ENGINE FORM for a 1-D tensor. +/// +/// `kind` is not decoration. The engine form of a 1-D tensor is whatever `WeightKind` the loader applied - +/// `F32` copies 4 B/elem, `Bf16InF32` re-rounds to 2 - and a consumer that casts either one to `const float*` +/// reads 2x its length. **THAT IS NOT HYPOTHETICAL: `ffn_gate_inp_shexp.weight` is BF16, so the arena holds +/// 5120 B for 2560 elements, and `shared_expert` read it as f32. Every one of the 2560 MoE outputs came out +/// non-finite** - a wrong answer loud enough to notice, which is the lucky version. Reading 5120 B past the +/// end of a tensor inside a 4.5 GiB arena does not fault, so the same mistake on a tensor followed by +/// plausible bytes would have produced plausible logits. +struct Want1 { + const char* suffix; + int64_t elements; + WeightKind kind; + bool qsa_only; + bool gdn_only; +}; + +bool fail(std::string& err, const LayerView& v, const char* suffix, const char* what, int64_t got, + int64_t want) { + char buf[512]; + std::snprintf(buf, sizeof buf, "layer %lld: %s %s is %lld, the kernels require %lld", + (long long) v.layer(), v.name(suffix).c_str(), what, (long long) got, (long long) want); + err = buf; + return false; +} + +bool check_one(const WeightTable& t, const ModelGeometry& g, int64_t layer, std::string& err) { + const LayerView v(t, layer); + const bool qsa = is_qsa_layer(g, layer); + + // ---- the 2-D tensor set, per layer family + const Want2 want2[] = { + // gated residual, EVERY layer - `gr_read` takes w_down (hc_lr, hc_dim) and w_up (hc_lr, hc_dim) + // after its own transpose, so the pack's orientation is [hc_dim, hc_lr] and [hc_lr, hc_dim]. + {"hc_attn_down.weight", g.hc_dim(), g.hc_lr, false, false}, + {"hc_attn_up.weight", g.hc_lr, g.hc_dim(), false, false}, + {"hc_attn_inject.weight", g.hc_dim(), g.hc, false, false}, + {"hc_ffn_down.weight", g.hc_dim(), g.hc_lr, false, false}, + {"hc_ffn_up.weight", g.hc_lr, g.hc_dim(), false, false}, + {"hc_ffn_inject.weight", g.hc_dim(), g.hc, false, false}, + // MoE, EVERY layer + {"ffn_gate_inp.weight", g.n_embd, g.n_expert, false, false}, + {"ffn_gate_shexp.weight", g.n_embd, g.n_ff, false, false}, + {"ffn_up_shexp.weight", g.n_embd, g.n_ff, false, false}, + {"ffn_down_shexp.weight", g.n_ff, g.n_embd, false, false}, + // GDN only + {"attn_qkv.weight", g.n_embd, g.ssm_conv_channels, false, true}, + {"attn_gate.weight", g.n_embd, g.ssm_value_dim, false, true}, + {"ssm_out.weight", g.ssm_value_dim, g.n_embd, false, true}, + {"ssm_conv1d.weight", g.ssm_d_conv, g.ssm_conv_channels, false, true}, + {"ssm_alpha.weight", g.n_embd, g.ssm_v_heads, false, true}, + {"ssm_beta.weight", g.n_embd, g.ssm_v_heads, false, true}, + // QSA only + {"attn_q.weight", g.n_embd, 2 * g.n_head * g.head_dim, true, false}, + {"attn_k.weight", g.n_embd, g.n_head_kv * g.head_dim, true, false}, + {"attn_v.weight", g.n_embd, g.n_head_kv * g.head_dim, true, false}, + {"attn_output.weight", g.n_head * g.head_dim, g.n_embd, true, false}, + // THE INDEXER. `q_proj` is the QUERY count and `k_proj` is the KEY width, and they are different + // numbers - conflating them is what made the planner's indexer term 4x too big in round 194. + {"indexer.q_proj.weight", g.n_embd, g.idx_q_heads * g.idx_key_dim, true, false}, + {"indexer.k_proj.weight", g.n_embd, g.idx_key_dim, true, false}, + }; + for (const Want2& w : want2) { + if (w.qsa_only && !qsa) continue; + if (w.gdn_only && qsa) continue; + const WeightRef* r = v.get(w.suffix); + if (!r) { + err = "layer " + std::to_string(layer) + ": missing " + v.name(w.suffix); + return false; + } + if (r->ne0 != w.ne0) return fail(err, v, w.suffix, "ne0", r->ne0, w.ne0); + if (r->ne1 != w.ne1) return fail(err, v, w.suffix, "ne1", r->ne1, w.ne1); + } + + // ---- the 1-D set. EVERY ONE OF THESE IS `F32` EXCEPT the shared expert's scalar gate, which is BF16 - + // and that single exception is the one a reader would not guess, so it is written down rather than + // inferred from the tensor count. + const Want1 want1[] = { + {"hc_attn_norm.weight", g.hc_dim(), WeightKind::F32, false, false}, + {"hc_ffn_norm.weight", g.hc_dim(), WeightKind::F32, false, false}, + {"ffn_gate_inp_shexp.weight", g.n_embd, WeightKind::Bf16InF32, false, false}, + {"ssm_a", g.ssm_v_heads, WeightKind::F32, false, true}, + {"ssm_dt.bias", g.ssm_v_heads, WeightKind::F32, false, true}, + {"ssm_norm.weight", g.ssm_state_size, WeightKind::F32, false, true}, + {"attn_q_norm.weight", g.head_dim, WeightKind::F32, true, false}, + {"attn_k_norm.weight", g.head_dim, WeightKind::F32, true, false}, + {"indexer.q_norm.weight", g.idx_key_dim, WeightKind::F32, true, false}, + {"indexer.k_norm.weight", g.idx_key_dim, WeightKind::F32, true, false}, + }; + for (const Want1& w : want1) { + if (w.qsa_only && !qsa) continue; + if (w.gdn_only && qsa) continue; + const WeightRef* r = v.get(w.suffix); + if (!r) { + err = "layer " + std::to_string(layer) + ": missing " + v.name(w.suffix); + return false; + } + if (r->elements != w.elements) return fail(err, v, w.suffix, "elements", r->elements, w.elements); + if (r->kind != w.kind) { + // The byte count is what makes this a REAL check and not a label: a 4 B/elem tensor holds + // `elements * 4`, a 2 B/elem one holds `elements * 2`, and a consumer reading it as the wrong one + // walks off the end. + const uint64_t want_bytes = (uint64_t) w.elements * + (w.kind == WeightKind::Bf16InF32 ? 2u : 4u); + char buf[512]; + std::snprintf(buf, sizeof buf, + "layer %lld: %s is engine form %d (%llu B), the kernels read it as form %d (%llu B)", + (long long) layer, v.name(w.suffix).c_str(), (int) r->kind, + (unsigned long long) r->bytes, (int) w.kind, (unsigned long long) want_bytes); + err = buf; + return false; + } + } + return true; +} + +} // namespace + +std::string LayerView::name(const char* suffix) const { + return "blk." + std::to_string(layer_) + "." + suffix; +} + +bool check_layer(const WeightTable& table, const ModelGeometry& g, int64_t layer, std::string& err) { + if (layer < 0 || layer >= g.n_layers) { + err = "layer " + std::to_string(layer) + " is outside 0.." + std::to_string(g.n_layers - 1); + return false; + } + return check_one(table, g, layer, err); +} + +bool check_all(const WeightTable& table, const ModelGeometry& g, std::string& err) { + int64_t n_qsa = 0, n_gdn = 0; + for (int64_t l = 0; l < g.n_layers; ++l) { + if (!check_one(table, g, l, err)) return false; + if (is_qsa_layer(g, l)) { + ++n_qsa; + } else { + ++n_gdn; + } + } + // The split is derived twice over in `docs/semantics.md` - the interval and an explicit ratio array - + // and both give 36 GDN and 12 QSA. Counting them here is the check that the LAYER TYPE PREDICATE and + // the pack agree, which no per-tensor shape check can see. + if (n_qsa != g.n_qsa_layers() || n_gdn != g.n_gdn_layers()) { + char buf[256]; + std::snprintf(buf, sizeof buf, "layer split is %lld QSA / %lld GDN, the geometry says %lld / %lld", + (long long) n_qsa, (long long) n_gdn, (long long) g.n_qsa_layers(), + (long long) g.n_gdn_layers()); + err = buf; + return false; + } + return true; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/load_main.cpp b/engine/strata/src/core/load_main.cpp new file mode 100644 index 00000000..0885b766 --- /dev/null +++ b/engine/strata/src/core/load_main.cpp @@ -0,0 +1,122 @@ +// src/core/load_main.cpp - `strata-load`: the expert arena load, measurable at any scale. +// +// P2.S1 gives this a target (<= 60 s cold, <= 10 s warm for 33.97 GB) and a method (8 threads, 16 MB chunks, +// a checksum per layer). The size is a FLAG rather than hard-coded because the honest way to measure a 34 GB +// load is to measure a smaller one first and project - and because pinning 34 GB evicts every page of page +// cache on the machine, which is not something a test should do while other work is running. +#include "strata/core/pinned.hpp" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + std::string path; + uint64_t layers = 2; + int threads = 8; + uint64_t chunk = 16ull << 20; + uint64_t blob_bytes = 1382400; // architecture §3.2, asserted by tools/pack_layer.py + uint64_t blobs_per_layer = 512; + bool pin = true; + bool stream = false; + + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto val = [&]() -> const char* { + if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + if (a == "--file") path = val(); + else if (a == "--layers") layers = std::strtoull(val(), nullptr, 10); + else if (a == "--threads") threads = std::atoi(val()); + else if (a == "--chunk-mb") chunk = std::strtoull(val(), nullptr, 10) << 20; + else if (a == "--no-pin") pin = false; + else if (a == "--stream") stream = true; + else if (a == "--help" || a == "-h") { + std::printf("usage: strata-load --file experts.bin [--layers N] [--threads N] [--chunk-mb N]\n" + " [--no-pin]\n"); + return 0; + } else { + std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); + return 2; + } + } + if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } + + const uint64_t bytes = layers * blobs_per_layer * blob_bytes; + std::printf("expert arena: %llu layers x %llu blobs x %llu B = %.3f GiB\n", (unsigned long long) layers, + (unsigned long long) blobs_per_layer, (unsigned long long) blob_bytes, + (double) bytes / (1024.0 * 1024 * 1024)); + + strata::core::PinnedArena arena; + uint8_t* dst = nullptr; + if (pin) { + // constructed in place so the note from the constructor can be printed before the load + new (&arena) strata::core::PinnedArena(bytes); + std::printf("backing: %s\n", arena.note.c_str()); + if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } + dst = arena.data(); + } else { + dst = (uint8_t*) std::malloc((size_t) bytes); + if (!dst) { std::fprintf(stderr, "malloc failed\n"); return 1; } + std::printf("backing: malloc, NOT pinned (--no-pin)\n"); + } + + const strata::core::LoadStats st = + strata::core::load_experts(path, dst, blob_bytes, blobs_per_layer, layers, threads, chunk); + if (!st.ok) { + std::fprintf(stderr, "loading the experts failed: %s\n", st.error.empty() ? "unknown" : st.error.c_str()); + return 1; + } + + std::printf("loaded %.3f GiB in %.3f s with %d threads and %llu MiB chunks -> %.2f GiB/s\n", + (double) st.bytes / (1024.0 * 1024 * 1024), st.seconds, threads, + (unsigned long long) (chunk >> 20), st.gib_per_second()); + std::printf("per-layer checksums (FNV-1a 64):\n"); + for (size_t i = 0; i < st.layer_checksums.size() && i < 4; ++i) { + std::printf(" layer %zu %016llx\n", i, (unsigned long long) st.layer_checksums[i]); + } + if (st.layer_checksums.size() > 4) { + std::printf(" ... %zu more (all layers loaded)\n", st.layer_checksums.size() - 4); + } + if (stream) { + // The bus is the ceiling, so measure it at the granularity the engine actually uses. Printed as a + // sweep rather than one number because "bandwidth" without a transfer size is not a specification. + std::printf("\nexpert stream over the pinned arena (host -> device, one reused destination):\n"); + const uint64_t granularities[] = {blob_bytes, 16 * blob_bytes, 512 * blob_bytes, bytes}; + const char* names[] = {"1 blob (1.38 MB)", "16 blobs (22 MB)", "1 layer (707 MB)", "whole arena"}; + for (int i = 0; i < 4; ++i) { + const uint64_t g = granularities[i]; + if (g > bytes) continue; + const int iters = (int) (g >= bytes ? 3 : (bytes / g >= 8 ? 8 : 3)); + const strata::core::StreamStats ss = + strata::core::stream_bandwidth(dst, (bytes / g) * g, g, iters); + if (ss.seconds < 0) continue; + std::printf(" %-18s chunk %8.2f MB %6.2f GB/s (%.3f GiB in %.3f s)\n", names[i], + (double) g / 1e6, ss.gib_per_second() * 1.073741824, + (double) ss.bytes / (1024.0 * 1024 * 1024), ss.seconds); + } + // And what it means, using the design's own constants, stated with the assumption attached. + const double best = 60.0; // GB/s, replaced below by the measured best if it is larger + (void) best; + std::printf("\nper-token expert stream at E = 663.6 MB and hit rate h (VRAM-resident fraction):\n"); + std::printf(" %-8s %-14s %-14s %s\n", "h", "miss MB/token", "ms at 1 blob", "tok/s ceiling"); + const strata::core::StreamStats one = strata::core::stream_bandwidth(dst, blob_bytes, blob_bytes, 64); + for (double h : {0.0, 0.5, 0.833, 0.9, 0.95}) { + const double miss_mb = (1.0 - h) * 663.6; + const double ms = miss_mb / 1000.0 / (one.gib_per_second() * 1.073741824) * 1000.0; + std::printf(" %-8.3f %-14.1f %-14.2f %.1f\n", h, miss_mb, ms, ms > 0 ? 1000.0 / ms : 0.0); + } + std::printf(" h = 0.167 is the design's constant; h = 0.833 is its complement, shown because the\n" + " plan's E = 663.6 MB is the FULL expert set per token, so which fraction is cached is\n" + " the question the number hinges on.\n"); + } + + // The projection is the number the phase's <= 60 s target is about, and it is printed as a projection + // rather than as the result, because at --layers 2 this program has NOT loaded 33.97 GB. + const double full = 33973862400.0; + std::printf("projection for the full %.2f GiB at this rate: %.1f s\n", full / (1024.0 * 1024 * 1024), + full / (1024.0 * 1024 * 1024) / (st.gib_per_second() > 0 ? st.gib_per_second() : 1e-9)); + return 0; +} diff --git a/engine/strata/src/core/mtp.cpp b/engine/strata/src/core/mtp.cpp new file mode 100644 index 00000000..5db90887 --- /dev/null +++ b/engine/strata/src/core/mtp.cpp @@ -0,0 +1,845 @@ +// src/core/mtp.cpp - see include/strata/core/mtp.hpp. +#include "strata/core/mtp.hpp" +#include "strata/core/coupled_draft.hpp" +#include "strata/core/on_device.hpp" + +#include "strata/core/native_head.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/gr.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/router_top10.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/sampler.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { +namespace { + +constexpr float EPS = 1e-6f; +constexpr int GGML_Q8_0 = 8; +using Clock = std::chrono::steady_clock; +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +struct Bump { + uint8_t* base = nullptr; + uint64_t used = 0; + template T* take(uint64_t n) { + T* p = base ? (T*) (base + used) : nullptr; + used += (n * sizeof(T) + 255) & ~255ull; + return p; + } +}; + +bool mapped(size_t bytes, void** h, void** d) { + if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false; + std::memset(*h, 0, bytes); + return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; +} + +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; + s.n_head_kv = g.n_head_kv; + s.head_dim = g.head_dim; + s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + return s; +} + +// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB. +#if defined(_WIN32) +#define STRATA_FILE_SEEK64(f, o, w) _fseeki64((f), (long long) (o), (w)) +#define STRATA_FILE_TELL64(f) _ftelli64(f) +#else +#define STRATA_FILE_SEEK64(f, o, w) fseeko((f), (off_t) (o), (w)) +#define STRATA_FILE_TELL64(f) ftello(f) +#endif + +bool read_file(const std::string& path, std::vector& out) { + // Loader fix (0.1.15+loaderfix.2): `ifstream::read` reaches the disk as 4095-byte reads on MSVC - the same + // split `load_experts_ranges` had - so the drafter's 111 MiB dense blob paid 4 KiB per operation on a cold + // start. `fread` passes a request bigger than the stream buffer straight to `ReadFile()`. + FILE* f = std::fopen(path.c_str(), "rb"); + if (f == nullptr) return false; + // A `FILE*` has no destructor and the short-read path below returns early: the guard closes on every path. + struct Closer { + FILE* f; + ~Closer() { if (f != nullptr) std::fclose(f); } + } closer{f}; + if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false; + const long long n = (long long) STRATA_FILE_TELL64(f); + if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false; + out.resize((size_t) n); + return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n; +} + +} // namespace + +MtpDrafter::~MtpDrafter() { + if (cs_) cudaStreamSynchronize(cs_); + for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e); + for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e); + if (pf_dev_) cudaFree(pf_dev_); + for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e); + for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e); + for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e); + for (auto& e : step_exec_c_) if (e) cudaGraphExecDestroy(e); + if (cparams_) cudaFree(cparams_); + if (cring_) cudaFree(cring_); + if (dinv_) cudaFree(dinv_); + if (cscratch_) cudaFree(cscratch_); + if (h_cparams_) cudaFreeHost(h_cparams_); + if (h_chist_) cudaFreeHost(h_chist_); + if (cs_) cudaStreamDestroy(cs_); + if (dense_) cudaFree(dense_); + if (experts_) cudaFree(experts_); + if (state_arena_) cudaFree(state_arena_); + if (arena_) cudaFree(arena_); + if (head_logits_) cudaFree(head_logits_); + if (dhead_) cudaFree(dhead_); + if (dvocab_) cudaFree(dvocab_); + void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; + for (void* h : hosts) if (h) cudaFreeHost(h); +} + +const float* MtpDrafter::f32(const char* name) const { + for (const auto& t : tensors_) if (t.name == name && t.kind == "f32") return (const float*) (dense_ + t.off); + return nullptr; +} +const uint16_t* MtpDrafter::bf16(const char* name) const { + for (const auto& t : tensors_) if (t.name == name && t.kind == "bf16") return (const uint16_t*) (dense_ + t.off); + return nullptr; +} +const void* MtpDrafter::q8(const char* name) const { + for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off; + return nullptr; +} + +bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, + int64_t window) { + cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there + g_ = &g; + ss_ = &ss; + max_t_ = max_t; + rt_dir_ = rt_dir; + if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; } + // Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting + // them apart from the rest of the stage is what makes the next regression visible. + const auto t_files = std::chrono::steady_clock::now(); + // ---- the index and the dense weights + { + std::ifstream idx(rt_dir + "/dense.txt"); + if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; } + std::string line; + while (std::getline(idx, line)) { + if (line.empty()) continue; + std::istringstream is(line); + Tensor t; + is >> t.name >> t.kind >> t.rows >> t.cols >> t.off >> t.bytes; + if (!is) { err = "mtp: malformed dense.txt line: " + line; return false; } + tensors_.push_back(t); + } + std::vector blob; + if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; } + const cudaError_t alloc = cudaMalloc((void**) &dense_, blob.size()); + if (alloc != cudaSuccess) { + size_t free_bytes = 0, total_bytes = 0; + const cudaError_t info = cudaMemGetInfo(&free_bytes, &total_bytes); + err = "mtp: dense weights allocation failed (" + std::string(cudaGetErrorString(alloc)) + + "), requested " + std::to_string(blob.size() >> 20) + " MiB, CUDA0 free " + + (info == cudaSuccess ? std::to_string(free_bytes >> 20) + " MiB" : "unknown"); + return false; + } + cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice); + vram_ += blob.size(); + } + // ---- the 512 routed experts, one blob each + { + const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB; + // Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under + // MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes. + FILE* f = std::fopen((rt_dir + "/experts.bin").c_str(), "rb"); + if (f == nullptr) { err = "mtp: cannot open experts.bin"; return false; } + struct Closer { + FILE* f; + ~Closer() { if (f != nullptr) std::fclose(f); } + } closer{f}; + if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the 512 experts do not fit in VRAM"; return false; } + std::vector chunk(64u << 20); + for (uint64_t off = 0; off < bytes;) { + const uint64_t n = std::min(chunk.size(), bytes - off); + if (std::fread(chunk.data(), 1, (size_t) n, f) != (size_t) n) { err = "mtp: experts.bin is truncated"; return false; } + cudaMemcpy(experts_ + off, chunk.data(), n, cudaMemcpyHostToDevice); + off += n; + } + vram_ += bytes; + } + const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", + "self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"}; + for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; } + + // ---- the layer's own K/V (dense attention: no indexer state is read) + const strata::kernels::QsaShapes s = shapes_of(g); + const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells; + // KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the + // window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy + // is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM. + int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). + struct RestoreKeylessMode { + bool previous = qsa_without_key(); + ~RestoreKeylessMode() { qsa_set_without_key(previous); } + } restore_keyless_mode; + qsa_set_without_key(false); + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); + if (kv_hybrid_was) qsa_set_kv_int8(true); // the drafter under --kv k8v4: plain INT8 + uint64_t sb = qsa_state_bytes(g, max_cells, false, ring); + if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } + if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { + if (st_.kv_mode == 0) { err = "mtp: state init failed"; return false; } + std::fprintf(stderr, "strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n"); + cudaGetLastError(); + cudaFree(state_arena_); + st_ = QsaState{}; + ring = -1; // fully resident + sb = qsa_state_bytes(g, max_cells, false, ring); + if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; } + if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { err = "mtp: state init failed"; return false; } + } + qsa_set_kv_int8(kv_int8_was); + qsa_set_kv_hybrid(kv_hybrid_was); + qsa_state_zero(st_, g, nullptr); + cudaDeviceSynchronize(); + vram_ += sb; + + // ---- buffers + window_ = (window > 0 && window < max_cells) ? window : 0; + cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64; + attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s); + const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k; + const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv; + const uint64_t R2 = 2 * T; // step/pos rows: T catch-up rows + up to T-2 chain steps + bool ok = mapped(T * 4 + 64, (void**) &h_tok_, (void**) &m_tok_) && + mapped(R2 * 4 * 4 + 64, (void**) &h_step_, (void**) &m_step_) && + mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) && + mapped(64, (void**) &h_row_, (void**) &m_row_) && + mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) && + mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_); + if (!ok) { err = "mtp: mapped staging failed"; return false; } + auto carve = [&](Bump& b) { + tok_ = b.take(T); step_ = b.take(R2 * 4); pos_ = b.take(R2 * NH); row_ = b.take(4); + ident_ = b.take(T * (uint64_t) cap_); + Rin_ = b.take(T * HC * N); R_ = b.take(T * HC * N); + emb_ = b.take(T * N); en_ = b.take(T * N); e2_ = b.take(T * N); + hn_ = b.take(T * HC * N); h2_ = b.take(T * HC * N); + mixed_ = b.take(T * N); inj_ = b.take(T * HC); inj2_ = b.take(T * HC); + lo_ = b.take(T * (uint64_t) g.hc_lr); rs_ = b.take(T * HC); bo_ = b.take(T * N); + xn_ = b.take(T * HC * N); + xq_ = b.take(strata::kernels::native_q8_1_bytes((int) (NH * HD), 8)); + qfull_ = b.take(T * NH * 2 * HD); qcur_ = b.take(T * NH * HD); + kcur_ = b.take(T * NKV * HD); vcur_ = b.take(T * NKV * HD); + attn_ = b.take(T * NH * HD); attn32_ = b.take(T * NH * HD); + attn_scratch_ = b.take((uint64_t) attn_scratch_floats_); // the full layer runs one row at a time + logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); + shared_ = b.take(T * N); parts_ = b.take(T * K * N); y_ = b.take(T * N); + sample_ = b.take(T * N); + hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); + grp_ptr_ = b.take(T * K); grp_start_ = b.take(T * K + 1); + grp_counts_ = b.take(4); + hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); + hit_scratch_ = b.take(strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff)); + sh_scratch_ = (float*) b.take(strata::kernels::shared_expert_scratch_bytes(g.n_ff)); + x_bf16_ = b.take(N); + out_ids_ = b.take(T + 4); + probs_ = b.take(T + 4); + dummy_inj_ = b.take(HC); + }; + Bump count; + carve(count); + if (cudaMalloc(&arena_, count.used) != cudaSuccess) { err = "mtp: buffers do not fit"; return false; } + cudaMemset(arena_, 0, count.used); + Bump real; + real.base = (uint8_t*) arena_; + carve(real); + vram_ += count.used; + { + std::vector id((size_t) (T * (uint64_t) cap_)); + for (uint64_t t = 0; t < T; ++t) + for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i; + cudaMemcpy(ident_, id.data(), id.size() * 4, cudaMemcpyHostToDevice); + } + if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } + const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); + std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n", + (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0, + (double) tensors_.back().off / 1048576.0, files_s, + files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) / + 1048576.0 / files_s : 0.0); + return true; +} + +uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { + uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); + if (dhead_ == nullptr) { + if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) { + std::fseek(f, 0, SEEK_END); + const long size = std::ftell(f); + std::fclose(f); + if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size; + } + } + // coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring, + // the split scratch (64 lists of 64 entries at most) and the parameters + if (coupled_draft_env() && cparams_ == nullptr) + bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096; + return bytes; +} + +bool MtpDrafter::setup_coupled(std::string& err) { + const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_; + const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv); + if (scratch == 0) { + std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; " + "argmax drafts\n", (long long) nv); + return true; + } + const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t); + if (cudaMalloc((void**) &cparams_, sizeof(strata::kernels::SamplerParams)) != cudaSuccess || + cudaMalloc((void**) &cring_, ring) != cudaSuccess || cudaMalloc(&cscratch_, scratch) != cudaSuccess || + !mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) || + !mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) { + err = "mtp: the coupled draft sampler's buffers do not fit"; + return false; + } + cudaMemset(cring_, 0xff, ring); // -1: no token + std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1); + vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch; + if (dhead_ != nullptr) { // token id -> subset index (-1: not in the draft head), for the penalties + std::vector sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1); + cudaMemcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t), cudaMemcpyDeviceToHost); + for (size_t i = 0; i < sub.size(); ++i) + if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i; + if (cudaMalloc((void**) &dinv_, inv.size() * sizeof(int32_t)) != cudaSuccess) { + err = "mtp: the coupled draft sampler's token map does not fit"; + return false; + } + cudaMemcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + vram_ += inv.size() * sizeof(int32_t); + } + if (cudaDeviceSynchronize() != cudaSuccess) { + err = std::string("mtp: coupled setup: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + coupled_ok_ = true; + std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the " + "target's chain and Philox draw over %lld tokens\n", (long long) nv); + return true; +} + +void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) { + coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f; + if (!coupled_active_) return; + *h_cparams_ = sp; // read by the next round graph (after the previous one has synced) + std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1); +} + +void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) { + if (!coupled_active_) return; + const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap); + coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h)); +} + +bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) { + const OnDevice on_device(device_); + wt_ = &wt; + head_ = head; + window_R_ = window_R; + const WeightRef* wo = wt.find("output.weight"); + if (!wo) { err = "mtp: output.weight is missing"; return false; } + n_vocab_ = wo->ne1; + if (head == nullptr || !head->loaded()) { err = "mtp: the draft layer needs the native head (--native)"; return false; } + if (head_logits_ == nullptr && + cudaMalloc((void**) &head_logits_, (size_t) max_t_ * (size_t) n_vocab_ * sizeof(float)) != cudaSuccess) { + err = "mtp: the draft logits do not fit"; + return false; + } + // the draft head's token subset, when tools/draft_vocab.py wrote one + if (dhead_ == nullptr) { + std::vector raw; + if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) { + n_dvocab_ = (int64_t) (raw.size() / 4); + const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head + if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess || + cudaMalloc((void**) &dhead_, (size_t) (n_dvocab_ * row_bytes)) != cudaSuccess) { + err = "mtp: the draft head does not fit"; + return false; + } + cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice); + strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr); + cudaDeviceSynchronize(); + vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size(); + std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_, + (double) (n_dvocab_ * row_bytes) / 1048576.0); + } + } + if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false; + return true; +} + +// The layer for T rows. full = false stops after the K/V append (the prompt only needs the cache). +bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::string& err) { + using namespace strata::kernels; + const ModelGeometry& g = *g_; + SessionState& ss = *ss_; + // step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T) + const bool full = step_row0 >= 0; + const int row0 = full ? step_row0 : -1 - step_row0; + if (full && T != 1) { err = "mtp: the full layer runs one row at a time (its attention scratch is sized for one)"; return false; } + const int64_t N = g.n_embd, HC = g.hc, K = ss.k, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv; + const QsaShapes s = shapes_of(g); + const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; + const int32_t* step = step_ + row0 * 4; + const int32_t* pos = pos_ + row0 * NH; + try { + // ---- the two input branches + const WeightRef* we = wt_->find("token_embd.weight"); + if (!we) { err = "mtp: token_embd.weight is missing"; return false; } + if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table + ne->gather_dev(tok_, T, emb_, cs); + } else { + const auto* codes = (const uint8_t*) we->data; + const auto* scales = (const float*) (codes + we->codes_bytes); + const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr; + embedding_gather_dev(codes, scales, offsets, tok_, T, we->ne0, we->code_bits, we->code_bias, we->group_elems, + (uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), emb_, cs); + } + native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs); + native_quantize_q8_1(en_, xq_, (int) N, T, cs); + native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs); + native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs); + for (int c0 = 0; c0 < T * HC; c0 += 8) { + const int nc = (int) std::min(8, T * HC - c0); + native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs); + native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs); + } + add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs); + // ---- the attention hyper-connection + { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = 0; t < T; ++t) { + fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = false; + fa[t].w_norm = f32("attn_hyper_connection.hc_norm.weight"); + fa[t].w_down = bf16("attn_hyper_connection.input_mix_weight_down.weight"); + fa[t].w_up = bf16("attn_hyper_connection.input_mix_weight_up.weight"); + fa[t].w_inject = bf16("attn_hyper_connection.block_inject_weight.weight"); + fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; + fa[t].inject_out = inj_ + t * HC; fa[t].mixed = mixed_ + t * N; + } + fused_gr_read_multi(fa, T, xn_, cs); + } + // ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell + auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) { + native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); + }; + native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); + native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs); + native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs); + for (int t = 0; t < T; ++t) { + norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH); + if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 + fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs); + fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs); + } + // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has) + if (st_.kv_q4) + kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, &st_.host); + else if (st_.kv_int8) + kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4, + kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host); + else + kv_append_step(st_.k_pool, st_.v_pool, st_.page_table, step + t * 4, kcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, &st_.host); + } + if (!full) return true; + native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs); + for (int t = 0; t < T; ++t) { + float* qc = qcur_ + t * NH * HD; + if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4, + (size_t) NH, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { + err = "mtp: q split failed"; + return false; + } + norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH); + if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs); + } + const QsaAttnPools pools = qsa_attn_pools(st_); + if (window_ > 0) window_ids(const_cast(step), T, (int) window_, ident_, cap_, cs); + qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs); + if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs); + for (int t = 0; t < T; ++t) + native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs); + native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs); + native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs); + // ---- the MLP hyper-connection (the attention write folded in) + { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = 0; t < T; ++t) { + fa[t].R = R_ + (size_t) t * HC * N; fa[t].R_out = R_ + (size_t) t * HC * N; fa[t].apply = true; + fa[t].bo_prev = bo_ + t * N; fa[t].inj_prev = inj_ + t * HC; + fa[t].w_norm = f32("mlp_hyper_connection.hc_norm.weight"); + fa[t].w_down = bf16("mlp_hyper_connection.input_mix_weight_down.weight"); + fa[t].w_up = bf16("mlp_hyper_connection.input_mix_weight_up.weight"); + fa[t].w_inject = bf16("mlp_hyper_connection.block_inject_weight.weight"); + fa[t].eps = EPS; fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; + fa[t].inject_out = inj2_ + t * HC; fa[t].mixed = mixed_ + t * N; + } + fused_gr_read_multi(fa, T, xn_, cs); + } + // ---- MoE: router, the 512 resident experts, the shared expert, the combine, the write + for (int t = 0; t < T; ++t) { + bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs); + if (native_router_enabled()) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs); + else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs); + } + moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_, + grp_start_, grp_counts_, hit_dst_, hit_slot_, cs); + quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs); + moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_, + hit_xs_, hit_scratch_, parts_, cs); + NativeSharedWeights nsw; + nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight"); + nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight"); + nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight"); + nsw.q8_1 = xq_; + const SForm none{}; + for (int t = 0; t < T; ++t) { + f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs); + shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr, none, + nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_, shared_ + t * N, + N, g.n_ff, 32, cs, mixed_ + t * N, &nsw); + if (native_moe_combine_enabled()) + native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs); + else + moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs); + gr_write(R_ + (size_t) t * HC * N, y_ + t * N, inj2_ + t * HC, gs, R_ + (size_t) t * HC * N, cs); + } + // ---- the final mixer and the main model's head + for (int t = 0; t < T; ++t) + gr_read(R_ + (size_t) t * HC * N, f32("hyper_connection_mixer.hc_norm.weight"), + bf16("hyper_connection_mixer.input_mix_weight_down.weight"), + bf16("hyper_connection_mixer.input_mix_weight_up.weight"), nullptr, EPS, gs, ss.block.gr, + sample_ + t * N, dummy_inj_, cs); + native_quantize_q8_1(sample_, xq_, (int) N, T, cs); + const bool sub = dhead_ != nullptr; + const int64_t nv = sub ? n_dvocab_ : n_vocab_; + native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs); + if (coupled_rec_) { + // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft + // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer) + coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_, + cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs); + return true; + } + SamplerParams sp; + sp.greedy = true; + sp.temperature = 0.0f; + sample_tokens(head_logits_, T, (int) nv, nullptr, 0, sp, out_ids_, cs); + row_top_prob(head_logits_, T, (int) nv, out_ids_, probs_, cs); + if (sub) map_ids(out_ids_, dvocab_, T, cs); + } catch (const std::exception& e) { + err = std::string("mtp: ") + e.what(); + return false; + } + return true; +} + +namespace { +bool finish_capture(cudaStream_t cs, bool ok, cudaGraphExec_t& exec, const char* what, std::string& err) { + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs, &graph); + if (!ok) { + if (graph) cudaGraphDestroy(graph); + return false; + } + if (ce != cudaSuccess || cudaGraphInstantiate(&exec, graph, 0) != cudaSuccess) { + if (graph) cudaGraphDestroy(graph); + err = std::string("mtp: ") + what + " capture: " + cudaGetErrorString(ce); + return false; + } + cudaGraphDestroy(graph); + // an explicit upload: the first launch's implicit one blocked behind a device-side spin (verify.cpp) + cudaGraphUpload(exec, cs); + cudaStreamSynchronize(cs); + return true; +} +} // namespace + +bool MtpDrafter::capture_prefill(int T, std::string& err) { + if (prefill_exec_[T]) return true; + using namespace strata::kernels; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } + copy_i32_from_mapped(tok_, m_tok_, T, cs_); + copy_i32_from_mapped(step_, m_step_, (int64_t) T * 4, cs_); + copy_i32_from_mapped(pos_, m_pos_, (int64_t) T * g_->n_head, cs_); + const bool ok = record_forward(T, -1, cs_, err); // K/V only, rows [0, T) + return finish_capture(cs_, ok, prefill_exec_[T], "prefill", err); +} + +bool MtpDrafter::capture_prefill_dev(int T, std::string& err) { + if (prefill_dev_exec_[T]) return true; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } + const bool ok = record_forward(T, -1, cs_, err); // K/V only, rows [0, T); tok_/step_/pos_ filled before launch + return finish_capture(cs_, ok, prefill_dev_exec_[T], "prefill (device inputs)", err); +} + +bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) { + cudaGraphExec_t& exec = coupled ? round_exec_c_[T] : round_exec_[T]; + if (exec) return true; + using namespace strata::kernels; + const int64_t HCN = g_->hc * g_->n_embd; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } + bool ok = true; + // coupled: the request's chain and the penalty history's base, for this round's drafts + if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_); + copy_i32_from_mapped(tok_, m_tok_, T, cs_); + copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_); + copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_); + copy_i32_from_mapped(row_, m_row_, 2, cs_); + copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_); + // the catch-up: K/V for the window's T cells, then the full layer for row a only (its cell's K/V is written + // again, identically), staged by the host in step row 2*max_t - 1; the draft chain is one graph per step + // (`capture_step`) so the host can stop it when a draft is unlikely + const int ra = 2 * max_t_ - 1; + ok = record_forward(T, -1, cs_, err); + if (ok) mtp_select(Rin_, HCN, tok_, row_, Rin_, tok_, nullptr, 0, cs_); + if (ok) { + copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_); + copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_); + coupled_rec_ = coupled; + coupled_j_ = 0; + ok = record_forward(1, ra, cs_, err); + coupled_rec_ = false; + } + if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_); + return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err); +} + +// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's +// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs. +bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) { + cudaGraphExec_t& exec = coupled ? step_exec_c_[j] : step_exec_[j]; + if (exec) return true; + using namespace strata::kernels; + const int64_t HCN = g_->hc * g_->n_embd; + const int row = max_t_ + j - 1; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; } + copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_); + copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_); + coupled_rec_ = coupled; + coupled_j_ = j; + bool ok = record_forward(1, row, cs_, err); + coupled_rec_ = false; + if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_); + return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err); +} + +void MtpDrafter::kv_restore(int64_t upto) { + const OnDevice on_device(device_); + if (st_.kv_mode != 2 || upto <= 0) return; + // the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them + const strata::kernels::QsaShapes s = shapes_of(*g_); + const int64_t b1 = (upto + s.page_size - 1) / s.page_size, b0 = std::max(0, b1 - st_.n_slots); + strata::kernels::kv_ring_restore(qsa_attn_pools(st_), st_.host, qsa_kv_format(st_), b0, b1, st_.n_slots, s, cs_); + cudaStreamSynchronize(cs_); +} + +bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { + const OnDevice on_device(device_); + const Clock::time_point t0 = Clock::now(); + const int64_t HCN = g_->hc * g_->n_embd; + // cells the window can never reach again need no K/V + const int64_t first_needed = (window_ > 0 && prompt_len_ > 0) ? prompt_len_ - window_ - 64 : 0; + // E-4: every group's token / step / position records uploaded at once; each group is then device copies and a + // graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped + // memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same + // order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop. + static const bool per_group_sync = std::getenv("STRATA_MTP_PREFILL_SYNC") != nullptr; + const int64_t NHp = g_->n_head, per_row = 1 + 4 + NHp; + if (!per_group_sync && n > 0) { + if (pf_cap_ < n * per_row) { + if (pf_dev_) cudaFree(pf_dev_); + pf_dev_ = nullptr; + pf_cap_ = 0; + if (cudaMalloc((void**) &pf_dev_, (size_t) (n * per_row) * sizeof(int32_t)) != cudaSuccess) { + err = "mtp prefill: the input records do not fit"; + return false; + } + pf_cap_ = n * per_row; + } + std::vector rec((size_t) (n * per_row)); + int32_t* tk = rec.data(); + int32_t* stp = tk + n; + int32_t* ps = stp + 4 * n; + for (int64_t i = 0; i < n; ++i) { + const int64_t cell = cell0 + i; + tk[i] = next_tokens[i]; + stp[i * 4 + 0] = (int32_t) cell; + stp[i * 4 + 1] = (int32_t) (cell + 1); + stp[i * 4 + 2] = (int32_t) ((cell + 1) / 4); + stp[i * 4 + 3] = (int32_t) (cell + 1); + for (int64_t h = 0; h < NHp; ++h) ps[i * NHp + h] = (int32_t) cell; + } + if (cudaMemcpyAsync(pf_dev_, rec.data(), rec.size() * sizeof(int32_t), cudaMemcpyHostToDevice, cs_) != cudaSuccess) { + err = "mtp prefill: the input records upload failed"; + return false; + } + const int32_t* d_tk = pf_dev_; + const int32_t* d_stp = d_tk + n; + const int32_t* d_ps = d_stp + 4 * n; + for (int64_t c = 0; c < n; c += max_t_) { + const int T = (int) std::min(max_t_, n - c); + if (cell0 + c + T <= first_needed) continue; + if (!capture_prefill_dev(T, err)) return false; + if (cudaMemcpyAsync(tok_, d_tk + c, (size_t) T * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || + cudaMemcpyAsync(step_, d_stp + c * 4, (size_t) T * 16, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || + cudaMemcpyAsync(pos_, d_ps + c * NHp, (size_t) (T * NHp) * 4, cudaMemcpyDeviceToDevice, cs_) != cudaSuccess || + cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice, + cs_) != cudaSuccess || + cudaGraphLaunch(prefill_dev_exec_[T], cs_) != cudaSuccess) { + err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + } + if (cudaStreamSynchronize(cs_) != cudaSuccess) { + err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + ms_prefill += ms_since(t0); + return true; + } + for (int64_t c = 0; c < n; c += max_t_) { + const int T = (int) std::min(max_t_, n - c); + if (cell0 + c + T <= first_needed) continue; + if (!capture_prefill(T, err)) return false; + for (int t = 0; t < T; ++t) { + const int64_t cell = cell0 + c + t; + h_tok_[t] = next_tokens[c + t]; + h_step_[t * 4 + 0] = (int32_t) cell; + h_step_[t * 4 + 1] = (int32_t) (cell + 1); + h_step_[t * 4 + 2] = (int32_t) ((cell + 1) / 4); + h_step_[t * 4 + 3] = (int32_t) (cell + 1); + for (int64_t h = 0; h < g_->n_head; ++h) h_pos_[t * g_->n_head + h] = (int32_t) cell; + } + if (cudaMemcpyAsync(Rin_, R_rows + (size_t) c * HCN, (size_t) T * HCN * sizeof(float), cudaMemcpyDeviceToDevice, + cs_) != cudaSuccess || + cudaGraphLaunch(prefill_exec_[T], cs_) != cudaSuccess || + cudaStreamSynchronize(cs_) != cudaSuccess) { + err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + } + ms_prefill += ms_since(t0); + return true; +} + +bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err, + float* probs, float min_p, int* n_drafts) { + const OnDevice on_device(device_); + if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } + const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs + if (!capture_round(T, cp, err)) return false; + const Clock::time_point t0 = Clock::now(); + const int64_t NH = g_->n_head; + auto put = [&](int row, int64_t cell) { + h_step_[row * 4 + 0] = (int32_t) cell; + h_step_[row * 4 + 1] = (int32_t) (cell + 1); + h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); + h_step_[row * 4 + 3] = (int32_t) (cell + 1); + for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; + }; + for (int t = 0; t < T; ++t) { + h_tok_[t] = tokens[t]; + put(t, p + t); + } + put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0)); // p + a: draft 0's cell + h_row_[0] = a; + h_row_[1] = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + if (cudaGraphLaunch(cp ? round_exec_c_[T] : round_exec_[T], cs_) != cudaSuccess || + cudaStreamSynchronize(cs_) != cudaSuccess) { + err = std::string("mtp draft: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + drafts[0] = ((volatile int32_t*) h_out_)[0]; + float pj = ((volatile float*) h_prob_)[0]; + if (probs) probs[0] = pj; + int n = 1; + // the chain continues while the last draft is likely enough to be verified + for (int j = 1; j < std::min(max_t_ - 1, max_drafts_) && pj >= min_p; ++j) { + if (!capture_step(j, cp, err)) return false; + put(max_t_ + j - 1, coupled_draft_cell(p, a, j)); // p + a + j; coupled: drawn at counter cell + 1 + std::atomic_thread_fence(std::memory_order_seq_cst); + if (cudaGraphLaunch(cp ? step_exec_c_[j] : step_exec_[j], cs_) != cudaSuccess || + cudaStreamSynchronize(cs_) != cudaSuccess) { + err = std::string("mtp draft step: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + drafts[j] = ((volatile int32_t*) h_out_)[j]; + pj = ((volatile float*) h_prob_)[j]; + if (probs) probs[j] = pj; + ++n; + } + for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; } + if (n_drafts) *n_drafts = n; + ms_draft += ms_since(t0); + ++rounds; + return true; +} + +bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, + float* probs, float min_p, int* n_drafts) { + const OnDevice on_device(device_); + // row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites + const int64_t HCN = g_->hc * g_->n_embd; + for (int t = 0; t < T; ++t) + if (cudaMemcpy((void*) (window_R_ + (size_t) t * HCN), R_row, (size_t) HCN * sizeof(float), + cudaMemcpyDeviceToDevice) != cudaSuccess) { + err = "mtp: staging the first residual failed"; + return false; + } + std::vector toks((size_t) T, token); + return draft(T, toks.data(), cell, 0, drafts, err, probs, min_p, n_drafts); +} + +} // namespace strata::core diff --git a/engine/strata/src/core/native_dense.cpp b/engine/strata/src/core/native_dense.cpp new file mode 100644 index 00000000..4a86d48c --- /dev/null +++ b/engine/strata/src/core/native_dense.cpp @@ -0,0 +1,195 @@ +#include "strata/core/native_dense.hpp" +#include "strata/core/weights.hpp" +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { +namespace { +bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) { + const auto& name = tensor.name; + if (name.rfind("blk.", 0) != 0) return false; + // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 + // fallback. + if (name == "blk.1.ple_key.weight") + return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23 || tensor.type == 8); + static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", + ".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight", + ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"}; + for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true; + return false; +} +struct DeviceFree { void operator()(void* p) const { if (p) cudaFree(p); } }; +using DevicePtr = std::unique_ptr; +struct Pending { + WeightRef* ref; + int type; + uint64_t bytes; + DevicePtr data; +}; +} + +bool NativeDense::served_names(const std::vector& shards, bool include_ple_key, + std::set& out, std::string& err) { + try { + for (const auto& path : shards) { + strata::GgufFile gguf(path); + for (const auto& tensor : gguf.tensors()) + if (eligible(tensor, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) && + tensor.shape.size() == 2) + out.insert(tensor.name); + } + return true; + } catch (const std::exception& error) { + err = std::string("native dense: ") + error.what(); + return false; + } +} + +bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set& skip, + std::string& err) { + const std::string key = "blk.1.ple_key.weight"; + if (!skip.count(key)) return true; + int code_bits = -1; + if (!WeightTable::index_code_bits(pack_dir, key, code_bits, err)) return false; + if (code_bits == 0) skip.erase(key); + return true; +} + +NativeDense::~NativeDense() { + if (scratch_) cudaFree(scratch_); + for (void* p : weights_) cudaFree(p); +} + +bool NativeDense::load(const std::vector& shards, WeightTable& table, std::string& err, + bool include_ple_key) { + if (scratch_ || !weights_.empty()) { err = "native dense: already loaded"; return false; } + if (shards.empty()) { err = "native dense: at least one GGUF shard is required"; return false; } + try { + std::vector pending; + std::set seen; + int max_in = 0; + uint64_t total = 0; + uint64_t split_count = 0, split_tensors = 0; + std::set split_numbers; + bool have_architecture = false; + for (const auto& path : shards) { + strata::GgufFile gguf(path); + const auto* count = gguf.get("split.count"); + const auto* number = gguf.get("split.no"); + const auto* tensors = gguf.get("split.tensors.count"); + if (gguf.get("general.architecture")) { + err = strata::check_architecture(gguf); + if (!err.empty()) return false; + have_architecture = true; + if (count && number && tensors && number->u == 0 && count->u > 1) { + split_count = count->u; + split_tensors = tensors->u; + } + } else if (!have_architecture || !split_count || !count || !number || !tensors || + count->u != split_count || number->u == 0 || number->u >= split_count || + tensors->u != split_tensors) { + err = "native dense: additional shard must match the architecture-validated first shard's split metadata"; + return false; + } + if (number && !split_numbers.insert(number->u).second) { + err = "native dense: duplicate split shard number"; return false; + } + std::vector offsets; + for (const auto& tensor : gguf.tensors()) offsets.push_back(tensor.offset); + std::sort(offsets.begin(), offsets.end()); + if (std::adjacent_find(offsets.begin(), offsets.end()) != offsets.end()) { + err = "native dense: tensor payload offsets overlap"; return false; + } + // Validate every directory span, including tensors we do not upload: + // an ignored tensor must not overlap the native matrix that follows it. + const uint64_t payload = gguf.file_size() - gguf.data_start(); + for (const auto& tensor : gguf.tensors()) { + int block_elements = 0, block_bytes = 0; + uint64_t elements = 1; + if (tensor.shape.empty() || !strata::block_geometry(tensor.type, block_elements, block_bytes) || + tensor.shape[0] % (uint64_t) block_elements != 0) { + err = "native dense: invalid block geometry " + tensor.name; return false; + } + for (uint64_t dimension : tensor.shape) { + if (!dimension || elements > (std::numeric_limits::max)() / dimension) { + err = "native dense: invalid tensor extent " + tensor.name; return false; + } + elements *= dimension; + } + const uint64_t blocks = elements / (uint64_t) block_elements; + if (blocks > (std::numeric_limits::max)() / (uint64_t) block_bytes) { + err = "native dense: tensor byte count overflow " + tensor.name; return false; + } + const uint64_t bytes = blocks * (uint64_t) block_bytes; + if (tensor.offset > payload || bytes > payload - tensor.offset) { + err = "native dense: truncated payload " + tensor.name; return false; + } + const auto next = std::upper_bound(offsets.begin(), offsets.end(), tensor.offset); + if (next != offsets.end() && bytes > *next - tensor.offset) { + err = "native dense: overlapping payload " + tensor.name; return false; + } + } + for (const auto& tensor : gguf.tensors()) { + if (!eligible(tensor, include_ple_key)) continue; + if (!seen.insert(tensor.name).second) { + err = "native dense: duplicate tensor " + tensor.name; return false; + } + auto found = table.table_.find(tensor.name); + if (found == table.table_.end()) { + err = "native dense: tensor absent from canonical table: " + tensor.name; return false; + } + auto& ref = found->second; + if (ref.native_data) { err = "native dense: override already attached"; return false; } + if (!strata::kernels::native_mmvq_supported(tensor.type)) continue; + // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena + if (tensor.name == "blk.1.ple_key.weight" && !ref.quantized()) continue; + if (!ref.quantized() || tensor.shape.size() != 2 || + ref.ne0 <= 0 || ref.ne0 > INT_MAX || ref.ne1 <= 0 || ref.ne1 > INT_MAX || + tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1) { + err = "native dense: incompatible matrix " + tensor.name; return false; + } + const auto bytes = strata::kernels::native_mmvq_weight_bytes( + tensor.type, (int) ref.ne0, (int) ref.ne1); + void* allocation = nullptr; + auto status = cudaMalloc(&allocation, bytes); + DevicePtr data(allocation); + if (status == cudaSuccess) + status = cudaMemcpy(data.get(), gguf.tensor_data(tensor), bytes, cudaMemcpyHostToDevice); + if (status != cudaSuccess) { + err = "native dense upload " + tensor.name + ": " + cudaGetErrorString(status); return false; + } + max_in = (std::max)(max_in, (int) ref.ne0); + total += bytes; + pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data)}); + } + } + if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; } + void* allocation = nullptr; + const auto status = cudaMalloc(&allocation, strata::kernels::native_q8_1_bytes(max_in)); + DevicePtr scratch(allocation); + if (status != cudaSuccess) { err = std::string("native dense scratch: ") + cudaGetErrorString(status); return false; } + // All checks and allocations finish before publishing any reference. + weights_.reserve(pending.size()); + for (auto& item : pending) { + item.ref->native_data = item.data.get(); + item.ref->native_type = item.type; + item.ref->native_q8_1 = scratch.get(); + weights_.push_back(item.data.release()); + } + scratch_ = scratch.release(); + bytes_ = total; + return true; + } catch (const std::exception& error) { + err = std::string("native dense: ") + error.what(); + return false; + } +} +} // namespace strata::core diff --git a/engine/strata/src/core/native_head.cpp b/engine/strata/src/core/native_head.cpp new file mode 100644 index 00000000..acb4f81f --- /dev/null +++ b/engine/strata/src/core/native_head.cpp @@ -0,0 +1,198 @@ +#include "strata/core/native_head.hpp" +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include +#include + +namespace strata::core { + +NativeHead::~NativeHead() { + if (scratch_) cudaFree(scratch_); + if (weights_) cudaFree(weights_); +} + +bool NativeHead::load(const std::vector& shards, int64_t n_in, int64_t n_out, std::string& err) { + if (loaded()) { err = "native head is already loaded"; return false; } + if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) { + err = "native head requires positive int32 dimensions and whole 256-value rows"; + return false; + } + try { + // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 + // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. + const strata::GgufModel model(shards); + err = strata::check_architecture(model.meta()); + if (!err.empty()) return false; + size_t at = 0; + const strata::TensorInfo* tensor = model.find("output.weight", &at); + const strata::GgufFile& gguf = model.shard(at); + if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 || + tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) { + err = "native head: expected a natively supported output.weight with the canonical head dimensions"; + return false; + } + const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes((int) tensor->type, (int) n_in, (int) n_out); + const uint64_t payload = gguf.file_size() - gguf.data_start(); + if (tensor->offset > payload || bytes > payload - tensor->offset) { + err = "native head: truncated output.weight payload"; + return false; + } + void* weights = nullptr; + void* scratch = nullptr; + cudaError_t status = cudaMalloc(&weights, bytes); + if (status == cudaSuccess) + status = cudaMalloc(&scratch, strata::kernels::native_q8_1_bytes((int) n_in, 1)); + if (status == cudaSuccess) + status = cudaMemcpy(weights, gguf.tensor_data(*tensor), bytes, cudaMemcpyHostToDevice); + if (status != cudaSuccess) { + if (scratch) cudaFree(scratch); + if (weights) cudaFree(weights); + err = std::string("native head upload: ") + cudaGetErrorString(status); + return false; + } + weights_ = weights; + scratch_ = scratch; + bytes_ = bytes; + n_in_ = (int) n_in; + n_out_ = (int) n_out; + type_ = (int) tensor->type; + return true; + } catch (const std::exception& error) { + err = std::string("native head: ") + error.what(); + return false; + } +} + +bool NativeHead::run(const float* mixed, float* logits, void* stream, std::string& err) const { + if (!loaded() || !mixed || !logits || !stream) { + err = "native head requires loaded weights, device buffers and an explicit stream"; + return false; + } + try { + if (type_ == 13) { + strata::kernels::native_q5_k_f32(weights_, mixed, scratch_, logits, n_in_, n_out_, 1, stream); + } else { + strata::kernels::native_quantize_q8_1(mixed, scratch_, n_in_, 1, stream); + strata::kernels::native_mmvq(type_, weights_, scratch_, logits, n_in_, n_out_, 1, stream); + } + } catch (const std::exception& error) { + err = std::string("native head launch: ") + error.what(); + return false; + } + const cudaError_t status = cudaPeekAtLastError(); + if (status != cudaSuccess) { + err = std::string("native head launch: ") + cudaGetErrorString(status); + return false; + } + return true; +} + +// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================ + +namespace { +const NativeEmbed* g_embed = nullptr; +} +void set_native_embed(const NativeEmbed* e) { g_embed = e; } +const NativeEmbed* native_embed() { return g_embed; } + +NativeEmbed::~NativeEmbed() { + if (host_) cudaFreeHost(host_); + else if (dev_) cudaFree(const_cast(dev_)); // the VRAM fallback below +} + +bool NativeEmbed::load(const std::vector& shards, int64_t n_embd, int64_t n_vocab, std::string& err) { + try { + const strata::GgufModel model(shards); + // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked + const strata::MetaValue* arch = model.meta().get("general.architecture"); + err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta()); + if (!err.empty()) { err = "native embedding: " + err; return false; } + size_t at = 0; + const strata::TensorInfo* t = model.find("token_embd.weight", &at); + const strata::GgufFile& gguf = model.shard(at); + if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab || + !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) { + err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " + "dequantizer"; + return false; + } + row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd); + bytes_ = (uint64_t) row_ * (uint64_t) n_vocab; + // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF + if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) { + err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) + + " B (" + gguf.path() + ")"; + bytes_ = 0; + return false; + } + if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { + // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts + // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM + // instead: it costs its size there and reads faster than over PCIe. + cudaGetLastError(); + host_ = nullptr; + void* d = nullptr; + if (cudaMalloc(&d, bytes_) != cudaSuccess || + cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { + if (d) cudaFree(d); + cudaGetLastError(); + err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB, nor place it in VRAM"; + return false; + } + std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n", + (unsigned long long) (bytes_ >> 20)); + dev_ = d; + } else { + std::memcpy(host_, gguf.tensor_data(*t), bytes_); + void* d = nullptr; +#if defined(STRATA_USE_HIP) + // #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives + // one, it is the host address itself - unified addressing; kernels read it correctly there, a + // device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from, + // so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start. + if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess || d == nullptr) { + cudaGetLastError(); + d = nullptr; + if (cudaMalloc(&d, bytes_) != cudaSuccess || + cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) { + if (d) cudaFree(d); + cudaGetLastError(); + err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into"; + return false; + } + cudaFreeHost(host_); // the destructor frees dev_ when host_ is null + host_ = nullptr; + std::fprintf(stderr, "strata: native embedding: no device alias for the mapped table, kept in VRAM\n"); + } +#else + if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) { + err = "native embedding: no device alias for the mapped table"; + return false; + } +#endif + dev_ = d; + } + type_ = (int) t->type; + n_embd_ = n_embd; + n_vocab_ = n_vocab; + return true; + } catch (const std::exception& e) { + err = std::string("native embedding: ") + e.what(); + return false; + } +} + +void NativeEmbed::gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const { + strata::kernels::iq_embed_rows(type_, dev_, row_, tokens, n_tok, n_embd_, out, stream); +} + +void NativeEmbed::gather_one(int64_t token, float* out, void* stream) const { + strata::kernels::iq_dequant_f32(type_, (const uint8_t*) dev_ + (size_t) token * row_, n_embd_, out, stream); +} + +} // namespace strata::core diff --git a/engine/strata/src/core/overlap_main.cpp b/engine/strata/src/core/overlap_main.cpp new file mode 100644 index 00000000..f5981c12 --- /dev/null +++ b/engine/strata/src/core/overlap_main.cpp @@ -0,0 +1,169 @@ +// src/core/overlap_main.cpp - `strata-overlap`: does streaming an expert overlap with computing on it? +// +// THE ARCHITECTURE'S CENTRAL PREMISE. Only (1 - h) of a token's expert weights are in VRAM, so the rest must +// cross the bus while the GPU is working. If the copy and the compute do not overlap, the per-token cost is +// their SUM; if they do, it is their MAXIMUM. L3 measured the stream at 4.07 ms/token (design h) and L5 the +// matvec at 27.9 ms/token, so serial would be ~32 ms and overlapped ~28 - but those are the STEADY-STATE +// numbers for a whole token; at one expert's granularity the ratio is completely different and that is what +// decides how the loop must be built. +// +// Measured against a SERIAL baseline in the same process, because the interesting quantity is the ratio and +// not the absolute figure - and L6 established that absolute figures on this machine move by 20%. +#include "strata/core/pinned.hpp" +#include "strata/kernels/s_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +struct Timing { + double seconds = 0; + const char* name = ""; +}; + +} // namespace + +int main(int argc, char** argv) { + std::string path; + int experts = 64; + int threads_per_row = 32; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto val = [&]() -> const char* { + if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + if (a == "--file") path = val(); + else if (a == "--experts") experts = std::atoi(val()); + else if (a == "--tpr") threads_per_row = std::atoi(val()); + else { + std::fprintf(stderr, "usage: strata-overlap --file experts.bin [--experts N] [--tpr N]\n"); + return 2; + } + } + if (path.empty()) { std::fprintf(stderr, "--file is required\n"); return 2; } + + // One ROLE's worth of S2 weights: gate is [n_embd 2560] x [ff 640] = 1,638,400 weights = 460,800 B of + // codes at 4 codes per byte, plus 40 scales per row. + const long long n_in = 2560, n_out = 640; + const uint64_t role_codes = (uint64_t) n_out * n_in / 4; + const uint64_t role_bytes = role_codes + (uint64_t) n_out * (n_in / 64) * 4; + std::printf("per role: %lld x %lld S2 weights, %.1f KB of planes\n", n_in, n_out, role_bytes / 1024.0); + + // host side: `experts` blobs read into a pinned arena, and the S2 planes the GEMV will read + strata::core::PinnedArena arena((uint64_t) experts * role_codes); + if (!arena.valid()) { std::fprintf(stderr, "arena allocation failed\n"); return 1; } + { + std::ifstream f(path, std::ios::binary); + if (!f) { std::fprintf(stderr, "cannot open %s\n", path.c_str()); return 1; } + // take the first `experts` blobs' worth of CODE bytes, pretending each is a role's plane: the bytes + // are real Q2_0 codes, so the kernel decodes real data and no cache-friendly pattern is invented + for (int i = 0; i < experts; ++i) { + f.seekg((std::streamoff) i * 1382400); + f.read((char*) arena.data() + (uint64_t) i * role_codes, (std::streamsize) role_codes); + if ((uint64_t) f.gcount() != role_codes) { + std::fprintf(stderr, "short read on expert %d\n", i); + return 1; + } + } + } + std::printf("loaded %d role-sized planes into a %s arena\n", experts, arena.note.c_str()); + + // device side: double buffered codes, plus x / scales / y + uint8_t* d_codes[2] = {nullptr, nullptr}; + for (int b = 0; b < 2; ++b) check(cudaMalloc(&d_codes[b], role_codes), "cudaMalloc codes"); + uint16_t* d_x = nullptr; + float *d_scales = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, n_in * sizeof(uint16_t)), "cudaMalloc x"); + check(cudaMalloc(&d_scales, (size_t) n_out * (n_in / 64) * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_y, n_out * sizeof(float)), "cudaMalloc y"); + std::vector hx((size_t) n_in, 0x3C00); + std::vector hs((size_t) n_out * (size_t) (n_in / 64), 0.001f); + check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_scales, hs.data(), hs.size() * sizeof(float), cudaMemcpyHostToDevice), "copy scales"); + + cudaStream_t s_copy{}, s_comp{}; + check(cudaStreamCreate(&s_copy), "stream copy"); + check(cudaStreamCreate(&s_comp), "stream compute"); + const strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; + + // ---- SERIAL: the same operations on the SAME stream, so the GPU runs them one after another ---- + // + // NOT a sync-per-iteration loop. The first version waited with `cudaStreamSynchronize` after every copy and + // measured 234.8 us/expert where a copy plus a GEMV is ~43 us: the baseline was dominated by the CPU + // round-trip, so the ratio of 0.095 mostly measured "with syncs" against "without syncs". Putting both + // operations on one stream expresses the same dependency with NO CPU involvement and ONE sync at the end, + // which is what makes the comparison about overlap rather than about synchronisation. + check(cudaStreamSynchronize(0), "pre sync"); + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < experts; ++i) { + check(cudaMemcpyAsync(d_codes[0], arena.data() + (uint64_t) i * role_codes, role_codes, + cudaMemcpyHostToDevice, 0), + "serial copy"); + strata::kernels::s_gemv_split_async(d_x, d_codes[0], d_scales, nullptr, d_y, n_in, n_out, form, + threads_per_row, (void*) (cudaStream_t) 0); + } + check(cudaStreamSynchronize(0), "serial final sync"); + const double serial = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + + // ---- OVERLAPPED: copy the next one while computing on the current one ---- + check(cudaStreamSynchronize(0), "pre sync 2"); + cudaEvent_t ev[2]; + for (int b = 0; b < 2; ++b) check(cudaEventCreateWithFlags(&ev[b], cudaEventDisableTiming), "event"); + t0 = std::chrono::steady_clock::now(); + check(cudaMemcpyAsync(d_codes[0], arena.data(), role_codes, cudaMemcpyHostToDevice, s_copy), "prologue"); + check(cudaEventRecord(ev[0], s_copy), "prologue event"); + for (int i = 0; i < experts; ++i) { + const int cur = i & 1, nxt = (i + 1) & 1; + if (i + 1 < experts) { + check(cudaMemcpyAsync(d_codes[nxt], arena.data() + (uint64_t) (i + 1) * role_codes, role_codes, + cudaMemcpyHostToDevice, s_copy), + "overlap copy"); + check(cudaEventRecord(ev[nxt], s_copy), "overlap event"); + } + // the compute stream must not start row i until its codes have landed + check(cudaStreamWaitEvent(s_comp, ev[cur], 0), "wait"); + // a hand-written launch so it goes on s_comp; `s_gemv` synchronises on the default stream + strata::kernels::s_gemv_split_async(d_x, d_codes[cur], d_scales, nullptr, d_y, n_in, n_out, form, + threads_per_row, (void*) s_comp); + } + check(cudaStreamSynchronize(s_comp), "final sync"); + check(cudaStreamSynchronize(s_copy), "final sync 2"); + const double overlap = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + + std::printf("\n serial %8.3f ms for %d experts (%.1f us/expert)\n", serial * 1000, experts, + serial * 1e6 / experts); + std::printf(" overlapped %8.3f ms for %d experts (%.1f us/expert)\n", overlap * 1000, experts, + overlap * 1e6 / experts); + std::printf(" ratio %.3f (1.00 = no overlap at all, <1.00 = overlap)\n", overlap / serial); + std::printf("\nNOTE: the OVERLAPPED loop launches on `s_comp` without synchronising, so the copy and the\n" + " compute really are concurrent; the serial loop waits after each step. What this does NOT\n" + " model is the CPU expert path, the router, or the fact that a real token has 1440 roles to\n" + " stream rather than %d.\n", experts); + + for (int b = 0; b < 2; ++b) { + cudaFree(d_codes[b]); + cudaEventDestroy(ev[b]); + } + cudaFree(d_x); + cudaFree(d_scales); + cudaFree(d_y); + cudaStreamDestroy(s_copy); + cudaStreamDestroy(s_comp); + return 0; +} diff --git a/engine/strata/src/core/pinned.cu b/engine/strata/src/core/pinned.cu new file mode 100644 index 00000000..64ffe013 --- /dev/null +++ b/engine/strata/src/core/pinned.cu @@ -0,0 +1,549 @@ +// src/core/pinned.cu - P2.S1: the pinned host arena and the parallel expert load. +#include "strata/core/pinned.hpp" +#include "strata/platform/memory.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// Loader fix: `fseek`/`ftell` are 32-bit on Windows by default (and the pack is 42.9 GB), and the 64-bit +// spelling is not the same on the two platforms the engine builds for. +#ifdef _WIN32 +#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET) +#else +#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET) +#endif + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#include +#ifndef MAP_HUGE_2MB +#define MAP_HUGE_2MB (21 << 26) +#endif +#endif + +namespace strata::core { + +namespace { + +constexpr uint64_t kSharedArenaHeaderBytes = 4096; +constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1"; + +struct SharedArenaHeader { + char magic[16]; + uint32_t version; + uint32_t header_bytes; + uint64_t arena_bytes; + uint64_t pack_hash; + uint64_t reserved[4]; +}; +static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes); + +// A 2 MB-aligned reservation. Large pages first, then the largest alignment the OS will give us for free. +// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes +// are the resident arena. This shared-file layout is intended for tmpfs (/dev/shm); hugetlbfs would need +// hugepage-aligned file size and arena offset rather than the 4 KiB header layout used here. +void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file, + uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) { + mapping_base = nullptr; + mapping_bytes = 0; +#ifdef _WIN32 + if (!shared_file.empty()) { + note = "shared-file arena backing is not implemented on Windows"; + return nullptr; + } + // MEM_LARGE_PAGES needs SeLockMemoryPrivilege. Having it assigned to the account is not enough: the + // PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails. + // An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc + // then refuses and the 4 KB fallback below runs - that is the EXPECTED outcome on a desktop. + { + HANDLE tok = nullptr; + if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) { + TOKEN_PRIVILEGES tp{}; + tp.PrivilegeCount = 1; + if (LookupPrivilegeValueW(nullptr, L"SeLockMemoryPrivilege", &tp.Privileges[0].Luid)) { + tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + if (!AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr) && GetLastError() != ERROR_NOT_ALL_ASSIGNED) + (void) 0; // nothing actionable: the large-page attempt below reports the outcome + } + CloseHandle(tok); + } + } + // MEM_LARGE_PAGES needs SeLockMemoryPrivilege; a normal account does not have it and VirtualAlloc then + // fails with ERROR_PRIVILEGE_NOT_HELD. That is the EXPECTED outcome on a desktop, not an error. + SIZE_T large = GetLargePageMinimum(); + // A/B switch: STRATA_NO_LARGEPAGES=1 skips the large-page attempt, same run, same boot. + if (large > 0 && std::getenv("STRATA_NO_LARGEPAGES") == nullptr) { + // MEM_LARGE_PAGES requires the allocation size to be an exact multiple of the large page size - + // anything else is ERROR_INVALID_PARAMETER (87), which reads like a privilege problem but is not. + // Round up: the slack is under 2 MB and the tail stays unused. + const SIZE_T lbytes = (SIZE_T) (((SIZE_T) bytes + large - 1) / large * large); + void* p = VirtualAlloc(nullptr, lbytes, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, + PAGE_READWRITE); + if (p) { + got = PageBacking::LargePages; + note = "large pages (" + std::to_string((unsigned long long) large) + " B)"; + return p; + } + // 1450 (ERROR_NO_SYSTEM_RESOURCES) is the large-page pool saying no, 87 is a size that is not a + // multiple of the minimum, 1314 is the privilege: without the byte count the three read as one bug. + note = "large pages refused for " + std::to_string((unsigned long long) lbytes) + " B (GetLargePageMinimum=" + + std::to_string((unsigned long long) large) + ", VirtualAlloc error " + + std::to_string((unsigned long long) GetLastError()) + "); using 4 KB pages"; + } else if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) { + note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages"; + } else { + note = "this system has no large-page minimum; using 4 KB pages"; + } + void* p = VirtualAlloc(nullptr, (SIZE_T) bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + got = PageBacking::NormalPages; + return p; +#else + if (!shared_file.empty()) { + if (shared_pack_hash == 0) { + note = "shared arena requires a nonzero pack hash"; + return nullptr; + } + if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) { + note = "shared arena size overflows its header"; + return nullptr; + } + const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes; + const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600); + if (fd < 0) { + note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno); + return nullptr; + } + struct stat st{}; + if (fstat(fd, &st) != 0) { + const int e = errno; + close(fd); + note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + + const bool fresh = st.st_size == 0; + if (fresh) { + if (ftruncate(fd, (off_t) file_bytes) != 0) { + const int e = errno; + close(fd); + note = "cannot size shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + SharedArenaHeader hdr{}; + std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic); + hdr.version = 1; + hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes; + hdr.arena_bytes = bytes; + hdr.pack_hash = shared_pack_hash; + const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0); + if (written != (ssize_t) sizeof hdr) { + const int e = errno; + close(fd); + note = "cannot write shared arena header " + shared_file + ": " + + (written < 0 ? std::string(std::strerror(e)) : std::string("short write")); + return nullptr; + } + } else { + if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) { + close(fd); + note = "shared arena " + shared_file + " is " + + std::to_string((unsigned long long) st.st_size) + " B, expected " + + std::to_string((unsigned long long) file_bytes) + " B including its header"; + return nullptr; + } + SharedArenaHeader hdr{}; + const ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0); + if (got_header != (ssize_t) sizeof hdr || + std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 || + hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) { + close(fd); + note = "shared arena " + shared_file + " has an incompatible or missing header"; + return nullptr; + } + if (hdr.pack_hash != shared_pack_hash) { + close(fd); + char b[256]; + std::snprintf(b, sizeof b, + "shared arena %s was written for pack hash %016llx, expected %016llx", + shared_file.c_str(), (unsigned long long) hdr.pack_hash, + (unsigned long long) shared_pack_hash); + note = b; + return nullptr; + } + } + + void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + const int e = errno; + close(fd); + if (map == MAP_FAILED) { + note = "cannot map shared arena " + shared_file + ": " + std::strerror(e); + return nullptr; + } + mapping_base = map; + mapping_bytes = file_bytes; + got = PageBacking::NormalPages; + note = "MAP_SHARED file " + shared_file + " (pack hash checked)"; + return (uint8_t*) map + kSharedArenaHeaderBytes; + } + + void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0); + if (p != MAP_FAILED) { + got = PageBacking::LargePages; + note = "hugetlb 2 MB pages"; + return p; + } + note = "MAP_HUGETLB unavailable (no hugetlb pool configured?); using 4 KB pages"; + p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + got = PageBacking::NormalPages; + return p == MAP_FAILED ? nullptr : p; +#endif +} + +void release(void* p, uint64_t bytes) { + if (!p) return; +#ifdef _WIN32 + (void) bytes; + VirtualFree(p, 0, MEM_RELEASE); +#else + munmap(p, bytes); +#endif +} + +} // namespace + +uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed) { + uint64_t h = seed; + for (uint64_t i = 0; i < n; ++i) { + h ^= p[i]; + h *= 1099511628211ull; + } + return h; +} + +namespace { +bool clear_error() { (void) cudaGetLastError(); return true; } +} // namespace + +int arena_pin_cap_gib() { + const char* e = std::getenv("STRATA_ARENA_PIN_GIB"); + if (e == nullptr || *e == '\0') return -1; + if (std::string(e) == "auto") return -2; // #243: the Windows shared-memory budget sets the sliced pin's cap + const int v = std::atoi(e); + return v < 0 ? -1 : v; +} + +namespace { +#ifdef _WIN32 +// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused. +// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until +// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed +// "out of memory". 4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI +// numbers, RAM/2 - 8 GiB (the budget is about half the RAM). False: no limit could be worked out. +bool sliced_pin_limit(uint64_t& limit, std::string& why) { + constexpr uint64_t GiB = 1ull << 30; + char buf[256]; + int dev = 0; + cudaDeviceProp p{}; + uint64_t budget = 0, usage = 0; + std::string err = "no CUDA device properties"; + if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess && + strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) { + limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0; + std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB", + (double) budget / GiB, (double) usage / GiB); + why = buf; + return true; + } + (void) cudaGetLastError(); + const uint64_t ram = strata::platform::total_physical_memory(); + if (ram == 0) return false; + limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0; + std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB); + why = buf; + return true; +} +#endif +} // namespace + +namespace { +std::vector uniform_bounds(uint64_t bytes, uint64_t slice) { + std::vector b; + if (slice == 0) return b; + for (uint64_t off = 0; off + slice <= bytes; off += slice) b.push_back(off); + if (!b.empty()) b.push_back(b.back() + slice); + return b; +} +} // namespace + +PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, uniform_bounds(bytes, slice)) { + if (slice_bytes) slice_bytes = slice; // sliced registration: record the uniform size +} + +PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, + uint64_t max_pinned_bytes, const std::string& shared_file, + uint64_t shared_pack_hash) : capacity(bytes) { + if (bytes == 0) return; + base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes); + if (base != nullptr && mapping_base == nullptr) { + mapping_base = base; + mapping_bytes = bytes; + } + + // Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region + // that has already been faulted in page by page is far more expensive to register and may fail outright. + if (base) { + // #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap + const int env_gib = arena_pin_cap_gib(); + uint64_t cap = max_pinned_bytes; + std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)"; + if (cap == 0 && env_gib > 0) { + cap = (uint64_t) env_gib << 30; + cap_why = "by STRATA_ARENA_PIN_GIB"; + } + const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2; + const cudaError_t e = capped ? cudaSuccess : + cudaHostRegister(base, (size_t) bytes, cudaHostRegisterPortable | cudaHostRegisterMapped); + if (!capped && e == cudaSuccess) { + note = "cudaHostRegister PORTABLE ok; " + note; + registered_bytes = bytes; + } else if (bounds.size() >= 2 && (capped || clear_error())) { + // Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays + // resident through the working-set lock below. (P6: slices may differ in size, one per layer.) + slice_bytes = 1; // sliced; the uniform constructor records the size + bool limited = capped; + uint64_t limit = cap; + std::string limit_why; +#ifdef _WIN32 + // #243 (opt-in, STRATA_ARENA_PIN_GIB=auto): not up to the driver's refusal but below the shared-memory + // budget, for a PC where the full sliced pin leaves WDDM refusing later allocations. Not the default: a + // 64 GB PC pins 30 GiB past that budget without trouble, and capping it at 26 cost ~20% prompt speed. + if (!capped && env_gib == -2) limited = sliced_pin_limit(limit, limit_why); +#endif + for (size_t i = 0; i + 1 < bounds.size(); ++i) { + const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i]; + if (limited && (off > limit || n > limit - off)) break; + if (cudaHostRegister((uint8_t*) base + off, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) { + (void) cudaGetLastError(); + break; + } + slice_starts.push_back(off); + registered_bytes = off + n; + ++registered_slices; + } + char gib[32]; + std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30)); + note = (capped ? "cudaHostRegister limited to " + std::to_string(cap >> 30) + " GiB " + cap_why + "; " : + "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); " + + (limited ? "slices capped at " + std::string(gib) + " GiB (" + limit_why + + "; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); " : std::string())) + + std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) + + " GiB); " + note; + if (registered_bytes < bytes) { + const char* env = std::getenv("STRATA_ARENA_LOCK"); + if (env == nullptr || std::string(env) != "0") { + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes); + locked_bytes = lr.locked_bytes; + note = lr.note + "; " + note; + } + } + } else { + note = std::string("cudaHostRegister FAILED (") + cudaGetErrorString(e) + + ") - the arena is NOT pinned, so copies will be slow; " + note; + // **CONSUME THE ERROR, OR IT LIES ABOUT SOMETHING ELSE LATER.** + // + // `cudaGetLastError()` returns the last error and CLEARS it; until something reads it, the error + // state is sticky. This failure is caught and handled right here - the arena is simply not pinned - + // but leaving it set meant the next `cudaGetLastError()` in the engine, which is `gr_read`'s launch + // check, reported "out of memory" for kernels that allocate nothing. That cost a round: the arena + // was written off as not fitting the machine when in fact the only thing wrong was a stale error + // from this line. + // + // It is the same trap `gr.cu` warns about for ASYNC faults, in the other direction: a synchronous + // failure is sticky too, and it lies about where it happened just as convincingly. + (void) cudaGetLastError(); + // Plan v0.3 P0.1: keep it RESIDENT instead. Unpinned, Windows trims the arena under memory pressure + // and the CPU pool's rate then depends on the OS; locking it through the working set needs no + // special privilege. STRATA_ARENA_LOCK=0 is the A/B arm. + const char* env = std::getenv("STRATA_ARENA_LOCK"); + if (env == nullptr || std::string(env) != "0") { + const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes); + locked_bytes = lr.locked_bytes; + note = lr.note + "; " + note; + } else { + note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note; + } + } + } +} + +PinnedArena::~PinnedArena() { + if (base) { + if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes); + if (slice_bytes) { + for (uint64_t off : slice_starts) cudaHostUnregister((uint8_t*) base + off); + } else { + cudaHostUnregister(base); + } + release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity); + base = nullptr; + mapping_base = nullptr; + mapping_bytes = 0; + } +} + +LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer, + uint64_t layers, int threads, uint64_t chunk) { + std::vector off((size_t) layers), n((size_t) layers, blobs_per_layer * blob_bytes); + for (uint64_t L = 0; L < layers; ++L) off[(size_t) L] = L * blobs_per_layer * blob_bytes; + return load_experts_ranges(path, dst, off, n, threads, chunk); +} + +LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector& layer_off, + const std::vector& layer_bytes, int threads, uint64_t chunk) { + LoadStats st; + const uint64_t layers = (uint64_t) layer_off.size(); + st.layers = layers; + st.bytes = 0; + for (uint64_t b : layer_bytes) st.bytes += b; + if (threads < 1) threads = 1; + + const auto t0 = std::chrono::steady_clock::now(); + std::vector layer_hash((size_t) layers, 1469598103934665603ull); + std::atomic next_layer{0}; + std::atomic read_ns_sum{0}; // summed over the threads: see LoadStats::read_seconds + std::atomic copy_ns_sum{0}; + std::mutex err_mu; + std::string err; + + auto worker = [&]() { + std::vector buf((size_t) chunk); + // One handle per thread, seeked once per layer: a shared handle would need a lock around the seek and + // would serialise the very thing the threads are here to parallelise. `fread` on a `FILE*` rather than + // `std::ifstream`: see the header - MSVC's `basic_filebuf::xsgetn` splits any request larger than + // `_INTERNAL_BUFSIZ - 1` into 4095-byte freads, which turned one 8 MiB chunk into ~2048 4 KiB reads. + // `fread` sees a request bigger than the stream buffer and passes it to `_read()`/ + // `ReadFile()` unchanged, so the chunk size reaches the disk. Buffered, not `FILE_FLAG_NO_BUFFERING`: + // the cache should still hold what it can. + FILE* f = std::fopen(path.c_str(), "rb"); + if (f == nullptr) { + std::lock_guard g(err_mu); + err = "cannot open " + path; + return; + } + // A `FILE*` has no destructor that closes it, and this function has early returns below (open, seek and + // short-read failures), so the guard is what keeps the closing correct on every path. + struct Closer { + FILE* f; + ~Closer() { if (f != nullptr) std::fclose(f); } + } closer{f}; + uint64_t read_ns = 0, copy_ns = 0; + for (;;) { + const uint64_t L = next_layer.fetch_add(1); + if (L >= layers) break; + const uint64_t off = layer_off[(size_t) L]; + uint64_t remaining = layer_bytes[(size_t) L]; + uint64_t pos = 0; + uint64_t h = 1469598103934665603ull; + // 64-bit seek: the pack is 42.9 GB, so the 32-bit `fseek` would wrap past 4 GiB + if (STRATA_FSEEK64(f, off) != 0) { + std::lock_guard g(err_mu); + err = "seek to " + std::to_string(off) + " B failed in layer " + std::to_string(L); + return; + } + while (remaining > 0) { + const uint64_t n = remaining < chunk ? remaining : chunk; + const auto t_read = std::chrono::steady_clock::now(); + const size_t got = std::fread(buf.data(), 1, (size_t) n, f); + read_ns += (uint64_t) std::chrono::duration_cast( + std::chrono::steady_clock::now() - t_read).count(); + // A short read is EOF or an I/O error, never a silent zero fill: say WHERE and HOW SHORT, and + // keep going no further - the caller turns this into a refused load, not a wrong answer. + if (got != (size_t) n) { + std::lock_guard g(err_mu); + err = "short read in layer " + std::to_string(L) + ": got " + std::to_string(got) + " of " + + std::to_string(n) + " B at offset " + std::to_string(off + pos) + + (std::ferror(f) != 0 ? " (ferror set)" : ""); + return; + } + const auto t_copy = std::chrono::steady_clock::now(); + std::memcpy(dst + off + pos, buf.data(), (size_t) n); + h = fnv1a64(buf.data(), n, h); + copy_ns += (uint64_t) std::chrono::duration_cast( + std::chrono::steady_clock::now() - t_copy).count(); + pos += n; + remaining -= n; + } + layer_hash[(size_t) L] = h; + } + read_ns_sum.fetch_add(read_ns); + copy_ns_sum.fetch_add(copy_ns); + }; + + std::vector pool; + for (int i = 1; i < threads; ++i) pool.emplace_back(worker); + worker(); + for (auto& t : pool) t.join(); + + if (!err.empty()) { + std::fprintf(stderr, "load_experts: %s\n", err.c_str()); + st.seconds = -1.0; + st.ok = false; + st.error = err; + return st; + } + st.read_seconds = (double) read_ns_sum.load() / 1e9; + st.copy_seconds = (double) copy_ns_sum.load() / 1e9; + st.layer_checksums = std::move(layer_hash); + st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + return st; +} + +StreamStats stream_bandwidth(const uint8_t* src, uint64_t bytes, uint64_t chunk, int iters) { + StreamStats st; + st.bytes = bytes * (uint64_t) iters; + st.chunk = chunk; + uint8_t* dst = nullptr; + cudaStream_t s{}; + if (cudaMalloc(&dst, (size_t) chunk) != cudaSuccess) { + std::fprintf(stderr, "stream_bandwidth: cudaMalloc failed for %llu B\n", (unsigned long long) chunk); + st.seconds = -1.0; + return st; + } + cudaStreamCreate(&s); + + // one untimed pass so the first transfer's page-fault and setup cost is not in the measurement + for (uint64_t off = 0; off + chunk <= bytes; off += chunk) { + cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s); + } + cudaStreamSynchronize(s); + + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) { + for (uint64_t off = 0; off + chunk <= bytes; off += chunk) { + cudaMemcpyAsync(dst, src + off, (size_t) chunk, cudaMemcpyHostToDevice, s); + } + } + cudaStreamSynchronize(s); + st.seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + + cudaStreamDestroy(s); + cudaFree(dst); + return st; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/pinned_shared_test.cpp b/engine/strata/src/core/pinned_shared_test.cpp new file mode 100644 index 00000000..c663f1a0 --- /dev/null +++ b/engine/strata/src/core/pinned_shared_test.cpp @@ -0,0 +1,61 @@ +// Linux selftest for the optional MAP_SHARED backing of PinnedArena. +#include "strata/core/pinned.hpp" + +#include +#include +#include +#include + +#include + +int main() { + char path[] = "/tmp/strata-shared-arena-XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) { + std::perror("mkstemp"); + return 2; + } + close(fd); + + int fail = 0; + const uint64_t bytes = 64u << 10; + const uint64_t pack_hash = 0x0123456789abcdefull; + const std::vector no_bounds; + { + strata::core::PinnedArena first(bytes, no_bounds, 0, path, pack_hash); + if (!first.valid()) { + std::fprintf(stderr, "first shared arena failed: %s\n", first.note.c_str()); + fail = 1; + } else { + first.data()[123] = 0x5a; + + strata::core::PinnedArena second(bytes, no_bounds, 0, path, pack_hash); + if (!second.valid()) { + std::fprintf(stderr, "second shared arena failed: %s\n", second.note.c_str()); + fail = 1; + } else if (second.data()[123] != 0x5a) { + std::fprintf(stderr, "shared mapping did not expose the same bytes\n"); + fail = 1; + } + + strata::core::PinnedArena wrong_pack(bytes, no_bounds, 0, path, pack_hash + 1); + if (wrong_pack.valid() || wrong_pack.note.find("pack hash") == std::string::npos) { + std::fprintf(stderr, "pack mismatch was not refused: %s\n", wrong_pack.note.c_str()); + fail = 1; + } + + strata::core::PinnedArena wrong_size(bytes * 2, no_bounds, 0, path, pack_hash); + if (wrong_size.valid() || wrong_size.note.find("expected") == std::string::npos) { + std::fprintf(stderr, "size mismatch was not refused: %s\n", wrong_size.note.c_str()); + fail = 1; + } + } + } + + if (unlink(path) != 0) { + std::perror("unlink"); + fail = 1; + } + std::printf("pinned_shared_test: %s\n", fail ? "FAILED" : "OK"); + return fail; +} diff --git a/engine/strata/src/core/remote_experts.cpp b/engine/strata/src/core/remote_experts.cpp new file mode 100644 index 00000000..53d8d764 --- /dev/null +++ b/engine/strata/src/core/remote_experts.cpp @@ -0,0 +1,328 @@ +#include "strata/core/remote_experts.hpp" + +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" + +#include +#include +#include +#include + +namespace strata::core { +namespace { +constexpr int64_t H = strata::kernels::cpu::H; +constexpr int64_t FF = strata::kernels::cpu::FF; +constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10; + +// Small enough to copy as one pinned buffer per layer. The kernels read the +// individual arrays through pointers into the same device allocation. +struct RemoteMeta { + unsigned long long ptr[CAP]; + int32_t start[CAP + 1]; + int32_t dst[CAP]; + int32_t tok[CAP]; + int32_t count; +}; + +struct DeviceScope { + int previous = -1; + bool ok = false; + cudaError_t status = cudaSuccess; + const char* failed_step = nullptr; + explicit DeviceScope(int device) { + status = cudaGetDevice(&previous); + if (status != cudaSuccess) { + previous = -1; + failed_step = "cudaGetDevice"; + return; + } + status = cudaSetDevice(device); + if (status != cudaSuccess) { + failed_step = "cudaSetDevice"; + return; + } + ok = true; + } + ~DeviceScope() { if (previous >= 0) cudaSetDevice(previous); } + std::string error(int device) const { + return std::string("CUDA") + std::to_string(device) + " experts: " + + (failed_step ? failed_step : "device switch") + + "(" + std::to_string(device) + ") failed: " + cudaGetErrorString(status) + + " (CUDA error " + std::to_string((int) status) + ")"; + } +}; + +bool check(cudaError_t result, const char* what, std::string& err, int device) { + if (result == cudaSuccess) return true; + err = "CUDA" + std::to_string(device) + " experts: " + what + ": " + cudaGetErrorString(result); + return false; +} +} // namespace + +RemoteExperts::~RemoteExperts() { close(); } + +bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) { + int count = 0; + if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; + if (device < 1 || device >= count) { + err = "CUDA" + std::to_string(device) + " experts: CUDA device is not visible"; + return false; + } + // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up + // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible + // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. +#if !defined(STRATA_USE_HIP) + const char* spin = std::getenv("STRATA_REMOTE_SPIN"); + if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0); + cudaGetLastError(); +#endif + // HIP has no cudaInitDevice equivalent; retain its default scheduling policy. + DeviceScope scope(device); + if (!scope.ok) { err = scope.error(device); return false; } + size_t free_bytes = 0, total_bytes = 0; + if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "preflight free memory", err, device)) return false; + free_gib = (double) free_bytes / 1073741824.0; + return true; +} + +void RemoteExperts::close() { + if (device_ < 0) return; + DeviceScope scope(device_); + if (scope.ok) { + if (stream_) cudaStreamSynchronize(stream_); + cache_.close(); + if (d_x_) cudaFree(d_x_); + if (d_out_) cudaFree(d_out_); + if (d_q8_) cudaFree(d_q8_); + if (d_scales_) cudaFree(d_scales_); + if (d_scratch_) cudaFree(d_scratch_); + if (d_meta_) cudaFree(d_meta_); + if (h_x_) cudaFreeHost(h_x_); + if (h_out_) cudaFreeHost(h_out_); + if (h_meta_) cudaFreeHost(h_meta_); + if (stream_) cudaStreamDestroy(stream_); + } + device_ = -1; + stream_ = nullptr; + h_x_ = h_out_ = d_x_ = d_out_ = nullptr; + h_meta_ = d_meta_ = nullptr; + d_q8_ = nullptr; + d_scales_ = nullptr; + d_scratch_ = nullptr; + d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr; + d_ptr_ = nullptr; + original_row_.clear(); + layers_present_.clear(); +} + +bool RemoteExperts::open(int device, int slots, int64_t layers, int64_t experts, + const std::vector>& ranked, + const ExpertCache& primary, ExpertSource& source, + std::vector& claimed, std::string& err) { + close(); + int count = 0; + if (!check(cudaGetDeviceCount(&count), "cudaGetDeviceCount", err, device)) return false; + if (device < 1 || device >= count || slots <= 0 || ranked.empty() || + layers <= 0 || experts <= 0 || claimed.size() != (size_t) layers * (size_t) experts) { + err = "CUDA" + std::to_string(device) + " experts: need the device, ranked experts and positive slot count"; + return false; + } + DeviceScope scope(device); + if (!scope.ok) { err = scope.error(device); return false; } + device_ = device; + n_expert_ = experts; + const auto& lay = strata::kernels::cpu::expert_layout(); + std::vector> selected; + selected.reserve((size_t) slots); + std::vector picked(claimed.size(), 0); + for (const auto& pair : ranked) { + if (pair.first < 0 || pair.first >= layers || pair.second < 0 || pair.second >= experts) continue; + const size_t index = (size_t) pair.first * (size_t) experts + (size_t) pair.second; + if (primary.slot_of(pair.first, pair.second) < 0 && !claimed[index] && !picked[index]) { + selected.push_back(pair); + picked[index] = 1; + if ((int) selected.size() >= slots) break; + } + } + if (selected.empty()) { err = "CUDA" + std::to_string(device) + " experts: no unclaimed experts remain"; close(); return false; } + std::vector sizes; + if (lay.native) { + sizes.reserve(selected.size()); + for (const auto& pair : selected) sizes.push_back((int64_t) lay.blob_bytes(pair.first)); + } + size_t free_bytes = 0, total_bytes = 0; + if (!check(cudaMemGetInfo(&free_bytes, &total_bytes), "free memory", err, device)) { close(); return false; } + uint64_t needed = 0; + for (const auto& pair : selected) + needed += lay.native ? (lay.blob_bytes(pair.first) + 255) / 256 * 256 : lay.max_blob; + // Leave room for the CUDA context, staging and later driver allocations, especially under WDDM. + if (needed + (512ull << 20) > free_bytes) { + err = "CUDA" + std::to_string(device) + " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string(device); + close(); return false; + } + const bool cache_ok = lay.native ? cache_.open_sized(sizes, layers, experts, err) + : cache_.open((int64_t) selected.size(), layers, experts, + (int64_t) lay.max_blob, err); + if (!cache_ok) { err = "CUDA" + std::to_string(device) + " experts: " + err; close(); return false; } + for (const auto& pair : selected) { + const int32_t slot = cache_.admit(pair.first, pair.second); + const uint8_t* blob = source.blob(pair.first, pair.second); + if (slot < 0 || !blob || !cache_.fill_slot_blocking(slot, blob, err, (int64_t) lay.blob_bytes(pair.first))) { + err = "CUDA" + std::to_string(device) + " experts: " + + (err.empty() ? "cache fill failed" : err); + close(); return false; + } + } + const auto& first = selected.front(); + if (!cache_.verify_slot(cache_.slot_of(first.first, first.second), source.blob(first.first, first.second), + err, (int64_t) lay.blob_bytes(first.first))) { + err = "CUDA" + std::to_string(device) + " experts: " + err; + close(); return false; + } + + const size_t scratch = std::max( + (size_t) strata::kernels::moe_hit_grouped_scratch_bytes(CAP, H, FF), + strata::kernels::native_expert_scratch_bytes(CAP, FF)); + const bool allocated = + check(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking), "stream", err, device) && + check(cudaHostAlloc((void**) &h_x_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "input staging", err, device) && + check(cudaHostAlloc((void**) &h_out_, (size_t) CAP * H * sizeof(float), cudaHostAllocPortable | cudaHostAllocMapped), "result staging", err, device) && + check(cudaHostAlloc(&h_meta_, sizeof(RemoteMeta), cudaHostAllocPortable), "metadata staging", err, device) && + check(cudaMalloc((void**) &d_x_, (size_t) CAP * H * sizeof(float)), "input", err, device) && + check(cudaMalloc((void**) &d_out_, (size_t) CAP * H * sizeof(float)), "result", err, device) && + check(cudaMalloc((void**) &d_q8_, (size_t) CAP * (H / 32) * 36), "activation", err, device) && + check(cudaMalloc((void**) &d_scales_, (size_t) CAP * (H / 32) * sizeof(float)), "activation scales", err, device) && + check(cudaMalloc(&d_scratch_, scratch), "scratch", err, device) && + check(cudaMalloc(&d_meta_, sizeof(RemoteMeta)), "group metadata", err, device); + if (!allocated) { close(); return false; } + // Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers + // directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. + const char* zc = std::getenv("STRATA_REMOTE_ZEROCOPY"); + zero_copy_ = !(zc && zc[0] == '0') && + cudaHostGetDevicePointer((void**) &z_x_, h_x_, 0) == cudaSuccess && + cudaHostGetDevicePointer((void**) &z_out_, h_out_, 0) == cudaSuccess; + cudaGetLastError(); + auto* meta = (RemoteMeta*) d_meta_; + d_ptr_ = meta->ptr; + d_start_ = meta->start; + d_dst_ = meta->dst; + d_tok_ = meta->tok; + d_count_ = &meta->count; + owned_.resize(CAP); + layers_present_.assign((size_t) layers, 0); + group_of_.resize(CAP); + group_id_.reserve(CAP); + ptr_.reserve(CAP); + start_.reserve(CAP + 1); + dst_.reserve(CAP); + tok_.reserve(CAP); + original_row_.reserve(CAP); + computed_ = 0; + launched_layers_ = 0; + returned_bytes_ = full_row_bytes_ = 0; + for (const auto& pair : selected) { + layers_present_[(size_t) pair.first] = 1; + claimed[(size_t) pair.first * (size_t) experts + (size_t) pair.second] = 1; + } + return true; +} + +bool RemoteExperts::begin(int64_t layer, const float* x, const int32_t* ids, int64_t n_tok, + int64_t k, const int32_t* kind, const int32_t* primary_res, + std::string& err) { + // cumulative host time in here (staging and launches), reported per request by the driver + struct Timer { double& acc; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now(); + ~Timer() { acc += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); } } timer{ms_begin_}; + const int64_t n = n_tok * k; + if (n <= 0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != 10 || layer < 0 || + (size_t) layer >= layers_present_.size() || device_ < 0) { + err = "CUDA" + std::to_string(device_) + " experts: invalid layer, routing width or window size"; + return false; + } + std::fill(owned_.begin(), owned_.begin() + n, 0); + group_id_.clear(); ptr_.clear(); start_.clear(); dst_.clear(); tok_.clear(); original_row_.clear(); + if (!layers_present_[(size_t) layer]) return true; + std::fill(group_of_.begin(), group_of_.begin() + n, -1); + for (int64_t i = 0; i < n; ++i) { + const int32_t e = ids[i]; + if ((kind && kind[i] != -1) || e < 0 || e >= n_expert_ || + (primary_res && primary_res[(size_t) layer * (size_t) n_expert_ + (size_t) e] >= 0)) continue; + const int32_t slot = cache_.slot_of(layer, e); + if (slot < 0) continue; + owned_[(size_t) i] = 1; + int32_t group = -1; + for (size_t g = 0; g < group_id_.size(); ++g) + if (group_id_[g] == e) { group = (int32_t) g; break; } + if (group < 0) { + group = (int32_t) group_id_.size(); + group_id_.push_back(e); + ptr_.push_back((unsigned long long) cache_.device_slot(slot)); + } + group_of_[(size_t) i] = group; + ++computed_; + } + if (group_id_.empty()) return true; + for (size_t g = 0; g < group_id_.size(); ++g) { + start_.push_back((int32_t) dst_.size()); + for (int64_t i = 0; i < n; ++i) if (group_of_[(size_t) i] == (int32_t) g) { + // The grouped kernels read the activation from `tok`, so their + // output row can instead be packed densely for the USB4 return. + original_row_.push_back((int32_t) i); + dst_.push_back((int32_t) dst_.size()); + tok_.push_back((int32_t) (i / k)); + } + } + start_.push_back((int32_t) dst_.size()); + // Private pinned buffers survive until this GPU has consumed them. The CPU + // pool can write other output rows without a cross-device race. + std::memcpy(h_x_, x, (size_t) n_tok * H * sizeof(float)); + auto* meta = (RemoteMeta*) h_meta_; + std::memcpy(meta->ptr, ptr_.data(), ptr_.size() * sizeof(ptr_[0])); + std::memcpy(meta->start, start_.data(), start_.size() * sizeof(start_[0])); + std::memcpy(meta->dst, dst_.data(), dst_.size() * sizeof(dst_[0])); + std::memcpy(meta->tok, tok_.data(), tok_.size() * sizeof(tok_[0])); + meta->count = (int32_t) group_id_.size(); + DeviceScope scope(device_); + if (!scope.ok) { err = scope.error(device_); return false; } + groups_ = (int32_t) group_id_.size(); + const cudaStream_t s = stream_; + const bool staged = + (zero_copy_ || check(cudaMemcpyAsync(d_x_, h_x_, (size_t) n_tok * H * sizeof(float), cudaMemcpyHostToDevice, s), "copy input", err, device_)) && + check(cudaMemcpyAsync(d_meta_, h_meta_, sizeof(RemoteMeta), cudaMemcpyHostToDevice, s), "copy group metadata", err, device_); + if (!staged) return false; + const auto& lay = strata::kernels::cpu::expert_layout(); + if (lay.native) { + strata::kernels::quantize_q8_1_rows(zero_copy_ ? z_x_ : d_x_, n_tok, H, d_q8_, s); + const auto& fmt = lay.fmt[(size_t) layer]; + auto L = strata::kernels::native_expert_layout(fmt.gu_type, fmt.d_type, fmt.n_embd, fmt.n_ff); + strata::kernels::native_expert_grouped(L, d_ptr_, d_start_, d_count_, d_dst_, d_tok_, + groups_, (int64_t) dst_.size(), d_q8_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s); + } else { + strata::kernels::quantize_q8_0_scaled(zero_copy_ ? z_x_ : d_x_, d_q8_, d_scales_, n_tok * H, s); + strata::kernels::moe_grouped_s2(d_ptr_, d_start_, d_count_, d_dst_, d_tok_, + groups_, (int64_t) dst_.size(), d_q8_, d_scales_, d_scratch_, zero_copy_ ? z_out_ : d_out_, s); + } + const uint64_t compact_bytes = (uint64_t) dst_.size() * H * sizeof(float); + if (!zero_copy_ && !check(cudaMemcpyAsync(h_out_, d_out_, (size_t) compact_bytes, cudaMemcpyDeviceToHost, s), + "copy results", err, device_)) return false; + ++launched_layers_; + returned_bytes_ += compact_bytes; + full_row_bytes_ += (uint64_t) n * H * sizeof(float); + return true; +} + +bool RemoteExperts::finish(float* out, std::string& err) { + if (group_id_.empty()) return true; + DeviceScope scope(device_); + if (!scope.ok) { err = scope.error(device_); return false; } + const auto w0 = std::chrono::steady_clock::now(); + if (!check(cudaStreamSynchronize(stream_), "finish", err, device_)) return false; + ms_wait_ += std::chrono::duration(std::chrono::steady_clock::now() - w0).count(); + for (size_t i = 0; i < original_row_.size(); ++i) + std::memcpy(out + (size_t) original_row_[i] * H, h_out_ + i * H, (size_t) H * sizeof(float)); + return true; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/session.cpp b/engine/strata/src/core/session.cpp new file mode 100644 index 00000000..14c61663 --- /dev/null +++ b/engine/strata/src/core/session.cpp @@ -0,0 +1,970 @@ +// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. +#include "strata/core/session.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/core/progress.hpp" + +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/cpu/pool.hpp" +#include "strata/kernels/ngram.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +// `_mm_pause` for the doorbell spin. Guarded because it is x86-only; a target without it still builds, the +// spin is just less polite to the pipeline. +#if defined(_MSC_VER) || defined(__x86_64__) || defined(__i386__) +#include +#define STRATA_SPIN_PAUSE() _mm_pause() +#else +#define STRATA_SPIN_PAUSE() ((void) 0) +#endif + +namespace strata::core { +namespace { + +constexpr uint64_t SESSION_STATE_ALIGN = 256; + +uint64_t align_up(uint64_t n, uint64_t a) { return (n + a - 1) / a * a; } + +/// The floats one GDN layer's recurrent + conv state needs. `gdn_buffers_bytes` carves them for ONE layer and +/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one +/// its own - they cannot share, because the recurrence is the whole point. +uint64_t gdn_state_floats(const ModelGeometry& g) { + return (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); +} + +} // namespace + +/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the +/// session arena. The table and the weights are model-level and the caller owns them. +static uint64_t ple_hist_bytes() { + return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float); +} + +uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) { + if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; + if (layer_lo < 0) layer_lo = 0; + // QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound` + const int64_t I = std::max(g.qsa_interval, 1); + const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I; + const int64_t q_n = std::max(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0); + const int64_t gdn_n = std::max((layer_hi - layer_lo) - std::max(q_hi - q_lo, 0), 0); + uint64_t n = 0; + n += gdn_buffers_bytes(g); + n += (uint64_t) gdn_n * gdn_state_floats(g) * 4; + // One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K). + if (g.n_qsa_layers() > 0) + n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (q_n - 1) * qsa_state_bytes(g, max_cells, false); + n += qsa_buffers_bytes(g, max_cells); + n += moe_buffers_bytes(g, k); + n += block_buffers_bytes(g); + n += ple_hist_bytes(); // the PLE's NG_HIST normalized history rows + return align_up(n, SESSION_STATE_ALIGN) + 4096; +} + +uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s, + int64_t layer_lo, int64_t layer_hi) { + if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; + if (layer_lo < 0) layer_lo = 0; + uint8_t* p = (uint8_t*) base; + uint64_t used = 0; + auto take = [&](uint64_t bytes) { + uint8_t* r = p + used; + used = align_up(used + bytes, SESSION_STATE_ALIGN); + return r; + }; + + s.max_cells = max_cells; + s.k = k; + s.layer_lo = layer_lo; + s.layer_hi = layer_hi; + const int64_t I = std::max(g.qsa_interval, 1); + const int64_t q_n_range = layer_hi / I - layer_lo / I; + s.qsa_ord0 = layer_lo / I; + s.qsa_alloc = std::max(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0); + s.gdn_ord0 = layer_lo - layer_lo / I; + s.gdn_alloc = std::max((layer_hi - layer_lo) - q_n_range, 0); + + gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn); + s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4); + + // the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of + // pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the + // same way, which is a coupling with nothing to gain. Only the range's ordinals are initialized; the + // rest stay value-initialized nulls. The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0) + // owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow. + const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false); + s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0); + s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()](); + s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells)); + + uint8_t* qp = (uint8_t*) s.qsa_state_arena; + // a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the + // attention read null host pointers at the first request ("illegal memory access"), so the session fails here + for (int64_t j = 0; j < s.qsa_alloc; ++j) + if (qsa_state_init(g, max_cells, qp + (j == 0 ? 0 : first + (uint64_t) (j - 1) * rest), + s.qsa_states[s.qsa_ord0 + j], j == 0 ? nullptr : &s.qsa_states[s.qsa_ord0]) == 0) + return 0; + qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs); + + s.moe_arena = take(moe_buffers_bytes(g, k)); + moe_buffers_init(g, k, s.moe_arena, s.moe); + s.block_arena = take(block_buffers_bytes(g)); + block_buffers_init(g, s.block_arena, s.block); + // THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest. Sequence state, carved here and zeroed by + // `session_zero`; it survives every token, which is the whole point of a conv history. + s.ple_hist = (float*) take(ple_hist_bytes()); + s.R = s.block.R; + return used; +} + +void session_release(SessionState& s) { + for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j) + if (s.qsa_states[j].owns_rope) { + strata::kernels::rope_table_release(s.qsa_states[j].cos_tab); + s.qsa_states[j].owns_rope = false; + } +} + +void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) { + cudaStream_t cs = (cudaStream_t) stream; + // the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the + // embedding broadcast to every stream, which is the reference's own initial condition. + if (R_init != nullptr) { + for (int64_t c = 0; c < g.hc; ++c) + cudaMemcpyAsync(s.block.R + (size_t) c * g.n_embd, R_init, (size_t) g.n_embd * 4, + cudaMemcpyDeviceToDevice, cs); + } else { + cudaMemsetAsync(s.block.R, 0, (size_t) g.hc * g.n_embd * 4, cs); + } + // every owned GDN layer's recurrence and conv history + cudaMemsetAsync(s.gdn_state, 0, (size_t) s.gdn_alloc * gdn_state_floats(g) * 4, cs); + // and every owned QSA layer's cache and indexer + for (int64_t j = 0; j < s.qsa_alloc; ++j) qsa_state_zero(s.qsa_states[s.qsa_ord0 + j], g, stream); + // **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.** A sequence that started with a warm history would + // convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows, + // so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls + // for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence + // boundary IS. + cudaMemsetAsync(s.ple_hist, 0, (size_t) ple_hist_bytes(), cs); + s.ple_prev[0] = -1; + s.ple_prev[1] = -1; + s.ple_token = -1; +} + +/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own. Shared by +/// the direct and captured paths so the two cannot disagree about which slice a layer owns. +void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) { + if (is_qsa_layer(g, layer)) return; + int64_t gdn_index = 0; + for (int64_t l = 0; l < layer; ++l) if (!is_qsa_layer(g, l)) ++gdn_index; + s.gdn.state = s.gdn_state + (size_t) (gdn_index - s.gdn_ord0) * gdn_state_floats(g); + s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; +} + +/// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs +/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. +void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s) { + strata::kernels::QsaShapes sh = strata::kernels::qsa_real_shapes(); + sh.n_head = g.n_head; + sh.n_head_kv = g.n_head_kv; + sh.head_dim = g.head_dim; + sh.idx_n_head = g.idx_q_heads; + sh.idx_dim = g.idx_key_dim; + for (int64_t j = 0; j < s.qsa_alloc; ++j) { + QsaState& q = s.qsa_states[s.qsa_ord0 + j]; + qsa_step_fill(q.host_step, pos, sh); + for (int64_t h = 0; h < g.n_head; ++h) q.host_pos[h] = (int32_t) (pos_base + pos); + } +} + +bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts, + SessionGraphs& gr, std::string& err, bool split, int64_t layer_lo, int64_t layer_hi) { + if (gr.captured) return true; + if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers; + if (layer_lo < 0) layer_lo = 0; + gr.execs = new cudaGraphExec_t[(size_t) g.n_layers](); + gr.posts = new cudaGraphExec_t[(size_t) g.n_layers](); + for (int64_t i = 0; i < g.n_layers; ++i) gr.posts[i] = nullptr; + if (split) { + gr.preA = new cudaGraphExec_t[(size_t) g.n_layers](); + gr.preB = new cudaGraphExec_t[(size_t) g.n_layers](); + for (int64_t i = 0; i < g.n_layers; ++i) { gr.preA[i] = nullptr; gr.preB[i] = nullptr; } + for (int k = 0; k < 5; ++k) { + gr.preP[k] = new cudaGraphExec_t[(size_t) g.n_layers](); + for (int64_t i = 0; i < g.n_layers; ++i) gr.preP[k][i] = nullptr; + } + } + gr.split_captured = split; + gr.n = 0; + + int64_t qsa_index = s.qsa_ord0; + for (int64_t l = layer_lo; l < layer_hi; ++l) { + gdn_point_at(g, l, s); + const bool qsa = is_qsa_layer(g, l); + QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[s.qsa_primary()]; + + // **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.** `pre` ends with the doorbell rung; the host then runs + // the CPU pool on what it published; `post` combines those experts with THIS layer's weights. Capturing + // them together is what the old single graph could not do, and the reason it could not is that + // `moe_combine` needs the pool's answer and the pool needs the router's. + auto capture = [&](bool post, cudaGraphExec_t* out, const char* what, int half = 0, + int stage_prefix = 0) -> bool { + cudaStream_t cs = nullptr; + if (cudaStreamCreate(&cs) != cudaSuccess) { + err = std::string("session_capture: stream create failed"); + return false; + } + if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { + err = "session_capture: begin failed at layer " + std::to_string(l); + return false; + } + err.clear(); + // R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the + // stages so the mixer and the FFN-front-plus-router can be timed separately. + const bool ok = post + ? block_layer_post(tables, g, l, s.k, s.moe, s.block, parts, (void*) cs, err) + : block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k, + s.block, (void*) cs, err, s.db, s.ple.ready() ? &s.ple : nullptr, + half, stage_prefix); + if (!ok) { + err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + err; + return false; + } + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs, &graph); + cudaStreamDestroy(cs); + if (ce != cudaSuccess) { + err = "session_capture: " + std::string(what) + " layer " + std::to_string(l) + ": " + + cudaGetErrorString(ce) + " (a synchronous call in the layer?)"; + return false; + } + if (cudaGraphInstantiate(out, graph, 0) != cudaSuccess) { + err = "session_capture: instantiate failed at layer " + std::to_string(l); + return false; + } + cudaGraphDestroy(graph); + return true; + }; + if (!capture(/*post=*/false, &gr.execs[l], "pre")) return false; + if (!capture(/*post=*/true, &gr.posts[l], "post")) return false; + if (split) { + if (!capture(/*post=*/false, &gr.preA[l], "preA", /*half=*/1)) return false; + if (!capture(/*post=*/false, &gr.preB[l], "preB", /*half=*/2)) return false; + // Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth + // differ only in the one stage between them and not in how many nodes their graphs carry. + for (int k = 1; k <= 5; ++k) + if (!capture(/*post=*/false, &gr.preP[k - 1][l], "preP", /*half=*/0, /*stage_prefix=*/k)) + return false; + } + ++gr.n; + if (qsa) ++qsa_index; + } + gr.captured = true; + gr.parts_dev = const_cast(parts); // the address the graphs baked in; the loop copies here + return true; +} + +bool session_replay(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, + void* stream, std::string& err) { + if (!gr.captured || gr.n != g.n_layers) { err = "session_replay: not captured"; return false; } + cudaStream_t cs = (cudaStream_t) stream; + stage_token(g, pos, pos_base, s); + for (int64_t l = 0; l < g.n_layers; ++l) { + const cudaError_t e = cudaGraphLaunch(gr.execs[l], cs); + if (e != cudaSuccess) { + err = "session_replay: layer " + std::to_string(l) + ": " + cudaGetErrorString(e); + return false; + } + } + return true; +} + +bool session_replay_full(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::string& err) { + if (!gr.captured || gr.n != g.n_layers || gr.posts == nullptr) { + err = "session_replay_full: not captured with post graphs"; + return false; + } + cudaStream_t cs = (cudaStream_t) stream; + stage_token(g, pos, pos_base, s); + for (int64_t l = 0; l < g.n_layers; ++l) { + // `pre[l]` then `post[l]`, in the order `session_loop` uses. The two are ordered on one stream, and + // `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently. + cudaError_t e = cudaGraphLaunch(gr.execs[l], cs); + if (e != cudaSuccess) { + err = "session_replay_full: pre[" + std::to_string(l) + "]: " + cudaGetErrorString(e); + return false; + } + e = cudaGraphLaunch(gr.posts[l], cs); + if (e != cudaSuccess) { + err = "session_replay_full: post[" + std::to_string(l) + "]: " + cudaGetErrorString(e); + return false; + } + } + return true; +} + +bool session_replay_stages_per_layer(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::vector& mixer_per_layer, + double& ms_ffn, double& ms_post, std::string& err) { + if (!gr.split_captured || gr.preA == nullptr || gr.preB == nullptr) { + err = "session_replay_stages: not captured with the split"; + return false; + } + cudaStream_t cs = (cudaStream_t) stream; + stage_token(g, pos, pos_base, s); + + // Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after + // every layer to read them before the next launch overwrote them, and a per-layer sync would report the + // serialised time rather than the graph's. + const int64_t n = g.n_layers; + std::vector ev((size_t) (n * 4)); + for (auto& e : ev) { + if (cudaEventCreate(&e) != cudaSuccess) { err = "session_replay_stages: event create"; return false; } + } + struct Free { + std::vector* v; + ~Free() { for (auto& e : *v) cudaEventDestroy(e); } + } frees{&ev}; + + for (int64_t l = 0; l < n; ++l) { + cudaEventRecord(ev[(size_t) (l * 4 + 0)], cs); + if (cudaGraphLaunch(gr.preA[l], cs) != cudaSuccess) { err = "stages: preA"; return false; } + cudaEventRecord(ev[(size_t) (l * 4 + 1)], cs); + if (cudaGraphLaunch(gr.preB[l], cs) != cudaSuccess) { err = "stages: preB"; return false; } + cudaEventRecord(ev[(size_t) (l * 4 + 2)], cs); + if (cudaGraphLaunch(gr.posts[l], cs) != cudaSuccess) { err = "stages: post"; return false; } + cudaEventRecord(ev[(size_t) (l * 4 + 3)], cs); + } + if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "stages: final sync"; return false; } + + mixer_per_layer.assign((size_t) n, 0.0); + ms_ffn = 0; ms_post = 0; + for (int64_t l = 0; l < n; ++l) { + float a = 0, b = 0, c = 0; + cudaEventElapsedTime(&a, ev[(size_t) (l * 4 + 0)], ev[(size_t) (l * 4 + 1)]); + cudaEventElapsedTime(&b, ev[(size_t) (l * 4 + 1)], ev[(size_t) (l * 4 + 2)]); + cudaEventElapsedTime(&c, ev[(size_t) (l * 4 + 2)], ev[(size_t) (l * 4 + 3)]); + mixer_per_layer[(size_t) l] = (double) a; + ms_ffn += b; ms_post += c; + } + return true; +} + +bool session_replay_stages(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, double& ms_mixer, double& ms_ffn, double& ms_post, + std::string& err) { + std::vector per; + if (!session_replay_stages_per_layer(g, pos, pos_base, s, gr, stream, per, ms_ffn, ms_post, err)) return false; + ms_mixer = 0; + for (double v : per) ms_mixer += v; + return true; +} + +bool session_replay_stage_sweep(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, int k, double& ms, std::string& err) { + if (!gr.split_captured || gr.preP[0] == nullptr) { + err = "session_replay_stage_sweep: not captured with the split"; + return false; + } + if (k < 1 || k > 5) { err = "session_replay_stage_sweep: k must be 1..5"; return false; } + cudaStream_t cs = (cudaStream_t) stream; + stage_token(g, pos, pos_base, s); + + cudaEvent_t a, b; + if (cudaEventCreate(&a) != cudaSuccess || cudaEventCreate(&b) != cudaSuccess) { + err = "session_replay_stage_sweep: event create"; + return false; + } + cudaEventRecord(a, cs); + for (int64_t l = 0; l < g.n_layers; ++l) { + const cudaError_t e = cudaGraphLaunch(gr.preP[k - 1][l], cs); + if (e != cudaSuccess) { + cudaEventDestroy(a); + cudaEventDestroy(b); + err = std::string("session_replay_stage_sweep: launch: ") + cudaGetErrorString(e); + return false; + } + } + cudaEventRecord(b, cs); + if (cudaStreamSynchronize(cs) != cudaSuccess) { + cudaEventDestroy(a); + cudaEventDestroy(b); + err = "session_replay_stage_sweep: sync"; + return false; + } + float v = 0; + cudaEventElapsedTime(&v, a, b); + cudaEventDestroy(a); + cudaEventDestroy(b); + ms = (double) v; + return true; +} + +bool session_replay_stage_prefixes(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, + SessionGraphs& gr, void* stream, std::vector& stage_ms, + std::vector& mixer_per_layer, std::string& err) { + if (!gr.split_captured || gr.preP[0] == nullptr) { + err = "session_replay_stage_prefixes: not captured with the split"; + return false; + } + cudaStream_t cs = (cudaStream_t) stream; + stage_token(g, pos, pos_base, s); + const int64_t n = g.n_layers; + const size_t r_floats = (size_t) g.hc * (size_t) g.n_embd; + + float* saved = nullptr; + if (cudaMalloc((void**) &saved, r_floats * sizeof(float)) != cudaSuccess) { + err = "session_replay_stage_prefixes: could not save the residual"; + return false; + } + std::vector ev((size_t) (n * 6)); + bool ev_ok = true; + for (auto& e : ev) if (cudaEventCreate(&e) != cudaSuccess) { ev_ok = false; break; } + if (!ev_ok) { + for (auto& e : ev) cudaEventDestroy(e); + cudaFree(saved); + err = "session_replay_stage_prefixes: event create"; + return false; + } + struct Cleanup { + std::vector* v; + float* p; + ~Cleanup() { for (auto& e : *v) cudaEventDestroy(e); cudaFree(p); } + } cleanup{&ev, saved}; + + double t[5] = {0, 0, 0, 0, 0}; + mixer_per_layer.assign((size_t) n, 0.0); + for (int64_t l = 0; l < n; ++l) { + // The residual as this layer receives it, before any prefix has advanced it. + cudaMemcpyAsync(saved, s.block.R, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs); + for (int k = 1; k <= 5; ++k) { + if (k > 1) cudaMemcpyAsync(s.block.R, saved, r_floats * sizeof(float), cudaMemcpyDeviceToDevice, cs); + cudaEventRecord(ev[(size_t) (l * 6 + k - 1)], cs); + const cudaGraphExec_t ge = (k == 5) ? gr.execs[l] : gr.preP[k - 1][l]; + const cudaError_t e = cudaGraphLaunch(ge, cs); + if (e != cudaSuccess) { + err = std::string("session_replay_stage_prefixes: launch prefix ") + std::to_string(k) + ": " + + cudaGetErrorString(e); + return false; + } + } + cudaEventRecord(ev[(size_t) (l * 6 + 5)], cs); + } + if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "prefixes: final sync"; return false; } + + float t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; + for (int64_t l = 0; l < n; ++l) { + float a = 0, b = 0, c = 0, d = 0, e = 0; + cudaEventElapsedTime(&a, ev[(size_t) (l * 6 + 0)], ev[(size_t) (l * 6 + 1)]); + cudaEventElapsedTime(&b, ev[(size_t) (l * 6 + 1)], ev[(size_t) (l * 6 + 2)]); + cudaEventElapsedTime(&c, ev[(size_t) (l * 6 + 2)], ev[(size_t) (l * 6 + 3)]); + cudaEventElapsedTime(&d, ev[(size_t) (l * 6 + 3)], ev[(size_t) (l * 6 + 4)]); + cudaEventElapsedTime(&e, ev[(size_t) (l * 6 + 4)], ev[(size_t) (l * 6 + 5)]); + t1 += a; t2 += b; t3 += c; t4 += d; t5 += e; + mixer_per_layer[(size_t) l] = (double) c; // prefix 3 IS the mixer: stages 0..2 + } + t[0] = t1; + t[1] = t2 - t1; + t[2] = t3 - t2; + t[3] = t4 - t3; + t[4] = t5 - t4; + stage_ms.assign(t, t + 5); + return true; +} + +void session_graphs_free(SessionGraphs& gr) { + if (gr.execs) { + for (int64_t i = 0; i < gr.n; ++i) cudaGraphExecDestroy(gr.execs[i]); + delete[] gr.execs; + } + if (gr.posts) { + for (int64_t i = 0; i < gr.n; ++i) + if (gr.posts[i] != nullptr) cudaGraphExecDestroy(gr.posts[i]); + delete[] gr.posts; + } + if (gr.preA) { + for (int64_t i = 0; i < gr.n; ++i) + if (gr.preA[i] != nullptr) cudaGraphExecDestroy(gr.preA[i]); + delete[] gr.preA; + } + if (gr.preB) { + for (int64_t i = 0; i < gr.n; ++i) + if (gr.preB[i] != nullptr) cudaGraphExecDestroy(gr.preB[i]); + delete[] gr.preB; + } + for (int k = 0; k < 5; ++k) { + if (gr.preP[k] == nullptr) continue; + for (int64_t i = 0; i < gr.n; ++i) + if (gr.preP[k][i] != nullptr) cudaGraphExecDestroy(gr.preP[k][i]); + delete[] gr.preP[k]; + gr.preP[k] = nullptr; + } + gr.preA = nullptr; + gr.preB = nullptr; + gr.split_captured = false; + gr.posts = nullptr; + gr.execs = nullptr; + gr.parts_dev = nullptr; + gr.n = 0; + gr.captured = false; +} + +bool SessionLoopScratch::init(size_t parts_bytes_in, std::string& err) { + if (y_miss != nullptr || probe != nullptr) { + err = "SessionLoopScratch::init: already initialised"; + return false; + } + parts_bytes = parts_bytes_in; + // MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer. + if (cudaHostAlloc((void**) &y_miss, parts_bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { + err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed"; + return false; + } + std::memset(y_miss, 0, parts_bytes); + if (cudaEventCreate(&probe) != cudaSuccess) { + err = "SessionLoopScratch: cudaEventCreate failed"; + free(); + return false; + } + // **PIN THE HOST ONCE, NOT ONCE PER TOKEN.** `ExpertPool` builds its workers from `physical_cores(true)`, + // which drops the first physical core so the host loop can spin without taking a worker's cycles - and + // nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's + // core or its SMT sibling. The symptom is not an error: it is a CPU path at 26.9 GB/s where the same pool + // runs at 36.32. It was being done and undone on EVERY token, which is a syscall pair on the critical path + // for a property that wants to hold for the whole session. + const std::vector cores = strata::kernels::cpu::physical_cores(false); + if (!cores.empty()) { + pinned_core = strata::kernels::cpu::pin_current_thread(cores[0]); + pinned = true; + } + return true; +} + +void SessionLoopScratch::free() { + // Restores the caller's affinity on every path, including teardown: a library that silently leaves its + // caller's thread nailed to one core is worse than one that never pinned at all. + if (pinned) { + strata::kernels::cpu::restore_thread_affinity(pinned_core); + pinned = false; + pinned_core = -1; + } + if (probe != nullptr) { cudaEventDestroy(probe); probe = nullptr; } + if (y_miss != nullptr) { cudaFreeHost(y_miss); y_miss = nullptr; } + parts_bytes = 0; +} + +bool session_loop(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, SessionGraphs& gr, + PoolFn pool, HitFn hits, void* user, bool overlap, void* stream, std::string& err, + float* dump_layers, SessionLoopScratch* scratch) { + if (!gr.captured || gr.n != g.n_layers) { err = "session_loop: not captured"; return false; } + if (gr.parts_dev == nullptr) { err = "session_loop: the graphs were captured without a parts buffer"; return false; } + if (s.db == nullptr) { err = "session_loop: no doorbell; the loop has nothing to poll"; return false; } + + cudaStream_t cs = (cudaStream_t) stream; + const int64_t k = s.k; + const size_t parts_bytes = (size_t) k * g.n_embd * 4; + ++gr.calls_total; + + // ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================ + // + // **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.** The QSA layers read their per-token counts from + // `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph. A + // graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every + // replay, and those hold whatever was last written there. `session_capture` left them at position 0. + // + // `layer.hpp` documents the requirement this loop was missing: "The per-token staging every QSA layer's + // captured H2D reads FROM. Must run before each replay: the graphs captured the SOURCE POINTER, not the + // value, and that is exactly why the buffers are pinned and fixed." `session_replay` calls `stage_token`; + // `session_loop` did not. **A single-token test cannot see a position that never advances** - which is why + // the whole suite passed while a 20-token prompt rotated every token at position 0. + stage_token(g, pos, pos_base, s); + + // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** + // + // Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe + // event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in. It used to + // be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE + // DEVICE, so every token finished with a device-wide sync that nothing had asked for. A comment here said + // "allocated once"; once per token is not once. + // + // Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a + // local scratch and frees it on every exit path below, including the error returns. + SessionLoopScratch local; + if (scratch == nullptr) { + if (!local.init(parts_bytes, err)) return false; + scratch = &local; + } + struct LocalFree { + SessionLoopScratch* p; + ~LocalFree() { if (p != nullptr) p->free(); } + } local_free{scratch == &local ? &local : nullptr}; + if (scratch->parts_bytes != parts_bytes) { + err = "session_loop: the scratch was sized for a different k or n_embd"; + return false; + } + + // HOST-side staging for the pool's answer. It is copied to `gr.parts_dev` before the next launch, on the + // same stream, so the ordering is the stream's and no captured node is needed for it. + // + // ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.** + // + // `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal + // pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer. So the "async" + // copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers. The + // doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of + // object. + float* y_miss = scratch->y_miss; + cudaEvent_t probe = scratch->probe; + + // the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty + // in this phase" means once every miss has been computed + cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs); + doorbell_reset(*s.db); + uint32_t expected = 0; + + // **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that + // `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`. + // + // SLOT 0 OF THE DUMP IS THE INPUT, not a layer output. `s.R` holds the embedding broadcast to every stream + // when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits + // "the input to layer 0 is already wrong" from "layer 0 is wrong". + if (dump_layers != nullptr) { + const size_t n = (size_t) g.hc * (size_t) g.n_embd; + const cudaError_t de = cudaMemcpyAsync(dump_layers, s.R, n * sizeof(float), cudaMemcpyDeviceToHost, cs); + if (de != cudaSuccess) { + err = "session_loop: dump the input residual: " + std::string(cudaGetErrorString(de)); + return false; + } + } + { + const auto t0 = std::chrono::steady_clock::now(); + const cudaError_t le = cudaGraphLaunch(gr.execs[0], cs); + if (le != cudaSuccess) { + err = "session_loop: launch pre[0]: " + std::string(cudaGetErrorString(le)); + return false; + } + cudaEventRecord(probe, cs); + (void) t0; + } + + for (int64_t l = 0; l < g.n_layers; ++l) { + const auto t_launch = std::chrono::steady_clock::now(); + + // ---- poll for the ring. **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.** + const uint32_t want = ++expected; + bool rang = false; + bool mid_graph = false; + // VOLATILE, because the device writes this through mapped pinned memory and a cached host line would + // never see it. Read through a volatile pointer so the compiler re-issues the load every iteration - + // otherwise this whole spin collapses into `while (true) { }`. + volatile uint32_t* const seq = s.db->h_seq; + for (;;) { + // **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.** Round 287 + // throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to + // `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again. So the call + // is not merely flushing submission (round 195's reading) and it is not a missing fence either: on + // this driver, the device's write to mapped pinned memory becomes host-visible only when the driver + // is entered. The fence and the volatile read are kept because they are correct and cost nothing - + // without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not + // remove the need for the call, and nothing here should be read as claiming they do. + const cudaError_t q = cudaEventQuery(probe); + if (!rang && *seq >= want) { + rang = true; + mid_graph = (q != cudaSuccess); + } + if (q == cudaSuccess) break; // the graph has ended + if (q != cudaErrorNotReady) { + err = "session_loop: query at layer " + std::to_string(l) + ": " + cudaGetErrorString(q); + return false; + } + if (rang) break; // rung, and the graph is still running: the overlap + STRATA_SPIN_PAUSE(); + } + if (mid_graph) ++gr.rings_mid_graph; + // the window, from just before the launch to the instant the ring was seen + const auto t_ring = std::chrono::steady_clock::now(); + gr.ms_to_ring += std::chrono::duration(t_ring - t_launch).count(); + if (!rang) { + // The graph finished without the ring being observed. `h_seq` is monotonic, so this is not a race + // - it means the ring never happened, which is the failure round 199 found in a captured event. + err = "session_loop: layer " + std::to_string(l) + " ended without ringing"; + return false; + } + + // ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.** `Launch` only enqueues: + // the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately, + // while the host is still inside `pool` below. Nothing here waits. + if (hits != nullptr) hits(user, cs, HitPhase::Launch, s.db->h_ids, k); + + // ---- the pool, on the bytes the doorbell published. **THESE ARE LAYER `l`'s EXPERTS.** + if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, k, y_miss); + + // ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.** + // + // This copy and the launch below are the whole of the L100 fix. `moe_combine` multiplies `parts` by + // THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied + // the pool's answer into `parts_dev` for the NEXT layer, which computed + // `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while + // the weights were current. It produced finite, fluent, deterministic tokens that were not the + // model's, and no timing test could see it. + cudaMemcpyAsync(gr.parts_dev, y_miss, parts_bytes, cudaMemcpyHostToDevice, cs); + // ---- **AND THEN THE COMBINE.** Stream-ordered after the copy above, so `hit_out` is added to misses + // that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum. A no-op when + // there is no VRAM tier or nothing is resident, which is every layer until the cache warms. + if (hits != nullptr) hits(user, cs, HitPhase::Combine, nullptr, 0); + { + const cudaError_t pe = cudaGraphLaunch(gr.posts[l], cs); + if (pe != cudaSuccess) { + err = "session_loop: launch post[" + std::to_string(l) + "]: " + cudaGetErrorString(pe); + return false; + } + } + // ---- the C1 oracle. `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so + // a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone. + // Nothing is synchronised: the loop's existing final sync is what completes these. See the note on + // `dump_layers` in session.hpp for why this is an enqueue and not a read. + if (dump_layers != nullptr) { + const size_t n = (size_t) g.hc * (size_t) g.n_embd; + const cudaError_t de = cudaMemcpyAsync(dump_layers + (size_t) (l + 1) * n, s.R, n * sizeof(float), + cudaMemcpyDeviceToHost, cs); + if (de != cudaSuccess) { + err = "session_loop: dump layer " + std::to_string(l) + ": " + cudaGetErrorString(de); + return false; + } + } + if (!overlap) { + // THE COMPARISON ARM. The same sequence with the pipeline removed: the CPU does not start until the + // layer is over, so nothing overlaps and the difference is attributable to the doorbell alone. + if (cudaStreamSynchronize(cs) != cudaSuccess) { + err = "session_loop: sync at layer " + std::to_string(l); + return false; + } + } + // ---- and layer l+1's routing starts. `pre[l+1]` touches none of the buffers `post[l]` reads, because + // the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own + // `gr_read`, which comes after `post[l]` has consumed them. + if (l + 1 < g.n_layers) { + const cudaError_t ne = cudaGraphLaunch(gr.execs[l + 1], cs); + if (ne != cudaSuccess) { + err = "session_loop: launch pre[" + std::to_string(l + 1) + "]: " + cudaGetErrorString(ne); + return false; + } + cudaEventRecord(probe, cs); + } + // ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.** + // + // From seeing the ring to having queued the next `pre`. Everything in here is a driver call, and on + // the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and + // `post[l]` cannot start until this code launches it. So this interval is GPU-idle time, and it is + // the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel. + // + // It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm + // exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison. + gr.ms_host += std::chrono::duration(std::chrono::steady_clock::now() - t_ring).count(); + } + if (cudaStreamSynchronize(cs) != cudaSuccess) { err = "session_loop: final sync"; return false; } + return true; +} + +bool session_token(const WeightTable& tables, const ModelGeometry& g, int64_t pos, int32_t pos_base, + SessionState& s, const float* parts, void* stream, bool sync_every_layer, + std::string& err) { + cudaStream_t cs = (cudaStream_t) stream; + int64_t qsa_index = 0; + int64_t gdn_index = 0; + + for (int64_t l = 0; l < g.n_layers; ++l) { + // THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the + // shared scratch at the right slice before each call. Sharing one state across 36 layers would make + // every layer start from the previous layer's recurrence, which produces a perfectly finite answer. + if (!is_qsa_layer(g, l)) { + s.gdn.state = s.gdn_state + (size_t) gdn_index * gdn_state_floats(g); + s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + ++gdn_index; + } + + err.clear(); + const bool ok = is_qsa_layer(g, l) + ? block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[qsa_index], s.qsa_bufs, s.moe, s.k, + s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr) + : block_layer(tables, g, l, pos, pos_base, s.gdn, s.qsa_states[0], s.qsa_bufs, s.moe, s.k, + s.block, parts, stream, err, nullptr, s.ple.ready() ? &s.ple : nullptr); + if (!ok) { + err = "layer " + std::to_string(l) + ": " + err; + return false; + } + if (is_qsa_layer(g, l)) ++qsa_index; + + if (sync_every_layer) { + // THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which + // P2.X3 forbids in the fast path. It exists to turn an ASYNCHRONOUS error - a kernel reading a + // buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED + // IT, instead of a wrong number 40 layers later or at the end of the token. + const cudaError_t e = cudaStreamSynchronize(cs); + if (e != cudaSuccess) { + err = "layer " + std::to_string(l) + ": " + cudaGetErrorString(e); + return false; + } + } + } + return true; +} + +} // namespace strata::core + +namespace strata::core { + +bool session_capture_token(const WeightTable& tables, const ModelGeometry& g, SessionState& s, float* parts_dev, + const float* y_miss_host, size_t parts_bytes, TokenGraph& tg, std::string& err, + const TokenHits* hits) { + if (hits != nullptr && !hits->on()) { err = "session_capture_token: incomplete hit configuration"; return false; } + if (tg.captured) return true; + if (s.db == nullptr || s.db->d_flag == nullptr || s.db->d_seq == nullptr) { + err = "session_capture_token: the doorbell has no flag"; + return false; + } + if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0) { + err = "session_capture_token: parts buffers are required"; + return false; + } + float* y_dev = nullptr; + if (cudaHostGetDevicePointer((void**) &y_dev, const_cast(y_miss_host), 0) != cudaSuccess || !y_dev) { + err = "session_capture_token: the parts staging is not mapped pinned memory"; + return false; + } + cudaStream_t cs = nullptr; + if (cudaStreamCreate(&cs) != cudaSuccess) { err = "session_capture_token: stream create failed"; return false; } + if (cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { + cudaStreamDestroy(cs); + err = "session_capture_token: begin capture failed"; + return false; + } + int64_t qsa_index = 0; + bool ok = true; + for (int64_t l = 0; l < g.n_layers && ok; ++l) { + gdn_point_at(g, l, s); + const bool qsa = is_qsa_layer(g, l); + QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[0]; + err.clear(); + ok = block_layer_pre(tables, g, l, 0, 0, s.gdn, qst, s.qsa_bufs, s.moe, s.k, s.block, (void*) cs, err, s.db, + s.ple.ready() ? &s.ple : nullptr); + if (!ok) { err = "session_capture_token: pre layer " + std::to_string(l) + ": " + err; break; } + if (hits != nullptr) { + // After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses. + strata::kernels::moe_hit_select(s.moe.ids, hits->d_res + l * hits->n_expert, (int) s.k, + (int) hits->n_expert, hits->d_slot, hits->d_dst, hits->d_count, (void*) cs); + strata::kernels::quantize_q8_0_scaled(s.block.mixed, hits->x_q8, hits->x_scale, g.n_embd, (void*) cs); + strata::kernels::moe_hit_grouped_s2_dev(hits->cache_base, hits->d_slot, hits->d_dst, hits->d_count, s.k, + hits->blob, hits->x_q8, hits->scratch, hits->hit_out, (void*) cs, + hits->x_scale); + } + strata::kernels::doorbell_wait(s.db->d_flag, s.db->d_seq, (void*) cs); + // A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token). + strata::kernels::copy_from_mapped(parts_dev, y_dev, (int64_t) (parts_bytes / sizeof(float)), (void*) cs); + if (hits != nullptr) + strata::kernels::moe_hit_add(parts_dev, hits->hit_out, hits->d_dst, hits->d_count, s.k, g.n_embd, (void*) cs); + ok = block_layer_post(tables, g, l, s.k, s.moe, s.block, parts_dev, (void*) cs, err); + if (!ok) { err = "session_capture_token: post layer " + std::to_string(l) + ": " + err; break; } + if (qsa) ++qsa_index; + } + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs, &graph); + cudaStreamDestroy(cs); + if (!ok) { if (graph) cudaGraphDestroy(graph); return false; } + if (ce != cudaSuccess) { + err = std::string("session_capture_token: end capture: ") + cudaGetErrorString(ce); + return false; + } + const cudaError_t ie = cudaGraphInstantiate(&tg.exec, graph, 0); + cudaGraphDestroy(graph); + if (ie != cudaSuccess) { + err = std::string("session_capture_token: instantiate: ") + cudaGetErrorString(ie); + return false; + } + tg.captured = true; + tg.n_layers = g.n_layers; + tg.y_src = y_miss_host; + tg.parts_bytes = parts_bytes; + return true; +} + +bool session_run_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionState& s, TokenGraph& tg, + PoolFn pool, void* user, float* y_miss_host, void* stream, std::string& err) { + if (!tg.captured) { err = "session_run_token: not captured"; return false; } + if (y_miss_host != tg.y_src) { err = "session_run_token: the staging buffer is not the captured one"; return false; } + cudaStream_t cs = (cudaStream_t) stream; + ++tg.calls; + stage_token(g, pos, pos_base, s); + doorbell_reset(*s.db); + const cudaError_t le = cudaGraphLaunch(tg.exec, cs); + if (le != cudaSuccess) { err = std::string("session_run_token: launch: ") + cudaGetErrorString(le); return false; } + (void) cudaStreamQuery(cs); // one flush, so WDDM submits the graph now + static const int flush_us = [] { + const char* e = std::getenv("STRATA_TG_FLUSH_US"); + return e ? std::atoi(e) : 2000; // 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults + }(); + volatile uint32_t* const seq = s.db->h_seq; + volatile uint32_t* const flag = s.db->h_flag; + using Clock = std::chrono::steady_clock; + for (int64_t l = 0; l < g.n_layers; ++l) { + const uint32_t want = (uint32_t) (l + 1); + const auto t0 = Clock::now(); + auto last_flush = t0; + uint32_t spins = 0; + progress_at("token: waiting for the GPU to reach layer", l); + while (*seq < want) { + STRATA_SPIN_PAUSE(); + if ((++spins & 1023u) != 0) continue; + const auto now = Clock::now(); + if (now - last_flush > std::chrono::microseconds(flush_us)) { + // A slow ring: flush the submission queue once more, and notice a fault or a finished graph. + last_flush = now; + ++tg.flushes; + const cudaError_t q = cudaStreamQuery(cs); + if (q != cudaErrorNotReady && *seq < want) { + err = "session_run_token: layer " + std::to_string(l) + " never rang (" + + (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; + return false; + } + } + if (now - t0 > std::chrono::seconds(20)) { + err = "session_run_token: timed out waiting for layer " + std::to_string(l); + return false; + } + } + const auto t1 = Clock::now(); + progress_at("token: the CPU experts of layer", l); + if (pool != nullptr) pool(user, s.db->h_x_f, s.db->h_ids, s.db->h_weights, g.n_embd, s.k, y_miss_host); + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + *flag = want; + const auto t2 = Clock::now(); + tg.ms_wait += std::chrono::duration(t1 - t0).count(); + tg.ms_pool += std::chrono::duration(t2 - t1).count(); + } + progress_at("token: waiting for the GPU to finish the token"); + const cudaError_t se = cudaStreamSynchronize(cs); + if (se != cudaSuccess) { err = std::string("session_run_token: ") + cudaGetErrorString(se); return false; } + progress_at("decode"); + progress_beat(); + return true; +} + +void token_graph_free(TokenGraph& tg) { + if (tg.exec) cudaGraphExecDestroy(tg.exec); + tg = TokenGraph{}; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/verify.cpp b/engine/strata/src/core/verify.cpp new file mode 100644 index 00000000..58f7594b --- /dev/null +++ b/engine/strata/src/core/verify.cpp @@ -0,0 +1,1429 @@ +// src/core/verify.cpp - see include/strata/core/verify.hpp. +#include "strata/core/verify.hpp" +#include "strata/core/keyless.hpp" +#if defined(_WIN32) +#include +#endif + +#include "strata/core/native_head.hpp" +#include "strata/core/on_device.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/gr.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/ple.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/sampler.hpp" +#include "strata/core/progress.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { +namespace { + +constexpr float EPS = 1e-6f; +using Clock = std::chrono::steady_clock; +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } +const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr; +#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) + +struct Bump { + uint8_t* base = nullptr; + uint64_t used = 0; + template T* take(uint64_t n) { + T* p = base ? (T*) (base + used) : nullptr; + used += (n * sizeof(T) + 255) & ~255ull; + return p; + } +}; + +bool mapped(size_t bytes, void** h, void** d) { + if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false; + std::memset(*h, 0, bytes); + return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; +} + +strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; + s.n_head_kv = g.n_head_kv; + s.head_dim = g.head_dim; + s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + return s; +} + +const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) { + const WeightRef* r = v.get(suffix); + if (r == nullptr && err.empty()) err = v.name(suffix) + " is missing"; + return r; +} + +bool native_of(const WeightRef* w, const std::string& name, std::string& err) { + if (w == nullptr) return false; + if (w->native_data == nullptr) { + err = "verify: " + name + " is not served natively (run with --native)"; + return false; + } + return true; +} + +} // namespace + +namespace { +std::atomic g_diag_verifier{nullptr}; +void diag_active_verifier(std::FILE* f) { + if (const Verifier* v = g_diag_verifier.load()) v->diag(f); +} +// #267: every live verifier (a layer split has one per stage), for the release before the engine ends +constexpr int kLiveMax = 16; +std::atomic g_live[kLiveMax]; +void release_live_verifiers(std::FILE* f) { + for (auto& slot : g_live) + if (Verifier* v = slot.load()) { + const Clock::time_point t0 = Clock::now(); + const bool done = v->release_gpu_waits(5000); + if (f != nullptr) + std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n", + done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str() + : "did not finish within 5 s"); + } + if (f != nullptr) std::fflush(f); +} +std::string released_note(bool drained) { + return drained ? "; its GPU waits were released and the GPU finished (#267)" + : "; its GPU waits were released but the GPU did not finish within 5 s (#267)"; +} +// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the +// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never. +const int64_t g_test_stall = [] { + const char* e = std::getenv("STRATA_TEST_VERIFY_STALL"); + return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0; +}(); +} // namespace + +bool Verifier::release_gpu_waits(int timeout_ms) { + released_.store(true); + // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here + // reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but + // wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. + for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_}) + if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX; + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + const OnDevice on_device(device_); + const Clock::time_point t0 = Clock::now(); + for (cudaStream_t s : {cs_, copy_}) { + if (s == nullptr) continue; + while (cudaStreamQuery(s) == cudaErrorNotReady) { + if (ms_since(t0) > timeout_ms) return false; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + } + return true; +} + +void Verifier::diag(std::FILE* f) const { + auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; + // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's + const char* where = progress().where.load(); + const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0; + std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: " + "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)", + last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_)); +} + +Verifier::~Verifier() { + const Verifier* self = this; + g_diag_verifier.compare_exchange_strong(self, nullptr); + for (auto& slot : g_live) { + Verifier* me = this; + slot.compare_exchange_strong(me, nullptr); + } + if (cs_) cudaStreamSynchronize(cs_); + for (auto& e : exec_) + if (e) cudaGraphExecDestroy(e); + if (commit_exec_) cudaGraphExecDestroy(commit_exec_); + if (cs_) cudaStreamDestroy(cs_); + if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (commit_done_) cudaEventDestroy(commit_done_); + if (arena_) cudaFree(arena_); + if (trace_file_) std::fclose(trace_file_); + if (trace_q_file_) std::fclose(trace_q_file_); + void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, trace_h_, trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, + h_flagA_, h_plan_, h_flagB_}; + for (void* h : hosts) + if (h) cudaFreeHost(h); +} + +bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits, + const NativeHead* head, int max_t, std::string& err) { + g_diag_verifier.store(this); + diag_verify_fn().store(&diag_active_verifier); + for (auto& slot : g_live) { + Verifier* none = nullptr; + if (slot.load() == this || slot.compare_exchange_strong(none, this)) break; + } + release_gpu_fn().store(&release_live_verifiers); + cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there + strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there + wt_ = &wt; + g_ = &g; + ss_ = &ss; + hits_ = hits; + head_ = head; + max_t_ = max_t; + if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) { + if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; } + trace_file_ = std::fopen(path, "wb"); + trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb"); + const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t * + (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float); + const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head * + (size_t) g.head_dim * sizeof(float); + if (!trace_file_ || !trace_q_file_ || + cudaHostAlloc((void**) &trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess || + cudaHostAlloc((void**) &trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) { + err = "verify: cannot create pinned keyless activation trace"; + return false; + } + } + sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise + sampling_.temperature = 0.0f; + if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { + err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens"; + return false; + } + if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) { + err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " + "--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU"; + return false; + } + std::string why; + if (!layer_verify_compatible(why)) { + err = "verify: " + why + " (the verify window reproduces the default native decode path)"; + return false; + } + if (!strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr) || ss.k != 10 || g.ssm_state_size != 128 || + g.ssm_d_conv != 4) { + err = "verify: geometry differs from the artifact's"; + return false; + } + if (le_ < 0) le_ = g.n_layers; + if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) || + (le_ < g.n_layers && hand_out_ == nullptr)) { + err = "verify: the stage's layer range or its hand-off buffers are wrong"; + return false; + } + const WeightRef* wo = wt.find("output.weight"); + if (wo == nullptr) { err = "verify: output.weight is missing"; return false; } + n_vocab_ = wo->ne1; + + const strata::kernels::QsaShapes s = shapes_of(g); + cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); + max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s); + + const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k; + const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads; + const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv; + const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim; + const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers(); + const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM; + const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID; + const int max_in = (int) std::max(std::max(N, ZV), NH * HD); + + // ---- mapped staging + bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) && + mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) && + mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) && + mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) && + mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) && + mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) && + mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) && + mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) && + mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) && + mapped(64, (void**) &h_seq_, (void**) &m_seq_) && + mapped(64, (void**) &h_flag_, (void**) &m_flag_) && + mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) && + mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) && + mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); + if (!ok) { err = "verify: mapped staging allocation failed"; return false; } + // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) + { + const int64_t cap = (int64_t) (T * K); + const int64_t i32 = 4 + (cap + 1) + cap + cap; + const int64_t ptr_off = (i32 + 1) & ~1ll; + plan_i32_ = ptr_off + 4 * cap + (cap + 1) + 1; + if (!mapped((size_t) plan_i32_ * 4 * 2 + 64, (void**) &h_plan_, (void**) &m_plan_)) { + err = "verify: mapped plan allocation failed"; + return false; + } + sink_.counts = h_plan_; + sink_.start = h_plan_ + 4; + sink_.dst = sink_.start + cap + 1; + sink_.tok = sink_.dst + cap; + sink_.ptr = (unsigned long long*) (h_plan_ + ptr_off); + sink_.ptr2 = sink_.ptr + cap; + sink_.start2 = h_plan_ + ptr_off + 4 * cap; + sink_.cap = cap; + sink_.publish = &Verifier::publish_plan; + sink_.fetch = &Verifier::fetch_dma; + sink_.ctx = this; + } + + // ---- the device arena: the same sequence counted, then carved + auto carve = [&](Bump& b) { + tok_ = b.take(T); step_ = b.take(T * strata::kernels::kStepCount); + pos_ = b.take(T * (NH + NKV + IQ)); commit_ = b.take(2 + T); + ple_ = b.take(T * N); emb_ = b.take(T * N); R_ = b.take(T * HC * N); + mixed_ = b.take(T * N); bo_ = b.take(T * N); + inj_ = b.take(T * HC); inj2_ = b.take(T * HC); + lo_ = b.take(T * (uint64_t) g.hc_lr); rs_ = b.take(T * HC); xn_ = b.take(T * HC * N); + xq_ = b.take(strata::kernels::native_q8_1_bytes(max_in, (int) T)); + qkv_L_ = b.take(nG * T * C); h_L_ = b.take(nG * T * C); + gate_L_ = b.take(nG * T * HV); beta_L_ = b.take(nG * T * HV); + z_ = b.take(T * ZV); y_ = b.take(T * ZV); y_dummy_ = b.take(T * ZV); + qfull_ = b.take(T * NH * 2 * HD); qcur_ = b.take(T * NH * HD); + kcur_ = b.take(T * NKV * HD); vcur_ = b.take(T * NKV * HD); + idx_raw_L_ = b.take(nQ * T * ID); qidx_ = b.take(T * IQ * ID); + scores_ = b.take(T * (uint64_t) max_blocks_); sel_ = b.take(T * (uint64_t) cap_); + attn_ = b.take(T * NH * HD); attn32_ = b.take(T * NH * HD); + attn_scratch_ = b.take(T * (uint64_t) attn_scratch_floats_); + tail_snap_ = b.take(nQ * TS); + logits_ = b.take(T * (uint64_t) g.n_expert); w_ = b.take(T * K); ids_ = b.take(T * K); + shared_ = b.take(T * N); parts_ = b.take(T * K * N); hit_out_ = b.take(T * K * N); + hit_slot_ = b.take(T * K); hit_dst_ = b.take(T * K); hit_count_ = b.take(4); + plan_ = b.take(2 * ((uint64_t) plan_i32_ + 16)); + staging_ = b.take((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob); + hit_xq_ = b.take(T * (N / 32) * 34); hit_xs_ = b.take(T * (N / 32)); + nat_xq_ = b.take(T * (N / 32) * 36); + hit_scratch_ = b.take(std::max( + strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff), + strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff))); + head_mixed_ = b.take(T * N); head_inj_ = b.take(HC); + sh_bf16_ = b.take(T * N); sh_gate_ = b.take(T * (uint64_t) g.n_ff); + sh_up_ = b.take(T * (uint64_t) g.n_ff); sh_g_ = b.take(T + 4); + head_logits_ = b.take(T * (uint64_t) n_vocab_); + hist_snap_ = b.take(T * HS); + }; + Bump count; + carve(count); + if (cudaMalloc(&arena_, count.used) != cudaSuccess) { + err = "verify: the device arena (" + std::to_string(count.used >> 20) + " MiB) does not fit"; + return false; + } + cudaMemset(arena_, 0, count.used); + prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr; + if (prof_on_) { + const size_t np = (size_t) g.n_layers * kProfPer + 4; + if (cudaMalloc((void**) &prof_, np * 8) != cudaSuccess) { prof_on_ = false; prof_ = nullptr; cudaGetLastError(); } + else { cudaMemset(prof_, 0, np * 8); prof_h_.assign(np, 0); } + } + Bump real; + real.base = (uint8_t*) arena_; + carve(real); + sink_.staging = (unsigned long long) staging_; + sink_.staging_cap = kStagingBlobs; + (void) TS; + if (cudaStreamCreateWithFlags(©_, cudaStreamNonBlocking) != cudaSuccess) { + err = "verify: copy stream create failed"; + return false; + } + if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { + err = "verify: stream create failed"; + return false; + } + if (cudaEventCreateWithFlags(&commit_done_, cudaEventDisableTiming) != cudaSuccess) { + err = "verify: event create failed"; + return false; + } + // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; + // exact, but neutral on RIBPC 1-2 GPUs: off by default) + { + const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); + device_plan_ = v != nullptr && std::atoi(v) != 0; + } + if (device_plan_) { + bool ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess; + if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) { + ok2 = cudaMalloc((void**) &slot_off_d_, (size_t) hits.n_slots * sizeof(unsigned long long)) == cudaSuccess && + cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long), + cudaMemcpyHostToDevice) == cudaSuccess; + } + if (!ok2) { cudaGetLastError(); device_plan_ = false; } + } + std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers\n", max_t, + (double) count.used / 1048576.0); + return true; +} + +const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t) (g_->hc * g_->n_embd); } + +// ================================ THE WINDOW, AS CAPTURED ================================ +// +// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and +// B = the rest, and the stream is ordered +// +// pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ... +// +// so the CPU computes A's experts of layer l while the GPU runs B's mixer and router of layer l, and B's experts +// while the GPU combines A and runs A's layer l+1. B's mixer only needs A's mixer of the same layer (K/V, GDN +// state), never A's experts, so nothing waits that did not wait before. Every token's arithmetic is unchanged. +bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + using namespace strata::kernels; + const ModelGeometry& g = *g_; + const WeightTable& wt = *wt_; + SessionState& ss = *ss_; + const int64_t N = g.n_embd, HC = g.hc, K = ss.k, C = g.ssm_conv_channels, ZV = g.ssm_value_dim; + const int64_t HV = g.ssm_v_heads, HK = g.ssm_k_heads, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv; + const int64_t IQ = g.idx_q_heads, ID = g.idx_key_dim, NE = g.n_expert, MT = max_t_; + const QsaShapes s = shapes_of(g); + const GrShapes gs{g.n_embd, g.hc, g.hc_lr}; + const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); + const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM; + const int64_t TS = (s.idx_block - 1) * ID; + const bool ple_on = ss.ple.ready() && ple_stage(); + auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; }; + const int G = (split_ && T >= 2) ? 2 : 1; + static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); }; + const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T}; + groups_[T] = G; + + // ---- the window's inputs, from mapped staging + copy_i32_from_mapped(tok_, m_tok_, T, cs); + copy_i32_from_mapped(step_, m_step_, (int64_t) T * kStepCount, cs); + copy_i32_from_mapped(pos_, m_pos_, (int64_t) MT * (NH + NKV + IQ), cs); + // per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE) + const int32_t* pos_k = pos_ + MT * NH; + const int32_t* pos_i = pos_ + MT * (NH + NKV); + if (ple_on) copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs); + + // ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's + // residual, pending write and inject (see set_stage) + const int64_t HB = Verifier::handoff_floats(g); + if (lb_ > 0) { + for (int t = 0; t < T; ++t) { + copy_from_mapped(Rt(t), hand_in_ + (size_t) t * HB, HC * N, cs); + copy_from_mapped(bo_ + (size_t) t * N, hand_in_ + (size_t) t * HB + HC * N, N, cs); + copy_from_mapped(inj2_ + (size_t) t * HC, hand_in_ + (size_t) t * HB + HC * N + N, HC, cs); + } + } else if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table + ne->gather_dev(tok_, T, emb_, cs); + broadcast_streams(emb_, R_, N, (int) HC, T, cs); + } else { + const WeightRef* w = wt.find("token_embd.weight"); + if (w == nullptr || w->codebook_iq4nl || (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8)) { + err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor"; + return false; + } + const auto* codes = (const uint8_t*) w->data; + const auto* scales = (const float*) (codes + w->codes_bytes); + const auto* offsets = w->has_offset ? (const float*) (codes + w->codes_bytes + w->scales_bytes) : nullptr; + const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits)); + const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems); + embedding_gather_dev(codes, scales, offsets, tok_, T, w->ne0, w->code_bits, w->code_bias, w->group_elems, + row_codes, row_groups, emb_, cs); + broadcast_streams(emb_, R_, N, (int) HC, T, cs); + } + + // per-layer state indices (GDN and QSA layers are numbered separately) + std::vector gdn_idx((size_t) g.n_layers, -1), qsa_idx((size_t) g.n_layers, -1); + { + int64_t qi = 0, gi = 0; + for (int64_t l = 0; l < g.n_layers; ++l) { + if (is_qsa_layer(g, l)) qsa_idx[(size_t) l] = qi++; + else gdn_idx[(size_t) l] = gi++; + } + } + + // ---------------------------------------------------------------- pre(l, group): up to the ring + auto pre = [&](int64_t l, int grp) -> bool { + const int tb = tb_[grp], te = te_[grp], n = te - tb; + stamp(l, 0, grp); + const LayerView v(wt, l); + const char* pfx[2] = {"hc_attn_", "hc_ffn_"}; + const WeightRef *wn[2], *wd[2], *wu[2], *wi[2]; + for (int h = 0; h < 2; ++h) { + wn[h] = need(v, (std::string(pfx[h]) + "norm.weight").c_str(), err); + wd[h] = need(v, (std::string(pfx[h]) + "down.weight").c_str(), err); + wu[h] = need(v, (std::string(pfx[h]) + "up.weight").c_str(), err); + wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err); + if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false; + } + // the previous layer's FFN write, folded into this layer's first read (a control vector after it has + // already applied it) + bool pending = l > 0 && !cvec().covers(l - 1); + if (l == 1 && ple_on) { + float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes()); + for (int t = tb; t < te; ++t) { + gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); + PleOut po; + po.normalized = normalized; + po.result = Rt(t); + try { + ple_block(ple_ + t * N, Rt(t), ss.ple.hist, ss.ple.w, po, ss.ple.scratch, cs); + ple_history_advance(ss.ple.hist, normalized, cs); + } catch (const std::exception& e) { + err = std::string("verify PLE: ") + e.what(); + return false; + } + copy_from_mapped(hist_snap_ + (size_t) t * HS, ss.ple.hist, HS, cs); + } + pending = false; + } + auto gr_read_group = [&](int half, bool apply, float* inj_prev, float* inj_out) { + FusedGrArgs fa[kFusedGrMaxT]; + for (int t = tb; t < te; ++t) { + FusedGrArgs& a = fa[t - tb]; + a.R = Rt(t); a.R_out = Rt(t); a.apply = apply; + a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC; + a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data; + a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data; + a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; + a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N; + } + fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr, + (int) (l * kProfPer + (half == 0 ? 27 : 30))); + }; + gr_read_group(0, pending, inj2_, inj_); + stamp(l, 1, grp); + float* xm = mixed_ + tb * N; + try { + if (!is_qsa_layer(g, l)) { + // ======================= GDN ======================= + const WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err), + *wout = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err), + *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err), + *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err), + *wsa = need(v, "ssm_a", err); + if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false; + if (!native_of(wqkv, v.name("attn_qkv.weight"), err) || !native_of(wg, v.name("attn_gate.weight"), err) || + !native_of(wout, v.name("ssm_out.weight"), err)) + return false; + const int64_t gi = gdn_idx[(size_t) l]; + float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats; + float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + float* qkv = qkv_L_ + (size_t) gi * MT * C; + float* hb = h_L_ + (size_t) gi * MT * C; + float* gate = gate_L_ + (size_t) gi * MT * HV; + float* beta = beta_L_ + (size_t) gi * MT * HV; + native_quantize_q8_1(xm, xq_, (int) N, n, cs); + native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs); + stamp(l, 2, grp); + gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb); + stamp(l, 3, grp); + gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data, + (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV, + n, cs); + stamp(l, 4, grp); + native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs); + stamp(l, 5, grp); + // the recurrence from the untouched state over tokens [0, te); outputs only for this group's + gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, + (int) HV, te, nullptr, cs, tb); + stamp(l, 6, grp); + native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs); + native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs); + } else { + // ======================= QSA ======================= + const int64_t qi = qsa_idx[(size_t) l]; + const QsaState& st = ss.qsa_states[qi]; + const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err), + *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err), + *wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err), + *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err), + *wiqn = need(v, "indexer.q_norm.weight", err), *wikn = need(v, "indexer.k_norm.weight", err); + if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) || + !native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err)) + return false; + auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs); + if (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int)NH, (int)NH, (int)HD, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs); + }; + float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID; + // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the + // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) + const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4; + native_quantize_q8_1(xm, xq_, (int) N, n, cs); + if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs); + else for (int t = tb; t < te; ++t) + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); + stamp(l, 7, grp); + if (!st.without_key) native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); + native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); + if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); + else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) + fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } + if (trace_h_) { + const size_t width = (size_t) NKV * HD; + for (int t = tb; t < te; ++t) { + float* dst = trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width; + if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float), + cudaMemcpyDeviceToHost, cs) != cudaSuccess || + cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float), + cudaMemcpyDeviceToHost, cs) != cudaSuccess) { + err = "verify: keyless trace copy could not be captured"; + return false; + } + } + } + stamp(l, 8, grp); + if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + for (int t = tb; t < te; ++t) { + const int32_t* step_t = step_ + t * kStepCount; + if (st.kv_hybrid) { // K8V4: the unused half's lanes folded onto the used pool (layer.cpp) + kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t, + kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, nullptr); + kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, nullptr); + } else if (st.kv_q4) + kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, kcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, &st.host); + else if (st.kv_int8) + kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_t, + kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host); + else + kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD, + vcur_ + t * NKV * HD, s, cs, &st.host); + } + const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + for (int t = tb; t < te; ++t) + native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, + (const float*) wikn->data, EPS, ib, s, st.max_cells, + rope_scaling(), cs); + stamp(l, 9, grp); + native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), + n, cs); + if (qb) { + if (cudaMemcpy2DAsync(qcur_ + tb * NH * HD, (size_t) HD * 4, qfull_ + tb * NH * 2 * HD, (size_t) HD * 2 * 4, + (size_t) HD * 4, (size_t) (n * NH), cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { + err = "verify: the q/gate split failed"; + return false; + } + norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH); + if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // = + bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID, + N, IQ * ID, n, cs); + norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ); + } else { + for (int t = tb; t < te; ++t) { + float* qc = qcur_ + t * NH * HD; + if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, + (size_t) HD * 4, (size_t) NH, cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { + err = "verify: the q/gate split failed"; + return false; + } + norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH); + if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // = + } + for (int t = tb; t < te; ++t) { + float* qx = qidx_ + t * IQ * ID; + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), cs); + norm_rope(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH); + } + } + stamp(l, 10, grp); + qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_, + s, scores_ + (size_t) tb * max_blocks_, cs); + qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s, + sel_ + (size_t) tb * cap_, cs); + stamp(l, 11, grp); + // KV streaming: the n selections' blocks resident (device-side, inside the graph) + qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs); + stamp(l, 12, grp); + const QsaAttnPools pools = qsa_attn_pools(st); + qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, + s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); + if (trace_q_h_ && tb == 0 && + cudaMemcpyAsync(trace_q_h_ + (size_t) qi * NH * HD, qcur_, + (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) { + err = "verify: keyless query trace copy could not be captured"; + return false; + } + stamp(l, 13, grp); + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, + (int) (n * NH), (int) HD, cs); + else + for (int t = tb; t < te; ++t) { + if (native_qsa_enabled()) + native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, + (int) NH, (int) HD, cs); + else + qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs); + } + stamp(l, 14, grp); + native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs); + native_mmvq(wo->native_type, wo->native_data, xq_, bo_ + tb * N, (int) (NH * HD), (int) N, n, cs); + } + } catch (const std::exception& e) { + err = "verify layer " + std::to_string(l) + ": " + e.what(); + return false; + } + stamp(l, 16, grp); + gr_read_group(1, true, inj_, inj2_); + // the window's rows routed in 2 launches (one router GEMV reading the weight once, one + // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) + const WeightRef* w_router = v.get("ffn_gate_inp.weight"); + if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) { + try { + bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N, + NE, n, cs); + native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs); + } catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; } + } else + for (int t = tb; t < te; ++t) { + MoEBuffers mb = ss.moe; + mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K; + if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false; + } + if (device_plan_) // E-6: every routed expert resident: this group's plan without the host + resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert, + hits_.cache_base, slot_off_d_, (long long) hits_.blob, + plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp, + (uint32_t) ((l - lb_) * G + grp + 1), cs); + doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, + m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); + stamp(l, 17, grp); + { + const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err), + *wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err); + if (!wgi || !wsg || !wsu || !wsd) return false; + if (!native_of(wsg, v.name("ffn_gate_shexp.weight"), err) || !native_of(wsu, v.name("ffn_up_shexp.weight"), err) || + !native_of(wsd, v.name("ffn_down_shexp.weight"), err)) + return false; + NativeSharedWeights nsw; + nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data; + nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data; + nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data; + nsw.q8_1 = xq_; + if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows + else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs); + try { + shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff, + sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs); + } catch (const std::exception& e) { + err = std::string("verify shared expert: ") + e.what(); + return false; + } + } + if (strata::kernels::cpu::expert_layout().native) + quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs); + else + quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs); + stamp(l, 18, grp); + return true; + }; + + // ---------------------------------------------------------------- post(l, group): experts, combine + auto post = [&](int64_t l, int grp) -> bool { + const int tb = tb_[grp], te = te_[grp], n = te - tb; + const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1); + const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K; + int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16); + if (device_plan_) { // E-6: skipped when the device planned this group (all its experts resident) + wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs); + copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs); + } else { + wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan + copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs); + } + stamp(l, 19, grp); + const int32_t* p_counts = pl; + const int32_t* p_start = pl + 4; + const int32_t* p_dst = p_start + capx + 1; + const int32_t* p_tok = p_dst + capx; + const int64_t ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; + const unsigned long long* p_ptr = (const unsigned long long*) (pl + ptr_off); + const unsigned long long* p_ptr2 = p_ptr + capx; + const int32_t* p_start2 = pl + ptr_off + 4 * capx; + float* hit_out = hit_out_ + (size_t) tb * K * N; + const auto& lay = strata::kernels::cpu::expert_layout(); + // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging + auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn) { + if (lay.native) { + // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) + const auto& f = lay.fmt[(size_t) l]; + const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff); + native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap, + nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, hit_out, cs); + } else { + moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34, + hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, hit_out, cs); + } + }; + grouped(p_ptr, p_start, p_counts); + stamp(l, 20, grp); + if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); + else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped + if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging + const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; + uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob; + fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs); + rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs); + } + stamp(l, 21, grp); + grouped(p_ptr2, p_start2, p_counts + 2); + stamp(l, 22, grp); + if (device_plan_) { // no CPU share when the device planned the group: its rows are zeros + wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs); + copy_or_zero_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N, + skip_ + grp, ring, cs); + } else { + wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows + stamp(l, 23, grp); + if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows) + copy_rows_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N, + p_dst, p_counts + 1, cs); + else + copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs); + } + moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs); + if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows + try { + native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs); + } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; } + } else + for (int t = tb; t < te; ++t) { + MoEBuffers mb = ss.moe; + mb.weights = w_ + t * K; mb.shared = shared_ + t * N; + if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false; + } + stamp(l, 24, grp); + if (l == g.n_layers - 1) { + for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs); + if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs); + } else if (cvec().covers(l)) { + cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs); + } + return true; + }; + + for (int grp = 0; grp < G; ++grp) + if (!pre(lb_, grp)) return false; + for (int64_t l = lb_; l < le_; ++l) + for (int grp = 0; grp < G; ++grp) { + if (!post(l, grp)) return false; + if (l + 1 < le_ && !pre(l + 1, grp)) return false; + } + if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head + for (int t = 0; t < T; ++t) { + copy_from_mapped(hand_out_ + (size_t) t * HB, Rt(t), HC * N, cs); + copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N, bo_ + (size_t) t * N, N, cs); + copy_from_mapped(hand_out_ + (size_t) t * HB + HC * N + N, inj2_ + (size_t) t * HC, HC, cs); + } + return true; + } + + // ---- the head, T columns, and the argmax of each + stamp(g.n_layers, 0, 0); + { + const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"), + *hu = wt.find("output_hc_up.weight"); + if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; } + for (int t = 0; t < T; ++t) { + BlockBuffers bb = ss.block; + bb.R = Rt(t); + bb.mixed = head_mixed_ + t * N; + if (head_ != nullptr && head_->loaded()) { + if (!lm_head_mix(wt, g, bb, cs, err)) return false; + } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) { + return false; + } + } + if (head_ != nullptr && head_->loaded()) { + try { + native_quantize_q8_1(head_mixed_, xq_, (int) N, T, cs); + native_mmvq(head_->type(), head_->weights(), xq_, head_logits_, (int) N, (int) n_vocab_, T, cs); + } catch (const std::exception& e) { + err = std::string("verify head: ") + e.what(); + return false; + } + } + // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that + // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a + // fresh draw counter: a captured sampler would bake them in and replay the same draws forever. + SamplerParams sp; + sp.greedy = true; + sp.temperature = 0.0f; + sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs); + } + stamp(g.n_layers, 1, 0); + return true; +} + +std::string Verifier::profile_report() { + if (!prof_on_ || prof_windows_ == 0) return std::string(); + static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx", + "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", + "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant", + "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", + "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", "", ""}; + std::string out; + char b[80]; + double total = 0; + for (int k = 0; k < 2; ++k) { + out += k == 0 ? " GDN layers:" : " | QSA layers:"; + for (int i = 0; i < kProfPer; ++i) { + if (prof_sum_[k][i] <= 0) continue; + total += prof_sum_[k][i]; + std::snprintf(b, sizeof b, " %s %.2f", names[i], prof_sum_[k][i] / 1e6 / (double) prof_windows_); + out += b; + } + } + std::snprintf(b, sizeof b, " | total %.2f ms/window over %lld windows", total / 1e6 / (double) prof_windows_, (long long) prof_windows_); + out += b; + for (auto& r : prof_sum_) for (double& d : r) d = 0; + prof_windows_ = 0; + return out; +} + +bool Verifier::capture(int T, std::string& err) { + if (exec_[T] != nullptr) return true; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { + err = "verify: begin capture failed"; + return false; + } + std::string rerr; + const bool ok = record_window(T, cs_, rerr); + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); + if (!ok) { + if (graph) cudaGraphDestroy(graph); + err = rerr; + return false; + } + if (ce != cudaSuccess) { + err = std::string("verify: end capture: ") + cudaGetErrorString(ce); + return false; + } +#if !defined(STRATA_USE_HIP) // a CUDA debug listing (node types, kernel names) + if (std::getenv("STRATA_VERIFY_NODES") != nullptr) { // what the window graph holds + size_t nn = 0; + cudaGraphGetNodes(graph, nullptr, &nn); + std::vector nodes(nn); + cudaGraphGetNodes(graph, nodes.data(), &nn); + std::map kinds; + for (cudaGraphNode_t nd : nodes) { + cudaGraphNodeType ty; + cudaGraphNodeGetType(nd, &ty); + std::string name = "type" + std::to_string((int) ty); + if (ty == cudaGraphNodeTypeKernel) { + cudaKernelNodeParams kp{}; + if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) { +#if CUDART_VERSION >= 12030 // cudaFuncGetName arrived in CUDA 12.3 + const char* fn = nullptr; + if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn; +#endif + } + } else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy"; + else if (ty == cudaGraphNodeTypeMemset) name = "memset"; + ++kinds[name]; + } + std::vector> v; + for (auto& [k2, c] : kinds) v.push_back({c, k2}); + std::sort(v.rbegin(), v.rend()); + std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn); + for (size_t i = 0; i < v.size() && i < 40; ++i) std::fprintf(stderr, " %d x %.60s;", v[i].first, v[i].second.c_str()); + std::fprintf(stderr, "\n"); + } +#endif + const cudaError_t ie = cudaGraphInstantiate(&exec_[T], graph, 0); + cudaGraphDestroy(graph); + if (ie != cudaSuccess) { + err = std::string("verify: instantiate: ") + cudaGetErrorString(ie); + return false; + } + const cudaError_t ue = cudaGraphUpload(exec_[T], cs_); + const cudaError_t us = cudaStreamSynchronize(cs_); + std::fprintf(stderr, "strata verify: captured the %d-token window (upload %s, sync %s)\n", T, + cudaGetErrorString(ue), cudaGetErrorString(us)); + return true; +} + +bool Verifier::capture_commit(std::string& err) { + if (commit_exec_ != nullptr) return true; + using namespace strata::kernels; + const ModelGeometry& g = *g_; + SessionState& ss = *ss_; + const QsaShapes s = shapes_of(g); + const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ID = g.idx_key_dim, MT = max_t_; + const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); + const int64_t TS = (s.idx_block - 1) * ID; + const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { + err = "verify: begin commit capture failed"; + return false; + } + bool ok = true; + try { + copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_); + int64_t qsa_index = 0, gdn_index = 0; + for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; + for (int64_t l = lb_; l < le_ && ok; ++l) { + const LayerView v(*wt_, l); + if (!is_qsa_layer(g, l)) { + const WeightRef* wnm = need(v, "ssm_norm.weight", err); + if (!wnm) { ok = false; break; } + float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats; + float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C; + gdn_conv_commit(conv, qkv, (int) C, commit_, cs_); + gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV, + beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_, + (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_); + ++gdn_index; + } else { + const QsaState& st = ss.qsa_states[qsa_index]; + const WeightRef* wikn = need(v, "indexer.k_norm.weight", err); + if (!wikn) { ok = false; break; } + copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_); + const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + for (int64_t t = 0; t < MT; ++t) + native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0, + (const float*) wikn->data, EPS, ib, s, st.max_cells, + rope_scaling(), cs_); + ++qsa_index; + } + } + if (ok && ss.ple.ready() && ple_stage()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_); + } catch (const std::exception& e) { + err = std::string("verify commit: ") + e.what(); + ok = false; + } + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); + if (!ok) { + if (graph) cudaGraphDestroy(graph); + return false; + } + if (ce != cudaSuccess || cudaGraphInstantiate(&commit_exec_, graph, 0) != cudaSuccess) { + if (graph) cudaGraphDestroy(graph); + err = std::string("verify: commit capture: ") + cudaGetErrorString(ce); + return false; + } + cudaGraphDestroy(graph); + return true; +} + +bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, + std::string& err) { + using namespace strata::kernels; + const OnDevice on_device(device_); + if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } + if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } + const ModelGeometry& g = *g_; + SessionState& ss = *ss_; + if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } + if (!capture(T, err) || !capture_commit(err)) return false; + VDBG("captured; staging\n"); + const Clock::time_point t0 = Clock::now(); + const QsaShapes s = shapes_of(g); + for (int t = 0; t < T; ++t) { + h_tok_[t] = tokens[t]; + qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s); + for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) (pos0 + t); + int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head; + int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv; + for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) (pos0 + t); + for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) (pos0 + t); + } + if (ss.ple.ready() && ple_stage()) { + uint32_t rows[kVerifyMaxT * PLE_N_HEADS]; + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + for (int t = 0; t < T; ++t) { + ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows + t * PLE_N_HEADS); + prev[0] = prev[1]; + prev[1] = tokens[t]; + } + if (!ss.ple.table->gather_batch(rows, (size_t) T, h_ple_, err)) return false; + } + *(volatile uint32_t*) h_seq_ = 0; + *(volatile uint32_t*) h_flag_ = 0; + *(volatile uint32_t*) h_flagA_ = 0; + *(volatile uint32_t*) h_flagB_ = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + last_t_ = T; + last_pos0_ = pos0; + for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t]; + ms_host += ms_since(t0); + VDBG("staged; launching\n"); + const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } + (void) cudaStreamQuery(cs_); + VDBG("launched\n"); + volatile uint32_t* const seq = h_seq_; + volatile uint32_t* const flag = h_flag_; + const int G = groups_[T] > 0 ? groups_[T] : 1; + const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; + const int64_t steps = (le_ - lb_) * G; + const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false) + for (int64_t k = 0; k < steps; ++k) { + const int64_t l = lb_ + k / G; + const int grp = (int) (k % G); + const uint32_t want = (uint32_t) (k + 1); + const Clock::time_point a = Clock::now(); + auto last_flush = a; + uint32_t spins = 0; + progress_at("verify window: waiting for the GPU to reach layer", l); + while (*seq < want) { + _mm_pause(); + if ((++spins & 1023u) != 0) continue; + const auto now = Clock::now(); + if (now - last_flush > std::chrono::microseconds(2000)) { + last_flush = now; + const cudaError_t q = cudaStreamQuery(cs_); + if (q != cudaErrorNotReady && *seq < want) { + err = "verify: layer " + std::to_string(l) + " never rang (" + + (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; + return false; + } + } + if (now - a > std::chrono::seconds(20)) { + // #267: the caller ends the engine; no spin kernel may outlive it + err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000)); + return false; + } + } + const Clock::time_point b = Clock::now(); + VDBG("layer %lld rang\n", (long long) l); + cur_layer_ = want - 1; + set_plan_slot(grp); + const int tb = gtb[grp], n = gte[grp] - gtb[grp]; + progress_at("verify window: the CPU experts of layer", l); + if (pool != nullptr) + pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k, + h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l); + VDBG("layer %lld served\n", (long long) l); + progress_tick(); + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one + sink_.counts[0] = 0; + sink_.counts[1] = 0; + sink_.counts[2] = 0; + sink_.start[0] = 0; + sink_.start2[0] = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + *(volatile uint32_t*) h_flagA_ = want; + raise_flag(h_flagB_, want); + } + if (!(test_stall && k + 1 == steps)) *flag = want; + ms_wait += std::chrono::duration(b - a).count(); + ms_pool += ms_since(b); + } + progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T); + // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall + // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no + // spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle. The wait + // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver + // beside the expert workers). + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } + if (trace_file_) { + const uint32_t count = (uint32_t) T; + const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim; + bool written = std::fwrite(&count, sizeof(count), 1, trace_file_) == 1 && + std::fwrite(&pos0, sizeof(pos0), 1, trace_file_) == 1; + for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q) + for (int t = 0; written && t < T; ++t) + written = std::fwrite(trace_h_ + ((size_t) q * max_t_ + t) * 2 * width, + sizeof(float), 2 * width, trace_file_) == 2 * width; + if (!written || std::fflush(trace_file_) != 0) { + err = "verify: cannot write keyless activation trace"; + return false; + } + const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim; + bool q_written = std::fwrite(&count, sizeof(count), 1, trace_q_file_) == 1 && + std::fwrite(&pos0, sizeof(pos0), 1, trace_q_file_) == 1 && + std::fwrite(trace_q_h_, sizeof(float), + (size_t) g_->n_qsa_layers() * query_width, trace_q_file_) == + (size_t) g_->n_qsa_layers() * query_width; + if (!q_written || std::fflush(trace_q_file_) != 0) { + err = "verify: cannot write keyless query trace"; + return false; + } + } + progress_at("verify window: waiting for the expert copies", (int64_t) T); + cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one + if (prof_on_ && G == 1) { // the window's GPU stage stamps + cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost); + const int64_t L = g.n_layers; + auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; }; + // D8: the derived columns below read stamps the hc-read kernels write themselves or the next + // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - + // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now + // contributes nothing. + const auto gap = [](unsigned long long to, unsigned long long from) { + return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0; + }; + for (int64_t l = 0; l < L; ++l) { + const int kind = is_qsa_layer(g, l) ? 1 : 0; + unsigned long long prev = at(l, 0); + for (int i = 1; i <= 24; ++i) { + const unsigned long long x = at(l, i); + if (x == 0 || x < prev) continue; + prof_sum_[kind][i] += (double) (x - prev); + prev = x; + } + if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); + const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28)); + if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice + prof_sum_[kind][27] += dn; // hc-read0: norm + prof_sum_[kind][28] += dd; // down + prof_sum_[kind][29] += du; // up (through both halves, as before) + prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split) + } + } + prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); + ++prof_windows_; + } + // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's + // own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to + // the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever + // the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw. + if (le_ < g.n_layers) { // a layer split's earlier stage: the hand-off is written (synced above) + ++windows; + return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err); + } + const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; + if (head_sampling_ && (sampled || hist_d_ != nullptr)) { + SamplerParams sp = sampling_; + sp.counter = (uint64_t) pos0; + sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); + if (cudaStreamSynchronize(cs_) != cudaSuccess) { // m_out_ is the mapped h_out_: synced, it is readable + err = "verify: the head sampling failed"; + return false; + } + } + for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; + if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { // debug: the first non-finite head + static bool reported = false; + if (!reported) { + std::vector h((size_t) T * (size_t) n_vocab_); + cudaMemcpy(h.data(), head_logits_, h.size() * 4, cudaMemcpyDeviceToHost); + for (int t = 0; t < T && !reported; ++t) { + int64_t bad = 0; + for (int64_t v = 0; v < n_vocab_; ++v) bad += !std::isfinite(h[(size_t) t * n_vocab_ + v]); + if (bad) { + reported = true; + std::fprintf(stderr, "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite " + "(token out %d)\n", (long long) pos0, t, (long long) bad, (long long) n_vocab_, out[t]); + } + } + } + } + VDBG("window done\n"); + ++windows; + progress_at("decode"); + progress_beat(); + return true; +} + +void Verifier::set_plan_slot(int grp) { + const int64_t cap = sink_.cap; + int32_t* base = h_plan_ + (size_t) grp * (size_t) plan_i32_; + const int64_t i32 = 4 + (cap + 1) + cap + cap; + const int64_t ptr_off = (i32 + 1) & ~1ll; + sink_.counts = base; + sink_.start = base + 4; + sink_.dst = sink_.start + cap + 1; + sink_.tok = sink_.dst + cap; + sink_.ptr = (unsigned long long*) (base + ptr_off); + sink_.ptr2 = sink_.ptr + cap; + sink_.start2 = base + ptr_off + 4 * cap; + const int G = groups_[last_t_] > 0 ? groups_[last_t_] : 1; + const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; + sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob); + sink_.staging_cap = per; +} + +// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. +void Verifier::raise_flag(uint32_t* flag, uint32_t value) { + volatile long* f = (volatile long*) flag; +#if defined(_WIN32) + long cur = *f; + while ((uint32_t) cur < value) { + const long prev = _InterlockedCompareExchange(f, (long) value, cur); + if (prev == cur) break; + cur = prev; + } +#else + uint32_t cur = __atomic_load_n((uint32_t*) flag, __ATOMIC_SEQ_CST); + while (cur < value && !__atomic_compare_exchange_n((uint32_t*) flag, &cur, value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {} +#endif +} + +// Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the +// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe +// groups). Staging is split between the two token groups of a split window. +void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) { + Verifier* v = (Verifier*) ctx; + const uint32_t want = v->cur_layer_ + 1; + if (n <= 0) { raise_flag(v->h_flagB_, want); return; } + uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window + for (int i = 0; i < n; ++i) cudaMemcpyAsync(stage + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, v->copy_); + FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])]; + fs.flag = v->h_flagB_; + fs.value = want; + cudaLaunchHostFunc(v->copy_, [](void* p) { FlagSet* s = (FlagSet*) p; raise_flag(s->flag, s->value); }, &fs); +} + +void Verifier::publish_plan(void* ctx) { + Verifier* v = (Verifier*) ctx; + _mm_sfence(); + *(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1; +} + +bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out, + std::string& err) { + if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err); + const OnDevice on_device(device_); + if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) { + err = "window_logprobs: no head logits for this window"; + return false; + } + // run() synchronized cs_ before returning, so the head of this window is complete + std::vector h((size_t) T * (size_t) n_vocab_); + if (cudaMemcpy(h.data(), head_logits_, h.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { + err = "window_logprobs: the head logits copy failed"; + return false; + } + for (int t = 0; t < T; ++t) { + const float* row = h.data() + (size_t) t * (size_t) n_vocab_; + const int32_t tgt = targets[t]; + if (tgt < 0 || (int64_t) tgt >= n_vocab_) continue; + int64_t top = 0; + for (int64_t v = 1; v < n_vocab_; ++v) + if (row[v] > row[top]) top = v; + const double maxv = row[top]; + const bool has_extra = extra_id >= 0 && (int64_t) extra_id < n_vocab_; + double sum = 0.0, sum_without = 0.0; // the second skips extra_id: no cancellation when it holds ~all mass + for (int64_t v = 0; v < n_vocab_; ++v) { + const double e = std::exp((double) row[v] - maxv); + sum += e; + if (v != (int64_t) extra_id) sum_without += e; + } + const double lse = maxv + std::log(sum); + const double extra = has_extra ? (double) row[extra_id] - lse : NAN; + const double without = has_extra && tgt != extra_id && sum_without > 0.0 + ? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN; + std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt, + (double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra, + without); + // STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a + // top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md) + static const int topk = [] { + const char* v = std::getenv("STRATA_LOGPOS_TOPK"); + return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0; + }(); + if (topk > 0) { + std::vector order((size_t) n_vocab_); + for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v; + std::partial_sort(order.begin(), order.begin() + topk, order.end(), + [&](int32_t a, int32_t b) { return row[a] > row[b]; }); + for (int j = 0; j < topk; ++j) + std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse); + } + std::fprintf(out, "\n"); + } + std::fflush(out); + return true; +} + +namespace { bool g_commit_async = false; } +void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; } + +bool Verifier::commit(int n_keep, std::string& err) { + const OnDevice on_device(device_); + if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } + const Clock::time_point t0 = Clock::now(); + h_commit_[0] = n_keep; + h_commit_[1] = n_keep - 1; + for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; + std::atomic_thread_fence(std::memory_order_seq_cst); + const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_); + if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } + // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own + // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's + // results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). + if (!g_commit_async || next_ != nullptr) { + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } else { + const cudaError_t re = cudaEventRecord(commit_done_, cs_); + if (re != cudaSuccess) { err = std::string("verify: commit event: ") + cudaGetErrorString(re); return false; } + commit_pending_ = true; + } + if (ple_stage()) // stages that share one session must advance it once + for (int t = 0; t < n_keep; ++t) { + ss_->ple_prev[0] = ss_->ple_prev[1]; + ss_->ple_prev[1] = last_tokens_[t]; + } + ms_commit += ms_since(t0); + return next_ == nullptr || next_->commit(n_keep, err); +} + +bool Verifier::wait_commit(std::string& err) { + if (commit_pending_) { + const OnDevice on_device(device_); + commit_pending_ = false; + const cudaError_t se = cudaEventSynchronize(commit_done_); + if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; } + } + return next_ == nullptr || next_->wait_commit(err); +} + +bool Verifier::copy_logits(int t, float* host) const { + if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage + if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; + return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float), + cudaMemcpyDeviceToHost) == cudaSuccess; +} + +} // namespace strata::core diff --git a/engine/strata/src/core/weights.cpp b/engine/strata/src/core/weights.cpp new file mode 100644 index 00000000..8b42f84f --- /dev/null +++ b/engine/strata/src/core/weights.cpp @@ -0,0 +1,479 @@ +// src/core/weights.cpp - the dense-weight loader. See the header for the engine-vs-pack distinction. +#include "strata/core/weights.hpp" + +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#endif + +namespace strata::core { +namespace { + +constexpr uint64_t CHUNK = 8ull << 20; // 8 MiB of SOURCE per staging round + +double now_ms() { + using namespace std::chrono; + return duration(steady_clock::now().time_since_epoch()).count(); +} + +struct IndexRow { + std::string name; + int file = 0; + WeightKind kind = WeightKind::Verbatim; + uint64_t src_off = 0, src_bytes = 0, dst_off = 0, dst_bytes = 0; + int64_t ne0 = 0, ne1 = 0; + int code_bits = 0, code_bias = 0, group_elems = 0, codebook = 0, has_offset = 0; + uint64_t codes_bytes = 0, scales_bytes = 0, offset_bytes = 0; + int scales_fp16 = 0; + int act_kind = 0; + bool raw16 = false; ///< plan v0.3 P6: already 16-bit in the file (kinds 4/5) +}; + +/// How a segment's bytes must be transformed on the way from the pack to the arena. +enum class Conv : int { + Copy = 0, ///< the bytes are already the engine form + Bf16High = 1, ///< f32 container holding a bf16 value: take the high 16 bits + ToF16 = 2, ///< f32 container holding an f16 value: a real round-to-nearest-even conversion + WidenF16 = 3, ///< fp16 bits to be held as f32: EXACT, and the reason this path exists at all +}; + +/// One contiguous run of a tensor's source span with a single destination range and one transform. +/// +/// THE SEGMENT LIST IS WHY THIS LOADER CAN CHANGE WIDTHS PLANE BY PLANE. A quantized tensor used to be one +/// verbatim span, which is only correct when every plane is already in engine form - and for 90 of the 303 +/// quantized tensors the scale plane is fp16 in the pack and must be f32 in the arena. +struct Seg { + uint64_t src_off = 0; ///< relative to the row's src_off + uint64_t src_bytes = 0; + uint64_t dst_off = 0; ///< relative to the row's dst_off + uint64_t dst_bytes = 0; + Conv conv = Conv::Copy; +}; + +const char* file_name(int id) { + switch (id) { + case 0: return "dense.bin"; + case 1: return "embd.bin"; + case 2: return "experts.bin"; + case 3: return "extra.bin"; // plan v0.3 P6: a native pack's float tensors that the base pack quantized + default: return nullptr; + } +} + +/// UTF-16 path for CreateFile-free portability: the loader uses `std::fopen`, which on Windows takes an ANSI +/// path. The pack lives beside the executable in practice, but a pack under a user directory with a +/// non-ASCII name would silently fail to open, so the caller gets the errno rather than a null pointer. +bool read_at(std::FILE* f, uint64_t off, void* dst, size_t n, std::string& err, const char* what) { +#if defined(_WIN32) + if (_fseeki64(f, (long long) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; } +#else + if (fseeko(f, (off_t) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; } +#endif + if (std::fread(dst, 1, n, f) != n) { err = std::string(what) + ": short read"; return false; } + return true; +} + +} // namespace + +bool WeightTable::pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err, + const std::set* skip) { + const std::string path = pack_dir + "/index.txt"; + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) { err = "cannot open " + path; return false; } + char line[1024]; + out = 0; + uint64_t pool = 0, compact = 0; + int align = 0; + while (std::fgets(line, sizeof line, f)) { + if (line[0] == '#') { + unsigned long long p = 0; + int a = 0, tensors = 0; + if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &tensors) == 3) { pool = p; align = a; } + continue; + } + if (skip == nullptr) continue; + char name[256] = {0}; + unsigned long long dst_bytes = 0, dummy = 0; + int i1 = 0, i2 = 0; + if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu", name, &i1, &i2, &dummy, &dummy, &dummy, &dst_bytes) != 7) + continue; + if (skip->count(name)) continue; + const uint64_t a = align > 0 ? (uint64_t) align : 256; + compact += (dst_bytes + a - 1) / a * a; + } + std::fclose(f); + if (pool == 0) { err = "no '# align ... pool ...' header in " + path; return false; } + out = skip ? compact : pool; + return true; +} + +bool WeightTable::index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits, + std::string& err) { + const std::string path = pack_dir + "/index.txt"; + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) { err = "cannot open " + path; return false; } + char line[1024]; + code_bits = -1; + while (std::fgets(line, sizeof line, f)) { + if (line[0] == '#') continue; + char row[256] = {0}; + unsigned long long dummy = 0; + long long ne = 0; + int i1 = 0, i2 = 0, bits = 0; + // the first ten fields of the row `load` parses: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits + if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu %lld %lld %d", row, &i1, &i2, &dummy, &dummy, &dummy, + &dummy, &ne, &ne, &bits) != 10) + continue; + if (name == row) { code_bits = bits; break; } + } + std::fclose(f); + return true; +} + +bool WeightTable::load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err, + const std::set* skip) { + const std::string path = pack_dir + "/index.txt"; + std::FILE* idx = std::fopen(path.c_str(), "rb"); + if (!idx) { err = "cannot open " + path + " (run tools/pack_index.py)"; return false; } + + uint64_t pool = 0; + int align = 0; + std::vector rows; + char line[1024]; + while (std::fgets(line, sizeof line, idx)) { + if (line[0] == '#') { + unsigned long long p = 0; + int a = 0, t = 0; + if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &t) == 3) { pool = p; align = a; } + continue; + } + IndexRow r; + char name[256] = {0}; + int kind = 0; + // The format is written by tools/pack_index.py and is space-separated with no quoting; a name with a + // space in it would break the parse, which is why the parser REFUSES rather than taking what it got. + const int n = std::sscanf(line, + "%255s %d %d %llu %llu %llu %llu %lld %lld %d %d %d %d %d %llu %llu %llu %d %d", + name, &r.file, &kind, &r.src_off, &r.src_bytes, &r.dst_off, &r.dst_bytes, + &r.ne0, &r.ne1, &r.code_bits, &r.code_bias, &r.group_elems, &r.codebook, + &r.has_offset, &r.codes_bytes, &r.scales_bytes, &r.offset_bytes, + &r.scales_fp16, &r.act_kind); + if (n != 19) { + // A malformed index line is a WRONG BYTE OFFSET waiting to happen, and a wrong offset decodes to + // a plausible weight. Refuse loudly instead of loading the rows that happened to parse. + err = "index.txt: could not parse a row (" + std::to_string(n) + " of 19 fields)"; + std::fclose(idx); + return false; + } + r.name = name; + // plan v0.3 P6: a standalone native pack (tools/iq_pack.py) stores 16-bit floats as they are in the GGUF: + // index kinds 4 (BF16) and 5 (F16) are copied and take the engine forms of kinds 1 and 3 + if (kind == 4 || kind == 5) { + r.raw16 = true; + kind = kind == 4 ? (int) WeightKind::Bf16InF32 : (int) WeightKind::F16InF32; + } + r.kind = (WeightKind) kind; + rows.push_back(r); + } + std::fclose(idx); + + if (pool == 0 || rows.empty()) { err = "index.txt has no header or no rows"; return false; } + // Plan v0.3 P1: a skip set compacts the arena. Kept rows are re-placed in index order at the index's + // alignment; skipped rows keep their metadata and get no bytes. + std::vector skipped(rows.size(), false); + if (skip != nullptr) { + const uint64_t a = align > 0 ? (uint64_t) align : 256; + uint64_t at = 0; + for (size_t i = 0; i < rows.size(); ++i) { + if (skip->count(rows[i].name)) { skipped[i] = true; continue; } + rows[i].dst_off = at; + at += (rows[i].dst_bytes + a - 1) / a * a; + } + pool = at; + } + if (arena_bytes < pool) { + err = "arena is " + std::to_string(arena_bytes) + " B but the index needs " + std::to_string(pool); + return false; + } + + // Two pinned staging buffers, both reused. Pinned because a 5 GB pageable upload spends its time in the + // driver copying through a bounce buffer, and bounded by CHUNK rather than by the largest tensor. + // + // STAGE_OUT IS NOT OPTIONAL. The first version of this loop converted the values straight into the + // destination pointer - which is DEVICE memory - from host code. A host write to a device address is + // undefined behaviour, and on this driver it does not fault: it corrupts whatever the address maps to in + // the host's own space, which is nothing at all, so the tensor would have loaded as the UNCONVERTED pack + // bytes and every BF16 weight would have been read as 32-bit garbage. Converted data goes to a host + // buffer and crosses the bus once. + // + // STAGE_OUT IS TWICE STAGE_IN because a conversion can now GROW: widening an fp16 scale plane to f32 + // doubles it. Sized at CHUNK it would have written 8 MiB past the end of a pinned allocation for every + // one of the 90 widened tensors - a heap corruption that would have been blamed on whatever ran next. + void* stage_in = nullptr; + void* stage_out = nullptr; + if (cudaHostAlloc(&stage_in, CHUNK, cudaHostAllocDefault) != cudaSuccess || + cudaHostAlloc(&stage_out, CHUNK * 2, cudaHostAllocDefault) != cudaSuccess) { + err = "cudaHostAlloc for the staging buffers failed"; + if (stage_in) cudaFreeHost(stage_in); + if (stage_out) cudaFreeHost(stage_out); + return false; + } + + uint8_t* dst_base = (uint8_t*) arena_base; + std::FILE* cur = nullptr; + int cur_file = -1; + table_.clear(); + report_ = LoadReport{}; + + const double t_read0 = now_ms(); + double upload_ms = 0; + for (size_t row_i = 0; row_i < rows.size(); ++row_i) { + const IndexRow& r = rows[row_i]; + if (skipped[row_i]) { + WeightRef wr; + wr.data = nullptr; + wr.resident = false; + wr.bytes = r.dst_bytes; + wr.ne0 = r.ne0; + wr.ne1 = r.ne1; + wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1); + wr.kind = r.kind; + wr.code_bits = r.code_bits; + wr.code_bias = r.code_bias; + wr.group_elems = r.group_elems; + wr.codebook_iq4nl = r.codebook != 0; + wr.has_offset = r.has_offset != 0; + wr.codes_bytes = r.codes_bytes; + wr.scales_bytes = r.scales_bytes; + wr.offset_bytes = r.offset_bytes; + wr.src_off = r.src_off; + wr.src_bytes = r.src_bytes; + wr.file_id = r.file; + wr.scales_fp16 = r.scales_fp16 != 0; + wr.act_kind = r.act_kind; + table_[r.name] = wr; + ++report_.tensors; + continue; + } + if (r.code_bits != 0 && r.dst_bytes == 0) { + // plan v0.3 P6: a native pack's row that carries a shape only - the GGUF form must serve it + err = r.name + ": this pack holds the tensor only in its GGUF form (run with --native SHARD1)"; + cudaFreeHost(stage_in); cudaFreeHost(stage_out); + return false; + } + if (r.file != cur_file) { + if (cur) std::fclose(cur); + const char* fn = file_name(r.file); + const std::string p = pack_dir + "/" + (fn ? fn : "?"); + cur = std::fopen(p.c_str(), "rb"); + if (!cur) { err = "cannot open " + p; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } + cur_file = r.file; + } + + // ---- the segment list: what this tensor's bytes are, plane by plane, in both forms + Seg segs[3]; + int n_segs = 0; + bool bad = false; + uint64_t sum_src = 0, sum_dst = 0; + if (r.codes_bytes != 0) { + // A quantized tensor: codes, then scales, then the optional offset plane, each contiguous in the + // source span in that order (pack_index.py verifies the contiguity and refuses otherwise). + segs[n_segs++] = Seg{0, r.codes_bytes, 0, r.codes_bytes, Conv::Copy}; + if (r.scales_bytes) { + const uint64_t src_scale_bytes = r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes; + if (r.scales_fp16 && (r.scales_bytes % 2 || src_scale_bytes * 2 != r.scales_bytes)) { + err = r.name + ": an fp16 scale plane of an odd byte count"; + bad = true; + } + segs[n_segs++] = Seg{r.codes_bytes, src_scale_bytes, r.codes_bytes, r.scales_bytes, + r.scales_fp16 ? Conv::WidenF16 : Conv::Copy}; + } + if (r.offset_bytes) { + const uint64_t after = r.codes_bytes + (r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes); + segs[n_segs++] = Seg{after, r.offset_bytes, r.codes_bytes + r.scales_bytes, r.offset_bytes, + Conv::Copy}; + } + } else { + // Everything else is one run whose transform is the row's kind. The two promoted types shrink + // 4 B/elem to 2; the rest are already the engine form. + Conv c = Conv::Copy; + if (r.raw16) c = Conv::Copy; + else if (r.kind == WeightKind::Bf16InF32) c = Conv::Bf16High; + else if (r.kind == WeightKind::F16InF32) c = Conv::ToF16; + const uint64_t elems = (uint64_t) r.ne0 * (uint64_t) (r.ne1 > 0 ? r.ne1 : 1); + if (c != Conv::Copy && (r.src_bytes != elems * 4 || r.dst_bytes != elems * 2)) { + // A promoted type is 4 B/elem in and 2 B/elem out, and nothing else. If those two numbers do + // not say so, the shape and the byte counts disagree and the element count this loop would + // use to walk the source is not the element count the pack wrote. + char buf[320]; + std::snprintf(buf, sizeof buf, + "%s: a promoted tensor of %llu elements is %llu B in and %llu B out, not %llu/%llu", + r.name.c_str(), (unsigned long long) elems, (unsigned long long) r.src_bytes, + (unsigned long long) r.dst_bytes, (unsigned long long) (elems * 4), + (unsigned long long) (elems * 2)); + err = buf; + bad = true; + } + segs[n_segs++] = Seg{0, r.src_bytes, 0, r.dst_bytes, c}; + } + for (int i = 0; i < n_segs; ++i) { sum_src += segs[i].src_bytes; sum_dst += segs[i].dst_bytes; } + // The segment list is this loop's own idea of the layout, and it is the ONLY thing standing between a + // mis-sized plane and a wrong byte offset. It is checked against both recorded totals, not trusted. + if (!bad && (sum_src != r.src_bytes || sum_dst != r.dst_bytes)) { + char buf[360]; + std::snprintf(buf, sizeof buf, + "%s: the segments cover %llu/%llu B but the index says %llu/%llu - the plane layout " + "this loader built is not the one the index describes", + r.name.c_str(), (unsigned long long) sum_src, (unsigned long long) sum_dst, + (unsigned long long) r.src_bytes, (unsigned long long) r.dst_bytes); + err = buf; + bad = true; + } + if (bad) { cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } + + for (int si = 0; si < n_segs; ++si) { + const Seg& s = segs[si]; + const bool widening = (s.conv == Conv::WidenF16); + if (widening && (s.src_bytes & 1ull)) { + err = r.name + ": an fp16 plane with an odd source byte count"; + cudaFreeHost(stage_in); cudaFreeHost(stage_out); + return false; + } + uint64_t done = 0; + while (done < s.src_bytes) { + uint64_t n = std::min(CHUNK, s.src_bytes - done); + // WIDENING NEVER SPLITS AN ELEMENT. CHUNK is even, so a full chunk cannot, but the tail of a + // plane whose length is odd would - and half an fp16 is a plausible-looking scale. + if (widening && (n & 1ull)) { + if (n == 1) { err = r.name + ": an fp16 plane ending on a half element"; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; } + n -= 1; + } + if (!read_at(cur, r.src_off + s.src_off + done, stage_in, (size_t) n, err, r.name.c_str())) { + cudaFreeHost(stage_in); cudaFreeHost(stage_out); + return false; + } + const uint8_t* src = (const uint8_t*) stage_in; + const void* host_src = src; + uint64_t out_bytes = n; + uint64_t out_at = s.dst_off + done; + + switch (s.conv) { + case Conv::Copy: + break; + case Conv::Bf16High: { + // THE HIGH 16 BITS ARE THE BF16 ENCODING, exactly - not a rounding. A bf16 value is + // the top half of its f32 image, and the pack promoted it without changing it, so + // this is a copy with a stride. + const uint64_t elems = n / 4; + out_bytes = elems * 2; + uint8_t* o = (uint8_t*) stage_out; + for (uint64_t i = 0; i < elems; ++i) { + uint32_t v; + std::memcpy(&v, src + i * 4, 4); + const uint16_t h = (uint16_t) (v >> 16); + std::memcpy(o + i * 2, &h, 2); + } + host_src = stage_out; + out_at = s.dst_off + done / 2; + break; + } + case Conv::ToF16: { + const uint64_t elems = n / 4; + out_bytes = elems * 2; + uint8_t* o = (uint8_t*) stage_out; + for (uint64_t i = 0; i < elems; ++i) { + float v; + std::memcpy(&v, src + i * 4, 4); + const uint16_t h = strata::kernels::f16_from_f32(v); + std::memcpy(o + i * 2, &h, 2); + } + host_src = stage_out; + out_at = s.dst_off + done / 2; + break; + } + case Conv::WidenF16: { + // fp16 bits -> f32. EXACT: every fp16 value is an f32 value, including the + // subnormals, so this cannot change a single weight - which is why the engine may do + // it at all, and why doing it costs 10.88 MiB rather than a second kernel family. + const uint64_t elems = n / 2; + out_bytes = elems * 4; + float* o = (float*) stage_out; + for (uint64_t i = 0; i < elems; ++i) { + uint16_t h; + std::memcpy(&h, src + i * 2, 2); + o[i] = strata::kernels::f32_from_f16(h); + } + host_src = stage_out; + out_at = s.dst_off + done * 2; + break; + } + } + + const double u0 = now_ms(); + if (cudaMemcpy(dst_base + r.dst_off + out_at, host_src, out_bytes, cudaMemcpyHostToDevice) != + cudaSuccess) { + err = "cudaMemcpy failed for " + r.name; + cudaFreeHost(stage_in); cudaFreeHost(stage_out); + return false; + } + upload_ms += now_ms() - u0; + done += n; + } + } + + WeightRef wr; + wr.data = dst_base + r.dst_off; + wr.bytes = r.dst_bytes; + wr.ne0 = r.ne0; + wr.ne1 = r.ne1; + wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1); + wr.kind = r.kind; + wr.code_bits = r.code_bits; + wr.code_bias = r.code_bias; + wr.group_elems = r.group_elems; + wr.codebook_iq4nl = r.codebook != 0; + wr.has_offset = r.has_offset != 0; + wr.codes_bytes = r.codes_bytes; + wr.scales_bytes = r.scales_bytes; + wr.offset_bytes = r.offset_bytes; + wr.src_off = r.src_off; + wr.src_bytes = r.src_bytes; + wr.file_id = r.file; + wr.scales_fp16 = r.scales_fp16 != 0; + wr.act_kind = r.act_kind; + table_[r.name] = wr; + + ++report_.tensors; + if ((r.kind == WeightKind::Bf16InF32 || r.kind == WeightKind::F16InF32) && !r.raw16) { + ++report_.re_rounded; + report_.bytes_saved += r.src_bytes - r.dst_bytes; + } + } + if (cur) std::fclose(cur); + cudaFreeHost(stage_in); + cudaFreeHost(stage_out); + + report_.arena_bytes = pool; + report_.read_ms = now_ms() - t_read0 - upload_ms; + report_.upload_ms = upload_ms; + if (cudaDeviceSynchronize() != cudaSuccess) { err = "cudaDeviceSynchronize after the load failed"; return false; } + return true; +} + +const WeightRef* WeightTable::find(const std::string& name) const { + const auto it = table_.find(name); + return it == table_.end() ? nullptr : &it->second; +} + +} // namespace strata::core diff --git a/engine/strata/src/kernels/bf16_bits_test.cpp b/engine/strata/src/kernels/bf16_bits_test.cpp new file mode 100644 index 00000000..f996463f --- /dev/null +++ b/engine/strata/src/kernels/bf16_bits_test.cpp @@ -0,0 +1,80 @@ +// src/kernels/bf16_bits_test.cpp - `bf16_bits.hpp` against ggml's rule, over EVERY f32 bit pattern (CPU only). +// +// the rounding add `i + 0x7FFF + bit16` carries out of the mantissa for a NaN, so 0x7FFFFFFF came back as +// -0 and 0x7F800001 as +inf - an upstream NaN was masked instead of propagated. `ggml_compute_fp32_to_bf16` +// (ggml-impl.h at the pinned llama.cpp) tests the NaN first and returns `(i >> 16) | 64`. Three checks, all +// exhaustive (2^32 inputs, a few seconds): +// +// 1. the header equals ggml's function, transcribed below, on every input; +// 2. on every NON-NaN input it equals the previous rounding, so the change cannot move a finite value or an +// infinity by a single bit; +// 3. every NaN input gives a quiet NaN of the same sign. +// +// And the round trip over all 65,536 bf16 patterns: a non-NaN bf16 survives f32 and back unchanged. +#include "strata/kernels/bf16_bits.hpp" + +#include +#include +#include + +namespace { + +/// ggml_compute_fp32_to_bf16, ggml/src/ggml-impl.h (MIT, the ggml authors), on raw bits. +uint16_t ggml_bf16(uint32_t u) { + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); + return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); +} + +/// The rule before this fix, kept only to prove the change is confined to NaN inputs. +uint16_t previous_bf16(uint32_t u) { + u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; + return (uint16_t) (u >> 16); +} + +bool is_nan_bits(uint32_t u) { return (u & 0x7fffffffu) > 0x7f800000u; } + +} // namespace + +int main() { + unsigned long long vs_ggml = 0, vs_previous = 0, nan_lost = 0, nan_inputs = 0, previous_masked = 0; + uint32_t first_bad = 0; + bool have_bad = false; + for (uint64_t k = 0; k <= 0xFFFFFFFFull; ++k) { + const uint32_t u = (uint32_t) k; + float f; + std::memcpy(&f, &u, 4); + const uint16_t got = strata::kernels::bf16_from_f32(f); + if (got != ggml_bf16(u)) { + ++vs_ggml; + if (!have_bad) { first_bad = u; have_bad = true; } + } + if (is_nan_bits(u)) { + ++nan_inputs; + const uint32_t back = (uint32_t) got << 16; + // a quiet NaN (bit 22 of the f32) with the input's sign + if (!is_nan_bits(back) || (back & 0x00400000u) == 0 || (back >> 31) != (u >> 31)) ++nan_lost; + if (!is_nan_bits((uint32_t) previous_bf16(u) << 16)) ++previous_masked; + } else if (got != previous_bf16(u)) { + ++vs_previous; + if (!have_bad) { first_bad = u; have_bad = true; } + } + } + std::printf(" f32 -> bf16 over 2^32 inputs: %llu differ from ggml, %llu non-NaN differ from the previous rule\n", + vs_ggml, vs_previous); + std::printf(" NaN inputs: %llu, not a quiet same-sign NaN now: %llu (the previous rule masked %llu of them)\n", + nan_inputs, nan_lost, previous_masked); + if (have_bad) std::printf(" first mismatch at input 0x%08x\n", first_bad); + + unsigned long long trip_bad = 0; + for (uint32_t h = 0; h <= 0xFFFFu; ++h) { + const float f = strata::kernels::f32_from_bf16((uint16_t) h); + const uint16_t back = strata::kernels::bf16_from_f32(f); + const bool nan = is_nan_bits(h << 16); + if (back != (nan ? (uint16_t) (h | 64u) : (uint16_t) h)) ++trip_bad; + } + std::printf(" bf16 -> f32 -> bf16 over 65536 patterns: %llu wrong\n", trip_bad); + + const bool ok = vs_ggml == 0 && vs_previous == 0 && nan_lost == 0 && trip_bad == 0 && previous_masked > 0; + std::printf("\nbf16_bits_test %s\n", ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/engine/strata/src/kernels/bf16_gemv_parity.cpp b/engine/strata/src/kernels/bf16_gemv_parity.cpp new file mode 100644 index 00000000..435c336e --- /dev/null +++ b/engine/strata/src/kernels/bf16_gemv_parity.cpp @@ -0,0 +1,148 @@ +// src/kernels/bf16_gemv_parity.cpp - P2.S5's test for the BF16 GEMV. +// +// THREE THINGS ARE CHECKED, and the third is the one the engine's correctness rests on: +// +// 1. both kernels against a host reference that reads the SAME bf16 bits - so what is under test is the +// reduction, not the conversion, and the tolerance is set by summation order and nothing else; +// 2. the naive and the split kernel agree with each other, because the naive one is the reference the +// split one exists to be checked against and a disagreement there means one of them is wrong; +// 3. **THE ACTIVATION CONTRACT IS OBSERVABLE.** A BF16 weight sees a BF16 activation; feeding it fp16 or +// f32 instead is a 2^-9 = 1.95e-03 relative change, which is above any 1e-3 tolerance. An fp16 +// activation is the rival reading, computed and required to differ, because it is what the engine did +// before `docs/activation-contract.md` settled the question and it produces perfectly plausible output. +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using strata::kernels::bf16_from_f32; +using strata::kernels::f32_from_bf16; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +double rel_l1(const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); +} + +/// The host reference, in DOUBLE, over the same bf16 bits. +void reference(const std::vector& x, const std::vector& w, long long n_in, long long n_out, + std::vector& y) { + y.assign((size_t) n_out, 0.0f); + for (long long o = 0; o < n_out; ++o) { + double acc = 0; + for (long long i = 0; i < n_in; ++i) + acc += (double) f32_from_bf16(x[(size_t) i]) * (double) f32_from_bf16(w[(size_t) (o * n_in + i)]); + y[(size_t) o] = (float) acc; + } +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: bf16_gemv_parity [--selftest]\n"); return 2; } + } + int bad = 0; + + // THE REAL SHAPES, because a kernel that only works on a square toy is not a kernel this engine can use. + // `ssm_alpha` is [2560, 48] - a wide reduction and 48 outputs - and `indexer.k_proj` is [2560, 128]. + struct Shape { long long n_in, n_out; const char* what; }; + const Shape shapes[] = { + {2560, 48, "ssm_alpha.weight [2560, 48]"}, + {2560, 128, "indexer.k_proj [2560, 128]"}, + {2560, 512, "indexer.q_proj [2560, 512]"}, + {2560, 2560, "ple_value [2560, 2560]"}, + }; + + for (const Shape& s : shapes) { + std::mt19937 rng(4242); + std::normal_distribution g(0.0f, 1.0f); + std::vector fx((size_t) s.n_in), fw((size_t) (s.n_in * s.n_out)); + for (auto& v : fx) v = g(rng); + // a realistic weight scale: these are projections, not embeddings + for (auto& v : fw) v = g(rng) * 0.05f; + + // THE ACTIVATION IS ROUNDED TO BF16 FIRST, which is the contract, and the WEIGHT is already bf16 in + // the pack - the loaded bytes ARE the high 16 bits of an f32. + std::vector x((size_t) s.n_in), w((size_t) (s.n_in * s.n_out)); + for (size_t i = 0; i < fx.size(); ++i) x[i] = bf16_from_f32(fx[i]); + for (size_t i = 0; i < fw.size(); ++i) w[i] = bf16_from_f32(fw[i]); + + std::vector want; + reference(x, w, s.n_in, s.n_out, want); + + uint16_t *d_x = nullptr, *d_w = nullptr; + float *d_y = nullptr; + check(cudaMalloc(&d_x, x.size() * 2), "x"); + check(cudaMalloc(&d_w, w.size() * 2), "w"); + check(cudaMalloc(&d_y, (size_t) s.n_out * 4), "y"); + check(cudaMemcpy(d_x, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "cx"); + check(cudaMemcpy(d_w, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "cw"); + + std::vector naive((size_t) s.n_out), warp((size_t) s.n_out), split((size_t) s.n_out); + strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr); + check(cudaMemcpy(naive.data(), d_y, naive.size() * 4, cudaMemcpyDeviceToHost), "cy1"); + strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 32, nullptr); + check(cudaMemcpy(warp.data(), d_y, warp.size() * 4, cudaMemcpyDeviceToHost), "cy2"); + strata::kernels::bf16_gemv_split(d_x, d_w, d_y, s.n_in, s.n_out, 256, nullptr); + check(cudaMemcpy(split.data(), d_y, split.size() * 4, cudaMemcpyDeviceToHost), "cy3"); + + const double rn = rel_l1(want, naive), rw = rel_l1(want, warp), rs = rel_l1(want, split); + std::printf(" %-34s naive %.2e warp %.2e split256 %.2e\n", s.what, rn, rw, rs); + // The products are EXACT - both sides are bf16-valued, so f32 represents each product exactly - and + // the only difference is the order the 2560 terms are added. A tight bound is therefore meaningful. + if (!(rn <= 1e-5 && rw <= 1e-5 && rs <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++bad; } + + // ---- 3. THE ACTIVATION CONTRACT. The rival: an fp16 activation instead of bf16, which is what the + // engine did before the contract was settled. It must be observable, or check 1 above would pass + // against either and the contract would be untested. + { + std::vector fp16_as_f32((size_t) s.n_in); + std::vector x16((size_t) s.n_in); + for (size_t i = 0; i < fx.size(); ++i) { + x16[i] = strata::kernels::f16_from_f32(fx[i]); + fp16_as_f32[i] = strata::kernels::f32_from_f16(x16[i]); + } + // Round the fp16 value to bf16 - i.e. give the kernel a bf16 activation whose VALUES came through + // fp16. That is the whole difference between the two contracts at this call site. + for (size_t i = 0; i < fp16_as_f32.size(); ++i) x[i] = bf16_from_f32(fp16_as_f32[i]); + check(cudaMemcpy(d_x, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "cx2"); + std::vector rival((size_t) s.n_out); + strata::kernels::bf16_gemv(d_x, d_w, d_y, s.n_in, s.n_out, nullptr); + check(cudaMemcpy(rival.data(), d_y, rival.size() * 4, cudaMemcpyDeviceToHost), "cy4"); + const double r = rel_l1(want, rival); + const bool visible = r > 1e-4; + std::printf(" %-30s %s (%.4f%% apart)\n", "bf16 vs fp16 activation", + visible ? "yes" : "*** NO ***", r * 100); + if (!visible) ++bad; + } + cudaFree(d_x); cudaFree(d_w); cudaFree(d_y); + } + + std::printf("\nbf16_gemv: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("bf16_gemv_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/cpu/expert.cpp b/engine/strata/src/kernels/cpu/expert.cpp new file mode 100644 index 00000000..045e3d58 --- /dev/null +++ b/engine/strata/src/kernels/cpu/expert.cpp @@ -0,0 +1,683 @@ +// src/kernels/cpu/expert.cpp - P2.S3: the Q2_0 expert kernel, promoted from bench/micro/cpu_s2.cpp. +// +// The body is the validated kernel, moved rather than rewritten: it carries the P0.T2 parity result +// (rel 1.461e-06 against the ggml formula) and the three performance findings recorded in +// include/strata/kernels/cpu/expert.hpp. Read that header first; it says why each piece is shaped this way. +#include "strata/kernels/cpu/expert.hpp" + +#include +#if defined(_MSC_VER) +#include +#else +#include +#endif + +#include +#include +#include +#include +#include + +namespace strata::kernels::cpu { +namespace { + +std::atomic oracle_q8_0{false}; + +/// fp16 -> fp32, written out rather than using `_cvtsh_ss`, because the F16C intrinsic's behaviour on +/// subnormals is the one place the two can differ and the scales in this artifact are small. +inline float h2f(const uint8_t* p) { + uint16_t h; + std::memcpy(&h, p, 2); + const uint32_t sign = (uint32_t) (h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) { + f = sign << 31; + } else { + exp = 127 - 15 + 1; + while (!(man & 0x400u)) { man <<= 1; --exp; } + man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); + } + } else if (exp == 31) { + f = (sign << 31) | 0x7F800000u | (man << 13); + } else { + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + } + float out; + std::memcpy(&out, &f, 4); + return out; +} + +// The x86 Q8_0 quantization and generic Q2_0 dot sequences are adapted from llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d, +// ggml/src/ggml-cpu/arch/x86/quants.c: quantize_row_q8_0 and +// ggml/src/ggml-cpu/quants.c: ggml_vec_dot_q2_0_q8_0_generic. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +void quantize_oracle_q8_0(const float* x, int n, ActQ& a) { + a.nchunks = n / QKA; + for (int chunk = 0; chunk < a.nchunks; ++chunk) { + const float* xb = x + chunk * QKA; + __m256 v0 = _mm256_loadu_ps(xb); + __m256 v1 = _mm256_loadu_ps(xb + 8); + __m256 v2 = _mm256_loadu_ps(xb + 16); + __m256 v3 = _mm256_loadu_ps(xb + 24); + const __m256 sign = _mm256_set1_ps(-0.0f); + __m256 maximum = _mm256_andnot_ps(sign, v0); + maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v1)); + maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v2)); + maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v3)); + __m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maximum, 1), _mm256_castps256_ps128(maximum)); + max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4)); + max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4)); + const float amax = _mm_cvtss_f32(max4); + const float d = amax / 127.0f; + const uint16_t half_d = (uint16_t) _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(d), 0)); + const __m256 inverse = _mm256_set1_ps(amax != 0.0f ? 127.0f / amax : 0.0f); + v0 = _mm256_round_ps(_mm256_mul_ps(v0, inverse), _MM_FROUND_TO_NEAREST_INT); + v1 = _mm256_round_ps(_mm256_mul_ps(v1, inverse), _MM_FROUND_TO_NEAREST_INT); + v2 = _mm256_round_ps(_mm256_mul_ps(v2, inverse), _MM_FROUND_TO_NEAREST_INT); + v3 = _mm256_round_ps(_mm256_mul_ps(v3, inverse), _MM_FROUND_TO_NEAREST_INT); + __m256i i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1)); + const __m256i i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3)); + i0 = _mm256_packs_epi16(i0, i2); + i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); + int8_t* q = a.q + chunk * QKA; + _mm256_storeu_si256((__m256i*) q, i0); + int32_t sum = 0; + for (int j = 0; j < QKA; ++j) sum += q[j]; + a.scale[chunk] = h2f((const uint8_t*) &half_d); + a.sum[chunk] = sum; + a.hx[chunk] = a.scale[chunk] * float(sum); + } +} + +/// 2-bit unpack via VPMULTISHIFTQB. +/// +/// ARGUMENT ORDER IS (control, data) AND WAS DETERMINED EMPIRICALLY (`bench/micro/probe_multishift.cpp`). +/// The Intel guide states (a=data, b=control); using that produced 43 of 64 wrong codes. `plan.md`'s sketch +/// passes the shift pattern first, which is correct - so a "fix" that swapped it to match the guide was the +/// bug, not the fix. Within each 64-bit lane, output byte i is `(u16 >> 2i) & 0xFF`, so AND 3 yields the +/// eight 2-bit codes in order. +/// +/// The result is the 32 codes of ONE ACTIVATION CHUNK (4 qword lanes), which is the unit the Q8_1 scale is +/// defined on - not the 64-weight block. +inline __m256i unpack_q2_0(const uint8_t* codes) { + const __m128i packed = _mm_loadl_epi64((const __m128i*) codes); // 8 bytes -> 4 u16 in the low half + const __m256i lanes = _mm256_cvtepu16_epi64(packed); // 4 qwords, 8 codes each + const __m256i ctrl = _mm256_set1_epi64x((long long) 0x0E0C0A0806040200ULL); + return _mm256_and_si256(_mm256_multishift_epi64_epi8(ctrl, lanes), _mm256_set1_epi8(3)); +} + +/// 32 codes against 32 int8 activations. Codes 0 contribute nothing to `sum(c*xhat)`, so the zero lanes the +/// narrow load leaves behind are harmless. +inline __m256i block_dot(const uint8_t* codes, const int8_t* xq) { + return _mm256_dpbusd_epi32(_mm256_setzero_si256(), unpack_q2_0(codes), + _mm256_load_si256((const __m256i*) xq)); +} + +inline float hsum_ps(__m256 v) { + const __m128 s = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1)); + return _mm_cvtss_f32(_mm_hadd_ps(_mm_hadd_ps(s, s), s)); +} + +// ================================ plan v0.3 P6: the row dot in 512-bit lanes ================================ +// +// The 256-bit row dot below spent ~12 cycles per 64-weight block: two unpacks, two VNNI dots, two converts, two +// scalar scale products broadcast into two FMAs, an fp16 conversion and a scalar correction - compute-bound at +// ~39 GB/s while the machine streams 52. Here a block is ONE unpack (16 code bytes -> 64 codes), ONE VNNI dot +// over 64 activations, ONE convert and ONE FMA whose per-chunk scales come from a permute of a vector of scale +// products built for eight blocks at a time; the weight-independent correction is one FMA per eight blocks. +// The sum order differs from the 256-bit kernel (last-bit differences); the verify window and plain decode both +// use this kernel, so speculative decode still reproduces plain decode exactly. +static const bool kZmm = std::getenv("STRATA_CPU_YMM") == nullptr; + +inline __m512i unpack64_q2_0(const uint8_t* codes) { + const __m128i packed = _mm_loadu_si128((const __m128i*) codes); // 8 u16 = 64 codes + const __m512i lanes = _mm512_cvtepu16_epi64(packed); // 8 qwords, 8 codes each + const __m512i ctrl = _mm512_set1_epi64((long long) 0x0E0C0A0806040200ULL); + return _mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3)); +} + +// For blocks [b0, b0+nb) (nb <= 8): p[2i+h] = d_{b0+i} * xscale[2(b0+i)+h], dd[2i+h] = d_{b0+i}. +inline void scales8(const uint8_t* wscales, const ActQ& a, int b0, int nb, __m512& p, __m512& dd) { + const __mmask8 m8 = nb >= 8 ? (__mmask8) 0xFF : (__mmask8) ((1u << nb) - 1u); + const __m128i h = _mm_maskz_loadu_epi16(m8, wscales + 2 * b0); + const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(h)); + const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); + dd = _mm512_permutexvar_ps(dup, d8); + const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); + dd = _mm512_maskz_mov_ps(m16, dd); + p = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a.scale + 2 * b0)); +} + +inline float row_dot_z(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { + __m512 acc = _mm512_setzero_ps(), corr = _mm512_setzero_ps(); + const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); + for (int b0 = 0; b0 < nblocks; b0 += 8) { + const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; + __m512 p, dd; + scales8(scales, a, b0, nb, p, dd); + const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); + corr = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a.hx + 2 * b0), corr); + for (int i = 0; i < nb; ++i) { + const int b = b0 + i; + const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), unpack64_q2_0(codes + b * 16), + _mm512_load_si512((const void*) (a.q + b * QK))); + const __m512 sv = _mm512_permutexvar_ps(_mm512_add_epi32(base, _mm512_set1_epi32(2 * i)), p); + acc = _mm512_fmadd_ps(sv, _mm512_cvtepi32_ps(dot), acc); + } + } + return _mm512_reduce_add_ps(acc) - _mm512_reduce_add_ps(corr); +} + +template +inline void row_dot_multi_z(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks, + float* res) { + __m512 acc[NT], corr[NT]; + for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); } + const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); + for (int b0 = 0; b0 < nblocks; b0 += 8) { + const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; + const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); + __m512 p[NT]; + for (int t = 0; t < NT; ++t) { + __m512 dd; + scales8(scales, *a[t], b0, nb, p[t], dd); + corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]); + } + for (int i = 0; i < nb; ++i) { + const int b = b0 + i; + const __m512i w = unpack64_q2_0(codes + b * 16); + const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i)); + for (int t = 0; t < NT; ++t) { + const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w, + _mm512_load_si512((const void*) (a[t]->q + b * QK))); + acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]); + } + } + } + for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); +} + +/// One weight row against a quantized activation. +/// +/// sum_j (c_j - 1) d_w xhat_j d_x == d_w * ( d_x*sum(c*xhat) - d_x*sum(xhat) ) +/// +/// split per 32-chunk because `d_x` changes at the chunk boundary while `d_w` does not. +/// +/// The accumulator stays a FLOAT VECTOR for the whole row and is reduced once at the end. Reducing per +/// 64-weight block (two 8-lane horizontal sums: a store plus 16 scalar adds) cost far more than the dot +/// products themselves - it made the kernel compute-bound at 21 GB/s instead of DRAM-bound at 32. +inline float row_dot(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { + if (kZmm) return row_dot_z(codes, scales, a, nblocks); + __m256 acc = _mm256_setzero_ps(); + // The -sum(xhat) term is a SCALAR: broadcasting it into all 8 lanes and letting hsum_ps add them would + // apply it eight times per block. + float corr = 0.f; + for (int b = 0; b < nblocks; ++b) { + const float d = h2f(scales + 2 * b); + const __m256 slo = _mm256_cvtepi32_ps(block_dot(codes + b * 16, a.q + b * QK)); + const __m256 shi = _mm256_cvtepi32_ps(block_dot(codes + b * 16 + 8, a.q + b * QK + QKA)); + acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b]), slo, acc); + acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b + 1]), shi, acc); + corr += d * (a.hx[2 * b] + a.hx[2 * b + 1]); + } + return hsum_ps(acc) - corr; +} + +// VNNI's integer partial sums are exact. Remove the Q2_0 code offset BEFORE +// conversion to float, then follow the pinned generic CPU dot's two-chunk and +// per-64-block reduction. Its x86 type trait selects this generic reduction even +// in the AVX-512 oracle build. The legacy eight-lane FP32 reduction above has a +// different rounding order and remains the default. +inline int chunk_dot_oracle(const uint8_t* codes, const int8_t* q, int sum) { + const __m256i lanes = block_dot(codes, q); + const __m128i halves = _mm_add_epi32(_mm256_castsi256_si128(lanes), _mm256_extracti128_si256(lanes, 1)); + const __m128i pairs = _mm_hadd_epi32(halves, halves); + return _mm_cvtsi128_si32(_mm_hadd_epi32(pairs, pairs)) - sum; +} + +inline float row_dot_oracle(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) { + float result = 0.0f; + for (int b = 0; b < nblocks; ++b) { + float block = 0.0f; + for (int half = 0; half < 2; ++half) { + const int chunk = 2 * b + half; + const int dot = chunk_dot_oracle(codes + b * 16 + half * 8, a.q + chunk * QKA, a.sum[chunk]); + block += a.scale[chunk] * float(dot); + } + result += h2f(scales + 2 * b) * block; + } + return result; +} + +/// `row_dot` for NT activations at once: the codes of each block are unpacked once, and each token's +/// accumulator sees exactly the operations `row_dot` would apply to it, in the same order. +template +inline void row_dot_multi(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks, + float* res) { + if (kZmm) { row_dot_multi_z(codes, scales, a, nblocks, res); return; } + __m256 acc[NT]; + float corr[NT]; + for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; } + for (int b = 0; b < nblocks; ++b) { + const float d = h2f(scales + 2 * b); + const __m256i lo = unpack_q2_0(codes + b * 16); + const __m256i hi = unpack_q2_0(codes + b * 16 + 8); + for (int t = 0; t < NT; ++t) { + const __m256 slo = _mm256_cvtepi32_ps( + _mm256_dpbusd_epi32(_mm256_setzero_si256(), lo, _mm256_load_si256((const __m256i*) (a[t]->q + b * QK)))); + const __m256 shi = _mm256_cvtepi32_ps( + _mm256_dpbusd_epi32(_mm256_setzero_si256(), hi, + _mm256_load_si256((const __m256i*) (a[t]->q + b * QK + QKA)))); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), slo, acc[t]); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), shi, acc[t]); + corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]); + } + } + for (int t = 0; t < NT; ++t) res[t] = hsum_ps(acc[t]) - corr[t]; +} + +template +void expert_multi(const uint8_t* blob, const ActQ* const* a1, float* const* out, ExpertScratchMulti& ws) { + float g[NT], u[NT]; + for (int r = 0; r < FF; ++r) { + row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g); + row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u); + for (int t = 0; t < NT; ++t) ws.ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } + const ActQ* a2[NT]; + for (int t = 0; t < NT; ++t) { + act_quant_q8_1(ws.ff[t], FF, ws.a2[t]); + a2[t] = &ws.a2[t]; + } + float o[NT]; + for (int r = 0; r < H; ++r) { + row_dot_multi(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, + SC_D, o); + for (int t = 0; t < NT; ++t) out[t][r] = o[t]; + } +} + +void expert_oracle_q8_0(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) { + for (int r = 0; r < FF; ++r) { + const float g = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r) * ROW_GU, + blob + O_GU_SCALES + size_t(2 * r) * SC_GU * 2, a1, SC_GU); + const float u = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r + 1) * ROW_GU, + blob + O_GU_SCALES + size_t(2 * r + 1) * SC_GU * 2, a1, SC_GU); + ws.ff[r] = (g / (1.f + std::exp(-g))) * u; + } + quantize_oracle_q8_0(ws.ff, FF, ws.a2); + for (int r = 0; r < H; ++r) + out[r] = row_dot_oracle(blob + O_D_CODES + size_t(r) * ROW_D, + blob + O_D_SCALES + size_t(r) * SC_D * 2, ws.a2, SC_D); +} + +} // namespace + +const char* CpuFeatures::reason() const { + if (usable()) return "ok"; + // Named individually: "AVX-512 not supported" sends a user looking for a new CPU when the machine may have + // AVX-512F and be missing only VNNI, which is a much narrower and more explicable gap. + static char buf[160]; + std::snprintf(buf, sizeof buf, "missing %s%s%s%s%s", avx512f ? "" : "AVX512F ", + avx512bw ? "" : "AVX512BW ", avx512vl ? "" : "AVX512VL ", + avx512_vnni ? "" : "AVX512-VNNI ", avx512_vbmi ? "" : "AVX512-VBMI"); + return buf; +} + +CpuFeatures cpu_features() { + CpuFeatures f; + int reg[4] = {0, 0, 0, 0}; +#if defined(_MSC_VER) + __cpuid(reg, 0); + if (reg[0] < 7) return f; + __cpuidex(reg, 7, 0); +#else + unsigned r[4] = {0, 0, 0, 0}; + __cpuid_count(0, 0, r[0], r[1], r[2], r[3]); + if (r[0] < 7) return f; + __cpuid_count(7, 0, r[0], r[1], r[2], r[3]); + for (int i = 0; i < 4; ++i) reg[i] = (int) r[i]; +#endif + const unsigned ebx = (unsigned) reg[1], ecx = (unsigned) reg[2]; + f.avx512f = (ebx >> 16) & 1u; + f.avx512bw = (ebx >> 30) & 1u; + f.avx512vl = (ebx >> 31) & 1u; + f.avx512_vnni = (ecx >> 11) & 1u; + f.avx512_vbmi = (ecx >> 1) & 1u; + return f; +} + +void cpu_require_expert_support() { + const CpuFeatures f = cpu_features(); + if (f.usable()) return; + std::fprintf(stderr, + "strata: this CPU cannot run the expert kernel: %s.\n" + " The engine needs AVX512-VNNI and AVX512-VBMI (Intel Ice Lake / AMD Zen 4 or newer).\n" + " The scalar fallback exists for tests only and is far too slow to decode with.\n", + f.reason()); + std::exit(1); +} + +void act_quant_q8_1(const float* x, int n, ActQ& a) { + if (oracle_q8_0.load(std::memory_order_relaxed)) { + quantize_oracle_q8_0(x, n, a); + return; + } + a.nchunks = n / QKA; + // Plan v0.3 P6: AVX-512, the same operations per element as the scalar loop below (max of |x|, one multiply, + // +-0.5 away from zero, truncation, clamp), so the result is bitwise the scalar one. The scalar loop took + // ~22 us per 2560 values - 3.2 ms of every speculative round. + { + const __m512 half = _mm512_set1_ps(0.5f), mhalf = _mm512_set1_ps(-0.5f), zero = _mm512_setzero_ps(); + const __m512i lo = _mm512_set1_epi32(-127), hi = _mm512_set1_epi32(127); + const __m512 absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff)); + for (int k = 0; k < a.nchunks; ++k) { + const float* xb = x + k * QKA; + const __m512 x0 = _mm512_loadu_ps(xb), x1 = _mm512_loadu_ps(xb + 16); + const float amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask))); + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + const __m512 vinv = _mm512_set1_ps(inv); + const __m512 t0 = _mm512_mul_ps(x0, vinv), t1 = _mm512_mul_ps(x1, vinv); + const __m512 r0 = _mm512_add_ps(t0, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t0, zero, _CMP_GE_OQ), mhalf, half)); + const __m512 r1 = _mm512_add_ps(t1, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t1, zero, _CMP_GE_OQ), mhalf, half)); + __m512i v0 = _mm512_cvttps_epi32(r0), v1 = _mm512_cvttps_epi32(r1); + v0 = _mm512_min_epi32(_mm512_max_epi32(v0, lo), hi); + v1 = _mm512_min_epi32(_mm512_max_epi32(v1, lo), hi); + _mm_storeu_si128((__m128i*) (a.q + k * QKA), _mm512_cvtepi32_epi8(v0)); + _mm_storeu_si128((__m128i*) (a.q + k * QKA + 16), _mm512_cvtepi32_epi8(v1)); + const int32_t sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1)); + a.scale[k] = s; + a.sum[k] = sum; + a.hx[k] = s * (float) sum; + } + return; + } + for (int k = 0; k < a.nchunks; ++k) { + const float* xb = x + k * QKA; + float amax = 0.f; + for (int j = 0; j < QKA; ++j) amax = std::fmax(amax, std::fabs(xb[j])); + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + int32_t sum = 0; + int8_t* q = a.q + k * QKA; + for (int j = 0; j < QKA; ++j) { + // **`std::lround` IS A FUNCTION CALL AND IT COST 51 us PER LAYER.** Measured: quantizing 2560 + // floats took 51.3 us - 20 ns per element, about 60 cycles for a fabs, a multiply and a round. + // `lround` respects the current rounding mode, so MSVC cannot inline it to a single instruction + // and emits a call per element. 48 layers x 51.3 us = 2.46 ms/token, which is 8.6% of the whole + // CPU expert term and is pure overhead. + // + // `t + copysign(0.5, t)` is EXACTLY `lround`'s rule - round half AWAY FROM ZERO - and it is + // branchless and vectorizable. It is NOT `_mm256_round_ps`, which rounds half to EVEN and would + // quietly change the activation on the ties. The cast is safe because `|t| <= 127` by construction + // (`s = amax/127`, so `|x_j|/s <= 127`), well inside int32. + const float t = xb[j] * inv; + const float r = t + (t >= 0.f ? 0.5f : -0.5f); + int v = (int) r; + v = v < -127 ? -127 : (v > 127 ? 127 : v); + q[j] = (int8_t) v; + sum += v; + } + a.scale[k] = s; + a.sum[k] = sum; + a.hx[k] = s * (float) sum; + } +} + +void expert_set_oracle_q8_0(bool enabled) { + oracle_q8_0.store(enabled, std::memory_order_relaxed); +} + +void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws) { + act_quant_q8_1(x, H, ws.a1); + s2_expert_vnni_q(blob, ws.a1, out, ws); +} + +void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) { + if (oracle_q8_0.load(std::memory_order_relaxed)) { + expert_oracle_q8_0(blob, a1, out, ws); + return; + } + for (int r = 0; r < FF; ++r) { + const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU); + const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU); + // SiLU on the GATE, multiplied by up - the same reading `docs/semantics.md` records for the shared + // expert, and the one that is wrong the other way round in a way that still produces a number. + ws.ff[r] = (g / (1.f + std::exp(-g))) * u; + } + act_quant_q8_1(ws.ff, FF, ws.a2); + for (int r = 0; r < H; ++r) + out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D, + blob + O_D_SCALES + (size_t) r * SC_D * 2, ws.a2, SC_D); +} + +bool expert_oracle_q8_0_enabled() { return oracle_q8_0.load(std::memory_order_relaxed); } + +void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1) { + for (int r = r0; r < r1; ++r) { + const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU); + const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU); + ff[r] = (g / (1.f + std::exp(-g))) * u; + } +} + +void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1) { + for (int r = r0; r < r1; ++r) + out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, SC_D); +} + +namespace { +template +void gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, float* const* ff, int r0, int r1) { + float g[NT], u[NT]; + for (int r = r0; r < r1; ++r) { + row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g); + row_dot_multi(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU, + blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u); + for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } +} +template +void down_rows_multi(const uint8_t* blob, const ActQ* const* a2, float* const* out, int r0, int r1) { + float o[NT]; + for (int r = r0; r < r1; ++r) { + row_dot_multi(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, + SC_D, o); + for (int t = 0; t < NT; ++t) out[t][r] = o[t]; + } +} +} // namespace + +void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0, + int r1) { + switch (n_tokens) { + case 1: gu_rows_multi<1>(blob, a1, ff, r0, r1); break; + case 2: gu_rows_multi<2>(blob, a1, ff, r0, r1); break; + case 3: gu_rows_multi<3>(blob, a1, ff, r0, r1); break; + case 4: gu_rows_multi<4>(blob, a1, ff, r0, r1); break; + case 5: gu_rows_multi<5>(blob, a1, ff, r0, r1); break; + case 6: gu_rows_multi<6>(blob, a1, ff, r0, r1); break; + case 7: gu_rows_multi<7>(blob, a1, ff, r0, r1); break; + default: gu_rows_multi<8>(blob, a1, ff, r0, r1); break; + } +} + +void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0, + int r1) { + switch (n_tokens) { + case 1: down_rows_multi<1>(blob, a2, out, r0, r1); break; + case 2: down_rows_multi<2>(blob, a2, out, r0, r1); break; + case 3: down_rows_multi<3>(blob, a2, out, r0, r1); break; + case 4: down_rows_multi<4>(blob, a2, out, r0, r1); break; + case 5: down_rows_multi<5>(blob, a2, out, r0, r1); break; + case 6: down_rows_multi<6>(blob, a2, out, r0, r1); break; + case 7: down_rows_multi<7>(blob, a2, out, r0, r1); break; + default: down_rows_multi<8>(blob, a2, out, r0, r1); break; + } +} + +// ================================ plan v0.3 P6: Q2_0 rows in the GGUF block layout ================================ +// +// The IQ model files keep their down projections in Q2_0 GGUF blocks (fp16 d, then 16 code bytes: 18 bytes per +// 64 weights, interleaved), which ggml-cpu computes with a scalar loop on x86. This is `row_dot_multi_z` with +// the block stride of the GGUF layout: the same unpack, the same VNNI dot, the same correction. +namespace { +template +inline void q2g_row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) { + __m512 acc[NT], corr[NT]; + for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); } + const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); + const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); + for (int b0 = 0; b0 < nblocks; b0 += 8) { + const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; + const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u); + alignas(16) uint16_t sc[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + for (int i = 0; i < nb; ++i) std::memcpy(&sc[i], row + (size_t) (b0 + i) * 18, 2); + const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_load_si128((const __m128i*) sc))); + const __m512 dd = _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, d8)); + __m512 p[NT]; + for (int t = 0; t < NT; ++t) { + p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->scale + 2 * b0)); + corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]); + } + for (int i = 0; i < nb; ++i) { + const int b = b0 + i; + const __m512i w = unpack64_q2_0(row + (size_t) b * 18 + 2); + const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i)); + for (int t = 0; t < NT; ++t) { + const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w, + _mm512_load_si512((const void*) (a[t]->q + b * QK))); + acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]); + } + } + } + for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); +} +template +void q2g_rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) { + float res[NT]; + for (int r = r0; r < r1; ++r) { + q2g_row_multi(w + (size_t) r * row_bytes, a, nblocks, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} +} // namespace + +void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1) { + switch (nt) { + case 1: q2g_rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 2: q2g_rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 3: q2g_rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 4: q2g_rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 5: q2g_rows<5>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 6: q2g_rows<6>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 7: q2g_rows<7>(w, row_bytes, nblocks, a, out, r0, r1); break; + default: q2g_rows<8>(w, row_bytes, nblocks, a, out, r0, r1); break; + } +} + +void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out, + ExpertScratchMulti& ws) { + if (oracle_q8_0.load(std::memory_order_relaxed) || n_tokens < 1 || n_tokens > MAXT) { + for (int t = 0; t < n_tokens; ++t) s2_expert_vnni_q(blob, *a1[t], out[t], ws.single); + return; + } + switch (n_tokens) { + case 1: expert_multi<1>(blob, a1, out, ws); break; + case 2: expert_multi<2>(blob, a1, out, ws); break; + case 3: expert_multi<3>(blob, a1, out, ws); break; + case 4: expert_multi<4>(blob, a1, out, ws); break; + case 5: expert_multi<5>(blob, a1, out, ws); break; + case 6: expert_multi<6>(blob, a1, out, ws); break; + case 7: expert_multi<7>(blob, a1, out, ws); break; + default: expert_multi<8>(blob, a1, out, ws); break; + } +} + +void s2_expert_scalar(const uint8_t* blob, const float* x_in, float* out, bool quant_acts) { + // BOTH STAGES, which is what `quant_acts` promises and what `bench/micro/cpu_s2.cpp` does NOT do. + // + // The original's comment says the oracle "consume[s] the SAME INT8 activation values the VNNI path uses, + // at both stages", but its code quantizes only the INTERMEDIATE - the gate/up projections still see raw + // f32 `x`. Feeding it an already-quantized input (which is what the engine does) makes the two coincide + // and hides the discrepancy entirely; feeding it a raw f32 input makes the comparison one between two + // DIFFERENT computations, and the gap measured here was 1.19e-02 - three times P2.S3's tolerance, and + // read as a kernel bug when it was a fixture bug. + float xq[H]; + const float* x = x_in; + if (quant_acts) { + ActQ a1; + act_quant_q8_1(x_in, H, a1); + for (int i = 0; i < H; ++i) xq[i] = a1.scale[i / QKA] * (float) a1.q[i]; + x = xq; + } + float ff[FF]; + for (int r = 0; r < FF; ++r) { + const uint8_t* gc = blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU; + const uint8_t* gs = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2; + const uint8_t* uc = blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU; + const uint8_t* us = blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2; + float sg = 0.f, su = 0.f; + for (int b = 0; b < SC_GU; ++b) { + const float dg = h2f(gs + 2 * b), du = h2f(us + 2 * b); + for (int j = 0; j < QK; ++j) { + const int o = b * QK + j; + sg += (float) (((gc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * dg * x[o]; + su += (float) (((uc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * du * x[o]; + } + } + ff[r] = (sg / (1.f + std::exp(-sg))) * su; + } + if (quant_acts) { + // Replace the exact intermediate with the INT8 values the VNNI path actually sees, so the two differ + // only by FP32 evaluation order. + ActQ a2; + act_quant_q8_1(ff, FF, a2); + for (int i = 0; i < FF; ++i) ff[i] = a2.scale[i / QKA] * (float) a2.q[i]; + } + for (int r = 0; r < H; ++r) { + const uint8_t* dc = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* ds = blob + O_D_SCALES + (size_t) r * SC_D * 2; + float acc = 0.f; + for (int b = 0; b < SC_D; ++b) { + const float d = h2f(ds + 2 * b); + for (int j = 0; j < QK; ++j) + acc += (float) (((dc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * d * ff[b * QK + j]; + } + out[r] = acc; + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/expert_layout.cpp b/engine/strata/src/kernels/cpu/expert_layout.cpp new file mode 100644 index 00000000..4583b107 --- /dev/null +++ b/engine/strata/src/kernels/cpu/expert_layout.cpp @@ -0,0 +1,240 @@ +// src/kernels/cpu/expert_layout.cpp - plan v0.3 P6: the per-layer expert table. See the header. +#include "strata/kernels/cpu/expert_layout.hpp" + +#include +#include +#include +#include +#if defined(_MSC_VER) +#include +#include +#else +#include +#endif +#include +#include + +namespace strata::kernels::cpu { +namespace { +ExpertLayout g_layout; +} + +const ExpertLayout& expert_layout() { return g_layout; } + +bool cpu_avx512_ok() { + static const bool ok = [] { + if (const char* f = std::getenv("STRATA_FORCE_AVX2"); f != nullptr && f[0] == '1') return false; + unsigned r[4] = {0, 0, 0, 0}; + auto cpuid = [&](unsigned leaf, unsigned sub) { +#if defined(_MSC_VER) + int x[4]; + __cpuidex(x, (int) leaf, (int) sub); + for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; +#else + __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]); +#endif + }; + cpuid(0, 0); + if (r[0] < 7) return false; + cpuid(1, 0); + if (!((r[2] >> 27) & 1u)) return false; // OSXSAVE +#if defined(_MSC_VER) + const unsigned long long xcr0 = _xgetbv(0); +#else + unsigned lo = 0, hi = 0; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; +#endif + if ((xcr0 & 0xE6) != 0xE6) return false; // the OS saves the AVX-512 state + cpuid(7, 0); + const unsigned ebx = r[1], ecx = r[2]; + return ((ebx >> 16) & 1u) && ((ebx >> 30) & 1u) && ((ebx >> 31) & 1u) && ((ecx >> 11) & 1u) && ((ecx >> 1) & 1u); + }(); + return ok; +} + +bool cpu_avx2_ok() { + static const bool ok = [] { + unsigned r[4] = {0, 0, 0, 0}; + auto cpuid = [&](unsigned leaf, unsigned sub) { +#if defined(_MSC_VER) + int x[4]; + __cpuidex(x, (int) leaf, (int) sub); + for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i]; +#else + __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]); +#endif + }; + cpuid(0, 0); + if (r[0] < 7) return false; + cpuid(1, 0); + const unsigned ecx1 = r[2]; + // FMA (12), OSXSAVE (27), AVX (28), F16C (29) + if (!((ecx1 >> 12) & 1u) || !((ecx1 >> 27) & 1u) || !((ecx1 >> 28) & 1u) || !((ecx1 >> 29) & 1u)) return false; +#if defined(_MSC_VER) + const unsigned long long xcr0 = _xgetbv(0); +#else + unsigned lo = 0, hi = 0; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; +#endif + if ((xcr0 & 0x6) != 0x6) return false; // the OS saves the SSE and AVX state + cpuid(7, 0); + return ((r[1] >> 5) & 1u) != 0; // AVX2 + }(); + return ok; +} + +std::string cpu_name() { + unsigned r[12] = {}; +#if defined(_MSC_VER) + int x[4]; + __cpuid(x, (int) 0x80000000u); + if ((unsigned) x[0] < 0x80000004u) return "unknown"; + for (unsigned i = 0; i < 3; ++i) { + __cpuid(x, (int) (0x80000002u + i)); + for (int j = 0; j < 4; ++j) r[i * 4 + j] = (unsigned) x[j]; + } +#else + unsigned a = 0, b = 0, c = 0, d = 0; + __cpuid(0x80000000u, a, b, c, d); + if (a < 0x80000004u) return "unknown"; + for (unsigned i = 0; i < 3; ++i) __cpuid(0x80000002u + i, r[i * 4], r[i * 4 + 1], r[i * 4 + 2], r[i * 4 + 3]); +#endif + char s[49] = {}; + std::memcpy(s, r, 48); + std::string name(s); + const size_t b0 = name.find_first_not_of(' '), b1 = name.find_last_not_of(' '); + return b0 == std::string::npos ? std::string("unknown") : name.substr(b0, b1 - b0 + 1); +} + +void q2_rows_any(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, float* const* out, + int r0, int r1) { + if (cpu_avx512_ok()) q2_0_gguf_rows_multi(w, row_bytes, nblocks, a, nt, out, r0, r1); + else q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a, nt, out, r0, r1); +} + +void act_quant_any(const float* x, int n, ActQ& a) { + if (cpu_avx512_ok()) act_quant_q8_1(x, n, a); + else act_quant_q8_1_avx2(x, n, a); +} + +#if !defined(STRATA_NATIVE_EXPERTS) +// Without ggml-cpu no native pack loads (expert_layout_load refuses), so these are never reached. +bool native_experts_available() noexcept { return false; } +bool native_fmt(int, int, int64_t, int64_t, NativeFmt&, std::string& err) { err = "built without native experts"; return false; } +void native_quant_act(const NativeFmt&, const float*, void*) { std::abort(); } +void native_quant_h(const NativeFmt&, const float*, void*) { std::abort(); } +void native_gu_rows(const NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int) { std::abort(); } +void native_down_rows(const NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int) { std::abort(); } +#endif + +bool expert_layout_load(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) { + ExpertLayout L; + L.n_layers = n_layers; + L.n_expert = n_expert; + std::ifstream in(pack_dir + "/native_experts.txt"); + if (!in) { + L.total = (uint64_t) n_layers * (uint64_t) n_expert * (uint64_t) BLOB; + g_layout = L; + return true; + } +#if !defined(STRATA_NATIVE_EXPERTS) + err = "this pack has native (IQ) experts but the engine was built without STRATA_NATIVE_EXPERTS"; + return false; +#else + L.native = true; + L.fmt.resize((size_t) n_layers); + L.offset.assign((size_t) n_layers, ~0ull); + L.bytes.assign((size_t) n_layers, 0); + L.max_blob = 0; + std::string line; + while (std::getline(in, line)) { + if (line.empty() || line[0] == '#') { + if (!line.empty() && line[0] == '#') { + // "# strata native experts vN: ...". A version this engine does not know may mean columns it + // would misread, so it is refused rather than parsed as far as the known columns go. + static const char tag[] = "# strata native experts v"; + if (line.compare(0, sizeof tag - 1, tag) == 0) { + L.version = std::atoi(line.c_str() + sizeof tag - 1); + if (L.version > kExpertLayoutVersion) { + err = "native_experts.txt is v" + std::to_string(L.version) + "; this engine reads up to v" + + std::to_string(kExpertLayoutVersion) + " (the pack was written by a newer tools/" + "iq_pack.py: update the engine, or repack with this one)"; + return false; + } + } + // v3 packs record their expert count in the header; a pruned model (GSQ-RCO Coder) ships + // fewer experts than the canonical geometry the caller passes, which is a compile-time + // default, so the header wins. + const size_t at = line.find("(n_expert "); + if (at != std::string::npos) L.n_expert = std::atoll(line.c_str() + at + 10); + } + continue; + } + std::istringstream ss(line); + long long l = -1, gt = -1, dt = -1; + unsigned long long off = 0, blob = 0, go = 0, uo = 0, dox = 0; + if (!(ss >> l >> gt >> dt >> off >> blob) || l < 0 || l >= n_layers) { + err = "native_experts.txt: a malformed line: " + line; + return false; + } + NativeFmt f; + if (!native_fmt((int) gt, (int) dt, H, FF, f, err)) return false; + if (f.bytes != blob) { + err = "native_experts.txt: layer " + std::to_string(l) + " blob is " + std::to_string(blob) + + " B but its formats make " + std::to_string(f.bytes); + return false; + } + if (ss >> go >> uo >> dox) { // v2 lines: the GGUF offsets + if (L.gguf_off.empty()) L.gguf_off.assign((size_t) (3 * n_layers), 0); + L.gguf_off[(size_t) (3 * l)] = go; + L.gguf_off[(size_t) (3 * l + 1)] = uo; + L.gguf_off[(size_t) (3 * l + 2)] = dox; + std::string file; // v3: the shard that holds this layer (a file name beside --native) + if (ss >> file) { + if (L.gguf_file.empty()) L.gguf_file.assign((size_t) (3 * n_layers), std::string()); + // One name covers all three roles. When a shard boundary falls inside a layer the packer writes + // "gate,up,down" instead (v4), an empty field meaning the --native shard. A GGUF file name has no + // comma, so the split is unambiguous; an engine older than v4 fails to open such a "file" loudly. + // The comma form is from #255 (gopinath87607). + std::vector parts; + for (size_t from = 0;;) { + const size_t comma = file.find(',', from); + parts.push_back(file.substr(from, comma == std::string::npos ? comma : comma - from)); + if (comma == std::string::npos) break; + from = comma + 1; + } + if (parts.size() == 1) { + const std::string one = parts[0]; // not parts.assign(3, parts[0]): that aliases the element + parts.assign(3, one); // the assignment is about to overwrite + } + std::string extra; + if (parts.size() != 3 || (ss >> extra)) { + err = "native_experts.txt: layer " + std::to_string(l) + ": the shard column is one name or " + "gate,up,down, not: " + line; + return false; + } + for (size_t r = 0; r < 3; ++r) L.gguf_file[(size_t) (3 * l) + r] = parts[r]; + } + } + L.fmt[(size_t) l] = f; + L.offset[(size_t) l] = off; + L.bytes[(size_t) l] = blob; + if (blob > L.max_blob) L.max_blob = blob; + } + uint64_t at = 0; + for (int64_t l = 0; l < n_layers; ++l) { + if (L.offset[(size_t) l] != at) { + err = "native_experts.txt: layer " + std::to_string(l) + " is missing or not contiguous"; + return false; + } + at += L.bytes[(size_t) l] * (uint64_t) L.n_expert; + } + L.total = at; + g_layout = L; + return true; +#endif +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/expert_multi_test.cpp b/engine/strata/src/kernels/cpu/expert_multi_test.cpp new file mode 100644 index 00000000..446c95fe --- /dev/null +++ b/engine/strata/src/kernels/cpu/expert_multi_test.cpp @@ -0,0 +1,87 @@ +// src/kernels/cpu/expert_multi_test.cpp - plan v0.3 P6: one expert, several tokens (CPU only, synthetic data). +// +// expert_multi_test bitwise check: s2_expert_vnni_multi vs s2_expert_vnni_q per token, n = 1..8 +// expert_multi_test --bench [E] time per expert for n = 1..5 over E synthetic experts (default 256 = 354 MB, +// far beyond L3, so the blob comes from DRAM as it does in the engine); 1 thread +// +// The bench measures the speculation model's `extra_use_cost`: the CPU time of each extra token routed to an +// expert, as a fraction of reading the expert once (tools/spec_economics.py assumes 0.2). +#include "strata/kernels/cpu/expert.hpp" + +#include +#include +#include +#include +#include +#include + +namespace c = strata::kernels::cpu; + +namespace { +void make_blob(uint8_t* b, std::mt19937& rng) { + for (size_t i = 0; i < c::O_GU_SCALES; ++i) b[i] = (uint8_t) rng(); // codes + for (size_t i = c::O_GU_SCALES; i < c::BLOB; i += 2) { // fp16 scales ~0.004-0.016 + const uint16_t h = (uint16_t) (0x1C00 + rng() % 0x0800); + std::memcpy(b + i, &h, 2); + } +} + +double now_ms() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +} // namespace + +int main(int argc, char** argv) { + c::cpu_require_expert_support(); + std::mt19937 rng(9); + const bool bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0; + const int E = bench ? (argc > 2 ? std::atoi(argv[2]) : 256) : 4; + std::vector blobs((size_t) E * c::BLOB); + for (int e = 0; e < E; ++e) make_blob(&blobs[(size_t) e * c::BLOB], rng); + std::normal_distribution nd(0.f, 1.f); + static c::ActQ acts[c::MAXT]; + static float xs[c::MAXT][c::H]; + for (int t = 0; t < c::MAXT; ++t) { + for (float& v : xs[t]) v = nd(rng); + c::act_quant_q8_1(xs[t], c::H, acts[t]); + } + const c::ActQ* a1[c::MAXT]; + for (int t = 0; t < c::MAXT; ++t) a1[t] = &acts[t]; + static float out_multi[c::MAXT][c::H], out_single[c::H]; + float* outs[c::MAXT]; + for (int t = 0; t < c::MAXT; ++t) outs[t] = out_multi[t]; + static c::ExpertScratchMulti wsm; + static c::ExpertScratch ws; + + if (!bench) { + int fail = 0; + for (int e = 0; e < E; ++e) { + const uint8_t* blob = &blobs[(size_t) e * c::BLOB]; + for (int n = 1; n <= c::MAXT; ++n) { + c::s2_expert_vnni_multi(blob, a1, n, outs, wsm); + for (int t = 0; t < n; ++t) { + c::s2_expert_vnni_q(blob, acts[t], out_single, ws); + if (std::memcmp(out_single, out_multi[t], sizeof out_single) != 0) { + std::fprintf(stderr, "FAIL expert %d n=%d token %d differs\n", e, n, t); + ++fail; + } + } + } + } + std::printf("expert_multi_test: %s\n", fail ? "FAILED" : "OK (every token bitwise equal to the single-token kernel)"); + return fail ? 1 : 0; + } + + std::printf("%d experts x %.2f MB, one thread\n", E, c::BLOB / 1e6); + double base = 0; + for (int n = 1; n <= 5; ++n) { + c::s2_expert_vnni_multi(&blobs[0], a1, n, outs, wsm); // warm the code path + const double t0 = now_ms(); + for (int e = 0; e < E; ++e) c::s2_expert_vnni_multi(&blobs[(size_t) e * c::BLOB], a1, n, outs, wsm); + const double us = 1000.0 * (now_ms() - t0) / E; + if (n == 1) base = us; + std::printf("tokens per expert %d: %7.1f us per expert (%.2fx one token; extra token = %.2f of one read), %.1f GB/s\n", + n, us, us / base, n > 1 ? (us / base - 1.0) / (n - 1) : 0.0, c::BLOB / (us * 1e3)); + } + return 0; +} diff --git a/engine/strata/src/kernels/cpu/expert_parity.cpp b/engine/strata/src/kernels/cpu/expert_parity.cpp new file mode 100644 index 00000000..39f24a1c --- /dev/null +++ b/engine/strata/src/kernels/cpu/expert_parity.cpp @@ -0,0 +1,184 @@ +// src/kernels/cpu/expert_parity.cpp - P2.S3's test for the CPU expert path. +// +// WHAT IS BEING CHECKED, and the two tolerances are different questions: +// +// 1. VNNI vs the scalar oracle with `quant_acts = true`. Both sides consume the SAME INT8 activation +// values, so the only difference is FP32 evaluation ORDER. This is the check that proves the KERNEL - +// the VNNI unpack, the 32-element chunk split, the scalar correction term - and P2.S3 asks for 3e-3. +// 2. VNNI vs the oracle with `quant_acts = false`. Now the oracle uses exact FP32 activations, so the gap +// IS the activation contract (`docs/activation-contract.md`). It is REPORTED, not asserted tightly, +// because it is a property of the model's quantisation and not of this code. +// +// The activation contract is asserted OBSERVABLE between the two: if rounding the activation to Q8_1 made no +// difference, then one of the two paths is not doing what it claims and check 1 would be vacuous. +// +// A SELF-CONSISTENT TEST CANNOT CATCH A WRONG FILE OFFSET. Both sides read the same blob, so pointing at the +// wrong expert would still agree perfectly. What is checked instead is structural: the blob must decode to +// finite, non-zero scales, and the blob at a DIFFERENT layer must be different data - which is what a wrong +// stride would break. +#include "strata/kernels/cpu/expert.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +namespace { + +/// Normalised L1 difference, with the reference magnitude returned for reporting. +double rel_l1(const float* a, const float* b, int n, double* mag_out = nullptr) { + double d = 0, mag = 0; + for (int i = 0; i < n; ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + mag += std::fabs((double) a[i]); + } + if (mag_out) *mag_out = mag / n; + return d / (mag > 1e-30 ? mag : 1e-30); +} + +bool read_blob(const char* path, long long index, std::vector& out) { + out.assign(cpu::BLOB, 0); + std::FILE* f = std::fopen(path, "rb"); + if (!f) return false; +#if defined(_MSC_VER) + if (_fseeki64(f, (long long) index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } +#else + if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } +#endif + const size_t got = std::fread(out.data(), 1, out.size(), f); + std::fclose(f); + return got == out.size(); +} + +/// The fp16 scale at a byte offset, decoded by the SAME rule the kernel uses. Used only for the structural +/// sanity check, so it is deliberately a second, independent transcription of the three lines in question. +float f16_at(const std::vector& b, size_t off) { + uint16_t h; + std::memcpy(&h, b.data() + off, 2); + const uint32_t sign = (uint32_t) (h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) f = sign << 31; + else { exp = 127 - 15 + 1; while (!(man & 0x400u)) { man <<= 1; --exp; } man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); } + } else if (exp == 31) { + f = (sign << 31) | 0x7F800000u | (man << 13); + } else { + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + } + float o; + std::memcpy(&o, &f, 4); + return o; +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + const char* path = "pack/full/experts.bin"; + long long layer = 0, expert = 0; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") selftest = true; + else if (a == "--file" && i + 1 < argc) path = argv[++i]; + else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]); + else if (a == "--expert" && i + 1 < argc) expert = std::atoll(argv[++i]); + else { std::fprintf(stderr, "usage: expert_parity [--selftest] [--file P] [--layer N] [--expert N]\n"); + return 2; } + } + + int bad = 0; + + // ---- the CPU must be able to run the kernel, and the report must say WHICH feature is missing + const cpu::CpuFeatures feat = cpu::cpu_features(); + std::printf(" %-44s %s\n", "AVX512 F/BW/VL/VNNI/VBMI", + feat.usable() ? "all present" : feat.reason()); + if (!feat.usable()) { + std::printf(" the VNNI path cannot run here; only the scalar oracle can be exercised.\n"); + std::printf(" P2.S3's kernel check is SKIPPED, not passed.\n"); + std::printf("\nexpert_parity: 0 failures, 1 SKIPPED\n"); + return 0; + } + + // ---- a real blob out of the pack: layer stride is 512 experts + const long long idx = layer * 512 + expert; + std::vector blob; + if (!read_blob(path, idx, blob)) { + std::fprintf(stderr, "cannot read expert %lld (layer %lld) from %s\n", expert, layer, path); + return 2; + } + + // ---- structural sanity, because the agreement checks below are self-consistent and would pass on the + // wrong blob. A mis-strided read lands on a different expert's data, which is still plausible Q2_0, + // so the check that has teeth is the DIFFERENCE between layers. + { + int nonzero = 0; + float smin = 1e30f, smax = -1e30f; + for (int b = 0; b < cpu::SC_GU; ++b) { + const float s = f16_at(blob, cpu::O_GU_SCALES + (size_t) b * 2); + if (s != 0.f) ++nonzero; + smin = std::fmin(smin, std::fabs(s)); + smax = std::fmax(smax, std::fabs(s)); + } + const bool ok = nonzero > cpu::SC_GU / 2 && std::isfinite(smin) && std::isfinite(smax) && smax > 0.f; + std::printf(" %-44s %s (%d/%d non-zero, |s| in [%.4g, %.4g])\n", "blob decodes to live scales", + ok ? "yes" : "*** NO ***", nonzero, cpu::SC_GU, (double) smin, (double) smax); + if (!ok) ++bad; + } + { + std::vector other; + if (read_blob(path, (layer * 512 + expert) + 1, other)) { + long long diff = 0; + for (size_t i = 0; i < blob.size(); ++i) if (blob[i] != other[i]) ++diff; + const double frac = (double) diff / (double) blob.size(); + const bool ok = frac > 0.1; + std::printf(" %-44s %s (%.1f%% of bytes differ)\n", "the next expert is different data", + ok ? "yes" : "*** NO ***", frac * 100); + if (!ok) ++bad; + } + } + + // ---- a realistic activation + std::mt19937 rng(4242); + std::normal_distribution gauss(0.0f, 1.0f); + std::vector x(cpu::H); + for (auto& v : x) v = gauss(rng); + + cpu::ExpertScratch ws; + std::vector vnni(cpu::H), scalar_q(cpu::H), scalar_fp(cpu::H); + cpu::s2_expert_vnni(blob.data(), x.data(), vnni.data(), ws); + cpu::s2_expert_scalar(blob.data(), x.data(), scalar_q.data(), true); + cpu::s2_expert_scalar(blob.data(), x.data(), scalar_fp.data(), false); + + double mag = 0; + const double rel_kernel = rel_l1(scalar_q.data(), vnni.data(), cpu::H, &mag); + const double rel_contract = rel_l1(scalar_fp.data(), vnni.data(), cpu::H); + const double trap_contract = rel_l1(scalar_fp.data(), scalar_q.data(), cpu::H); + + // ---- the activation contract must be OBSERVABLE, or check 1 is vacuous + { + const bool visible = trap_contract > 1e-4; + std::printf(" %-44s %s (%.4f%% apart)\n", "the Q8_1 activation contract is observable", + visible ? "yes" : "*** NO ***", trap_contract * 100); + if (!visible) ++bad; + } + + // ---- 1. the kernel, against an oracle fed the SAME activations + std::printf(" %-44s rel %.3e (P2.S3 asks <= 3e-3, mean |ref| %.4f)\n", "VNNI vs scalar (INT8 acts)", + rel_kernel, mag); + if (!(rel_kernel <= 3e-3)) { std::printf(" *** over P2.S3's 3e-3 ***\n"); ++bad; } + + // ---- 2. the activation contract's own cost, reported rather than asserted + std::printf(" %-44s rel %.3e (the cost of the contract, REPORTED)\n", + "VNNI vs scalar (FP32 acts)", rel_contract); + + std::printf("\nexpert_parity: %d failures (layer %lld expert %lld of %s)\n", bad, layer, expert, path); + if (bad) return 1; + if (selftest) std::printf("expert_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/cpu/iq_avx2.cpp b/engine/strata/src/kernels/cpu/iq_avx2.cpp new file mode 100644 index 00000000..790d9dcd --- /dev/null +++ b/engine/strata/src/kernels/cpu/iq_avx2.cpp @@ -0,0 +1,440 @@ +// src/kernels/cpu/iq_avx2.cpp - the i-quant expert rows in 256-bit lanes, several tokens at once. +// +// The AVX-512 kernels' (iq_avx512.cpp) multi-token scheme on the CPUs without AVX-512 (AMD Zen 2/3, Intel +// Core 12th-14th gen and Core Ultra): each 32-value chunk is decoded once - grid lookups, one sign vector, +// one scale vector - and every token of the verify window applies them with a load, a `sign`, a `maddubs`, +// a `madd` and an `add`. ggml-cpu's own AVX2 dot products for these formats are single-token: every token +// re-does the codebook lookups and the sign expansion. The sign vector is ggml's bit_selector pattern +// (ggml-cpu/arch/x86/quants.c): pshufb-broadcast of each sign byte, AND with the bit selector, CMPEQ, OR +// with one, `vpsignb`. The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the +// order of the float additions differs. +// +// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu. +#include "strata/kernels/cpu/iq_avx2.hpp" + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#include + +#include +#include +#include + +namespace strata::kernels::cpu { +namespace { + +inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); } +inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; } +inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } +inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } + +// 32 sign bits -> 32 bytes of -1 (bit set) / +1: ggml's bit_selector pattern, shared by all tokens. +inline __m256i sgn_vec(uint32_t m) { + const __m128i bm = _mm_set1_epi32((int) m); + const __m128i lo = _mm_shuffle_epi8(bm, _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1)); + const __m128i hi = _mm_shuffle_epi8(bm, _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3)); + const __m256i bits = _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + const __m256i sel = _mm256_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80, + 1, 2, 4, 8, 16, 32, 64, (char) 0x80, + 1, 2, 4, 8, 16, 32, 64, (char) 0x80, + 1, 2, 4, 8, 16, 32, 64, (char) 0x80); + const __m256i nz = _mm256_cmpeq_epi8(_mm256_and_si256(bits, sel), sel); + return _mm256_or_si256(nz, _mm256_set1_epi8(1)); +} + +// The two 16-value scales of one 32-value half (IQ2_XS, IQ2_S): int16 lanes 0-7 = a (values 0-15), +// 8-15 = b (values 16-31). NOT a broadcast dword [a,b] - that would alternate the scales lane by lane. +inline __m256i sc16(int a, int b) { + return _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi16((short) a)), + _mm_set1_epi16((short) b), 1); +} +// One scale for the whole 32-value half (IQ2_XXS, IQ3_XXS, IQ3_S). +inline __m256i sc32(int s) { return _mm256_set1_epi16(s); } + +// keven_signs_q2xs (ggml keeps it static in arch/x86/quants.c): one u64 per 7-bit sign index, byte k +// = 0xFF when bit k of ksigns_iq2xs[i] is set, 0x01 otherwise. With this a whole 32-value sign vector +// is four scalar loads and a set_epi64x - no ksigns byte packing chain and no bit_selector expansion. +// Built once at load time from the shared ggml-common table so it can never drift from it. +struct EvenSigns { + uint64_t v[128]; + EvenSigns() { + for (int i = 0; i < 128; ++i) { + uint64_t r = 0; + for (int k = 0; k < 8; ++k) + r |= (uint64_t) (((ksigns_iq2xs[i] >> k) & 1) ? 0xFF : 0x01) << (8 * k); + v[i] = r; + } + } +}; +static const EvenSigns even_signs; + +inline float hsum8(__m256 v) { + const __m128 lo = _mm256_castps256_ps128(v), hi = _mm256_extractf128_ps(v, 1); + __m128 s = _mm_add_ps(lo, hi); + s = _mm_hadd_ps(s, s); + s = _mm_hadd_ps(s, s); + return _mm_cvtss_f32(s); +} + +// E-2 (iq_avx512.cpp) on the AVX-2 path: the pool streams the expert rows from DRAM at ~25 GB/s (4 KB pages +// when large pages are refused), so ask for the bytes a few blocks before the decode needs them - 2048 B is +// two gate/up rows ahead, a row is ~1 KB. Same switch as the AVX-512 kernels: STRATA_IQ_PREFETCH is the +// distance in bytes, 0 = off, default 2048. Measured on a Zen 3 5700X3D (no AVX-512) on IQ3_S decode: -4% on +// the gate/up phase, +1.0 GB/s over the rows, -1.3% ms/round end to end. The non-temporal hint measured +// worse than T0 at the same distance, so this keeps T0. +const int prefetch_ahead = [] { + const char* v = std::getenv("STRATA_IQ_PREFETCH"); + return v ? std::atoi(v) : 2048; +}(); + +inline void rows_ahead(const uint8_t* p) { + if (prefetch_ahead <= 0) return; + _mm_prefetch((const char*) p, _MM_HINT_T0); + _mm_prefetch((const char*) p + 64, _MM_HINT_T0); +} + +// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector, scales +template struct Fmt32; + +template <> struct Fmt32<16> { // IQ2_XXS: d, qs[32] u16 + static constexpr int bytes = 66; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { + const uint8_t* q = b + 2 + 16 * j + 8 * half; + const uint32_t w0 = u32(q), w1 = u32(q + 4); + g = _mm256_set_epi64x((long long) iq2xxs_grid[w0 >> 24], (long long) iq2xxs_grid[(w0 >> 16) & 255], + (long long) iq2xxs_grid[(w0 >> 8) & 255], (long long) iq2xxs_grid[w0 & 255]); + sgn = _mm256_set_epi64x((long long) even_signs.v[(w1 >> 21) & 127], (long long) even_signs.v[(w1 >> 14) & 127], + (long long) even_signs.v[(w1 >> 7) & 127], (long long) even_signs.v[w1 & 127]); + sc = sc32(2 * (int) (w1 >> 28) + 1); + } +}; + +template <> struct Fmt32<17> { // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8] + static constexpr int bytes = 74; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { + uint16_t v[8]; + std::memcpy(v, b + 2 + 16 * j, 16); + const int o = 4 * half; + g = _mm256_set_epi64x((long long) iq2xs_grid[v[o + 3] & 511], (long long) iq2xs_grid[v[o + 2] & 511], + (long long) iq2xs_grid[v[o + 1] & 511], (long long) iq2xs_grid[v[o] & 511]); + uint32_t s = 0; + for (int l = 0; l < 4; ++l) s |= (uint32_t) ksigns_iq2xs[v[o + l] >> 9] << (8 * l); + sgn = sgn_vec(s); + const uint8_t sb = b[66 + 2 * j + half]; + sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1); + } +}; + +template <> struct Fmt32<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8] + static constexpr int bytes = 82; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { + const uint8_t* qs = b + 2 + 8 * j; + const uint8_t h = b[66 + 2 * j + half]; + const int o = 4 * half; + g = _mm256_set_epi64x((long long) iq2s_grid[qs[o + 3] | ((h << 2) & 0x300)], + (long long) iq2s_grid[qs[o + 2] | ((h << 4) & 0x300)], + (long long) iq2s_grid[qs[o + 1] | ((h << 6) & 0x300)], + (long long) iq2s_grid[qs[o] | ((h << 8) & 0x300)]); + const uint64_t m = u64(b + 2 + 32 + 8 * j); + sgn = sgn_vec(half ? (uint32_t) (m >> 32) : (uint32_t) m); + const uint8_t sb = b[74 + 2 * j + half]; + sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1); + } +}; + +template <> struct Fmt32<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale) + static constexpr int bytes = 98; + static constexpr float K = 0.25f; + static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { + const uint8_t* q = b + 2 + 16 * j + 8 * half; + g = _mm256_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]], + (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); + const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half); + sgn = _mm256_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127], + (long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]); + sc = sc32(2 * (int) (w >> 28) + 1); + } +}; + +template <> struct Fmt32<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4] + static constexpr int bytes = 110; + static constexpr float K = 1.0f; + static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) { + const uint8_t* q = b + 2 + 16 * j + 8 * half; + const uint32_t h = b[66 + 2 * j + half]; +#define G3(k) (int) iq3s_grid[q[k] | (((h >> k) & 1u) << 8)] + g = _mm256_set_epi32(G3(7), G3(6), G3(5), G3(4), G3(3), G3(2), G3(1), G3(0)); +#undef G3 + const uint64_t m = u64(b + 74 + 8 * j); + sgn = sgn_vec(half ? (uint32_t) (m >> 32) : (uint32_t) m); + const uint8_t s = b[106 + j]; + sc = sc32(half ? 2 * (s >> 4) + 1 : 2 * (s & 15) + 1); + } +}; + +template +inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { + __m256 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); + for (int i = 0; i < nblocks; ++i) { + const uint8_t* blk = row + (size_t) i * Fmt32::bytes; + rows_ahead(blk + prefetch_ahead); + __m256i acci[NT]; + for (int t = 0; t < NT; ++t) acci[t] = _mm256_setzero_si256(); + for (int j = 0; j < 4; ++j) { + for (int half = 0; half < 2; ++half) { + __m256i g, sgn, sc; + Fmt32::decode(blk, j, half, g, sgn, sc); + const int off = 64 * j + 32 * half; + for (int t = 0; t < NT; ++t) { + const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off)); + const __m256i ys = _mm256_sign_epi8(yv, sgn); + acci[t] = _mm256_add_epi32(acci[t], _mm256_madd_epi16(_mm256_maddubs_epi16(g, ys), sc)); + } + } + } + const float dx = h2f(u16(blk)) * Fmt32::K; + for (int t = 0; t < NT; ++t) + accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(acci[t]), accf[t]); + } + for (int t = 0; t < NT; ++t) res[t] = hsum8(accf[t]); +} + +// ---- IQ2_XS (17) with ggml's vectorized sign decode (arch/x86/quants.c, ggml_vec_dot_iq2_xs_q8_K): +// the 7-bit sign indices never touch ksigns_iq2xs - the 8th sign bit is reconstructed by parity (two +// shifts, a xor and ggml's bit_helper pshufb) and the per-half sign vectors come out of shuffles of one +// 32-byte load. The 8 scale bytes become all 16 half-scales with ggml's unpack trick. The grid lookups +// stay scalar loads into set_epi64x (ggml does the same). Every token still only pays a load, a sign, +// a maddubs, a madd and an add per half, into alternating accumulators. +template +inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { + static const uint8_t bit_sel[32] = { + 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, + 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80, 1, 2, 4, 8, 16, 32, 64, (uint8_t) 0x80 }; + static const char shuf_even[32] = { // sign bits of u16 0,1,2,3 (even bytes of the sign register) + 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, + 4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6, 6, 6 }; + static const char shuf_odd[32] = { // sign bits of u16 4,5,6,7 + 8, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, + 12, 12, 12, 12, 12, 12, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14 }; + static const uint8_t bit_help[32] = { // 0x80 when the 4-bit index has odd popcount (parity bit 7) + 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, + (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, + 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, + (uint8_t) 0x80, 0x00, 0x00, (uint8_t) 0x80, 0x00, (uint8_t) 0x80, (uint8_t) 0x80, 0x00 }; + static const uint8_t k_sc_shuffle[128] = { // half h -> scale bytes 2h (lanes 0-7), 2h+1 (lanes 8-15) + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, + 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, + 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, + 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15 }; + const __m256i bsel = _mm256_loadu_si256((const __m256i*) bit_sel); + const __m256i shev = _mm256_loadu_si256((const __m256i*) shuf_even); + const __m256i shod = _mm256_loadu_si256((const __m256i*) shuf_odd); + const __m256i bhelp = _mm256_loadu_si256((const __m256i*) bit_help); + const __m256i m511 = _mm256_set1_epi16(511); + const __m128i m4 = _mm_set1_epi8(0xf), m1 = _mm_set1_epi8(1); + const __m256i one8 = _mm256_set1_epi8(1); + + __m256 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); + for (int i = 0; i < nblocks; ++i) { + const uint8_t* blk = row + (size_t) i * 74; + rows_ahead(blk + prefetch_ahead); + // the 8 scale bytes -> 16 half-scales of 2*s+1, interleaved [a0, b0, a1, b1, ...] (ggml's unpack) + __m128i st = _mm_set1_epi64x((long long) u64(blk + 66)); + st = _mm_unpacklo_epi8(_mm_and_si128(st, m4), _mm_and_si128(_mm_srli_epi16(st, 4), m4)); + const __m128i scales = _mm_add_epi8(_mm_slli_epi16(st, 1), m1); + __m256i acc[NT][2]; + for (int t = 0; t < NT; ++t) acc[t][0] = acc[t][1] = _mm256_setzero_si256(); + for (int jj = 0; jj < 2; ++jj) { // 128 values (16 u16) per step + const __m256i q2 = _mm256_loadu_si256((const __m256i*) (blk + 2 + 32 * jj)); + const __m256i p7 = _mm256_srli_epi16(q2, 9); // 7 sign bits per u16, even bytes + const __m256i p3 = _mm256_srli_epi16(q2, 13); // sign index bits 4-6 + const __m256i fsb = _mm256_or_si256(p7, + _mm256_shuffle_epi8(bhelp, _mm256_xor_si256(p7, p3))); // + the parity sign bit 7 + const __m256i s01 = _mm256_broadcastsi128_si256(_mm256_castsi256_si128(fsb)); // u16 0-7 + const __m256i s23 = _mm256_broadcastsi128_si256(_mm256_extracti128_si256(fsb, 1)); // u16 8-15 + alignas(32) uint16_t gi[16]; + _mm256_store_si256((__m256i*) gi, _mm256_and_si256(q2, m511)); + for (int h = 0; h < 4; ++h) { // the four 32-value halves of this group + const int H = 4 * jj + h; // global half index -> scales byte pair + const __m256i g = _mm256_set_epi64x((long long) iq2xs_grid[gi[4 * h + 3]], + (long long) iq2xs_grid[gi[4 * h + 2]], + (long long) iq2xs_grid[gi[4 * h + 1]], + (long long) iq2xs_grid[gi[4 * h]]); + const __m256i sb = _mm256_shuffle_epi8(h < 2 ? s01 : s23, (h & 1) ? shod : shev); + const __m256i sgn = _mm256_or_si256( + _mm256_cmpeq_epi8(_mm256_and_si256(sb, bsel), bsel), one8); + const __m256i sc = _mm256_cvtepi8_epi16( + _mm_shuffle_epi8(scales, _mm_loadu_si128((const __m128i*) k_sc_shuffle + H))); + const int off = 128 * jj + 32 * h; + for (int t = 0; t < NT; ++t) { + const __m256i yv = _mm256_loadu_si256((const __m256i*) (y[t][i].qs + off)); + const __m256i ys = _mm256_sign_epi8(yv, sgn); + acc[t][h & 1] = _mm256_add_epi32(acc[t][h & 1], + _mm256_madd_epi16(_mm256_maddubs_epi16(g, ys), sc)); + } + } + } + const float dx = h2f(u16(blk)) * 0.125f; + for (int t = 0; t < NT; ++t) + accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), + _mm256_cvtepi32_ps(_mm256_add_epi32(acc[t][0], acc[t][1])), accf[t]); + } + for (int t = 0; t < NT; ++t) res[t] = hsum8(accf[t]); +} + +template +inline void row_dot_any(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { + if constexpr (TY == 17) row_dot_iq2xs(row, nblocks, y, res); + else row_dot(row, nblocks, y, res); +} + +template +void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, + int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + const int nb = n / QK_K; + float g[NT], u[NT]; + for (int r = r0; r < r1; ++r) { + row_dot_any(blob + (size_t) r * gu_row, nb, y, g); + row_dot_any(blob + up_off + (size_t) r * gu_row, nb, y, u); + for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } +} + +template +void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + float res[NT]; + for (int r = r0; r < r1; ++r) { + row_dot_any(w + (size_t) r * row_bytes, n / QK_K, y, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} + +template +void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + float* const* ff, int r0, int r1) { + switch (nt) { + case 1: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 2: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 3: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 4: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 5: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 6: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 7: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + } +} + +template +void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, + int r1) { + switch (nt) { + case 1: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 2: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 3: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 4: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + default: for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + dot_rows_nt(k, w, row_bytes, n, act + t0, out + t0, r0, r1); + } + } +} + +} // namespace + +bool iq256_supported(int type) noexcept { + return type == 16 || type == 17 || type == 18 || type == 21 || type == 22; +} + +void iq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, + float* const* ff, int r0, int r1) { + switch (type) { + case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: break; + } +} + +void iq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, + int r0, int r1) { + switch (type) { + case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 18: dot_rows_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 21: dot_rows_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 22: dot_rows_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break; + default: break; + } +} + +// ---- IQ4_NL (type 20): 32-value blocks of 18 bytes (f16 d + 16 nibble bytes) against Q8_0 activations. +// ggml-cpu's own AVX-2 dot (ggml_vec_dot_iq4_nl_q8_0) is single-token: every token redoes the nibble -> +// kvalues_iq4nl pshufb decode and the |w| half of the signed x signed product. Here both are computed once +// per block; every token then costs a sign, a maddubs, a madd and an fmadd. The arithmetic is ggml's - only +// the order of the float additions differs. +template +void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out, + int r0, int r1) { + const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl); + const __m128i m4b = _mm_set1_epi8(0x0f); + const __m256i ones = _mm256_set1_epi16(1); + const int nb = n / QK4_NL; + for (int r = r0; r < r1; ++r) { + const uint8_t* row = w + (size_t) r * row_bytes; + __m256 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps(); + for (int ib = 0; ib < nb; ++ib) { + const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl); + rows_ahead(blk + prefetch_ahead); + const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2)); + const __m128i lo = _mm_and_si128(bits, m4b); // values 0..15 + const __m128i hi = _mm_and_si128(_mm_srli_epi16(bits, 4), m4b); // values 16..31 + const __m256i q4 = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_shuffle_epi8(values, lo)), + _mm_shuffle_epi8(values, hi), 1); + const __m256i aq = _mm256_sign_epi8(q4, q4); // |w|: the unsigned operand of maddubs + const float dx = h2f(u16(blk)); + for (int t = 0; t < NT; ++t) { + const block_q8_0& b = y[t][ib]; + const __m256i q8 = _mm256_loadu_si256((const __m256i*) b.qs); + const __m256i p = _mm256_madd_epi16(_mm256_maddubs_epi16(aq, _mm256_sign_epi8(q8, q4)), ones); + accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * h2f(b.d)), _mm256_cvtepi32_ps(p), accf[t]); + } + } + for (int t = 0; t < NT; ++t) out[t][r] = hsum8(accf[t]); + } +} + +void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, float* const* out, + int r0, int r1) { + const block_q8_0* y[8]; + for (int t = 0; t < nt; ++t) y[t] = (const block_q8_0*) hq[t]; + switch (nt) { + case 1: iq4nl_rows<1>(w, row_bytes, n, y, out, r0, r1); break; + case 2: iq4nl_rows<2>(w, row_bytes, n, y, out, r0, r1); break; + case 3: iq4nl_rows<3>(w, row_bytes, n, y, out, r0, r1); break; + case 4: iq4nl_rows<4>(w, row_bytes, n, y, out, r0, r1); break; + default: for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + iq4nl256_down_rows(w, row_bytes, n, hq + t0, k, out + t0, r0, r1); + } + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/iq_avx512.cpp b/engine/strata/src/kernels/cpu/iq_avx512.cpp new file mode 100644 index 00000000..26d2c5a7 --- /dev/null +++ b/engine/strata/src/kernels/cpu/iq_avx512.cpp @@ -0,0 +1,273 @@ +// src/kernels/cpu/iq_avx512.cpp - plan v0.3 P6: the i-quant expert rows in 512-bit lanes, several tokens at once. +// +// ggml-cpu's x86 dot products for these formats are AVX2 and single-token: every token re-decodes the weights +// and a sign is applied with five instructions per 32 values. Here 64 values are decoded once (8 or 16 grid +// lookups, one 64-bit sign mask, one vector of scales) and every token applies them with a masked subtract, a +// `maddubs` and a `madd`. The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references): integer sums +// per block, times d_x * d_y * the format's constant - only the order of the float additions differs. +// +// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu (no shipped +// model has IQ1_M expert rows: the 'Coder IQ1_M' pack's gate/up are IQ2_S / IQ3_XXS / IQ3_S). +#include "strata/kernels/cpu/iq_avx512.hpp" + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#include + +#include +#include +#include + +namespace strata::kernels::cpu { +namespace { + +inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); } +inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; } +inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } +inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; } + +// E-2: the IQ3 grids by one AVX-512 gather (the same words, the same results) - measured 3-5% SLOWER than the scalar +// lookups on a Ryzen 5 7600 (Zen 4 gathers are microcoded), so opt-in: STRATA_IQ_GATHER=1 +const bool gather = std::getenv("STRATA_IQ_GATHER") != nullptr; +// E-2: software prefetch distance in bytes (STRATA_IQ_PREFETCH; 0 = off): -2-3% gate/up time on IQ3_S decode +// (the rows are read at ~30 GB/s by 6 cores, near what DDR5 with 4 KB pages gives: the pool is memory-bound) +const int prefetch_ahead = [] { + const char* v = std::getenv("STRATA_IQ_PREFETCH"); + return v ? std::atoi(v) : 2048; +}(); + +// lanes 0-7 -> s0, 8-15 -> s1, 16-23 -> s2, 24-31 -> s3 (int16 lanes of a maddubs result: two values each) +inline __m512i scales4(int s0, int s1, int s2, int s3) { + const __m512i idx = _mm512_set_epi16(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0); + const uint64_t packed = (uint64_t) (uint16_t) s0 | ((uint64_t) (uint16_t) s1 << 16) | + ((uint64_t) (uint16_t) s2 << 32) | ((uint64_t) (uint16_t) s3 << 48); + return _mm512_permutexvar_epi16(idx, _mm512_set1_epi64((long long) packed)); +} + +// ---- per format: 64 values (chunk j of a 256-value block) -> grid magnitudes, sign mask, scales +template struct Fmt; + +template <> struct Fmt<16> { // IQ2_XXS: d, qs[32] u16 + static constexpr int bytes = 66; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { + const uint8_t* q = b + 2 + 16 * j; + const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12); + g = _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], + (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255], + (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255], + (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]); + const uint64_t s = (uint64_t) ksigns_iq2xs[a1 & 127] | ((uint64_t) ksigns_iq2xs[(a1 >> 7) & 127] << 8) | + ((uint64_t) ksigns_iq2xs[(a1 >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a1 >> 21) & 127] << 24) | + ((uint64_t) ksigns_iq2xs[b1 & 127] << 32) | ((uint64_t) ksigns_iq2xs[(b1 >> 7) & 127] << 40) | + ((uint64_t) ksigns_iq2xs[(b1 >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(b1 >> 21) & 127] << 56); + m = _cvtu64_mask64(s); + const int sa = 2 * (int) (a1 >> 28) + 1, sb = 2 * (int) (b1 >> 28) + 1; + sc = scales4(sa, sa, sb, sb); + } +}; + +template <> struct Fmt<17> { // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8] + static constexpr int bytes = 74; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { + const uint8_t* q = b + 2 + 16 * j; + uint16_t v[8]; + std::memcpy(v, q, 16); + g = _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], + (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511], + (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511], + (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]); + uint64_t s = 0; + for (int l = 0; l < 8; ++l) s |= (uint64_t) ksigns_iq2xs[v[l] >> 9] << (8 * l); + m = _cvtu64_mask64(s); + const uint8_t s0 = b[66 + 2 * j], s1 = b[66 + 2 * j + 1]; + sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1); + } +}; + +template <> struct Fmt<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8] + static constexpr int bytes = 82; + static constexpr float K = 0.125f; + static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { + const uint8_t* qs = b + 2 + 8 * j; + const uint8_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1]; + g = _mm512_set_epi64((long long) iq2s_grid[qs[7] | ((h1 << 2) & 0x300)], (long long) iq2s_grid[qs[6] | ((h1 << 4) & 0x300)], + (long long) iq2s_grid[qs[5] | ((h1 << 6) & 0x300)], (long long) iq2s_grid[qs[4] | ((h1 << 8) & 0x300)], + (long long) iq2s_grid[qs[3] | ((h0 << 2) & 0x300)], (long long) iq2s_grid[qs[2] | ((h0 << 4) & 0x300)], + (long long) iq2s_grid[qs[1] | ((h0 << 6) & 0x300)], (long long) iq2s_grid[qs[0] | ((h0 << 8) & 0x300)]); + m = _cvtu64_mask64(u64(b + 2 + 32 + 8 * j)); + const uint8_t s0 = b[74 + 2 * j], s1 = b[74 + 2 * j + 1]; + sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1); + } +}; + +template <> struct Fmt<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale) + static constexpr int bytes = 98; + static constexpr float K = 0.25f; + static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { + const uint8_t* q = b + 2 + 16 * j; + // E-2: one gather of the 16 grid words (the scalar lookups assembled with set_epi32 cost ~30 uops) + g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4) + : _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]], + (int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]], + (int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]], + (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); + const uint32_t a = u32(b + 2 + 64 + 8 * j), c = u32(b + 2 + 64 + 8 * j + 4); + const uint64_t s = (uint64_t) ksigns_iq2xs[a & 127] | ((uint64_t) ksigns_iq2xs[(a >> 7) & 127] << 8) | + ((uint64_t) ksigns_iq2xs[(a >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a >> 21) & 127] << 24) | + ((uint64_t) ksigns_iq2xs[c & 127] << 32) | ((uint64_t) ksigns_iq2xs[(c >> 7) & 127] << 40) | + ((uint64_t) ksigns_iq2xs[(c >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(c >> 21) & 127] << 56); + m = _cvtu64_mask64(s); + const int sa = 2 * (int) (a >> 28) + 1, sb = 2 * (int) (c >> 28) + 1; + sc = scales4(sa, sa, sb, sb); + } +}; + +template <> struct Fmt<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4] + static constexpr int bytes = 110; + static constexpr float K = 1.0f; + static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { + const uint8_t* q = b + 2 + 16 * j; + const uint32_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1]; + if (gather) { // E-2: the 9-bit indices (the high bit from qh under a mask), one gather + __m512i idx = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)); + idx = _mm512_mask_add_epi32(idx, (__mmask16) (h0 | (h1 << 8)), idx, _mm512_set1_epi32(256)); + g = _mm512_i32gather_epi32(idx, iq3s_grid, 4); + } else { +#define G3(k, h, kk) (int) iq3s_grid[q[k] | (((h >> kk) & 1) << 8)] + g = _mm512_set_epi32(G3(15, h1, 7), G3(14, h1, 6), G3(13, h1, 5), G3(12, h1, 4), + G3(11, h1, 3), G3(10, h1, 2), G3(9, h1, 1), G3(8, h1, 0), + G3(7, h0, 7), G3(6, h0, 6), G3(5, h0, 5), G3(4, h0, 4), + G3(3, h0, 3), G3(2, h0, 2), G3(1, h0, 1), G3(0, h0, 0)); +#undef G3 + } + m = _cvtu64_mask64(u64(b + 74 + 8 * j)); + const uint8_t s = b[106 + j]; + const int sa = 2 * (s & 15) + 1, sb = 2 * (s >> 4) + 1; + sc = scales4(sa, sa, sb, sb); + } +}; + +template +inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) { + __m512 accf[NT]; + for (int t = 0; t < NT; ++t) accf[t] = _mm512_setzero_ps(); + const __m512i zero = _mm512_setzero_si512(); + for (int i = 0; i < nblocks; ++i) { + const uint8_t* blk = row + (size_t) i * Fmt::bytes; + // E-2: the weight rows stream from DRAM (4 KB pages when large pages are refused): ask for the bytes a few + // blocks ahead (the next row's start included) before the decode needs them + if (prefetch_ahead > 0) { + const uint8_t* ahead = blk + (size_t) prefetch_ahead; + _mm_prefetch((const char*) ahead, _MM_HINT_T0); + _mm_prefetch((const char*) ahead + 64, _MM_HINT_T0); + } + __m512i acci[NT]; + for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512(); + for (int j = 0; j < 4; ++j) { + __m512i g, sc; + __mmask64 m; + Fmt::decode(blk, j, g, m, sc); + for (int t = 0; t < NT; ++t) { + const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j)); + const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv); + acci[t] = _mm512_add_epi32(acci[t], _mm512_madd_epi16(_mm512_maddubs_epi16(g, ys), sc)); + } + } + const float dx = h2f(u16(blk)) * Fmt::K; + for (int t = 0; t < NT; ++t) + accf[t] = _mm512_fmadd_ps(_mm512_set1_ps(dx * y[t][i].d), _mm512_cvtepi32_ps(acci[t]), accf[t]); + } + for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(accf[t]); +} + +template +void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, + int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + const int nb = n / QK_K; + float g[NT], u[NT]; + for (int r = r0; r < r1; ++r) { + row_dot(blob + (size_t) r * gu_row, nb, y, g); + row_dot(blob + up_off + (size_t) r * gu_row, nb, y, u); + for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } +} + +template +void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) { + const block_q8_K* y[NT]; + for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t]; + float res[NT]; + for (int r = r0; r < r1; ++r) { + row_dot(w + (size_t) r * row_bytes, n / QK_K, y, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} + +template +void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, + float* const* ff, int r0, int r1) { + switch (nt) { + case 1: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 2: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 3: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 4: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 5: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 6: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 7: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: gu_rows(blob, gu_row, up_off, n, act, ff, r0, r1); break; + } +} + +template +void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, + int r1) { + switch (nt) { + case 1: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 2: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 3: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + case 4: dot_rows(w, row_bytes, n, act, out, r0, r1); break; + default: for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + dot_rows_nt(k, w, row_bytes, n, act + t0, out + t0, r0, r1); + } + } +} + +} // namespace + +bool iq512_supported(int type) noexcept { + return type == 16 || type == 17 || type == 18 || type == 21 || type == 22; +} + +void iq512_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, + float* const* ff, int r0, int r1) { + switch (type) { + case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break; + default: break; + } +} + +void iq512_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, + int r0, int r1) { + switch (type) { + case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 18: dot_rows_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 21: dot_rows_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break; + case 22: dot_rows_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break; + default: break; + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/kq_avx2.cpp b/engine/strata/src/kernels/cpu/kq_avx2.cpp new file mode 100644 index 00000000..a3473119 --- /dev/null +++ b/engine/strata/src/kernels/cpu/kq_avx2.cpp @@ -0,0 +1,265 @@ +// src/kernels/cpu/kq_avx2.cpp - Unsloth UD-Q4_K_XL's expert rows (Q4_K gate/up, Q5_1 and Q8_0 down) for several +// tokens at once, BIT-EXACT against ggml-cpu's own dot products. +// +// ggml-cpu is built for AVX2 here (STRATA_PORTABLE: GGML_AVX2=ON, GGML_AVX512=OFF), so its vec_dot for these formats +// is the __AVX2__ branch of ggml-cpu/arch/x86/quants.c: ggml_vec_dot_q4_K_q8_K, ggml_vec_dot_q5_1_q8_1, +// ggml_vec_dot_q8_0_q8_0. The functions below are those branches with the loop over tokens moved inside the loop +// over blocks: everything that depends only on the weights (the 4-bit unpacking, the 6-bit scales and mins, the +// fifth bits, the absolute values of the Q8_0 weights, the fp16 scales) is done once per block, and every token then +// runs exactly ggml's integer chain and ggml's float operations in ggml's order - so each token's result is ggml's +// to the bit (native_expert_parity checks it), whatever the number of tokens. Unlike the i-quant kernels (#152) +// the group size therefore never changes an answer. +// +// The gain is the weight-side work and the weight bytes, read once per verify window instead of once per token. +#include "strata/kernels/cpu/kq_avx2.hpp" + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#include + +#include +#include + +namespace strata::kernels::cpu { +namespace { + +constexpr int MAXT = 8; // the verify window's tokens per group (kVerifyMaxT) + +inline float h2f(ggml_half h) { + uint16_t u; + std::memcpy(&u, &h, 2); + return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) u))); +} +// the fp16 pair {d, dmin} / {d, m} / {d, s} a block starts with (a union in ggml-common.h's C++ declarations) +inline float half_at(const void* block, int i) { + ggml_half h; + std::memcpy(&h, (const uint8_t*) block + 2 * i, 2); + return h2f(h); +} + +// ---- ggml's helpers (ggml-cpu/arch/x86/quants.c, the AVX2 / non-VNNI forms), verbatim +inline float hsum_float_8(const __m256 x) { + __m128 res = _mm256_extractf128_ps(x, 1); + res = _mm_add_ps(res, _mm256_castps256_ps128(x)); + res = _mm_add_ps(res, _mm_movehl_ps(res, res)); + res = _mm_add_ss(res, _mm_movehdup_ps(res)); + return _mm_cvtss_f32(res); +} +inline __m256i bytes_from_bits_32(const uint8_t* x) { + uint32_t x32; + std::memcpy(&x32, x, sizeof(uint32_t)); + const __m256i shuf_mask = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, + 0x0000000000000000); + __m256i bytes = _mm256_shuffle_epi8(_mm256_set1_epi32((int) x32), shuf_mask); + const __m256i bit_mask = _mm256_set1_epi64x(0x7fbfdfeff7fbfdfe); + bytes = _mm256_or_si256(bytes, bit_mask); + return _mm256_cmpeq_epi8(bytes, _mm256_set1_epi64x(-1)); +} +inline __m256i bytes_from_nibbles_32(const uint8_t* rsi) { + const __m128i tmp = _mm_loadu_si128((const __m128i*) rsi); + const __m256i bytes = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), _mm_srli_epi16(tmp, 4), 1); + const __m256i lowMask = _mm256_set1_epi8(0xF); + return _mm256_and_si256(lowMask, bytes); +} +inline __m256 sum_i16_pairs_float(const __m256i x) { + const __m256i ones = _mm256_set1_epi16(1); + return _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, x)); +} +inline __m256 mul_sum_us8_pairs_float(const __m256i ax, const __m256i sy) { + return sum_i16_pairs_float(_mm256_maddubs_epi16(ax, sy)); +} +alignas(32) const uint8_t k_shuffle[256] = { + 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, + 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, + 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, + 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, + 10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11, + 12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13, + 14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15}; +inline __m256i get_scale_shuffle_k4(int i) { return _mm256_loadu_si256((const __m256i*) k_shuffle + i); } + +// ---- Q4_K x Q8_K (ggml_vec_dot_q4_K_q8_K, __AVX2__) +void q4k_dot(const block_q4_K* x, int nb, const void* const* act, int nt, float* res) { + static const uint32_t kmask1 = 0x3f3f3f3f, kmask2 = 0x0f0f0f0f, kmask3 = 0x03030303; + const __m256i m4 = _mm256_set1_epi8(0xF); + __m256 acc[MAXT]; + __m128 acc_m[MAXT]; + for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); acc_m[t] = _mm_setzero_ps(); } + for (int i = 0; i < nb; ++i) { + const float xd = half_at(&x[i], 0), xdmin = half_at(&x[i], 1); + uint32_t utmp[4]; + std::memcpy(utmp, x[i].scales, 12); + utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4); + const uint32_t uaux = utmp[1] & kmask1; + utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4); + utmp[2] = uaux; + utmp[0] &= kmask1; + const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32((int) utmp[3], (int) utmp[2], + (int) utmp[1], (int) utmp[0])); + const __m128i mins = _mm256_extracti128_si256(mins_and_scales, 1); + const __m128i sc128 = _mm256_extracti128_si256(mins_and_scales, 0); + const __m256i scales = _mm256_insertf128_si256(_mm256_castsi128_si256(sc128), sc128, 1); + __m256i scale_l[4], scale_h[4], q4l[4], q4h[4]; + const uint8_t* q4 = x[i].qs; + for (int j = 0; j < QK_K / 64; ++j) { + scale_l[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0)); + scale_h[j] = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1)); + const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4); + q4 += 32; + q4l[j] = _mm256_and_si256(q4bits, m4); + q4h[j] = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4); + } + for (int t = 0; t < nt; ++t) { + const block_q8_K* y = (const block_q8_K*) act[t] + i; + const float d = y->d * xd; + const float dmin = -y->d * xdmin; + const int8_t* q8 = y->qs; + const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y->bsums); + const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1)); + const __m128i prod = _mm_madd_epi16(mins, q8s); + acc_m[t] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[t]); + __m256i sumi = _mm256_setzero_si256(); + for (int j = 0; j < QK_K / 64; ++j) { + const __m256i q8l = _mm256_loadu_si256((const __m256i*) q8); + q8 += 32; + __m256i p16l = _mm256_maddubs_epi16(q4l[j], q8l); + p16l = _mm256_madd_epi16(scale_l[j], p16l); + const __m256i q8h = _mm256_loadu_si256((const __m256i*) q8); + q8 += 32; + __m256i p16h = _mm256_maddubs_epi16(q4h[j], q8h); + p16h = _mm256_madd_epi16(scale_h[j], p16h); + sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16l, p16h)); + } + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]); + } + } + for (int t = 0; t < nt; ++t) { + __m128 m = acc_m[t]; + m = _mm_add_ps(m, _mm_movehl_ps(m, m)); + m = _mm_add_ss(m, _mm_movehdup_ps(m)); + res[t] = hsum_float_8(acc[t]) + _mm_cvtss_f32(m); + } +} + +// ---- Q5_1 x Q8_1 (ggml_vec_dot_q5_1_q8_1, __AVX2__) +void q5_1_dot(const block_q5_1* x, int nb, const void* const* act, int nt, float* res) { + __m256 acc[MAXT]; + float summs[MAXT]; + for (int t = 0; t < nt; ++t) { acc[t] = _mm256_setzero_ps(); summs[t] = 0.0f; } + for (int ib = 0; ib < nb; ++ib) { + const __m256 dx = _mm256_set1_ps(half_at(&x[ib], 0)); + const float xm = half_at(&x[ib], 1); + __m256i qx = bytes_from_nibbles_32(x[ib].qs); + __m256i bxhi = bytes_from_bits_32(x[ib].qh); + bxhi = _mm256_and_si256(bxhi, _mm256_set1_epi8(0x10)); + qx = _mm256_or_si256(qx, bxhi); + for (int t = 0; t < nt; ++t) { + const block_q8_1* y = (const block_q8_1*) act[t] + ib; + summs[t] += xm * half_at(y, 1); + const __m256 dy = _mm256_set1_ps(half_at(y, 0)); + const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); + const __m256 q = mul_sum_us8_pairs_float(qx, qy); + acc[t] = _mm256_fmadd_ps(q, _mm256_mul_ps(dx, dy), acc[t]); + } + } + for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]) + summs[t]; +} + +// ---- Q8_0 x Q8_0 (ggml_vec_dot_q8_0_q8_0, __AVX2__; mul_sum_i8_pairs_float without AVX-VNNI-INT8) +void q8_0_dot(const block_q8_0* x, int nb, const void* const* act, int nt, float* res) { + __m256 acc[MAXT]; + for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); + for (int ib = 0; ib < nb; ++ib) { + const float xd = h2f(x[ib].d); + const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs); + const __m256i ax = _mm256_sign_epi8(qx, qx); + for (int t = 0; t < nt; ++t) { + const block_q8_0* y = (const block_q8_0*) act[t] + ib; + const __m256 d = _mm256_set1_ps(xd * h2f(y->d)); + const __m256i qy = _mm256_loadu_si256((const __m256i*) y->qs); + const __m256i sy = _mm256_sign_epi8(qy, qx); + const __m256 q = mul_sum_us8_pairs_float(ax, sy); + acc[t] = _mm256_fmadd_ps(d, q, acc[t]); + } + } + for (int t = 0; t < nt; ++t) res[t] = hsum_float_8(acc[t]); +} + +void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int nt, float* res) { + switch (type) { + case 12: q4k_dot((const block_q4_K*) row, n / QK_K, act, nt, res); break; + case 7: q5_1_dot((const block_q5_1*) row, n / QK5_1, act, nt, res); break; + case 8: q8_0_dot((const block_q8_0*) row, n / QK8_0, act, nt, res); break; + default: break; + } +} + +} // namespace + +bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type == 8; } + +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) { + // each row is read once for all `nt` (<= 8) tokens: the router (2.6 MB per layer) streams once per prediction + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc[8]; + for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); + for (int c = 0; c + 8 <= cols; c += 8) { + const __m256 wf = _mm256_castsi256_ps( + _mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))), 16)); + for (int t = 0; t < nt; ++t) acc[t] = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x + (size_t) t * cols + c), acc[t]); + } + for (int t = 0; t < nt; ++t) out[(size_t) t * rows + r] = hsum_float_8(acc[t]); // cols % 8 == 0 (2560) + } +} + +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out) { + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc = _mm256_setzero_ps(); + int c = 0; + for (; c + 8 <= cols; c += 8) { + const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))); + acc = _mm256_fmadd_ps(_mm256_castsi256_ps(_mm256_slli_epi32(h, 16)), _mm256_loadu_ps(x + c), acc); + } + float s = hsum_float_8(acc); + for (; c < cols; ++c) { + const uint32_t b = (uint32_t) wr[c] << 16; + float f; + std::memcpy(&f, &b, 4); + s += f * x[c]; + } + out[r] = s; + } +} + +void kq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, + float* const* ff, int r0, int r1) { + for (int t0 = 0; t0 < nt; t0 += MAXT) { + const int m = nt - t0 < MAXT ? nt - t0 : MAXT; + float g[MAXT], u[MAXT]; + for (int r = r0; r < r1; ++r) { + dot_rows(type, blob + (size_t) r * gu_row, n, act + t0, m, g); + dot_rows(type, blob + up_off + (size_t) r * gu_row, n, act + t0, m, u); + // native_gu_rows' own SwiGLU expression: the same bits as the per-token ggml path + for (int t = 0; t < m; ++t) ff[t0 + t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t]; + } + } +} + +void kq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, + int r0, int r1) { + for (int t0 = 0; t0 < nt; t0 += MAXT) { + const int m = nt - t0 < MAXT ? nt - t0 : MAXT; + float s[MAXT]; + for (int r = r0; r < r1; ++r) { + dot_rows(type, w + (size_t) r * row_bytes, n, act + t0, m, s); + for (int t = 0; t < m; ++t) out[t0 + t][r] = s[t]; + } + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/native_expert.cpp b/engine/strata/src/kernels/cpu/native_expert.cpp new file mode 100644 index 00000000..2e8d8adb --- /dev/null +++ b/engine/strata/src/kernels/cpu/native_expert.cpp @@ -0,0 +1,152 @@ +// src/kernels/cpu/native_expert.cpp - plan v0.3 P6: native (GGUF-form) experts on the CPU through ggml-cpu. +// See the header. Nothing here is Strata arithmetic: the activation quantizers and the row dot products are +// ggml-cpu's, so an IQ expert computes what llama.cpp's CPU backend computes for it. +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/iq_avx512.hpp" +#include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include + +namespace strata::kernels::cpu { +namespace { + +const ggml_type_traits_cpu* traits(int type) { return ggml_get_type_traits_cpu((ggml_type) type); } + +void init_once() { + static std::once_flag once; + std::call_once(once, [] { ggml_cpu_init(); }); +} + +} // namespace + +bool native_experts_available() noexcept { return true; } + +bool native_fmt(int gu_type, int d_type, int64_t n_embd, int64_t n_ff, NativeFmt& f, std::string& err) { + init_once(); + const ggml_type_traits_cpu* tg = traits(gu_type); + const ggml_type_traits_cpu* td = traits(d_type); + if (tg == nullptr || tg->vec_dot == nullptr || td == nullptr || td->vec_dot == nullptr) { + err = "native experts: ggml-cpu has no dot product for type " + std::to_string(tg && tg->vec_dot ? d_type : gu_type); + return false; + } + const ggml_type_traits_cpu* ag = traits(tg->vec_dot_type); + const ggml_type_traits_cpu* ad = traits(td->vec_dot_type); + if (ag == nullptr || ag->from_float == nullptr || ad == nullptr || ad->from_float == nullptr) { + err = "native experts: ggml-cpu cannot quantize an activation for this layer"; + return false; + } + if (n_embd % ggml_blck_size((ggml_type) gu_type) || n_ff % ggml_blck_size((ggml_type) d_type) || + n_embd % ggml_blck_size(tg->vec_dot_type) || n_ff % ggml_blck_size(td->vec_dot_type)) { + err = "native experts: expert geometry is not whole blocks"; + return false; + } + f.gu_type = gu_type; + f.d_type = d_type; + f.gu_act = (int) tg->vec_dot_type; + f.d_act = (int) td->vec_dot_type; + f.n_embd = n_embd; + f.n_ff = n_ff; + f.gu_row = ggml_row_size((ggml_type) gu_type, n_embd); + f.d_row = ggml_row_size((ggml_type) d_type, n_ff); + f.up_off = f.gu_row * (size_t) n_ff; + f.down_off = 2 * f.up_off; + f.bytes = f.down_off + f.d_row * (size_t) n_embd; + f.act_bytes = ggml_row_size(tg->vec_dot_type, n_embd); + f.h_bytes = ggml_row_size(td->vec_dot_type, n_ff); + if (f.act_bytes > kNativeActBytes || f.h_bytes > kNativeHBytes) { + err = "native experts: activation larger than the pool's buffers"; + return false; + } + return true; +} + +void native_quant_act(const NativeFmt& f, const float* x, void* dst) { + traits(f.gu_act)->from_float(x, dst, f.n_embd); +} + +void native_quant_h(const NativeFmt& f, const float* h, void* dst) { + traits(f.d_act)->from_float(h, dst, f.n_ff); +} + +void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* act, int nt, float* const* ff, + int r0, int r1) { + // the multi-token kernels decode the weights once for all tokens: 2.0-2.4x ggml-cpu at three tokens, no faster + // at one (all are bound by the codebook lookups, ~5 GB/s per core), measured by native_expert_parity. AVX-512 + // first, then the AVX-2 one (Zen 2/3, Intel 12th-14th gen). STRATA_NO_IQ512 drops an AVX-512 CPU to the + // AVX-2 kernel, STRATA_NO_IQ256 drops the AVX-2 kernel; ggml-cpu's single-token vec_dot is reached only with + // both set (and on a CPU without AVX-512, STRATA_NO_IQ512 changes nothing). + static const bool avx512 = cpu_avx512_ok() && std::getenv("STRATA_NO_IQ512") == nullptr; + static const bool avx2 = std::getenv("STRATA_NO_IQ256") == nullptr; + // #152: from how many tokens the multi-token kernels run (ggml's vec_dot below that). The default 2 is the + // measured-fastest rule, but a token's expert rows then round differently alone than in a group, so greedy output + // can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token + // kernels for every group: output independent of the drafting, at a measured -1..-3% decode on IQ3_S (AVX-512). + static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); + // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group + // size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold + // ~1.4 tokens and the weights stay in L1 across ggml's per-token calls; 1.01-1.13x in native_expert_parity). + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); + if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead) + kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } + if (nt >= mt_min && iq512_supported(f.gu_type)) { + if (avx512) { + iq512_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } + if (avx2) { + iq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); + return; + } + } + const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot; + const int n = (int) f.n_embd; + for (int r = r0; r < r1; ++r) { + const uint8_t* gr = blob + (size_t) r * f.gu_row; + const uint8_t* ur = blob + f.up_off + (size_t) r * f.gu_row; + for (int t = 0; t < nt; ++t) { + float g = 0.f, u = 0.f; + dot(n, &g, 0, gr, 0, act[t], 0, 1); + dot(n, &u, 0, ur, 0, act[t], 0, 1); + ff[t][r] = (g / (1.f + std::exp(-g))) * u; + } + } +} + +void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const* hq, int nt, float* const* out, + int r0, int r1) { + // IQ4_NL down rows: the AVX-2 multi-token kernel decodes the nibbles and absolutises the weights once per + // block instead of once per token; ggml-cpu's dot is single-token. STRATA_NO_IQ4NL falls back to it. + static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; + static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); + if (kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size + kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); + return; + } + if (nt >= mt_min && f.d_type == 20 && iq4nl_mt) { // #152: the same rule as the gate/up rows + iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); + return; + } + const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot; + const int n = (int) f.n_ff; + for (int r = r0; r < r1; ++r) { + const uint8_t* dr = blob + f.down_off + (size_t) r * f.d_row; + for (int t = 0; t < nt; ++t) { + float s = 0.f; + dot(n, &s, 0, dr, 0, hq[t], 0, 1); + out[t][r] = s; + } + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/pool.cpp b/engine/strata/src/kernels/cpu/pool.cpp new file mode 100644 index 00000000..45e43470 --- /dev/null +++ b/engine/strata/src/kernels/cpu/pool.cpp @@ -0,0 +1,753 @@ +// src/kernels/cpu/pool.cpp - P2.S3: the CPU expert pool. Read pool.hpp first; it explains the protocol. +#include "strata/kernels/cpu/pool.hpp" +#include "strata/core/progress.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#include +#include +#include +#include + +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#include +#else +#include +#include +#endif + +namespace strata::kernels::cpu { + +namespace { +constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { + return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i; +} +} // namespace + +CpuTopology detect_cpu_topology(bool skip_first, PoolAffinity affinity) { + CpuTopology topo; +#if defined(_WIN32) + // Ask the OS rather than assuming a layout. `hardware_concurrency()` returns LOGICAL processors, and on + // every SMT machine half of them are siblings - pinning one worker to each of the first N would put two + // workers on each physical core and halve the bandwidth the expert kernel is bound by. + DWORD len = 0; + GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); + if (len == 0) { + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) topo.worker_cores.push_back((int) i); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + std::vector buf(len); + if (GetLogicalProcessorInformationEx(RelationProcessorCore, + (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) { + const char* p = buf.data(); + const char* end = p + len; + struct CoreDesc { + uint8_t efficiency = 0; + bool has_smt = false; + std::vector lps; + }; + std::vector descs; + while (p < end) { + const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; + if (e->Relationship == RelationProcessorCore) { + CoreDesc cd; + cd.efficiency = e->Processor.EfficiencyClass; + cd.has_smt = (e->Processor.Flags & LTP_PC_SMT) != 0; + const GROUP_AFFINITY& g = e->Processor.GroupMask[0]; + for (int bit = 0; bit < 64; ++bit) { + if (g.Mask & (1ull << bit)) { + cd.lps.push_back((int) (g.Group * 64 + bit)); + } + } + if (!cd.lps.empty()) { + descs.push_back(std::move(cd)); + } + } + p += e->Size; + } + + uint8_t min_eff = 255, max_eff = 0; + for (const auto& c : descs) { + min_eff = (std::min)(min_eff, c.efficiency); + max_eff = (std::max)(max_eff, c.efficiency); + } + + topo.is_hybrid = (max_eff > min_eff); + if (topo.is_hybrid) { + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + topo.p_cores++; + topo.p_threads += (int) c.lps.size(); + } else { + topo.e_cores++; + } + } + } else { + topo.p_cores = (int) descs.size(); + for (const auto& c : descs) topo.p_threads += (int) c.lps.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& c : descs) topo.worker_cores.push_back(c.lps[0]); + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU with Auto or PCores affinity: + // Prioritize Performance cores: + // 1. Primary logical processor of each P-core (avoids SMT resource contention) + // 2. SMT sibling logical processors of P-cores + // 3. E-cores (only as overflow in Auto mode) + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& c : descs) { + if (c.efficiency == max_eff) { + p_primaries.push_back(c.lps[0]); + for (size_t s = 1; s < c.lps.size(); ++s) { + p_siblings.push_back(c.lps[s]); + } + } else { + for (int lp : c.lps) e_cores.push_back(lp); + } + } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; + } +#else + // The logical CPUs this process may run on, ONE PER PHYSICAL CORE (issue #40): SMT siblings share a core's + // load/store bandwidth, so a worker on each would put two workers on one core, as the Windows branch above + // explains. sysfs names each CPU's (package, core); the first allowed CPU of each pair is kept, so a taskset + // that leaves out the first sibling still gets its core. Without sysfs every allowed CPU counts, as before. + auto topo_read = [](int cpu, const char* what) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/%s", cpu, what); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + auto cap_read = [](int cpu) -> long { + char path[96]; + std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpu_capacity", cpu); + long v = -1; + if (std::FILE* f = std::fopen(path, "r")) { + if (std::fscanf(f, "%ld", &v) != 1) v = -1; + std::fclose(f); + } + return v; + }; + + std::vector allowed; + cpu_set_t set; + CPU_ZERO(&set); + if (sched_getaffinity(0, sizeof set, &set) == 0) { + for (int i = 0; i < CPU_SETSIZE; ++i) + if (CPU_ISSET(i, &set)) allowed.push_back(i); + } else { + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) allowed.push_back((int) i); + } + + struct CoreLinux { + int cpu = -1; + long pkg = -1; + long core = -1; + long cap = -1; + bool is_sibling = false; + }; + std::vector all_cpus; + std::vector> seen_phys; + long max_cap = 0, min_cap = 1000000; + + for (int cpu : allowed) { + CoreLinux cl; + cl.cpu = cpu; + cl.pkg = topo_read(cpu, "physical_package_id"); + cl.core = topo_read(cpu, "core_id"); + cl.cap = cap_read(cpu); + if (cl.cap > 0) { + max_cap = (std::max)(max_cap, cl.cap); + min_cap = (std::min)(min_cap, cl.cap); + } + if (cl.pkg >= 0 && cl.core >= 0) { + const std::pair key{cl.pkg, cl.core}; + if (std::find(seen_phys.begin(), seen_phys.end(), key) != seen_phys.end()) { + cl.is_sibling = true; + } else { + seen_phys.push_back(key); + } + } + all_cpus.push_back(cl); + } + + topo.is_hybrid = (max_cap > 0 && max_cap > min_cap); + if (topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) topo.p_cores++; + topo.p_threads++; + } else { + if (!cl.is_sibling) topo.e_cores++; + } + } + } else { + topo.p_cores = (int) seen_phys.size(); + topo.p_threads = (int) all_cpus.size(); + } + + if (affinity == PoolAffinity::All || !topo.is_hybrid) { + for (const auto& cl : all_cpus) { + if (!cl.is_sibling) topo.worker_cores.push_back(cl.cpu); + } + if (skip_first && !topo.worker_cores.empty()) { + topo.host_core = topo.worker_cores.front(); + topo.worker_cores.erase(topo.worker_cores.begin()); + } + return topo; + } + + // Hybrid CPU on Linux: + std::vector p_primaries; + std::vector p_siblings; + std::vector e_cores; + + for (const auto& cl : all_cpus) { + if (cl.cap == max_cap) { + if (!cl.is_sibling) p_primaries.push_back(cl.cpu); + else p_siblings.push_back(cl.cpu); + } else { + e_cores.push_back(cl.cpu); + } + } + + if (skip_first && !p_primaries.empty()) { + topo.host_core = p_primaries.front(); + p_primaries.erase(p_primaries.begin()); + } + + for (int cpu : p_primaries) topo.worker_cores.push_back(cpu); + for (int cpu : p_siblings) topo.worker_cores.push_back(cpu); + if (affinity != PoolAffinity::PCores) { + for (int cpu : e_cores) topo.worker_cores.push_back(cpu); + } + return topo; +#endif + return topo; +} + +std::vector physical_cores(bool skip_first, PoolAffinity affinity) { + return detect_cpu_topology(skip_first, affinity).worker_cores; +} + +namespace { + +void pin_this_thread(int core) { + if (core < 0) return; +#if defined(_WIN32) + SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) 1 << (core & 63)); +#else + cpu_set_t set; + CPU_ZERO(&set); + CPU_SET(core, &set); + pthread_setaffinity_np(pthread_self(), sizeof set, &set); +#endif +} + +} // namespace + +long long pin_current_thread(int core) { + if (core < 0) return -1; +#if defined(_WIN32) + // `SetThreadAffinityMask` RETURNS the previous mask, or 0 on failure - so 0 doubles as the error, which is + // why the caller must not treat it as a restorable value. + const DWORD_PTR prev = SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) 1 << (core & 63)); + return prev == 0 ? -1 : (long long) prev; +#else + cpu_set_t prev; + CPU_ZERO(&prev); + if (pthread_getaffinity_np(pthread_self(), sizeof prev, &prev) != 0) return -1; + unsigned long mask = 0; + for (int i = 0; i < CPU_SETSIZE && i < 64; ++i) + if (CPU_ISSET(i, &prev)) mask |= 1ul << i; + pin_this_thread(core); + return (long long) mask; +#endif +} + +void restore_thread_affinity(long long previous) { + if (previous <= 0) return; +#if defined(_WIN32) + SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) previous); +#else + cpu_set_t set; + CPU_ZERO(&set); + for (int i = 0; i < 64; ++i) + if ((previous >> i) & 1) CPU_SET(i, &set); + pthread_setaffinity_np(pthread_self(), sizeof set, &set); +#endif +} + +namespace { +std::atomic g_diag_pool{nullptr}; +void diag_active_pool(std::FILE* f) { + if (const ExpertPool* p = g_diag_pool.load()) p->diag(f); +} +int64_t now_ms() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); +} +} // namespace + +void ExpertPool::diag(std::FILE* f) const { + const uint64_t h = head_.load(); + std::fprintf(f, " expert pool: epoch %u, batch epoch %u: %u of %u jobs claimed, %u done; %u of %d workers parked, " + "%u sleeping; mode %d\n", epoch_.load(), (uint32_t) (h >> 32), (uint32_t) h & 0xffffu, + (uint32_t) (h >> 16) & 0xffffu, done_.load(), parked_.load(), n_, sleepers_.load(), mode_); + std::fprintf(f, " expert pool threads:"); + for (int i = 0; i < n_; ++i) { + const int32_t s = wstate_[(size_t) i].load(); + if (s == kParked) std::fprintf(f, " w%d=parked", i); + else if (s == kSleeping) std::fprintf(f, " w%d=sleeping", i); + else if (s == kBetween) std::fprintf(f, " w%d=draining", i); + else std::fprintf(f, " w%d=job%d", i, s); + } + const int32_t hs = hstate_.load(); + const char* hn = hs == kIdle ? "idle" : hs == kWaitParked ? "waiting for the workers to park" + : hs == kWaitDone ? "waiting for the jobs to finish" : "running a job"; + std::fprintf(f, "; host %s", hn); + if (hs >= 0) std::fprintf(f, " %d", hs); + std::fprintf(f, " for %lld ms\n", (long long) (now_ms() - hstate_ms_.load())); +} + +ExpertPool::ExpertPool(int n_workers, bool pin, bool host_works, PoolAffinity affinity) + : host_works_(host_works), affinity_(affinity), topo_(detect_cpu_topology(true, affinity)) { + if (const char* e = std::getenv("STRATA_POOL_SPIN_US")) // a test knob; see kSpinBeforeSleep + spin_before_sleep_ = std::chrono::microseconds((std::max)(0, std::atoi(e))); + if (n_workers > 0) { + n_ = n_workers; + } else if (topo_.is_hybrid && affinity_ != PoolAffinity::All) { + n_ = (std::max)(1, topo_.p_cores - 1); + } else { + n_ = (int) topo_.worker_cores.size(); + } + if (n_ < 1) n_ = 1; + scratch_.resize((size_t) n_); + wstate_.reset(new std::atomic[(size_t) n_]); + for (int i = 0; i < n_; ++i) wstate_[(size_t) i].store(kParked); + hstate_ms_.store(now_ms()); + g_diag_pool.store(this); + strata::core::diag_pool_fn().store(&diag_active_pool); + split_.resize((size_t) kMaxSplit); + split_multi_.resize((size_t) kMaxSplitMulti); + threads_.reserve((size_t) n_); + for (int i = 0; i < n_; ++i) { + const int core = pin ? (i < (int) topo_.worker_cores.size() ? topo_.worker_cores[(size_t) i] : -1) : -1; + threads_.emplace_back([this, i, core] { + pin_this_thread(core); + worker(i); + }); + } +} + +ExpertPool::~ExpertPool() { + const ExpertPool* self = this; + g_diag_pool.compare_exchange_strong(self, nullptr); + stop_.store(true, std::memory_order_release); + // Bump the epoch so a PARKED worker notices the stop flag rather than sleeping through it. + publish(); + for (auto& t : threads_) t.join(); +} + +void ExpertPool::publish() { + // Both sides are seq_cst, and that is the whole lost-wakeup argument: a worker going to sleep does + // `sleepers_++` and then reads `epoch_`, the host does `epoch_++` and then reads `sleepers_`. In one total + // order at least one of them sees the other's write - the worker sees the new epoch and does not sleep, or + // the host sees the sleeper and notifies under the mutex the worker holds until it is inside `wait`. + // On x86 the fetch_add is a locked xadd either way, so this costs the token path nothing. + epoch_.fetch_add(1, std::memory_order_seq_cst); + if (sleepers_.load(std::memory_order_seq_cst) != 0) { + std::lock_guard lk(sleep_mu_); + sleep_cv_.notify_all(); + } +} + +void ExpertPool::worker(int id) { + uint32_t seen = 0; + // ARRIVE at the park before the first wait, so `parked_ == n_` is true from construction. Counting only + // on the RETURN from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first + // `run()` - which waits for `parked_ == n_` before publishing - then deadlocks. It deadlocks on the very + // first call, which is the good case; a version that deadlocked on the second would be far worse. + parked_.fetch_add(1, std::memory_order_acq_rel); + for (;;) { + // Park: wait for work. `_mm_pause` rather than a bare spin because it yields the pipeline to the + // sibling hyperthread; `epoch_` is bumped once per LAYER, not once per expert, so most of these + // iterations are spent here with nothing to do. + // + // **AND NOTHING ELSE HAPPENS IN HERE.** This loop used to do `pauses_.fetch_add(1)` on every iteration + // - a locked read-modify-write, five workers against one cache line - so the workers spent their wait + // invalidating each other's caches and the very line the host writes to publish work. The counter was + // diagnostic and nothing branched on it. See the note on the atomics in pool.hpp. + // + // After `kSpinBeforeSleep` with no work the worker sleeps instead (issue #4). The clock is read once + // every 1024 pauses, so the spin itself is unchanged. + const auto parked_at = std::chrono::steady_clock::now(); + uint32_t spins = 0; + while (epoch_.load(std::memory_order_acquire) == seen) { + if (stop_.load(std::memory_order_relaxed)) return; + _mm_pause(); + if ((++spins & 1023u) != 0) continue; + if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue; + std::unique_lock lk(sleep_mu_); + wstate_[(size_t) id].store(kSleeping, std::memory_order_relaxed); + sleepers_.fetch_add(1, std::memory_order_seq_cst); + sleep_cv_.wait(lk, [&] { + return epoch_.load(std::memory_order_seq_cst) != seen || stop_.load(std::memory_order_relaxed); + }); + sleepers_.fetch_sub(1, std::memory_order_relaxed); + wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); + } + if (stop_.load(std::memory_order_acquire)) return; + // acquire: the batch this epoch published (`head`, and the description before it) is visible from here + seen = epoch_.load(std::memory_order_acquire); + parked_.fetch_sub(1, std::memory_order_acq_rel); // leaving the park + + // Drain: one claim per iteration, so a slow worker takes fewer experts and a fast one takes more. + // Every job is the same size (all experts are 1,382,400 bytes), so there is nothing to schedule. Only + // this epoch's jobs: if the host has already moved on, the claims fail and the worker parks again. + wstate_[(size_t) id].store(kBetween, std::memory_order_relaxed); + drain(id, scratch_[(size_t) id], seen); + wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); + parked_.fetch_add(1, std::memory_order_acq_rel); // back at the park + } +} + +int ExpertPool::claim(uint32_t epoch) { + uint64_t h = head_.load(std::memory_order_acquire); + for (;;) { + if ((uint32_t) (h >> 32) != epoch) return -1; // not the batch this thread woke for + const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu; + if (i >= n) return -1; // exhausted + if (head_.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire)) + return (int) i; + } +} + +uint32_t ExpertPool::begin_batch(int n) { + if (n < 0 || n > 0xffff) { + std::fprintf(stderr, "strata: expert pool batch of %d jobs is out of range\n", n); + std::abort(); + } + // Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so + // nothing adds to `done` until this batch's first claim - which the release below orders after the reset. + done_.store(0, std::memory_order_relaxed); + const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1; // only the host bumps the epoch + head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release); + publish(); + return e; +} + +void ExpertPool::wait_parked(const char* what) { + hstate_.store(kWaitParked, std::memory_order_relaxed); + hstate_ms_.store(now_ms(), std::memory_order_relaxed); + uint32_t spins = 0; + std::chrono::steady_clock::time_point t0{}; + while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) { + _mm_pause(); + if ((++spins & 1023u) != 0) continue; + const auto now = std::chrono::steady_clock::now(); + if (spins == 1024u) t0 = now; + else if (now - t0 > kStall) { + std::fprintf(stderr, "strata: the CPU expert pool stalled %s (%u of %d workers parked) - stopping the engine " + "so the server can start it again (issue #29)\n", + what, parked_.load(), n_); + strata::core::release_gpu_waits(stderr); // #267: the GPU may be spinning on this layer's flag + std::fflush(stderr); + std::abort(); + } + } +} + +void ExpertPool::wait_done(int n) { + hstate_.store(kWaitDone, std::memory_order_relaxed); + hstate_ms_.store(now_ms(), std::memory_order_relaxed); + uint32_t spins = 0, seen = 0; + std::chrono::steady_clock::time_point t0{}; + for (;;) { + const uint32_t d = done_.load(std::memory_order_acquire); + if (d >= (uint32_t) n) return; // `>=`: never a wait that an overshoot outlives + _mm_pause(); + if ((++spins & 1023u) != 0) continue; + const auto now = std::chrono::steady_clock::now(); + if (spins == 1024u || d != seen) { t0 = now; seen = d; } // progress restarts the clock + else if (now - t0 > kStall) { + std::fprintf(stderr, "strata: the CPU expert pool stalled: %u of %d jobs done, %u of %d workers parked - " + "stopping the engine so the server can start it again (issue #29)\n", + d, n, parked_.load(), n_); + strata::core::release_gpu_waits(stderr); // #267 + std::fflush(stderr); + std::abort(); + } + } +} + +void ExpertPool::drain(int id, ExpertScratch& scratch, uint32_t epoch) { + (void) id; + for (;;) { + const int ci = claim(epoch); + if (ci < 0) break; + const uint32_t i = (uint32_t) ci; + if (id >= 0) wstate_[(size_t) id].store(ci, std::memory_order_relaxed); + else { hstate_.store(ci, std::memory_order_relaxed); hstate_ms_.store(now_ms(), std::memory_order_relaxed); } + if (mode_ == 0) { + const ExpertJob& j = jobs_[i]; + s2_expert_vnni_q(j.blob, *j.act, j.out, scratch); + } else if (mode_ == 1) { + const int e = (int) i / parts_a_, part = (int) i % parts_a_; + const int r0 = FF * part / parts_a_, r1 = FF * (part + 1) / parts_a_; + s2_expert_gu_rows(jobs_[e].blob, *jobs_[e].act, split_[(size_t) e].ff, r0, r1); + } else if (mode_ == 2) { + const int e = (int) i / parts_b_, part = (int) i % parts_b_; + const int r0 = H * part / parts_b_, r1 = H * (part + 1) / parts_b_; + s2_expert_down_rows(jobs_[e].blob, split_[(size_t) e].a2, jobs_[e].out, r0, r1); + } else if (mode_ >= 5) { + // plan v0.3 P6: native layers, 5 = gate/up rows, 6 = down rows + const int per = mode_ == 5 ? FF : H; + const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_; + for (int64_t r = g0; r < g1;) { + const int e = (int) (r / per), r0 = (int) (r % per); + const int r1 = (int) std::min(per, r0 + (g1 - r)); + SplitBufMulti& sb = split_multi_[(size_t) e]; + if (mode_ == 5 && nfmt_->gu_type == 42) { + // a native Q2_0 pack: gate and up rows on the Q2_0 kernels, then SwiGLU + thread_local float gbuf[MAXT][FF], ubuf[MAXT][FF]; + float* gp[MAXT]; + float* up[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) { gp[t] = gbuf[t]; up[t] = ubuf[t]; } + const int nbk = (int) (nfmt_->n_embd / 64); + q2_rows_any(mjobs_[e].blob, nfmt_->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, gp, r0, r1); + q2_rows_any(mjobs_[e].blob + nfmt_->up_off, nfmt_->gu_row, nbk, mjobs_[e].act, mjobs_[e].nt, up, r0, r1); + for (int t = 0; t < mjobs_[e].nt; ++t) + for (int r = r0; r < r1; ++r) + sb.ff[t][r] = (gbuf[t][r] / (1.f + std::exp(-gbuf[t][r]))) * ubuf[t][r]; + } else if (mode_ == 5) { + float* ff[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t]; + native_gu_rows(*nfmt_, mjobs_[e].blob, mjobs_[e].nact, mjobs_[e].nt, ff, r0, r1); + } else if (nfmt_->d_type == 42) { + // Q2_0 down (most IQ layers): the AVX-512 kernel, ggml-cpu has only a scalar one on x86 + const ActQ* a2[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t]; + q2_rows_any(mjobs_[e].blob + nfmt_->down_off, nfmt_->d_row, (int) (nfmt_->n_ff / 64), a2, + mjobs_[e].nt, mjobs_[e].out, r0, r1); + } else { + const void* hq[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) hq[t] = sb.hq[t]; + native_down_rows(*nfmt_, mjobs_[e].blob, hq, mjobs_[e].nt, mjobs_[e].out, r0, r1); + } + r += r1 - r0; + } + } else { + // plan v0.3 P6: an equal range of the phase's rows across ALL its experts (a range may span two) + const int per = mode_ == 3 ? FF : H; + const int64_t g0 = mrows_ * (int64_t) i / mtasks_, g1 = mrows_ * (int64_t) (i + 1) / mtasks_; + for (int64_t r = g0; r < g1;) { + const int e = (int) (r / per), r0 = (int) (r % per); + const int r1 = (int) std::min(per, r0 + (g1 - r)); + SplitBufMulti& sb = split_multi_[(size_t) e]; + if (mode_ == 3) { + float* ff[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) ff[t] = sb.ff[t]; + s2_expert_gu_rows_multi(mjobs_[e].blob, mjobs_[e].act, mjobs_[e].nt, ff, r0, r1); + } else { + const ActQ* a2[MAXT]; + for (int t = 0; t < mjobs_[e].nt; ++t) a2[t] = &sb.a2[t]; + s2_expert_down_rows_multi(mjobs_[e].blob, a2, mjobs_[e].nt, mjobs_[e].out, r0, r1); + } + r += r1 - r0; + } + } + done_.fetch_add(1, std::memory_order_release); + } +} + +void ExpertPool::run_phase(int mode, int n_tasks) { + wait_parked("before a phase"); + mode_ = mode; + njobs_ = n_tasks; + const uint32_t e = begin_batch(n_tasks); + if (host_works_) drain(-1, host_scratch_, e); + wait_done(n_tasks); + wait_parked("after a phase"); + hstate_.store(kIdle, std::memory_order_relaxed); + hstate_ms_.store(now_ms(), std::memory_order_relaxed); +} + +void ExpertPool::run_split(ExpertJob* jobs, int n) { + if (n <= 0) return; + if (n > kMaxSplit || n_ == 1 || expert_oracle_q8_0_enabled()) { run(jobs, n); return; } + const auto t0 = std::chrono::steady_clock::now(); + jobs_ = jobs; + const int threads = n_ + (host_works_ ? 1 : 0); + // about three tasks per thread in each phase, so the tail is short + parts_a_ = (std::max)(1, (3 * threads + n - 1) / n); + parts_b_ = parts_a_; + run_phase(1, n * parts_a_); + for (int e = 0; e < n; ++e) act_quant_q8_1(split_[(size_t) e].ff, FF, split_[(size_t) e].a2); + run_phase(2, n * parts_b_); + mode_ = 0; + ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +void ExpertPool::run_split_multi(ExpertJobMulti* jobs, int n) { + if (n <= 0) return; + if (n > kMaxSplitMulti || expert_oracle_q8_0_enabled()) { + // one token at a time through the single-token path (the oracle contract has no multi kernel) + std::vector single; + for (int e = 0; e < n; ++e) + for (int t = 0; t < jobs[e].nt; ++t) { + ExpertJob j; + j.blob = jobs[e].blob; + j.act = jobs[e].act[t]; + j.out = jobs[e].out[t]; + single.push_back(j); + } + for (size_t i = 0; i < single.size(); i += kMaxSplit) + run_split(single.data() + i, (int) (std::min)((size_t) kMaxSplit, single.size() - i)); + return; + } + const auto t0 = std::chrono::steady_clock::now(); + mjobs_ = jobs; + const int threads = n_ + (host_works_ ? 1 : 0); + mtasks_ = 3 * threads; + mrows_ = (int64_t) n * FF; + run_phase(3, mtasks_); + const auto t1 = std::chrono::steady_clock::now(); + for (int e = 0; e < n; ++e) + for (int t = 0; t < jobs[e].nt; ++t) + act_quant_q8_1(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]); + const auto t2 = std::chrono::steady_clock::now(); + mrows_ = (int64_t) n * H; + run_phase(4, mtasks_); + const auto t3 = std::chrono::steady_clock::now(); + ms_multi_gu += std::chrono::duration(t1 - t0).count(); + ms_multi_q += std::chrono::duration(t2 - t1).count(); + ms_multi_down += std::chrono::duration(t3 - t2).count(); + multi_bytes += (int64_t) n * (int64_t) BLOB; + mode_ = 0; + ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +void ExpertPool::run_split_multi_native(const NativeFmt& f, ExpertJobMulti* jobs, int n) { + if (n <= 0) return; + const auto t0 = std::chrono::steady_clock::now(); + // more distinct experts than buffers: run them in batches + for (int b0 = 0; b0 < n; b0 += kMaxSplitMulti) { + const int nb = (std::min)(kMaxSplitMulti, n - b0); + mjobs_ = jobs + b0; + nfmt_ = &f; + const int threads = n_ + (host_works_ ? 1 : 0); + mtasks_ = 3 * threads; + mrows_ = (int64_t) nb * FF; + const auto a = std::chrono::steady_clock::now(); + run_phase(5, mtasks_); + const auto b = std::chrono::steady_clock::now(); + for (int e = 0; e < nb; ++e) + for (int t = 0; t < mjobs_[e].nt; ++t) + if (f.d_type == 42) act_quant_any(split_multi_[(size_t) e].ff[t], FF, split_multi_[(size_t) e].a2[t]); + else native_quant_h(f, split_multi_[(size_t) e].ff[t], split_multi_[(size_t) e].hq[t]); + const auto c = std::chrono::steady_clock::now(); + mrows_ = (int64_t) nb * H; + run_phase(6, mtasks_); + const auto d = std::chrono::steady_clock::now(); + ms_multi_gu += std::chrono::duration(b - a).count(); + ms_multi_q += std::chrono::duration(c - b).count(); + ms_multi_down += std::chrono::duration(d - c).count(); + } + multi_bytes += (int64_t) n * (int64_t) f.bytes; + mode_ = 0; + ms_drain_ += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +void ExpertPool::run(ExpertJob* jobs, int n) { + if (n <= 0) return; + if (n_ == 1) { // no workers: run inline, so a single-core machine still produces a token + for (int i = 0; i < n; ++i) s2_expert_vnni_q(jobs[i].blob, *jobs[i].act, jobs[i].out, scratch_[0]); + return; + } + // Wait for every worker to be parked BEFORE touching the batch, so the publish below is the only thing + // that can move a worker into the drain loop. + // + // THE THREE PHASES ARE TIMED SEPARATELY. They were one number, which cannot distinguish a pool that is + // slow at the WORK from one that is slow at the SYNCHRONISATION - and those need opposite fixes. + const auto t_a = std::chrono::steady_clock::now(); + wait_parked("before a batch"); + const auto t_b = std::chrono::steady_clock::now(); + jobs_ = jobs; + njobs_ = n; + mode_ = 0; + const uint32_t e = begin_batch(n); // done, then head (release), then the epoch: the batch is described first + + // ---- **THE HOST DRAINS TOO (R2.2), INSTEAD OF SPINNING ON `done_`.** + // + // The loop below used to be `while (done_ != n) _mm_pause();`. The host is pinned to core 0 - the core + // `physical_cores(true)` deliberately keeps the five workers off - so for the whole drain that core was + // idle while five cores did six cores' worth of work. Measured before the change: 33.7 GB/s against + // 5/6 x 44.14 = 36.8 for five workers and 44.14 for six. + // + // The host claims through the SAME `head_` counter, so this is not a second scheduler and nothing about + // the ordering changes: `head_` is a single `fetch_add`, every job is the same size, and a thread that + // arrives late simply claims nothing. `done_` is still the completion signal and the host still waits for + // it - what changed is only that the host arrives at that wait having done a share of the work. + // + // The host's `done_.fetch_add` is a release for the same reason a worker's is: `j.out` is read by the + // device after `run()` returns, so the write must be published, not merely performed. + if (host_works_) { + for (;;) { + const int ci = claim(e); + if (ci < 0) break; + hstate_.store(ci, std::memory_order_relaxed); + hstate_ms_.store(now_ms(), std::memory_order_relaxed); + const ExpertJob& j = jobs_[ci]; + s2_expert_vnni_q(j.blob, *j.act, j.out, host_scratch_); + done_.fetch_add(1, std::memory_order_release); + } + } + + wait_done(n); + // And park again, so the next `run` starts from a known state. See the header for why `done` alone is + // not enough. + const auto t_c = std::chrono::steady_clock::now(); + wait_parked("after a batch"); + hstate_.store(kIdle, std::memory_order_relaxed); + hstate_ms_.store(now_ms(), std::memory_order_relaxed); + const auto t_d = std::chrono::steady_clock::now(); + + ms_wait_park_ += std::chrono::duration(t_b - t_a).count(); + ms_drain_ += std::chrono::duration(t_c - t_b).count(); + ms_repark_ += std::chrono::duration(t_d - t_c).count(); +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cpu/pool_stress.cpp b/engine/strata/src/kernels/cpu/pool_stress.cpp new file mode 100644 index 00000000..2c9fca54 --- /dev/null +++ b/engine/strata/src/kernels/cpu/pool_stress.cpp @@ -0,0 +1,99 @@ +// src/kernels/cpu/pool_stress.cpp - issue #29: the expert pool under the load a big-VRAM card gives it. +// +// With most experts resident on the GPU, many layers hand the pool nothing, the workers go to sleep in the middle +// of a request, and the next tiny batch (one or two experts) is often finished by the host and the awake workers +// before a sleeper has even woken. That late wake-up is what the park/claim protocol has to survive. This drives +// hundreds of thousands of such batches - 0-4 jobs, run() and run_split(), with pauses long enough for the workers +// to sleep - and checks that every batch returns, with every job's output written. A watchdog thread turns a +// hang into a failure instead of a frozen test. +// +// pool_stress [seconds] (default 20) +#include "strata/kernels/cpu/pool.hpp" +#include "strata/kernels/cpu/expert.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +int main(int argc, char** argv) { + const double seconds = argc > 1 ? std::atof(argv[1]) : 20.0; + const cpu::CpuFeatures feat = cpu::cpu_features(); + if (!feat.usable()) { + std::printf("CPU lacks %s: pool_stress SKIPPED\n", feat.reason()); + return 0; + } + constexpr int NJ = 4; + std::vector> blobs(NJ, std::vector(cpu::BLOB, 0)); + std::vector x(cpu::H, 0.25f); + cpu::ActQ act; + cpu::act_quant_q8_1(x.data(), cpu::H, act); + std::vector out((size_t) NJ * cpu::H); + std::vector jobs(NJ); + for (int e = 0; e < NJ; ++e) { + jobs[(size_t) e].blob = blobs[(size_t) e].data(); + jobs[(size_t) e].act = &act; + jobs[(size_t) e].out = out.data() + (size_t) e * cpu::H; + jobs[(size_t) e].slot = e; + } + + cpu::ExpertPool pool; + std::printf("pool_stress: %d workers + host, %.0f s\n", pool.workers(), seconds); + + // the watchdog: a batch that does not return within 10 s is a hang + std::atomic beat{0}; + std::atomic finished{false}; + std::thread dog([&] { + long long last = -1; + auto since = std::chrono::steady_clock::now(); + while (!finished.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + const long long b = beat.load(); + const auto now = std::chrono::steady_clock::now(); + if (b != last) { last = b; since = now; continue; } + if (now - since > std::chrono::seconds(10)) { + std::printf("\npool_stress: HANG - batch %lld has not returned for 10 s\n", b); + std::fflush(stdout); + std::_Exit(3); + } + } + }); + + std::mt19937 rng(29); + const float SENTINEL = -1.2345e33f; + long long batches = 0, sleeps = 0, missed = 0; + const auto t0 = std::chrono::steady_clock::now(); + while (std::chrono::steady_clock::now() - t0 < std::chrono::duration(seconds)) { + // now and then a gap long enough for every worker to go to sleep (the pool sleeps after 20 ms) + if (rng() % 64 == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(21 + (int) (rng() % 10))); + ++sleeps; + } else if (rng() % 4 == 0) { + std::this_thread::sleep_for(std::chrono::microseconds(rng() % 300)); + } + const int n = (int) (rng() % (NJ + 1)); + for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); + if (rng() % 2) pool.run(jobs.data(), n); + else pool.run_split(jobs.data(), n); + for (int e = 0; e < n; ++e) + if (jobs[(size_t) e].out[0] == SENTINEL || jobs[(size_t) e].out[cpu::H - 1] == SENTINEL) ++missed; + beat.fetch_add(1); + ++batches; + } + finished.store(true); + dog.join(); + std::printf("pool_stress: %lld batches (%lld after the workers slept), %lld jobs not run\n", batches, sleeps, + missed); + if (missed) { + std::printf("pool_stress: FAILED\n"); + return 1; + } + std::printf("pool_stress OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/cpu/pool_test.cpp b/engine/strata/src/kernels/cpu/pool_test.cpp new file mode 100644 index 00000000..dbc7288a --- /dev/null +++ b/engine/strata/src/kernels/cpu/pool_test.cpp @@ -0,0 +1,224 @@ +// src/kernels/cpu/pool_test.cpp - P2.S3's test for the expert pool. +// +// The pool's correctness claims are small and specific, so they are checked directly rather than through a +// timing number: +// +// 1. THE SAME ANSWER AS SERIAL. Every job's output must be bit-identical to running that expert serially. +// Each worker owns its own `ExpertScratch`, and the jobs share one read-only activation, so there is no +// legitimate source of difference - "close enough" here would be hiding a data race. +// 2. EVERY JOB RUNS EXACTLY ONCE. Claiming is `head.fetch_add`, and an off-by-one in the bound is the +// classic pool bug: it either drops a job or runs one twice. Checked with a sentinel-filled output +// buffer, so a dropped job is visible as an untouched slot rather than as a slightly wrong number. +// 3. REPEATED BATCHES. A pool that works once and hangs or corrupts on the second `run()` is the failure +// mode the park protocol exists to prevent, so `run()` is called many times in a row. +// 4. A BATCH BIGGER AND SMALLER THAN THE WORKER COUNT, because `n < workers` leaves most workers claiming +// nothing and `n > workers` is the real case (10 experts, 5 workers). +#include "strata/kernels/cpu/pool.hpp" +#include "strata/kernels/cpu/expert.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +namespace { + +bool read_blob(const char* path, long long index, std::vector& out) { + out.assign(cpu::BLOB, 0); + std::FILE* f = std::fopen(path, "rb"); + if (!f) return false; +#if defined(_MSC_VER) + if (_fseeki64(f, index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } +#else + if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; } +#endif + const size_t got = std::fread(out.data(), 1, out.size(), f); + std::fclose(f); + return got == out.size(); +} + +double now_ms() { + using namespace std::chrono; + return duration(steady_clock::now().time_since_epoch()).count(); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + const char* path = "pack/full/experts.bin"; + long long layer = 0; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") selftest = true; + else if (a == "--file" && i + 1 < argc) path = argv[++i]; + else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]); + else { std::fprintf(stderr, "usage: pool_test [--selftest] [--file P] [--layer N]\n"); return 2; } + } + + const cpu::CpuFeatures feat = cpu::cpu_features(); + if (!feat.usable()) { + std::printf(" CPU lacks %s - the VNNI path cannot run here; pool test SKIPPED, not passed.\n", + feat.reason()); + std::printf("\npool: 0 failures, 1 SKIPPED\n"); + return 0; + } + + int bad = 0; + + // ---- ten experts off one layer, which is exactly what a token uses + const int NEXP = 10; + std::vector> blobs((size_t) NEXP); + for (int e = 0; e < NEXP; ++e) + if (!read_blob(path, layer * 512 + e, blobs[(size_t) e])) { + std::fprintf(stderr, "cannot read expert %d of layer %lld from %s\n", e, layer, path); + return 2; + } + + std::mt19937 rng(99); + std::normal_distribution gauss(0.0f, 1.0f); + std::vector x(cpu::H); + for (auto& v : x) v = gauss(rng); + + cpu::ActQ act; + cpu::act_quant_q8_1(x.data(), cpu::H, act); + + // ---- serial reference + std::vector ref((size_t) NEXP * cpu::H); + { + cpu::ExpertScratch ws; + for (int e = 0; e < NEXP; ++e) + cpu::s2_expert_vnni_q(blobs[(size_t) e].data(), act, ref.data() + (size_t) e * cpu::H, ws); + } + + // ---- the pool + const std::vector cores = cpu::physical_cores(true); + const int hw = (int) std::thread::hardware_concurrency(); + std::printf(" %-44s %d logical, %d physical (skipping the first)\n", "cores the pool will use", + hw, (int) cores.size()); + + cpu::ExpertPool pool; + std::printf(" %-44s %d\n", "workers", pool.workers()); + + std::vector jobs((size_t) NEXP); + std::vector got((size_t) NEXP * cpu::H); + std::vector weights((size_t) NEXP); + for (int e = 0; e < NEXP; ++e) weights[(size_t) e] = 0.1f * (float) (e + 1); + + // ---- 1 + 2: same answer as serial, and every job exactly once. + // The output buffer starts at a sentinel no real result can equal, so a job that never runs shows up as + // an untouched slot instead of as a plausible number. + const float SENTINEL = -1.2345e33f; + for (int e = 0; e < NEXP; ++e) { + jobs[(size_t) e].blob = blobs[(size_t) e].data(); + jobs[(size_t) e].act = &act; + jobs[(size_t) e].out = got.data() + (size_t) e * cpu::H; + jobs[(size_t) e].weight = weights[(size_t) e]; + jobs[(size_t) e].slot = e; + std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); + } + pool.run(jobs.data(), NEXP); + + long long not_run = 0, diff = 0; + float worst = 0.f; + for (int e = 0; e < NEXP; ++e) + for (int i = 0; i < cpu::H; ++i) { + const float a = ref[(size_t) e * cpu::H + i], b = got[(size_t) e * cpu::H + i]; + if (b == SENTINEL) { ++not_run; continue; } + if (std::memcmp(&a, &b, 4) != 0) ++diff; + worst = std::fmax(worst, std::fabs(a - b)); + } + std::printf(" %-44s %s (%lld of %d outputs untouched)\n", "every job ran exactly once", + not_run ? "*** NO ***" : "yes", not_run, NEXP * cpu::H); + if (not_run) ++bad; + // BIT-IDENTICAL, not "close". Each worker has a private scratch and the activation is shared read-only, + // so any difference at all is a race or a scratch collision - and a tolerance would hide exactly that. + std::printf(" %-44s %s (%lld of %d differ, worst |d| %.3e)\n", "identical to the serial run", + diff ? "*** NO ***" : "yes", diff, NEXP * cpu::H, (double) worst); + if (diff) ++bad; + + // ---- 3: repeated batches. A park protocol that works once and corrupts on the second call is the + // exact failure this loop is here to catch. + { + int repeats_bad = 0; + for (int r = 0; r < 200; ++r) { + for (int e = 0; e < NEXP; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); + pool.run(jobs.data(), NEXP); + for (int e = 0; e < NEXP && !repeats_bad; ++e) + for (int i = 0; i < cpu::H; ++i) + if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) { + ++repeats_bad; + break; + } + } + std::printf(" %-44s %s (200 consecutive batches)\n", "repeated batches stay correct", + repeats_bad ? "*** NO ***" : "yes"); + if (repeats_bad) ++bad; + } + + // ---- 4: batch sizes either side of the worker count + { + int size_bad = 0; + for (int n : {1, 2, pool.workers() - 1 > 0 ? pool.workers() - 1 : 1, pool.workers(), + pool.workers() + 1, NEXP}) { + if (n < 1 || n > NEXP) continue; + for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL); + pool.run(jobs.data(), n); + for (int e = 0; e < n && !size_bad; ++e) + for (int i = 0; i < cpu::H; ++i) + if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) { + ++size_bad; + break; + } + } + std::printf(" %-44s %s (1, w-1, w, w+1, 10)\n", "batch sizes around the worker count", + size_bad ? "*** NO ***" : "yes"); + if (size_bad) ++bad; + } + + // ---- and the number that matters for the ledger: c for one layer, 10 experts over 48 layers. + // + // BEST OF N, not a mean. The first version divided a 10-run total by 10 and reported 6.604 ms per layer - + // 2.1 GB/s against L9's measured 42.55 - purely because a CUDA build was running on the same 6-core + // machine at the time. A mean over a contended machine measures the contention; a best-of measures the + // instrument, and every other timing tool in this project already takes the best. The spread is printed + // so a contended run is visible rather than being read as a regression. + { + const int REPS = 20; + std::vector t((size_t) REPS, 0.0); + for (int r = 0; r < REPS; ++r) { + const double t0 = now_ms(); + pool.run(jobs.data(), NEXP); + t[(size_t) r] = now_ms() - t0; + } + std::vector sorted = t; + std::sort(sorted.begin(), sorted.end()); + const double best = sorted.front(), median = sorted[sorted.size() / 2], worst = sorted.back(); + const double gbs = (double) NEXP * cpu::BLOB / (best * 1e-3) / 1e9; + std::printf("\n %-44s %7.3f ms (%.1f GB/s)\n", "10 experts, one layer (best of 20)", + best, gbs); + std::printf(" %-44s %7.3f / %7.3f ms (spread %.2fx)\n", "median / worst", median, worst, + median / (best > 0 ? best : 1)); + std::printf(" %-44s %7.3f ms -> %.1f tok/s for the full 48 layers\n", + "extrapolated to 48 layers", best * 48, 1000.0 / (best * 48)); + std::printf(" L9 measured 42.55 GB/s on 6 cores; this pool uses %d workers (core 0 is left to the\n", + pool.workers()); + std::printf(" host loop), so %.1f GB/s x 6/%d = %.1f GB/s is the per-core comparison.\n", + gbs, pool.workers(), gbs * 6.0 / pool.workers()); + if (median / (best > 0 ? best : 1) > 1.5) + std::printf(" *** the spread is over 1.5x: this machine was CONTENDED and the median is not a\n" + " property of the pool. Re-run on a quiet machine before quoting it. ***\n"); + } + + std::printf("\npool: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("pool_test OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/cpu/q2_avx2.cpp b/engine/strata/src/kernels/cpu/q2_avx2.cpp new file mode 100644 index 00000000..8e276a5e --- /dev/null +++ b/engine/strata/src/kernels/cpu/q2_avx2.cpp @@ -0,0 +1,130 @@ +// src/kernels/cpu/q2_avx2.cpp - plan v0.3 P6: the Q2_0 expert rows and the activation quantizer for CPUs +// without AVX-512 (Intel Core 12th-14th gen and Core Ultra, AMD Zen 2/3). +// +// Compiled with AVX2 only, so nothing here can fault on those CPUs. The arithmetic is the AVX-512 kernels': +// codes 0..3 against the int8 activation per 32-value chunk, times the weight scale and the chunk scale, minus +// the weight scale times the chunk's `hx` (the -1 code offset); the quantizer is the scalar rule, bit for bit. +#include "strata/kernels/cpu/expert.hpp" + +#include + +#include +#include + +namespace strata::kernels::cpu { +namespace { + +inline float h2f(const uint8_t* p) { + uint16_t h; + std::memcpy(&h, p, 2); + return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); +} + +// 16 bytes of 2-bit codes (value i in byte i/4, bits 2*(i%4)) -> 64 codes in value order, two 32-byte vectors +inline void unpack64(const uint8_t* codes, __m256i& lo, __m256i& hi) { + const __m128i b = _mm_loadu_si128((const __m128i*) codes); + const __m128i m3 = _mm_set1_epi8(3); + const __m128i c0 = _mm_and_si128(b, m3); + const __m128i c1 = _mm_and_si128(_mm_srli_epi16(b, 2), m3); + const __m128i c2 = _mm_and_si128(_mm_srli_epi16(b, 4), m3); + const __m128i c3 = _mm_and_si128(_mm_srli_epi16(b, 6), m3); + const __m128i a0 = _mm_unpacklo_epi8(c0, c1), a1 = _mm_unpacklo_epi8(c2, c3); // bytes 0..7 + const __m128i b0 = _mm_unpackhi_epi8(c0, c1), b1 = _mm_unpackhi_epi8(c2, c3); // bytes 8..15 + lo = _mm256_set_m128i(_mm_unpackhi_epi16(a0, a1), _mm_unpacklo_epi16(a0, a1)); // values 0..31 + hi = _mm256_set_m128i(_mm_unpackhi_epi16(b0, b1), _mm_unpacklo_epi16(b0, b1)); // values 32..63 +} + +template +inline void row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) { + __m256 acc[NT]; + float corr[NT]; + for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; } + const __m256i ones = _mm256_set1_epi16(1); + for (int b = 0; b < nblocks; ++b) { + const uint8_t* blk = row + (size_t) b * 18; + const float d = h2f(blk); + __m256i lo, hi; + unpack64(blk + 2, lo, hi); + for (int t = 0; t < NT; ++t) { + const int8_t* q = a[t]->q + b * 64; + const __m256i s0 = _mm256_madd_epi16(_mm256_maddubs_epi16(lo, _mm256_loadu_si256((const __m256i*) q)), ones); + const __m256i s1 = _mm256_madd_epi16(_mm256_maddubs_epi16(hi, _mm256_loadu_si256((const __m256i*) (q + 32))), ones); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), _mm256_cvtepi32_ps(s0), acc[t]); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), _mm256_cvtepi32_ps(s1), acc[t]); + corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]); + } + } + for (int t = 0; t < NT; ++t) { + const __m128 h = _mm_add_ps(_mm256_castps256_ps128(acc[t]), _mm256_extractf128_ps(acc[t], 1)); + const __m128 s = _mm_add_ps(h, _mm_movehl_ps(h, h)); + res[t] = _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) - corr[t]; + } +} + +template +void rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) { + float res[NT]; + for (int r = r0; r < r1; ++r) { + row_multi(w + (size_t) r * row_bytes, a, nblocks, res); + for (int t = 0; t < NT; ++t) out[t][r] = res[t]; + } +} + +} // namespace + +void q2_0_gguf_rows_multi_avx2(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1) { + switch (nt) { + case 1: rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 2: rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 3: rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break; + case 4: rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break; + default: + for (int t0 = 0; t0 < nt; t0 += 4) { + const int k = nt - t0 < 4 ? nt - t0 : 4; + q2_0_gguf_rows_multi_avx2(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1); + } + } +} + +void act_quant_q8_1_avx2(const float* x, int n, ActQ& a) { + a.nchunks = n / QKA; + const __m256 absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)); + const __m256 half = _mm256_set1_ps(0.5f), mhalf = _mm256_set1_ps(-0.5f), zero = _mm256_setzero_ps(); + const __m256i lo = _mm256_set1_epi32(-127), hi = _mm256_set1_epi32(127); + for (int k = 0; k < a.nchunks; ++k) { + const float* xb = x + k * QKA; + __m256 v[4]; + __m256 m = _mm256_setzero_ps(); + for (int i = 0; i < 4; ++i) { + v[i] = _mm256_loadu_ps(xb + 8 * i); + m = _mm256_max_ps(m, _mm256_and_ps(v[i], absmask)); + } + __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + const float amax = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h))); + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + const __m256 vinv = _mm256_set1_ps(inv); + __m256i sum = _mm256_setzero_si256(); + alignas(32) int32_t qi[QKA]; + for (int i = 0; i < 4; ++i) { + const __m256 t = _mm256_mul_ps(v[i], vinv); + const __m256 r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps(t, zero, _CMP_GE_OQ))); + __m256i q = _mm256_cvttps_epi32(r); + q = _mm256_min_epi32(_mm256_max_epi32(q, lo), hi); + sum = _mm256_add_epi32(sum, q); + _mm256_store_si256((__m256i*) (qi + 8 * i), q); + } + for (int j = 0; j < QKA; ++j) a.q[k * QKA + j] = (int8_t) qi[j]; + __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1)); + const int32_t total = _mm_cvtsi128_si32(s4); + a.scale[k] = s; + a.sum[k] = total; + a.hx[k] = s * (float) total; + } +} + +} // namespace strata::kernels::cpu diff --git a/engine/strata/src/kernels/cuda/bf16_gemv.cu b/engine/strata/src/kernels/cuda/bf16_gemv.cu new file mode 100644 index 00000000..04473ad0 --- /dev/null +++ b/engine/strata/src/kernels/cuda/bf16_gemv.cu @@ -0,0 +1,141 @@ +// src/kernels/cuda/bf16_gemv.cu - the BF16 GEMV. See the header for why it is not `s_gemv`. +#include "strata/kernels/bf16_gemv.hpp" + +#include "strata/kernels/bf16_bits.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; + +/// One thread per output row, walking it contiguously. Kept as the naive reference the split version is +/// checked against, and used directly for the shapes where the output width is already large. +__global__ void bf16_gemv_naive_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out) { + const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = 0; i < n_in; ++i) + acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); + y[o] = acc; +} + +/// One WARP per output row, lanes striding the reduction axis. For a fixed `i` consecutive lanes touch +/// consecutive addresses in this layout, so the load is coalesced - the property that took `gr_read` from +/// 262 ms/token to 8.9. +__global__ void bf16_gemv_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + if (o >= n_out) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = lane; i < n_in; i += 32) + acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + if (lane == 0) y[o] = acc; +} + +/// TPR lanes cooperate on ONE row's reduction: `threads_per_row` threads each take a strided slice and the +/// block reduces through shared memory. Used when the output width is too small to fill the machine. +__global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, long long n_in, long long n_out, int tpr) { + extern __shared__ float scratch[]; + const long long o = blockIdx.x; + if (o >= n_out) return; + const int t = threadIdx.x; // 0 .. tpr-1 + const uint16_t* row = w + o * n_in; + float acc = 0.0f; + for (long long i = t; i < n_in; i += tpr) + acc += f32_from_bf16(x[i]) * f32_from_bf16(row[i]); + // block reduction; `tpr` is at most a few hundred, so a tree in shared is enough + scratch[t] = acc; + __syncthreads(); + for (int off = tpr >> 1; off > 0; off >>= 1) { + if (t < off) scratch[t] += scratch[t + off]; + __syncthreads(); + } + if (t == 0) y[o] = scratch[0]; +} + +inline void finish(void* stream, const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } + if (stream != nullptr) return; + const cudaError_t s = cudaDeviceSynchronize(); + if (s != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(s)); + std::exit(1); + } +} + +} // namespace + +void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + // **THIS USED TO ALWAYS USE THE NAIVE KERNEL, AND THE NAIVE KERNEL IS UNCOALESCED.** + // + // `bf16_gemv_naive_kernel` gives one THREAD per output row and walks the row contiguously, so at a fixed + // `i` the 32 threads of a warp read `w[(o+k)*n_in + i]` - addresses `n_in * 2` bytes apart. Every load in + // the kernel's inner loop costs 32 transactions instead of 1. The comment above that kernel claims it is + // "used directly for the shapes where the output width is already large", but nothing ever made that + // choice: this function called it unconditionally, at every shape. + // + // What that costs, from the nsys per-kernel table: **4.66 ms/token across 24 calls, 194 us each** - the + // third largest kernel in the engine at the time, moving 1.19 GiB/token at ~210 GB/s where a plain read at + // this geometry measures 641 GB/s (`bench/micro/p32_floor.cu`). + // + // `bf16_gemv_warp_kernel` exists, is checked against this one by `bf16_gemv_parity`, and is coalesced - + // consecutive lanes touch consecutive addresses - which is the property `gr_read`'s comment records as + // having taken it from 262 ms/token to 8.9. The threshold below is where warp-per-row has enough rows to + // fill the machine: 8 warps per block, so 64 rows is 8 blocks and 128 is 16, against 48 SMs. + if (n_out >= 64) { + const int warps = THREADS / 32; + const unsigned grid = (unsigned) ((n_out + warps - 1) / warps); + bf16_gemv_warp_kernel<<>>(x, w, y, n_in, n_out); + finish(stream, "bf16_gemv(warp)"); + return; + } + // Below the threshold the warp kernel would leave most of the machine idle, and the naive one is at least + // not wasting warps. It is still uncoalesced, so this is the branch to revisit if a small-output caller + // ever shows up hot in the profile. + const unsigned grid = (unsigned) ((n_out + THREADS - 1) / THREADS); + bf16_gemv_naive_kernel<<>>(x, w, y, n_in, n_out); + finish(stream, "bf16_gemv"); +} + +void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, + int threads_per_row, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + // WARP-PER-ROW when the caller asks for 32, because that path needs no shared memory and no barrier - and + // with 48 output rows it is the configuration that fills the machine. A `tpr` that is not 32 and not a + // power of two is refused rather than quietly rounded, because the tree reduction below needs one. + if (threads_per_row == 32) { + const int warps = THREADS / 32; + const unsigned grid = (unsigned) ((n_out + warps - 1) / warps); + bf16_gemv_warp_kernel<<>>(x, w, y, n_in, n_out); + finish(stream, "bf16_gemv_split(warp)"); + return; + } + if (threads_per_row <= 0 || (threads_per_row & (threads_per_row - 1)) != 0) { + std::fprintf(stderr, "bf16_gemv_split: threads_per_row %d must be a power of two (32 selects the " + "warp-per-row path)\n", threads_per_row); + std::exit(1); + } + const unsigned grid = (unsigned) n_out; + bf16_gemv_split_kernel<<>>(x, w, y, n_in, n_out, threads_per_row); + finish(stream, "bf16_gemv_split"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/cvec.cu b/engine/strata/src/kernels/cuda/cvec.cu new file mode 100644 index 00000000..66829324 --- /dev/null +++ b/engine/strata/src/kernels/cuda/cvec.cu @@ -0,0 +1,166 @@ +// src/kernels/cuda/cvec.cu - see include/strata/kernels/cvec.hpp. +#include "strata/kernels/cvec.hpp" + +#include + +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; +constexpr int MAXK = 16; // n_embd up to 4096, held in registers between the dot and the update + +Cvec g_cvec; // the description; its device pointers are the uploading device's +bool g_on_host = false; +// the tables on every device that holds them (a layer split applies the vector on several) +constexpr int kDevices = 64; +struct DevTables { float* dir = nullptr; float* s = nullptr; int* on = nullptr; }; +DevTables g_dev[kDevices]; +std::vector g_dir_host, g_s_host; +int cur_device() { + int d = 0; + if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kDevices) d = 0; + return d; +} +bool upload_here(std::string& err) { + DevTables& t = g_dev[cur_device()]; + if (t.dir != nullptr) return true; + const int flag = g_on_host ? 1 : 0; + if (cudaMalloc(&t.dir, g_dir_host.size() * sizeof(float)) != cudaSuccess || + cudaMalloc(&t.s, g_s_host.size() * sizeof(float)) != cudaSuccess || cudaMalloc(&t.on, sizeof(int)) != cudaSuccess || + cudaMemcpy(t.dir, g_dir_host.data(), g_dir_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(t.s, g_s_host.data(), g_s_host.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess || + cudaMemcpy(t.on, &flag, sizeof(int), cudaMemcpyHostToDevice) != cudaSuccess) { + err = "control vector: device allocation failed"; + t = DevTables{}; + return false; + } + return true; +} + +// the fused hyper-connection read's gate (fused_gr.cu), so a write done here is bitwise the one it would have folded +__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } + +// one block per (stream, token): the pending write, then h . v over the stream, then the update +__global__ void cvec_kernel(float* __restrict__ R, const float* __restrict__ dir, const float* __restrict__ s_l, + const int* __restrict__ on, int mode, int64_t layer, int n, int hc, int64_t r_ld, + const float* __restrict__ bo, int64_t bo_ld, const float* __restrict__ inj, + int64_t inj_ld, int write) { + const int c = blockIdx.x; + const int64_t t = blockIdx.y; + float* r = R + t * r_ld + (int64_t) c * n; + const float s = s_l[layer]; + const bool steer = *on != 0 && s != 0.0f; // uniform over the block + if (!steer && !write) return; + const float* v = dir + layer * n; + const float w = write ? 2.0f * sigmoidf_(inj[t * inj_ld + c] / (float) hc) : 0.0f; + const float* b = write ? bo + t * bo_ld : nullptr; + float x[MAXK]; + float dot = 0.0f; +#pragma unroll + for (int k = 0; k < MAXK; ++k) { + const int d = threadIdx.x + k * THREADS; + if (d < n) { + float xv = r[d]; + if (write) xv = fmaf(b[d], w, xv); + x[k] = xv; + if (steer && mode == 0) dot = fmaf(xv, v[d], dot); + } + } + if (steer && mode == 0) { + __shared__ float part[THREADS / 32]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffffu, dot, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = dot; + __syncthreads(); + if (threadIdx.x < 32) { + float p = threadIdx.x < THREADS / 32 ? part[threadIdx.x] : 0.0f; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) p += __shfl_xor_sync(0xffffffffu, p, o); + if (threadIdx.x == 0) part[0] = p; + } + __syncthreads(); + dot = part[0] * s; // s (h . v) + } +#pragma unroll + for (int k = 0; k < MAXK; ++k) { + const int d = threadIdx.x + k * THREADS; + if (d < n) { + float xv = x[k]; + if (steer) xv = mode == 0 ? fmaf(-dot, v[d], xv) : xv + v[d]; + r[d] = xv; + } + } +} + +} // namespace + +const Cvec& cvec() { return g_cvec; } + +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& err) { + if (n_embd < 1 || n_embd > (int64_t) THREADS * MAXK) { err = "control vector: unsupported n_embd"; return false; } + if (s.empty() || dir.size() != s.size() * (size_t) n_embd) { err = "control vector: bad table sizes"; return false; } + int prev = 0; // a new vector replaces the old one on every device + cudaGetDevice(&prev); + for (int d = 0; d < kDevices; ++d) { + if (g_dev[d].dir == nullptr) continue; + cudaSetDevice(d); + cudaDeviceSynchronize(); + cudaFree(g_dev[d].dir); + cudaFree(g_dev[d].s); + cudaFree(g_dev[d].on); + g_dev[d] = DevTables{}; + } + cudaSetDevice(prev); + g_dir_host = dir; + g_s_host = s; + g_on_host = true; + if (!upload_here(err)) return false; + const DevTables& t = g_dev[cur_device()]; + g_cvec.dir = t.dir; + g_cvec.s = t.s; + g_cvec.on = t.on; + g_cvec.mode = mode; + g_cvec.first = first; + g_cvec.last = last; + g_cvec.n_embd = n_embd; + g_cvec.hc = hc; + g_cvec.steered.assign(s.size(), false); + for (size_t l = 0; l < s.size(); ++l) g_cvec.steered[l] = s[l] != 0.0f; + return true; +} + +bool cvec_replicate(std::string& err) { return !g_cvec.loaded() || upload_here(err); } + +void cvec_set_enabled(bool on) { + if (!g_cvec.loaded() || on == g_on_host) return; + int prev = 0; + cudaGetDevice(&prev); + const int v = on ? 1 : 0; + for (int d = 0; d < kDevices; ++d) { + if (g_dev[d].on == nullptr) continue; + cudaSetDevice(d); + cudaDeviceSynchronize(); // nothing in flight may still read the flag + cudaMemcpy(g_dev[d].on, &v, sizeof(int), cudaMemcpyHostToDevice); + } + cudaSetDevice(prev); + g_on_host = on; +} + +bool cvec_enabled() { return g_cvec.loaded() && g_on_host; } + +void cvec_apply(float* R, int64_t layer, int64_t T, int64_t r_ld, const float* bo, int64_t bo_ld, const float* inj, + int64_t inj_ld, bool write, void* stream) { + if (!g_cvec.loaded() || T < 1) return; + const DevTables& t = g_dev[cur_device()]; + if (t.dir == nullptr) throw std::runtime_error("cvec_apply: the control vector is not on this device (cvec_replicate)"); + const dim3 grid((unsigned) g_cvec.hc, (unsigned) T); + cvec_kernel<<>>(R, t.dir, t.s, t.on, g_cvec.mode, layer, + (int) g_cvec.n_embd, (int) g_cvec.hc, r_ld, bo, bo_ld, + inj, inj_ld, write ? 1 : 0); + if (cudaPeekAtLastError() != cudaSuccess) throw std::runtime_error("cvec_apply: launch failed"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/dequant_bf16.cu b/engine/strata/src/kernels/cuda/dequant_bf16.cu new file mode 100644 index 00000000..32601d60 --- /dev/null +++ b/engine/strata/src/kernels/cuda/dequant_bf16.cu @@ -0,0 +1,261 @@ +// src/kernels/cuda/dequant_bf16.cu - see include/strata/kernels/dequant_bf16.hpp. +// +// Arithmetic transcribed from ggml/src/ggml-quants.c at the pinned llama.cpp (MIT License, Copyright (c) 2023-2026 +// The ggml authors): dequantize_row_q2_0/q4_0/q5_0/q8_0/q3_K/q4_K/q5_K/q6_K/iq4_nl/iq4_xs. +#include "strata/kernels/dequant_bf16.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +__device__ __forceinline__ float h2f(const uint8_t* p) { + return __half2float(__ushort_as_half((uint16_t) (p[0] | (p[1] << 8)))); +} +__device__ __forceinline__ uint16_t f2bf(float f) { + uint32_t u = __float_as_uint(f); + // a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`: + // the rounding add below would carry it into -0 or inf + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u); + u += 0x7fffu + ((u >> 16) & 1u); // round to nearest even + return (uint16_t) (u >> 16); +} +__device__ __forceinline__ void put(uint16_t* o, int i, float v) { o[i] = f2bf(v); } +struct H16 { uint16_t v; }; +__device__ __forceinline__ void put(H16* o, int i, float v) { o[i].v = __half_as_ushort(__float2half_rn(v)); } +__device__ __forceinline__ void put(float* o, int i, float v) { o[i] = v; } + +__constant__ int8_t kv_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; + +__device__ __forceinline__ void scale_min_k4(int j, const uint8_t* q, int& d, int& m) { + if (j < 4) { d = q[j] & 63; m = q[j + 4] & 63; } + else { d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); } +} + +// One 32-element group `g` (row-major over the whole slice); `out` points at that group's 32 outputs. +template +__device__ __forceinline__ void group32(const uint8_t* row_blocks, int gi_in_row, T* out) { + if constexpr (TYPE == 42) { // Q2_0: 64 per block of 18 B + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 2) * 18; + const float d = h2f(b); + const int e0 = (gi_in_row % 2) * 32; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int e = e0 + j; + const int q = (b[2 + e / 4] >> ((e % 4) * 2)) & 3; + put(out, j, (float) (q - 1) * d); + } + } else if constexpr (TYPE == 2) { // Q4_0 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 18; + const float d = h2f(b); + for (int j = 0; j < 16; ++j) { + put(out, j, (float) ((b[2 + j] & 0x0F) - 8) * d); + put(out, j + 16, (float) ((b[2 + j] >> 4) - 8) * d); + } + } else if constexpr (TYPE == 6) { // Q5_0 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 22; + const float d = h2f(b); + const uint32_t qh = (uint32_t) b[2] | ((uint32_t) b[3] << 8) | ((uint32_t) b[4] << 16) | ((uint32_t) b[5] << 24); + for (int j = 0; j < 16; ++j) { + const int xh0 = ((qh >> j) << 4) & 0x10; + const int xh1 = (qh >> (j + 12)) & 0x10; + put(out, j, (float) (((b[6 + j] & 0x0F) | xh0) - 16) * d); + put(out, j + 16, (float) (((b[6 + j] >> 4) | xh1) - 16) * d); + } + } else if constexpr (TYPE == 7) { // Q5_1 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 24; + const float d = h2f(b), m = h2f(b + 2); + const uint32_t qh = (uint32_t) b[4] | ((uint32_t) b[5] << 8) | + ((uint32_t) b[6] << 16) | ((uint32_t) b[7] << 24); + for (int j = 0; j < 16; ++j) { + const int xh0 = ((qh >> j) & 1) << 4; + const int xh1 = ((qh >> (j + 16)) & 1) << 4; + put(out, j, (float) ((b[8 + j] & 15) | xh0) * d + m); + put(out, j + 16, (float) ((b[8 + j] >> 4) | xh1) * d + m); + } + } else if constexpr (TYPE == 8) { // Q8_0 + const uint8_t* b = row_blocks + (size_t) gi_in_row * 34; + const float d = h2f(b); + for (int j = 0; j < 32; ++j) put(out, j, (float) (int8_t) b[2 + j] * d); + } else if constexpr (TYPE == 20) { // IQ4_NL + const uint8_t* b = row_blocks + (size_t) gi_in_row * 18; + const float d = h2f(b); + for (int j = 0; j < 16; ++j) { + put(out, j, d * (float) kv_iq4nl[b[2 + j] & 0xf]); + put(out, j + 16, d * (float) kv_iq4nl[b[2 + j] >> 4]); + } + } else if constexpr (TYPE == 11) { // Q3_K: hmask[32] qs[64] scales[12] d + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 110; + const int gi = gi_in_row % 8, n = gi / 4, jj = gi % 4; + const uint8_t* hm = b; + const uint8_t* q = b + 32 + n * 32; + const uint8_t* sc = b + 96; + const float d_all = h2f(b + 108); + uint32_t aux[4]; + memcpy(aux, sc, 12); + const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu, tmp = aux[2]; + aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); + aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); + aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); + aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); + const int8_t* scales = reinterpret_cast(aux); + const int shift = 2 * jj; + const uint8_t m = (uint8_t) (1u << (n * 4 + jj)); + for (int t = 0; t < 32; ++t) { + const int is = n * 8 + jj * 2 + (t >= 16 ? 1 : 0); + const float dl = d_all * (float) (scales[is] - 32); + put(out, t, dl * (float) ((int) ((q[t] >> shift) & 3) - ((hm[t] & m) ? 0 : 4))); + } + } else if constexpr (TYPE == 12) { // Q4_K: d dmin scales[12] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 144; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = h2f(b), dmin = h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* q = b + 16 + 32 * j64; + for (int l = 0; l < 32; ++l) put(out, l, d1 * (float) (hi ? (q[l] >> 4) : (q[l] & 0xF)) - m1); + } else if constexpr (TYPE == 13) { // Q5_K: d dmin scales[12] qh[32] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 176; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = h2f(b), dmin = h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * (float) sc, m1 = dmin * (float) m; + const uint8_t* qh = b + 16; + const uint8_t* ql = b + 48 + 32 * j64; + const uint8_t u = (uint8_t) (1u << (2 * j64 + hi)); + for (int l = 0; l < 32; ++l) { + const int nib = hi ? (ql[l] >> 4) : (ql[l] & 0xF); + put(out, l, d1 * (float) (nib + ((qh[l] & u) ? 16 : 0)) - m1); + } + } else if constexpr (TYPE == 14) { // Q6_K: ql[128] qh[64] scales[16] d + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 210; + const int gi = gi_in_row % 8, n = gi / 4, qu = gi % 4; + const uint8_t* ql = b + 64 * n; + const uint8_t* qh = b + 128 + 32 * n; + const int8_t* sc = reinterpret_cast(b + 192) + 8 * n; + const float d = h2f(b + 208); + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + int q; + if (qu == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4); + else if (qu == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4); + else if (qu == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4); + else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4); + put(out, l, d * (float) sc[is + 2 * qu] * (float) (q - 32)); + } + } else if constexpr (TYPE == 23) { // IQ4_XS: d scales_h scales_l[4] qs[128] + const uint8_t* b = row_blocks + (size_t) (gi_in_row / 8) * 136; + const int ib = gi_in_row % 8; + const float d = h2f(b); + const uint16_t scales_h = (uint16_t) (b[2] | (b[3] << 8)); + const int ls = ((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xf) | (((scales_h >> (2 * ib)) & 3) << 4); + const float dl = d * (float) (ls - 32); + const uint8_t* qs = b + 8 + 16 * ib; + for (int j = 0; j < 16; ++j) { + put(out, j, dl * (float) kv_iq4nl[qs[j] & 0xf]); + put(out, j + 16, dl * (float) kv_iq4nl[qs[j] >> 4]); + } + } +} + +template +__global__ void dequant_kernel(const uint8_t* __restrict__ blocks, int64_t row_bytes, int64_t row0, int64_t rows, + int64_t groups_per_row, T* __restrict__ out) { + const int64_t g = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (g >= rows * groups_per_row) return; + const int64_t r = g / groups_per_row, gi = g % groups_per_row; + group32(blocks + (row0 + r) * row_bytes, (int) gi, out + r * groups_per_row * 32 + gi * 32); +} + +bool geometry(int type, int& block_elems, int& block_bytes) { + switch (type) { + case 2: block_elems = 32; block_bytes = 18; return true; + case 6: block_elems = 32; block_bytes = 22; return true; + case 7: block_elems = 32; block_bytes = 24; return true; + case 8: block_elems = 32; block_bytes = 34; return true; + case 20: block_elems = 32; block_bytes = 18; return true; + case 11: block_elems = 256; block_bytes = 110; return true; + case 12: block_elems = 256; block_bytes = 144; return true; + case 13: block_elems = 256; block_bytes = 176; return true; + case 14: block_elems = 256; block_bytes = 210; return true; + case 23: block_elems = 256; block_bytes = 136; return true; + case 42: block_elems = 64; block_bytes = 18; return true; + default: return false; + } +} + +template +void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, T* out, void* stream) { + int be = 0, bb = 0; + if (!geometry(type, be, bb) || cols % be != 0 || rows <= 0) { + std::fprintf(stderr, "dequant: unsupported type %d or shape %lld x %lld\n", type, (long long) rows, + (long long) cols); + std::exit(1); + } + const int64_t row_bytes = cols / be * bb, gpr = cols / 32, total = rows * gpr; + const unsigned grid = (unsigned) ((total + 255) / 256); + const uint8_t* p = (const uint8_t*) blocks; + cudaStream_t st = (cudaStream_t) stream; +#define STRATA_DQ(TY) dequant_kernel<<>>(p, row_bytes, row0, rows, gpr, out); break + switch (type) { + case 2: STRATA_DQ(2); + case 6: STRATA_DQ(6); + case 7: STRATA_DQ(7); + case 8: STRATA_DQ(8); + case 11: STRATA_DQ(11); + case 12: STRATA_DQ(12); + case 13: STRATA_DQ(13); + case 14: STRATA_DQ(14); + case 20: STRATA_DQ(20); + case 23: STRATA_DQ(23); + case 42: STRATA_DQ(42); + } +#undef STRATA_DQ + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "dequant launch: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +} // namespace + +bool dequant_bf16_supported(int ggml_type) noexcept { + int a, b; + return geometry(ggml_type, a, b); +} + +namespace { +// plan v0.3 P6: the i-quant formats (llama.cpp's dequantizers, iq_kernels.cu) +bool iq_only(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22 || t == 29; } +} // namespace + +void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, + void* stream) { + launch(ggml_type, blocks, row0, rows, cols, out, stream); +} + +void dequant_f16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, + void* stream) { + if (iq_only(ggml_type)) { + iq_dequant_f16(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, + out, stream); + return; + } + launch(ggml_type, blocks, row0, rows, cols, reinterpret_cast(out), stream); +} + +void dequant_f32(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, float* out, void* stream) { + if (iq_only(ggml_type)) { + iq_dequant_f32(ggml_type, (const uint8_t*) blocks + (size_t) row0 * iq_row_bytes(ggml_type, cols), rows * cols, + out, stream); + return; + } + launch(ggml_type, blocks, row0, rows, cols, out, stream); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/dequant_s2.cu b/engine/strata/src/kernels/cuda/dequant_s2.cu new file mode 100644 index 00000000..c141b933 --- /dev/null +++ b/engine/strata/src/kernels/cuda/dequant_s2.cu @@ -0,0 +1,51 @@ +// src/kernels/cuda/dequant_s2.cu - P2.S2's first naive kernel. +// +// S2 is Q2_0's canonical form and 31.64 GiB of the artifact is Q2_0, so this is the single hottest decode in +// the engine. The canonical plane layout is `docs/pack-format.md`'s: codes packed 4 per byte LSB-first +// (element i at byte i/4, bits (i%4)*2 - Q2_0's own convention, kept for every form) and one FP32 scale per +// group (64 elements for S2). The decode is `(code + code_bias) * scale` with `code_bias = -1`, the +// subtraction inside the INTEGER domain, which is what makes it bit-exact (docs/pack-format.md §3.1). +// +// Naive on purpose: one thread per block, no vectors, no shared memory, no unrolling. Phase 3 changes this +// file and the parity test in src/kernels/dequant_s2_parity.cpp is what says whether a change is still right. +#include "strata/kernels/dequant_s2.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK = 64; // S2 group = Q2_0 block = 64 elements +constexpr int CODES_PER_BYTE = 4; + +__global__ void dequant_s2_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, + float* __restrict__ out, long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const float d = scales[b]; + const uint8_t* c = codes + b * (QK / CODES_PER_BYTE); + float* y = out + b * QK; + for (int j = 0; j < QK; ++j) { + const int code = (c[j / CODES_PER_BYTE] >> ((j % CODES_PER_BYTE) * 2)) & 0x03; + y[j] = (float)(code - 1) * d; // the -1 is applied to the CODE, then ONE multiply + } +} + +} // namespace + +void dequant_s2(const uint8_t* codes, const float* scales, float* out, int64_t n_blocks) { + if (n_blocks <= 0) return; + const int threads = 256; + const long long blocks = (n_blocks + threads - 1) / threads; + dequant_s2_kernel<<<(unsigned) blocks, threads>>>(codes, scales, out, n_blocks); + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "dequant_s2: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/elementwise.cu b/engine/strata/src/kernels/cuda/elementwise.cu new file mode 100644 index 00000000..22d022e9 --- /dev/null +++ b/engine/strata/src/kernels/cuda/elementwise.cu @@ -0,0 +1,325 @@ +// src/kernels/cuda/elementwise.cu - P2.S5's glue kernels. See the header for why each exists. +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/dp4a.hpp" + +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; + +__global__ void embedding_gather_kernel(const uint8_t* __restrict__ codes, + const float* __restrict__ scales, + const float* __restrict__ offsets, int64_t n, + int code_bits, int code_bias, int group_elems, + float* __restrict__ out) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const int per_byte = 8 / code_bits; + const unsigned mask = (1u << code_bits) - 1u; + const int code = (codes[i / per_byte] >> ((i % per_byte) * code_bits)) & mask; + const int64_t group = i / group_elems; + const float product = __fmul_rn((float) (code + code_bias), scales[group]); + out[i] = __fadd_rn(product, offsets ? offsets[group] : 0.0f); +} + +/// `ggml_compute_softplus_f32`: `log1p(exp(x))`, with the large-x branch that avoids overflow. +/// +/// The branch is not cosmetic. `exp(89)` overflows f32 and `exp(20)` is already 4.85e8 where `log1p` loses +/// relative precision; above 20 the function is `x` to within f32 anyway. +__device__ __forceinline__ float softplus_dev(float x) { return x > 20.0f ? x : log1pf(expf(x)); } + +__global__ void gdn_gate_kernel(const float* __restrict__ alpha, const float* __restrict__ dt, + const float* __restrict__ ssm_a, float* __restrict__ gate, int64_t h_v) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= h_v) return; + const int64_t t = i / h_v; // `n_tokens` is the leading dim; the real call has one token + const int64_t h = i % h_v; + gate[i] = softplus_dev(alpha[i] + dt[h]) * ssm_a[h]; + (void) t; +} + +__global__ void scale_kernel(float* __restrict__ x, int64_t n, float s) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] *= s; +} + +// `dst[i] += src[i]`. See the header: this is what lets R4's GPU half and CPU half run at the same +// time and still add up to one `parts` buffer. +__global__ void add_kernel(float* __restrict__ dst, const float* __restrict__ src, long long n) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) dst[i] += src[i]; +} + +__global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = f16_from_f32(x[i]); +} + +__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = bf16_from_f32(x[i]); +} + +__global__ void silu_kernel(float* __restrict__ x, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + // DOUBLE then cast, matching `ref/gdn.py`'s numpy: its arrays are f32 but `np.exp` on an f32 array is + // computed to f32 precision by a different algorithm than `expf`, and the reference is the oracle. The + // difference is in the last bits and this is one line. + const double v = (double) x[i]; + x[i] = (float) (v / (1.0 + exp(-v))); +} + +/// A bounded launch: a zero-length grid is illegal, and `n == 0` is a real call (an empty selection). +inline unsigned grid_for(int64_t n) { return (unsigned) ((n + THREADS - 1) / THREADS); } + +/// One WARP per row, reduced through shuffles. The rows here are short and few - (24, 256), (2, 256), +/// (4, 128) - so a block-per-row tree would spend its time in `__syncthreads` for 8 warps of 32, and the whole +/// call is 30 rows. A warp reduction with NO shared memory and NO barrier is the shape that fits. +__global__ void rms_norm_weighted_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t rows, + int64_t cols, float eps) { + + const int lane = threadIdx.x & 31; + const int64_t row = ((int64_t) blockIdx.x * (blockDim.x >> 5)) + (threadIdx.x >> 5); + // **THE ROW GUARD IS NOT DECORATION, AND ITS ABSENCE WAS THE QSA BUG.** The launcher rounds the grid up to + // whole 4-warp blocks, so a call with `rows` = 2 - the QSA k-norm, the only non-multiple-of-4 row count in + // the engine - runs EIGHT warps: rows 0 and 1 are the data, and rows 2 and 3 write 2*cols floats PAST the + // end of `b.kcur`, which in the arena is exactly where `b.vcur` begins. `b.vcur` was therefore silently + // replaced by two rows of `rms_norm(...) * attn_k_norm`: a normalized vector with l2 ~20.6 against V's + // ~5.7, which the attention then attended to. `rope_neox_kernel` has had this guard all along. + if (row >= rows) return; + float* r = x + row * cols; + float acc = 0.0f; + for (int64_t c = lane; c < cols; c += 32) acc += r[c] * r[c]; + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + // The MEAN, not the sum: `ref/qsa.py::rms_norm` divides by `np.mean(np.square(x))`. Broadcasting the + // reciprocal from lane 0 keeps all 32 lanes on the same value - computing `rsqrt` per lane would be the + // same number but a needless 32-way divergence in the last bit. + float inv = 0.0f; + if (lane == 0) inv = rsqrtf(acc / (float) cols + eps); + inv = __shfl_sync(0xFFFFFFFFu, inv, 0); + for (int64_t c = lane; c < cols; c += 32) r[c] = (w ? r[c] * w[c] : r[c]) * inv; +} + +void sync_if_needed(void* stream, const char* what) { + if (stream != nullptr) return; + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +bool check_launch(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + +} // namespace + +void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets, + int64_t n, int code_bits, int code_bias, int group_elems, + float* out, void* stream) { + if (n <= 0) return; + embedding_gather_kernel<<>>( + codes, scales, offsets, n, code_bits, code_bias, group_elems, out); + check_launch("embedding_gather"); +} + +void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens, + int64_t h_v, void* stream) { + if (n_tokens <= 0 || h_v <= 0) return; + const int64_t n = n_tokens * h_v; + gdn_gate_kernel<<>>(alpha, dt, ssm_a, gate, h_v); + check_launch("gdn_gate"); + sync_if_needed(stream, "gdn_gate"); +} + +void scale_inplace(float* x, int64_t n, float s, void* stream) { + if (n <= 0) return; + scale_kernel<<>>(x, n, s); + check_launch("scale_inplace"); + sync_if_needed(stream, "scale_inplace"); +} + +void add_inplace(float* dst, const float* src, int64_t n, void* stream) { + if (n <= 0) return; + add_kernel<<>>(dst, src, n); + check_launch("add_inplace"); + sync_if_needed(stream, "add_inplace"); +} + +void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) { + if (n <= 0) return; + to_f16_kernel<<>>(x, y, n); + check_launch("f32_to_f16_bulk"); + sync_if_needed(stream, "f32_to_f16_bulk"); +} + +void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) { + if (n <= 0) return; + to_bf16_kernel<<>>(x, y, n); + check_launch("f32_to_bf16_bulk"); + sync_if_needed(stream, "f32_to_bf16_bulk"); +} + +void silu_inplace(float* x, int64_t n, void* stream) { + if (n <= 0) return; + silu_kernel<<>>(x, n); + check_launch("silu_inplace"); + sync_if_needed(stream, "silu_inplace"); +} + +/// THE DOORBELL. One thread, one INCREMENT - the cost is the launch, and inside a graph that is paid once. +/// +/// **IT INCREMENTS THE MEMORY, AND IT DOES NOT TAKE THE VALUE AS AN ARGUMENT.** The first version did - +/// doorbell_ring(d_seq, *(h_seq) + 1u) - and that is a CLONED LITERAL: the expression is evaluated on the HOST +/// at CAPTURE time, so the graph rings 1 on every replay and a host waiting for a change waits forever. It +/// would have looked like a working doorbell on the first token, which is the worst way for it to be wrong. +/// **THE FENCE IS NOT DECORATION, AND ITS ABSENCE WAS COSTING ~10 ms PER TOKEN ON THE HOST SIDE.** +/// +/// The ring PUBLISHES three buffers the host is about to read - `h_x_f`, `h_ids`, `h_weights` - so the increment +/// must be ordered after their writes, or the host can observe the ring and then read a payload that has not +/// landed. `__threadfence_system()` is what orders them, and it covers the HOST as well as the device, which is +/// the whole point: the reader is the CPU. +/// +/// Without it the host loop was compensating with a driver call. `session_loop` polled with `cudaEventQuery` +/// on EVERY spin iteration, because round 195 had measured that a memory-only spin never saw the datum flip - +/// and that measurement was right about the symptom and wrong about the cause. The cause is this missing fence: +/// the write was not ordered into host-visible memory, so no amount of reading it would show it, and the driver +/// call was flushing the whole pipeline enough to make it appear. A 10-22 us driver call per iteration is a +/// very expensive substitute for one fence instruction. +/// +/// **THE STORE IS VOLATILE**, like `doorbell_publish_kernel`'s. On RDNA4 (gfx1201) a plain store to mapped pinned +/// memory stays in the GPU's L2 until the stream is synchronized - the host never saw the ring (tests/hip/handoff: +/// 0 of 100 rings seen without a sync; volatile, a system-scope atomic store or a fence after the store: 100 of 100). +__global__ void doorbell_ring_kernel(uint32_t* seq) { + __threadfence_system(); + *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; +} + +__global__ void doorbell_wait_kernel(const volatile uint32_t* flag, const volatile uint32_t* seq) { + const uint32_t want = *seq; + while (*flag != want) strata_spin_pause(); + __threadfence_system(); +} + +void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream) { + if (d_flag == nullptr || d_seq == nullptr) return; + doorbell_wait_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(d_flag, d_seq); + check_launch("doorbell_wait"); +} + +__global__ void copy_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t n4) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (int64_t) gridDim.x * blockDim.x) { + const float4 v = const_cast(src)[i]; + dst[i] = v; + } +} + +// the CPU rows of a verify window, skipping the rows the GPU plan computes itself (the +// pool writes +0.0 into those, so this writes +0.0 too): block = row, the plan's hit rows `dst[0, *count)`. +__global__ void copy_rows_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t row4, + const int32_t* __restrict__ hit_rows, const int32_t* __restrict__ count) { + const int row = blockIdx.x; + __shared__ int hit; + if (threadIdx.x == 0) { + int h = 0; + const int c = *count; + for (int i = 0; i < c; ++i) h |= hit_rows[i] == row; + hit = h; + } + __syncthreads(); + float4* d = dst + (int64_t) row * row4; + if (hit) { + for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + } else { + const volatile float4* sr = src + (int64_t) row * row4; + for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = const_cast(sr)[i]; + } +} +void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows, + const int32_t* count, void* stream) { + if (rows <= 0) return; + if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { + std::fprintf(stderr, "copy_rows_from_mapped: width must be a multiple of 4 and both pointers 16-byte aligned\n"); + std::exit(1); + } + copy_rows_from_mapped_kernel<<<(unsigned) rows, 128, 0, (cudaStream_t) stream>>>((float4*) dst, (const volatile float4*) src, + width / 4, hit_rows, count); +} +void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream) { + if (n <= 0) return; + if ((n & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) { + std::fprintf(stderr, "copy_from_mapped: n must be a multiple of 4 and both pointers 16-byte aligned\n"); + std::exit(1); + } + const int64_t n4 = n / 4; + const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64); + copy_from_mapped_kernel<<>>((float4*) dst, (const volatile float4*) src, n4); + check_launch("copy_from_mapped"); +} + +__global__ void doorbell_publish_kernel(const float* __restrict__ x, const int32_t* __restrict__ ids, + const float* __restrict__ w, int n, int k, float* x_out, int32_t* ids_out, + float* w_out, uint32_t* seq) { + for (int i = threadIdx.x; i < n; i += blockDim.x) x_out[i] = x[i]; + if ((int) threadIdx.x < k) { ids_out[threadIdx.x] = ids[threadIdx.x]; w_out[threadIdx.x] = w[threadIdx.x]; } + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + __threadfence_system(); + *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; + } +} + +void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out, + int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream) { + if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); } + doorbell_publish_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(x, ids, weights, (int) n, (int) k, x_out, ids_out, + weights_out, d_seq); + check_launch("doorbell_publish"); +} + +__global__ void copy_i32_from_mapped_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n) { + for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i]; +} + +void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream) { + if (n <= 0) return; + copy_i32_from_mapped_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n); + check_launch("copy_i32_from_mapped"); +} + +void doorbell_ring(uint32_t* d_seq, void* stream) { + if (d_seq == nullptr) return; + doorbell_ring_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(d_seq); + check_launch("doorbell_ring"); + sync_if_needed(stream, "doorbell_ring"); +} + +void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream) { + if (rows <= 0 || cols <= 0) return; + // 4 warps per block, so a row count that is not a multiple of 4 wastes at most 3 warps rather than + // launching a block per row for a 2-row call. + const unsigned warps_per_block = 4; + const unsigned grid = (unsigned) ((rows + warps_per_block - 1) / warps_per_block); + rms_norm_weighted_kernel<<>>(x, w, rows, cols, eps); + check_launch("rms_norm_weighted"); + sync_if_needed(stream, "rms_norm_weighted"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/fused_gdn.cu b/engine/strata/src/kernels/cuda/fused_gdn.cu new file mode 100644 index 00000000..ef2e7787 --- /dev/null +++ b/engine/strata/src/kernels/cuda/fused_gdn.cu @@ -0,0 +1,166 @@ +// src/kernels/cuda/fused_gdn.cu - see include/strata/kernels/fused_gdn.hpp. +#include "strata/kernels/fused_gdn.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int S = 128; // state size (rows = cols = 128) +constexpr int RG = 4; // row groups +constexpr int RPG = S / RG; // 32 rows per thread + +__global__ void __launch_bounds__(S * RG) gdn_step_norm_kernel(float* __restrict__ state, const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, + const float* __restrict__ beta, + const float* __restrict__ z, + const float* __restrict__ gamma, float eps, + float* __restrict__ y, int h_k, int h_v) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][S]; + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x; + const int col = threadIdx.x; // 0..127 + const int rg = threadIdx.y; // 0..3 + const int tid = rg * S + col; + const int qh = head % h_k; + if (tid < S) { sk[tid] = k[qh * S + tid]; sq[tid] = q[qh * S + tid]; } + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + __syncthreads(); + const float g = __expf(gate[head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][col] = kv; + __syncthreads(); + const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; + const float delta = (v[head * S + col] - g * kv_col) * beta[head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + base[r * row_stride] = s[r]; + } + __syncthreads(); // every thread has read red[] for kv_col + red[rg][col] = o; + __syncthreads(); + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); + sq_part = oc * oc; + } + // RMS over the head's 128 outputs: warps of row group 0 are threads 0..127. + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; + __syncthreads(); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[head * S + col]; + y[head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } +} + +__global__ void __launch_bounds__(S) gdn_conv_l2_kernel(float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, + int qk_heads, float eps) { + __shared__ float part[S / 32]; + const int c = blockIdx.x * S + threadIdx.x; + const float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2], x = qkv[c]; + float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3]; + hist[c * 3] = v1; + hist[c * 3 + 1] = v2; + hist[c * 3 + 2] = x; + float y = sum / (1.0f + __expf(-sum)); + if ((int) blockIdx.x < qk_heads) { + float sq = y * y; + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + y *= rsqrtf(ss + eps); + } + h[c] = y; +} + +__global__ void __launch_bounds__(256) gdn_ab_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa, + const uint16_t* __restrict__ wb, const float* __restrict__ dt, + const float* __restrict__ ssm_a, float* __restrict__ gate, + float* __restrict__ beta, int n, int h_v) { + const int row = blockIdx.x * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (row >= 2 * h_v) return; + const bool is_beta = row >= h_v; + const int r = is_beta ? row - h_v : row; + const uint4* w4 = reinterpret_cast((is_beta ? wb : wa) + (size_t) r * n); + float acc = 0.0f; + for (int j = lane; j < n / 8; j += 32) { + const uint4 wv = __ldg(w4 + j); + const float4 xa = *reinterpret_cast(x + j * 8); + const float4 xb = *reinterpret_cast(x + j * 8 + 4); + acc = fmaf(__uint_as_float(wv.x << 16), xa.x, acc); acc = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, acc); + acc = fmaf(__uint_as_float(wv.y << 16), xa.z, acc); acc = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, acc); + acc = fmaf(__uint_as_float(wv.z << 16), xb.x, acc); acc = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, acc); + acc = fmaf(__uint_as_float(wv.w << 16), xb.z, acc); acc = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, acc); + } + for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o); + if (lane != 0) return; + if (is_beta) { + beta[r] = 1.0f / (1.0f + __expf(-acc)); + } else { + const float v = acc + dt[r]; + const float sp = v > 20.0f ? v : log1pf(__expf(v)); + gate[r] = sp * ssm_a[r]; + } +} + +} // namespace + +void fused_gdn_conv_l2(float* history, const float* qkv, const float* conv_w, float* h, int channels, int qk_heads, + float eps, void* stream) { + if (!history || !qkv || !conv_w || !h || channels % S != 0 || qk_heads < 0 || qk_heads > channels / S) { + std::fprintf(stderr, "fused_gdn_conv_l2: invalid arguments\n"); + std::exit(1); + } + gdn_conv_l2_kernel<<<(unsigned) (channels / S), S, 0, (cudaStream_t) stream>>>(history, qkv, conv_w, h, qk_heads, eps); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_conv_l2: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +void fused_gdn_ab(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a, + float* gate, float* beta, int n_embd, int h_v, void* stream) { + if (!x || !w_alpha || !w_beta || !dt || !ssm_a || !gate || !beta || n_embd % 8 != 0 || h_v <= 0) { + std::fprintf(stderr, "fused_gdn_ab: invalid arguments\n"); + std::exit(1); + } + gdn_ab_kernel<<<(unsigned) ((2 * h_v + 7) / 8), 256, 0, (cudaStream_t) stream>>>(x, w_alpha, w_beta, dt, ssm_a, gate, + beta, n_embd, h_v); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "fused_gdn_ab: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +void fused_gdn_step_norm(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, + void* stream) { + if (!state || !q || !k || !v || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v <= 0 || h_v % h_k) { + std::fprintf(stderr, "fused_gdn_step_norm: invalid arguments\n"); + std::exit(1); + } + gdn_step_norm_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, q, k, v, gate, beta, z, + gamma, eps, y, h_k, h_v); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "fused_gdn_step_norm: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/fused_gr.cu b/engine/strata/src/kernels/cuda/fused_gr.cu new file mode 100644 index 00000000..e7766fb7 --- /dev/null +++ b/engine/strata/src/kernels/cuda/fused_gr.cu @@ -0,0 +1,1081 @@ +// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. +#include "strata/core/emulate.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int N = 2560; // n_embd +constexpr int HC = 4; // streams +constexpr int D = N * HC; // 10240 +constexpr int LR = 320; // hc_lr +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; +constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows +constexpr int UP_COLS = 32; // columns d per `up` block (x 4 streams = 128 rows) +constexpr int UP_BLOCKS = N / UP_COLS; // 80 + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} +__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + __expf(-x)); } + +// 8 bf16 packed in a uint4 against 8 floats. +__device__ __forceinline__ float dot8(const uint4 w, const float* x) { + float acc = 0.0f; + const uint32_t v[4] = {w.x, w.y, w.z, w.w}; +#pragma unroll + for (int j = 0; j < 4; ++j) { + acc = fmaf(__uint_as_float(v[j] << 16), x[2 * j], acc); + acc = fmaf(__uint_as_float(v[j] & 0xffff0000u), x[2 * j + 1], acc); + } + return acc; +} + +__global__ void __launch_bounds__(THREADS) gr_down_kernel(FusedGrArgs a) { + __shared__ __align__(16) float xn[D]; + __shared__ float part[WARPS][HC]; + __shared__ float s_rs[HC]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + float gw[HC]; +#pragma unroll + for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + // 1. R' * w_norm into shared memory, and the per-stream sums of squares of R'. + float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int i = t * 4; i < D; i += THREADS * 4) { + const int c = i / N, d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); + r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + i); + float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; +#pragma unroll + for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; + *reinterpret_cast(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float v = warp_sum(ss[c]); + if (lane == 0) part[warp][c] = v; + } + __syncthreads(); + if (t < HC) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w][t]; + s_rs[t] = rsqrtf(s / (float) N + a.eps); + if (blockIdx.x == 0) a.rs[t] = s_rs[t]; + } + __syncthreads(); + for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; + __syncthreads(); + // 2. one warp per output row: 10240 bf16 = 1280 chunks of 8, 40 per lane. + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? warp : blockIdx.x * WARPS + warp; + if (inject_block && (a.w_inject == nullptr || warp >= HC)) return; + const uint16_t* wrow = (inject_block ? a.w_inject : a.w_down) + (size_t) row * D; + const uint4* w4 = reinterpret_cast(wrow); + float acc = 0.0f; +#pragma unroll 4 + for (int j = lane; j < D / 8; j += 32) acc += dot8(__ldg(w4 + j), xn + j * 8); + acc = warp_sum(acc); + if (lane != 0) return; + if (inject_block) { + a.inject_out[row] = acc; + } else { + const float x = acc / (float) HC; + a.lo[row] = x / (1.0f + __expf(-x)); + } +} + +__global__ void __launch_bounds__(THREADS) gr_up_kernel(FusedGrArgs a) { + __shared__ __align__(16) float lo[LR]; + __shared__ float g[HC][UP_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int d0 = blockIdx.x * UP_COLS; + for (int k = t; k < LR; k += THREADS) lo[k] = a.lo[k]; + __syncthreads(); + // 128 rows (4 streams x 32 columns), 16 per warp: 320 bf16 = 40 chunks of 8. + for (int r = warp; r < HC * UP_COLS; r += WARPS) { + const int c = r / UP_COLS, dd = r - c * UP_COLS, i = c * N + d0 + dd; + const uint4* w4 = reinterpret_cast(a.w_up + (size_t) i * LR); + float acc = dot8(__ldg(w4 + lane), lo + lane * 8); + if (lane < LR / 8 - 32) acc += dot8(__ldg(w4 + 32 + lane), lo + (32 + lane) * 8); + acc = warp_sum(acc); + if (lane == 0) { + float rv = a.R[i]; + if (a.apply) { + rv = fmaf(a.bo_prev[d0 + dd], 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC), rv); + a.R_out[i] = rv; // this block owns column d0+dd of every stream + } + const float x = rv * a.w_norm[i] * a.rs[c]; + g[c][dd] = x * sigmoidf_(acc); + } + } + __syncthreads(); + if (t < UP_COLS) { + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) s += g[c][t]; + a.mixed[d0 + t] = s / (float) HC; + } +} + +// ================================ plan v0.3 P6: T tokens, one weight read ================================ +struct GrMulti { + FusedGrArgs a[kFusedGrMaxT]; + float* xn; + int T; +}; + +// Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. +__global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { + __shared__ float part[WARPS][HC]; + __shared__ float s_rs[HC]; + const FusedGrArgs& a = m.a[blockIdx.x]; + float* xn = m.xn + (size_t) blockIdx.x * D; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + float gw[HC]; +#pragma unroll + for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int i = t * 4; i < D; i += THREADS * 4) { + const int c = i / N, d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw[c], r.x); r.y = fmaf(b.y, gw[c], r.y); + r.z = fmaf(b.z, gw[c], r.z); r.w = fmaf(b.w, gw[c], r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + i); + float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; +#pragma unroll + for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; + *reinterpret_cast(xn + i) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float v = warp_sum(ss[c]); + if (lane == 0) part[warp][c] = v; + } + __syncthreads(); + if (t < HC) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w][t]; + s_rs[t] = rsqrtf(s / (float) N + a.eps); + a.rs[t] = s_rs[t]; + } + __syncthreads(); + for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; +} + +// Step 2 of `gr_down_kernel` for T tokens. One warp per row (so each lane accumulates the same chunks in the +// same order as the single-token kernel); per tile the lane's weight chunks are loaded BEFORE the activation +// tile is staged, so the DRAM and L2 traffic are in flight together. +// +// TILEV = xn floats per token staged at a time. The tile only changes the staging granularity: the lane's chunk +// order (lane + 32*q within the tile, tiles ascending) is strictly increasing for either value, so the results are +// bitwise identical to `gr_down_kernel` for both. 2560 stages 320 chunks of 8 per tile (10 per lane); cards whose +// opt-in below 8 * 2560 * 4 B slices the tokens - sm_75 (64 KiB) carries 6 tokens of it - run TILEV 1280 instead, +// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held +// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks +// of four tokens instead of one on sm_75. +template +__global__ void __launch_bounds__(THREADS) gr_down_multi_kernel(GrMulti m) { + constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile + extern __shared__ __align__(16) float tile[]; // [T][TILEV] + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? warp : blockIdx.x * WARPS + warp; + const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); + const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; + const uint4* w4 = reinterpret_cast(wrow); + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; + for (int base = 0; base < D; base += TILEV) { + uint4 wv[TQ]; + if (active) { +#pragma unroll + for (int q = 0; q < TQ; ++q) wv[q] = __ldg(w4 + base / 8 + lane + 32 * q); + } + __syncthreads(); // the previous tile is consumed + const float4* src4 = reinterpret_cast(m.xn); + float4* tile4 = reinterpret_cast(tile); + for (int i = t; i < T * (TILEV / 4); i += THREADS) { + const int k = i / (TILEV / 4), off = i - k * (TILEV / 4); + tile4[i] = src4[((size_t) k * D + base) / 4 + off]; + } + __syncthreads(); + if (!active) continue; +#pragma unroll + for (int q = 0; q < TQ; ++q) { + const int j = lane + 32 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) + if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8); + } + } + if (!active) return; + float s[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; + // lane k writes token k (every lane holds every sum after the xor reduction) +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T || lane != k) continue; + if (inject_block) { + m.a[k].inject_out[row] = s[k]; + } else { + const float x = s[k] / (float) HC; + m.a[k].lo[row] = x / (1.0f + __expf(-x)); + } + } +} + +constexpr int UPM_COLS = 16; // columns per block (x 4 streams = 64 rows, 8 per warp) +constexpr int UPM_BLOCKS = N / UPM_COLS; // 160 + +// `gr_up_kernel` for T tokens: each row of w_up read once; the T dots reduced by xor so every lane holds every +// sum, and lane k runs token k's epilogue - the T epilogues in parallel instead of one after another. +__global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) { + __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; + __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const int d0 = blockIdx.x * UPM_COLS; + for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; + __syncthreads(); + for (int r = warp; r < HC * UPM_COLS; r += WARPS) { + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); + const uint4 wa = __ldg(w4 + lane); + const uint4 wb = lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0); + // the epilogue inputs of this lane's token, fetched while the dots run + float rv = 0.0f, wn = 0.0f, rsc = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (lane < T) { + const FusedGrArgs& a = m.a[lane]; + rv = a.R[i]; + wn = a.w_norm[i]; + rsc = a.rs[c]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + float acc = dot8(wa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8); + acc = warp_sum(acc); + if (lane == k) mine = acc; + } + if (lane < T) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[lane].R_out[i] = rv; + } + const float x = rv * wn * rsc; + g[lane][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) s += g[k][c][col]; + m.a[k].mixed[d0 + col] = s / (float) HC; + } +} + + +// ================================ hc read v3 (opt-in: STRATA_GR_V3=1) - two kernels, stream-split ================ +// The norm kernel runs on only T blocks (~16 us of pure latency per call) and `down` on 41 blocks (~280 GB/s). +// v3: `down` is split over (row group, stream[, column half]) = 164 or 328 blocks; each block stages its slice of +// R' * w_norm for the T tokens, reduces that slice's sum of squares itself, and writes UNSCALED partial dots. The +// rms scale is per stream, so w_down . xn = sum_c rs[c] * (w_down[:, c] . (R'[c] * w_norm[c])) - `up` applies it +// in its prologue (lo, inject, rs). Same maths, ANOTHER SUMMATION ORDER: not bitwise the default kernels, hence +// opt-in. Dynamic shared memory is T * (N / S) floats: S (1 or 2 column halves) is the smallest that fits the +// card's opt-in limit at kFusedGrMaxT tokens (Ampere 99 KB: S = 1; Turing / HIP 64 KB: S = 2); a card where +// neither fits keeps the default kernels. +constexpr int PR = LR + HC; // partial rows per (token, stream): 320 down + 4 inject +constexpr int TQ3 = N / 8 / 32; // uint4 weight chunks per lane in one stream's slice (10) + +template +__global__ void __launch_bounds__(THREADS) gr_down_v3_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) { + extern __shared__ __align__(16) float xs[]; // [T][N / S] + constexpr int R2 = 1; // down rows per warp + __shared__ float red[WARPS][kFusedGrMaxT]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + // S = 2: each stream's 2560 columns in two halves (blockIdx.y = stream * S + half): twice the blocks + constexpr int SL = N / S, TQS = SL / 8 / 32; + const int rg = blockIdx.x, c = blockIdx.y / S, h = blockIdx.y - (blockIdx.y / S) * S; + constexpr int NDB = LR / (WARPS * R2); // down row blocks per stream; block NDB = the inject rows + const bool inject_block = rg == NDB; + // warp w owns rows row0 + w * R2 + r (r < R2); the inject block: warps 0-3, one row each + const int row0 = inject_block ? warp : (rg * WARPS + warp) * R2; + const int nrows = inject_block ? ((m.a[0].w_inject != nullptr && warp < HC) ? 1 : 0) : R2; + const bool active = nrows > 0; + const uint16_t* wbase = inject_block ? m.a[0].w_inject : m.a[0].w_down; + uint4 wv[R2][TQS]; +#pragma unroll + for (int r = 0; r < R2; ++r) { + if (r >= nrows) break; + const uint4* w4 = reinterpret_cast(wbase + (size_t) (row0 + r) * D + (size_t) c * N + (size_t) h * SL); +#pragma unroll + for (int q = 0; q < TQS; ++q) wv[r][q] = __ldg(w4 + lane + 32 * q); + } + float ssp[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + ssp[k] = 0.0f; + if (k >= T) continue; + const FusedGrArgs& a = m.a[k]; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + const float4* R4 = reinterpret_cast(a.R + (size_t) c * N + (size_t) h * SL); + const float4* G4 = reinterpret_cast(a.w_norm + (size_t) c * N + (size_t) h * SL); + const float4* B4 = reinterpret_cast(a.bo_prev + (size_t) h * SL); + float4* X4 = reinterpret_cast(xs + (size_t) k * SL); + for (int i = t; i < SL / 4; i += THREADS) { + float4 r = R4[i]; + if (a.apply) { + const float4 b = B4[i]; + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = G4[i]; + ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + X4[i] = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w); + } + } +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + const float v = warp_sum(ssp[k]); + if (lane == 0) red[warp][k] = v; + } + __syncthreads(); + if (rg == 0 && t < T) { + float sum = 0.0f; + for (int w = 0; w < WARPS; ++w) sum += red[w][t]; + ssg[(t * HC + c) * S + h] = sum; + } + if (!active) return; +#pragma unroll + for (int r = 0; r < R2; ++r) { + if (r >= nrows) break; + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; +#pragma unroll + for (int q = 0; q < TQS; ++q) { + const int j = lane + 32 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) + if (k < T) acc[k] += dot8(wv[r][q], xs + (size_t) k * SL + j * 8); + } + const int prow = inject_block ? LR + warp : row0 + r; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + const float v = warp_sum(acc[k]); + if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v; + } + } +} + +template +__global__ void __launch_bounds__(THREADS) gr_up_v3_kernel(GrMulti m, const float* __restrict__ part, + const float* __restrict__ ssg) { + __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; + __shared__ float rsS[kFusedGrMaxT][HC]; + __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const int d0 = blockIdx.x * UPM_COLS; + constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp + if (t < T * HC) { + const int k = t / HC, c = t - k * HC; + float ss = 0.0f; +#pragma unroll + for (int h = 0; h < S; ++h) ss += ssg[t * S + h]; + const float r = rsqrtf(ss / (float) N + m.a[k].eps); + rsS[k][c] = r; + if (blockIdx.x == 0) m.a[k].rs[c] = 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; +#pragma unroll + for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + r]; + sum = fmaf(rsS[k][c], p, sum); + } + const float x = sum / (float) HC; + lo[k][r] = x / (1.0f + __expf(-x)); + } + if (blockIdx.x == 0 && t < T * HC) { + const int k = t / HC, cc = t - k * HC; + if (m.a[k].w_inject != nullptr) { + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + float p = 0.0f; +#pragma unroll + for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + LR + cc]; + sum = fmaf(rsS[k][c], p, sum); + } + m.a[k].inject_out[cc] = sum; + } + } + __syncthreads(); +#pragma unroll + for (int q = 0; q < RPW; ++q) { + const int r = warp + q * WARPS; + const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); + const uint4 wa = __ldg(w4 + lane); + const uint4 wb = lane < LR / 8 - 32 ? __ldg(w4 + 32 + lane) : make_uint4(0, 0, 0, 0); + float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f; + bool apply = false; + if (lane < T) { + const FusedGrArgs& a = m.a[lane]; + rv = a.R[i]; + wn = a.w_norm[i]; + apply = a.apply; + if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; } + } + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + float acc = dot8(wa, lo[k] + lane * 8); + if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8); + acc = warp_sum(acc); + if (lane == k) mine = acc; + } + if (lane < T) { + if (apply) { + rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv); + m.a[lane].R_out[i] = rv; + } + const float x = rv * wn * rsS[lane][c]; + g[lane][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) sum += g[k][c][col]; + m.a[k].mixed[d0 + col] = sum / (float) HC; + } +} +// ================================ #315: split / staged - the same arithmetic, split differently ================== +// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums +// in another order). Every variant computes each output with exactly the plain read's operations in its order (so +// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check` +// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below). +// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits +// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs +// is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and +// scaled it in place: the same two roundings). On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per +// 4-token round (96 launches of 1-4 blocks), this one 0.23 ms. +// - the down projection, split: the plain read's kernel. +// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by +// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared +// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's +// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still +// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80 +// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous. +constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3; +constexpr int H_TILE = 1280; // staged tile: half a stream = 160 chunks of 8, 5 per lane +constexpr int HQ = H_TILE / 8 / 32; +constexpr int N_HTILES = D / H_TILE; // 8 +static_assert(N % H_TILE == 0, "a staged tile never straddles two streams"); +static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order"); + +__global__ void __launch_bounds__(THREADS) gr_norm_split_kernel(GrMulti m) { + __shared__ float part[WARPS]; + __shared__ float s_rs; + const FusedGrArgs& a = m.a[blockIdx.x]; + const int c = blockIdx.y; + float* xn = m.xn + (size_t) blockIdx.x * D; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + float ss = 0.0f; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; // another stream's element: another block's + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float sq = r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w; + ss += sq; + } + const float v = warp_sum(ss); + if (lane == 0) part[warp] = v; + __syncthreads(); + if (t == 0) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w]; + s_rs = rsqrtf(s / (float) N + a.eps); + a.rs[c] = s_rs; + } + __syncthreads(); + const float rs = s_rs; + for (int i = t * 4; i < D; i += THREADS * 4) { + if (i / N != c) continue; + const int d = i - c * N; + float4 r = *reinterpret_cast(a.R + i); + if (a.apply) { + const float4 b = *reinterpret_cast(a.bo_prev + d); + r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y); + r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w); + } + const float4 g = *reinterpret_cast(a.w_norm + i); + const float px = r.x * g.x, py = r.y * g.y, pz = r.z * g.z, pw = r.w * g.w; + *reinterpret_cast(xn + i) = make_float4(px * rs, py * rs, pz * rs, pw * rs); + } +} + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 && !defined(__HIPCC__) +#define STRATA_GR_CP_ASYNC 1 +#endif +__device__ __forceinline__ void cp_async16(void* smem, const void* gmem) { +#if defined(STRATA_GR_CP_ASYNC) + const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa), "l"(gmem) : "memory"); +#else + *reinterpret_cast(smem) = *reinterpret_cast(gmem); +#endif +} +__device__ __forceinline__ void cp_async_commit() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.commit_group;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait1() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 1;\n" ::: "memory"); +#endif +} +__device__ __forceinline__ void cp_async_wait0() { +#if defined(STRATA_GR_CP_ASYNC) + asm volatile("cp.async.wait_group 0;\n" ::: "memory"); +#endif +} + +// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order +__device__ __forceinline__ float dot8v(const uint4 w, const float4 x0, const float4 x1) { + float acc = 0.0f; + acc = fmaf(__uint_as_float(w.x << 16), x0.x, acc); + acc = fmaf(__uint_as_float(w.x & 0xffff0000u), x0.y, acc); + acc = fmaf(__uint_as_float(w.y << 16), x0.z, acc); + acc = fmaf(__uint_as_float(w.y & 0xffff0000u), x0.w, acc); + acc = fmaf(__uint_as_float(w.z << 16), x1.x, acc); + acc = fmaf(__uint_as_float(w.z & 0xffff0000u), x1.y, acc); + acc = fmaf(__uint_as_float(w.w << 16), x1.z, acc); + acc = fmaf(__uint_as_float(w.w & 0xffff0000u), x1.w, acc); + return acc; +} + +// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk. +__device__ __forceinline__ void stage_htile(const GrMulti& m, int T, int h, float4* buf, int t) { + for (int i = t; i < T * (H_TILE / 4); i += THREADS) { + const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1 + const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4; + cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src); + } +} + +__global__ void __launch_bounds__(THREADS) gr_down_staged_kernel(GrMulti m) { + extern __shared__ __align__(16) float4 hbuf[]; // 2 buffers x [T][2][160] float4 + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int T = m.T; + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? warp : blockIdx.x * WARPS + warp; + const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); + const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; + const uint4* w4 = reinterpret_cast(wrow); + const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first) + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; + uint4 wv[HQ], wnext[HQ]; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = __ldg(w4 + lane + 32 * q); + } + stage_htile(m, T, 0, hbuf, t); + cp_async_commit(); + stage_htile(m, T, 1, hbuf + buf_f4, t); + cp_async_commit(); +#pragma unroll 1 + for (int h = 0; h < N_HTILES; ++h) { + if (active && h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wnext[q] = __ldg(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q); + } + if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way) + else cp_async_wait0(); + __syncthreads(); + const float4* cur = hbuf + (h & 1) * buf_f4; + if (active) { +#pragma unroll + for (int q = 0; q < HQ; ++q) { + const int j = lane + 32 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k < T) { + const float4* pk = cur + (size_t) k * (H_TILE / 4); + acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]); + } + } + } + } + __syncthreads(); // every warp is done with buffer h & 1 + if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t); + cp_async_commit(); // an empty group at the end keeps the wait counts simple + if (h + 1 < N_HTILES) { +#pragma unroll + for (int q = 0; q < HQ; ++q) wv[q] = wnext[q]; + } + } + if (!active) return; + float s[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f; + // lane k writes token k (every lane holds every sum after the xor reduction) +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T || lane != k) continue; + if (inject_block) { + m.a[k].inject_out[row] = s[k]; + } else { + const float x = s[k] / (float) HC; + m.a[k].lo[row] = x / (1.0f + __expf(-x)); + } + } +} + +// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read +// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory +// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards). +int down_chunk(bool staged, int* tile_out) { + static bool attr[64] = {}; + static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card + static int chunk_staged[64] = {}; // the same for staged + static int tile[64] = {}; // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere) + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64) { + *tile_out = 2560; + return kFusedGrMaxT; + } + if (!attr[dev]) { + int optin = 0; + cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only) + // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the + // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing), + // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid + // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens; + // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and + // the up kernel below still sees every token of the batch in one launch. +#if defined(__HIPCC__) + const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile +#else + int cc_maj = 0, cc_min = 0; + cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&cc_min, cudaDevAttrComputeCapabilityMinor, dev); + const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75; +#endif + const int tv = small_tile ? 1280 : 2560; + tile[dev] = tv; + int want = (int) (kFusedGrMaxT * tv * sizeof(float)); + if (optin > 0 && want > optin) want = optin; + if (small_tile) { + cudaFuncSetAttribute(gr_down_multi_kernel<1280>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } else { + cudaFuncSetAttribute(gr_down_multi_kernel<2560>, cudaFuncAttributeMaxDynamicSharedMemorySize, want); + } + int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float)); + if (optin > 0 && want_staged > optin) want_staged = optin; + cudaFuncSetAttribute(gr_down_staged_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, want_staged); + cudaGetLastError(); // drop any error the attempt left behind + // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers 65536 and accepts the + // cudaFuncSetAttribute for 61440 B, then fails the LAUNCH with "invalid argument". What such a card + // will launch is its per-block limit, so the capacity comes from that below sm_70 - the same tokens + // the "no opt-in" branch assumes, but taken from the attribute that is actually enforced. +#if defined(__HIPCC__) + const int usable = optin > 0 ? optin : 48 * 1024; +#else + int cc = 0, per_block = 0; + cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev); + cc = strata::cc_major_of(cc); + const int usable = (cc >= 7 && optin > 0) ? optin : per_block; +#endif + const int capacity = usable / (int) (tv * sizeof(float)); + chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity); + const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float)); + chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged); + attr[dev] = true; + } + *tile_out = tile[dev] ? tile[dev] : 2560; + return staged ? chunk_staged[dev] : chunk[dev]; +} + +// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as +// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection. +// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi +// takes first). +void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) { + const int n_tok = m.T; + if (variant >= kHcSplit) gr_norm_split_kernel<<>>(m); + else gr_norm_multi_kernel<<>>(m); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st); + const bool staged = variant >= kHcStaged; + int tv = 2560; + const int chunk_tok = down_chunk(staged, &tv); + const size_t per_tok = (staged ? (size_t) 2 * H_TILE : (size_t) tv) * sizeof(float); + for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) { + const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok; + GrMulti c{}; + if (ct == n_tok) { + c = m; + } else { + c.xn = m.xn + (size_t) c0 * D; + c.T = ct; + for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k]; + } + const size_t smem = (size_t) ct * per_tok; + if (staged) gr_down_staged_kernel<<>>(c); + else if (tv == 1280) gr_down_multi_kernel<1280><<>>(c); + else gr_down_multi_kernel<2560><<>>(c); + } + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st); + gr_up_multi_kernel<<>>(m); +} + +/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read +int env_variant() { + const char* e = std::getenv("STRATA_HC_SPLIT"); + if (e == nullptr || e[0] == '\0') return kHcStaged; + if (e[0] == '0') return kHcPlain; + if (e[0] == '1') return kHcSplit; + return kHcStaged; +} + +// per device: the variant `fused_gr_check` chose (0 = not checked yet) +std::atomic g_variant[64]; + +} // namespace + +void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, + int stamp_i0) { + if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { + std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n"); + std::exit(1); + } + GrMulti m; + for (int t = 0; t < n_tok; ++t) { + m.a[t] = a[t]; + const FusedGrArgs& x = a[t]; + if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) || + (x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up || + x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) { + std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t); + std::exit(1); + } + } + m.xn = xn_scratch; + m.T = n_tok; + cudaStream_t st = (cudaStream_t) stream; + // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in) + static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); + static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit + int dev3 = 0; + if (v3) { + cudaGetDevice(&dev3); + if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) { + int optin = 0; + cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev3); + const int limit = optin > 0 ? optin : 48 * 1024; + const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need2 = need1 / 2; + int split = -1; + if (need1 <= limit && + cudaFuncSetAttribute(gr_down_v3_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess) + split = 1; + else if (need2 <= limit) + // #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity + // (graph replay vs direct call) - such a card keeps the default read until that split is fixed + std::fprintf(stderr, "strata: STRATA_GR_V3=1 needs the two-half split on this card, which fails its " + "checks (#375): the default read is used\n"); + cudaGetLastError(); // drop any error the attempts left behind + split3[dev3] = split; + } + } + const int split = v3 && dev3 >= 0 && dev3 < 64 ? split3[dev3] : -1; + if (split > 0) { // 2 kernels; scratch = partials + sums of squares + float* part = xn_scratch; + float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR; // room for S = 2 + const size_t sm = (size_t) n_tok * (N / split) * sizeof(float); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); + if (split == 2) gr_down_v3_kernel<2><<>>(m, part, ssg); + else gr_down_v3_kernel<1><<>>(m, part, ssg); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); + if (split == 2) gr_up_v3_kernel<2><<>>(m, part, ssg); + else gr_up_v3_kernel<1><<>>(m, part, ssg); + const cudaError_t e3 = cudaGetLastError(); + if (e3 != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read_multi v3: %s\n", cudaGetErrorString(e3)); + std::exit(1); + } + return; + } + // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted + launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr) { + return n_embd == N && hc == HC && hc_lr == LR; +} + +void fused_gr_read(const FusedGrArgs& a, void* stream) { + if (!a.R || !a.w_norm || !a.w_down || !a.w_up || !a.lo || !a.rs || !a.mixed || + (a.w_inject && !a.inject_out) || (a.apply && (!a.bo_prev || !a.inj_prev || !a.R_out)) || + (a.apply && a.inj_prev == a.inject_out)) { + std::fprintf(stderr, "fused_gr_read: invalid arguments\n"); + std::exit(1); + } + cudaStream_t st = (cudaStream_t) stream; + gr_down_kernel<<>>(a); + gr_up_kernel<<>>(a); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + + +namespace { + +/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs, +/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's +/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant +/// v; false if the check itself could not run. +bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) { + constexpr int TM = kFusedGrMaxT; + constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token + std::mt19937 rng(20260930u); + std::normal_distribution nd(0.0f, 1.0f); + std::vector h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D); + std::vector h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC); + for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng)); + for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng)); + for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng); + for (auto& x : h_R) x = nd(rng); + for (auto& x : h_bo) x = 0.5f * nd(rng); + for (auto& x : h_ip) x = 2.0f * nd(rng); + for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); } + + const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats) + const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 + + (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256; + uint8_t* base = nullptr; + if (cudaMalloc((void**) &base, bytes) != cudaSuccess) { + cudaGetLastError(); + why[0] = "no room for the check (" + std::to_string(bytes >> 20) + " MiB)"; + return false; + } + size_t off = 0; + auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; }; + uint16_t* d_down = (uint16_t*) take(h_down.size() * 2); + uint16_t* d_up = (uint16_t*) take(h_up.size() * 2); + uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2); + float* d_norm = (float*) take(h_norm.size() * 4); + float* d_R = (float*) take(h_R.size() * 4); + float* d_bo = (float*) take(h_bo.size() * 4); + float* d_ip = (float*) take(h_ip.size() * 4); + struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV]; + for (Set& x : set) { + x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4); + x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4); + x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4); + } + cudaStream_t st = nullptr; + bool ok = off <= bytes && cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking) == cudaSuccess && + cudaMemcpyAsync(d_down, h_down.data(), h_down.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_up, h_up.data(), h_up.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_inj, h_inj.data(), h_inj.size() * 2, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_norm, h_norm.data(), h_norm.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_R, h_R.data(), h_R.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_bo, h_bo.data(), h_bo.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess && + cudaMemcpyAsync(d_ip, h_ip.data(), h_ip.size() * 4, cudaMemcpyHostToDevice, st) == cudaSuccess; + if (!ok) why[0] = "setting up the check failed"; + std::vector h1, h2; + // true when equal; false with the first difference in `w` (or a read-back failure in `ok`) + auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) { + h1.resize(n); + h2.resize(n); + if (cudaMemcpyAsync(h1.data(), d1, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaMemcpyAsync(h2.data(), d2, n * 4, cudaMemcpyDeviceToHost, st) != cudaSuccess || + cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "reading back the check failed"; + ok = false; + return false; + } + for (size_t i = 0; i < n; ++i) { + uint32_t u1, u2; + std::memcpy(&u1, &h1[i], 4); + std::memcpy(&u2, &h2[i], 4); + if (u1 != u2) { + char buf[192]; + std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T, + apply ? " with the pending write" : "", i, u2, u1); + w = buf; + return false; + } + } + return true; + }; + auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) { + return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) && + same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) && + same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) && + same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) && + same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w); + }; + ok_variant[2] = ok_variant[3] = ok; + bool single_ok = ok; + for (int apply = 0; apply < 2 && ok; ++apply) { + for (int T = 1; T <= TM && ok; ++T) { + FusedGrArgs a[NV][TM]; + for (int v = 0; v < NV; ++v) { + const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out); + ok = ok && cudaMemsetAsync(set[v].R_out, 0xFF, span, st) == cudaSuccess; // the whole set + for (int k = 0; k < T; ++k) { + FusedGrArgs& x = a[v][k]; + x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0; + x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC; + x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f; + x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC; + x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N; + } + } + for (int v = 0; v < 3; ++v) { + GrMulti m; + for (int k = 0; k < T; ++k) m.a[k] = a[v][k]; + m.xn = set[v].xn; + m.T = T; + launch_multi(m, v + 1, st, nullptr, 0); + } + if (T == 1) fused_gr_read(a[3][0], st); + if (cudaGetLastError() != cudaSuccess || cudaStreamSynchronize(st) != cudaSuccess) { + why[0] = "a kernel of the check failed"; + ok = false; + break; + } + if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false; + if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false; + if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false; + } + } + if (!single_ok && ok) { // the plain read itself disagrees with the single-token read + why[2] = why[3] = "the plain read differs from the single-token read: " + why[1]; + ok_variant[2] = ok_variant[3] = false; + } + if (st != nullptr) { + cudaStreamSynchronize(st); + cudaStreamDestroy(st); + } + cudaFree(base); + cudaGetLastError(); + if (!ok) ok_variant[2] = ok_variant[3] = false; + return ok; +} + +} // namespace + +int fused_gr_variant() { + int dev = 0; + cudaGetDevice(&dev); + const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0; + if (v > 0) return v; + // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity) + const char* e = std::getenv("STRATA_HC_SPLIT"); + return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain; +} + +void fused_gr_check() { + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return; + const int want = env_variant(); + if (want == kHcPlain) { + g_variant[dev].store(kHcPlain); + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n", + dev); + return; + } + bool okv[4]; + std::string why[4]; + const bool ran = fused_gr_selftest(okv, why); + int use = kHcPlain; + if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged; + else if (okv[kHcSplit]) use = kHcSplit; + g_variant[dev].store(use); + if (!ran) + std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str()); + static const char* const name[4] = {"", "plain", "split", "staged"}; + for (int v = kHcStaged; v >= kHcSplit; --v) + if (v <= want && !okv[v] && ran) + std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: " + "%s\n", dev, name[v], why[v].c_str()); + static const char* const what[4] = { + "", "the plain read (the norm per token, the down projection on 41 blocks)", + "split (the norm per token and stream, then the plain read's down projection)", + "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"}; + std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use], + use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 " + "for the earlier ones)" : ""); +} + + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/gdn.cu b/engine/strata/src/kernels/cuda/gdn.cu new file mode 100644 index 00000000..aad247a7 --- /dev/null +++ b/engine/strata/src/kernels/cuda/gdn.cu @@ -0,0 +1,248 @@ +// src/kernels/cuda/gdn.cu - P2.S2: the gated delta-net's non-projection parts. +// +// See include/strata/kernels/gdn.hpp for the state layout (S, h_v, S) and for why the recurrence needs no +// barrier at all: every line of it touches only one (j, h) column, so one thread owns a column end to end. +#include "strata/kernels/gdn.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int JTHREADS = 32; ///< threads along j, the state's fast axis +/// Heads staged per block. **THIS IS A LATENCY-HIDING KNOB, NOT A CAPACITY ONE, AND IT WAS SET WRONG.** +/// +/// The kernel is one thread per `(h, j)` COLUMN of the state, so the thread count is fixed at +/// `S * h_v` = 128 * 48 = **6,144** no matter how the work is packed - and `MAX_H` decides only how many of +/// those columns share a block: +/// +/// MAX_H = 8 grid = (S/32, h_v/8) = (4, 6) = 24 blocks x 32 threads -> 1 warp on 24 of 48 SMs +/// MAX_H = 1 grid = (S/32, h_v/1) = (4, 48) = 192 blocks x 32 threads -> 4 warps on every SM +/// +/// Each thread walks `i` in 0..S-1 TWICE per head with a strided global load each step, so it is entirely +/// latency-bound: a warp that issues one 128-byte transaction and then waits ~600 cycles needs other warps to +/// run meanwhile, and at 24 blocks there were none. Measured 0.2800 ms per GDN block - 10 ms of a 71.5 ms +/// token, 14%, in a kernel touching 12.6 MB that a 643 GB/s card should do in 0.020 ms. +/// +/// The arithmetic does not change at all: the same columns are computed by the same code, in different blocks. +constexpr int MAX_H = 1; ///< heads staged in shared memory per block + +/// ggml_compute_softplus_f32: log1p(exp(x)), with the large-x branch that avoids overflow. +__device__ __forceinline__ float softplus_f(float x) { return x > 20.0f ? x : log1pf(expf(x)); } +__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); } + +/// One step of the recurrence. One thread per (h, j) column of the state. +/// +/// `ks`/`qs` stage `k[idx[h]]` and `q[idx[h]]` for the block's heads. Within a warp h is constant and j +/// varies, so the staged row is read with a single broadcast - which is also why the GLOBAL loads of +/// `q`/`k` are done once per block into shared instead of once per thread. +__global__ void gdn_step_kernel(float* __restrict__ state, const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ v, + const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ o, int S, int h_k, int h_v) { + __shared__ float ks[MAX_H][128]; + __shared__ float qs[MAX_H][128]; + __shared__ float dec_s[MAX_H]; + __shared__ float beta_s[MAX_H]; + + const int h0 = blockIdx.y * MAX_H; + const int nh = min(MAX_H, h_v - h0); + const int j = blockIdx.x * JTHREADS + threadIdx.x; + + // stage this block's q/k rows and its per-head scalars + for (int hi = 0; hi < nh; ++hi) { + const int h = h0 + hi; + const int src = h % h_k; // MODULO head pairing + for (int i = threadIdx.x; i < S; i += JTHREADS) { + ks[hi][i] = k[src * S + i]; + qs[hi][i] = q[src * S + i]; + } + if (threadIdx.x == 0) { + dec_s[hi] = expf(gate[h]); + beta_s[hi] = beta[h]; + } + } + __syncthreads(); + if (j >= S) return; + + for (int hi = 0; hi < nh; ++hi) { + const int h = h0 + hi; + const float dec = dec_s[hi], b = beta_s[hi]; + float* col = state + (size_t) h * S + j; // (S, h_v, S) with j fastest + const size_t stride = (size_t) h_v * S; + + // pass 1: decay the state and contract it against k. Decay BEFORE the update - PROPERTY 5. + float sk = 0.0f; + for (int i = 0; i < S; ++i) { + const float s = col[(size_t) i * stride] * dec; + col[(size_t) i * stride] = s; + sk += s * ks[hi][i]; + } + const float d = (v[(size_t) h * S + j] - sk) * b; + // pass 2: the rank-1 update, then read out against q using the UPDATED state + float dot = 0.0f; + for (int i = 0; i < S; ++i) { + const float s = col[(size_t) i * stride] + ks[hi][i] * d; + col[(size_t) i * stride] = s; + dot += s * qs[hi][i]; + } + o[(size_t) h * S + j] = dot; + } +} + +/// `ggml_ssm_conv`: out[c] = sum_i inp[i][c] * kW[c*d_conv + i], inp = [conv_state | x], and the state slides. +/// One thread per channel; d_conv is 4, so the serial work per thread is a 4-tap dot and an unrolled shift. +__global__ void gdn_conv_kernel(float* __restrict__ cs, const float* __restrict__ x, + const float* __restrict__ kW, float* __restrict__ out, int C, int dc) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float* st = cs + (size_t) c * (dc - 1); + const float* w = kW + (size_t) c * dc; + float acc = 0.0f; + for (int i = 0; i < dc - 1; ++i) acc += st[i] * w[i]; // kernel[0] reads the OLDEST state row + acc += x[c] * w[dc - 1]; // the new input lands in the LAST tap + out[c] = acc; + for (int i = 0; i < dc - 2; ++i) st[i] = st[i + 1]; // slide: drop the oldest, append the newest + st[dc - 2] = x[c]; +} + +/// `build_gdn_l2_norm`, one warp per row: x / sqrt(sum(x^2) + eps) over the last axis. +/// +/// The sum is accumulated in DOUBLE, as `ref/gdn.py` does (`l2_norm(q.astype(np.float64), eps)`), because the +/// reference deliberately computes this one in float64 and then casts - so matching its precision is part of +/// transcribing it. +__global__ void gdn_l2_kernel(float* __restrict__ x, int cols, float eps) { + const int row = blockIdx.x; + float* p = x + (size_t) row * cols; + double acc = 0.0; + for (int i = threadIdx.x; i < cols; i += blockDim.x) acc += (double) p[i] * (double) p[i]; + // warp reduction + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + __shared__ double ssum; + if (threadIdx.x == 0) ssum = acc; + __syncthreads(); + const float inv = (float) (1.0 / sqrt(ssum + (double) eps)); + for (int i = threadIdx.x; i < cols; i += blockDim.x) p[i] *= inv; +} + +/// y = rms_norm(o, eps) * ssm_norm * sigmoid(z), one warp per head, norm over that head's S values. +__global__ void gdn_out_norm_kernel(const float* __restrict__ o, const float* __restrict__ z, + const float* __restrict__ ssm_norm, float* __restrict__ y, int S, + float eps) { + const int h = blockIdx.x; + const float* po = o + (size_t) h * S; + const float* pz = z + (size_t) h * S; + float* py = y + (size_t) h * S; + double acc = 0.0; + for (int i = threadIdx.x; i < S; i += blockDim.x) acc += (double) po[i] * (double) po[i]; + for (int off = 16; off > 0; off >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, off); + __shared__ double ssum; + if (threadIdx.x == 0) ssum = acc; + __syncthreads(); + const float inv = (float) (1.0 / sqrt(ssum / (double) S + (double) eps)); + for (int i = threadIdx.x; i < S; i += blockDim.x) + py[i] = po[i] * inv * ssm_norm[i] * sigmoid_f(pz[i]); +} + +} // namespace + +void gdn_step(float* state, const float* q, const float* k, const float* v, const float* gate, + const float* beta, float* o, const GdnShapes& s, void* stream) { + if (s.S <= 0 || s.h_k <= 0 || s.h_v <= 0) return; + if (s.S > 128) { + std::fprintf(stderr, "gdn_step: S = %lld exceeds the staged 128 (`ks`/`qs` are [8][128])\n", + (long long) s.S); + std::exit(1); + } + const dim3 grid((unsigned) ((s.S + JTHREADS - 1) / JTHREADS), + (unsigned) ((s.h_v + MAX_H - 1) / MAX_H)); + gdn_step_kernel<<>>(state, q, k, v, gate, beta, o, (int) s.S, + (int) s.h_k, (int) s.h_v); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_step: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +void gdn_conv_step(float* conv_state, const float* x, const float* kW, float* out, int64_t channels, + int64_t d_conv, void* stream) { + if (channels <= 0 || d_conv < 1) return; + const int blocks = (int) ((channels + 255) / 256); + gdn_conv_kernel<<>>(conv_state, x, kW, out, (int) channels, + (int) d_conv); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_conv_step: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +void gdn_l2_norm(float* x, int64_t rows, int64_t cols, float eps, void* stream) { + if (rows <= 0 || cols <= 0) return; + if (cols > 1024) { + std::fprintf(stderr, "gdn_l2_norm: cols = %lld exceeds the 1024-wide warp reduction\n", (long long) cols); + std::exit(1); + } + gdn_l2_kernel<<<(unsigned) rows, 32, 0, (cudaStream_t) stream>>>(x, (int) cols, eps); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_l2_norm: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +/// `beta = sigmoid(beta)`, in place, over the `h_v` per-head scalars. +/// +/// **THIS IS `build_layer_attn_linear` L889, AND LEAVING IT OUT WAS THE C1 BUG.** The reference computes +/// `beta = ggml_sigmoid(ssm_beta @ cur)` and hands the RESULT to the delta net; `gdn_step_kernel` is documented +/// as `d[h,j] = (v[h,j] - sk[h,j]) * beta[h]` and applies no sigmoid of its own, so the layer glue owes it one. +/// The engine passed the raw pre-activation, which is unbounded and signed - the delta-net write strength then +/// stops being a fraction and the whole recurrence is wrong from layer 0. +/// +/// **IT SURVIVED `gdn_parity` BECAUSE THAT TEST SUPPLIES ITS OWN `beta`.** The kernel was always right; only +/// the glue between the projection and the kernel was wrong, and `ref/gdn.py` (`beta = sigmoid(wbeta @ x)`) and +/// `ref/model.py` (`beta = G.sigmoid(proj(...))`) both get it right - so the two transcriptions agreed with +/// each other and neither was ever compared against the C++ that actually runs. +__global__ void gdn_beta_gate_kernel(float* __restrict__ beta, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) beta[i] = sigmoid_f(beta[i]); +} + +void gdn_beta_gate(float* beta, int64_t h_v, void* stream) { + if (beta == nullptr || h_v <= 0) return; + const int n = (int) h_v; + gdn_beta_gate_kernel<<<(unsigned) ((n + 127) / 128), 128, 0, (cudaStream_t) stream>>>(beta, n); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_beta_gate: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +void gdn_out_norm(const float* o, const float* z, const float* ssm_norm, float* y, int64_t h_v, int64_t S, + float eps, void* stream) { + if (h_v <= 0 || S <= 0) return; + gdn_out_norm_kernel<<<(unsigned) h_v, 32, 0, (cudaStream_t) stream>>>(o, z, ssm_norm, y, (int) S, eps); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gdn_out_norm: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/gr.cu b/engine/strata/src/kernels/cuda/gr.cu new file mode 100644 index 00000000..7eea7f49 --- /dev/null +++ b/engine/strata/src/kernels/cuda/gr.cu @@ -0,0 +1,432 @@ +// src/kernels/cuda/gr.cu - P2.S2: the gated residual / hyper-connection, `gr_read` and `gr_write`. +// +// See include/strata/kernels/gr.hpp for the semantics, for why the weights are bf16, and for the history of +// this kernel's 134x-off-the-floor first version. The short form: it was launched `<<<1, 256>>>` so that +// `xn`/`xq` fit in shared memory, which used ONE of 48 SMs and cost 262 ms/token. +// +// THE SHAPE OF THE FIX is that each projection is an ordinary GEMV and is now mapped the way the shapes want: +// +// norm hc blocks, one per residual stream (each needs its own reduction) +// down ONE WARP PER OUTPUT ROW, lanes stride the 10240 reduction axis +// gate ONE WARP PER OUTPUT ROW, lanes stride the 320 reduction axis +// mean a flat elementwise pass over n_embd +// +// WARP-PER-ROW RATHER THAN THREAD-PER-ROW, and that is the whole difference. A thread walking one row is +// coalesced with ITSELF and 32 transactions away from its warp neighbours: `w_down[k*hc_dim + i]` for fixed k +// is contiguous, but two threads on rows k and k+1 are hc_dim*2 bytes apart. With the warp on one row, lanes +// i, i+1, i+2 touch consecutive addresses in EITHER orientation - which is why this version needs no +// transposed copies and takes both matrices exactly as the manifest stores them. +// +// Layouts are the MANIFEST's: `hc_attn_down.weight` is [10240, 320] with ne0 = hc*n_embd fast, so it holds +// `w_down[k][i]` with i contiguous - `ref/gr.py`'s (hc_lr, hc*n_embd) row-major. `hc_attn_up.weight` is +// [320, 10240] so it holds `w_up[i][k]` with k contiguous - `ref/gr.py`'s (hc*n_embd, hc_lr) row-major. Both +// index with no permutation at all. +#include "strata/kernels/gr.hpp" +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/native_gr_norm.hpp" +#include "strata/kernels/native_gr_postops.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; +bool fp32_activations = false; +bool native_mmvf = false; + +/// The bf16 conversions live in `strata/kernels/bf16_bits.hpp`, and this file used to carry its own copies. +/// Two files with a private copy of a conversion whose failure mode is silent wrong bits is one too many - +/// and the reason the shared header exists is that `bf16` and `fp16` are NOT two spellings of one idea, so a +/// routine written for one and reused for the other is wrong in a way that still produces numbers. +/// +/// The local names are kept as thin wrappers so the body below is untouched by the swap. +__device__ __forceinline__ uint16_t f32_to_bf16_bits(float f) { return bf16_from_f32(f); } +__device__ __forceinline__ float bf16_bits_to_f32(uint16_t h) { return f32_from_bf16(h); } +__device__ __forceinline__ float activation_f32(float x) { return x; } +__device__ __forceinline__ float activation_f32(uint16_t x) { return bf16_bits_to_f32(x); } +__device__ __forceinline__ void store_activation(float* dst, int i, float x) { dst[i] = x; } +__device__ __forceinline__ void store_activation(uint16_t* dst, int i, float x) { + dst[i] = f32_to_bf16_bits(x); +} + +/// silu and sigmoid exactly as `ref/gr.py` writes them - in FLOAT, not double. +/// +/// This is the opposite of `shared_expert.cu`, which uses double, and the difference is not stylistic: +/// `ref/gr.py`'s arrays are float32, so `x / (1.0 + np.exp(-x))` evaluates in float32 under NEP 50, while +/// `ref/moe.py` works in float64. Matching the reference's PRECISION is part of transcribing it. +__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); } +__device__ __forceinline__ float sigmoid_f(float x) { return 1.0f / (1.0f + expf(-x)); } + +__device__ __forceinline__ double warp_sum(double v) { + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + return __shfl_sync(0xFFFFFFFFu, v, 0); +} + +__device__ __forceinline__ float warp_sumf(float v) { + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + return __shfl_sync(0xFFFFFFFFu, v, 0); +} + +/// The FP32 block-wide sum, for the reason the review's G5 states: this is a GeForce part and FP64 runs at a +/// small fraction of FP32, so a `double` reduction turns a bandwidth kernel into a latency kernel. +/// +/// The scratch is taken as `double*` and reinterpreted as `float*` rather than changing the callers' shared +/// arrays, because `double scratch[8]` is 64 bytes and so is at least as large as the `float[8]` this needs - +/// the cast cannot overrun, and it keeps the change to one function instead of one per caller. +__device__ float block_sumf(float v, double* scratch_raw) { + float* scratch = (float*) scratch_raw; + // The leading barrier is not decoration - see the note on `block_sum` above: the result is read straight out + // of `scratch[0]` by every thread and a later call reuses the array, so without it a fast thread can + // overwrite `scratch[0]` before a slow one has read the previous result. + __syncthreads(); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_sumf(v); + if (lane == 0) scratch[warp] = v; + __syncthreads(); + const int nw = ((int) blockDim.x + 31) >> 5; + v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0f; + if (warp == 0) v = warp_sumf(v); + if (threadIdx.x == 0) scratch[0] = v; + __syncthreads(); + return scratch[0]; +} + +/// Block-wide sum in DOUBLE, broadcast to every thread. +/// +/// Double because `ref/gr.py` reduces in float64 for the norm and the bottleneck, and because a block-wide +/// f32 sum of 2560 squares is a different number from the reference's; the shuffle tree here also reorders +/// the additions, so the only defence is enough precision that the order stops mattering. +/// +/// The leading `__syncthreads()` is not decoration: the result is read straight out of `scratch[0]` by every +/// thread, and a later call reuses the same array. Without a barrier on entry a fast thread can overwrite +/// `scratch[0]` before a slow one has read the previous result - a race that is invisible in most runs. +__device__ double block_sum(double v, double* scratch) { + __syncthreads(); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[warp] = v; + __syncthreads(); + const int nw = ((int) blockDim.x + 31) >> 5; + v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; + if (warp == 0) v = warp_sum(v); + if (threadIdx.x == 0) scratch[0] = v; + __syncthreads(); + return scratch[0]; +} + +/// `hc` blocks, one per residual stream: per-stream RMSNorm, then the activated stream in both forms. +/// +/// ggml_rms_norm reduces over ne[0], and ne[0] is n_embd, so the reduction is PER STREAM. The `[n_embd, hc]` +/// gamma then scales each stream individually. +/// +/// A per-thread accumulator is only a sum when the block is narrower than the row, which is why this is a +/// block reduction: with `n_embd` equal to the thread count every thread would hold exactly one element and +/// normalise by its own square. That mistake is silent - it produces a plausible vector of the right shape - +/// and it is what `gr_parity`'s `mixed vs reference` caught at 2.0e+01 in round 196. +template +__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w_norm, float eps, + int n_embd, float* __restrict__ xn, uint16_t* __restrict__ xq) { + __shared__ double scratch[8]; + const int c = blockIdx.x; + const float* Rc = R + (size_t) c * n_embd; + float* xnc = xn + (size_t) c * n_embd; + uint16_t* xqc = xq + (size_t) c * n_embd; + + // FP32, for the same reason as `gr_down_kernel` and `gr_inject_kernel`: this is a GeForce part, FP64 runs + // at a small fraction of FP32, and the sum of squares is a pure reduction. It was the last `double` on the + // `gr_read` path. `gr_norm` is only 0.80 ms/token, so this is hygiene rather than a headline - but it is + // 12 of the FP64 sites the review's G5 counted in this file, and the rule it states ("no FP64 on any decode + // or prefill path") is worth being able to check mechanically rather than case by case. + float ss = 0.0f; + for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { + const float v = Rc[d]; + ss += v * v; + } + const float ms = block_sumf(ss, scratch) / (float) n_embd; + const float rs = rsqrtf(ms + eps); + for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { + const float x = Rc[d] * rs * w_norm[(size_t) c * n_embd + d]; + xnc[d] = x; + if constexpr (!FP32_ACT) xqc[d] = f32_to_bf16_bits(x); + } +} + +/// `lo = silu((bf16(xn) @ w_down.T) / hc)`, ONE BLOCK PER OUTPUT ROW with its warps splitting the reduction. +template +__global__ void gr_down_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_down, int hc_dim, + int hc_lr, int hc, Activation* __restrict__ lq) { + const int k = blockIdx.x; + if (k >= hc_lr) return; + const int lane = threadIdx.x & 31; + const int warp = threadIdx.x >> 5; + const int nw = (int) (blockDim.x >> 5); // warps per row == warps per block + const uint16_t* row = w_down + (size_t) k * hc_dim; + // **THE OCCUPANCY HERE IS 10% AND IT IS REAL, BUT FIXING IT DOES NOT PAY.** `hc_lr` is 320, one warp per + // row, 8 warps per block, so this launches 40 blocks = 320 warps: **6.7 warps per SM out of the 64 a + // Blackwell SM holds**, each lane walking 10,240 elements in 320 dependent steps. + // + // Four independent accumulators were tried to break the dependency chain and put four loads in flight per + // lane. **Measured: 39.86 ms/token of pure GPU against 39.80, i.e. no change**, with `gr_parity` green + // either way. Removed, on the rule this file already states about `#pragma unroll 4`: a hint that does not + // change the timing is a claim that is not true. + // + // The reason is that `gr_read`'s cost is not here. Its four kernels are the norm (4 blocks), this (40), + // `gr_gate_kernel` (1,280) and the mean (10), and the 1,280-block gate kernel reads 6.55 MB of weights with + // good occupancy - so `gr_read`'s ~93 us is mostly the gate kernel at its own memory rate, and the ~165 GB/s + // whole-call figure is an average over kernels that do not share a rate. + // **FP32, AND THE FP64 THAT WAS HERE COST MORE THAN EVERYTHING ELSE IN `gr_read`.** + // + // This accumulated in `double`. GeForce Blackwell executes FP64 at a small fraction of FP32 - 1/64 on + // recent parts - so a 320-step dependent FP64 chain per lane turned a memory-bound reduction into a + // latency-bound one. The `nsys` per-kernel table (round 2) measured it at **5.07 ms/token, 15.3% of all + // GPU time**, against `gr_gate_kernel`'s 1.23 ms - which REFUTES the comment that used to sit here, that + // "gr_read's ~93 us is mostly the gate kernel at its own memory rate". It was not: down + inject were + // 8.77 of gr_read's 10.8 ms, and the gate was 1.23. + // + // The justification for `double` was matching `ref/gr.py`'s float64 transcription. **The ground truth is + // llama.cpp, and llama.cpp accumulates in FP32** - so this does not move away from the oracle, it moves + // toward it, and the review's G1 lists it first. + // + // Four independent accumulators were tried here BEFORE, against the FP64 version, and measured no change + // (39.86 vs 39.80 ms/token) - because FP64 throughput was the limit, not the dependency chain. With FP32 + // the kernel becomes memory-bound: it reads ~13 MB per call across xq and w_down, which at the measured + // 641 GB/s is ~20 us against the 52 us this took. + // **THE OCCUPANCY CONCLUSION ABOVE IS STALE, AND THIS IS THE RETEST IT ASKED FOR.** + // + // "Fixing it does not pay" was measured against the FP64 version, where FP64 THROUGHPUT was the limit and + // more parallelism could not help. The kernel is FP32 now (round 282: 5.07 -> 2.38 ms/token) and the limit + // moved to memory - which is the regime where occupancy does pay, because at 6.7 warps/SM there are not + // enough bytes in flight to cover DRAM latency. The old result is not wrong; it is about a different kernel. + // + // One BLOCK per row, its 8 warps splitting the 10,240-element reduction: 320 blocks x 8 = **2,560 warps = + // 53 warps/SM instead of 6.7**, with no second kernel and no partial buffer - the eight partials meet in + // shared memory. Lanes within a warp still read consecutive addresses, because warp `w` starts at + // `w * 32` and strides by `nw * 32`. + float acc = 0.0f; + for (int i = warp * 32 + lane; i < hc_dim; i += nw * 32) + acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]); + acc = warp_sumf(acc); + + __shared__ float part[WARPS]; + if (lane == 0) part[warp] = acc; + __syncthreads(); + if (warp == 0) { + float t = (lane < nw) ? part[lane] : 0.0f; + t = warp_sumf(t); + // NOTE: the reduction order differs from the one-warp version, so this is a NUMERICS CHANGE. C1 is the + // gate that judges it - not this comment, and not `gr_parity`, which compares against the reference on + // a fixture that a changed summation order can still pass. + if (lane == 0) store_activation(lq, k, silu_f(t / (float) hc)); + } +} + +/// `gated[i] = xn[i] * sigmoid(bf16(lo) @ w_up.T)`, one warp per output row, lanes striding hc_lr. +template +__global__ void gr_gate_kernel(const Activation* __restrict__ lq, const uint16_t* __restrict__ w_up, + const float* __restrict__ xn, int hc_dim, int hc_lr, float* __restrict__ gated) { + const int i = blockIdx.x * WARPS + (threadIdx.x >> 5); + if (i >= hc_dim) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w_up + (size_t) i * hc_lr; + float acc = 0.0f; + for (int k = lane; k < hc_lr; k += 32) + acc += activation_f32(lq[k]) * bf16_bits_to_f32(row[k]); + acc = warp_sumf(acc); + // Every lane computes the sigmoid (the shuffle broadcasts acc), so there is no second sync point and no + // branch; lane 0 stores. + if (lane == 0) gated[i] = xn[i] * sigmoid_f(acc); +} + +/// `mixed[d] = mean over c of gated[c][d]`. Flat elementwise: the mean is over the streams, which are +/// strided by n_embd, so no cross-thread reduction is needed at all. +__global__ void gr_mean_kernel(const float* __restrict__ gated, int n_embd, int hc, float* __restrict__ mixed) { + const int d = blockIdx.x * blockDim.x + threadIdx.x; + if (d >= n_embd) return; + float m = 0.0f; + for (int c = 0; c < hc; ++c) m += gated[(size_t) c * n_embd + d]; + mixed[d] = m / (float) hc; +} + +/// `inject[c] = bf16(xn) @ w_inject[c]`, one value per stream: ONE WARP PER STREAM, lanes striding hc_dim. +/// +/// This mirrors `gr_down_kernel` rather than using a block-wide reduction. `hc` is 4 at the real geometry, +/// so a block per stream would put 256 threads on a 10240-element dot and leave the reduction to do all the +/// work; a warp per stream is the same shape as the down projection and reuses its pattern exactly. The +/// whole kernel is one block of `32*hc` threads, which is small - and it is a 4-value output, so it is. +template +__global__ void gr_inject_kernel(const Activation* __restrict__ xq, const uint16_t* __restrict__ w_inject, + int hc_dim, int hc, float* __restrict__ inject) { + const int c = threadIdx.x >> 5; + if (c >= hc) return; + const int lane = threadIdx.x & 31; + const uint16_t* row = w_inject + (size_t) c * hc_dim; + // FP32, for the same reason as `gr_down_kernel` - and this one is worse. A ONE-BLOCK kernel doing four + // 10,240-element FP64 reductions measured **3.70 ms/token, 11.1% of all GPU time, from a single SM out of + // 48.** It is the fourth largest consumer of GPU time in the engine and it cannot use more than 1/48th of + // the machine. In FP32 the same reduction is a few microseconds and the block size stops mattering. + float acc = 0.0f; + for (int i = lane; i < hc_dim; i += 32) + acc += activation_f32(xq[i]) * bf16_bits_to_f32(row[i]); + acc = warp_sumf(acc); + if (lane == 0) inject[c] = acc; +} + +__global__ void gr_write_kernel(const float* __restrict__ R, const float* __restrict__ block_out, + const float* __restrict__ inject, int n_embd, int hc, float* __restrict__ out) { + // w = 2*sigmoid(inject/hc), computed once per stream in shared rather than per element. + extern __shared__ unsigned char smem_raw[]; + float* w = (float*) smem_raw; + if ((int) threadIdx.x < hc) w[threadIdx.x] = 2.0f * sigmoid_f(inject[threadIdx.x] / (float) hc); + __syncthreads(); + const long long n = (long long) hc * n_embd; + for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n; + i += (long long) gridDim.x * blockDim.x) { + const int c = (int) (i / n_embd), d = (int) (i % n_embd); + // every stream adds the SAME block output; only the weight differs per stream + out[i] = R[i] + block_out[d] * w[c]; + } +} + +} // namespace + +void gr_set_fp32_activations(bool enabled) { fp32_activations = enabled; } +void gr_set_native_mmvf(bool enabled) { native_mmvf = enabled; } + +size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out) { + const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd; + // ONE table, indexed by the same `k` that assigns the pointers below. The first version of this function + // sized three locals named `xn`, `xq`, `lq` in a DIFFERENT order from the pointer assignments - `xq` got + // hc_lr*2 while `lq` got hc_dim*4 - so for the real geometry xq was given 640 bytes where it needed + // 20,480 and every region overlapped its neighbour. + // + // What that looked like is worth recording: `inject` came out ~20% wrong, and rewriting its reduction + // from block-wide to warp-wide produced BYTE-IDENTICAL wrong answers. Two different reductions agreeing + // exactly is not a coincidence to investigate - it means the reduction is not where the bug is, and the + // inputs are. Chasing the reduction instead cost most of a round. + const size_t sz[5] = { + hc_dim * sizeof(float), // 0: xn + hc_dim * sizeof(uint16_t), // 1: xq + (size_t) s.hc_lr * sizeof(uint16_t), // 2: lq + hc_dim * sizeof(float), // 3: gated + (size_t) s.hc_lr * sizeof(float), // 4: lo (FP32 activation experiment) + }; + size_t al[5], bytes = 0; + for (int k = 0; k < 5; ++k) { + al[k] = (sz[k] + 15) & ~(size_t) 15; + bytes += al[k]; + } + out.bytes = bytes; + if (base != nullptr) { + unsigned char* p = (unsigned char*) base; + void* ptr[5]; + for (int k = 0; k < 5; ++k) { + ptr[k] = p; + p += al[k]; + } + out.xn = (float*) ptr[0]; + out.xq = (uint16_t*) ptr[1]; + out.lq = (uint16_t*) ptr[2]; + out.gated = (float*) ptr[3]; + out.lo = (float*) ptr[4]; + } + return bytes; +} + +void gr_read(const float* R, const float* w_norm, const uint16_t* w_down, const uint16_t* w_up, + const uint16_t* w_inject, float eps, const GrShapes& s, const GrWorkspace& ws, float* mixed, + float* inject, void* stream) { + if (s.n_embd <= 0 || s.hc <= 0 || s.hc_lr <= 0) return; + if (ws.xn == nullptr || ws.xq == nullptr || ws.lq == nullptr || ws.gated == nullptr || ws.lo == nullptr) { + std::fprintf(stderr, "gr_read: GrWorkspace is not initialised (see gr_workspace_init)\n"); + std::exit(1); + } + if (ws.bytes < gr_workspace_bytes(s)) { + std::fprintf(stderr, "gr_read: GrWorkspace is %zu bytes but this geometry needs %zu\n", + ws.bytes, gr_workspace_bytes(s)); + std::exit(1); + } + const int n_embd = (int) s.n_embd, hc = (int) s.hc, hc_lr = (int) s.hc_lr; + const int hc_dim = (int) (s.hc * s.n_embd); + cudaStream_t st = (cudaStream_t) stream; + + // One setting selects every projection in this call. Captured graphs retain these kernel variants. + const bool use_native = native_mmvf; + const bool use_fp32 = fp32_activations || use_native; + if (use_native) { + if ((hc_dim & 1) != 0 || (hc_lr & 1) != 0) + throw std::invalid_argument("gr_read native MMVF requires even hc*n_embd and hc_lr"); + native_gr_rms_norm_weighted(R, w_norm, ws.xn, n_embd, hc, eps, stream); + bf16_gemv_fp32_mmvf(ws.xn, w_down, ws.lo, hc_dim, hc_lr, stream); + native_gr_down_silu(ws.lo, hc_lr, hc, stream); + bf16_gemv_fp32_mmvf(ws.lo, w_up, ws.gated, hc_lr, hc_dim, stream); + // The existing null-injection contract identifies the final mixer. + // Pinned qwen4exp uses fused HC pre for layers and the unfused graph for il=-1. + native_gr_pre_gated(ws.xn, ws.gated, mixed, n_embd, hc, w_inject != nullptr, stream); + } else if (use_fp32) { + gr_norm_kernel<<>>(R, w_norm, eps, n_embd, ws.xn, ws.xq); + gr_down_kernel<<>>(ws.xn, w_down, hc_dim, hc_lr, hc, ws.lo); + gr_gate_kernel<<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>( + ws.lo, w_up, ws.xn, hc_dim, hc_lr, ws.gated); + } else { + gr_norm_kernel<<>>(R, w_norm, eps, n_embd, ws.xn, ws.xq); + gr_down_kernel<<>>(ws.xq, w_down, hc_dim, hc_lr, hc, ws.lq); + gr_gate_kernel<<<(hc_dim + WARPS - 1) / WARPS, THREADS, 0, st>>>( + ws.lq, w_up, ws.xn, hc_dim, hc_lr, ws.gated); + } + if (!use_native) + gr_mean_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(ws.gated, n_embd, hc, mixed); + // Absent for the final mixer, and then nothing is written - computing an injection nobody reads would be + // a claim, not a convenience. + if (w_inject != nullptr) { + const int nthreads = 32 * hc; + if (use_native) + bf16_gemv_fp32_mmvf(ws.xn, w_inject, inject, hc_dim, hc, stream); + else if (use_fp32) + gr_inject_kernel<<<1, nthreads, 0, st>>>(ws.xn, w_inject, hc_dim, hc, inject); + else + gr_inject_kernel<<<1, nthreads, 0, st>>>(ws.xq, w_inject, hc_dim, hc, inject); + } + + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gr_read launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) { + const cudaError_t se = cudaDeviceSynchronize(); + if (se != cudaSuccess) { + std::fprintf(stderr, "gr_read: %s\n", cudaGetErrorString(se)); + std::exit(1); + } + } +} + +void gr_write(const float* R, const float* block_out, const float* inject, const GrShapes& s, float* R_out, + void* stream) { + if (s.n_embd <= 0 || s.hc <= 0) return; + const long long n = (long long) s.hc * s.n_embd; + const int blocks = (int) ((n + THREADS - 1) / THREADS); + if (native_mmvf) + native_gr_post(R, block_out, inject, R_out, (int) s.n_embd, (int) s.hc, stream); + else + gr_write_kernel<<>>( + R, block_out, inject, (int) s.n_embd, (int) s.hc, R_out); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "gr_write: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/iq_kernels.cu b/engine/strata/src/kernels/cuda/iq_kernels.cu new file mode 100644 index 00000000..3081c82c --- /dev/null +++ b/engine/strata/src/kernels/cuda/iq_kernels.cu @@ -0,0 +1,1474 @@ +// src/kernels/cuda/iq_kernels.cu - see include/strata/kernels/iq_kernels.hpp. +// +// The dot products (vec_dot_*_q8_1), the dequantizers and the q8_1 quantizer are transcribed from llama.cpp +// (ggml/src/ggml-cuda/vecdotq.cuh, dequantize.cuh, quantize.cu at the commit in third_party/ggml/VERSION.txt; +// MIT license, third_party/ggml/LICENSE). The block structs and codebook grids come from its ggml-common.h, +// included unchanged. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/dp4a.hpp" + +#include +#include + +#define GGML_COMMON_DECL_CUDA +#define GGML_COMMON_IMPL_CUDA +#include "ggml-common.h" + +#include +#include + +namespace strata::kernels { +namespace { + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } +} + +// ---------------------------------------------------------------- llama.cpp helpers (vecdotq.cuh) +__device__ __forceinline__ int get_int_b2(const void* x, const int& i32) { + const uint16_t* x16 = (const uint16_t*) x; + int x32 = x16[2 * i32 + 0] << 0; + x32 |= x16[2 * i32 + 1] << 16; + return x32; +} +__device__ __forceinline__ int get_int_b4(const void* x, const int& i32) { return ((const int*) x)[i32]; } +__device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) { + const uint32_t p = __popc(v) & 1; + const uint32_t s = v ^ p << 7; + return s * 0x01010101; +} +__device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) { + const uint32_t* table32 = (const uint32_t*) table; + uint32_t tmp[2]; + const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1)); +#pragma unroll + for (uint32_t i = 0; i < 2; ++i) { + const uint32_t shift = 16 * i; + const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift); + const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift); + tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); + } + return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); +} +#define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c)) + +// ---------------------------------------------------------------- the dot products (vecdotq.cuh) +__device__ __forceinline__ float vec_dot_q2_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; + const float d2 = bq2_0->d; + const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; + const block_q8_1* bq8_1_chunk = bq8_1 + iqs; + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); + const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); + const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0); + const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2); + const int qx = __byte_perm(qe, qo, 0x5140); + const int qy = __byte_perm(qe, qo, 0x7362); + sumi = ggml_cuda_dp4a(u, qx, sumi); + sumi = ggml_cuda_dp4a(v, qy, sumi); + } + const float d8 = __low2float(bq8_1_chunk->ds); + return d2 * d8 * sumi; +} + +__device__ __forceinline__ float vec_dot_iq2_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx; + const int q2 = get_int_b2(bq2->qs, iqs); + const uint8_t* aux8 = (const uint8_t*) &q2; + const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1); + int sumi = 0; +#pragma unroll + for (int k0 = 0; k0 < 8; k0 += 2) { + const uint2 grid_pos = ((const uint2*) iq2xxs_grid)[aux8[k0 / 2]]; + const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + const int grid0 = __vsub4(grid_pos.x ^ signs0, signs0); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0); + sumi = ggml_cuda_dp4a(grid0, u0, sumi); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + const int grid1 = __vsub4(grid_pos.y ^ signs1, signs1); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1); + sumi = ggml_cuda_dp4a(grid1, u1, sumi); + } + const int ls = aux32 >> 27 | 1; + sumi = sumi * ls / 8; + const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} + +__device__ __forceinline__ float vec_dot_iq2_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx; + const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1)); + const uint16_t* q2 = (const uint16_t*) &q2_packed; + const int ls0 = bq2->scales[iqs / 2] & 0x0F; + const int ls1 = bq2->scales[iqs / 2] >> 4; + int sumi0 = 0, sumi1 = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const uint2 grid_pos = ((const uint2*) iq2xs_grid)[q2[l0 / 2] & 0x1FF]; + const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + if (l0 < 4) { + sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); + sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0); + } else { + sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1); + sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1); + } + } + const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} + +__device__ __forceinline__ float vec_dot_iq2_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; + const int qs_packed = get_int_b2(bq2->qs, iqs / 2); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq2->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + const int ls0 = bq2->scales[iqs / 2] & 0x0F; + const int ls1 = bq2->scales[iqs / 2] >> 4; + int sumi0 = 0, sumi1 = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0); + const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + if (l0 < 4) { + sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); + sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0); + } else { + sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1); + sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1); + } + } + const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} + +__device__ __forceinline__ float vec_dot_iq3_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; + const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* q3 = (const uint8_t*) &q3_packed; + const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); + const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + sumi = ggml_cuda_dp4a(grid_l, u0, sumi); + sumi = ggml_cuda_dp4a(grid_h, u1, sumi); + } + const int ls = aux32 >> 28; + sumi = (ls * sumi + sumi / 2) / 2; + const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} + +__device__ __forceinline__ float vec_dot_iq3_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq3->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); + const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + sumi = ggml_cuda_dp4a(grid_l, u0, sumi); + sumi = ggml_cuda_dp4a(grid_h, u1, sumi); + } + sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); + const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} + +__device__ __forceinline__ float vec_dot_iq1_m_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx; + const int qs_packed = get_int_b4(bq1->qs, iqs); + const uint8_t* qs = (const uint8_t*) &qs_packed; + int sumi[2] = {0, 0}; + float sumf[2] = {0.0f, 0.0f}; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2)); + const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)]; + const int grid0 = (grid >> 0) & 0x0F0F0F0F; + const int grid1 = (grid >> 4) & 0x0F0F0F0F; + const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); + sumi[l0 / 4] = ggml_cuda_dp4a(grid0, u0, sumi[l0 / 4]); + sumi[l0 / 4] = ggml_cuda_dp4a(grid1, u1, sumi[l0 / 4]); + const float delta = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08); + int sumy = 0; + sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy); + sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy); + sumf[l0 / 4] += delta * sumy; + } + const uint16_t* sc = (const uint16_t*) bq1->scales; + iq1m_scale_t scale; + scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000); + const float d = __half2float(scale.f16) * __low2float(bq8_1[iqs].ds); + const int tmp = sc[iqs / 2] >> (6 * (iqs % 2)); + const int sc0 = 2 * ((tmp >> 0) & 0x07) + 1; + const int sc1 = 2 * ((tmp >> 3) & 0x07) + 1; + return d * ((sumi[0] + sumf[0]) * sc0 + (sumi[1] + sumf[1]) * sc1); +} + +__device__ __forceinline__ float vec_dot_iq4_nl_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + const int* q8 = (const int*) bq8_1->qs + iqs; + int sumi = 0; +#pragma unroll + for (int l = 0; l < 2; ++l) { + const int aux_q4 = get_int_b2(bq4->qs, iqs + l); + const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl); + sumi = ggml_cuda_dp4a(v.x, q8[l + 0], sumi); + sumi = ggml_cuda_dp4a(v.y, q8[l + 4], sumi); + } + const float d = __half2float(bq4->d) * __low2float(bq8_1->ds); + return d * sumi; +} + +// IQ4_XS: 256 values as 8 sub-blocks of 32 (6-bit scale each); one call covers one sub-block (iqs = 4 * sub-block), +// and `bq8_1` is the super-block's first q8_1 block, so the call's activation is bq8_1[iqs / 4]. The GSQ-RCO IQ3_S +// file keeps one layer's routed gate/up experts in this format. +__device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx; + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int aux_q4 = get_int_b4(bq4->qs, iqs + j); + const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl); + const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0); + const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4); + sumi = ggml_cuda_dp4a(v.x, u0, sumi); + sumi = ggml_cuda_dp4a(v.y, u1, sumi); + } + const int ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4); + sumi *= ls - 32; + const float d = __half2float(bq4->d) * __low2float(bq8_1[iqs / 4].ds); + return d * sumi; +} + +// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts +// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the +// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0, +// gopinath87607), which agree with llama.cpp and with each other. +constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q8_0 = 2; + +__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u, + const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, + const half2& dm4, const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F; + const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F; + const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0)); + const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); // the min times the sum of the QUANTIZED activations + } + const float2 dm4f = __half22float2(dm4); + return dm4f.x * sumf_d - dm4f.y * sumf_m; +} +__device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq(const int* __restrict__ vl, const int* __restrict__ vh, + const int* __restrict__ u, const uint8_t* __restrict__ sc, + const uint8_t* __restrict__ m, const half2& dm5, + const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F; + const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F; + const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; + const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; + const int v0i = vl0i | vh0i; + const int v1i = vl1i | vh1i; + const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0)); + const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); + } + const float2 dm5f = __half22float2(dm5); + return dm5f.x * sumf_d - dm5f.y * sumf_m; +} +// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K) +__device__ __forceinline__ void k_scale_min(const uint8_t* scales8, int bq8_offset, uint16_t aux[2]) { + const uint16_t* scales = (const uint16_t*) scales8; + const int j = bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm + 0]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = (uint32_t) -(int32_t) (j >= 2); + aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); +} +__device__ __forceinline__ float vec_dot_q4_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx; + int v[2]; + int u[2 * QR4_K]; + float d8[QR4_K]; + const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2)); + const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + v[0] = q4[0]; + v[1] = q4[4]; + uint16_t aux[2]; + k_scale_min(bq4_K->scales, bq8_offset, aux); + const uint8_t* sc = (const uint8_t*) aux; + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < QR4_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8); +} +__device__ __forceinline__ float vec_dot_q5_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx; + int vl[2]; + int vh[2]; + int u[2 * QR5_K]; + float d8[QR5_K]; + const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2)); + const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4)); + vl[0] = ql[0]; + vl[1] = ql[4]; + vh[0] = qh[0] >> bq8_offset; + vh[1] = qh[4] >> bq8_offset; + uint16_t aux[2]; + k_scale_min(bq5_K->scales, bq8_offset, aux); + const uint8_t* sc = (const uint8_t*) aux; + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < QR5_K; ++i) { + const block_q8_1* bq8i = bq8_1 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4); + u[2 * i + 0] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8); +} +// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with +// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum +// of the ORIGINAL activations. That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant +// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2% +// against 1.9% relative error per expert). Result: sumi * (d5 * d8) + sumu * (m5 * d8). +__device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx; + int sumi = 0, sumu = 0; +#pragma unroll + for (int i = 0; i < VDR_Q5_1; ++i) { + const int vl = get_int_b4(bq5_1->qs, iqs + i); + const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i)); + const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1); + int vi0 = (vl >> 0) & 0x0F0F0F0F; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + sumi = ggml_cuda_dp4a(vi0, u0, sumi); + int vi1 = (vl >> 4) & 0x0F0F0F0F; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; + sumi = ggml_cuda_dp4a(vi1, u1, sumi); + sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu)); + } + const float2 dm5 = __half22float2(bq5_1->dm); + const float d8 = __low2float(bq8_1->ds); + return sumi * (dm5.x * d8) + sumu * (dm5.y * d8); +} +__device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx; + int sumi = 0; +#pragma unroll + for (int i = 0; i < VDR_Q8_0; ++i) + sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi); + const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds); + return d8_0 * d8_1 * ((float) sumi); +} + +// ---------------------------------------------------------------- the formats +// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls. +template struct Fmt; +template<> struct Fmt<16> { static constexpr int qk = 256, ipb = 8, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<17> { static constexpr int qk = 256, ipb = 8, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xs_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<18> { static constexpr int qk = 256, ipb = 8, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_xxs_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<20> { static constexpr int qk = 32, ipb = 2, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_nl_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<21> { static constexpr int qk = 256, ipb = 8, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_s_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<23> { static constexpr int qk = 256, ipb = 8, step = 4; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<22> { static constexpr int qk = 256, ipb = 8, step = 2; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } }; + +// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every +// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(8) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(8) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(8) + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// One row against one q8_1 activation, the whole warp: call k = (block, part) is lane-strided. +template +__device__ __forceinline__ float row_dot(const uint8_t* row, const block_q8_1* x, int nb, int lane) { + using F = Fmt; + float s = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs); + } + return warp_sum(s); +} + +template +__global__ void __launch_bounds__(128) mmvq_kernel(const uint8_t* __restrict__ w, size_t row_bytes, + const block_q8_1* __restrict__ x, float* __restrict__ y, int n_in, + int n_out, int ncols) { + const int row = blockIdx.x * 4 + threadIdx.y; + if (row >= n_out) return; + const int lane = threadIdx.x; + const int nb = n_in / Fmt::qk; + const uint8_t* wr = w + (size_t) row * row_bytes; + for (int c = 0; c < ncols; ++c) { + const float s = row_dot(wr, x + (size_t) c * (n_in / 32), nb, lane); + if (lane == 0) y[(size_t) c * n_out + row] = s; + } +} + +// ---------------------------------------------------------------- decode once, apply to every column +// The kernels above call Fmt::dot once per (call, column): each column re-reads the weight words and redoes +// the grid lookups and sign unpacking. Here each dot is split, as native_mmvq.cu's multi-column traits are, into +// `load` (everything that depends only on the weight: the signed grid words, the integer scales, the fp16 block +// scale as a float) and `apply` (the activation loads, the dp4a chain in the same order, the same integer scale +// step and the same float expression). `apply(load(...))` does the dot's integer and float operations in the same +// order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel / +// native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels). +template struct Split; +// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the +// per-entry ones, which call Fmt::dot per column exactly as before #242 (the launchers test kSplit at compile +// time, so the multi kernels are never instantiated for a type without a Split). +template inline constexpr bool kSplit = false; +template<> inline constexpr bool kSplit<16> = true; +template<> struct Split<16> { // IQ2_XXS + struct W { int g[8]; int ls; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx; + const int q2 = get_int_b2(bq2->qs, iqs); + const uint8_t* aux8 = (const uint8_t*) &q2; + const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1); + W r; +#pragma unroll + for (int k0 = 0; k0 < 8; k0 += 2) { + const uint2 grid_pos = ((const uint2*) iq2xxs_grid)[aux8[k0 / 2]]; + const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + r.g[k0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + r.g[k0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = aux32 >> 27 | 1; + r.dw = __half2float(bq2->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); + sumi = sumi * r.ls / 8; + const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; + } +}; +// IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales +struct SplitLs2 { + struct W { int g[8]; int ls0, ls1; float dw; }; + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi0 = 0, sumi1 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi0); +#pragma unroll + for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi1); + const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; + } +}; +template<> inline constexpr bool kSplit<17> = true; +template<> struct Split<17> : SplitLs2 { // IQ2_XS + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx; + const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1)); + const uint16_t* q2 = (const uint16_t*) &q2_packed; + W r; + r.ls0 = bq2->scales[iqs / 2] & 0x0F; + r.ls1 = bq2->scales[iqs / 2] >> 4; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const uint2 grid_pos = ((const uint2*) iq2xs_grid)[q2[l0 / 2] & 0x1FF]; + const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.dw = __half2float(bq2->d); + return r; + } +}; +template<> inline constexpr bool kSplit<22> = true; +template<> struct Split<22> : SplitLs2 { // IQ2_S + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; + const int qs_packed = get_int_b2(bq2->qs, iqs / 2); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq2->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; + r.ls0 = bq2->scales[iqs / 2] & 0x0F; + r.ls1 = bq2->scales[iqs / 2] >> 4; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos[0] ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos[1] ^ signs1, signs1); + } + r.dw = __half2float(bq2->d); + return r; + } +}; +template<> inline constexpr bool kSplit<18> = true; +template<> struct Split<18> { // IQ3_XXS + struct W { int g[8]; int ls; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; + const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* q3 = (const uint8_t*) &q3_packed; + const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); + const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = aux32 >> 28; + r.dw = __half2float(bq3->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); + sumi = (r.ls * sumi + sumi / 2) / 2; + const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; + } +}; +template<> inline constexpr bool kSplit<21> = true; +template<> struct Split<21> { // IQ3_S + struct W { int g[8]; int ls; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq3->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0); + r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1); + } + r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); + r.dw = __half2float(bq3->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi); + sumi *= r.ls; + const float d = r.dw * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; + } +}; +template<> inline constexpr bool kSplit<29> = true; +template<> struct Split<29> { // IQ1_M + struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx; + const int qs_packed = get_int_b4(bq1->qs, iqs); + const uint8_t* qs = (const uint8_t*) &qs_packed; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2)); + const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)]; + r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F; + r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F; + r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08); + } + const uint16_t* sc = (const uint16_t*) bq1->scales; + iq1m_scale_t scale; + scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000); + r.dw = __half2float(scale.f16); + const int tmp = sc[iqs / 2] >> (6 * (iqs % 2)); + r.sc0 = 2 * ((tmp >> 0) & 0x07) + 1; + r.sc1 = 2 * ((tmp >> 3) & 0x07) + 1; + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi[2] = {0, 0}; + float sumf[2] = {0.0f, 0.0f}; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); + sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi[l0 / 4]); + sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi[l0 / 4]); + int sumy = 0; + sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy); + sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy); + sumf[l0 / 4] += r.delta[l0 / 2] * sumy; + } + const float d = r.dw * __low2float(bq8_1[iqs].ds); + return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1); + } +}; +template<> inline constexpr bool kSplit<20> = true; +template<> struct Split<20> { // IQ4_NL + struct W { int2 v[2]; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx; + W r; +#pragma unroll + for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(get_int_b2(bq4->qs, iqs + l), kvalues_iq4nl); + r.dw = __half2float(bq4->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const int* q8 = (const int*) bq8_1->qs + iqs; + int sumi = 0; +#pragma unroll + for (int l = 0; l < 2; ++l) { + sumi = ggml_cuda_dp4a(r.v[l].x, q8[l + 0], sumi); + sumi = ggml_cuda_dp4a(r.v[l].y, q8[l + 4], sumi); + } + const float d = r.dw * __low2float(bq8_1->ds); + return d * sumi; + } +}; +template<> inline constexpr bool kSplit<23> = true; +template<> struct Split<23> { // IQ4_XS + struct W { int2 v[4]; int ls; float dw; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx; + W r; +#pragma unroll + for (int j = 0; j < 4; ++j) r.v[j] = get_int_from_table_16(get_int_b4(bq4->qs, iqs + j), kvalues_iq4nl); + r.ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4); + r.dw = __half2float(bq4->d); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0); + const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4); + sumi = ggml_cuda_dp4a(r.v[j].x, u0, sumi); + sumi = ggml_cuda_dp4a(r.v[j].y, u1, sumi); + } + sumi *= r.ls - 32; + const float d = r.dw * __low2float(bq8_1[iqs / 4].ds); + return d * sumi; + } +}; +template<> inline constexpr bool kSplit<42> = true; +template<> struct Split<42> { // Q2_0 + struct W { int qx[4], qy[4]; float d2; }; + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) { + const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx; + W r; + r.d2 = bq2_0->d; + const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0); + const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2); + r.qx[j] = __byte_perm(qe, qo, 0x5140); + r.qy[j] = __byte_perm(qe, qo, 0x7362); + } + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + const block_q8_1* bq8_1_chunk = bq8_1 + iqs; + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0); + const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1); + sumi = ggml_cuda_dp4a(u, r.qx[j], sumi); + sumi = ggml_cuda_dp4a(v, r.qy[j], sumi); + } + const float d8 = __low2float(bq8_1_chunk->ds); + return r.d2 * d8 * sumi; + } +}; + +// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to +// spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way, +// summed in the same order, then the same warp_sum. Only the weight side moves out of the per-activation loop. +template +__device__ __forceinline__ void row_dot_multi(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, + int nb, int lane, float (&s)[NC]) { + using F = Fmt; + using S = Split; +#pragma unroll + for (int c = 0; c < NC; ++c) s[c] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + const typename S::W w = S::load(row, kbx, iqs); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs); + } +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < n) s[c] = warp_sum(s[c]); +} + +// mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores +// column c. +template +__global__ void __launch_bounds__(128) mmvq_multi_kernel(const uint8_t* __restrict__ w, size_t row_bytes, + const block_q8_1* __restrict__ x, float* __restrict__ y, + int n_in, int n_out, int ncols) { + const int row = blockIdx.x * 4 + threadIdx.y; + if (row >= n_out) return; + const int lane = threadIdx.x; + const int nb = n_in / Fmt::qk, xb = n_in / 32; + const uint8_t* wr = w + (size_t) row * row_bytes; + for (int c0 = 0; c0 < ncols; c0 += NC) { + const int n = min(NC, ncols - c0); + int off[NC]; +#pragma unroll + for (int c = 0; c < NC; ++c) off[c] = (c0 + min(c, n - 1)) * xb; + float s[NC]; + row_dot_multi(wr, x, off, n, nb, lane, s); +#pragma unroll + for (int c = 0; c < NC; ++c) + if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c]; + } +} + +// ---------------------------------------------------------------- grouped native experts +constexpr int GU_ROWS = 8; // rows per block (one warp each) + +template +__global__ void __launch_bounds__(256) native_gu_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row = blockIdx.x * GU_ROWS + warp; // 0 .. 2*n_ff + if (row >= 2 * L.n_ff) return; + const bool is_up = row >= L.n_ff; + const int r = is_up ? row - (int) L.n_ff : row; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + (is_up ? L.up_off : 0) + (size_t) r * L.gu_row; + const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; ++e) { + const float s = row_dot(wr, xq + (size_t) ent_tok[e] * xb, nb, lane); + if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s; + } +} + +// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass. +// A group has at most one entry per token of the window (kVerifyMaxT = 8; setup writes --spec 4, and a split window +// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v). +constexpr int GRP_NC = 4; + +template +__global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row = blockIdx.x * GU_ROWS + warp; // 0 .. 2*n_ff + if (row >= 2 * L.n_ff) return; + const bool is_up = row >= L.n_ff; + const int r = is_up ? row - (int) L.n_ff : row; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + (is_up ? L.up_off : 0) + (size_t) r * L.gu_row; + const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + float* dst = is_up ? up : gate; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + int off[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + float s[GRP_NC]; + row_dot_multi(wr, xq, off, n, nb, lane, s); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c]; + } +} + +__global__ void swiglu_entries_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h, + long long n) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float g = gate[i]; + h[i] = (g / (1.0f + __expf(-g))) * up[i]; +} + +template +__global__ void __launch_bounds__(256) native_down_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r = blockIdx.x * 8 + warp; + if (r >= L.n_embd) return; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row; + const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; ++e) { + const float s = row_dot(wr, hq + (size_t) e * hb, nb, lane); + if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s; + } +} + +// native_down_kernel with the entries taken GRP_NC at a time +template +__global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r = blockIdx.x * 8 + warp; + if (r >= L.n_embd) return; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row; + const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + int off[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + float s[GRP_NC]; + row_dot_multi(wr, hq, off, n, nb, lane, s); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; + } +} + +// ---------------------------------------------------------------- q8_1 (quantize.cu) +__global__ void quantize_q8_1_kernel(const float* __restrict__ x, block_q8_1* __restrict__ y, long long n) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float xi = x[i]; + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + sum += __shfl_xor_sync(0xffffffffu, sum, o); + } + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + const long long ib = i / 32, iqs = i % 32; + y[ib].qs[iqs] = q; + if (iqs == 0) y[ib].ds = make_half2(d, sum); +} + +// ---------------------------------------------------------------- dequant (dequantize.cuh) +template __device__ __forceinline__ dst_t cvt(float v); +template<> __device__ __forceinline__ float cvt(float v) { return v; } +template<> __device__ __forceinline__ __half cvt<__half>(float v) { return __float2half(v); } + +template +__device__ void dq_iq2_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq2_xxs* x = (const block_iq2_xxs*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint16_t* q2 = x[ibs].qs + 4 * ib; + const uint8_t* aux8 = (const uint8_t*) q2; + const uint8_t* grid = (const uint8_t*) (iq2xxs_grid + aux8[il]); + const uint32_t aux32 = q2[2] | (q2[3] << 16); + const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f; + const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; + for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); +} +template +__device__ void dq_iq2_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq2_xs* x = (const block_iq2_xs*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint16_t* q2 = x[ibs].qs + 4 * ib; + const uint8_t* grid = (const uint8_t*) (iq2xs_grid + (q2[il] & 511)); + const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; + const uint8_t signs = ksigns_iq2xs[q2[il] >> 9]; + for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); +} +template +__device__ void dq_iq2_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq2_s* x = (const block_iq2_s*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint8_t* grid = (const uint8_t*) (iq2s_grid + (x[ibs].qs[4 * ib + il] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 0x300))); + const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; + const uint8_t signs = x[ibs].qs[QK_K / 8 + 4 * ib + il]; + for (int j = 0; j < 8; ++j) y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); +} +template +__device__ void dq_iq3_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq3_xxs* x = (const block_iq3_xxs*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint8_t* q3 = x[ibs].qs + 8 * ib; + const uint16_t* gas = (const uint16_t*) (x[ibs].qs + QK_K / 4) + 2 * ib; + const uint8_t* grid1 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 0]); + const uint8_t* grid2 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 1]); + const uint32_t aux32 = gas[0] | (gas[1] << 16); + const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.5f; + const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; + for (int j = 0; j < 4; ++j) { + y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); + y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); + } +} +template +__device__ void dq_iq3_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq3_s* x = (const block_iq3_s*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint8_t* qs = x[ibs].qs + 8 * ib; + const uint8_t* grid1 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 0] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 256))); + const uint8_t* grid2 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 1] | ((x[ibs].qh[ib] << (7 - 2 * il)) & 256))); + const float d = (float) x[ibs].d * (1 + 2 * ((x[ibs].scales[ib / 2] >> 4 * (ib % 2)) & 0xf)); + const uint8_t signs = x[ibs].signs[4 * ib + il]; + for (int j = 0; j < 4; ++j) { + y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); + y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); + } +} +template +__device__ void dq_iq1_m(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq1_m* x = (const block_iq1_m*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const uint16_t* sc = (const uint16_t*) x[ibs].scales; + iq1m_scale_t scale; + scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); + const int64_t ib16 = 2 * ib + il / 2; + const float d = (float) scale.f16 * (2 * ((sc[ib16 / 4] >> 3 * (ib16 % 4)) & 0x7) + 1); + const float delta = x[ibs].qh[2 * ib + il / 2] & (0x08 << 4 * (il % 2)) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA; + uint32_t grid32[2]; + const int8_t* q = (const int8_t*) grid32; + grid32[0] = iq1s_grid_gpu[x[ibs].qs[4 * ib + il] | (((x[ibs].qh[2 * ib + il / 2] >> 4 * (il % 2)) & 7) << 8)]; + grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f; + grid32[0] &= 0x0f0f0f0f; + for (int j = 0; j < 8; ++j) y[j] = cvt(d * (q[j] + delta)); +} +template +__device__ void dq_iq4_nl(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq4_nl* x = (const block_iq4_nl*) vx + ibs * (QK_K / QK4_NL); + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 4 * il; + const uint8_t* q4 = x[ib].qs + 4 * il; + const float d = (float) x[ib].d; + for (int j = 0; j < 4; ++j) { + y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); + y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); + } +} +// Q3_K (the Q2_0 file's token_embd): llama.cpp's dequantize_block_q3_K, its 64 threads folded onto 32 +template +__device__ void dq_q3_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q3_K* x = (const block_q3_K*) vx + ibs; + for (int tt = tid; tt < 64; tt += 32) { + const int r = tt / 4, t2 = r / 2, is0 = r % 2; + const int l0 = 16 * is0 + 4 * (tt % 4); + const int n = t2 / 4, j = t2 - 4 * n; + const uint8_t m = (uint8_t) (1 << (4 * n + j)); + const int is = 8 * n + 2 * j + is0; + const int shift = 2 * j; + const int8_t us = is < 4 ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 8] >> 0) & 3) << 4)) : + is < 8 ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 4] >> 2) & 3) << 4)) : + is < 12 ? (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is + 0] >> 4) & 3) << 4)) : + (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is - 4] >> 6) & 3) << 4)); + const float dl = (float) x->d * (us - 32); + dst_t* y = yy + 128 * n + 32 * j; + const uint8_t* q = x->qs + 32 * n; + const uint8_t* hm = x->hmask; + for (int l = l0; l < l0 + 4; ++l) y[l] = cvt(dl * ((int8_t) ((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4))); + } +} +template +__device__ void dq_iq4_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq4_xs* x = (const block_iq4_xs*) vx + ibs; + const int il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 4 * il; + const uint8_t* q4 = x->qs + 16 * ib + 4 * il; + const float d = (float) x->d * ((((x->scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) | (((x->scales_h >> 2 * ib) & 3) << 4)) - 32); + for (int j = 0; j < 4; ++j) { + y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); + y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); + } +} +template +__device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { + // one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values + const block_q2_0* x = (const block_q2_0*) vx + ibs * 4; + const int b = tid / 8, part = tid % 8; // block 0..3, 8 values each + const float d = (float) x[b].d; + for (int j = 0; j < 8; ++j) { + const int i = part * 8 + j; + const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3; + yy[b * 64 + i] = cvt(d * (float) (code - 1)); + } +} + +// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value +// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid % 8). +__device__ __forceinline__ void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { + if (j < 4) { + d = q[j] & 63; m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4); + } +} +template +__device__ void dq_q4_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q4_K* x = (const block_q4_K*) vx; + const int64_t il = tid / 8, ir = tid % 8, is = 2 * il; + const int n = 4; + dst_t* y = yy + 64 * il + n * ir; + const float dall = __low2half(x[ibs].dm); + const float dmin = __high2half(x[ibs].dm); + const uint8_t* q = x[ibs].qs + 32 * il + n * ir; + uint8_t sc, m; + get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m); + const float d1 = dall * sc, m1 = dmin * m; + get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m); + const float d2 = dall * sc, m2 = dmin * m; + for (int l = 0; l < n; ++l) { + y[l + 0] = cvt(d1 * (q[l] & 0xF) - m1); + y[l + 32] = cvt(d2 * (q[l] >> 4) - m2); + } +} +template +__device__ void dq_q5_k(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q5_K* x = (const block_q5_K*) vx; + for (int tt = tid; tt < 64; tt += 32) { + const int il = tt / 16, ir = tt % 16, is = 2 * il; + dst_t* y = yy + 64 * il + 2 * ir; + const float dall = __low2half(x[ibs].dm); + const float dmin = __high2half(x[ibs].dm); + const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir; + const uint8_t* qh = x[ibs].qh + 2 * ir; + uint8_t sc, m; + get_scale_min_k4(is + 0, x[ibs].scales, sc, m); + const float d1 = dall * sc, m1 = dmin * m; + get_scale_min_k4(is + 1, x[ibs].scales, sc, m); + const float d2 = dall * sc, m2 = dmin * m; + uint8_t hm = (uint8_t) (1 << (2 * il)); + y[0] = cvt(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1); + y[1] = cvt(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1); + hm <<= 1; + y[32] = cvt(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2); + y[33] = cvt(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2); + } +} +template +__device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1); + const int ib = tid % 8, il = tid / 8; + const float2 dm = __half22float2(x[ib].dm); + uint32_t qh; + memcpy(&qh, x[ib].qh, sizeof(qh)); + dst_t* y = yy + 32 * ib; + for (int j = 0; j < 4; ++j) { + const int iqs = 4 * il + j; // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16 + const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; + const int xh_1 = ((qh >> (iqs + 12))) & 0x10; + y[iqs] = cvt((float) ((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x + dm.y); + y[iqs + 16] = cvt((float) ((x[ib].qs[iqs] >> 4) | xh_1) * dm.x + dm.y); + } +} +template +__device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0); + const int ib = tid % 8, il = tid / 8; + const float d = __half2float(x[ib].d); + dst_t* y = yy + 32 * ib + 8 * il; + for (int j = 0; j < 8; ++j) y[j] = cvt((float) x[ib].qs[8 * il + j] * d); +} + +// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread. +template +__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8; + for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt(__uint_as_float((uint32_t) x[j] << 16)); +} + +// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others, +// so the default is unreachable. +template +__device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) { + switch (ty) { + case 16: dq_iq2_xxs(vx, ibs, y, tid); break; + case 17: dq_iq2_xs(vx, ibs, y, tid); break; + case 18: dq_iq3_xxs(vx, ibs, y, tid); break; + case 20: dq_iq4_nl(vx, ibs, y, tid); break; + case 21: dq_iq3_s(vx, ibs, y, tid); break; + case 22: dq_iq2_s(vx, ibs, y, tid); break; + case 29: dq_iq1_m(vx, ibs, y, tid); break; + case 23: dq_iq4_xs(vx, ibs, y, tid); break; + case 11: dq_q3_k(vx, ibs, y, tid); break; + case 42: dq_q2_0(vx, ibs, y, tid); break; + case 12: dq_q4_k(vx, ibs, y, tid); break; + case 13: dq_q5_k(vx, ibs, y, tid); break; + case 7: dq_q5_1(vx, ibs, y, tid); break; + case 8: dq_q8_0(vx, ibs, y, tid); break; + case 30: dq_bf16(vx, ibs, y, tid); break; + default: break; + } +} + +// flat: superblock i -> y + 256 i +template +__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y) { + const int64_t i = blockIdx.x; + dq_dispatch(ty, vx, i, y + i * QK_K, threadIdx.x); +} +// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity +__global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const void* __restrict__ up, int64_t per_row, + __half* __restrict__ y) { + const int64_t i = blockIdx.x; + const int parity = blockIdx.y; + const int64_t r = i / per_row, c = i % per_row; + dq_dispatch<__half>(ty, parity ? up : gate, i, y + ((2 * r + parity) * per_row + c) * QK_K, threadIdx.x); +} + +// the types dq_dispatch dequantizes +bool is_iq(int t) { + return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || + t == 12 || t == 13 || t == 7 || t == 8; +} +// values per block of the types the grouped expert kernels take (0 = none) +int gu_qk(int t) { + switch (t) { +#define STRATA_QK(T) case T: return Fmt::qk; + STRATA_GU_FMTS(STRATA_QK) +#undef STRATA_QK + default: return 0; + } +} +int d_qk(int t) { + switch (t) { +#define STRATA_QK(T) case T: return Fmt::qk; + STRATA_D_FMTS(STRATA_QK) +#undef STRATA_QK + default: return 0; + } +} + +bool env_on(const char* name) { + const char* v = std::getenv(name); + return v != nullptr && v[0] != '\0' && v[0] != '0'; +} +// STRATA_OLD_IQ_MMVQ=1 keeps the per-column kernels (bitwise equal to the new ones; kept for A/B timing) +bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ"); + +template +void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, int ncols, + cudaStream_t s) { + const dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4); + if constexpr (!kSplit) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else if (g_old_kernels) mmvq_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else if (ncols <= 1) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else if (ncols == 2) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else if (ncols <= 4) mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); + else mmvq_multi_kernel<<>>(W, rb, X, y, n_in, n_out, ncols); // 8 at a time past 8 +} + +template +void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L, + float* gate, float* up) { + if constexpr (!kSplit) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else if (g_old_kernels) native_gu_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); + else native_gu_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); +} + +template +void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L, + float* out) { + if constexpr (!kSplit) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else if (g_old_kernels) native_down_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_multi_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); +} + +} // namespace + +void iq_set_old_kernels(bool old) { g_old_kernels = old; } +bool iq_old_kernels() { return g_old_kernels; } + +bool iq_supported(int t) noexcept { return is_iq(t); } +bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } + +size_t iq_row_bytes(int t, int64_t n) noexcept { + switch (t) { + case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs); + case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs); + case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs); + case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl); + case 21: return (size_t) (n / 256) * sizeof(block_iq3_s); + case 22: return (size_t) (n / 256) * sizeof(block_iq2_s); + case 29: return (size_t) (n / 256) * sizeof(block_iq1_m); + case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs); + case 11: return (size_t) (n / 256) * sizeof(block_q3_K); + case 42: return (size_t) (n / 64) * sizeof(block_q2_0); + case 12: return (size_t) (n / 256) * sizeof(block_q4_K); + case 13: return (size_t) (n / 256) * sizeof(block_q5_K); + case 7: return (size_t) (n / 32) * sizeof(block_q5_1); + case 8: return (size_t) (n / 32) * sizeof(block_q8_0); + case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32) + default: return 0; + } +} + +void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) { + const long long n = (long long) n_rows * n_cols; + if (n <= 0) return; + quantize_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(x, (block_q8_1*) y, n); + check("quantize_q8_1_rows"); +} + +void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + const size_t rb = iq_row_bytes(t, n_in); + cudaStream_t s = (cudaStream_t) stream; + const auto* W = (const uint8_t*) w; + const auto* X = (const block_q8_1*) x_q8_1; + switch (t) { +#define STRATA_MMVQ(T) case T: launch_mmvq(W, rb, X, y, n_in, n_out, ncols, s); break; + STRATA_MMVQ_FMTS(STRATA_MMVQ) +#undef STRATA_MMVQ + default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1); + } + check("iq_mmvq"); +} + +void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream) { + if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); } + dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst); + check("iq_dequant_f16"); +} + +namespace { +__global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, size_t row_bytes, + const int32_t* __restrict__ tokens, int64_t n_embd, float* __restrict__ y) { + const int t = blockIdx.y; + const int64_t b = blockIdx.x; + const uint8_t* row = table + (size_t) tokens[t] * row_bytes; + dq_dispatch(ty, row, b, y + (size_t) t * n_embd + b * QK_K, threadIdx.x); +} +} // namespace + +void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd, + float* out, void* stream) { + if (n_tok <= 0) return; + if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); } + embed_rows_kernel<<>>( + t, (const uint8_t*) table, row_bytes, tokens, n_embd, out); + check("iq_embed_rows"); +} + +void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) { + if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); } + dequant_flat_kernel<<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst); + check("iq_dequant_f32"); +} + +void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) { + // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error + if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); } + const int64_t per_row = n_embd / 256; + dequant_gu_kernel<<>>(t, gate, up, per_row, + (__half*) dst); + check("iq_dequant_gu_f16"); +} + +bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { + const int qg = gu_qk(gu_type), qd = d_qk(d_type); + return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && + n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0; +} + +NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { + NativeExpertLayout L; + L.gu_type = gu_type; + L.d_type = d_type; + L.n_embd = n_embd; + L.n_ff = n_ff; + L.gu_row = iq_row_bytes(gu_type, n_embd); + L.d_row = iq_row_bytes(d_type, n_ff); + L.up_off = (size_t) n_ff * L.gu_row; + L.down_off = 2 * L.up_off; + L.bytes = L.down_off + (size_t) n_embd * L.d_row; + return L; +} + +size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { + const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float); + return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); +} + +void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, + const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, + int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream) { + if (cap_groups <= 0 || cap_entries <= 0) return; + cudaStream_t s = (cudaStream_t) stream; + const size_t f = (size_t) cap_entries * (size_t) L.n_ff * sizeof(float), fa = (f + 255) & ~(size_t) 255; + float* gate = (float*) scratch; + float* up = (float*) ((uint8_t*) scratch + fa); + float* h = (float*) ((uint8_t*) scratch + 2 * fa); + block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa); + const auto* X = (const block_q8_1*) x_q8_1; + const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) cap_groups); + switch (L.gu_type) { +#define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + STRATA_GU_FMTS(STRATA_GU) +#undef STRATA_GU + default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); + } + check("native_expert_grouped/gu"); + const long long nh = (long long) cap_entries * L.n_ff; + swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); + quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); + const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) cap_groups); + switch (L.d_type) { +#define STRATA_DOWN(T) case T: launch_down(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + STRATA_D_FMTS(STRATA_DOWN) +#undef STRATA_DOWN + default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1); + } + check("native_expert_grouped/down"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/keyless.cu b/engine/strata/src/kernels/cuda/keyless.cu new file mode 100644 index 00000000..16485d30 --- /dev/null +++ b/engine/strata/src/kernels/cuda/keyless.cu @@ -0,0 +1,25 @@ +#include "strata/core/keyless.hpp" +#include +#include +namespace strata::kernels { +namespace { +__global__ void route_kernel(float* q, const float* matrices, int heads) { + __shared__ float row[256]; + const int d = threadIdx.x, h = blockIdx.x % heads; + float* query = q + (size_t)blockIdx.x * 256; + row[d] = query[d]; + __syncthreads(); + const float* weight = matrices + ((size_t)h * 256 + d) * 256; + float sum = 0; + for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum); + query[d] = sum; +} +} +void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) { + if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads) + throw std::runtime_error("invalid keyless query routing geometry or artifact"); + route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} diff --git a/engine/strata/src/kernels/cuda/kv_q4.cu b/engine/strata/src/kernels/cuda/kv_q4.cu new file mode 100644 index 00000000..b7de61fa --- /dev/null +++ b/engine/strata/src/kernels/cuda/kv_q4.cu @@ -0,0 +1,231 @@ +// src/kernels/cuda/kv_q4.cu - see include/strata/kernels/kv_q4.hpp. Q4_0 KV with Walsh-Hadamard rotation +// (from PR #21 by code-martin; KV-streaming integration and the deterministic group maximum added on merge). +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_stream.hpp" + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "kv_q4: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// Fast Walsh-Hadamard Transform for N = 256: one warp per row, 8 values per lane in registers. +// Orthonormal (scale 1/sqrt(256) = 1/16), so it is its own inverse. +__global__ void fwht256_kernel(const float* __restrict__ src, float* __restrict__ dst, int64_t n_rows, float scale) { + constexpr int warp_size = 32; + constexpr int N = 256; + constexpr int el_w = N / warp_size; // 8 + + const int64_t r = (int64_t) blockIdx.x * blockDim.y + threadIdx.y; + if (r >= n_rows) return; + + const float* row_src = src + r * N; + float* row_dst = dst + r * N; + + float reg[el_w]; + const int lane = threadIdx.x; + +#pragma unroll + for (int i = 0; i < el_w; ++i) reg[i] = row_src[i * warp_size + lane] * scale; + + // the low 5 index bits live across lanes +#pragma unroll + for (int h = 1; h < warp_size; h *= 2) { +#pragma unroll + for (int j = 0; j < el_w; ++j) { + const float val = reg[j]; + const float val2 = __shfl_xor_sync(0xffffffffu, val, h, warp_size); + reg[j] = (lane & h) == 0 ? val + val2 : val2 - val; + } + } + // the high 3 bits across each lane's registers +#pragma unroll + for (int h = warp_size; h < N; h *= 2) { + const int step = h / warp_size; +#pragma unroll + for (int j = 0; j < el_w; j += 2 * step) { +#pragma unroll + for (int k = 0; k < step; ++k) { + const float x = reg[j + k]; + const float y = reg[j + k + step]; + reg[j + k] = x + y; + reg[j + k + step] = x - y; + } + } + } +#pragma unroll + for (int i = 0; i < el_w; ++i) row_dst[i * warp_size + lane] = reg[i]; +} + +// One 32-value group in one warp (lane = element), ggml's q4_0: d = (the value of largest |x|) / -8, +// q = clamp(trunc(x / d + 8.5), 0, 15). Returns the scale bits; `byte` is lane t's packed byte for t < 16 +// (element t in the low nibble, t + 16 in the high one). Ties in |x| resolve to the larger value in EVERY lane, +// so all lanes agree on d (a plain `a > amax` could leave lanes with opposite signs and one block two scales). +__device__ __forceinline__ uint16_t q4_group(float x, int lane, uint8_t& byte) { + float amax = fabsf(x), mval = x; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + const float a = __shfl_xor_sync(0xffffffffu, amax, o); + const float v = __shfl_xor_sync(0xffffffffu, mval, o); + if (a > amax || (a == amax && v > mval)) { amax = a; mval = v; } + } + const float d = mval / -8.0f; + const float id = d != 0.0f ? 1.0f / d : 0.0f; + int q = __float2int_rz(x * id + 8.5f); + const uint8_t qc = (uint8_t) (q < 0 ? 0 : (q > 15 ? 15 : q)); + const uint8_t qhi = __shfl_down_sync(0xffffffffu, qc, 16); + byte = (uint8_t) (qc | (qhi << 4)); + (void) lane; + return f16_from_f32(d); +} + +__device__ __forceinline__ void q4_store(uint8_t* pool, long long row, int b, int lane, uint16_t d, uint8_t byte) { + block_q4_0* blk = reinterpret_cast(pool + row * (long long) sizeof(block_q4_0) * 8) + b; + if (lane == 0) blk->d = d; + if (lane < 16) blk->qs[lane] = byte; +} + +// One block = one 32-value group of one KV head of K (blockIdx.z = 0) or V (1); 32 threads. KV streaming: the VRAM +// page only if the block is resident (table >= 0), the host copy always (identity layout) when there is one. +__global__ void kv_append_q4_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4, + const int32_t* __restrict__ table, const int32_t* __restrict__ step, + const float* __restrict__ kcur, const float* __restrict__ vcur, + int kv_heads, int head_dim, int page_size, KvHostPools host) { + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, b = blockIdx.y, t = threadIdx.x; + const bool is_v = blockIdx.z == 1; + const float x = (is_v ? vcur : kcur)[h * head_dim + b * QK4_0 + t]; + uint8_t byte; + const uint16_t d = q4_group(x, t, byte); + const long long page = (long long) table[pos / page_size]; + if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, t, d, byte); + if (host.k_q4 != nullptr) + q4_store(is_v ? host.v_q4 : host.k_q4, ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size), b, t, + d, byte); +} + +// The prompt path: grid (T, kv_heads, groups), K then V; also into the staging pool (identity layout) when given. +__global__ void kv_append_q4_batch_kernel(uint8_t* __restrict__ k_q4, uint8_t* __restrict__ v_q4, + const int32_t* __restrict__ table, int64_t pos0, + const float* __restrict__ K, const float* __restrict__ V, + int kv_heads, int head_dim, int page_size, int is_v_grid, KvHostPools host, + KvHostPools stage) { + const long long t = blockIdx.x; + const long long pos = pos0 + t; + const int h = blockIdx.y, b = blockIdx.z, th = threadIdx.x; + const bool is_v = is_v_grid != 0; + const float x = (is_v ? V : K)[t * (kv_heads * head_dim) + h * head_dim + b * QK4_0 + th]; + uint8_t byte; + const uint16_t d = q4_group(x, th, byte); + const long long page = (long long) table[pos / page_size]; + const long long row_id = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + if (page >= 0) q4_store(is_v ? v_q4 : k_q4, (page * kv_heads + h) * page_size + (pos % page_size), b, th, d, byte); + if (host.k_q4 != nullptr) q4_store(is_v ? host.v_q4 : host.k_q4, row_id, b, th, d, byte); + if (stage.k_q4 != nullptr) q4_store(is_v ? stage.v_q4 : stage.k_q4, row_id, b, th, d, byte); +} + +// Gather step[kStepWidth] cells into FP16 scratch (the non-fused attention paths) +__global__ void kv_gather_q4_kernel(const uint8_t* __restrict__ k_q4, const uint8_t* __restrict__ v_q4, + const int32_t* __restrict__ table, const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, + uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { + const long long n_ids = (long long) __ldg(step + kStepWidth); + const int blocks_per_head = head_dim / QK4_0; // 8 + const int bytes_per_head = blocks_per_head * sizeof(block_q4_0); // 144 + const long long total_blocks = n_ids * kv_heads * blocks_per_head; + + const long long blk_idx = (long long) blockIdx.x * blockDim.y + threadIdx.y; + if (blk_idx >= total_blocks) return; + + const int t = threadIdx.x; + const long long id = blk_idx / (kv_heads * blocks_per_head); + const int rem = (int) (blk_idx % (kv_heads * blocks_per_head)); + const int h = rem / blocks_per_head; + const int b = rem % blocks_per_head; + + const int cell = ids[id]; + const long long page = (long long) table[cell / page_size]; + const long long row = (page * kv_heads + h) * page_size + (cell % page_size); + + const block_q4_0* k_blk = reinterpret_cast(k_q4 + row * bytes_per_head) + b; + const block_q4_0* v_blk = reinterpret_cast(v_q4 + row * bytes_per_head) + b; + const float kd = f32_from_f16(k_blk->d); + const float vd = f32_from_f16(v_blk->d); + const int j = t < 16 ? t : (t - 16); + const uint8_t k_byte = k_blk->qs[j]; + const uint8_t v_byte = v_blk->qs[j]; + const int kq = (t < 16) ? ((k_byte & 0x0F) - 8) : ((k_byte >> 4) - 8); + const int vq = (t < 16) ? ((v_byte & 0x0F) - 8) : ((v_byte >> 4) - 8); + const long long dst_offset = ((id * kv_heads + h) * head_dim) + (b * QK4_0 + t); + k_scratch[dst_offset] = f16_from_f32((float) kq * kd); + v_scratch[dst_offset] = f16_from_f32((float) vq * vd); +} + +void need_256(const QsaShapes& s, const char* what) { + if (s.head_dim != 256) { + std::fprintf(stderr, "%s: head_dim must be 256 (the Hadamard transform's size)\n", what); + std::exit(1); + } +} + +} // namespace + +void fwht256_cuda(const float* src, float* dst, int64_t n_rows, void* stream) { + if (n_rows <= 0) return; + const int rows_per_block = 4; + const int64_t num_blocks = (n_rows + rows_per_block - 1) / rows_per_block; + fwht256_kernel<<>>( + src, dst, n_rows, 1.0f / 16.0f); + check("fwht256 launch"); +} + +void kv_append_q4_step(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, const int32_t* step, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + need_256(s, "kv_append_q4"); + const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0), 2); + kv_append_q4_kernel<<>>( + k_q4, v_q4, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, + host ? *host : KvHostPools{}); + check("kv_append_q4 launch"); +} + +void kv_append_q4(uint8_t* k_q4, uint8_t* v_q4, const int32_t* page_table, int64_t pos0, int64_t T, const float* K, + const float* V, const QsaShapes& s, void* stream, const KvHostPools* host, const KvHostPools* stage) { + if (T <= 0) return; + need_256(s, "kv_append_q4"); + const dim3 grid((unsigned) T, (unsigned) s.n_head_kv, (unsigned) (s.head_dim / QK4_0)); + cudaStream_t cs = (cudaStream_t) stream; + const KvHostPools h = host ? *host : KvHostPools{}, st = stage ? *stage : KvHostPools{}; + for (int is_v = 0; is_v < 2; ++is_v) + kv_append_q4_batch_kernel<<>>(k_q4, v_q4, page_table, pos0, K, V, (int) s.n_head_kv, + (int) s.head_dim, (int) s.page_size, is_v, h, st); + check("kv_append_q4 batch launch"); +} + +void kv_gather_q4_step(const uint8_t* k_q4, const uint8_t* v_q4, const int32_t* page_table, const int32_t* ids, + const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, + uint16_t* v_scratch, void* stream) { + if (max_ids <= 0) return; + const int blocks_per_head = (int) (s.head_dim / QK4_0); + const int64_t total_blocks = max_ids * s.n_head_kv * blocks_per_head; + const int rows_per_block = 4; + const unsigned num_blocks = (unsigned) ((total_blocks + rows_per_block - 1) / rows_per_block); + kv_gather_q4_kernel<<>>( + k_q4, v_q4, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, k_scratch, + v_scratch); + check("kv_gather_q4 launch"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/kv_q8.cu b/engine/strata/src/kernels/cuda/kv_q8.cu new file mode 100644 index 00000000..077e3167 --- /dev/null +++ b/engine/strata/src/kernels/cuda/kv_q8.cu @@ -0,0 +1,127 @@ +// src/kernels/cuda/kv_q8.cu - see include/strata/kernels/kv_q8.hpp. +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "kv_q8: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +void validate(const QsaShapes& s, const char* what) { + if (s.head_dim % KV_Q8_GROUP != 0 || s.n_head_kv <= 0 || s.page_size <= 0) { + std::fprintf(stderr, "kv_q8: %s: head_dim %lld must be a multiple of %d\n", what, (long long) s.head_dim, + KV_Q8_GROUP); + std::exit(1); + } +} + +// One block = one 64-value group of one KV head of K (blockIdx.z = 0) or V (1); 64 threads, one value each. +__global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict__ v_q, + uint16_t* __restrict__ k_scale, uint16_t* __restrict__ v_scale, + const int32_t* __restrict__ table, const int32_t* __restrict__ step, + const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, + int head_dim, int page_size, KvHostPools host) { + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; + const bool is_v = k_q == nullptr || blockIdx.z == 1; + const int groups = head_dim / KV_Q8_GROUP; + const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; + // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order + float a = fabsf(x); + for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); + __shared__ float warp_max[2]; + if ((t & 31) == 0) warp_max[t >> 5] = a; + __syncthreads(); + const float amax = fmaxf(warp_max[0], warp_max[1]); + const uint16_t sbits = f16_from_f32(amax / 127.0f); + const float sf = f32_from_f16(sbits); // quantize against the STORED scale + int q = 0; + if (sf > 0.0f) { + q = __float2int_rn(x / sf); + q = q < -127 ? -127 : (q > 127 ? 127 : q); + } + // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident + const long long page = (long long) table[pos / page_size]; + if (page >= 0) { + const long long row = (page * kv_heads + h) * page_size + (pos % page_size); + (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; + } + if ((is_v ? host.v_q : host.k_q) != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; + } +} + +// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). +__global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q, + const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale, + const int32_t* __restrict__ table, const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, + uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { + const long long n_ids = (long long) __ldg(step + kStepWidth); + const int per = head_dim / 4; + const long long total = n_ids * kv_heads * per; + const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; + if (i >= total) return; + const long long id = i / (kv_heads * (long long) per); + const int rem = (int) (i % (kv_heads * (long long) per)); + const int h = rem / per, q4 = rem - h * per; + const int cell = ids[id]; + const long long page = (long long) table[cell / page_size]; + const long long row = (page * kv_heads + h) * page_size + (cell % page_size); + const int d = q4 * 4; + const int groups = head_dim / KV_Q8_GROUP; + const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]); + const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]); + const char4 kc = reinterpret_cast(k_q + row * head_dim)[q4]; + const char4 vc = reinterpret_cast(v_q + row * head_dim)[q4]; + ushort4 ko, vo; + ko.x = f16_from_f32((float) kc.x * ks); ko.y = f16_from_f32((float) kc.y * ks); + ko.z = f16_from_f32((float) kc.z * ks); ko.w = f16_from_f32((float) kc.w * ks); + vo.x = f16_from_f32((float) vc.x * vs); vo.y = f16_from_f32((float) vc.y * vs); + vo.z = f16_from_f32((float) vc.z * vs); vo.w = f16_from_f32((float) vc.w * vs); + const long long dst = (id * kv_heads + h) * (long long) per + q4; + reinterpret_cast(k_scratch)[dst] = ko; + reinterpret_cast(v_scratch)[dst] = vo; +} + +} // namespace + +void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table, + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + validate(s, "kv_append_q8"); + const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}); + check("kv_append_q8 launch"); +} + +void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_scale, const uint16_t* v_scale, + const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, + const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { + validate(s, "kv_gather_q8"); + if (max_ids <= 0) return; + const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); + const unsigned blocks = (unsigned) ((total + 255) / 256); + kv_gather_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, + k_scratch, v_scratch); + check("kv_gather_q8 launch"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/kv_stream.cu b/engine/strata/src/kernels/cuda/kv_stream.cu new file mode 100644 index 00000000..ae78d8f0 --- /dev/null +++ b/engine/strata/src/kernels/cuda/kv_stream.cu @@ -0,0 +1,271 @@ +// src/kernels/cuda/kv_stream.cu - see include/strata/kernels/kv_stream.hpp. +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "kv_stream: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +constexpr int RT = 1024; // the resolve block + +// The per-block byte runs of the (up to four) pool arrays: block b of array i is bytes [b * len, (b + 1) * len). +struct Runs { + const uint8_t* src[4]; + uint8_t* dst[4]; + int len[4]; + int n; +}; + +Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) { + const int rows = (int) (s.n_head_kv * s.page_size); + Runs r{}; + if (fmt == kKvValueInt8) { + r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim; + r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2; + r.n = 2; + } else if (fmt == kKvQ4) { + const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); + r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; + r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes; + r.n = 2; + } else if (fmt == kKvInt8) { + const int codes = rows * (int) s.head_dim, scales = rows * (int) (s.head_dim / KV_Q8_GROUP) * 2; + r.src[0] = (const uint8_t*) host.k_q; r.dst[0] = (uint8_t*) slots.k_q; r.len[0] = codes; + r.src[1] = (const uint8_t*) host.v_q; r.dst[1] = (uint8_t*) slots.v_q; r.len[1] = codes; + r.src[2] = (const uint8_t*) host.k_scale; r.dst[2] = (uint8_t*) slots.k_scale; r.len[2] = scales; + r.src[3] = (const uint8_t*) host.v_scale; r.dst[3] = (uint8_t*) slots.v_scale; r.len[3] = scales; + r.n = 4; + } else { + const int bytes = rows * (int) s.head_dim * 2; + r.src[0] = (const uint8_t*) host.k_pool; r.dst[0] = (uint8_t*) slots.k_pool; r.len[0] = bytes; + r.src[1] = (const uint8_t*) host.v_pool; r.dst[1] = (uint8_t*) slots.v_pool; r.len[1] = bytes; + r.n = 2; + } + return r; +} + +// Block-wide exclusive prefix sum of one int per thread (RT threads); `total` is the sum over the block. +__device__ int block_scan(int v, int* warp_sums, int& total) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + int x = v; + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, x, o); + if (lane >= o) x += y; + } + if (lane == 31) warp_sums[w] = x; + __syncthreads(); + if (w == 0) { + int t = warp_sums[lane]; + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, t, o); + if (lane >= o) t += y; + } + warp_sums[lane] = t; + } + __syncthreads(); + total = warp_sums[31]; + const int excl = x - v + (w > 0 ? warp_sums[w - 1] : 0); + __syncthreads(); + return excl; +} + +__global__ void __launch_bounds__(RT) resolve_kernel(KvStreamMap m, const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_q, int cap, int page_size) { + __shared__ int s_nmiss, s_lookups, s_cut; + __shared__ int warp_sums[32]; + const int epoch = m.ctl[0] + 1; + if (threadIdx.x == 0) { s_nmiss = 0; s_lookups = 0; } + __syncthreads(); + // 1. hits take this epoch and their reference bit; a missing block is claimed exactly once (-1 -> -2) + int lookups = 0; + for (int q = 0; q < n_q; ++q) { + const int width = steps[q * kStepCount + kStepWidth]; + const int32_t* qi = ids + (long long) q * cap; + for (int i = threadIdx.x; i < width; i += RT) { + const int b = qi[i] / page_size; + if (i > 0 && qi[i - 1] / page_size == b) continue; // ids are ascending: one lookup per block + ++lookups; + const int sl = m.page_table[b]; + if (sl >= 0) { + m.slot_stamp[sl] = epoch; + m.slot_ref[sl] = 1; + } else if (sl == -1 && atomicCAS(&m.page_table[b], -1, -2) == -1) { + m.miss_block[atomicAdd(&s_nmiss, 1)] = b; + } + } + } + atomicAdd(&s_lookups, lookups); + __syncthreads(); + // 2. one victim per miss: a clock sweep from the hand. A slot this call uses (stamp == epoch) is never taken; + // a referenced one loses its bit as the hand passes it and is taken on the next pass. + const int need = s_nmiss, n = (int) m.n_slots; + int hand = m.ctl[1], got = 0; + for (int scanned = 0; got < need && scanned < 3 * n; scanned += RT) { + const int j = (int) (((long long) hand + threadIdx.x) % n); + const bool mine = m.slot_stamp[j] == epoch; + const bool cand = !mine && (m.slot_block[j] < 0 || m.slot_ref[j] == 0); + int total = 0; + const int rank = block_scan(cand ? 1 : 0, warp_sums, total); + const int want = need - got; + if (threadIdx.x == 0) s_cut = RT; + __syncthreads(); + if (cand && rank == want - 1) s_cut = threadIdx.x + 1; // the hand stops just past the last slot taken + __syncthreads(); + const int cut = s_cut; + if (cand && rank < want) { + m.miss_slot[got + rank] = j; + m.slot_stamp[j] = epoch; // taken: a sweep that wraps around must not take it twice + } else if (threadIdx.x < cut && !mine) { + m.slot_ref[j] = 0; + } + got += total < want ? total : want; + hand = (int) (((long long) hand + cut) % n); + __syncthreads(); + } + // 3. re-point the table; the copy kernel fills the slots + const int placed = got < need ? got : need; + for (int k = threadIdx.x; k < need; k += RT) { + const int b = m.miss_block[k]; + if (k >= placed) { m.page_table[b] = -1; continue; } // overflow: never happens with a legal n_slots + const int sl = m.miss_slot[k]; + const int old = m.slot_block[sl]; + if (old >= 0) m.page_table[old] = -1; + m.slot_block[sl] = b; + m.slot_stamp[sl] = epoch; + m.slot_ref[sl] = 1; + m.page_table[b] = sl; + } + if (threadIdx.x == 0) { + m.ctl[0] = epoch; + m.ctl[1] = hand; + m.ctl[2] = placed; + if (placed < need) m.ctl[3] = 1; + unsigned long long* c = reinterpret_cast(m.ctl + 4); + c[0] += (unsigned long long) placed; + c[1] += (unsigned long long) s_lookups; + c[2] += 1ull; + } +} + +// One block per missed block (grid-stride): copy its runs from the host copy into its slot, 16 B per thread. +__global__ void copy_kernel(KvStreamMap m, Runs r) { + const int need = m.ctl[2]; + for (int k = blockIdx.x; k < need; k += gridDim.x) { + const long long b = m.miss_block[k], sl = m.miss_slot[k]; + for (int a = 0; a < r.n; ++a) { + const uint4* src = reinterpret_cast(r.src[a] + b * r.len[a]); + uint4* dst = reinterpret_cast(r.dst[a] + sl * r.len[a]); + for (int i = threadIdx.x; i < r.len[a] / 16; i += blockDim.x) dst[i] = src[i]; + } + } +} + +__global__ void reset_kernel(KvStreamMap m) { + const long long i0 = (long long) blockIdx.x * blockDim.x + threadIdx.x, st = (long long) gridDim.x * blockDim.x; + for (long long i = i0; i < m.n_blocks; i += st) m.page_table[i] = -1; + for (long long i = i0; i < m.n_slots; i += st) { + m.slot_block[i] = -1; + m.slot_stamp[i] = -1; + m.slot_ref[i] = 0; + } + if (i0 < kKvCtlInts) m.ctl[i0] = 0; +} + +__global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slots) { + for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n_blocks; + i += (long long) gridDim.x * blockDim.x) + table[i] = (int32_t) (i % n_slots); +} + +} // namespace + +uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { + const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); + if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2); + if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2; + return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2 + : rows * (uint64_t) s.head_dim * 2 * 2; +} + +void kv_stream_reset(const KvStreamMap& m, void* stream) { + reset_kernel<<<128, 256, 0, (cudaStream_t) stream>>>(m); + check("reset"); +} + +void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const KvHostPools& host, int fmt, + const int32_t* ids, const int32_t* steps, int64_t n_q, int64_t cap, const QsaShapes& s, + void* stream) { + if (n_q <= 0) return; + if (s.n_head_kv * s.page_size * (s.head_dim / KV_Q8_GROUP) * 2 % 16 != 0) { + std::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n"); + std::exit(1); + } + // one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two + // threads see the same slot and may both take it for two different misses. The engine never streams with fewer + // than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit. + if (m.n_slots < RT) { + std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a " + "slot twice\n", (long long) m.n_slots, RT); + std::exit(1); + } + resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size); + check("resolve"); + copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s)); + check("copy"); +} + +void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void* stream) { + ring_kernel<<<64, 256, 0, (cudaStream_t) stream>>>(page_table, n_blocks, n_slots); + check("ring table"); +} + +void kv_ring_restore(const QsaAttnPools& slots, const KvHostPools& host, int fmt, int64_t b0, int64_t b1, + int64_t n_slots, const QsaShapes& s, void* stream) { + const Runs r = runs_of(slots, host, fmt, s); + for (int64_t b = b0; b < b1;) { + const int64_t sl = b % n_slots, run = std::min(b1 - b, n_slots - sl); // up to the ring's end + for (int a = 0; a < r.n; ++a) + if (cudaMemcpyAsync(r.dst[a] + sl * r.len[a], r.src[a] + b * r.len[a], (size_t) (run * r.len[a]), + cudaMemcpyDefault, (cudaStream_t) stream) != cudaSuccess) + check("ring restore"); + b += run; + } +} + +void kv_stage_from_host(const QsaAttnPools& stage, const KvHostPools& host, int fmt, int64_t n_blocks, + const QsaShapes& s, void* stream) { + if (n_blocks <= 0) return; + const Runs r = runs_of(stage, host, fmt, s); + for (int a = 0; a < r.n; ++a) + if (cudaMemcpyAsync(r.dst[a], r.src[a], (size_t) (n_blocks * r.len[a]), cudaMemcpyDefault, + (cudaStream_t) stream) != cudaSuccess) + check("stage"); +} + +KvStreamCounters kv_stream_counters(const KvStreamMap& m) { + int32_t c[kKvCtlInts] = {}; + KvStreamCounters r; + if (m.ctl == nullptr || cudaMemcpy(c, m.ctl, sizeof(c), cudaMemcpyDeviceToHost) != cudaSuccess) return r; + const unsigned long long* u = reinterpret_cast(c + 4); + r.misses = u[0]; + r.lookups = u[1]; + r.calls = u[2]; + r.overflow = c[3] != 0; + return r; +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_bf16.cu b/engine/strata/src/kernels/cuda/native_bf16.cu new file mode 100644 index 00000000..1390a6ab --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_bf16.cu @@ -0,0 +1,186 @@ +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/bf16_bits.hpp" + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +// The FP32-activation MMVF implementation below is adapted from llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d, ggml/src/ggml-cuda/{mmvf.cu,common.cuh}. +// Scope: ordinary contiguous BF16 matrix, one FP32 activation vector, no fusion/ids/channels. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +__device__ __forceinline__ float mmvf_warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) + value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + return value; +} + +template +__global__ void bf16_f32_mmvf_kernel(const float* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, int n_in) { + const int t = threadIdx.x; + const uint16_t* row = w + (size_t) blockIdx.x * n_in; + const uint32_t* weights2 = reinterpret_cast(row); + const float2* inputs2 = reinterpret_cast(x); + __shared__ float partials[32]; + if constexpr (BLOCK_SIZE > 32) { + if (t < 32) partials[t] = 0.0f; + __syncthreads(); + } + float acc = 0.0f; + for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { + const uint32_t weight = weights2[pair]; + const float2 input = inputs2[pair]; + // Match the two ordered multiply-adds in ggml_cuda_mad, not a pair sum followed by one add. + acc = __fmaf_rn(f32_from_bf16((uint16_t) weight), input.x, acc); + acc = __fmaf_rn(f32_from_bf16((uint16_t) (weight >> 16)), input.y, acc); + } + acc = mmvf_warp_sum(acc); + if constexpr (BLOCK_SIZE > 32) { + // All lanes have the same reduced value; one store avoids a same-value shared-memory race. + if ((t & 31) == 0) partials[t / 32] = acc; + __syncthreads(); + if (t < 32) acc = mmvf_warp_sum(partials[t]); + } + if (t == 0) y[blockIdx.x] = acc; +} + +// the same kernel for up to 8 activation rows - the weight row is read ONCE and every +// token keeps its own accumulator with exactly the single-row kernel's order (pairs, two ordered FMAs, the same warp +// and block reductions), so each output is bit-identical to a bf16_f32_mmvf_kernel launch of its own. +template +__global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w, + float* __restrict__ y, int64_t ldy, int n_in, int n_tok) { + const int t = threadIdx.x; + const uint16_t* row = w + (size_t) blockIdx.x * n_in; + const uint32_t* weights2 = reinterpret_cast(row); + __shared__ float partials[NT][32]; + if constexpr (BLOCK_SIZE > 32) { + if (t < 32) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f; + __syncthreads(); + } + float acc[NT]; +#pragma unroll + for (int k = 0; k < NT; ++k) acc[k] = 0.0f; + for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) { + const uint32_t weight = weights2[pair]; + const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16)); +#pragma unroll + for (int k = 0; k < NT; ++k) { + if (k < n_tok) { + const float2 input = reinterpret_cast(x + (size_t) k * ldx)[pair]; + acc[k] = __fmaf_rn(w0, input.x, acc[k]); + acc[k] = __fmaf_rn(w1, input.y, acc[k]); + } + } + } +#pragma unroll + for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(acc[k]); + if constexpr (BLOCK_SIZE > 32) { + if ((t & 31) == 0) +#pragma unroll + for (int k = 0; k < NT; ++k) partials[k][t / 32] = acc[k]; + __syncthreads(); + if (t < 32) +#pragma unroll + for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(partials[k][t]); + } + if (t == 0) +#pragma unroll + for (int k = 0; k < NT; ++k) + if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k]; +} + +int mmvf_block_size(int64_t n_in) { + int best = 32; + int64_t best_iterations = (n_in + 63) / 64; + for (int candidate = 64; candidate <= 256; candidate += 32) { + const int64_t iterations = (n_in + 2 * candidate - 1) / (2 * candidate); + if (iterations < best_iterations) { + best_iterations = iterations; + best = candidate; + } + } + return best; +} + +} // namespace + +void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, + int64_t n_in, int64_t n_out, int n_tok, void* stream) { + if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; } + if (n_tok < 1 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || n_out <= 0 || (ldx & 1) != 0 || x == nullptr || + w == nullptr || y == nullptr || (reinterpret_cast(x) & 7u) != 0) + throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers"); + const cudaStream_t st = (cudaStream_t) stream; +#define STRATA_MMVF_M(N) case N: \ + if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \ + else bf16_f32_mmvf_multi_kernel<<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break + switch (mmvf_block_size(n_in)) { + STRATA_MMVF_M(32); STRATA_MMVF_M(64); STRATA_MMVF_M(96); STRATA_MMVF_M(128); + STRATA_MMVF_M(160); STRATA_MMVF_M(192); STRATA_MMVF_M(224); STRATA_MMVF_M(256); + } +#undef STRATA_MMVF_M + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result)); +} + +void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y, + int64_t n_in, int64_t n_out, void* stream) { + if (n_in <= 0 || (n_in & 1) != 0 || n_in > std::numeric_limits::max() || + n_out <= 0 || n_out > std::numeric_limits::max()) + throw std::invalid_argument("bf16_gemv_fp32_mmvf: require positive even n_in and positive n_out <= INT_MAX"); + if (x == nullptr || w == nullptr || y == nullptr || + (reinterpret_cast(x) & 7u) != 0 || + (reinterpret_cast(w) & 3u) != 0 || + (reinterpret_cast(y) & 3u) != 0) + throw std::invalid_argument("bf16_gemv_fp32_mmvf: null or misaligned pointer"); + const cudaStream_t st = (cudaStream_t) stream; +#define STRATA_MMVF_CASE(N) case N: \ + bf16_f32_mmvf_kernel<<<(unsigned) n_out, N, 0, st>>>(x, w, y, (int) n_in); break + switch (mmvf_block_size(n_in)) { + STRATA_MMVF_CASE(32); + STRATA_MMVF_CASE(64); + STRATA_MMVF_CASE(96); + STRATA_MMVF_CASE(128); + STRATA_MMVF_CASE(160); + STRATA_MMVF_CASE(192); + STRATA_MMVF_CASE(224); + STRATA_MMVF_CASE(256); + } +#undef STRATA_MMVF_CASE + const cudaError_t result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf launch: ") + cudaGetErrorString(result)); +} + + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_flash_attn.cu b/engine/strata/src/kernels/cuda/native_flash_attn.cu new file mode 100644 index 00000000..5a4f36d5 --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_flash_attn.cu @@ -0,0 +1,212 @@ +// Specialized from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d, +// ggml/src/ggml-cuda/{fattn-vec.cuh,fattn-common.cuh,common.cuh}. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_flash_attn.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +template __device__ __forceinline__ float warp_sum(float x) { +#pragma unroll + for (int offset = Width / 2; offset; offset >>= 1) + x += __shfl_xor_sync(0xffffffffu, x, offset, Width); + return x; +} +__device__ __forceinline__ float warp_max(float x) { +#pragma unroll + for (int offset = 16; offset; offset >>= 1) + x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, offset, 32)); + return x; +} + +// D=256,ncols=1,F16/F16; 128 threads, nthreads_KQ=nthreads_V=8, +// four values (float2) per load, four V columns per iteration. Padded length256 +// gives ntiles_KV=ceil(256/D)=1, so the pinned launcher selects grid.y=1. +__launch_bounds__(128, 1) +__global__ void attend(const float* __restrict__ q, const half* __restrict__ k, + const half* __restrict__ v, const int32_t* __restrict__ step, + int max_context, int padded_length, float scale, float* __restrict__ out, int32_t* __restrict__ status, + const half* __restrict__ mask) { + const int lane = threadIdx.x, warp = threadIdx.y, tid = warp * 32 + lane; + const int head = blockIdx.x, kv = head / 12; + const int width = step[kStepWidth], nkv = step[kStepNKv]; + const bool valid = width >= 1 && width <= max_context && nkv == width && + step[kStepPos] == width - 1 && step[kStepNBid] == width / 4; + if (head == 0 && tid == 0) + *status = valid ? kNativeFlashAttnSuccess : kNativeFlashAttnUnsupportedStep; + if (!valid) { + out[head * 256 + tid] = __int_as_float(0x7fc00000); + out[head * 256 + tid + 128] = __int_as_float(0x7fc00000); + return; + } + float2 qreg[16]; + float2 vkq[16] = {}; + __shared__ float tile[4 * 4 * 256]; + __shared__ float max_shared[32], sum_shared[32]; + float maximum = -FLT_MAX / 2.0f, sum = 0.0f; +#pragma unroll + for (int i0 = 0; i0 < 128; i0 += 32) { + const int i = i0 + (lane % 8) * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = 2 * (i + j); + qreg[i0 / 8 + j] = make_float2(q[head * 256 + d] * scale, + q[head * 256 + d + 1] * scale); + } + } + for (int base = 0; base < padded_length; base += 128) { + float score = 0.0f, next_max = maximum; +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int cell = base + warp * 32 + (lane & ~7) + row; + float dot = 0.0f; +#pragma unroll + for (int i0 = 0; i0 < 128; i0 += 32) { + const int i = i0 + (lane % 8) * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = 2 * (i + j); + const float a = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d]) : 0.0f; + const float b = cell < width ? __half2float(k[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; + dot += a * qreg[i0 / 8 + j].x; + dot += b * qreg[i0 / 8 + j].y; + } + } + dot = warp_sum<8>(dot); + dot += cell < width ? (mask ? __half2float(mask[cell]) : 0.0f) : __int_as_float(0xff800000u); + next_max = fmaxf(next_max, dot + (3.0f * 0.6931f)); + if (lane % 8 == row) score = dot; + } +#pragma unroll + for (int offset = 8; offset < 32; offset <<= 1) + next_max = fmaxf(next_max, __shfl_xor_sync(0xffffffffu, next_max, offset, 32)); + const float rescale = expf(maximum - next_max); + maximum = next_max; + score = expf(score - maximum); + sum = sum * rescale + score; + tile[tid] = score; + __syncwarp(); +#pragma unroll + for (int k0 = 0; k0 < 32; k0 += 4) { + const int local = warp * 32 + k0 + lane / 8, cell = base + local; + const float weight = tile[local]; +#pragma unroll + for (int i0 = 0; i0 < 128; i0 += 32) { + const int i = i0 + (lane % 8) * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = 2 * (i + j); + const float a = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d]) : 0.0f; + const float b = cell < width ? __half2float(v[(cell * 2 + kv) * 256 + d + 1]) : 0.0f; + // The pinned sm120a binary contracts the old-accumulator + // rescale with the FIRST addition: fma(rescale,old,round(V*w)). + // Later columns use fma(V,w,acc). Explicit intrinsics retain + // that order despite this adapter's masked-load branches. + if (k0 == 0) { + vkq[i0 / 8 + j].x = __fmaf_rn(rescale, vkq[i0 / 8 + j].x, __fmul_rn(a, weight)); + vkq[i0 / 8 + j].y = __fmaf_rn(rescale, vkq[i0 / 8 + j].y, __fmul_rn(b, weight)); + } else { + vkq[i0 / 8 + j].x = __fmaf_rn(a, weight, vkq[i0 / 8 + j].x); + vkq[i0 / 8 + j].y = __fmaf_rn(b, weight, vkq[i0 / 8 + j].y); + } + } + } + } + } + if (warp == 0) { max_shared[lane] = -FLT_MAX / 2.0f; sum_shared[lane] = 0.0f; } + __syncthreads(); + if (lane == 0) max_shared[warp] = maximum; + __syncthreads(); + const float global_max = warp_max(max_shared[lane]); + const float rescale = expf(maximum - global_max); +#pragma unroll + for (int i = 0; i < 16; ++i) { + vkq[i].x = __fmul_rn(vkq[i].x, rescale); + vkq[i].y = __fmul_rn(vkq[i].y, rescale); + } +#pragma unroll + for (int i0 = 0; i0 < 128; i0 += 32) { + const int start = warp * 4 * 256 + (lane / 8) * 256 + 2 * (i0 + (lane % 8) * 4); +#pragma unroll + for (int j = 0; j < 4; ++j) { + tile[start + 2 * j] = vkq[i0 / 8 + j].x; + tile[start + 2 * j + 1] = vkq[i0 / 8 + j].y; + } + } + sum *= rescale; + sum = warp_sum<32>(sum); + if (lane == 0) sum_shared[warp] = sum; + __syncthreads(); + sum = warp_sum<32>(sum_shared[lane]); +#pragma unroll + for (int i0 = 0; i0 < 256; i0 += 128) { + float result = 0.0f; +#pragma unroll + for (int w = 0; w < 4; ++w) { +#pragma unroll + for (int group = 0; group < 4; ++group) + result += tile[w * 4 * 256 + group * 256 + i0 + tid]; + } + out[head * 256 + i0 + tid] = result / sum; + } +} +struct Span { const void* p; std::size_t n, alignment; }; +void validate_spans(const Span* spans, int count) { + for (int i = 0; i < count; ++i) { + const auto a = reinterpret_cast(spans[i].p); + if (!a || a % spans[i].alignment || spans[i].n > UINTPTR_MAX - a) + throw std::invalid_argument("native FlashAttention requires nonnull aligned bounded spans"); + for (int j = 0; j < i; ++j) { + const auto b = reinterpret_cast(spans[j].p); + if (a < b + spans[j].n && b < a + spans[i].n) + throw std::invalid_argument("native FlashAttention requires disjoint buffers"); + } + } +} +} // namespace + +void native_flash_attn_short_step(const float* q, const uint16_t* k, const uint16_t* v, + const int32_t* step, int64_t capacity, int max_context, + const QsaShapes& shapes, float* output, int32_t* status, + const uint16_t* mask, void* stream) { + if (!stream || shapes.n_head != 24 || shapes.n_head_kv != 2 || shapes.head_dim != 256 || + shapes.idx_block != 4 || shapes.idx_top_k < 256 || capacity < 256 || + uint64_t(capacity) > std::numeric_limits::max() / 1024 || + max_context < 1 || max_context > 256) + throw std::invalid_argument("native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream"); + const std::size_t kv_bytes = std::size_t(capacity) * 1024; + const Span spans[] = {{q, 24 * 256 * 4, 4}, {k, kv_bytes, 2}, {v, kv_bytes, 2}, + {step, kStepCount * 4, 4}, {output, 24 * 256 * 4, 4}, + {status, 4, 4}, {mask, 256 * 2, 2}}; + validate_spans(spans, mask ? 7 : 6); + attend<<<24, dim3(32, 4), 0, static_cast(stream)>>>(q, reinterpret_cast(k), + reinterpret_cast(v), step, max_context, 256, 0.0625f, output, status, reinterpret_cast(mask)); + const auto result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("native FlashAttention launch: ") + cudaGetErrorString(result)); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_gdn.cu b/engine/strata/src/kernels/cuda/native_gdn.cu new file mode 100644 index 00000000..6661d50f --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_gdn.cu @@ -0,0 +1,122 @@ +// Arithmetic adapted from gated_delta_net.cu at pinned llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d. Only state addressing differs: +// each warp owns one Strata (head,column) and retains its four rows in registers. +// Compile with --use_fast_math to match the pinned CUDA implementation. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "strata/kernels/native_gdn.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +constexpr int S = 128; + +__device__ __forceinline__ float warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) + value += __shfl_xor_sync(0xffffffff, value, offset, 32); + return value; +} + +__global__ void __launch_bounds__(128, 2) +step(float* __restrict__ state, const float* __restrict__ q, const float* __restrict__ k, + const float* __restrict__ v, const float* __restrict__ gate, const float* __restrict__ beta, + float* __restrict__ output, int h_k, int h_v, float scale) { + const int head = blockIdx.x; + const int lane = threadIdx.x; + const int col = blockIdx.z * blockDim.y + threadIdx.y; + const int q_head = head % h_k; + float s_shard[4], k_reg[4], q_reg[4]; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int i = r * 32 + lane; + s_shard[r] = state[(size_t(i) * h_v + head) * S + col]; + k_reg[r] = k[q_head * S + i]; + q_reg[r] = q[q_head * S + i]; + } + const float g_val = expf(gate[head]); + float kv_shard = 0.0f; +#pragma unroll + for (int r = 0; r < 4; ++r) kv_shard += s_shard[r] * k_reg[r]; + const float kv_col = warp_sum(kv_shard); + const float delta_col = (v[head * S + col] - g_val * kv_col) * beta[head]; + float attn_partial = 0.0f; +#pragma unroll + for (int r = 0; r < 4; ++r) { + s_shard[r] = g_val * s_shard[r] + k_reg[r] * delta_col; + attn_partial += s_shard[r] * q_reg[r]; + } + const float attn_col = warp_sum(attn_partial); + if (lane == 0) output[head * S + col] = attn_col * scale; +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int i = r * 32 + lane; + state[(size_t(i) * h_v + head) * S + col] = s_shard[r]; + } +} + +bool valid_span(const void* pointer, size_t bytes) { + const auto address = reinterpret_cast(pointer); + return pointer && address % sizeof(float) == 0 && bytes <= UINTPTR_MAX - address; +} +bool overlap(const void* a, size_t an, const void* b, size_t bn) { + const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); + return ap < bp + bn && bp < ap + an; +} +} + +void native_gdn_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_gdn_enabled() { return enabled.load(std::memory_order_relaxed); } + +void native_gdn_step(float* state, const float* q, const float* k, const float* v, + const float* gate, const float* beta, float* output, + const GdnShapes& shape, void* stream) { + if (!stream || shape.S != S || shape.h_k <= 0 || shape.h_v <= 0 || + shape.h_v > 65535 || shape.h_v % shape.h_k != 0) + throw std::invalid_argument("native GDN requires a stream, S=128 and positive divisible head counts <=65535"); + const size_t state_bytes = size_t(S) * S * size_t(shape.h_v) * sizeof(float); + const size_t qk_bytes = size_t(S) * size_t(shape.h_k) * sizeof(float); + const size_t output_bytes = size_t(S) * size_t(shape.h_v) * sizeof(float); + const size_t head_bytes = size_t(shape.h_v) * sizeof(float); + if (!valid_span(state, state_bytes) || !valid_span(output, output_bytes) || + overlap(state, state_bytes, output, output_bytes)) + throw std::invalid_argument("native GDN requires aligned, disjoint state and output spans"); + const void* inputs[] = {q, k, v, gate, beta}; + const size_t bytes[] = {qk_bytes, qk_bytes, output_bytes, head_bytes, head_bytes}; + for (int i = 0; i < 5; ++i) { + if (!valid_span(inputs[i], bytes[i]) || overlap(state, state_bytes, inputs[i], bytes[i]) || + overlap(output, output_bytes, inputs[i], bytes[i])) + throw std::invalid_argument("native GDN requires aligned input spans disjoint from state and output"); + } + const float scale = 1.0f / sqrtf(float(S)); + step<<(stream)>>>( + state, q, k, v, gate, beta, output, int(shape.h_k), int(shape.h_v), scale); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_gdn_preprocess.cu b/engine/strata/src/kernels/cuda/native_gdn_preprocess.cu new file mode 100644 index 00000000..86b10453 --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_gdn_preprocess.cu @@ -0,0 +1,199 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu,unary.cuh,ssm-conv.cu,scale.cu}. +// Compile with --use_fast_math, as the pinned backend does. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "strata/kernels/native_gdn_preprocess.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +constexpr int S = 128; + +__device__ __forceinline__ float warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) + value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + return value; +} +__device__ __forceinline__ float norm_sum(float value, float* sums) { + const int lane = threadIdx.x % 32; + value = warp_sum(value); + if (lane == 0) sums[threadIdx.x / 32] = value; + __syncthreads(); + value = lane < 8 ? sums[lane] : 0.0f; + return warp_sum(value); +} +__device__ __forceinline__ float sigmoid(float value) { return 1.0f / (1.0f + expf(-value)); } + +__global__ void conv_silu(float* __restrict__ history, const float* __restrict__ input, + const float* __restrict__ weights, float* __restrict__ raw_output, + float* __restrict__ silu_output, int channels) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + float values[4] = {history[c * 3], history[c * 3 + 1], history[c * 3 + 2], input[c]}; + float sum = 0.0f; +#pragma unroll + for (int tap = 0; tap < 4; ++tap) sum += values[tap] * weights[c * 4 + tap]; + // The native SSM kernel adds its zero bias even when there is no bias input. + sum = __fadd_rn(sum, 0.0f); + raw_output[c] = sum; + silu_output[c] = sum / (1.0f + expf(-sum)); +#pragma unroll + for (int tap = 0; tap < 3; ++tap) history[c * 3 + tap] = values[tap + 1]; +} + +__global__ void l2_norm(float* input, float epsilon, float scale_after) { + const int col = threadIdx.x; + input += size_t(blockIdx.x) * S; + const float value = col < S ? input[col] : 0.0f; + float partial = 0.0f; + if (col < S) partial += value * value; + __shared__ float sums[32]; + partial = norm_sum(partial, sums); + const float scale = rsqrtf(partial / S + epsilon); + if (col < S) { + // Preserve the FP32 store boundary between RMSNorm and ggml_scale. + const float normalized = __fmul_rn(scale, value); + input[col] = __fmaf_rn(normalized, scale_after, 0.0f); + } +} + +__global__ void beta_sigmoid(float* beta, int count) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < count) beta[i] = sigmoid(beta[i]); +} +__global__ void gate_softplus(const float* __restrict__ alpha, const float* __restrict__ dt, + const float* __restrict__ ssm_a, float* __restrict__ gate, int count) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const float value = __fadd_rn(alpha[i], dt[i]); + const float softplus = value > 20.0f ? value : log1pf(expf(value)); // 1 + e^v loses e^v below ~1e-7 + gate[i] = softplus * ssm_a[i]; +} + +__global__ void out_norm(const float* __restrict__ input, const float* __restrict__ z, + const float* __restrict__ gamma, float* __restrict__ output, float epsilon) { + const int col = threadIdx.x; + const size_t offset = size_t(blockIdx.x) * S; + const float value = col < S ? input[offset + col] : 0.0f; + float partial = 0.0f; + if (col < S) partial += value * value; + __shared__ float sums[32]; + partial = norm_sum(partial, sums); + const float scale = rsqrtf(partial / S + epsilon); + if (col < S) { + // RMSNorm+gamma is one pinned fused operator, followed by sigmoid*mul. + const float weighted = __fmul_rn(__fmul_rn(scale, value), gamma[col]); + output[offset + col] = weighted * sigmoid(z[offset + col]); + } +} + +struct Span { const void* pointer; size_t bytes; }; +void valid(Span span) { + const auto address = reinterpret_cast(span.pointer); + if (!span.pointer || address % sizeof(float) || span.bytes > UINTPTR_MAX - address) + throw std::invalid_argument("native GDN preprocessing requires aligned nonnull valid spans"); +} +void disjoint(Span a, Span b) { + const auto ap = reinterpret_cast(a.pointer), bp = reinterpret_cast(b.pointer); + if (ap < bp + b.bytes && bp < ap + a.bytes) + throw std::invalid_argument("native GDN preprocessing requires disjoint writable spans"); +} +void count_and_stream(int64_t count, void* stream) { + if (!stream || count <= 0 || count > 65535) + throw std::invalid_argument("native GDN preprocessing requires a stream and count in [1,65535]"); +} +void norm_geometry(int64_t rows, int64_t cols, float epsilon, void* stream) { + count_and_stream(rows, stream); + if (cols != S || !std::isfinite(epsilon) || epsilon < 0.0f) + throw std::invalid_argument("native GDN norm requires width 128 and finite nonnegative epsilon"); +} +void check_launch() { + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} + +void native_gdn_conv_silu(float* history, const float* input, const float* weights, + float* raw_output, float* silu_output, int64_t channels, + int64_t d_conv, void* stream) { + count_and_stream(channels, stream); + if (d_conv != 4) throw std::invalid_argument("native GDN convolution requires four taps"); + const size_t bytes = size_t(channels) * sizeof(float); + const Span writable[] = {{history, 3 * bytes}, {raw_output, bytes}, {silu_output, bytes}}; + const Span inputs[] = {{input, bytes}, {weights, 4 * bytes}}; + for (auto span : writable) valid(span); + for (auto span : inputs) valid(span); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < i; ++j) disjoint(writable[i], writable[j]); + for (auto span : inputs) disjoint(writable[i], span); + } + conv_silu<<(stream)>>>( + history, input, weights, raw_output, silu_output, int(channels)); + check_launch(); +} +void native_gdn_l2_norm(float* input, int64_t rows, int64_t cols, float epsilon, void* stream) { + norm_geometry(rows, cols, epsilon, stream); + valid({input, size_t(rows) * S * sizeof(float)}); + l2_norm<<(stream)>>>(input, epsilon / S, 1.0f / sqrtf(float(S))); + check_launch(); +} +void native_gdn_beta_gate(float* beta, int64_t heads, void* stream) { + count_and_stream(heads, stream); + valid({beta, size_t(heads) * sizeof(float)}); + beta_sigmoid<<(stream)>>>(beta, int(heads)); + check_launch(); +} +void native_gdn_gate(const float* alpha, const float* dt, const float* ssm_a, + float* gate, int64_t heads, void* stream) { + count_and_stream(heads, stream); + const size_t bytes = size_t(heads) * sizeof(float); + const Span output{gate, bytes}; + valid(output); + for (auto input : {Span{alpha, bytes}, Span{dt, bytes}, Span{ssm_a, bytes}}) { + valid(input); + disjoint(output, input); + } + gate_softplus<<(stream)>>>(alpha, dt, ssm_a, gate, int(heads)); + check_launch(); +} +void native_gdn_out_norm(const float* output, const float* z, const float* gamma, + float* destination, int64_t heads, int64_t cols, + float epsilon, void* stream) { + norm_geometry(heads, cols, epsilon, stream); + const size_t bytes = size_t(heads) * S * sizeof(float); + const Span writable{destination, bytes}; + valid(writable); + for (auto input : {Span{output, bytes}, Span{z, bytes}, Span{gamma, S * sizeof(float)}}) { + valid(input); + disjoint(writable, input); + } + out_norm<<(stream)>>>(output, z, gamma, destination, epsilon); + check_launch(); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_gr_norm.cu b/engine/strata/src/kernels/cuda/native_gr_norm.cu new file mode 100644 index 00000000..5abe013e --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_gr_norm.cu @@ -0,0 +1,102 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{norm.cu,common.cuh}. Scope: contiguous weighted F32 RMSNorm. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_gr_norm.hpp" + +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +__device__ __forceinline__ float norm_warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + } + return value; +} + +template +__global__ void weighted_rms_norm(const float* __restrict__ input, + const float* __restrict__ gamma, + float* __restrict__ output, int n_cols, float epsilon) { + const int tid = threadIdx.x; + const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; + input += row_offset; + gamma += row_offset; + output += row_offset; + float partial = 0.0f; + for (int col = tid; col < n_cols; col += BlockSize) { + const float value = input[col]; + partial += value * value; + } + + // Pinned block_reduce: every warp repeats the final XOR + // reduction. There is no warp-0-only broadcast or downward-shuffle tree. + __shared__ float sums[32]; + partial = norm_warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + __syncthreads(); + partial = 0.0f; + if (lane < BlockSize / 32) partial = sums[lane]; + partial = norm_warp_sum(partial); + + const float mean = partial / n_cols; + const float scale = rsqrtf(mean + epsilon); + for (int col = tid; col < n_cols; col += BlockSize) { + output[col] = scale * input[col] * gamma[col]; + } +} + +void check_pointer(const void* p) { + if (!p || reinterpret_cast(p) % alignof(float) != 0) + throw std::invalid_argument("native GR RMSNorm requires non-null four-byte aligned pointers"); +} + +} // namespace + +void native_gr_rms_norm_weighted(const float* input, const float* gamma, float* output, + int n_cols, int n_rows, float epsilon, void* stream) { + if (n_cols <= 0 || n_rows <= 0 || !std::isfinite(epsilon) || epsilon < 0.0f) + throw std::invalid_argument("native GR RMSNorm requires positive dimensions and finite nonnegative epsilon"); + check_pointer(input); + check_pointer(gamma); + check_pointer(output); + const auto cuda_stream = static_cast(stream); + if (n_cols < 1024) + weighted_rms_norm<256><<>>(input, gamma, output, n_cols, epsilon); + else + weighted_rms_norm<1024><<>>(input, gamma, output, n_cols, epsilon); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + throw std::runtime_error(std::string("native GR RMSNorm launch: ") + cudaGetErrorString(error)); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_gr_postops.cu b/engine/strata/src/kernels/cuda/native_gr_postops.cu new file mode 100644 index 00000000..8616e331 --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_gr_postops.cu @@ -0,0 +1,115 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_gr_postops.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +constexpr int THREADS = 256; +__device__ __forceinline__ float sigmoid(float x) { return 1.0f / (1.0f + expf(-x)); } +// ggml SCALE uses scale*x+bias, including its +0 bias. Retain this operation +// explicitly so compile-time zero does not change signed-zero behavior. +__device__ __forceinline__ float scale_zero_bias(float x, float scale) { + return __fmaf_rn(scale, x, 0.0f); +} +__global__ void down_silu(float* lo, int count, float scale) { + const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= std::size_t(count)) return; + const float x = scale_zero_bias(lo[i], scale); + lo[i] = x / (1.0f + expf(-x)); +} +template +__global__ void pre_gated(const float* __restrict__ xn, float* __restrict__ gate, + float* __restrict__ mixed, int n_embd, int hc, float scale) { + const std::size_t d = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (d >= std::size_t(n_embd)) return; + float sum = 0.0f; + for (int c = 0; c < hc; ++c) { + const std::size_t i = std::size_t(c) * n_embd + d; + const float x = xn[i], w = sigmoid(gate[i]); + const float product = __fmul_rn(x, w); + gate[i] = product; + if constexpr (Fused) sum = __fmaf_rn(x, w, sum); + else sum = c == 0 ? product : __fadd_rn(sum, product); + } + if constexpr (Fused) mixed[d] = scale * sum; + else mixed[d] = scale_zero_bias(sum, scale); +} +__global__ void post(const float* residual, const float* __restrict__ block_out, + const float* __restrict__ inject, float* output, + int n_embd, int hc, float scale) { + const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= std::size_t(n_embd) * hc) return; + const int c = int(i / n_embd), d = int(i % n_embd); + const float weight = scale_zero_bias(sigmoid(scale_zero_bias(inject[c], scale)), 2.0f); + // Exact residual/output alias is supported; no other thread reads residual[i]. + output[i] = __fmaf_rn(block_out[d], weight, residual[i]); +} +void check_pointer(const void* p) { + if (!p || reinterpret_cast(p) % alignof(float)) + throw std::invalid_argument("native GR postops require non-null four-byte aligned pointers"); +} +void check_shape(int n, int hc) { + if (n <= 0 || hc <= 0 || std::uint64_t(n) * hc > std::uint64_t(std::numeric_limits::max())) + throw std::invalid_argument("native GR postops require positive bounded dimensions"); +} +unsigned blocks(std::size_t n) { return unsigned((n + THREADS - 1) / THREADS); } +void check_launch() { + const auto error = cudaGetLastError(); + if (error != cudaSuccess) + throw std::runtime_error(std::string("native GR postops launch: ") + cudaGetErrorString(error)); +} +} // namespace + +void native_gr_down_silu(float* lo, int hc_lr, int hc, void* stream) { + check_shape(hc_lr, hc); + check_pointer(lo); + down_silu<<(stream)>>>(lo, hc_lr, 1.0f / float(hc)); + check_launch(); +} +void native_gr_pre_gated(const float* xn, float* gate, float* mixed, + int n_embd, int hc, bool fused_layer, void* stream) { + check_shape(n_embd, hc); + check_pointer(xn); check_pointer(gate); check_pointer(mixed); + if (fused_layer) + pre_gated<<(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc)); + else + pre_gated<<(stream)>>>(xn, gate, mixed, n_embd, hc, 1.0f / float(hc)); + check_launch(); +} +void native_gr_post(const float* residual, const float* block_out, const float* inject, + float* output, int n_embd, int hc, void* stream) { + check_shape(n_embd, hc); + check_pointer(residual); check_pointer(block_out); check_pointer(inject); check_pointer(output); + post<<(stream)>>>( + residual, block_out, inject, output, n_embd, hc, 1.0f / float(hc)); + check_launch(); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_mmvq.cu b/engine/strata/src/kernels/cuda/native_mmvq.cu new file mode 100644 index 00000000..e0a4c1bd --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_mmvq.cu @@ -0,0 +1,1495 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh} +// and ggml/src/ggml-common.h. See docs/native-mmvq.md for exact scope. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/dp4a.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK = 256; +constexpr int Q8K = 32; +constexpr int QI = 32; +constexpr int VDR = 2; +constexpr int WARPS = 4; +constexpr int WARP = 32; +constexpr int QUANT_THREADS = 256; + +struct Q5KBlock { + half2 dm; + uint8_t scales[12]; + uint8_t qh[32]; + uint8_t qs[128]; +}; +struct Q81Block { + half2 ds; + int8_t qs[32]; +}; +struct Q20Block { + half d; + uint8_t qs[16]; +}; +struct Q3KBlock { + uint8_t hmask[32]; + uint8_t qs[64]; + uint8_t scales[12]; + half d; +}; +struct IQ4XSBlock { + half d; + uint16_t scales_h; + uint8_t scales_l[4]; + uint8_t qs[128]; +}; +struct Q4KBlock { + half2 dm; + uint8_t scales[12]; + uint8_t qs[128]; +}; +struct Q6KBlock { + uint8_t ql[128]; + uint8_t qh[64]; + int8_t scales[16]; + half d; +}; +struct Q40Block { + half d; + uint8_t qs[16]; +}; +struct Q50Block { + half d; + uint8_t qh[4]; + uint8_t qs[16]; +}; +struct Q80Block { + half d; + int8_t qs[32]; +}; +struct IQ4NLBlock { + half d; + uint8_t qs[16]; +}; +static_assert(sizeof(Q5KBlock) == 176 && alignof(Q5KBlock) == 4); +static_assert(sizeof(Q81Block) == 36 && alignof(Q81Block) == 4); +static_assert(sizeof(Q20Block) == 18 && alignof(Q20Block) == 2 && offsetof(Q20Block, qs) == 2); +static_assert(sizeof(Q3KBlock) == 110 && alignof(Q3KBlock) == 2 && offsetof(Q3KBlock, qs) == 32 && + offsetof(Q3KBlock, scales) == 96 && offsetof(Q3KBlock, d) == 108); +static_assert(sizeof(IQ4XSBlock) == 136 && alignof(IQ4XSBlock) == 2 && + offsetof(IQ4XSBlock, scales_h) == 2 && offsetof(IQ4XSBlock, scales_l) == 4 && + offsetof(IQ4XSBlock, qs) == 8); +static_assert(offsetof(Q5KBlock, scales) == 4 && offsetof(Q5KBlock, qh) == 16 && + offsetof(Q5KBlock, qs) == 48 && offsetof(Q81Block, qs) == 4); +static_assert(sizeof(Q4KBlock) == 144 && alignof(Q4KBlock) == 4 && + offsetof(Q4KBlock, scales) == 4 && offsetof(Q4KBlock, qs) == 16); +static_assert(sizeof(Q6KBlock) == 210 && alignof(Q6KBlock) == 2 && + offsetof(Q6KBlock, qh) == 128 && offsetof(Q6KBlock, scales) == 192 && + offsetof(Q6KBlock, d) == 208); +static_assert(sizeof(Q40Block) == 18 && alignof(Q40Block) == 2 && offsetof(Q40Block, qs) == 2); +static_assert(sizeof(Q50Block) == 22 && alignof(Q50Block) == 2 && + offsetof(Q50Block, qh) == 2 && offsetof(Q50Block, qs) == 6); +static_assert(sizeof(Q80Block) == 34 && alignof(Q80Block) == 2 && offsetof(Q80Block, qs) == 2); +static_assert(sizeof(IQ4NLBlock) == 18 && alignof(IQ4NLBlock) == 2 && offsetof(IQ4NLBlock, qs) == 2); + +__device__ __forceinline__ float warp_sum(float x) { +#pragma unroll + for (int offset = WARP / 2; offset > 0; offset >>= 1) { + x += __shfl_xor_sync(0xffffffff, x, offset, WARP); + } + return x; +} + +__device__ __forceinline__ float warp_max(float x) { +#pragma unroll + for (int offset = WARP / 2; offset > 0; offset >>= 1) { + x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, offset, WARP)); + } + return x; +} + +__launch_bounds__(QUANT_THREADS, 1) +__global__ void native_quantize_q8_1_kernel(const float* __restrict__ x, + Q81Block* __restrict__ y, int n_in) { + const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x); + if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return. + const float xi = x[i]; + const float amax = warp_max(fabsf(xi)); + const float sum = warp_sum(xi); + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + y[i / Q8K].qs[i % Q8K] = q; + if (i % Q8K == 0) y[i / Q8K].ds = make_half2(d, sum); +} + +// Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. +__device__ __forceinline__ float q5_q8_dot_impl( + const int* __restrict__ vl, const int* __restrict__ vh, const int* __restrict__ u, + const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm5, + const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int vl0i = (vl[0] >> (4 * i)) & 0x0f0f0f0f; + const int vl1i = (vl[1] >> (4 * i)) & 0x0f0f0f0f; + const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; + const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; + const int v0i = vl0i | vh0i; + const int v1i = vl1i | vh1i; + const int dot1 = STRATA_DP4A(v0i, u[2 * i], STRATA_DP4A(v1i, u[2 * i + 1], 0)); + const int dot2 = STRATA_DP4A(0x01010101, u[2 * i], STRATA_DP4A(0x01010101, u[2 * i + 1], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); + } + const float2 dm5f = __half22float2(dm5); + return dm5f.x * sumf_d - dm5f.y * sumf_m; +} + +__device__ __forceinline__ float q5_q8_dot(const Q5KBlock* __restrict__ bq5, + const Q81Block* __restrict__ bq8, int iqs) { + int vl[2]; + int vh[2]; + int u[4]; + float d8[2]; + const int bq8_offset = 2 * ((iqs / 2) / 4); + const int* ql = reinterpret_cast(bq5->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = reinterpret_cast(bq5->qh + 4 * ((iqs / 2) % 4)); + vl[0] = ql[0]; + vl[1] = ql[4]; + vh[0] = qh[0] >> bq8_offset; + vh[1] = qh[4] >> bq8_offset; + + const uint16_t* scales = reinterpret_cast(bq5->scales); + const int j = bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + uint16_t aux[2]; + aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | + ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | + ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + const uint8_t* sc = reinterpret_cast(aux); + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const Q81Block* bq8i = bq8 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); + u[2 * i] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return q5_q8_dot_impl(vl, vh, u, sc, m, bq5->dm, d8); +} + +// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K), +// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q5_k_mmvq_kernel(const Q5KBlock* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / QK; + float tmp[ROWS] = {}; + for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * (QK / Q8K); + const int kqs = VDR * (tid % (QI / VDR)); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + // The source assumes allocator padding for partial row groups. This + // guard preserves every valid row's math without an out-of-bounds read. + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += q5_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// Exact pinned vec_dot_q2_0_q8_1: each thread handles one 32-element chunk. +// The weight block is only 2-byte aligned, so qs is intentionally loaded as +// int16_t, unlike the naturally 4-byte aligned activation codes. +__device__ __forceinline__ float q2_q8_dot(const Q20Block* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + const float d2 = w->d; + const int16_t* qs = reinterpret_cast(w->qs) + iqs * 4; + const Q81Block* chunk = x + iqs; + const int* q8 = reinterpret_cast(chunk->qs); + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + const int u = q8[j * 2]; + const int v = q8[j * 2 + 1]; + const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0); + const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2); + const int qx = __byte_perm(qe, qo, 0x5140); + const int qy = __byte_perm(qe, qo, 0x7362); + sumi = STRATA_DP4A(u, qx, sumi); + sumi = STRATA_DP4A(v, qy, sumi); + } + const float d8 = __low2float(chunk->ds); + return d2 * d8 * sumi; +} + +// Q2_0 generic MMVQ: QK=64, QI=2, VDR=1, 64 blocks per iteration. +// Preserve the same outer accumulation and cross-warp reduction as the oracle. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q2_0_mmvq_kernel(const Q20Block* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = WARPS * WARP / 2; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / 64; + float tmp[ROWS] = {}; + for (int kbx = tid / 2; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * 2; + const int kqs = tid % 2; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += q2_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// Q3_K's 110-byte stride gives alternate blocks only two-byte alignment. +// Preserve the pinned helper's pair of 16-bit loads and little-endian combine. +__device__ __forceinline__ int load_int_b2(const void* ptr, int i32) { + const auto* x = static_cast(ptr); + int value = x[2 * i32] << 0; + value |= x[2 * i32 + 1] << 16; + return value; +} + +__device__ __forceinline__ float q3_q8_dot_impl(int vl, int vh, const int* __restrict__ u, + const uint8_t* __restrict__ scales, + int scale_offset, float d3, + const float* __restrict__ d8) { + float sumf = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int isc = scale_offset + 2 * i; + const int isc_low = isc % 8; + const int sc_shift_low = 4 * (isc / 8); + const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xf; + const int isc_high = isc % 4; + const int sc_shift_high = 2 * (isc / 4); + const int sc_high = ((scales[8 + isc_high] >> sc_shift_high) & 3) << 4; + const int sc = (sc_low | sc_high) - 32; + const int vil = (vl >> (2 * i)) & 0x03030303; + const int vih = ((vh >> i) << 2) & 0x04040404; + const int vi = __vsubss4(vil, vih); + sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc); + } + return d3 * sumf; +} + +__device__ __forceinline__ float q3_q8_dot(const Q3KBlock* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + const int bq8_offset = 4 * (iqs / 8); + const int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4; + const float d = w->d; + const int vl = load_int_b2(w->qs, iqs); + const int vh = ~load_int_b2(w->hmask, iqs % 8) >> bq8_offset; + int u[4]; + float d8[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + u[i] = reinterpret_cast(x[bq8_offset + i].qs)[iqs % 8]; + d8[i] = __low2float(x[bq8_offset + i].ds); + } + return q3_q8_dot_impl(vl, vh, u, w->scales, scale_offset, d, d8); +} + +// Q3_K generic MMVQ: QK=256, QI=16, VDR=1, eight blocks per iteration. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q3_k_mmvq_kernel(const Q3KBlock* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = WARPS * WARP / 16; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / 256; + float tmp[ROWS] = {}; + for (int kbx = tid / 16; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * 8; + const int kqs = tid % 16; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += q3_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// The pinned nonlinear IQ4 codebook and its CUDA two-stage byte lookup. The +// explicit alignment satisfies the four 32-bit table loads; values are unchanged. +__device__ __align__(4) int8_t iq4nl_values[16] = { + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 +}; + +__device__ __forceinline__ int2 iq4_table_lookup(int q4) { + const uint32_t* table32 = reinterpret_cast(iq4nl_values); + uint32_t tmp[2]; + const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1); +#pragma unroll + for (uint32_t i = 0; i < 2; ++i) { + const uint32_t shift = 16 * i; + const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift); + const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift); + tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); + } + return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); +} + +// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock, +// computes integer dot products, applies signed scale in the integer domain, +// then multiplies the two half scales and integer sum in the original order. +__device__ __forceinline__ float iq4_xs_q8_dot(const IQ4XSBlock* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int aux_q4 = reinterpret_cast(w->qs)[iqs + j]; + const int2 v = iq4_table_lookup(aux_q4); + const int u0 = reinterpret_cast(x[iqs / 4].qs)[j]; + const int u1 = reinterpret_cast(x[iqs / 4].qs)[j + 4]; + sumi = STRATA_DP4A(v.x, u0, sumi); + sumi = STRATA_DP4A(v.y, u1, sumi); + } + const int ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | + (((w->scales_h >> (iqs / 2)) & 0x03) << 4); + sumi *= ls - 32; + const float d = __half2float(w->d) * __low2float(x[iqs / 4].ds); + return d * sumi; +} + +// IQ4_XS generic MMVQ: QK=256, QI=32, VDR=4,16 blocks per iteration. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_iq4_xs_mmvq_kernel(const IQ4XSBlock* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = 4 * WARPS * WARP / 32; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / 256; + float tmp[ROWS] = {}; + for (int kbx = tid / 8; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * 8; + const int kqs = 4 * (tid % 8); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += iq4_xs_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// Exact pinned vec_dot_q4_K_q8_1_impl_vmmq expression and integer dot order. +__device__ __forceinline__ float q4_q8_dot_impl( + const int* __restrict__ v, const int* __restrict__ u, + const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm4, + const float* __restrict__ d8) { + float sumf_d = 0.0f; + float sumf_m = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v0i = (v[0] >> (4 * i)) & 0x0f0f0f0f; + const int v1i = (v[1] >> (4 * i)) & 0x0f0f0f0f; + const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1], STRATA_DP4A(v0i, u[2 * i], 0)); + const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1], STRATA_DP4A(0x01010101, u[2 * i], 0)); + sumf_d += d8[i] * (dot1 * sc[i]); + sumf_m += d8[i] * (dot2 * m[i]); + } + const float2 dm4f = __half22float2(dm4); + return dm4f.x * sumf_d - dm4f.y * sumf_m; +} + +__device__ __forceinline__ float q4_q8_dot(const Q4KBlock* __restrict__ bq4, + const Q81Block* __restrict__ bq8, int iqs) { + int v[2]; + int u[4]; + float d8[2]; + const int bq8_offset = 2 * ((iqs / 2) / 4); + const int* ql = reinterpret_cast(bq4->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4)); + v[0] = ql[0]; + v[1] = ql[4]; + + const uint16_t* scales = reinterpret_cast(bq4->scales); + const int j = bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + uint16_t aux[2]; + aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | + ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | + ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + const uint8_t* sc = reinterpret_cast(aux); + const uint8_t* m = sc + 2; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const Q81Block* bq8i = bq8 + bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); + u[2 * i] = q8[0]; + u[2 * i + 1] = q8[4]; + } + return q4_q8_dot_impl(v, u, sc, m, bq4->dm, d8); +} + +// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K), +// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q4_k_mmvq_kernel(const Q4KBlock* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / QK; + float tmp[ROWS] = {}; + for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * (QK / Q8K); + const int kqs = VDR * (tid % (QI / VDR)); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + // The source assumes allocator padding for partial row groups. This + // guard preserves every valid row's math without an out-of-bounds read. + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += q4_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// Exact pinned vec_dot_q6_K_q8_1: keep signed per-16-element scales, +// signed-byte subtraction, DP4A order, and the float accumulation sequence. +__device__ __forceinline__ float q6_q8_dot_impl(int vl, int vh, const int* __restrict__ u, + const int8_t* __restrict__ scales, + float d, const float* __restrict__ d8) { + float sumf = 0.0f; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int sc = scales[4 * i]; + const int vil = (vl >> (4 * i)) & 0x0f0f0f0f; + const int vih = ((vh >> (4 * i)) << 4) & 0x30303030; + const int vi = __vsubss4(vil | vih, 0x20202020); + sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc); + } + return d * sumf; +} + +__device__ __forceinline__ float q6_q8_dot(const Q6KBlock* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + const int vh_shift = 2 * ((iqs % 16) / 8); + const int vl = load_int_b2(w->ql, iqs); + const int vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift; + int u[2]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + u[i] = reinterpret_cast(x[bq8_offset + 2 * i].qs)[iqs % 8]; + d8[i] = __low2float(x[bq8_offset + 2 * i].ds); + } + return q6_q8_dot_impl(vl, vh, u, w->scales + scale_offset, w->d, d8); +} + +// Q6_K generic MMVQ: QK=256, QI=32, VDR=1, four blocks per iteration. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_q6_k_mmvq_kernel(const Q6KBlock* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = WARPS * WARP / 32; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / 256; + float tmp[ROWS] = {}; + for (int kbx = tid / 32; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kby = kbx * 8; + const int kqs = tid % 32; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += q6_q8_dot(w + block, x + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// The four 32-element formats use native two-byte loads and VDR=2. The affine +// Q4_0/Q5_0 correction consumes the original-input sum stored in Q8_1, exactly +// as the pinned CUDA dot does; a signed-integer code substitution would differ. +__device__ __forceinline__ float small_q8_dot(const Q40Block* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + int sumi = 0; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v = load_int_b2(w->qs, iqs + i); + const int vi0 = (v >> 0) & 0x0f0f0f0f; + const int vi1 = (v >> 4) & 0x0f0f0f0f; + sumi = STRATA_DP4A(vi0, reinterpret_cast(x->qs)[iqs + i], sumi); + sumi = STRATA_DP4A(vi1, reinterpret_cast(x->qs)[iqs + i + 4], sumi); + } + const float2 ds = __half22float2(x->ds); + const float d = w->d; + return d * (sumi * ds.x - 4 * ds.y); +} + +__device__ __forceinline__ float small_q8_dot(const Q50Block* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + int sumi = 0; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int vl = load_int_b2(w->qs, iqs + i); + const int vh = load_int_b2(w->qh, 0) >> (4 * (iqs + i)); + int vi0 = (vl >> 0) & 0x0f0f0f0f; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + sumi = STRATA_DP4A(vi0, reinterpret_cast(x->qs)[iqs + i], sumi); + int vi1 = (vl >> 4) & 0x0f0f0f0f; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; + sumi = STRATA_DP4A(vi1, reinterpret_cast(x->qs)[iqs + i + 4], sumi); + } + const float2 ds = __half22float2(x->ds); + const float d = w->d; + return d * (sumi * ds.x - 8 * ds.y); +} + +__device__ __forceinline__ float small_q8_dot(const Q80Block* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + int sumi = 0; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int v = load_int_b2(w->qs, iqs + i); + const int u = reinterpret_cast(x->qs)[iqs + i]; + sumi = STRATA_DP4A(v, u, sumi); + } + const float d0 = w->d; + const float d1 = __low2float(x->ds); + return d0 * d1 * float(sumi); +} + +__device__ __forceinline__ float small_q8_dot(const IQ4NLBlock* __restrict__ w, + const Q81Block* __restrict__ x, int iqs) { + const int* q8 = reinterpret_cast(x->qs) + iqs; + int sumi = 0; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const int2 v = iq4_table_lookup(load_int_b2(w->qs, iqs + i)); + sumi = STRATA_DP4A(v.x, q8[i], sumi); + sumi = STRATA_DP4A(v.y, q8[i + 4], sumi); + } + const float d = __half2float(w->d) * __low2float(x->ds); + return d * sumi; +} + +// QI=4 for Q4_0/Q5_0/IQ4_NL and QI=8 for Q8_0. With VDR=2 this preserves +// the pinned 64/32-block iteration and 2048/1024-element small-K thresholds. +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_small_mmvq_kernel(const Weight* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int ROWS = SmallK ? WARPS : 1; + constexpr int BLOCKS_PER_ITER = 2 * WARPS * WARP / Qi; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / 32; + float tmp[ROWS] = {}; + for (int kbx = tid / (Qi / 2); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) { + const int kqs = 2 * (tid % (Qi / 2)); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + tmp[i] += small_q8_dot(w + block, x + kbx, kqs); + } + } + } + __shared__ float partial[WARPS - 1][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x]; + tmp[i] = warp_sum(tmp[i]); + if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i]; + } +} + +// ============================ plan v0.3 P3: ncols = 2..8 (speculative verify, small batches) ============================ +// +// One generic kernel for every format, parameterized by the format's iteration traits below, which are +// transcribed from the ncols = 1 kernels above (same thread-to-block mapping, same blocks per iteration, same +// small-K rule). Column j reads activation blocks x + j * (n_in / 32) and writes y + j * n_out. Each (column, +// row) value is accumulated over kbx in the same order, summed across warps in the same order and reduced with +// the same warp tree as the ncols = 1 kernel, so every column is BITWISE equal to a single-column call on that +// column (checked by bench/micro/native_mmvq_multi.cpp). The ncols = 1 kernels are untouched. +constexpr int MAX_NCOLS = 8; + +// Each format splits its dot product into `load` (everything that depends only on the weight block: codes, +// unpacked scales, block scale) and `apply` (the activation loads and the original *_impl expression). `load` runs +// once per (row, block) and `apply` once per column, so adding columns adds only activation work. `apply` calls +// the same impl functions, in the same order, with the same values as the ncols = 1 dot, which is what keeps +// every column bitwise equal to it. +struct Q5KTraits { + using Block = Q5KBlock; + static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; + __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } + struct W { int vl[2], vh[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; + __device__ static W load(const Block* __restrict__ bq5, int iqs) { + W r; + r.bq8_offset = 2 * ((iqs / 2) / 4); + const int* ql = reinterpret_cast(bq5->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)); + const int* qh = reinterpret_cast(bq5->qh + 4 * ((iqs / 2) % 4)); + r.vl[0] = ql[0]; + r.vl[1] = ql[4]; + r.vh[0] = qh[0] >> r.bq8_offset; + r.vh[1] = qh[4] >> r.bq8_offset; + const uint16_t* scales = reinterpret_cast(bq5->scales); + const int j = r.bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + r.dm = bq5->dm; + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) { + int u[4]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const Q81Block* bq8i = bq8 + r.bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); + u[2 * i] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = reinterpret_cast(r.aux); + return q5_q8_dot_impl(r.vl, r.vh, u, sc, sc + 2, r.dm, d8); + } +}; +struct Q4KTraits { + using Block = Q4KBlock; + static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI; + __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); } + struct W { int v[2]; uint16_t aux[2]; half2 dm; int bq8_offset; }; + __device__ static W load(const Block* __restrict__ bq4, int iqs) { + W r; + r.bq8_offset = 2 * ((iqs / 2) / 4); + const int* ql = reinterpret_cast(bq4->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)); + r.v[0] = ql[0]; + r.v[1] = ql[4]; + const uint16_t* scales = reinterpret_cast(bq4->scales); + const int j = r.bq8_offset / 2; + const int jm = j & 1; + const uint32_t s0 = scales[jm]; + const uint32_t s2 = scales[jm + 2]; + const uint32_t s4 = scales[jm + 4]; + const uint32_t hi = uint32_t(-int32_t(j >= 2)); + r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi)); + r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi)); + r.dm = bq4->dm; + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) { + int u[4]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const Q81Block* bq8i = bq8 + r.bq8_offset + i; + d8[i] = __low2float(bq8i->ds); + const int* q8 = reinterpret_cast(bq8i->qs) + ((iqs / 2) % 4); + u[2 * i] = q8[0]; + u[2 * i + 1] = q8[4]; + } + const uint8_t* sc = reinterpret_cast(r.aux); + return q4_q8_dot_impl(r.v, u, sc, sc + 2, r.dm, d8); + } +}; +struct Q20Traits { + using Block = Q20Block; + static constexpr int DIV = 64, T = 2, KBY = 2, BPI = WARPS * WARP / 2; + __device__ static int kqs(int tid) { return tid % 2; } + struct W { int qx[4], qy[4]; float d2; }; + __device__ static W load(const Block* __restrict__ w, int iqs) { + W r; + r.d2 = w->d; + const int16_t* qs = reinterpret_cast(w->qs) + iqs * 4; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int q = qs[j]; + const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0); + const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2); + r.qx[j] = __byte_perm(qe, qo, 0x5140); + r.qy[j] = __byte_perm(qe, qo, 0x7362); + } + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { + const Q81Block* chunk = x + iqs; + const int* q8 = reinterpret_cast(chunk->qs); + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi = STRATA_DP4A(q8[j * 2], r.qx[j], sumi); + sumi = STRATA_DP4A(q8[j * 2 + 1], r.qy[j], sumi); + } + const float d8 = __low2float(chunk->ds); + return r.d2 * d8 * sumi; + } +}; +struct Q3KTraits { + using Block = Q3KBlock; + static constexpr int DIV = 256, T = 16, KBY = 8, BPI = WARPS * WARP / 16; + __device__ static int kqs(int tid) { return tid % 16; } + struct W { int vl, vh; float d; const uint8_t* scales; int scale_offset, bq8_offset; }; + __device__ static W load(const Block* __restrict__ w, int iqs) { + W r; + r.bq8_offset = 4 * (iqs / 8); + r.scale_offset = iqs - iqs % 8 + (iqs % 8) / 4; + r.d = w->d; + r.vl = load_int_b2(w->qs, iqs); + r.vh = ~load_int_b2(w->hmask, iqs % 8) >> r.bq8_offset; + r.scales = w->scales; + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { + int u[4]; + float d8[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + u[i] = reinterpret_cast(x[r.bq8_offset + i].qs)[iqs % 8]; + d8[i] = __low2float(x[r.bq8_offset + i].ds); + } + return q3_q8_dot_impl(r.vl, r.vh, u, r.scales, r.scale_offset, r.d, d8); + } +}; +struct Q6KTraits { + using Block = Q6KBlock; + static constexpr int DIV = 256, T = 32, KBY = 8, BPI = WARPS * WARP / 32; + __device__ static int kqs(int tid) { return tid % 32; } + struct W { int vl, vh; float d; const int8_t* scales; int bq8_offset; }; + __device__ static W load(const Block* __restrict__ w, int iqs) { + W r; + r.bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + const int vh_shift = 2 * ((iqs % 16) / 8); + r.vl = load_int_b2(w->ql, iqs); + r.vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift; + r.scales = w->scales + scale_offset; + r.d = w->d; + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { + int u[2]; + float d8[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + u[i] = reinterpret_cast(x[r.bq8_offset + 2 * i].qs)[iqs % 8]; + d8[i] = __low2float(x[r.bq8_offset + 2 * i].ds); + } + return q6_q8_dot_impl(r.vl, r.vh, u, r.scales, r.d, d8); + } +}; +struct IQ4XSTraits { + using Block = IQ4XSBlock; + static constexpr int DIV = 256, T = 8, KBY = 8, BPI = 4 * WARPS * WARP / 32; + __device__ static int kqs(int tid) { return 4 * (tid % 8); } + struct W { int2 v[4]; int ls; float dw; }; + __device__ static W load(const Block* __restrict__ w, int iqs) { + W r; +#pragma unroll + for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(reinterpret_cast(w->qs)[iqs + j]); + r.ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | (((w->scales_h >> (iqs / 2)) & 0x03) << 4); + r.dw = __half2float(w->d); + return r; + } + __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) { + int sumi = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int u0 = reinterpret_cast(x[iqs / 4].qs)[j]; + const int u1 = reinterpret_cast(x[iqs / 4].qs)[j + 4]; + sumi = STRATA_DP4A(r.v[j].x, u0, sumi); + sumi = STRATA_DP4A(r.v[j].y, u1, sumi); + } + sumi *= r.ls - 32; + const float d = r.dw * __low2float(x[iqs / 4].ds); + return d * sumi; + } +}; +// The four 32-element formats: `load` keeps the block pointer (their decode is a few integer ops) and `apply` is +// the unchanged small_q8_dot. Their per-column cost is small; the win above is for the K and IQ formats. +template +struct SmallTraits { + using Block = Weight; + static constexpr int DIV = 32, T = Qi / 2, KBY = 1, BPI = 2 * WARPS * WARP / Qi; + __device__ static int kqs(int tid) { return 2 * (tid % (Qi / 2)); } + struct W { const Weight* w; }; + __device__ static W load(const Block* __restrict__ w, int) { return W{w}; } + __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int k) { return small_q8_dot(r.w, x, k); } +}; + +// NW warps per block and ROWS rows per block. The EXACT layout (NW = 4, ROWS = 1, or 4 for small K) is the +// ncols = 1 layout and keeps every column bitwise equal to a single-column call. The UPSTREAM layout is +// llama.cpp's generic multi-column table (ncols 2-4: 4 warps; 5-8: 2 warps; always 2 rows per block): faster, +// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently). +bool g_multi_exact = true; // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured) + +template +__launch_bounds__(NW * WARP, 1) +__global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, + const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int BPI = F::BPI * NW / WARPS; // blocks per iteration scale with the warp count + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * int(blockIdx.x); + const int blocks_per_row = n_in / F::DIV; + const int x_stride = n_in / Q8K; // Q8_1 blocks per activation column + float tmp[NCOLS][ROWS] = {}; + for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += BPI) { + const int kby = kbx * F::KBY; + const int kqs = F::kqs(tid); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx; + const typename F::W wv = F::load(w + block, kqs); // once per (row, block) +#pragma unroll + for (int j = 0; j < NCOLS; ++j) // then per column + tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs); + } + } + } + __shared__ float partial[NW - 1 > 0 ? NW - 1 : 1][NCOLS][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; + tmp[j][i] = warp_sum(tmp[j][i]); + if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i]; + } + } +} + +template +void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) { + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + if (!g_multi_exact) { + constexpr int NW = NCOLS <= 4 ? 4 : 2; + const unsigned blocks = unsigned((std::size_t(n_out) + 1) / 2); + native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + return; + } + const dim3 threads(WARP, WARPS); + if (n_in / F::DIV < F::BPI) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_mmvq_multi_kernel<<>>(w, x, y, n_in, n_out); + } +} + +template +void launch_multi(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, + void* stream) { + const auto s = static_cast(stream); + switch (ncols) { + case 2: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 3: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 4: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 5: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 6: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 7: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 8: launch_multi_n(weights, x_q8_1, y, n_in, n_out, s); break; + default: throw std::invalid_argument("native MMVQ multi-column launch requires 2 <= ncols <= 8"); + } +} + +void validate_shape(int n_in, int ncols, int block_elems = Q8K) { + if (n_in <= 0 || n_in % block_elems != 0) { + throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count"); + } + if (ncols < 1 || ncols > MAX_NCOLS) throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); +} +void validate_pointer(const void* p) { + if (!p || reinterpret_cast(p) % 4 != 0) { + throw std::invalid_argument("native MMVQ requires non-null 4-byte aligned device pointers"); + } +} +void validate_stream(void* stream) { + if (!stream) throw std::invalid_argument("native MMVQ requires an explicit non-null CUDA stream"); +} +void launch_check() { + const auto error = cudaGetLastError(); + if (error != cudaSuccess) { + throw std::runtime_error(std::string("native MMVQ launch: ") + cudaGetErrorString(error)); + } +} + +template +void small_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 32); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi>(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 32 < 2 * WARPS * WARP / Qi) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_small_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_small_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +template +void small_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 32); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + small_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +} // namespace + +void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; } +bool native_mmvq_multi_exact() { return g_multi_exact; } + +std::size_t native_q8_1_bytes(int n_in, int ncols) { + validate_shape(n_in, ncols); + return std::size_t(ncols) * std::size_t(n_in / Q8K) * sizeof(Q81Block); +} + +void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, void* stream) { + validate_shape(n_in, ncols); + validate_pointer(x); + validate_pointer(x_q8_1); + validate_stream(stream); + // Columns are contiguous and n_in is a multiple of 32, so ncols columns quantize as one vector of + // ncols * n_in elements: every 32-element block stays inside one column. + const int n_total = n_in * ncols; + const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS); + native_quantize_q8_1_kernel<<(stream)>>>(x, static_cast(x_q8_1), n_total); + launch_check(); +} + +void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, QK); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / QK < VDR * WARPS * WARP / QI) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_q5_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_q5_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + // Validate all outputs before enqueueing the first operation. + validate_shape(n_in, ncols, QK); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_q5_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 64); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 64 < WARPS * WARP / 2) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_q2_0_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_q2_0_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 64); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_q2_0_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 256 < WARPS * WARP / 16) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_q3_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_q3_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_q3_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 256 < 4 * WARPS * WARP / 32) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_iq4_xs_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_iq4_xs_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_iq4_xs_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 256 < WARPS * WARP / 16) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_q4_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_q4_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_q4_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x_q8_1); + validate_pointer(y); + validate_stream(stream); + if (ncols > 1) { + launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); + launch_check(); + return; + } + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + const auto s = static_cast(stream); + const dim3 threads(WARP, WARPS); + if (n_in / 256 < WARPS * WARP / 32) { + const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS); + native_q6_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } else { + native_q6_k_mmvq_kernel<<>>(w, x, y, n_in, n_out); + } + launch_check(); +} + +void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + validate_shape(n_in, ncols, 256); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + validate_pointer(weights); + validate_pointer(x); + validate_pointer(scratch_q8_1); + validate_pointer(y); + validate_stream(stream); + native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream); + native_q6_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + small_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); +} + +void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1, + float* y, int n_in, int n_out, int ncols, void* stream) { + small_f32(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream); +} + +bool native_mmvq_supported(int ggml_type) noexcept { + return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 || + ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || + ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || + ggml_type == 21 || ggml_type == 22 || ggml_type == 29; +} + +std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { + int block_elems, block_bytes; + switch (ggml_type) { + case 2: block_elems = 32; block_bytes = 18; break; + case 6: block_elems = 32; block_bytes = 22; break; + case 7: block_elems = 32; block_bytes = 24; break; + case 8: block_elems = 32; block_bytes = 34; break; + case 20: block_elems = 32; block_bytes = 18; break; + case 11: block_elems = 256; block_bytes = 110; break; + case 12: block_elems = 256; block_bytes = 144; break; + case 13: block_elems = 256; block_bytes = 176; break; + case 14: block_elems = 256; block_bytes = 210; break; + case 23: block_elems = 256; block_bytes = 136; break; + case 42: block_elems = 64; block_bytes = 18; break; + case 16: case 17: case 18: case 21: case 22: case 29: + block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break; + default: throw std::invalid_argument("unsupported native MMVQ GGML type"); + } + validate_shape(n_in, 1, block_elems); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + const std::size_t row_bytes = std::size_t(n_in / block_elems) * block_bytes; + if (row_bytes > std::numeric_limits::max() / std::size_t(n_out)) { + throw std::length_error("native MMVQ weight byte count overflows size_t"); + } + return row_bytes * std::size_t(n_out); +} + +void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y, + int n_in, int n_out, int ncols, void* stream) { + switch (ggml_type) { + case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 12: native_q4_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 13: native_q5_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 14: native_q6_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 23: native_iq4_xs_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 42: native_q2_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + case 16: case 17: case 18: case 21: case 22: case 29: + iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; + default: throw std::invalid_argument("unsupported native MMVQ GGML type"); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_moe.cu b/engine/strata/src/kernels/cuda/native_moe.cu new file mode 100644 index 00000000..7f1f91ce --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_moe.cu @@ -0,0 +1,86 @@ +// Arithmetic adapted from the MIT-licensed pinned ggml CUDA +// moe-weighted-reduction.cu at 3cf03257f219afbe7334045ff7c6a06ac68c627d. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "strata/kernels/native_moe.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +__global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights, + const float* __restrict__ shared, float* __restrict__ output, + int64_t n_embd, int k) { + // blockIdx.y = the token of a multi-token launch (0 for the single one) + const int64_t tk = blockIdx.y; + parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd; + const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (col >= n_embd) return; + float sum = parts[col] * weights[0]; + for (int expert = 1; expert < k; ++expert) { + sum += parts[int64_t(expert) * n_embd + col] * weights[expert]; + } + if (shared) sum += shared[col]; + output[col] = sum; +} +bool valid_span(const void* p, size_t bytes) { + const auto address = reinterpret_cast(p); + return p && address % alignof(float) == 0 && bytes <= UINTPTR_MAX - address; +} +bool overlap(const void* a, size_t an, const void* b, size_t bn) { + const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); + return ap < bp + bn && bp < ap + an; +} +} +void native_moe_combine_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_moe_combine_enabled() { return enabled.load(std::memory_order_relaxed); } +void native_moe_combine(const float* parts, const float* weights, const float* shared, + float* output, int64_t n_embd, int64_t k, void* stream) { + if (!stream || n_embd <= 0 || n_embd > std::numeric_limits::max() || k < 1 || k > 15) + throw std::invalid_argument("native MoE combine requires a stream, positive width and 1..15 experts"); + const size_t row_bytes = size_t(n_embd) * sizeof(float); + const size_t part_bytes = row_bytes * size_t(k), weight_bytes = size_t(k) * sizeof(float); + if (!valid_span(parts, part_bytes) || !valid_span(weights, weight_bytes) || !valid_span(output, row_bytes) + || (shared && !valid_span(shared, row_bytes)) + || overlap(output, row_bytes, parts, part_bytes) + || overlap(output, row_bytes, weights, weight_bytes) + || (shared && overlap(output, row_bytes, shared, row_bytes))) + throw std::invalid_argument("native MoE combine requires aligned spans and disjoint output"); + combine<<(stream)>>>( + parts, weights, shared, output, n_embd, int(k)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output, + int64_t n_embd, int64_t k, int n_tok, void* stream) { + if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1) + throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens"); + combine<<(stream)>>>( + parts, weights, shared, output, n_embd, int(k)); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} diff --git a/engine/strata/src/kernels/cuda/native_ple_postops.cu b/engine/strata/src/kernels/cuda/native_ple_postops.cu new file mode 100644 index 00000000..922ae0a8 --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_ple_postops.cu @@ -0,0 +1,221 @@ +// Arithmetic adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// src/models/qwen4exp.cpp and ggml-cuda/{reduce_rows.cuh,sumrows.cu,unary.cu}. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_ple_postops.hpp" +#include "strata/kernels/native_gr_norm.hpp" +#include "strata/kernels/ngram.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +constexpr int N = 2560, H = 4, D = N * H, HISTORY = 9; +__device__ float warp_sum(float x) { + for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset); + return x; +} +__global__ void gate_kernel(const float* key, const float* query, float* gate, float scale) { + // SUM_ROWS selects 512 threads for four rows on the target GPU. Preserve + // its eight partial lanes and materialized MUL rounding (never a dot FMA). + float sums[8] = {}; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = threadIdx.x + j * 512; + const float p = d < N ? __fmul_rn(key[blockIdx.x * N + d], query[blockIdx.x * N + d]) : 0.0f; + sums[j] += p; + } + float sum = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) sum += sums[j]; + __shared__ float partials[32]; + sum = warp_sum(sum); + const int lane = threadIdx.x % 32; + if (!lane) partials[threadIdx.x / 32] = sum; + __syncthreads(); + sum = lane < 16 ? partials[lane] : 0.0f; + sum = warp_sum(sum); + if (threadIdx.x == 0) { + const float s = __fmaf_rn(scale, sum, 0.0f); // ggml SCALE's zero bias + const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f)); + const float sign = float((s > 0.0f) - (s < 0.0f)); + gate[blockIdx.x] = 1.0f / (1.0f + expf(-__fmul_rn(sign, mag))); + } +} +__global__ void broadcast_kernel(const float* value, const float* gate, float* gated) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < D) gated[i] = __fmul_rn(value[i % N], gate[i / N]); +} +__global__ void conv_residual_kernel(const float* history, const float* normalized, + const uint16_t* weights, const float* hidden, + const float* gated, float* conv, float* result) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= D) return; + float sum = 0; +#pragma unroll + for (int k = 0; k < 4; ++k) { + const float x = k == 3 ? normalized[c] : history[c * HISTORY + 3 * k]; + const float w = __half2float(__ushort_as_half(weights[c * 4 + k])); + const float term = __fmul_rn(x, w); + sum = k == 0 ? term : __fadd_rn(sum, term); + } + const float activation = sum / (1.0f + expf(-sum)); + conv[c] = activation; + // Exact hidden/result alias is safe: each thread owns one element. + result[c] = __fadd_rn(hidden[c], __fadd_rn(gated[c], activation)); +} +// ---- the batch: T tokens, the same arithmetic per element as the kernels above +// weighted_rms_norm (native_gr_norm.cu) with the gamma row repeating every H rows (one token's H groups) +__device__ float norm_warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + return value; +} +__global__ void rms_rep_kernel(const float* __restrict__ input, const float* __restrict__ gamma, + float* __restrict__ output) { + constexpr int BlockSize = 1024; // native_gr_rms_norm_weighted's choice for 2560 columns + const int tid = threadIdx.x; + const size_t row_offset = size_t(blockIdx.x) * N; + input += row_offset; + output += row_offset; + gamma += size_t(blockIdx.x % H) * N; + float partial = 0.0f; + for (int col = tid; col < N; col += BlockSize) { + const float value = input[col]; + partial += value * value; + } + __shared__ float sums[32]; + partial = norm_warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + __syncthreads(); + partial = 0.0f; + if (lane < BlockSize / 32) partial = sums[lane]; + partial = norm_warp_sum(partial); + const float mean = partial / N; + const float scale = rsqrtf(mean + NG_RMS_EPS); + for (int col = tid; col < N; col += BlockSize) output[col] = scale * input[col] * gamma[col]; +} +__global__ void broadcast_batch_kernel(const float* value, const float* gate, float* gated, int T) { + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= size_t(T) * D) return; + const size_t t = i / D, d = i % D; + gated[i] = __fmul_rn(value[t * N + d % N], gate[t * H + d / N]); +} +// the dilated conv (taps 9, 6, 3 tokens back and this one) and the residual; a tap before the chunk reads the history +__global__ void conv_residual_batch_kernel(const float* history, const float* normalized, const uint16_t* weights, + float* hidden, const float* gated, int T) { + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= size_t(T) * D) return; + const int t = int(i / D), c = int(i % D); + float sum = 0; +#pragma unroll + for (int k = 0; k < 4; ++k) { + const int p = t - 9 + 3 * k; // the token this tap reads (k == 3: this one) + const float x = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (9 + p)]; + const float wk = __half2float(__ushort_as_half(weights[c * 4 + k])); + const float term = __fmul_rn(x, wk); + sum = k == 0 ? term : __fadd_rn(sum, term); + } + const float activation = sum / (1.0f + expf(-sum)); + hidden[i] = __fadd_rn(hidden[i], __fadd_rn(gated[i], activation)); +} +// the history after the chunk: the last nine normalized rows (older ones from the history when T < 9) +__global__ void history_batch_kernel(float* history, const float* normalized, int T) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= D) return; + float h[HISTORY]; +#pragma unroll + for (int r = 0; r < HISTORY; ++r) { + const int p = T - HISTORY + r; + h[r] = p >= 0 ? normalized[size_t(p) * D + c] : history[size_t(c) * HISTORY + (T + r)]; + } +#pragma unroll + for (int r = 0; r < HISTORY; ++r) history[size_t(c) * HISTORY + r] = h[r]; +} + +struct Span { const void* p; size_t bytes; size_t alignment; }; +bool overlaps(Span a, Span b) { + const auto x = reinterpret_cast(a.p), y = reinterpret_cast(b.p); + return x < y + b.bytes && y < x + a.bytes; +} +void validate(Span span) { + const auto p = reinterpret_cast(span.p); + if (!p || p % span.alignment || p > std::numeric_limits::max() - span.bytes) + throw std::invalid_argument("native PLE postops require nonnull aligned bounded spans"); +} +void launch_check() { + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(std::string("native PLE postops launch: ") + cudaGetErrorString(error)); +} +} // namespace + +void native_ple_postops(const float* projected_key, const float* hidden, + const float* value, const float* history, + const PleWeights& w, const NativePlePostopsBuffers& b, void* stream) { + if (!stream) throw std::invalid_argument("native PLE postops require an explicit stream"); + const Span inputs[] = {{projected_key,D*4,4}, {hidden,D*4,4}, {value,N*4,4}, + {history,HISTORY*D*4,4}, {w.norm_key,D*4,4}, {w.norm_query,D*4,4}, + {w.norm_conv,D*4,4}, {w.conv1d_f16,4*D*2,2}}; + const Span outputs[] = {{b.key,D*4,4}, {b.query,D*4,4}, {b.gate,H*4,4}, + {b.gated,D*4,4}, {b.normalized,D*4,4}, {b.conv,D*4,4}, {b.result,D*4,4}}; + for (const auto& span : inputs) validate(span); + for (const auto& span : outputs) validate(span); + for (size_t i = 0; i < 7; ++i) { + for (size_t j = 0; j < 8; ++j) + if (!(i == 6 && j == 1 && b.result == hidden) && overlaps(outputs[i], inputs[j])) + throw std::invalid_argument("native PLE postops output overlaps an input or weight"); + for (size_t j = i + 1; j < 7; ++j) + if (!(i == 1 && j == 4 && b.query == b.normalized) && overlaps(outputs[i], outputs[j])) + throw std::invalid_argument("native PLE postops writable spans overlap"); + } + native_gr_rms_norm_weighted(projected_key,w.norm_key,b.key,N,H,NG_RMS_EPS,stream); + native_gr_rms_norm_weighted(hidden,w.norm_query,b.query,N,H,NG_RMS_EPS,stream); + auto st = static_cast(stream); + gate_kernel<<>>(b.key,b.query,b.gate,1.0f / std::sqrt(float(N))); + broadcast_kernel<<>>(value,b.gate,b.gated); + launch_check(); + native_gr_rms_norm_weighted(b.gated,w.norm_conv,b.normalized,N,H,NG_RMS_EPS,stream); + conv_residual_kernel<<>>(history,b.normalized,w.conv1d_f16,hidden,b.gated,b.conv,b.result); + launch_check(); +} + +void native_ple_postops_batch(float* key, float* hidden, const float* value, float* history, const PleWeights& w, + float* query_norm, float* gated, float* gate, int T, void* stream) { + if (!stream || T <= 0 || !key || !hidden || !value || !history || !query_norm || !gated || !gate) + throw std::invalid_argument("native PLE postops batch: null input or empty batch"); + auto st = static_cast(stream); + const unsigned rows = unsigned(T) * H; + const unsigned blocks = unsigned((size_t(T) * D + 255) / 256); + rms_rep_kernel<<>>(key, w.norm_key, key); + rms_rep_kernel<<>>(hidden, w.norm_query, query_norm); + gate_kernel<<>>(key, query_norm, gate, 1.0f / std::sqrt(float(N))); + broadcast_batch_kernel<<>>(value, gate, gated, T); + rms_rep_kernel<<>>(gated, w.norm_conv, query_norm); + conv_residual_batch_kernel<<>>(history, query_norm, w.conv1d_f16, hidden, gated, T); + history_batch_kernel<<>>(history, query_norm, T); + launch_check(); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_qsa.cu b/engine/strata/src/kernels/cuda/native_qsa.cu new file mode 100644 index 00000000..32e2511c --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_qsa.cu @@ -0,0 +1,127 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu}. +// +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_qsa.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +__device__ __forceinline__ float warp_sum(float value) { +#pragma unroll + for (int offset = 16; offset; offset >>= 1) + value += __shfl_xor_sync(0xffffffffu, value, offset, 32); + return value; +} +template +__global__ void norm(const float* input, const float* __restrict__ gamma, float* output, + int n_cols, float epsilon) { + const int tid = threadIdx.x; + const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols; + input += row_offset; output += row_offset; + float partial = 0.0f; + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) { + const float x = input[col]; + partial += x * x; + } + __shared__ float sums[32]; + partial = warp_sum(partial); + const int lane = tid % 32; + if (lane == 0) sums[tid / 32] = partial; + // All reads of input for the reduction precede this barrier. Afterwards, + // each thread reads/writes only its own elements, allowing exact in-place use. + __syncthreads(); + partial = lane < BlockSize / 32 ? sums[lane] : 0.0f; + partial = warp_sum(partial); + const float mean = partial / n_cols; + const float scale = rsqrtf(mean + epsilon); + for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) + output[col] = scale * input[col] * gamma[col]; +} +__global__ void gate(const float* attn, const float* __restrict__ q_full, float* output, + int n_head, int head_dim) { + const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= std::size_t(n_head) * head_dim) return; + const std::size_t head = i / head_dim, channel = i % head_dim; + const float raw = q_full[head * 2 * head_dim + head_dim + channel]; + const float sigmoid = 1.0f / (1.0f + expf(-raw)); + output[i] = attn[i] * sigmoid; +} +std::size_t elements(int cols, int rows) { + if (cols <= 0 || rows <= 0 || std::uint64_t(cols) * rows > std::uint64_t(std::numeric_limits::max())) + throw std::invalid_argument("native QSA requires positive bounded dimensions"); + return std::size_t(cols) * rows; +} +bool valid(const void* ptr, std::size_t bytes) { + const auto address = reinterpret_cast(ptr); + return ptr && address % 4 == 0 && bytes <= UINTPTR_MAX - address; +} +bool overlap(const void* a, std::size_t an, const void* b, std::size_t bn) { + const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); + return ap < bp + bn && bp < ap + an; +} +void buffers(const float* input, std::size_t in_bytes, const float* weight, std::size_t weight_bytes, + float* output, void* stream) { + if (!stream || !valid(input, in_bytes) || !valid(weight, weight_bytes) || !valid(output, in_bytes) || + overlap(input, in_bytes, weight, weight_bytes) || overlap(output, in_bytes, weight, weight_bytes) || + (input != output && overlap(input, in_bytes, output, in_bytes))) + throw std::invalid_argument("native QSA requires a stream, aligned spans, and disjoint buffers or exact input/output alias"); +} +void check_launch() { + const auto result = cudaGetLastError(); + if (result != cudaSuccess) + throw std::runtime_error(std::string("native QSA launch: ") + cudaGetErrorString(result)); +} +} // namespace + +void native_qsa_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_qsa_enabled() { return enabled.load(std::memory_order_relaxed); } + +void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output, + int n_cols, int n_rows, float epsilon, void* stream) { + const auto count = elements(n_cols, n_rows); + if (!std::isfinite(epsilon) || epsilon < 0.0f) + throw std::invalid_argument("native QSA requires finite nonnegative epsilon"); + buffers(input, count * 4, gamma, std::size_t(n_cols) * 4, output, stream); + if (n_cols < 1024) + norm<256><<(stream)>>>(input, gamma, output, n_cols, epsilon); + else + norm<1024><<(stream)>>>(input, gamma, output, n_cols, epsilon); + check_launch(); +} +void native_qsa_gate_apply(const float* attn, const float* q_full, float* output, + int n_head, int head_dim, void* stream) { + const auto count = elements(head_dim, n_head); + buffers(attn, count * 4, q_full, count * 8, output, stream); + gate<<(stream)>>>(attn, q_full, output, n_head, head_dim); + check_launch(); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_qsa_indexer.cu b/engine/strata/src/kernels/cuda/native_qsa_indexer.cu new file mode 100644 index 00000000..8147c709 --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_qsa_indexer.cu @@ -0,0 +1,290 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// src/models/qwen4exp.cpp; ggml/src/ggml-cuda/{set-rows.cu,norm.cu,rope.cu}. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/mrope.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +constexpr int D = 128, R = 4, ROT = 64, THREADS = 256; +__device__ float warp_sum(float x) { +#pragma unroll + for (int offset = 16; offset; offset >>= 1) + x += __shfl_xor_sync(0xffffffffu, x, offset); + return x; +} +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template +__global__ void append(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, + int pos_base, const float* __restrict__ gamma, float epsilon, + float* __restrict__ tail, float* __restrict__ dead, + float* __restrict__ pooled, int32_t* __restrict__ block_pos, + int max_cells, float theta_scale, float freq_scale, float corr_low, + float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab, RopeTab rt) { + const int pos = *pos_dev, d = threadIdx.x; + if (pos < 0 || pos >= max_cells) return; + const int slot = pos % R; + float incoming = 0.0f; + if (d < D) { + // SET_ROWS stores F16; GET_ROWS expands those exact values to F32. + incoming = __half2float(__float2half_rn(raw[d])); + if (slot < R - 1) tail[slot * D + d] = incoming; + } + if (pos != 0 && slot != R - 1) return; + __shared__ float values[D]; + __shared__ float partials[32]; + float mean = 0.0f; + if (d < D) { + // The spare's four gather indices all name cell zero. Completed blocks + // use chronological slices; each graph ADD materializes an F32 sum. + float sum = pos == 0 ? incoming : tail[d]; +#pragma unroll + for (int j = 1; j < R; ++j) + sum = __fadd_rn(sum, pos == 0 || j == R - 1 ? incoming : tail[j * D + d]); + mean = __fmaf_rn(0.25f, sum, 0.0f); // SCALE includes a zero bias. + } + float square_sum = 0.0f; + if (d < D) square_sum += mean * mean; + square_sum = warp_sum(square_sum); + const int lane = d % 32; + if (lane == 0) partials[d / 32] = square_sum; + __syncthreads(); + square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f; + square_sum = warp_sum(square_sum); + const float scale = rsqrtf(square_sum / D + epsilon); + if (d < D) values[d] = scale * mean * gamma[d]; + __syncthreads(); + if (d >= D) return; + const int b = pos / R; + const int rope_pos = pos == 0 ? 0 : pos_base + R * b; + float y = values[d]; + if (d < ROT) { + const int pair = d % (ROT / 2); + // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in + // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. + float c, s; + if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { + const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } + const float a = values[pair], z = values[pair + ROT / 2]; + y = d < ROT / 2 ? a * c - z * s : a * s + z * c; + } + pooled[std::size_t(b) * D + d] = y; + if (pos == 0) dead[d] = y; + else pooled[std::size_t(b + 1) * D + d] = dead[d]; + if (d == 0 && pos != 0) *block_pos = rope_pos; +} +// ---- C-2: the batched append. The pooled key of a completed block b (its last cell pos = 4b+3), computed with +// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order, +// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch +// (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the +// spare after it (every earlier one's is overwritten by the next block in order). +template +__device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, + float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* mtab, bool zero_pos, + const RopeTab& rt) { + float y = values[d]; + if (d < ROT) { + const int pair = d % (ROT / 2); + // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is + // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero + // angle carries the mscale magnitude through cos(0) exactly as the single append's does. + float c, s; + if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) { + const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } + const float a = values[pair], z = values[pair + ROT / 2]; + y = d < ROT / 2 ? a * c - z * s : a * s + z * c; + } + return y; +} +__device__ __forceinline__ float norm_scale(float mean, float* partials, int d) { + float square_sum = d < D ? mean * mean : 0.0f; + square_sum = warp_sum(square_sum); + const int lane = d % 32; + if (lane == 0) partials[d / 32] = square_sum; + __syncthreads(); + square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f; + square_sum = warp_sum(square_sum); + return square_sum; +} +// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead +template +__global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, + float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, + float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab, RopeTab rt) { + const int d = threadIdx.x; + __shared__ float values[D]; + __shared__ float partials[32]; + float mean = 0.0f; + if (d < D) { + const float incoming = __half2float(__float2half_rn(raw[d])); + float sum = incoming; +#pragma unroll + for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, incoming); + mean = __fmaf_rn(0.25f, sum, 0.0f); + } + const float square_sum = norm_scale(mean, partials, d); + const float scale = rsqrtf(square_sum / D + epsilon); + if (d < D) values[d] = scale * mean * gamma[d]; + __syncthreads(); + if (d >= D) return; + const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, + mtab, true, rt); + pooled[d] = y; + dead[d] = y; +} +template +__global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, + const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, + const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, + int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, + float corr_low, float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab, RopeTab rt) { + const int64_t b = first_block + blockIdx.x; + const int d = threadIdx.x; + __shared__ float values[D]; + __shared__ float partials[32]; + float mean = 0.0f; + if (d < D) { + auto key = [&](int j) -> float { + const int64_t cell = b * R + j; + return cell >= p0 ? __half2float(__float2half_rn(raw[(cell - p0) * D + d])) : tail[j * D + d]; + }; + float sum = key(0); +#pragma unroll + for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, key(j)); + mean = __fmaf_rn(0.25f, sum, 0.0f); + } + const float square_sum = norm_scale(mean, partials, d); + const float scale = rsqrtf(square_sum / D + epsilon); + if (d < D) values[d] = scale * mean * gamma[d]; + __syncthreads(); + if (d >= D) return; + const int rope_pos = pos_base + R * (int) b; + pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, + ext_factor, mscale, mtab, false, rt); + if (b == last_block) { + pooled[std::size_t(b + 1) * D + d] = dead[d]; + if (d == 0) *block_pos = rope_pos; + } +} +// the tail after the batch: slot s holds the key of the batch's last cell with cell % 4 == s (s < 3), if any +__global__ void append_tail(const float* __restrict__ raw, int64_t n, int64_t p0, float* __restrict__ tail) { + const int s = blockIdx.x, d = threadIdx.x; + if (d >= D) return; + const int64_t last = p0 + n - 1; + int64_t cell = last - ((last % R) - s + R) % R; // the last cell <= last with cell % 4 == s + if (cell < p0) return; + tail[s * D + d] = __half2float(__float2half_rn(raw[(cell - p0) * D + d])); +} +struct Span { const void* p; std::size_t n; }; +void validate(Span s) { + const auto p = reinterpret_cast(s.p); + if (!p || p % 4 || s.n > UINTPTR_MAX - p) + throw std::invalid_argument("native QSA indexer requires aligned bounded spans"); +} +bool overlaps(Span a, Span b) { + const auto x = reinterpret_cast(a.p), y = reinterpret_cast(b.p); + return x < y + b.n && y < x + a.n; +} +} // namespace + +void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); } +void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, + const float* gamma, float epsilon, const QsaIndexerBuffers& b, + const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) { + if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || + max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || + int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f || + rope_scaling_invalid(scaling) != nullptr) + throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream"); + const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4}, + {b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}}; + for (const auto& span : spans) validate(span); + for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j) + if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants + const RopeTab rt = rope_table_for(scaling); + if (rt.cos != nullptr) + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); + else + append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table(),rt); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, + float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, + const RopeScaling& scaling, void* stream) { + if (n <= 0) return; + if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells || + max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || + !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr) + throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling"); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants + const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor; + const cudaStream_t st = static_cast(stream); + const int32_t* mtab = mrope_table(); + const RopeTab rt = rope_table_for(scaling); + if (p0 == 0) { + if (rt.cos != nullptr) + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + else + append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab, rt); + } + // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) + const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 + const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 + if (hi >= first && rt.cos != nullptr) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); + else if (hi >= first) + append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, + b.tail, b.dead, b.pooled, b.block_pos, first, hi, theta_scale, fsf, cl, ch, ef, ms, mtab, rt); + append_tail<<>>(raw, n, p0, b.tail); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_qsa_score.cu b/engine/strata/src/kernels/cuda/native_qsa_score.cu new file mode 100644 index 00000000..cdcfeadd --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_qsa_score.cu @@ -0,0 +1,213 @@ +// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d: +// ggml/src/ggml-cuda/{mmf.cuh,mma.cuh,unary.cu,binbcast.cu}. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#include "strata/kernels/native_qsa_score.hpp" +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +constexpr int D=128, HEADS=4, R=4, ROWS=32, WARPS=2, STRIDE=36, COMBINE=68; +struct TileA { uint32_t x[4]; }; +struct TileB { uint32_t x[2]; }; +struct TileC { float x[4]={0.0f,0.0f,0.0f,0.0f}; }; +#if !defined(__HIPCC__) +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +__device__ __forceinline__ void load_a(TileA& a,const float* p) { + const float* src=p+(threadIdx.x%16)*STRIDE+(threadIdx.x/16)*4; + asm volatile("ldmatrix.sync.aligned.m8n8.x4.b16 {%0,%1,%2,%3}, [%4];" + : "=r"(a.x[0]),"=r"(a.x[1]),"=r"(a.x[2]),"=r"(a.x[3]):"l"(src)); +} +__device__ __forceinline__ void load_b(TileB& b,const float* p) { + const float* src=p+(threadIdx.x%8)*STRIDE+((threadIdx.x/8)*4)%8; + asm volatile("ldmatrix.sync.aligned.m8n8.x2.b16 {%0,%1}, [%2];" + : "=r"(b.x[0]),"=r"(b.x[1]):"l"(src)); +} +__device__ __forceinline__ void mma(TileC& c,const TileA& a,const TileB& b) { + // Deliberately no cvt.rn.tf32: pinned mma.cuh passes raw F32 bits directly. + asm("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" + : "+f"(c.x[0]),"+f"(c.x[1]),"+f"(c.x[2]),"+f"(c.x[3]) + : "r"(a.x[0]),"r"(a.x[1]),"r"(a.x[2]),"r"(a.x[3]),"r"(b.x[0]),"r"(b.x[1])); +} +#endif +__global__ __launch_bounds__(64,1) void score_kernel( + const float* __restrict__ pooled,const float* __restrict__ query, + const float* __restrict__ bias,const int32_t* __restrict__ step, + int max_cells,float* __restrict__ cells) { + const int n=step[kStepNKv],full=step[kStepNBid]; + if(n<1||n>max_cells||step[kStepPos]!=n-1||full!=n/R|| + step[kStepWidth]!=(n<2051?n:2051))return; + const int row0=blockIdx.x*ROWS; + if(row0>full)return; + const int lane=threadIdx.x,warp=threadIdx.y; +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 + // Turing (STRATA_EXPERIMENTAL_SM75, a layer-split stage): no tf32 mma. The same scores with FP32 FMAs, one row + // per thread of the first warp - rounded differently from the tensor-core path (FP32 instead of TF32 inputs). + if(warp!=0)return; + const int row=row0+lane; + if(row>full)return; + float h[HEADS]; + for(int j=0;jfull)return; + float h[HEADS]; +#pragma unroll + for(int j=0;jmax_cells||step[kStepPos]!=n-1||full!=n/R|| + step[kStepWidth]!=(n<2051?n:2051))return; + const int row=blockIdx.x; + if(row>full)return; + __shared__ float head_score[HEADS]; + const int head=threadIdx.x; + if(head0.0f?dot:0.0f; + } + __syncthreads(); + if(head==0){ + float sum=__fadd_rn(0.0f,head_score[0]); + sum=__fadd_rn(sum,head_score[1]); + sum=__fadd_rn(sum,head_score[2]); + sum=__fadd_rn(sum,head_score[3]); + if(bias)sum=__fadd_rn(sum,bias[row]); + sum=__fadd_rn(sum,row==full&&n%R?1e9f:0.0f); + sum=__fadd_rn(sum,0.0f); + for(int i=row*R;i(s.p); + if(!p||p%4||s.n>UINTPTR_MAX-p)throw std::invalid_argument("native QSA score requires aligned bounded spans"); +} +bool overlaps(Span a,Span b){ + const auto x=reinterpret_cast(a.p),y=reinterpret_cast(b.p); + return xINT32_MAX-3||max_blocks!=max_cells/R+1) + throw std::invalid_argument("native QSA score requires128dim/4heads/4cells/2048budget, exact capacities and explicit stream"); + const Span spans[]={{pooled,size_t(max_blocks)*D*4},{query,HEADS*D*4}, + {step,kStepCount*4},{cells,size_t(max_cells)*4},{bias,bias?size_t(max_blocks)*4:0}}; + const int count=bias?5:4; + for(int i=0;i(stream)>>>( + pooled,query,bias,step,int(max_cells),cells); +#else + score_kernel<<(stream)>>>( + pooled,query,bias,step,int(max_cells),cells); +#endif + const auto error=cudaGetLastError(); + if(error!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(error)); +} +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/native_rope.cu b/engine/strata/src/kernels/cuda/native_rope.cu new file mode 100644 index 00000000..57cbe79f --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_rope.cu @@ -0,0 +1,147 @@ +// Numerical contract: pinned ggml/src/ggml-cuda/rope.cu, rope_multi/rope_yarn. +// Text positions are equal across the four IMRoPE sections, so section routing +// reduces to the one position associated with each contiguous row. +// MIT License +// +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/mrope.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +bool overlaps(const void* a, size_t an, const void* b, size_t bn) { + auto x = reinterpret_cast(a), y = reinterpret_cast(b); + return x <= y ? y - x < an : x - y < bn; +} +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template +__global__ void apply(const float* x, float* out, int rows, int width, + int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int* positions, const int32_t* mtab, RopeTab rt) { + const int row = blockIdx.y; + const int pair = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= rows || pair >= width / 2) return; + const size_t start = size_t(row) * width; + if (pair >= n_rot / 2) { + if (x != out) { + out[start + 2 * pair] = x[start + 2 * pair]; + out[start + 2 * pair + 1] = x[start + 2 * pair + 1]; + } + return; + } + float c, s; + if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) { + const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); + } + const float a = x[start + pair], b = x[start + pair + n_rot / 2]; + out[start + pair] = a * c - b * s; + out[start + pair + n_rot / 2] = a * s + b * c; +} +} +// one table per device (a layer split runs the rope kernels on several): set and read for the current device +namespace { +constexpr int kMropeDevices = 64; +std::atomic mrope_tab[kMropeDevices] = {}; +int mrope_dev() { + int d = 0; + if (cudaGetDevice(&d) != cudaSuccess || d < 0 || d >= kMropeDevices) d = 0; + return d; +} +} // namespace +void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); } +const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); } +namespace { +// #280: the float64 angle table of each device, set at session init (before any graph is captured) +struct RopeReg { + RopeTab tab; + RopeScaling scaling; +}; +RopeReg rope_tab[kMropeDevices] = {}; +bool same_scaling(const RopeScaling& a, const RopeScaling& b) { + return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in && + a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor && + a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow; +} +// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move) +bool rope_table_enabled() { + static const bool on = [] { + const char* e = std::getenv("STRATA_ROPE_TABLE"); + return e != nullptr && e[0] == '1'; + }(); + return on; +} +} // namespace +void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) { + rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling}; +} +void rope_table_release(const float* cos_tab) { + // every device's entry that points at it (the caller may free it from another current device) + for (RopeReg& r : rope_tab) + if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{}; +} +RopeTab rope_table_for(const RopeScaling& scaling) { + if (!rope_table_enabled()) return {}; + const RopeReg& r = rope_tab[mrope_dev()]; + return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{}; +} +void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } +void native_rope_apply(const float* x, float* out, int rows, int head_dim, + int n_rot, const RopeScaling& scaling, const int* positions, void* stream) { + if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 || + (head_dim != 128 && head_dim != 256) || n_rot != 64 || + rope_scaling_invalid(scaling) != nullptr || + reinterpret_cast(x) % 4 || reinterpret_cast(out) % 4 || + reinterpret_cast(positions) % 4) { + throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream"); + } + const size_t bytes = size_t(rows) * head_dim * sizeof(float); + if ((x != out && overlaps(x, bytes, out, bytes)) || + overlaps(positions, size_t(rows) * sizeof(int), out, bytes) || + overlaps(positions, size_t(rows) * sizeof(int), x, bytes)) { + throw std::invalid_argument("native RoPE buffers partially overlap"); + } + // Match pinned host-side float powf before device fast powf/trigonometry. + const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); + const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants + const RopeTab rt = rope_table_for(scaling); + const dim3 grid((head_dim / 2 + 127) / 128, rows); + if (rt.cos != nullptr) + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); + else + apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, positions, mrope_table(), rt); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} diff --git a/engine/strata/src/kernels/cuda/native_router.cu b/engine/strata/src/kernels/cuda/native_router.cu new file mode 100644 index 00000000..3f8b69ce --- /dev/null +++ b/engine/strata/src/kernels/cuda/native_router.cu @@ -0,0 +1,127 @@ +// Adapted from topk-moe.cu/common.cuh in llama.cpp +// 3cf03257f219afbe7334045ff7c6a06ac68c627d; finite F32, 512-expert/10-output path. +// MIT License +// Copyright (c) 2023-2026 The ggml authors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#include "strata/kernels/native_router.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +std::atomic enabled{false}; +__device__ __forceinline__ float warp_sum(float value) { +#pragma unroll + for (int mask = 16; mask; mask >>= 1) value += __shfl_xor_sync(0xffffffffu, value, mask, 32); + return value; +} +__device__ __forceinline__ float warp_max(float value) { +#pragma unroll + for (int mask = 16; mask; mask >>= 1) value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, mask, 32)); + return value; +} +__launch_bounds__(256, 1) +__global__ void route(const float* __restrict__ logits, int32_t* __restrict__ ids, + float* __restrict__ weights) { + // Preserve the pinned 32x8 block geometry; only row zero is active here. + // blockIdx.x = the token (a multi-token launch; 0 for the single one) + logits += (size_t) blockIdx.x * 512; ids += (size_t) blockIdx.x * 10; weights += (size_t) blockIdx.x * 10; + if (threadIdx.y != 0) return; + const int lane = threadIdx.x; + float values[16]; +#pragma unroll + for (int i = 0; i < 16; ++i) values[i] = logits[lane + i * 32]; + __syncthreads(); + float maximum = -INFINITY; +#pragma unroll + for (int i = 0; i < 16; ++i) maximum = max(maximum, values[i]); + maximum = warp_max(maximum); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < 16; ++i) { + values[i] = expf(values[i] - maximum); + sum += values[i]; + } + const float reciprocal = 1.0f / warp_sum(sum); +#pragma unroll + for (int i = 0; i < 16; ++i) { + values[i] *= reciprocal; + if (__isnanf(values[i])) values[i] = -FLT_MAX; + } + float selected = 0.0f, selected_sum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = values[0]; + int expert = lane; +#pragma unroll + for (int i = 1; i < 16; ++i) { + if (values[i] > best) { best = values[i]; expert = lane + i * 32; } + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) { + const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32); + const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32); + if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; } + } + if ((expert & 31) == lane) { + values[expert / 32] = -INFINITY; + ids[rank] = expert; + // Deliberately accumulate by WINNING EXPERT lane, not output rank. + // Multiple selected experts in one lane add in selection order. + selected_sum += best; + } + if (rank == lane) selected = best; + } + selected_sum = max(warp_sum(selected_sum), 6.103515625e-5f); + const float inverse_selected_sum = 1.0f / selected_sum; + if (lane < 10) weights[lane] = selected * inverse_selected_sum; +} +bool valid(const void* p, size_t bytes) { + const auto address = reinterpret_cast(p); + return p && address % 4 == 0 && bytes <= UINTPTR_MAX - address; +} +bool overlap(const void* a, size_t an, const void* b, size_t bn) { + const auto ap = reinterpret_cast(a), bp = reinterpret_cast(b); + return ap < bp + bn && bp < ap + an; +} +} +void native_router_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } +bool native_router_enabled() { return enabled.load(std::memory_order_relaxed); } +void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream) { + if (!stream || !valid(logits, 512 * 4) || !valid(ids, 10 * 4) || !valid(weights, 10 * 4) + || overlap(logits, 512 * 4, ids, 10 * 4) || overlap(logits, 512 * 4, weights, 10 * 4) + || overlap(ids, 10 * 4, weights, 10 * 4)) + throw std::invalid_argument("native router requires a stream, aligned spans, and disjoint outputs"); + route<<<1, dim3(32, 8), 0, static_cast(stream)>>>(logits, ids, weights); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) { + if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) || + !valid(weights, (size_t) n_tok * 10 * 4)) + throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers"); + route<<<(unsigned) n_tok, dim3(32, 8), 0, static_cast(stream)>>>(logits, ids, weights); + const auto error = cudaGetLastError(); + if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); +} +} diff --git a/engine/strata/src/kernels/cuda/ple.cu b/engine/strata/src/kernels/cuda/ple.cu new file mode 100644 index 00000000..6585bbaa --- /dev/null +++ b/engine/strata/src/kernels/cuda/ple.cu @@ -0,0 +1,368 @@ +// src/kernels/cuda/ple.cu - P2.S4: the PLE block's GPU half. +// +// See include/strata/kernels/ple.hpp for the structure and for the `normalized`-is-the-conv-input finding. +// +// The legacy arithmetic below follows the captured CPU ggml graph +// (`bench/micro/ple_in.bin` / `ple_out.bin`, produced by `ple_layer_xcheck.cpp`): +// +// * `rms_norm` accumulates `(double)(x*x)` with the PRODUCT rounded in f32 first - that is literally what +// `ggml_compute_forward_rms_norm_f32` does (`sum += (ggml_float)(x[i00]*x[i00])` with `ggml_float` = +// double), and it is not the same as accumulating in f32 or as widening before the multiply. +// * `silu` is `x / (1 + expf(-x))` in f32, which is `ggml_silu_f32`. +// * the gate's `sqrt` and `sigmoid` are f32. +// +// The opt-in native BF16 path replaces only ple_value with the pinned CUDA single-token BF16/F32 MMVF. +// A separate opt-in native postops path follows the pinned CUDA arithmetic after both projections. +#include "strata/kernels/ple.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s2_gemv_q8.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_ple_postops.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 256; +bool native_bf16 = false; +bool native_postops = false; + +bool overlap(const void* a, size_t a_bytes, const void* b, size_t b_bytes) { + if (a == nullptr || b == nullptr || a_bytes == 0 || b_bytes == 0) return false; + const uintptr_t aa = reinterpret_cast(a), bb = reinterpret_cast(b); + return aa < bb ? bb - aa < a_bytes : aa - bb < b_bytes; +} + +__global__ void history_advance_kernel(float* __restrict__ history, const float* __restrict__ normalized) { + const int channel = blockIdx.x * blockDim.x + threadIdx.x; + if (channel >= NG_HC_DIM) return; + float* column = history + (size_t) channel * NG_HIST; + for (int row = 0; row + 1 < NG_HIST; ++row) column[row] = column[row + 1]; + column[NG_HIST - 1] = normalized[channel]; +} + +__device__ __forceinline__ uint16_t bf16_bits(float f) { + uint32_t i; + memcpy(&i, &f, 4); + i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; + return (uint16_t) (i >> 16); +} + +__device__ __forceinline__ float bf16_float(uint16_t h) { + const uint32_t i = (uint32_t) h << 16; + float f; + memcpy(&f, &i, 4); + return f; +} + +__device__ __forceinline__ float silu_f(float x) { return x / (1.0f + expf(-x)); } + +/// Block-wide sum in double, broadcast to all threads. The leading `__syncthreads` matters: the result is +/// read out of `scratch[0]` and a later call reuses the array, so without a barrier a fast thread can +/// overwrite it before a slow one has read it - invisible in most runs and a slightly different norm when it +/// fires. +__device__ double block_sum(double v, double* scratch) { + __syncthreads(); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + if (lane == 0) scratch[warp] = v; + __syncthreads(); + const int nw = ((int) blockDim.x + 31) >> 5; + v = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; + if (warp == 0) + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + if (threadIdx.x == 0) scratch[0] = v; + __syncthreads(); + return scratch[0]; +} + +/// `grouped_norm`, ONE BLOCK PER STREAM. The ggml form is `reshape_3d(x, n_embd, hc, T)` then +/// `rms_norm(..., eps) * w`, so ne0 = n_embd is the reduction axis and each hc stream is normalised on its +/// own. In the flat ggml layout (ne0 fastest) stream c occupies [c*n_embd, (c+1)*n_embd). +__global__ void gnorm_kernel(const float* __restrict__ x, const float* __restrict__ w, + float* __restrict__ y, int n_embd, float eps) { + __shared__ double scratch[8]; + const int c = blockIdx.x; + const float* xc = x + (size_t) c * n_embd; + const float* wc = w + (size_t) c * n_embd; + float* yc = y + (size_t) c * n_embd; + + double acc = 0.0; + for (int d = threadIdx.x; d < n_embd; d += blockDim.x) { + // The PRODUCT is rounded in f32 before it is widened - `(ggml_float)(x[i00]*x[i00])`. + const float sq = xc[d] * xc[d]; + acc += (double) sq; + } + const float mean = (float) (block_sum(acc, scratch) / (double) n_embd); + const float scale = 1.0f / sqrtf(mean + eps); + for (int d = threadIdx.x; d < n_embd; d += blockDim.x) yc[d] = xc[d] * scale * wc[d]; +} + +/// `s[c] = sum_d key[c][d]*query[c][d] / sqrt(n_embd)`, then the signed square root and the sigmoid. +/// +/// `mag = sqrt(clamp(|s|, 1e-6, inf))` and `gate = sigmoid(sgn(s) * mag)`. The clamp is a floor on |s|, so +/// it only bites near zero; the SIGN is carried separately, which is what keeps the gate symmetric about 0.5. +__global__ void gate_kernel(const float* __restrict__ key, const float* __restrict__ query, + float* __restrict__ gate, int n_embd, float inv_sqrt_n) { + __shared__ double scratch[8]; + const int c = blockIdx.x; + const float* kc = key + (size_t) c * n_embd; + const float* qc = query + (size_t) c * n_embd; + double acc = 0.0; + for (int d = threadIdx.x; d < n_embd; d += blockDim.x) acc += (double) (kc[d] * qc[d]); + const float s = (float) (block_sum(acc, scratch) / (double) 1.0) * inv_sqrt_n; + const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f)); + const float sgn = (s > 0.0f) ? 1.0f : ((s < 0.0f) ? -1.0f : 0.0f); + if (threadIdx.x == 0) gate[c] = 1.0f / (1.0f + expf(-(sgn * mag))); +} + +/// `gated[c][d] = value[d] * gate[c]` - the value broadcast across the hc streams. +__global__ void bcast_kernel(const float* __restrict__ value, const float* __restrict__ gate, + float* __restrict__ gated, int n_embd, int hc) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n_embd * hc) return; + gated[i] = value[i % n_embd] * gate[i / n_embd]; +} + +/// The depthwise causal dilated conv, then SiLU. One thread per channel. +/// +/// `out[c] = sum_k kW[k][c] * terms[t - (kern-1-k)*dil][c]` with `t = hist` (the first new position), so tap k +/// reads row `hist - (kern-1-k)*dil` of `[history | new]`. For the real geometry (kern 4, dil 3, hist 9) the +/// four taps read rows 0, 3, 6 and 9 - and row 9 is the NEW row, which is the only one beyond the history. +/// That is why no `terms` buffer is built: three taps come from the caller's history and one from `norm`. +/// +/// `kW` IS GGML-NATIVE: `kW[k + kern*c]`. The manifest's shape is [4, 10240] with ne0 = 4 fast, and +/// `ref/ngram.py`'s (4, 10240) numpy `kernel[k][c]` is the TRANSPOSE of that. The source's own view +/// (`ggml_view_2d(model.layers[il].ple_conv1d, 1, hc_dim, nb[1], k*nb[0])`) settles which one is meant. +__global__ void conv_kernel(const float* __restrict__ hist, const float* __restrict__ norm, + const uint16_t* __restrict__ kW, float* __restrict__ out, int hc_dim, int kern, + int dil, int nhist) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= hc_dim) return; + float acc = 0.0f; + for (int k = 0; k < kern; ++k) { + const int row = nhist - (kern - 1 - k) * dil; // tap 0 reads the FURTHEST back + // ROW-FASTEST: `hist[row + nhist*c]`. The conv state is `ggml_reshape_3d(state, d_conv-1, + // conv_channels, n_seqs)`, so ne0 = hist varies fastest and the flat index is row + hist*channel. + // Channel-slowest (`row*hc_dim + c`) is the natural thing to write and would read a transposed state - + // `ple_layer_xcheck.cpp` L79-83 records getting this wrong once already. + const float v = (row == nhist) ? norm[c] : hist[(size_t) row + (size_t) nhist * c]; + acc += f32_from_f16(kW[k + kern * c]) * v; + } + out[c] = silu_f(acc); +} + +/// `result = hidden + gated + conv`, elementwise over hc_dim. +__global__ void add3_kernel(const float* __restrict__ hidden, const float* __restrict__ gated, + const float* __restrict__ conv, float* __restrict__ result, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) result[i] = hidden[i] + gated[i] + conv[i]; +} + +/// `y[o] = sum_i bf16(x[i]) * bf16(w[o*n_in + i])`. The weight is BF16 and so is the ACTIVATION, which is +/// the contract for a BF16 tensor (`docs/activation-contract.md`); with both sides bf16 the products are +/// exact in f32 and only the summation order differs from ggml's. +__global__ void bf16_gemv_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + float* __restrict__ y, int n_in, int n_out) { + const int o = blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + const uint16_t* row = w + (size_t) o * n_in; + double acc = 0.0; + for (int i = 0; i < n_in; ++i) acc += (double) bf16_float(x[i]) * (double) bf16_float(row[i]); + y[o] = (float) acc; +} + +__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = bf16_bits(x[i]); +} + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "ple_block: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace + +void ple_set_native_bf16(bool enabled) { native_bf16 = enabled; } +void ple_set_native_postops(bool enabled) { native_postops = enabled; } +bool ple_native_postops_enabled() { return native_postops; } + +void ple_history_advance(float* hist, const float* normalized, void* stream) { + if (hist == nullptr || normalized == nullptr) + throw std::invalid_argument("ple_history_advance: null history or normalized input"); + if (overlap(hist, (size_t) NG_HIST * NG_HC_DIM * sizeof(float), + normalized, (size_t) NG_HC_DIM * sizeof(float))) + throw std::invalid_argument("ple_history_advance: history and normalized input overlap"); + history_advance_kernel<<<(NG_HC_DIM + THREADS - 1) / THREADS, THREADS, 0, (cudaStream_t) stream>>>(hist, normalized); + ck(cudaGetLastError(), "history advance launch"); +} + +bool ple_block_available() { + int n = 0; + return cudaGetDeviceCount(&n) == cudaSuccess && n > 0; +} + +uint64_t ple_block_scratch_bytes() { + // five hc_dim floats + n_embd + hc, then the Q8 activation image, then the BF16 embedding copy, each + // 16-byte aligned because `d_scratch` is cast to `float*` and `d_act` to `uint8_t*` at those offsets. + const size_t f = (size_t) (5 * NG_HC_DIM + NG_N_EMBD + NG_HC) * sizeof(float); + const size_t q = (size_t) (NG_N_EMBD / 32) * 34; + const size_t e = (size_t) NG_N_EMBD * sizeof(uint16_t); + return ((f + 15) & ~(size_t) 15) + ((q + 15) & ~(size_t) 15) + e + 256; +} + +void ple_block(const float* emb, const float* hidden, const float* hist_rows, const PleWeights& w, + PleOut& out, void* scratch, void* stream) { + const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr; + if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream || + !w.key_native_q8_1 || + (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 && + w.key_native_type != 8))) + throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS, IQ4_XS or Q8_0 weights, input/output, private scratch and explicit stream"); + if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return; + const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM; + static_assert(NG_N_EMBD == 2560 && NG_HC_DIM == 10240, "native PLE key geometry changed"); + const size_t float_bytes = (size_t) (5 * hc_dim + n_embd + hc) * sizeof(float); + cudaStream_t st = (cudaStream_t) stream; + + // One allocation for every intermediate. + // + // THE ENGINE WILL NOT DO THIS. P2.T10 requires zero token-path allocations, and the fix is the same one + // `gr_read` already uses: a caller-owned workspace carved once at startup. It is done this way here + // because this function's job in P2.S4 is to be CORRECT and comparable against the oracle, and matching + // `shared_expert.cu`'s existing shape keeps the diff small. Recorded rather than hidden. + // + // FIVE SEPARATE hc_dim BUFFERS, deliberately. `key` and `normalized` are both needed at the end for the + // oracle comparison, so aliasing one onto the other - which the first version did - silently returns the + // WRONG `key`. Two buffers of the same size look like an obvious saving and the only thing it saves is + // 40 KB. + // **THE WORKSPACE IS CARVED FROM THE CALLER'S, NOT ALLOCATED.** Three `cudaMalloc`s and a + // `cudaStreamSynchronize` used to live here, and inside a stream capture both are errors: the engine + // reported `ple_block: scratch: operation not permitted when stream is capturing`, and a token-path + // allocation is a P2.T10 violation besides. The comment this replaces already said the right shape was + // "a caller-owned workspace carved once at startup"; this is that. + const size_t q8_bytes = (size_t) (n_embd / 32) * 34; + if (scratch == nullptr) { + std::fprintf(stderr, "ple_block: scratch is null; the caller owns it (see ple_block_scratch_bytes)\n"); + std::exit(1); + } + const struct Export { const float* pointer; size_t count; const char* name; } exports[] = { + {out.key, (size_t) hc_dim, "key"}, {out.value, (size_t) n_embd, "value"}, + {out.gate, (size_t) hc, "gate"}, {out.gated, (size_t) hc_dim, "gated"}, + {out.normalized, (size_t) hc_dim, "normalized"}, {out.conv, (size_t) hc_dim, "conv"}, + {out.result, (size_t) hc_dim, "result"} + }; + for (const auto& item : exports) { + if (overlap(item.pointer, item.count * sizeof(float), scratch, (size_t) ple_block_scratch_bytes())) + throw std::invalid_argument(std::string("ple_block: output ") + item.name + " overlaps scratch"); + } + if (native_key) { + const size_t native_bytes = native_q8_1_bytes(n_embd); + const size_t weight_bytes = native_mmvq_weight_bytes(w.key_native_type, n_embd, hc_dim); + if ((reinterpret_cast(w.key_native_data) & 3u) || + (reinterpret_cast(w.key_native_q8_1) & 3u)) + throw std::invalid_argument("ple_block: native key buffers require four-byte alignment"); + const struct Region { const void* pointer; size_t bytes; } regions[] = { + {scratch, (size_t) ple_block_scratch_bytes()}, {emb, (size_t) n_embd * 4}, + {hidden, (size_t) hc_dim * 4}, {hist_rows, (size_t) NG_HIST * hc_dim * 4}, + {w.key_native_data, weight_bytes}, {w.value_bf16, (size_t) n_embd * n_embd * 2}, + {w.norm_key, (size_t) hc_dim * 4}, {w.norm_query, (size_t) hc_dim * 4}, + {w.norm_conv, (size_t) hc_dim * 4}, {w.conv1d_f16, (size_t) PLE_CONV_KERNEL * hc_dim * 2} + }; + for (const auto& region : regions) + if (overlap(w.key_native_q8_1, native_bytes, region.pointer, region.bytes)) + throw std::invalid_argument("ple_block: native key scratch overlaps workspace, input or weight"); + for (const auto& item : exports) + if (overlap(w.key_native_q8_1, native_bytes, item.pointer, item.count * sizeof(float))) + throw std::invalid_argument(std::string("ple_block: native key scratch overlaps output ") + item.name); + } + uint8_t* base = (uint8_t*) scratch; + float* d_scratch = (float*) base; + uint8_t* d_act = base + ((float_bytes + 15) & ~(size_t) 15); + uint16_t* d_emb16 = (uint16_t*) (d_act + ((q8_bytes + 15) & ~(size_t) 15)); + float* d_key = d_scratch; + float* d_query = d_key + hc_dim; + float* d_norm = d_query + hc_dim; + float* d_gated = d_norm + hc_dim; + float* d_conv = d_gated + hc_dim; + float* d_value = d_conv + hc_dim; + float* d_gate = d_value + n_embd; + + // ---- key = grouped_norm(ple_key @ emb). The optional native projection + // follows pinned CUDA Q8_1 MMVQ; the default retains its canonical Q8_0 path. + if (w.key_bf16 != nullptr) { + bf16_gemv_fp32_mmvf(emb, w.key_bf16, d_key, n_embd, hc_dim, stream); + } else if (native_key) { + native_quantize_q8_1(emb, w.key_native_q8_1, n_embd, 1, stream); + native_mmvq(w.key_native_type, w.key_native_data, w.key_native_q8_1, + d_key, n_embd, hc_dim, 1, stream); + } else { + quantize_q8_0(emb, d_act, n_embd, st); + s2_gemv_q8(d_act, w.key_codes, w.key_scales, d_key, n_embd, hc_dim, 8, st); + } + if (!native_postops) { + gnorm_kernel<<>>(d_key, w.norm_key, d_key, n_embd, NG_RMS_EPS); + gnorm_kernel<<>>(hidden, w.norm_query, d_query, n_embd, NG_RMS_EPS); + } + + // The value projection's independent option leaves the nonlinear PLE operations unchanged. + if (native_bf16) { + bf16_gemv_fp32_mmvf(emb, w.value_bf16, d_value, n_embd, n_embd, stream); + } else { + to_bf16_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(emb, d_emb16, n_embd); + bf16_gemv_kernel<<<(n_embd + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_emb16, w.value_bf16, d_value, + n_embd, n_embd); + } + + const float* normalized_key = d_key; + if (native_postops) { + // The key norm has a distinct destination; temporary query storage can + // be reused for normalized gated values after the gate consumes it. + NativePlePostopsBuffers buffers{d_query,d_norm,d_gate,d_gated,d_norm,d_conv,out.result}; + native_ple_postops(d_key,hidden,d_value,hist_rows,w,buffers,stream); + normalized_key = d_query; + } else { + gate_kernel<<>>(d_key, d_query, d_gate, n_embd, 1.0f / sqrtf((float) n_embd)); + bcast_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(d_value, d_gate, d_gated, n_embd, hc); + gnorm_kernel<<>>(d_gated, w.norm_conv, d_norm, n_embd, NG_RMS_EPS); + conv_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hist_rows, d_norm, w.conv1d_f16, d_conv, + hc_dim, PLE_CONV_KERNEL, NGRAM_SIZE, + NG_HIST); + add3_kernel<<<(hc_dim + THREADS - 1) / THREADS, THREADS, 0, st>>>(hidden, d_gated, d_conv, out.result, + hc_dim); + } + + // ---- the intermediates the oracle comparison needs. `key` is the NORMALISED key, because the source's + // `cb(key, ...)` capture is after `gnorm`; `value` is the projection before the gate. Each stage the + // oracle records is reproduced here so a mismatch can be attributed instead of guessed at. + if (out.key) ck(cudaMemcpyAsync(out.key, normalized_key, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "key"); + if (out.value) + ck(cudaMemcpyAsync(out.value, d_value, n_embd * sizeof(float), cudaMemcpyDeviceToDevice, st), "value"); + if (out.gate) ck(cudaMemcpyAsync(out.gate, d_gate, hc * sizeof(float), cudaMemcpyDeviceToDevice, st), "gate"); + if (out.gated) + ck(cudaMemcpyAsync(out.gated, d_gated, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "gated"); + if (out.normalized) + ck(cudaMemcpyAsync(out.normalized, d_norm, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "norm"); + if (out.conv) + ck(cudaMemcpyAsync(out.conv, d_conv, hc_dim * sizeof(float), cudaMemcpyDeviceToDevice, st), "conv"); + + ck(cudaGetLastError(), "launch"); + // **NO `cudaStreamSynchronize` HERE.** It was there to make the function self-contained for the parity + // test, and inside a capture it is an error - a caller that wants the result immediately synchronises + // itself, and the engine's caller does not want that at all. +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/qsa.cu b/engine/strata/src/kernels/cuda/qsa.cu new file mode 100644 index 00000000..a635e81e --- /dev/null +++ b/engine/strata/src/kernels/cuda/qsa.cu @@ -0,0 +1,821 @@ +// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp). +// +// The header documents the layouts and the scope; this file documents the four decisions that are about the +// KERNEL rather than about the interface. +// +// 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT. The selection has to reproduce `ggml_top_k` on the +// masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a +// different selected set is a different attention input, and `docs/capture-format.md` L127 gives +// `indexer_ids` no tolerance. The kernel therefore computes the width-th largest score as a 32-bit +// "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits - +// in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it. That +// is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no +// scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection +// runs in ONE block so the ascending walk is a chunked scan rather than a second global pass. Phase 3 +// replaces it with a radix select; this one is the thing that radix select has to agree with. +// +// 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY. n_ids reaches 2051, so a per-head score +// vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a +// small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps +// the softmax's three passes over the scores in shared memory instead of in global. The score loop has one +// thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value +// loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell. Both +// are coalesced for the layout the gather produces. +// +// 3. NO `__float2half`. `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half` +// produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0. The parity test checks that converter against +// vectors generated by numpy's float16, which is an oracle sharing no code with it. +// +// 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED. `pooled` and the spare key are compared BIT-EXACT +// against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact +// identity, so the comparison is not weakened by the rope). That needs the same summation order on both +// sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially, +// and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one +// operation with no intermediate rounding and land one ulp away from the host. +// +// THE `d` IN THOSE NAMES IS NOT COSMETIC. The first version wrote `__fadd_rn`/`__fmul_rn`, which are +// the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated +// there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only +// float precision (121.82236480712891 on the device against 121.82236342931094 in the reference). +// Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a +// BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest +// argument in this file for keeping both. +#include "strata/core/emulate.hpp" +#include "strata/kernels/qsa.hpp" + +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/mrope.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 128; + +void fail(const char* what) { + std::fprintf(stderr, "qsa: %s\n", what); + std::exit(1); +} + +void check_launch(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa: %s launch: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// The SYNCHRONOUS entry points must check their own wait. Without this the sticky error from a kernel that +/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel - +/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one. +void check_sync(const char* what) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa: %s (synchronise): %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently +/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused. +void validate(const QsaShapes& s, const char* who) { + if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 || + s.idx_block < 2 || s.page_size < 1) { + std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who); + std::exit(1); + } + if (s.n_head % s.n_head_kv != 0) { + std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who, + (long long) s.n_head, (long long) s.n_head_kv); + std::exit(1); + } + if (s.head_dim % 4 != 0) { + std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who, + (long long) s.head_dim); + std::exit(1); + } + if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) { + std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who, + (long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim); + std::exit(1); + } + if (s.idx_n_head > 32) { + std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who, + (long long) s.idx_n_head); + std::exit(1); + } +} + +__device__ __forceinline__ float h2f(uint16_t bits) { return f32_from_f16(bits); } + +// ================= 1. kv_append ================= + +__global__ void kv_append_kernel(uint16_t* __restrict__ k_pool, uint16_t* __restrict__ v_pool, + const int32_t* __restrict__ table, const int32_t* __restrict__ step, + const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, + int head_dim, int page_size, KvHostPools host) { + const long long pos = (long long) __ldg(step + kStepPos); + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= kv_heads * head_dim) return; + const int h = i / head_dim, d = i - h * head_dim; + // `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page. + // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident. + const long long page = (long long) table[pos / page_size]; + if (page >= 0) { + const long long row = (page * kv_heads + h) * page_size + (pos % page_size); + k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); + v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); + } + if (host.k_pool != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); + host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); + } +} + +// ================= 2. indexer_key_append ================= + +/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row. One thread per indexer +/// dim, shared `mean` in double. +/// +/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.** It used to be +/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on +/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's +/// position forever. Doing it here reads the position from `pos_dev` like every other kernel, so the grid and +/// the arguments are the same for every token and the graph replays correctly. +__global__ void indexer_key_append_kernel(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, + int pos_base, const float* __restrict__ w_k_norm, float eps, + float* __restrict__ tail, float* __restrict__ dead, + float* __restrict__ pooled, int32_t* __restrict__ block_pos, + int idx_dim, int r, int n_rot, const float* __restrict__ cos_tab, + const float* __restrict__ sin_tab, const int32_t* __restrict__ mtab) { + extern __shared__ double s_mean[]; // idx_dim doubles + const int d = threadIdx.x; + const int pos = (int) __ldg(pos_dev); + const int slot = pos % r; + + // The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly. + // That is what makes `idx_block - 1` rows enough. + if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d]; + + // The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason + // cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block. + if (pos == 0) { + double p = (double) raw[d]; + double ss = 0.0; + // Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential. + // Every thread computes the same `ss` and uses only its own output element. + // + // `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision + // intrinsics, and using them on doubles silently rounds every operation to float. `ss` then carries + // only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare + // key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices. `__ddiv_rn` + // and `__dsqrt_rn` pin the reciprocal square root for the same reason. + for (int i = 0; i < idx_dim; ++i) { + const double v = (double) raw[i]; + ss = __dadd_rn(ss, __dmul_rn(v, v)); + } + const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); + float y = (float) (p * inv * (double) w_k_norm[d]); + // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native + // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the + // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). + // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the + // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude + // correction exactly like every other pooled row and like the native kernel's spare (the unrotated + // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, + // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. + if (d < n_rot) y *= cos_tab[d % (n_rot / 2)]; + dead[d] = y; + pooled[d] = y; + } + + if (slot != r - 1) return; + __syncthreads(); // the tail rows this thread is about to read are written above + + // The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming + // cell (slot r-1). The sum of r f32 values is exact in double, so the mean's order cannot matter here - + // but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides. + double m = 0.0; + for (int j = 0; j < r - 1; ++j) m = __dadd_rn(m, (double) tail[(size_t) j * idx_dim + d]); + m = __dadd_rn(m, (double) raw[d]); + m = m / (double) r; + s_mean[d] = m; + __syncthreads(); + + double ss = 0.0; + for (int i = 0; i < idx_dim; ++i) ss = __dadd_rn(ss, __dmul_rn(s_mean[i], s_mean[i])); + const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); + + const int b = pos / r; + pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]); + // The spare slot MOVES to b+1 and is rewritten with the same constant value. + pooled[(size_t) (b + 1) * idx_dim + d] = dead[d]; + // The rotation position for this row, kept because a capture reader and the debug dumps want it. It is the + // block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`. + if (d == 0) *block_pos = (int32_t) (pos_base + b * r); + __syncthreads(); // the row is complete only now; the rotation below reads TWO elements of it + + // ---- the rotation of the row that just completed, IN PLACE. + // + // `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the + // barrier above, which is why the guard is here and not around the whole block's tail. + // + // The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps + // every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence. + const int half = n_rot / 2; + if (d < half) { + float* row = pooled + (size_t) b * idx_dim; + const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half; + // THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES. A second transcription of the pairing is + // what this project keeps finding written down wrong. + rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]); + } +} + +// ================= 3. qsa_index ================= + +/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps +/// the row's score onto its cells. The reference's Relu is PER HEAD, so the dots cannot be summed first. +__global__ void qsa_index_kernel(const float* __restrict__ pooled, + const float* __restrict__ q_idx, const float* __restrict__ bias, + int idx_n_head, int idx_dim, long long r, + const int32_t* __restrict__ step, float* __restrict__ cell_scores) { + const long long n_bid = (long long) __ldg(step + kStepNBid); + const long long n_kv = (long long) __ldg(step + kStepNKv); + __shared__ double s_dot[32]; + const long long b = blockIdx.x; + // A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING. This is what lets the LAYER launch a CONSTANT + // grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value + // is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument. + // Without this guard, a capacity-sized grid would score pooled rows that have not been written yet - + // reading zeros and producing a plausible score for a block that does not exist. + if (b > n_bid) return; + const int wid = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (wid == 0) s_dot[lane] = 0.0; // thread 0 reads all idx_n_head entries; zero the unused ones + __syncthreads(); + + double acc = 0.0; + for (int d = lane; d < idx_dim; d += 32) + acc = __dadd_rn(acc, __dmul_rn((double) pooled[(size_t) b * idx_dim + d], + (double) q_idx[(size_t) wid * idx_dim + d])); + for (int o = 16; o > 0; o >>= 1) acc = __dadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, o)); + if (lane == 0) s_dot[wid] = acc; + __syncthreads(); + + if (threadIdx.x != 0) return; + double score = 0.0; + for (int h = 0; h < idx_n_head; ++h) score += (s_dot[h] > 0.0) ? s_dot[h] : 0.0; + if (bias != nullptr) score += (double) bias[b]; + // cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid + long long lo = b * r, hi = lo + r; + if (b == n_bid) hi = n_kv; + if (hi > n_kv) hi = n_kv; + // llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells + // a finite +1e9 bias before top-k. Read the current step on every replay: + // the spare row becomes an ordinary block as soon as its fourth cell arrives. + float sc = (float) score; + if (b == n_bid && n_kv % r != 0) sc += 1e9f; + for (long long j = lo; j < hi; ++j) cell_scores[j] = sc; +} + +// ================= 4. topk_512 ================= + +/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float +/// semantics. `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by +/// index), while the raw bit pattern orders them. A NaN is mapped to 0, below every real key, i.e. never +/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement. +__device__ __forceinline__ uint32_t order_key(float s) { + const float v = s + 0.0f; + if (!(v == v)) return 0u; + uint32_t b; + memcpy(&b, &v, 4); + return (b & 0x80000000u) ? ~b : (b | 0x80000000u); +} + +constexpr int TOPK_THREADS = 256; + +__global__ void topk_kernel(const float* __restrict__ scores, const int32_t* __restrict__ step, + int* __restrict__ out_ids) { + const long long n_kv = (long long) __ldg(step + kStepNKv); + const long long width = (long long) __ldg(step + kStepWidth); + __shared__ int s_a[TOPK_THREADS]; + __shared__ int s_b[TOPK_THREADS]; + __shared__ long long s_cgt; + const int t = threadIdx.x; + const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS; + const long long lo = (long long) t * chunk; + long long hi = lo + chunk; + if (hi > n_kv) hi = n_kv; + + // ---- binary lifting: the largest key v with count(key >= v) >= width. Monotone in v, so setting the + // bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1). + uint32_t v = 0u; + for (int bit = 31; bit >= 0; --bit) { + const uint32_t cand = v | (1u << bit); + int c = 0; + for (long long j = lo; j < hi; ++j) if (order_key(scores[j]) >= cand) ++c; + s_a[t] = c; + __syncthreads(); + for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) { + if (t < s) s_a[t] += s_a[t + s]; + __syncthreads(); + } + const int tot = s_a[0]; + __syncthreads(); // before the next round overwrites s_a + if (tot >= (int) width) v = cand; + } + const uint32_t thr = v; + + // ---- counts and their exclusive prefixes. The prefixes are computed by thread 0 in one walk, which is + // 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already + // 32 passes deep. + int gt = 0, eq = 0; + for (long long j = lo; j < hi; ++j) { + const uint32_t k = order_key(scores[j]); + if (k > thr) ++gt; + else if (k == thr) ++eq; + } + s_a[t] = gt; + s_b[t] = eq; + __syncthreads(); + if (t == 0) { + long long ag = 0, ae = 0; + for (int i = 0; i < TOPK_THREADS; ++i) { + const int g = s_a[i], e = s_b[i]; + s_a[i] = (int) ag; + s_b[i] = (int) ae; + ag += g; + ae += e; + } + s_cgt = ag; // how many are strictly above the threshold, i.e. where the equals start + } + __syncthreads(); + // THE RANK VS THE COUNT. `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is + // compared against `eq_budget`, the number of them the selection has room for. The first version wrote + // `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and + // compared THAT against the budget. With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing + // was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale. + // Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide. + const long long off_eq = s_b[t]; + const long long eq_budget = width - s_cgt; + + // ---- how many this chunk selects, so the ascending walk can be scattered into place + int sel = 0; + { + long long e = off_eq; + for (long long j = lo; j < hi; ++j) { + const uint32_t k = order_key(scores[j]); + if (k > thr) ++sel; + else if (k == thr && e < eq_budget) { ++sel; ++e; } + } + } + s_a[t] = sel; + __syncthreads(); + if (t == 0) { + long long a = 0; + for (int i = 0; i < TOPK_THREADS; ++i) { + const int c = s_a[i]; + s_a[i] = (int) a; + a += c; + } + } + __syncthreads(); + + // ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself + long long w = s_a[t]; + long long e = off_eq; + for (long long j = lo; j < hi; ++j) { + const uint32_t k = order_key(scores[j]); + if (k > thr) out_ids[w++] = (int) j; + else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; } + } +} + +// ================= 5. kv_gather ================= + +__global__ void kv_gather_kernel(const uint16_t* __restrict__ k_pool, const uint16_t* __restrict__ v_pool, + const int32_t* __restrict__ table, const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, + uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { + const long long n_ids = (long long) __ldg(step + kStepWidth); + const int per = head_dim / 4; // 4 halfs per uint2 + const long long total = n_ids * kv_heads * per; + const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; + if (i >= total) return; + const long long id = i / (kv_heads * (long long) per); + const int rem = (int) (i % (kv_heads * (long long) per)); + const int h = rem / per, q = rem - h * per; + const int cell = ids[id]; + const long long page = (long long) table[cell / page_size]; + const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q; + const long long dst = (id * kv_heads + h) * (long long) per + q; + reinterpret_cast(k_scratch)[dst] = reinterpret_cast(k_pool)[src]; + reinterpret_cast(v_scratch)[dst] = reinterpret_cast(v_pool)[src]; +} + +// ================= 6. qsa_attend ================= + +__device__ __forceinline__ float warp_max(float v) { + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} + +__device__ __forceinline__ float warp_sum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +/// One block per query head. `s` holds the scores, which are then overwritten with the softmax weights. +__global__ void qsa_attend_kernel(const float* __restrict__ q, const uint16_t* __restrict__ k_scratch, + const uint16_t* __restrict__ v_scratch, const int32_t* __restrict__ step, + int n_head, int n_head_kv, int head_dim, + float* __restrict__ attn, float* __restrict__ weights) { + const long long n_ids = (long long) __ldg(step + kStepWidth); + extern __shared__ float s_w[]; // CAPACITY floats (scores, then weights) + 32 for the reductions + float* red = s_w; // red[0..31] live past the scores/weights: see the launch + float* w = s_w + 32; + const int h = blockIdx.x; + const int d = threadIdx.x; + // AN EMPTY SELECTION IS HANDLED HERE, not by a host early return. The wrapper used to check `n_ids == 0` + // and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the + // device, and this is also the only form a graph can replay: the launch is unconditional and the kernel + // decides. Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is + // reachable only for a genuinely empty cache, and the reference returns zeros for that. + if (n_ids == 0) { + for (int i = d; i < head_dim; i += blockDim.x) attn[(size_t) h * head_dim + i] = 0.0f; + return; + } + const int kv = h / (n_head / n_head_kv); // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv + const float scale = 1.0f / sqrtf((float) head_dim); + const int lane = d & 31, wid = d >> 5, nwarp = (int) ((blockDim.x + 31) >> 5); + + for (long long j = d; j < n_ids; j += blockDim.x) { + const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim; + float acc = 0.0f; + for (int i = 0; i < head_dim; ++i) acc += h2f(krow[i]) * q[(size_t) h * head_dim + i]; + w[j] = acc * scale; + } + __syncthreads(); + + float mx = -FLT_MAX; // not -inf, whose double -> float conversion nvcc warns about + for (long long j = d; j < n_ids; j += blockDim.x) mx = fmaxf(mx, w[j]); + mx = warp_max(mx); + if (lane == 0) red[wid] = mx; + __syncthreads(); + if (wid == 0) { + mx = (lane < nwarp) ? red[lane] : -FLT_MAX; + mx = warp_max(mx); + if (lane == 0) red[0] = mx; + } + __syncthreads(); + mx = red[0]; + __syncthreads(); + + float sum = 0.0f; + for (long long j = d; j < n_ids; j += blockDim.x) { + const float e = expf(w[j] - mx); + w[j] = e; + sum += e; + } + sum = warp_sum(sum); + if (lane == 0) red[wid] = sum; + __syncthreads(); + if (wid == 0) { + sum = (lane < nwarp) ? red[lane] : 0.0f; + sum = warp_sum(sum); + if (lane == 0) red[0] = 1.0f / sum; + } + __syncthreads(); + const float inv = red[0]; + __syncthreads(); + + float acc = 0.0f; + for (long long j = 0; j < n_ids; ++j) + acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]); + attn[(size_t) h * head_dim + d] = acc; + if (weights != nullptr) { + for (long long j = d; j < n_ids; j += blockDim.x) weights[(size_t) h * n_ids + j] = w[j] * inv; + } +} + +// ================= 7. qsa_gate_apply ================= + +__global__ void qsa_gate_apply_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, + int n_head, int head_dim, uint16_t* __restrict__ out) { + const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; + if (i >= (long long) n_head * head_dim) return; + const int h = (int) (i / head_dim), d = (int) (i % head_dim); + const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half + const double sig = 1.0 / (1.0 + exp(-g)); + out[i] = f16_from_f32((float) ((double) attn[i] * sig)); +} + +inline unsigned grid_for(long long n, int threads) { + return (unsigned) ((n + threads - 1) / threads); +} + +} // namespace + +/// THE STEP STATE, UPLOADED. Every kernel below reads its per-token counts from here rather than from a kernel +/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`. This +/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels +/// already read the device values; the layer will pass its own buffer once it captures. +/// +/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same +/// stream and the host is the only writer. `cudaMemcpyAsync` on the null stream is ordered against the null +/// stream's kernels, which is what every direct-launch caller here uses. +namespace { + +int32_t* step_scratch() { + static int32_t* d_step = nullptr; + if (d_step == nullptr) { + if (cudaMalloc(&d_step, qsa_step_bytes()) != cudaSuccess) { + std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n"); + std::exit(1); + } + } + return d_step; +} + +void step_upload_raw(const int32_t* h_step) { + int32_t* d = step_scratch(); + if (cudaMemcpy(d, h_step, qsa_step_bytes(), cudaMemcpyHostToDevice) != cudaSuccess) { + std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n"); + std::exit(1); + } +} + +/// From a POSITION: fills all four entries. This is the form the layer will use, and the only form that cannot +/// produce an inconsistent `n_kv`/`n_bid`/`width`. +const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) { + int32_t h[kStepCount]; + qsa_step_fill(h, pos, s); + // A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the + // inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent + // preference for one of the two. + if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) { + std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint, + h[kStepNKv]); + std::exit(1); + } + step_upload_raw(h); + return step_scratch(); +} + +/// From a WIDTH. `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so +/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale, +/// because a stale entry is a value the NEXT kernel might read. +const int32_t* step_upload_width(int64_t width, const QsaShapes& s) { + int32_t h[kStepCount]; + for (int i = 0; i < kStepCount; ++i) h[i] = 0; + h[kStepWidth] = (int32_t) width; + (void) s; + step_upload_raw(h); + return step_scratch(); +} + +} // namespace + +// ================= THE CAPTURABLE ENTRY POINTS ================= +// +// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token +// count comes from `step`. The host-scalar entry points further down are wrappers that fill a module-level step +// buffer and forward this token's counts as the capacities. + +void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) { + validate(s, "kv_append"); + if (step == nullptr) fail("kv_append: step is null"); + // The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell. + const long long n = s.n_head_kv * s.head_dim; + kv_append_kernel<<>>( + k_pool, v_pool, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, + host ? *host : KvHostPools{}); + check_launch("kv_append"); + if (stream == nullptr) check_sync("kv_append"); +} + +void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s, + const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) { + validate(s, "qsa_index"); + if (step == nullptr) fail("qsa_index: step is null"); + if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive"); + // THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`. The kernel returns for + // `b > n_bid`, so the surplus blocks cost a launch and nothing else. + const int threads = 32 * (int) s.idx_n_head; + qsa_index_kernel<<<(unsigned) max_blocks, threads, 0, (cudaStream_t) stream>>>( + pooled, q_idx, bias, (int) s.idx_n_head, (int) s.idx_dim, s.idx_block, step, cell_scores); + check_launch("qsa_index"); + if (stream == nullptr) check_sync("qsa_index"); +} + +void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step, + int32_t* ids, void* stream) { + validate(s, "topk_512"); + if (step == nullptr) fail("topk_512: step is null"); + // `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this + // token's is a device value. The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and + // `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write. + const int64_t width_max = qsa_selection_width(kTopkMaxCells, s); + if (cap < width_max) { + std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n", + (long long) cap, (long long) width_max); + std::exit(1); + } + // One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`. + topk_kernel<<<1, TOPK_THREADS, 0, (cudaStream_t) stream>>>(cell_scores, step, ids); + check_launch("topk_512"); + if (stream == nullptr) check_sync("topk_512"); +} + +void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, + const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, + uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { + validate(s, "kv_gather"); + if (step == nullptr) fail("kv_gather: step is null"); + if (max_ids <= 0) return; + // THE GRID IS THE CAPACITY. The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;` + // guard leaves the surplus threads idle. + const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); + kv_gather_kernel<<>>( + k_pool, v_pool, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, + k_scratch, v_scratch); + check_launch("kv_gather"); + if (stream == nullptr) check_sync("kv_gather"); +} + +void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, + const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights, + void* stream) { + validate(s, "qsa_attend"); + if (step == nullptr) fail("qsa_attend: step is null"); + if (max_ids <= 0) fail("qsa_attend: max_ids must be positive"); + // THE SHARED SIZE IS THE CAPACITY. Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from + // this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and + // then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is + // exactly what it wants. The opt-in therefore happens once, for the capacity. + const size_t smem = (size_t) (max_ids + 32) * sizeof(float); + // per DEVICE: the opt-in is a device setting (a layer split runs this on two cards) + static size_t s_configured_dev[64] = {}; + int cur_dev = 0; + cudaGetDevice(&cur_dev); + size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0]; + if (smem > s_configured) { + int dev = 0, max_shared = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); + max_shared = strata::smem_optin_of(max_shared); + if ((int) smem > max_shared) { + std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n", + (long long) max_ids, smem, max_shared); + std::exit(1); + } + const cudaError_t e = + cudaFuncSetAttribute(qsa_attend_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa: qsa_attend: shared opt-in: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + s_configured = smem; + } + qsa_attend_kernel<<<(unsigned) s.n_head, (unsigned) s.head_dim, smem, (cudaStream_t) stream>>>( + q, k_scratch, v_scratch, step, (int) s.n_head, (int) s.n_head_kv, (int) s.head_dim, attn, weights); + check_launch("qsa_attend"); + if (stream == nullptr) check_sync("qsa_attend"); +} + +// ================= host entry points ================= + +void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) { + if (host_step == nullptr) return; + if (pos < 0) fail("qsa_step_fill: pos < 0"); + // ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four + // separate parameters. `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in + // itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency + // now has a single writer to check against instead of two independent arguments. + // + // This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one + // H2D per token updates all of them and no entry point takes a per-token scalar. + const int64_t n_kv = pos + 1; + host_step[kStepPos] = (int32_t) pos; + host_step[kStepNKv] = (int32_t) n_kv; + host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block); + host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s); +} + +void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos, + const float* kcur, const float* vcur, const QsaShapes& s, void* stream) { + if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); } + kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream); +} + +void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm, + float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab, + const float* sin_tab, void* stream) { + validate(s, "indexer_key_append"); + if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null"); + if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr) + fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)"); + const int threads = (int) s.idx_dim; + const size_t smem = (size_t) s.idx_dim * sizeof(double); + // **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.** The completion rotation is inside the kernel now. The + // arguments here are identical for every token, which is the property a CUDA graph needs: this function can + // be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data. + indexer_key_append_kernel<<<1, threads, smem, (cudaStream_t) stream>>>( + raw, pos_dev, (int) pos_base, w_k_norm, eps, b.tail, b.dead, b.pooled, b.block_pos, (int) s.idx_dim, + (int) s.idx_block, (int) s.n_rot, cos_tab, sin_tab, mrope_table()); + check_launch("indexer_key_append"); + if (stream == nullptr) check_sync("indexer_key_append"); +} + +void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s, + int64_t n_kv, float* cell_scores, void* stream) { + validate(s, "qsa_index"); + if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0"); + // `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments + // disagree rather than launching a kernel that would score the wrong number of blocks. + if ((n_kv / s.idx_block) != n_bid) { + std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid, + (long long) n_kv, (long long) s.idx_block); + std::exit(1); + } + // THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph. The layer passes a + // constant `max_blocks` from its state instead - see the note in `qsa.hpp`. + qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream); +} + +void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids, + void* stream) { + validate(s, "topk_512"); + if (n_kv <= 0) return; + if (n_kv > kTopkMaxCells) { + std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n", + (long long) n_kv, (long long) kTopkMaxCells); + std::exit(1); + } + topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream); +} + +void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, + int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { + validate(s, "kv_gather"); + if (n_ids <= 0) return; + kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch, + v_scratch, stream); +} + +void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids, + const QsaShapes& s, float* attn, float* weights, void* stream) { + validate(s, "qsa_attend"); + if (n_ids < 0) fail("qsa_attend: n_ids < 0"); + if (n_ids == 0) { + // The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the + // wrapper gives it the geometry's capacity rather than 0. + qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s), + qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream); + return; + } + qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream); +} + +/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller +/// whose weight is a K-quant needs the f32 form. Identical arithmetic up to the last step. +__global__ void qsa_gate_apply_f32_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, + int n_head, int head_dim, float* __restrict__ out) { + const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; + if (i >= (long long) n_head * head_dim) return; + const int h = (int) (i / head_dim), d = (int) (i % head_dim); + const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half + const double sig = 1.0 / (1.0 + exp(-g)); + out[i] = (float) ((double) attn[i] * sig); +} + +void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) { + validate(s, "qsa_gate_apply_f32"); + const long long n = s.n_head * s.head_dim; + qsa_gate_apply_f32_kernel<<>>(attn, q_full, (int) s.n_head, + (int) s.head_dim, out); + check_launch("qsa_gate_apply_f32"); + if (stream == nullptr) check_sync("qsa_gate_apply_f32"); +} + +void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) { + validate(s, "qsa_gate_apply"); + const long long n = s.n_head * s.head_dim; + qsa_gate_apply_kernel<<>>(attn, q_full, (int) s.n_head, + (int) s.head_dim, out); + check_launch("qsa_gate_apply"); + if (stream == nullptr) check_sync("qsa_gate_apply"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/qsa_decode_attn.cu b/engine/strata/src/kernels/cuda/qsa_decode_attn.cu new file mode 100644 index 00000000..c59f21d4 --- /dev/null +++ b/engine/strata/src/kernels/cuda/qsa_decode_attn.cu @@ -0,0 +1,329 @@ +// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/kv_q4.hpp" + +#include +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int HD = 256; // head_dim +constexpr int G = 12; // query heads per KV head (24 / 2) +constexpr int CHUNK = 64; // cells per block +constexpr int THREADS = 256; +constexpr int WARPS = THREADS / 32; + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} + +// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8). +// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side. +__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0; + const uint4 raw = *reinterpret_cast(base); + const __half2* h2 = reinterpret_cast(&raw); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 f = __half22float2(h2[j]); + out[2 * j] = f.x; + out[2 * j + 1] = f.y; + } +} +__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0; + const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP]; + const float sc = __half2float(__ushort_as_half(sbits)); + const uint2 raw = *reinterpret_cast(codes); + const int8_t* c = reinterpret_cast(&raw); +#pragma unroll + for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc; +} +__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); + const int b = d0 / QK4_0; + const int rem = d0 % QK4_0; + const block_q4_0* blk = reinterpret_cast((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b; + const float d = __half2float(__ushort_as_half(blk->d)); + const int j = (rem == 0 || rem == 16) ? 0 : 8; + const uint8_t* bytes = blk->qs + j; + if (rem < 16) { +#pragma unroll + for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d; + } else { +#pragma unroll + for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d; + } +} +template +__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); + else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) + if (value) load8_q4(p, value, row, d0, out); + else load8_q8(p, value, row, d0, out); + } else load8_q4(p, value, row, d0, out); +} + +template +__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ step, int n_kv_heads, + int page_size, float scale, float* __restrict__ part_acc, + float* __restrict__ part_m, float* __restrict__ part_l, + int n_chunks, int cap = 0, long long scratch_stride = 0) { + // batched form: query blockIdx.z, with its own q row, selection, step and scratch + q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD; + ids += (size_t) blockIdx.z * (size_t) cap; + step += (size_t) blockIdx.z * kStepCount; + part_acc += (size_t) blockIdx.z * (size_t) scratch_stride; + part_m += (size_t) blockIdx.z * (size_t) scratch_stride; + part_l += (size_t) blockIdx.z * (size_t) scratch_stride; + __shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads + __shared__ float sp[G][CHUNK]; // scores, then probabilities + __shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot) + const int n_ids = __ldg(step + kStepWidth); + const int chunk = blockIdx.x, kvh = blockIdx.y; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int c0 = chunk * CHUNK; + const int n_here = min(CHUNK, n_ids - c0); + const int slot = kvh * n_chunks + chunk; + if (n_here <= 0) { + if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; } + return; + } + for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i]; + if (t < CHUNK) { + long long r = -1; + if (t < n_here) { + const int cell = ids[c0 + t]; + const long long page = (long long) p.page_table[cell / page_size]; + // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked + // (score -FLT_MAX, weight 0) instead of being read from before the pool. + if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + srow[t] = r; + } + __syncthreads(); + // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. + for (int c = warp; c < CHUNK; c += WARPS) { + if (c >= n_here || srow[c] < 0) { + if (lane < G) sp[lane][c] = -FLT_MAX; + continue; + } + float k8[8]; + load8(p, KV_MODE == 4, srow[c], lane * 8, k8); + if constexpr (KV_MODE == 4) { + const int d0 = lane * 8, half = p.keyless_n_rot / 2; + if (d0 < p.keyless_n_rot) { + float paired[8]; + load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired); + const int cell = ids[c0 + c]; + for (int d = 0; d < 8; ++d) { + const int pair = (d0 + d) % half; + const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair); + const float co = p.keyless_cos[(size_t)rotary_pos * half + pair]; + const float si = p.keyless_sin[(size_t)rotary_pos * half + pair]; + k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si; + } + } + } +#pragma unroll + for (int h = 0; h < G; ++h) { + const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); + const float4 qb = *reinterpret_cast(&sq[h][lane * 8 + 4]); + float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w + + k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w; + s = warp_sum(s); + if (lane == 0) sp[h][c] = s * scale; + } + } + __syncthreads(); + // per-head chunk max and exp-sum: warp w handles heads w and w+8. + for (int h = warp; h < G; h += WARPS) { + const float a = sp[h][lane], b = sp[h][lane + 32]; + const float m = warp_max(fmaxf(a, b)); + const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f; + const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f; + sp[h][lane] = ea; + sp[h][lane + 32] = eb; + const float l = warp_sum(ea + eb); + if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; } + } + __syncthreads(); + // values: thread t owns dimension t for all 12 heads. + float acc[G]; +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = 0.0f; + for (int c = 0; c < n_here; ++c) { + if (srow[c] < 0) continue; // masked above, weight 0 + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); + } else if constexpr (KV_MODE == 1 || KV_MODE == 4) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back + constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0); + const int b = t / QK4_0; + const int rem = t % QK4_0; + const block_q4_0* blk = reinterpret_cast(p.v_q4 + srow[c] * bytes_per_head) + b; + const float d = __half2float(__ushort_as_half(blk->d)); + const int j = rem < 16 ? rem : (rem - 16); + const uint8_t byte = blk->qs[j]; + const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8); + v = (float) nibble * d; + } +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]); + } +#pragma unroll + for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h]; +} + +__global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict__ part_acc, + const float* __restrict__ part_m, + const float* __restrict__ part_l, int n_chunks, + float* __restrict__ attn, long long scratch_stride = 0) { + part_acc += (size_t) blockIdx.y * (size_t) scratch_stride; + part_m += (size_t) blockIdx.y * (size_t) scratch_stride; + part_l += (size_t) blockIdx.y * (size_t) scratch_stride; + attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD; + const int h = blockIdx.x; // global query head + const int kvh = h / G, hl = h % G; + const int d = threadIdx.x; + float M = -FLT_MAX; + for (int c = 0; c < n_chunks; ++c) M = fmaxf(M, part_m[(kvh * n_chunks + c) * G + hl]); + float L = 0.0f, acc = 0.0f; + for (int c = 0; c < n_chunks; ++c) { + const int slot = kvh * n_chunks + c; + const float m = part_m[slot * G + hl]; + if (m == -FLT_MAX) continue; + const float w = __expf(m - M); + L = fmaf(part_l[slot * G + hl], w, L); + acc = fmaf(part_acc[((size_t) slot * G + hl) * HD + d], w, acc); + } + attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f; +} + +} // namespace + +void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !steps || + !pools.page_table || n_q > 65535) { + std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || + !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { + std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); + std::exit(1); + } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; + if (kv_mode == 4) + attn_chunk_kernel<4><<>>(q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride); + else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 2) + attn_chunk_kernel<2><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 1) + attn_chunk_kernel<1><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else + attn_chunk_kernel<0><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + attn_merge_kernel<<>>(part_acc, part_m, part_l, n_chunks, + attn, stride); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + const int64_t chunks = (cap + CHUNK - 1) / CHUNK; + return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64; +} + +void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { + if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } + const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); + if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64) + : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) + : (!pools.k_pool || !pools.v_pool))))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } + if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || + !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { + std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); + std::exit(1); + } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; + float* part_l = part_m + (size_t) n_chunks * s.n_head; + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; + if (kv_mode == 4) + attn_chunk_kernel<4><<>>(q, pools, ids, step, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 2) + attn_chunk_kernel<2><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 1) + attn_chunk_kernel<1><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else + attn_chunk_kernel<0><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_decode_attn: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/qsa_prompt_attn.cu b/engine/strata/src/kernels/cuda/qsa_prompt_attn.cu new file mode 100644 index 00000000..4af82be2 --- /dev/null +++ b/engine/strata/src/kernels/cuda/qsa_prompt_attn.cu @@ -0,0 +1,1032 @@ +// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp. +#include "strata/core/emulate.hpp" +#include +#include +#include "strata/kernels/qsa_prompt_attn.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/kv_q4.hpp" + +#include +#include +#include + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int HD = 256; // head_dim +constexpr int G = 12; // query heads per KV head +#ifndef D1_CH +#define D1_CH 32 +#endif +constexpr int CH = D1_CH; // cells per chunk +constexpr int THREADS = 128; // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group) +constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free fragment loads) + +// The MMA below needs sm_75 or newer (Turing runs it as two k=8 steps); cp.async needs sm_80. Builds for pre-sm_75 +// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs +// there. Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8. +#if defined(__HIPCC__) // AMD: no mma.sync / cp.async; the host keeps the old kernel (below) +#define STRATA_PA_SM80 0 +#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define STRATA_PA_SM80 1 +#else +#define STRATA_PA_SM80 0 +#endif + +// m16n8k16 with f16 inputs needs sm_80. Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the +// k=16 step is two k=8 steps on the fragments as they are already laid out: a[0]/a[1] are rows gid/gid+8 at k columns +// 2*tig..2*tig+1 (b[0]'s k rows), a[2]/a[3] the same rows at k columns 2*tig+8..2*tig+9 (b[1]'s k rows). The +// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16 +// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit. +__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) { +#if !STRATA_PA_SM80 && (defined(__HIPCC__) || !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 750) + __trap(); // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there) +#elif !STRATA_PA_SM80 + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(b[0])); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[2]), "r"(a[3]), "r"(b[1])); +#else + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); +#endif +} + +// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152. +__device__ __forceinline__ uint32_t i8x2_to_h2(uint32_t x) { + uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u; + y |= 0x64006400u; + __half2 h = *reinterpret_cast<__half2*>(&y); + h = __hsub2(h, __halves2half2(__float2half(1152.f), __float2half(1152.f))); + return *reinterpret_cast(&h); +} + +__device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) { // element k in the low half + __half2 h = __floats2half2_rn(lo_k, hi_k); + return *reinterpret_cast(&h); +} + +// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1). +// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at +// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output. +template +struct Smem { + using KElem = typename std::conditional::type; + using VElem = typename std::conditional::type; + static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16; // elements; 16-byte aligned rows, banks spread + static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8; + __half qh[16][QS]; + __half ql[16][QS]; + KElem k[CH][KROW]; + VElem v[CH][VROW]; + float ks[CH][4]; + float vs[CH][4]; + float s[16][CH + 1]; + float qmax[THREADS / 32]; + float alpha[16]; + float lsum[16]; + float mrow[16]; + long long row[CH]; +}; + +template +__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, float* __restrict__ attn, + int cap) { + extern __shared__ __align__(16) unsigned char smem_raw[]; + Smem& S = *reinterpret_cast*>(smem_raw); + const int qi = blockIdx.x, kvh = blockIdx.y; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int gid = lane >> 2, tig = lane & 3; + + // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the + // lo halves stay out of FP16's subnormal range), then split into hi + lo halves + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); + if (lane == 0) S.qmax[warp] = qm; + __syncthreads(); + qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); + int qe = 0; + if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe + const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); + for (int i = t; i < 16 * HD; i += THREADS) { + const int h = i / HD, d = i % HD; + const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f; + const __half hi = __float2half_rn(x); + S.qh[h][d] = hi; + S.ql[h][d] = __float2half_rn(x - __half2float(hi)); + } + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } + + float acc[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; + + for (int c0 = 0; c0 < n; c0 += CH) { + const int nh = min(CH, n - c0); + if (t < CH) { + long long r = -1; + if (t < nh) { + const int cell = ids[c0 + t]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + S.row[t] = r; + } + __syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s + // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16) + // and their scales + { + constexpr int KPIECES = HD * (int) sizeof(typename Smem::KElem) / 16; // per K row + for (int i = t; i < CH * KPIECES; i += THREADS) { + const int c = i / KPIECES, pc = i % KPIECES; + const long long r = S.row[c]; + uint4 kx = make_uint4(0, 0, 0, 0); + if (r >= 0) { + if constexpr (KV_MODE == 0) + kx = __ldg(reinterpret_cast(p.k_pool + r * HD) + pc); + else // modes 1 and 3: the K side is INT8 + kx = __ldg(reinterpret_cast(p.k_q + r * HD) + pc); + } + *reinterpret_cast(reinterpret_cast(&S.k[c][0]) + pc * 16) = kx; + } + if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row + constexpr int BLKS = HD / QK4_0; + constexpr int BYTES = BLKS * (int) sizeof(block_q4_0); + for (int i = t; i < CH * BLKS; i += THREADS) { + const int c = i / BLKS, b = i % BLKS; + const long long r = S.row[c]; +#pragma unroll + for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0); + if (r >= 0) { + const block_q4_0* blk = reinterpret_cast(p.v_q4 + r * BYTES) + b; + const float d = __half2float(__ushort_as_half(blk->d)); +#pragma unroll + for (int j = 0; j < QK4_0 / 2; ++j) { + S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d); + S.v[c][b * QK4_0 + j + QK4_0 / 2] = + __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d); + } + } + } + } else { + constexpr int VPIECES = HD * (int) sizeof(typename Smem::VElem) / 16; // per V row + for (int i = t; i < CH * VPIECES; i += THREADS) { + const int c = i / VPIECES, pc = i % VPIECES; + const long long r = S.row[c]; + uint4 vx = make_uint4(0, 0, 0, 0); + if (r >= 0) { + if constexpr (KV_MODE == 1) + vx = __ldg(reinterpret_cast(p.v_q + r * HD) + pc); + else + vx = __ldg(reinterpret_cast(p.v_pool + r * HD) + pc); + } + *reinterpret_cast(reinterpret_cast(&S.v[c][0]) + pc * 16) = vx; + } + } + for (int i = t; i < CH * 4; i += THREADS) { + const int c = i / 4, g = i % 4; + const long long r = S.row[c]; + float a = 0.0f, b = 0.0f; + if (r >= 0) { + if constexpr (KV_MODE == 1) { + a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); + b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g])); + } else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1) + a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])); + b = 1.0f; + } else { + a = b = 1.0f; + } + } + S.ks[c][g] = a; + S.vs[c][g] = b; + } + } + __syncthreads(); + // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per 64-dim scale group +#pragma unroll + for (int nt = 0; nt < CH / 32; ++nt) { + const int cb = (warp + 4 * nt) * 8; + float sc[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int g = 0; g < 4; ++g) { + float tg[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + const int k0 = (g * 4 + kk) * 16; + uint32_t ah[4], al[4], b[2]; + ah[0] = *reinterpret_cast(&S.qh[gid][k0 + 2 * tig]); + ah[1] = *reinterpret_cast(&S.qh[gid + 8][k0 + 2 * tig]); + ah[2] = *reinterpret_cast(&S.qh[gid][k0 + 2 * tig + 8]); + ah[3] = *reinterpret_cast(&S.qh[gid + 8][k0 + 2 * tig + 8]); + al[0] = *reinterpret_cast(&S.ql[gid][k0 + 2 * tig]); + al[1] = *reinterpret_cast(&S.ql[gid + 8][k0 + 2 * tig]); + al[2] = *reinterpret_cast(&S.ql[gid][k0 + 2 * tig + 8]); + al[3] = *reinterpret_cast(&S.ql[gid + 8][k0 + 2 * tig + 8]); + if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes + b[0] = i8x2_to_h2(*reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig])); + b[1] = i8x2_to_h2(*reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig + 8])); + } else { + b[0] = *reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig]); + b[1] = *reinterpret_cast(&S.k[cb + gid][k0 + 2 * tig + 8]); + } + mma16816(tg, ah, b); +#ifndef D1_NO_QLO + mma16816(tg, al, b); +#endif + } + const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g]; + sc[0] = fmaf(tg[0], s0, sc[0]); + sc[1] = fmaf(tg[1], s1, sc[1]); + sc[2] = fmaf(tg[2], s0, sc[2]); + sc[3] = fmaf(tg[3], s1, sc[3]); + } + const int c = cb + 2 * tig; + S.s[gid][c] = c < nh ? sc[0] * qdown : -INFINITY; + S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -INFINITY; + S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -INFINITY; + S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -INFINITY; + } + __syncthreads(); + // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp) + { + constexpr int PER = CH / 8; + const int r = t >> 3, sub = t & 7; + float x[PER], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < PER; ++j) { x[j] = S.s[r][sub * PER + j]; mx = fmaxf(mx, x[j]); } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.s[r][sub * PER + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + __syncwarp(); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w. The scale is folded into p relative to + // the chunk's largest, times 2^14 (p' <= 2^14: its lo half stays out of FP16's subnormal range); the chunk's + // sum is then added to the running one in FP32 with the factor taken back out + { + float vmax = 0.0f; +#pragma unroll + for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + float tmp[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; +#pragma unroll + for (int ks = 0; ks < CH / 16; ++ks) { + const int cA = ks * 16 + 2 * tig, cB = cA + 8; + const float w0 = S.vs[cA][warp] * vup, w1 = S.vs[cA + 1][warp] * vup, w2 = S.vs[cB][warp] * vup, + w3 = S.vs[cB + 1][warp] * vup; + const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1; + const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1; + const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3; + const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3; + uint32_t ah[4], al[4]; + ah[0] = pack_h2(p00, p01); + ah[1] = pack_h2(p10, p11); + ah[2] = pack_h2(p02, p03); + ah[3] = pack_h2(p12, p13); + { + const __half2* h = reinterpret_cast(ah); + float2 f; + f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y); + f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y); + f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y); + f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = warp * 64 + j * 8 + gid; + uint32_t b[2]; + if constexpr (KV_MODE == 1) { + const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8); + const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8); + b[0] = i8x2_to_h2(x0); + b[1] = i8x2_to_h2(x1); + } else { + const __half2 h0 = __halves2half2(S.v[cA][d], S.v[cA + 1][d]); + const __half2 h1 = __halves2half2(S.v[cB][d], S.v[cB + 1][d]); + b[0] = *reinterpret_cast(&h0); + b[1] = *reinterpret_cast(&h1); + } + mma16816(tmp[j], ah, b); +#ifndef D1_NO_PLO + mma16816(tmp[j], al, b); +#endif + } + } + const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); + acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); + acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); + acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown); + } + } + } + __syncthreads(); + const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8]; + const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = warp * 64 + j * 8 + 2 * tig; + *reinterpret_cast(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0); + if (gid + 8 < G) + *reinterpret_cast(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1); + } +} + +// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a +// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own +// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums +// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic. +constexpr int CH2 = 32; + +struct Smem2 { + int8_t kv[2][4][2][CH2][64]; // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell + float sc[2][4][2][CH2]; // stage, warp, K/V scale of the cell for the warp's group + float part[4][16][CH2 + 1]; // q.k per dim group + float p[16][CH2 + 1]; + float qmax[4]; + float alpha[16]; + float lsum[16]; + float mrow[16]; +}; + +__device__ __forceinline__ int swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice + return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15); +} +__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) { +#if !STRATA_PA_SM80 + __trap(); +#else + const unsigned sa = (unsigned) __cvta_generic_to_shared(smem); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0)); +#endif +} +__device__ __forceinline__ void cp_async_commit() { +#if STRATA_PA_SM80 + asm volatile("cp.async.commit_group;\n" ::); +#endif +} +__device__ __forceinline__ void cp_async_wait1() { +#if STRATA_PA_SM80 + asm volatile("cp.async.wait_group 1;\n" ::); +#endif +} + +__global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, + float* __restrict__ attn, int cap) { + extern __shared__ __align__(16) unsigned char smem_raw[]; + Smem2& S = *reinterpret_cast(smem_raw); + const int qi = blockIdx.x, kvh = blockIdx.y; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int gid = lane >> 2, tig = lane & 3; + const int dim0 = warp * 64; + + // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); + if (lane == 0) S.qmax[warp] = qm; + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } + __syncthreads(); + qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); + int qe = 0; + if (qm > 0.0f) frexpf(qm, &qe); + const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); + uint32_t qh[4][4], ql[4][4]; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { +#pragma unroll + for (int r = 0; r < 4; ++r) { + const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8; + float2 x = make_float2(0.f, 0.f); + if (row < G) x = *reinterpret_cast(q + (size_t) row * HD + col); + x.x *= qup; + x.y *= qup; + const __half2 hi = __floats2half2_rn(x.x, x.y); + const float2 hf = __half22float2(hi); + const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y); + qh[kk][r] = *reinterpret_cast(&hi); + ql[kk][r] = *reinterpret_cast(&lo); + } + } + + // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead + const int n_chunks = (n + CH2 - 1) / CH2; + auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; }; + auto row_of = [&](int cell) -> long long { + if (cell < 0) return -1; + const long long page = (long long) __ldg(p.page_table + cell / page_size); + return (page * n_kv_heads + kvh) * page_size + (cell % page_size); + }; + auto issue = [&](long long r, int st, float& ksr, float& vsr) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3; + const long long rr = __shfl_sync(0xffffffffu, r, cell); + const bool ok = rr >= 0; + const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0; + cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok); + cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok); + } + ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f; + }; + float ksn, vsn; + issue(row_of(cell_of(lane)), 0, ksn, vsn); + cp_async_commit(); + S.sc[0][warp][0][lane] = ksn; + S.sc[0][warp][1][lane] = vsn; + long long r_next = row_of(cell_of(CH2 + lane)); + int cell_next2 = cell_of(2 * CH2 + lane); + + float acc[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f; + + for (int ci = 0; ci < n_chunks; ++ci) { + const int st = ci & 1, c0 = ci * CH2; + const bool more = ci + 1 < n_chunks; + if (more) issue(r_next, st ^ 1, ksn, vsn); + cp_async_commit(); + r_next = row_of(cell_next2); + cell_next2 = cell_of((ci + 3) * CH2 + lane); + cp_async_wait1(); + __syncwarp(); + const int8_t* K = &S.kv[st][warp][0][0][0]; + const int8_t* V = &S.kv[st][warp][1][0][0]; + // q.k over this warp's 64 dims, times the cell's K scale for this group +#pragma unroll + for (int nt = 0; nt < CH2 / 8; ++nt) { + float tg[4] = {0.f, 0.f, 0.f, 0.f}; + const int cell = nt * 8 + gid; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + uint32_t b[2]; + b[0] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig))); + b[1] = i8x2_to_h2(*reinterpret_cast(K + swz(cell, kk * 16 + 2 * tig + 8))); + mma16816(tg, qh[kk], b); + mma16816(tg, ql[kk], b); + } + const int c = nt * 8 + 2 * tig; + const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1]; + S.part[warp][gid][c] = tg[0] * s0; + S.part[warp][gid][c + 1] = tg[1] * s1; + S.part[warp][gid + 8][c] = tg[2] * s0; + S.part[warp][gid + 8][c + 1] = tg[3] * s1; + } + __syncthreads(); + // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread + { + const int r = t >> 3, sub = t & 7; + float x[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = sub * 4 + j; + x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown + : -INFINITY; + mx = fmaxf(mx, x[j]); + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.p[r][sub * 4 + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + __syncwarp(); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + // p.v over this warp's 64 dims (as v1) + { + float vmax = S.sc[st][warp][1][lane]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + float tmp[8][4]; +#pragma unroll + for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f; +#pragma unroll + for (int ks = 0; ks < CH2 / 16; ++ks) { + const int cA = ks * 16 + 2 * tig, cB = cA + 8; + const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup, + w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup; + const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1; + const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1; + const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3; + const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3; + uint32_t ah[4], al[4]; + ah[0] = pack_h2(p00, p01); + ah[1] = pack_h2(p10, p11); + ah[2] = pack_h2(p02, p03); + ah[3] = pack_h2(p12, p13); + { + const __half2* h = reinterpret_cast(ah); + float2 f; + f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y); + f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y); + f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y); + f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = j * 8 + gid; + const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8); + const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8); + uint32_t b[2]; + b[0] = i8x2_to_h2(x0); + b[1] = i8x2_to_h2(x1); + mma16816(tmp[j], ah, b); + mma16816(tmp[j], al, b); + } + } + const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown); + acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown); + acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown); + acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown); + } + } + if (more) { + S.sc[st ^ 1][warp][0][lane] = ksn; + S.sc[st ^ 1][warp][1][lane] = vsn; + } + __syncwarp(); + } + __syncthreads(); + const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8]; + const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int d = dim0 + j * 8 + 2 * tig; + *reinterpret_cast(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0); + if (gid + 8 < G) + *reinterpret_cast(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1); + } +} + +bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { + static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs this on several) + int dev = 0; + cudaGetDevice(&dev); + const int bytes = (int) sizeof(Smem2); + if (dev < 0 || dev >= 64) return false; + if (!attr[dev]) { + if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != + cudaSuccess) { + cudaGetLastError(); + return false; + } + attr[dev] = true; + } + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + prompt_attn_i8_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + +template +bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { + static bool attr[64] = {}; // per device, as above + int dev = 0; + cudaGetDevice(&dev); + const int bytes = (int) sizeof(Smem); + if (dev < 0 || dev >= 64) return false; + if (!attr[dev]) { + if (cudaFuncSetAttribute(prompt_attn_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != + cudaSuccess) { + cudaGetLastError(); + return false; + } + attr[dev] = true; + } + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + prompt_attn_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} + +#if defined(__HIPCC__) +// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of +// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims +// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter +// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order. +// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order). +// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds +// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7. +#if defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_PA_WMMA 1 +#else +#define STRATA_PA_WMMA 0 +#endif +typedef _Float16 wh8 __attribute__((ext_vector_type(8))); +typedef float wf8 __attribute__((ext_vector_type(8))); +constexpr int WCH = 32; // cells per chunk (two 16-cell tiles) +constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread) +struct alignas(16) SmemW { + float part[4][16][WCH + 1]; // q.k per dim group + float p[16][WCH + 1]; + float vs[4][WCH]; // V scale per (group, cell) + int valid[WCH]; // the cell has a resident pool row + uint8_t v[4][WCH][WVS]; // per wave: the chunk's V codes of its group, one row per cell + float qmax[4]; + float alpha[16]; + float lsum[16]; + float mrow[16]; +}; + +__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) { +#if STRATA_PA_WMMA + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +#else + __builtin_trap(); + return c; +#endif +} + +__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128 + wh8 h; +#pragma unroll + for (int i = 0; i < 4; ++i) { + h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i)); + h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i)); + } + return h; +} + +__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p, + const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, + int page_size, float scale_log2, + float* __restrict__ attn, int cap) { +#if STRATA_PA_WMMA + __shared__ SmemW S; + const int qi = blockIdx.x, kvh = blockIdx.y; + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + const int col = lane & 15, half = lane >> 4; // fragment column / k half + const int dim0 = warp * 64; + + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i])); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o)); + if (lane == 0) S.qmax[warp] = qm; + if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; } + __syncthreads(); + qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3])); + int qe = 0; + if (qm > 0.0f) frexpf(qm, &qe); + const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14); + // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i + wh8 qh[4], ql[4]; +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + float x[8]; + if (col < G) { + const float4* src = reinterpret_cast(q + (size_t) col * HD + dim0 + kk * 16 + half * 8); + const float4 a = src[0], b = src[1]; + x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w; + } else { +#pragma unroll + for (int i = 0; i < 8; ++i) x[i] = 0.0f; + } +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float v = x[i] * qup; + const _Float16 hi = (_Float16) v; + qh[kk][i] = hi; + ql[kk][i] = (_Float16) (v - (float) hi); + } + } + + wf8 acc[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) acc[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + + const int n_chunks = (n + WCH - 1) / WCH; + for (int ci = 0; ci < n_chunks; ++ci) { + const int c0 = ci * WCH; + // this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the + // KV streaming left non-resident: masked as in the decode kernel) + long long myrow = -1; + if (c0 + lane < n) { + const int cell = __ldg(ids + c0 + lane); + const long long page = (long long) __ldg(p.page_table + cell / page_size); + if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + // stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight + // from global memory (8 consecutive codes per lane) + { + uint4 v0 = make_uint4(0, 0, 0, 0), v1 = v0, v2 = v0, v3 = v0; + float vsc = 0.0f; + if (myrow >= 0) { + const uint4* src = reinterpret_cast(p.v_q + myrow * HD + dim0); + v0 = __ldg(src); v1 = __ldg(src + 1); v2 = __ldg(src + 2); v3 = __ldg(src + 3); + vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + myrow * (HD / KV_Q8_GROUP) + warp))); + } + uint4* dst = reinterpret_cast(&S.v[warp][lane][0]); + dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; + S.vs[warp][lane] = vsc; + if (warp == 0) S.valid[lane] = myrow >= 0; + } + // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group +#pragma unroll + for (int nt = 0; nt < 2; ++nt) { + const long long rr = __shfl(myrow, nt * 16 + col); + wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + float ksc = 0.0f; + if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp))); +#pragma unroll + for (int kk = 0; kk < 4; ++kk) { + uint2 kx = make_uint2(0, 0); + if (rr >= 0) kx = __ldg(reinterpret_cast(p.k_q + rr * HD + dim0 + kk * 16 + half * 8)); + const wh8 b = i8x8_to_h8(kx); + s = wmma_f16(qh[kk], b, s); + s = wmma_f16(ql[kk], b, s); + } +#pragma unroll + for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc; + } + __syncthreads(); + // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread + { + const int r = t >> 3, sub = t & 7; + float x[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = sub * 4 + j; + // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight + x[j] = S.valid[c] ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown + : -INFINITY; + mx = fmaxf(mx, x[j]); + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o)); + const float m_old = S.mrow[r]; + const float m_new = fmaxf(m_old, mx); + float sum = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new); + S.p[r][sub * 4 + j] = e; + sum += e; + } +#pragma unroll + for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new); + S.alpha[r] = a; + S.lsum[r] = fmaf(S.lsum[r], a, sum); + S.mrow[r] = m_new; + } + } + __syncthreads(); + // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells + { + float vmax = S.vs[warp][lane]; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o)); + const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f); + wf8 tmp[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll + for (int ks = 0; ks < 2; ++ks) { + const int cb = ks * 16 + half * 8; // this lane's 8 cells + wh8 ah, al; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup); + const _Float16 hi = (_Float16) pv; + ah[i] = hi; + al[i] = (_Float16) (pv - (float) hi); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = j * 16 + col; + wh8 b; +#pragma unroll + for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d]; + tmp[j] = wmma_f16(ah, b, tmp[j]); + tmp[j] = wmma_f16(al, b, tmp[j]); + } + } + float a[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i]; +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown); + } + // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next + // chunk's first barrier (which every wave reaches after its p.v) + } + float inv[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float l = S.lsum[half * 8 + i]; + inv[i] = l > 0.0f ? 1.0f / l : 0.0f; + } +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = half * 8 + i; + if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i]; + } +#else + __builtin_trap(); +#endif +} + +// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits +bool hip_wmma_usable() { + static const bool want = [] { + const char* e = std::getenv("STRATA_HIP_WMMA"); + return e != nullptr && e[0] == '1'; + }(); + if (!want) return false; + static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; } + if (arch[dev] == 0) { + hipDeviceProp_t prop{}; + if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; } + arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2; + static bool told = false; + if (!told) { + told = true; + std::fprintf(stderr, "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n", + arch[dev] == 1 ? "on" : "unavailable", prop.gcnArchName); + } + } + return arch[dev] == 1; +} + +bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) { + const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + prompt_attn_wmma_kernel<<>>( + q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv, + (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap); + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return true; +} +#endif + +} // namespace + +bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return true; + bool turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards) + { // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has + // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card + // keeps the old kernel. + // #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75) + static int cc[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc[dev] == 0) { + int major = 0, minor = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess || + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75 + : 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor); + } + if (cc[dev] < 75) return false; + turing = cc[dev] < 80; + } +#if defined(__HIPCC__) + // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV + // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel + (void) turing; + if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr && + pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv && + cap > 0 && ids && steps && pools.page_table && hip_wmma_usable()) + return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream); + return false; +#endif + if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || + !steps || !pools.page_table) + return false; + cudaStream_t st = (cudaStream_t) stream; + if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V + if (!pools.k_scale) return false; + return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (pools.k_q != nullptr) { + if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false; + // STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control + // for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not + // exist before sm_80. + static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr; + if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st); + return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (!pools.k_pool || !pools.v_pool) return false; + return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/qsa_select.cu b/engine/strata/src/kernels/cuda/qsa_select.cu new file mode 100644 index 00000000..745e6d84 --- /dev/null +++ b/engine/strata/src/kernels/cuda/qsa_select.cu @@ -0,0 +1,788 @@ +// src/kernels/cuda/qsa_select.cu - see include/strata/kernels/qsa_select.hpp. +#include "strata/core/emulate.hpp" +#include +#include +#include "strata/kernels/qsa_select.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int IDX_DIM = 128, IDX_HEADS = 4, R = 4; +constexpr int SCORE_WARPS = 8; +constexpr int TOPK_T = 256; + +__device__ __forceinline__ uint32_t order_key(float s) { + const float v = s + 0.0f; + if (!(v == v)) return 0u; + const uint32_t b = __float_as_uint(v); + return (b & 0x80000000u) ? ~b : (b | 0x80000000u); +} + +__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_kernel(const float* __restrict__ pooled, + const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, + int64_t max_blocks, float* __restrict__ out) { + const int64_t qi = blockIdx.y; + const int32_t* st = steps + qi * kStepCount; + const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid]; + const int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); + if (b > n_bid || b >= max_blocks) return; + const int lane = threadIdx.x & 31; + const float* key = (b == n_bid) ? dead : pooled + b * IDX_DIM; + const float4 k4 = *reinterpret_cast(key + lane * 4); + const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); + float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); + score += d > 0.0f ? d : 0.0f; + } + if (lane == 0) { + if (b == n_bid && n_kv % R != 0) score += 1e9f; + out[qi * max_blocks + b] = score; + } +} + +__global__ void __launch_bounds__(TOPK_T) block_topk_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, int64_t max_blocks, + int64_t cap, int32_t* __restrict__ ids) { + __shared__ int hist[256]; + __shared__ int s_a[TOPK_T], s_b[TOPK_T]; + __shared__ int s_digit, s_above; + const int64_t qi = blockIdx.x; + const int32_t* st = steps + qi * kStepCount; + const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; + int32_t* out = ids + qi * cap; + const int t = threadIdx.x; + if (n_kv <= width) { // everything is selected: the identity, ascending + for (int64_t j = t; j < n_kv; j += TOPK_T) out[j] = (int32_t) j; + return; + } + const float* sc = scores + qi * max_blocks; + const int64_t nb = n_bid + 1; // blocks 0..n_bid, the last possibly empty + const int64_t per = (nb + TOPK_T - 1) / TOPK_T; + const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb; + auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; + // ---- radix select: the largest key thr with (cells with key >= thr) >= width, 8 bits at a time + uint32_t prefix = 0; + int above = 0; // cells strictly above the digits fixed so far + for (int shift = 24; shift >= 0; shift -= 8) { + for (int i = t; i < 256; i += TOPK_T) hist[i] = 0; + __syncthreads(); + const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); + for (int64_t b = b0; b < b1; ++b) { + const int w = weight(b); + if (w == 0) continue; + const uint32_t k = order_key(sc[b]); + if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], w); + } + __syncthreads(); + if (t == 0) { + int cum = above, d = 255; + for (; d > 0; --d) { + if (cum + hist[d] >= width) break; + cum += hist[d]; + } + s_digit = d; + s_above = cum; + } + __syncthreads(); + prefix |= (uint32_t) s_digit << shift; + above = s_above; + __syncthreads(); + } + const uint32_t thr = prefix; + const int64_t eq_budget = width - above; // cells equal to thr that fit, lowest index first + // ---- per-thread counts of cells above and at the threshold, then their exclusive prefixes + int gt = 0, eq = 0; + for (int64_t b = b0; b < b1; ++b) { + const int w = weight(b); + if (w == 0) continue; + const uint32_t k = order_key(sc[b]); + if (k > thr) gt += w; + else if (k == thr) eq += w; + } + s_a[t] = gt; + s_b[t] = eq; + __syncthreads(); + if (t == 0) { + int ag = 0, ae = 0; + for (int i = 0; i < TOPK_T; ++i) { + const int g = s_a[i], e = s_b[i]; + s_a[i] = ag; s_b[i] = ae; + ag += g; ae += e; + } + } + __syncthreads(); + const int64_t eq_before = s_b[t]; + int64_t my_eq = eq_budget - eq_before; + if (my_eq < 0) my_eq = 0; + if (my_eq > eq) my_eq = eq; + const int sel = gt + (int) my_eq; + __syncthreads(); + s_a[t] = sel; + __syncthreads(); + if (t == 0) { + int a = 0; + for (int i = 0; i < TOPK_T; ++i) { const int c = s_a[i]; s_a[i] = a; a += c; } + } + __syncthreads(); + int64_t wpos = s_a[t]; + int64_t eq_left = my_eq; + for (int64_t b = b0; b < b1; ++b) { + const int w = weight(b); + if (w == 0) continue; + const uint32_t k = order_key(sc[b]); + if (k > thr) { + for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c); + } else if (k == thr) { + for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c); + } + } +} + + +// ---- QSA select on tensor cores (perf-review, after D-1): the block scores of many queries are one GEMM, +// rows (query, indexer head) x columns (blocks), K = 128, with relu per head summed. 3xTF32 (each operand split +// into a TF32 hi and lo part, hi*hi + hi*lo + lo*hi) keeps FP32-level accuracy; the summation order differs from +// the warp kernel, so a score can move in its last bits and a near-tie can select differently (not bitwise). +// Blocks < n_bid only; the tail block n_bid (the `dead` key, +1e9) is scored by the warp kernel's own code. +constexpr int TC_QT = 16; // queries per CTA (one m16 tile per indexer head) +constexpr int TC_NB = 32; // blocks per tile (4 warps x n8) +constexpr int TC_ITER = 4; // tiles per CTA (the query tile is loaded once) +constexpr int TC_QS = IDX_HEADS * IDX_DIM + 4; // query row stride in floats +constexpr int TC_KS = IDX_DIM + 4; // key row stride + +// TF32 conversion and MMA need sm_80: below it they compile to a trap and qsa_block_scores_tc refuses the device +#if defined(__HIPCC__) // AMD: no mma.sync / cp.async; the host keeps the warp kernel (below) +#define STRATA_SEL_SM80 0 +#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define STRATA_SEL_SM80 1 +#else +#define STRATA_SEL_SM80 0 +#endif +__device__ __forceinline__ uint32_t tf32_hi(float x) { +#if STRATA_SEL_SM80 + uint32_t r; + asm("cvt.rna.tf32.f32 %0, %1;" : "=r"(r) : "f"(x)); + return r; +#else + return __float_as_uint(x); +#endif +} +__device__ __forceinline__ void mma_tf32(float* c, const uint32_t* a, const uint32_t* b) { +#if !STRATA_SEL_SM80 + __trap(); +#else + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); +#endif +} + +__global__ void __launch_bounds__(128) block_scores_tc_kernel(const float* __restrict__ pooled, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int64_t nq, + int64_t max_blocks, int64_t reach, + float* __restrict__ out) { + extern __shared__ __align__(16) float sm[]; + float* sQ = sm; // [TC_QT][TC_QS] + float* sK = sm + TC_QT * TC_QS; // [TC_NB][TC_KS] + __shared__ int s_nbid[TC_QT]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5, gid = lane >> 2, tig = lane & 3; + const int64_t q0 = (int64_t) blockIdx.y * TC_QT; + for (int i = t; i < TC_QT * IDX_HEADS * IDX_DIM / 4; i += 128) { + const int r = i / (IDX_HEADS * IDX_DIM / 4), c = i % (IDX_HEADS * IDX_DIM / 4); + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (q0 + r < nq) v = reinterpret_cast(q_idx + (q0 + r) * IDX_HEADS * IDX_DIM)[c]; + *reinterpret_cast(sQ + r * TC_QS + c * 4) = v; + } + if (t < TC_QT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0; + int lo_nbid = 0x7fffffff, hi_nbid = 0; + __syncthreads(); + for (int i = 0; i < TC_QT; ++i) { + if (q0 + i >= nq) break; + lo_nbid = min(lo_nbid, s_nbid[i]); + hi_nbid = max(hi_nbid, s_nbid[i]); + } + for (int it = 0; it < TC_ITER; ++it) { + const int64_t b0 = ((int64_t) blockIdx.x * TC_ITER + it) * TC_NB; + if (b0 >= reach || b0 >= hi_nbid) break; // blocks >= every query's n_bid: nothing to score + __syncthreads(); // the previous tile's reads are done + for (int i = t; i < TC_NB * IDX_DIM / 4; i += 128) { + const int r = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4); + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (b0 + r < hi_nbid) v = reinterpret_cast(pooled + (b0 + r) * IDX_DIM)[c]; + *reinterpret_cast(sK + r * TC_KS + c * 4) = v; + } + __syncthreads(); + float acc[IDX_HEADS][4]; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) acc[h][0] = acc[h][1] = acc[h][2] = acc[h][3] = 0.f; + const float* kr = sK + (warp * 8 + gid) * TC_KS; +#pragma unroll 4 + for (int k0 = 0; k0 < IDX_DIM; k0 += 8) { + const float kx0 = kr[k0 + tig], kx1 = kr[k0 + tig + 4]; + uint32_t bh[2], bl[2]; + bh[0] = tf32_hi(kx0); + bh[1] = tf32_hi(kx1); + bl[0] = tf32_hi(kx0 - __uint_as_float(bh[0])); + bl[1] = tf32_hi(kx1 - __uint_as_float(bh[1])); +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float* qa = sQ + h * IDX_DIM + k0 + tig; + const float x0 = qa[gid * TC_QS], x1 = qa[(gid + 8) * TC_QS]; + const float x2 = qa[gid * TC_QS + 4], x3 = qa[(gid + 8) * TC_QS + 4]; + uint32_t ah[4], al[4]; + ah[0] = tf32_hi(x0); ah[1] = tf32_hi(x1); ah[2] = tf32_hi(x2); ah[3] = tf32_hi(x3); + al[0] = tf32_hi(x0 - __uint_as_float(ah[0])); + al[1] = tf32_hi(x1 - __uint_as_float(ah[1])); + al[2] = tf32_hi(x2 - __uint_as_float(ah[2])); + al[3] = tf32_hi(x3 - __uint_as_float(ah[3])); + mma_tf32(acc[h], al, bh); + mma_tf32(acc[h], ah, bl); + mma_tf32(acc[h], ah, bh); + } + } + // relu per head, heads added in order (as the warp kernel), written where the block completed for the query + const int64_t bc = b0 + warp * 8 + 2 * tig; +#pragma unroll + for (int half = 0; half < 2; ++half) { + const int qr = gid + half * 8; + const int64_t qi = q0 + qr; + if (qi >= nq) continue; + const int nb = s_nbid[qr]; +#pragma unroll + for (int j = 0; j < 2; ++j) { + const int64_t b = bc + j; + if (b >= nb || b >= max_blocks) continue; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float d = acc[h][half * 2 + j]; + score += d > 0.0f ? d : 0.0f; + } + out[qi * max_blocks + b] = score; + } + } + } +} + +#if defined(__HIPCC__) +// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32). Same GEMM as above: for a tile of 16 +// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128. FP32-level accuracy from a +// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32 +// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first; +// like the TF32 kernel it sums in another order than the warp kernel (not bitwise). The tail block n_bid is the warp +// kernel's arithmetic (block_scores_tail_kernel). +// D = A x B with A = 16 key blocks (row l%16 of a lane, k = 8*(l/16)+i), B = 16 queries (column l%16, same k): +// a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its +// 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are +// split once per CTA into LDS. +#if defined(__gfx1200__) || defined(__gfx1201__) +#define STRATA_SEL_GFX12 1 +#else +#define STRATA_SEL_GFX12 0 +#endif +typedef short sel_s8 __attribute__((ext_vector_type(8))); +typedef float sel_f8 __attribute__((ext_vector_type(8))); +typedef uint32_t sel_u4 __attribute__((ext_vector_type(4))); +constexpr int WQT = 16; // queries per CTA (the N of one WMMA) +constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks) +constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads + +__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) { +#if STRATA_SEL_GFX12 + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +#else + __trap(); + return c; +#endif +} +// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero) +__device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uint32_t& lo) { + hi = __float_as_uint(x) & 0xffff0000u; + const float r1 = x - __uint_as_float(hi); // exact + mid = __float_as_uint(r1) & 0xffff0000u; + lo = __float_as_uint(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left +} +__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's +#if STRATA_SEL_GFX12 + return __builtin_amdgcn_perm(b, a, 0x07060302u); +#else + return (a >> 16) | (b & 0xffff0000u); +#endif +} + +__global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __restrict__ pooled, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int64_t nq, + int64_t max_blocks, int64_t reach, + float* __restrict__ out) { + __shared__ __align__(16) uint16_t sq[3][IDX_HEADS][WQT][WQS]; // hi / mid / lo, [head][query][dim] + __shared__ int s_nbid[WQT]; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5, l16 = lane & 15, g = lane >> 4; + const int64_t q0 = (int64_t) blockIdx.y * WQT; + for (int i = t; i < WQT * IDX_HEADS * IDX_DIM / 4; i += 128) { + const int row = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4); + const int qr = row / IDX_HEADS, h = row % IDX_HEADS; + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (q0 + qr < nq) v = reinterpret_cast(q_idx + (q0 + qr) * IDX_HEADS * IDX_DIM)[h * (IDX_DIM / 4) + c]; + const float x[4] = {v.x, v.y, v.z, v.w}; + uint32_t hb[4], mb[4], lb[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) split3(x[j], hb[j], mb[j], lb[j]); + *reinterpret_cast(&sq[0][h][qr][c * 4]) = make_uint2(pack_bf16x2(hb[0], hb[1]), pack_bf16x2(hb[2], hb[3])); + *reinterpret_cast(&sq[1][h][qr][c * 4]) = make_uint2(pack_bf16x2(mb[0], mb[1]), pack_bf16x2(mb[2], mb[3])); + *reinterpret_cast(&sq[2][h][qr][c * 4]) = make_uint2(pack_bf16x2(lb[0], lb[1]), pack_bf16x2(lb[2], lb[3])); + } + if (t < WQT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0; + __syncthreads(); + int hi_nbid = 0; +#pragma unroll + for (int i = 0; i < WQT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]); + const int64_t qi = q0 + l16; + const int nb_q = s_nbid[l16]; + for (int it = 0; it < WITER; ++it) { + const int64_t b0 = (((int64_t) blockIdx.x * WITER + it) * 4 + warp) * 16; + if (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higher + const int64_t row = b0 + l16; + const bool rv = row < hi_nbid && row < max_blocks; + const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8; + // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a + // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7 + // of the score scale; apart, near the warp kernel's) + sel_f8 acc[IDX_HEADS], cor[IDX_HEADS]; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; +#pragma unroll 2 + for (int kk = 0; kk < IDX_DIM / 16; ++kk) { + float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0; + if (rv) { + k0 = *reinterpret_cast(kp + kk * 16); + k1 = *reinterpret_cast(kp + kk * 16 + 4); + } + const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w}; + uint32_t hb[8], mb[8], lb[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]); + sel_u4 ah, am, al; +#pragma unroll + for (int j = 0; j < 4; ++j) { + ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]); + am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]); + al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]); + } + const sel_s8 Ah = __builtin_bit_cast(sel_s8, ah), Am = __builtin_bit_cast(sel_s8, am), + Al = __builtin_bit_cast(sel_s8, al); +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const sel_s8 Bh = *reinterpret_cast(&sq[0][h][l16][kk * 16 + g * 8]); + const sel_s8 Bm = *reinterpret_cast(&sq[1][h][l16][kk * 16 + g * 8]); + const sel_s8 Bl = *reinterpret_cast(&sq[2][h][l16][kk * 16 + g * 8]); + cor[h] = wmma_bf16(Al, Bh, cor[h]); + cor[h] = wmma_bf16(Ah, Bl, cor[h]); + cor[h] = wmma_bf16(Am, Bm, cor[h]); + cor[h] = wmma_bf16(Ah, Bm, cor[h]); + cor[h] = wmma_bf16(Am, Bh, cor[h]); + acc[h] = wmma_bf16(Ah, Bh, acc[h]); + } + } + // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7 + if (qi < nq) { +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int64_t b = b0 + g * 8 + i; + if (b >= nb_q || b >= max_blocks) continue; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float d = acc[h][i] + cor[h][i]; + score += d > 0.0f ? d : 0.0f; + } + out[qi * max_blocks + b] = score; + } + } + } +} + +// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout) +bool sel_gfx12_device() { + static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (ok[dev] == 0) { + cudaDeviceProp prop; + ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess && + (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0)) + ? 1 : 2; + cudaGetLastError(); + } + return ok[dev] == 1; +} +#endif // __HIPCC__ + +// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block +__global__ void __launch_bounds__(32) block_scores_tail_kernel(const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, + int64_t max_blocks, float* __restrict__ out) { + const int64_t qi = blockIdx.x; + const int32_t* st = steps + qi * kStepCount; + const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid]; + if (n_bid >= max_blocks) return; + const int lane = threadIdx.x & 31; + const float4 k4 = *reinterpret_cast(dead + lane * 4); + const float* q = q_idx + qi * IDX_HEADS * IDX_DIM + lane * 4; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); + float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); + score += d > 0.0f ? d : 0.0f; + } + if (lane == 0) { + if (n_kv % R != 0) score += 1e9f; + out[qi * max_blocks + n_bid] = score; + } +} + +// ---- the same top-k with each query's keys read once: 1,024 threads hold up to TK_PER consecutive blocks' keys in +// registers (contexts up to 4 * 1024 * TK_PER cells), per-warp histograms, block-wide scans. The selection rule is +// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids. +constexpr int TK_T = 1024; +constexpr int TK_PER = 33; +#if defined(__HIPCC__) +// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts +// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per +// thread at 1,024 threads allow only TK_PER. +constexpr int TK_PER_MAX = 66; +#else +constexpr int TK_PER_MAX = TK_PER; +#endif + +__device__ __forceinline__ int block_excl_scan(int v, int* s_warp, int& total) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + int x = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, x, o); + if (lane >= o) x += y; + } + if (lane == 31) s_warp[warp] = x; + __syncthreads(); + if (warp == 0) { + int w = s_warp[lane]; + int z = w; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int y = __shfl_up_sync(0xffffffffu, z, o); + if (lane >= o) z += y; + } + s_warp[lane] = z - w; // exclusive per warp + if (lane == 31) s_warp[32] = z; // total + } + __syncthreads(); + const int r = s_warp[warp] + x - v; + total = s_warp[32]; + __syncthreads(); + return r; +} + +template +__global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __restrict__ scores, + const int32_t* __restrict__ steps, int64_t max_blocks, + int64_t cap, int32_t* __restrict__ ids) { + __shared__ int hist[TK_T / 32][256]; + __shared__ int s_warp[33]; + __shared__ int s_digit, s_above; + const int64_t qi = blockIdx.x; + const int32_t* st = steps + qi * kStepCount; + const int64_t n_kv = st[kStepNKv], n_bid = st[kStepNBid], width = st[kStepWidth]; + int32_t* out = ids + qi * cap; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + if (n_kv <= width) { + for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j; + return; + } + const float* sc = scores + qi * max_blocks; + const int64_t nb = n_bid + 1; + const int64_t per = (nb + TK_T - 1) / TK_T; // <= PER (the caller checks) + const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb; + uint32_t key[PER]; +#pragma unroll + for (int j = 0; j < PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u; + auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); }; + uint32_t prefix = 0; + int above = 0; + for (int shift = 24; shift >= 0; shift -= 8) { + for (int i = lane; i < 256; i += 32) hist[warp][i] = 0; + __syncwarp(); + const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8)); +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int64_t b = b0 + j; + if (b >= b1) break; + const int w = weight(b); + if (w == 0) continue; + if ((key[j] & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(key[j] >> shift) & 255], w); + } + __syncthreads(); + if (t < 256) { // fold the warps' histograms into warp 0's + int s = 0; + for (int w2 = 0; w2 < TK_T / 32; ++w2) s += hist[w2][t]; + hist[0][t] = s; + } + __syncthreads(); + if (t == 0) { + int cum = above, d = 255; + for (; d > 0; --d) { + if (cum + hist[0][d] >= width) break; + cum += hist[0][d]; + } + s_digit = d; + s_above = cum; + } + __syncthreads(); + prefix |= (uint32_t) s_digit << shift; + above = s_above; + __syncthreads(); + } + const uint32_t thr = prefix; + const int64_t eq_budget = width - above; + int gt = 0, eq = 0; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int64_t b = b0 + j; + if (b >= b1) break; + const int w = weight(b); + if (w == 0) continue; + if (key[j] > thr) gt += w; + else if (key[j] == thr) eq += w; + } + int tot; + const int eq_before = block_excl_scan(eq, s_warp, tot); + int64_t my_eq = eq_budget - eq_before; + if (my_eq < 0) my_eq = 0; + if (my_eq > eq) my_eq = eq; + const int sel = gt + (int) my_eq; + int64_t wpos = block_excl_scan(sel, s_warp, tot); + int64_t eq_left = my_eq; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int64_t b = b0 + j; + if (b >= b1) break; + const int w = weight(b); + if (w == 0) continue; + if (key[j] > thr) { + for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c); + } else if (key[j] == thr) { + for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c); + } + } +} + + +// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is +// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed +// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel. +// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode +// window, the uncaptured decode, and prefill's pooled16 call. +constexpr int MQ = 8; +__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled, + const float* __restrict__ dead, + const float* __restrict__ q_idx, + const int32_t* __restrict__ steps, int nq, + int64_t max_blocks, float* __restrict__ out) { + __shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM]; + __shared__ int64_t s_nkv[MQ], s_nbid[MQ]; + for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i]; + if (threadIdx.x < nq) { + s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv]; + s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid]; + } + __syncthreads(); + int64_t top = 0; + for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top; + const int lane = threadIdx.x & 31; + const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS; + for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) { + const float4 kp = *reinterpret_cast(pooled + b * IDX_DIM + lane * 4); + const float4 kd = *reinterpret_cast(dead + lane * 4); + for (int qi = 0; qi < nq; ++qi) { + const int64_t n_bid = s_nbid[qi]; + if (b > n_bid) continue; + const float4 k4 = (b == n_bid) ? kd : kp; + const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4; + float score = 0.0f; +#pragma unroll + for (int h = 0; h < IDX_HEADS; ++h) { + const float4 q4 = *reinterpret_cast(q + h * IDX_DIM); + float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o); + score += d > 0.0f ? d : 0.0f; + } + if (lane == 0) { + if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f; + out[qi * max_blocks + b] = score; + } + } + } +} +} // namespace + +void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { + if (nq <= 0) return; + if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535) { + std::fprintf(stderr, "qsa_block_scores: unsupported indexer geometry\n"); + std::exit(1); + } + // a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1) + static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }(); + if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16 + block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq, + max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); } + return; + } + const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; + const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq); + block_scores_kernel<<>>(pooled, dead, q_idx, steps, max_blocks, + scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +bool qsa_block_scores_tc(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks) { + if (nq <= 0) return true; + if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false; +#if defined(__HIPCC__) + // AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp + // kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false) + static const bool wmma_on = [] { + const char* v = std::getenv("STRATA_SELECT_WMMA"); + return v != nullptr && v[0] != '\0' && v[0] != '0'; + }(); + if (!wmma_on || !sel_gfx12_device()) return false; + { + const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; + const int64_t per = (int64_t) 4 * WITER * 16; + const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + WQT - 1) / WQT)); + block_scores_wmma_kernel<<>>(pooled, q_idx, steps, nq, max_blocks, reach, scores); + block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; + } +#else + { // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel + static int cc_major[64] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } + if (cc_major[dev] == 0) { + int major = 0; + if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess) { + cudaGetLastError(); + return false; + } + // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them + const char* w = std::getenv("STRATA_QSA_WARP"); + cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major); + } + if (cc_major[dev] < 8) return false; + } + static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs it on several) + int adev = 0; + cudaGetDevice(&adev); + const int bytes = (TC_QT * TC_QS + TC_NB * TC_KS) * (int) sizeof(float); + if (!attr[adev]) { + if (cudaFuncSetAttribute(block_scores_tc_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != + cudaSuccess) { + cudaGetLastError(); + return false; + } + attr[adev] = true; + } + const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks; + const int64_t per = (int64_t) TC_NB * TC_ITER; + const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + TC_QT - 1) / TC_QT)); + block_scores_tc_kernel<<>>(pooled, q_idx, steps, nq, max_blocks, reach, + scores); + block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); } + return true; +#endif +} + +void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream) { + if (nq <= 0) return; + if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) { + std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n"); + std::exit(1); + } + block_topk_kernel<<<(unsigned) nq, TOPK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) { + // keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1: + // the kernel that reads them from memory on every pass + static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr; + if (nq <= 0) return; + // the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity. + // Decode (no count) keeps the capacity rule and the original register width: nothing changes there. +#if defined(__HIPCC__) + const bool counted = active_blocks > 0; +#else + // CUDA keeps 0.1.32's capacity rule: #337's dispatch was measured on RDNA4 only, and on the RTX 5070 the 64K + // prompts read 1-3% slower with it + const bool counted = false; + (void) active_blocks; +#endif + const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks; + const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER); +#if defined(__HIPCC__) + constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref + const bool too_small = counted && reach < kRegMinBlocks; +#else + const bool too_small = false; +#endif + if (old || too_small || reach > fit) { + qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream); + return; + } + if (s.idx_block != R || cap < qsa_selection_width(kTopkMaxCells, s)) { + std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n"); + std::exit(1); + } + if (reach <= (int64_t) TK_T * TK_PER) + block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); + else + block_topk_reg_kernel<<<(unsigned) nq, TK_T, 0, (cudaStream_t) stream>>>(scores, steps, max_blocks, cap, ids); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_topk: %s\n", cudaGetErrorString(e)); std::exit(1); } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/quantize_act.cu b/engine/strata/src/kernels/cuda/quantize_act.cu new file mode 100644 index 00000000..ddd14dfb --- /dev/null +++ b/engine/strata/src/kernels/cuda/quantize_act.cu @@ -0,0 +1,313 @@ +// src/kernels/cuda/quantize_act.cu - P2.S2: quantize an activation the way ggml converts src1. +// +// WHY THIS EXISTS AT ALL. `ggml_mul_mat` converts the ACTIVATION (src1) to the weight's `vec_dot_type` +// before the dot product - the rule established over rounds 119-136 and written into `ref/quant.py` as +// `apply_src1`. The CPU expert path already honours it (`bench/micro/cpu_s2.cpp` quantizes to int8 and uses +// `vpdpbusd`), and its P0.T2 parity passes at 1.461e-06. The GPU kernels added in rounds 166-177 take FP16 +// activations instead. **Left that way, the two paths would compute different numbers for different experts +// of the SAME token** - not a tolerance question, an inconsistency inside one forward pass. +// +// Q2_0 IS THE CASE THAT MATTERS: the routed experts are all Q2_0, `Q2_0 -> Q8_0`, and that is 31.64 GiB of the +// 38 GiB pack. Q8_K (for the K-quants and IQ4_XS) is the other half of the table and is not here yet. +// +// THE THREE SUBTLETIES, each of which was paid for once already and is transcribed rather than recalled: +// +// 1. `d32 = amax / 127.0f` is computed in FP32, and the QUANTIZED INTEGERS divide by **d32**, not by the +// fp16-rounded value that gets stored. Conflating the two shifts every quant near a rounding boundary - +// measured against ggml's own bytes, 18 of 80 blocks differed, and because Q2_0 experts convert to Q8_0 +// the error landed in all 48 MoE blocks and made the end-to-end KL WORSE. +// 2. The reference divides in FLOAT64 (`blk.astype(np.float64) / float(np.float32(d32))`) and rounds with +// `rint` - half to even. This kernel therefore divides in double too: an FP32 division followed by +// `rintf` differs from the reference wherever the f32 quotient rounds across a .5 boundary. +// 3. The DEQUANTIZED value is `q * d16`, the fp16 scale, not `q * d32`. The block stores fp16 and that is +// what a reader multiplies by. +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK8_0 = 32; + +// THE fp16 CONVERSION LIVES IN `strata/kernels/f16_bits.hpp`, and this file used to carry its own copy. +// +// Round 198 found the private copy wrong in a way no fixture here could see: it tested `if (exp >= 31)` to +// detect an out-of-range exponent, which conflates an f32 INF/NAN (raw exponent 255) with a FINITE value too +// large for fp16. Every finite overflow - 1e30, 65536, 1e45 - came back as a NaN instead of saturating to +// inf, and this file's fixture is O(1) throughout, so it passed. A numpy-generated oracle caught it on its +// first run. Three copies of a converter whose failure mode is silent wrong bits was two copies too many. + + +__global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, + long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const float* xb = x + b * QK8_0; + uint8_t* out = blocks + b * 34; // { fp16 d ; int8 qs[32] } + + float amax = 0.0f; + for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); + if (amax == 0.0f) { + // ggml leaves the block zeroed: d = 0 and every q = 0. Writing the fp16 zero explicitly rather than + // skipping keeps the block layout deterministic for the byte comparison. + const uint16_t zb = f16_from_f32(0.0f); + out[0] = (uint8_t) (zb & 0xFF); + out[1] = (uint8_t) (zb >> 8); + for (int i = 0; i < QK8_0; ++i) out[2 + i] = 0; + return; + } + const float d32 = amax / 127.0f; + const uint16_t d16bits = f16_from_f32(d32); + out[0] = (uint8_t) (d16bits & 0xFF); + out[1] = (uint8_t) (d16bits >> 8); + + // double division, matching the reference exactly (subtlety 2) + for (int i = 0; i < QK8_0; ++i) { + double q = rint((double) xb[i] / (double) d32); + if (q > 127.0) q = 127.0; + if (q < -128.0) q = -128.0; + out[2 + i] = (uint8_t) (int8_t) q; + } +} + +/// **THE HIT PATH'S QUANTIZER, AND IT EXISTS TO REPRODUCE `act_quant_q8_1` EXACTLY (R4.2h, round 331).** +/// +/// The engine computes every routed expert twice. MISSES go through `cpu/expert.cpp:138 act_quant_q8_1` +/// into the VNNI kernel; HITS went through `quantize_q8_0` above. **Those are not the same quantization**, +/// and round 330 measured the difference with both real implementations linked +/// (`bench/micro/act_quant_parity.cu`): +/// +/// int8 activations differing : 0 of 2560 <- this rule's ties are measure-zero +/// chunks whose SCALE differs : 80 of 80, max rel 4.761e-04 <- 2^-11: fp32 vs the block's fp16 +/// +/// The scale is the difference that matters: `ActQ::scale` is `float` and the CPU kernel multiplies by it +/// (`expert.cpp:92`), while `row_dot_s2_q8` read `f16_at(xb)` out of the `block_q8_0`. So this variant +/// writes the SAME 34-byte blocks (the kernel's indexing is unchanged) **and** a parallel fp32 scale array +/// carrying `d32` unrounded. +/// +/// It also adopts the CPU's ROUNDING RULE - multiply by the reciprocal, round half AWAY FROM ZERO - rather +/// than this file's `rint`. That is deliberate and it is the opposite of the direction the comment above +/// argues for. `quantize_q8_0` was tuned to match **ggml's Q8_0 bytes**, which is right for the pack and for +/// `moe_hit_parity`. This function's job is different: it must match **this engine's own CPU reference**, +/// because a hit and a miss for the same expert on the same layer have to produce the same number. The CPU +/// path is the reference - C1 passes on it - so the hit path is brought to it, not the reverse. +__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, + float* __restrict__ scales, long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const float* xb = x + b * QK8_0; + uint8_t* out = blocks + b * 34; + + float amax = 0.0f; + for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i])); + // VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here + // is bit-identical to the `s` the CPU path used. + const float s = amax > 0.f ? amax / 127.f : 0.f; + const float inv = s > 0.f ? 1.f / s : 0.f; + scales[b] = s; + + const uint16_t d16bits = f16_from_f32(s); + out[0] = (uint8_t) (d16bits & 0xFF); + out[1] = (uint8_t) (d16bits >> 8); + for (int i = 0; i < QK8_0; ++i) { + // VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated + // toward zero, which is `lround`'s rule - round half away from zero. + const float t = xb[i] * inv; + const float r = t + (t >= 0.f ? 0.5f : -0.5f); + int v = (int) r; + v = v < -127 ? -127 : (v > 127 ? 127 : v); + out[2 + i] = (uint8_t) (int8_t) v; + } +} + +__global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x, + long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const uint8_t* blk = blocks + b * 34; + const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); + const float d = f32_from_f16(dbits); + float* out = x + b * QK8_0; + for (int i = 0; i < QK8_0; ++i) out[i] = (float) (int8_t) blk[2 + i] * d; +} + +// ===================== Q8_K ===================== +// +// `block_q8_K` = { float d ; int8_t qs[256] ; int16_t bsums[16] } = 292 bytes, no padding +// (`static_assert` in ggml-common.h). QK_K = 256. + +constexpr int QK_K = 256; +constexpr int Q8K_BYTES = 292; + +/// ggml's `nearest_int` (ggml-quants.c L621), transcribed rather than replaced. +/// +/// The magic number is 1.5 * 2^23: adding it forces the mantissa's integer part into the low bits, and the +/// mask/subtract recover it. The reason it is transcribed and not written as `rintf` is that the two differ +/// on exact ties - and that is the whole point of the constant, so a "cleaner" rewrite would silently change +/// which way ties go. +__device__ __forceinline__ int nearest_int_dev(float fval) { + const float val = fval + 12582912.0f; + int i; + memcpy(&i, &val, 4); + return (i & 0x007fffff) - 0x00400000; +} + +__global__ void quantize_q8_K_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks, + long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const float* xb = x + b * QK_K; + uint8_t* out = blocks + b * Q8K_BYTES; + float* d = (float*) out; + int8_t* qs = (int8_t*) (out + 4); + int16_t* bsums = (int16_t*) (out + 4 + QK_K); + + // `max` is the SIGNED value at the largest magnitude position, and the comparison is STRICTLY greater, + // so a tie keeps the FIRST maximum - which is what `np.argmax` does in the reference transcription too. + float max = 0.0f, amax = 0.0f; + for (int j = 0; j < QK_K; ++j) { + const float ax = fabsf(xb[j]); + if (ax > amax) { + amax = ax; + max = xb[j]; + } + } + if (amax == 0.0f) { + // ggml writes d = 0 and zeroes qs, then `continue`s - which LEAVES bsums UNWRITTEN. A zeroed block + // and an untouched one are indistinguishable to the dot product, but not to a byte comparison, so + // this zeroes bsums as well and the parity test's reference does the same. Recorded because it is a + // deliberate divergence from the letter of the source. + *d = 0.0f; + for (int j = 0; j < QK_K; ++j) qs[j] = 0; + for (int j = 0; j < QK_K / 16; ++j) bsums[j] = 0; + return; + } + const float iscale = -127.0f / max; // -127, NOT -128; see the header + for (int j = 0; j < QK_K; ++j) { + // `__fmul_rn`, NOT `iscale * xb[j]`. ggml computes the product, ROUNDS IT TO F32, and then adds + // 12582912.0f inside `nearest_int`. Written as a plain expression, nvcc CONTRACTS the multiply into + // the add as an FMA - which is a more accurate product but not the same one, and it flips the result + // wherever the true product sits just off a .5 boundary. The first version of this kernel differed + // from the reference in 1 element of 524,288 for exactly this reason, and `__fmul_rn` pins the + // rounding step the source actually performs. + const int v = nearest_int_dev(__fmul_rn(iscale, xb[j])); + qs[j] = (int8_t) min(127, v); // MIN only - the source has no lower clamp + } + for (int j = 0; j < QK_K / 16; ++j) { + int sum = 0; + for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; + bsums[j] = (int16_t) sum; + } + *d = 1.0f / iscale; +} + +__global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x, + long long n_blocks) { + const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= n_blocks) return; + const uint8_t* blk = blocks + b * Q8K_BYTES; + float d; + memcpy(&d, blk, 4); + const int8_t* qs = (const int8_t*) (blk + 4); + float* out = x + b * QK_K; + for (int i = 0; i < QK_K; ++i) out[i] = (float) qs[i] * d; +} + +} // namespace + +void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream) { + if (n <= 0) return; + if (n % QK8_0 != 0) { + std::fprintf(stderr, "quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0); + std::exit(1); + } + const long long nb = n / QK8_0; + const int threads = 128; + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + quantize_q8_0_kernel<<>>(x, blocks, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "quantize_q8_0 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +/// See `quantize_q8_0_scaled_kernel`. Writes the same 34-byte `block_q8_0` layout as `quantize_q8_0`, plus +/// `scales[n/32]` carrying the fp32 `s` the CPU path used - so a hit can be computed with the CPU's +/// multiplier instead of the block's fp16 `d`. `scales` must not be null. +void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream) { + if (n <= 0) return; + if (n % QK8_0 != 0) { + std::fprintf(stderr, "quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0); + std::exit(1); + } + if (scales == nullptr) { + std::fprintf(stderr, "quantize_q8_0_scaled: scales is null\n"); + std::exit(1); + } + const long long nb = n / QK8_0; + const int threads = 128; + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + quantize_q8_0_scaled_kernel<<>>(x, blocks, scales, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "quantize_q8_0_scaled launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream) { + if (n <= 0) return; + const long long nb = n / QK8_0; + const int threads = 128; + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + dequant_q8_0_kernel<<>>(blocks, x, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "dequant_q8_0 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +void quantize_q8_K(const float* x, uint8_t* blocks, int64_t n, void* stream) { + if (n <= 0) return; + if (n % QK_K != 0) { + std::fprintf(stderr, "quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K); + std::exit(1); + } + const long long nb = n / QK_K; + const int threads = 64; // one block per thread, and a block is 256 elements + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + quantize_q8_K_kernel<<>>(x, blocks, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "quantize_q8_K launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream) { + if (n <= 0) return; + const long long nb = n / QK_K; + const int threads = 64; + const unsigned grid = (unsigned) ((nb + threads - 1) / threads); + dequant_q8_K_kernel<<>>(blocks, x, nb); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "dequant_q8_K launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/rope.cu b/engine/strata/src/kernels/cuda/rope.cu new file mode 100644 index 00000000..807545eb --- /dev/null +++ b/engine/strata/src/kernels/cuda/rope.cu @@ -0,0 +1,136 @@ +// src/kernels/cuda/rope.cu - P2.S2: NEOX partial RoPE. +// +// Semantics from `ref/qsa.py` (`rope_freqs` + `rope_neox`), which `bench/micro/rope_xcheck` validates against +// the oracle: +// +// inv[i] = theta ** (-2i / n_rot) i in [0, n_rot/2) +// ang = pos * inv +// cos, sin = cos(ang), sin(ang) +// out[:half] = a*cos - b*sin a = x[:half], b = x[half:n_rot] +// out[half:n_rot] = a*sin + b*cos +// +// THE PAIRING IS NEOX - (i, i + n_rot/2), NOT the adjacent pair (2i, 2i+1). `ggml.h` writes NEOX +// n_dims=8 as [ccccssss]; the adjacent-pair ("NORMAL") ordering is the other common convention and choosing +// wrongly rotates the wrong dimensions together, which produces correctly-shaped output with scrambled +// content. It is also PARTIAL: only the first n_rot of head_dim are touched, here 64 of 256. +// +// WHY THE TABLE IS BUILT ON THE HOST. The reference computes the frequencies in FLOAT64 (`theta ** (...)` +// on a float64 arange, cos/sin in float64). Reproducing that on device means double-precision pow and cos, +// which are slow on a consumer GPU and - more to the point - not guaranteed to agree with the host's libm. +// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and +// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one +// loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token. +// +// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by +// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds +// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's +// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec. +#include "strata/kernels/rope.hpp" +#include "strata/kernels/mrope.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { + +namespace { +// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before +// session_init builds any table or captures any graph - and readers after it. +RopeScaling g_rope_scaling; +} // namespace + +void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; } +const RopeScaling& rope_scaling() { return g_rope_scaling; } + +void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) { + const int half = n_rot / 2; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + // float64 throughout, in the reference's order: inv, then ang, then cos/sin + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = (double) p * inv; + cos_tab[(size_t) p * half + i] = (float) std::cos(ang); + sin_tab[(size_t) p * half + i] = (float) std::sin(ang); + } + } +} + +void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) { + if (sc.type == RopeScalingType::None) { + build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); // the original loop, verbatim + return; + } + const int half = n_rot / 2; + const double fs = sc.freq_scale(); + const double ms = sc.mscale(); + double cd[2]; + sc.corr_dims(n_rot, cd); + const bool correct = sc.ext_factor != 0; // ggml: the correction rides on ext_factor, not the type + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot); + const double extrap = (double) p * inv; // the trained angle, ggml's theta_extrap + const double interp = fs * extrap; // ggml's theta_interp + double ang = interp; + if (correct) { + const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor; + ang = interp * (1.0 - ramp) + extrap * ramp; + } + cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms); + sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms); + } + } +} + +namespace { + +// ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copy +// with hreadIdx.x strided loops - so up to 32 threads wrote into the SAME row, with no barrier between the +// copy and the rotation, and a thread's copy of orow[i] could land AFTER another thread had rotated it. A +// race that silently writes the unrotated value is worse than a wrong answer: it is intermittent. +// +// A row is head_dim floats (256 here) and there are batch x heads of them, so one thread per row is a +// handful of threads for a token and removes the ordering question entirely rather than synchronising it. +__global__ void rope_neox_kernel(const float* __restrict__ x, float* __restrict__ out, long long rows, + int head_dim, int n_rot, const float* __restrict__ cos_tab, + const float* __restrict__ sin_tab, const int* __restrict__ pos, + const int32_t* __restrict__ mtab) { + const long long r = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (r >= rows) return; + const int half = n_rot / 2; + const float* xr = x + r * head_dim; + float* orow = out + r * head_dim; + + for (int d = n_rot; d < head_dim; ++d) orow[d] = xr[d]; // the PARTIAL rotation's untouched tail + for (int i = 0; i < half; ++i) { + const size_t toff = (size_t) mrope_pos(mtab, pos[r], i) * half; // the image path's per-pair position + // THE PAIRING AND THE SIGNS COME FROM `rope_neox_pair`, shared with the indexer's pooling kernel. + rope_neox_pair(xr[i], xr[half + i], cos_tab[toff + i], sin_tab[toff + i], orow[i], orow[half + i]); + } +} + +} // namespace + +void rope_neox_apply(const float* x, float* out, int64_t rows, int head_dim, int n_rot, const float* cos_tab, + const float* sin_tab, const int* pos, void* stream) { + if (rows <= 0 || n_rot <= 0) return; + if (n_rot % 2 != 0 || n_rot > head_dim) { + std::fprintf(stderr, "rope_neox_apply: n_rot %d must be even and <= head_dim %d\n", n_rot, head_dim); + std::exit(1); + } + const int threads = 128; + const unsigned grid = (unsigned) ((rows + threads - 1) / threads); + rope_neox_kernel<<>>(x, out, rows, head_dim, n_rot, cos_tab, + sin_tab, pos, mrope_table()); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "rope_neox_apply launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/router_top10.cu b/engine/strata/src/kernels/cuda/router_top10.cu new file mode 100644 index 00000000..f23a63d7 --- /dev/null +++ b/engine/strata/src/kernels/cuda/router_top10.cu @@ -0,0 +1,401 @@ +// src/kernels/cuda/router_top10.cu - P2.S2: the MoE router. +// +// P2.S2's spec: "BF16 GEMV, softmax / top-k / renormalize per docs/semantics.md; emits (expert_id, weight) x 10 +// per token". This is the softmax/top-k/renormalize half; the BF16 GEMV that produces the logits is a +// separate kernel and is NOT here. +// +// The semantics are transcribed from `ref/moe.py::router`, which is itself transcribed from llama-graph.cpp: +// +// p = softmax(logits) over ALL experts, not over the selected subset +// ids = stable argsort(-p)[:k] ties break by INDEX, ascending +// w = gather(p, ids) +// s = max(sum(w), 2**-14) ggml_clamp(..., 2**-14, INF) +// return ids, w / s +// +// The two-step structure matters and is not cosmetic: computing softmax over the selected subset instead is +// mathematically identical (softmax is shift-invariant) but it moves the renormalisation, and the CLAMP is +// part of the renormalisation. Reproducing the gather form is what makes the clamp land in the same place. +// +// WHY THIS IS NO LONGER "NAIVE BY DESIGN", AND WHAT THE OLD REASONING GOT WRONG. +// +// The first version was ONE THREAD PER TOKEN: k passes over the experts, each pass recomputing +// `exp((double) l[e] - mx)` for every expert. Its comment justified that with +// +// "5,120 operations per token against 2.36e9 weights of expert matvec - three orders of magnitude smaller +// than the thing it feeds, so the simplest correct version is also fast enough" +// +// **That is a statement about OPERATION COUNT and it says nothing about TIME, because all 5,120 operations were +// on ONE THREAD while the matvec has thousands.** Measured (round 218, stage-by-stage inside one block): +// +// moe_layer 4.077 ms router_top10 3.387 ms bf16 gemv 0.270 ms +// +// 3.39 ms per layer x 48 layers = 163 ms of a 289 ms token - **56% of the whole forward pass, in a kernel that +// reads 2.6 MB.** It was invisible in `router_top10_parity` because that test runs the kernel ONCE and checks +// the right ids, and invisible in every per-layer test for the same reason. +// +// WHAT IS PARALLELISED AND WHAT IS DELIBERATELY NOT: +// +// * the MAX is a tree reduction of `fmaxf`, which is exact and order-independent - bit-identical to the +// serial scan it replaces; +// * the 512 EXPONENTIALS are computed ONCE each, in parallel. The old kernel computed them ELEVEN TIMES +// (once for the softmax, then again inside every one of the k passes). This is where the 3.4 ms was; +// * the DOUBLE SUM is still accumulated on ONE thread in ASCENDING order. 512 double adds is about a +// microsecond and it keeps the accumulation order - and therefore the last bits - identical to the +// reference-faithful serial version. Parallelising it would be a free speedup and a silent change to the +// values, and the exp was the cost, not this; +// * the SELECTION is by RANK rather than by k repeated maxima: +// +// rank(e) = #{ f : p[f] > p[e] } + #{ f < e : p[f] == p[e] } +// +// which IS "stable descending argsort, ties by ascending index" - the same order the repeated-maximum loop +// produced - computed in ONE parallel pass over the experts instead of k serial ones. It is O(n^2) +// comparisons and that is the right trade here: n = 512, every comparison is independent, and the old +// version was O(k*n) with a serial `exp` inside. +#include "strata/kernels/router_top10.hpp" + +#include + +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int RT_MAX_THREADS = 512; + +/// One BLOCK per token, so the reductions have somewhere to happen. `n_tokens` is 1 in decode; the grid keeps +/// the batch case working without a second code path. +__global__ void router_top10_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k, + int* __restrict__ ids, float* __restrict__ weights) { + // **`s_taken` IS FIRST SO THE OTHER TWO KEEP THEIR ALIGNMENT WITHOUT AN OFFSET PARAMETER**, and `s_p`'s + // existing `s_ex + n_expert` stays correct because it is relative to `s_ex`. One byte per expert. + extern __shared__ unsigned char s_raw[]; + const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; + unsigned char* s_taken = s_raw; + double* s_ex = (double*) (s_raw + taken_bytes); + __shared__ float s_red[RT_MAX_THREADS / 32]; + __shared__ int s_rid[RT_MAX_THREADS / 32]; + __shared__ double s_sum; + + const int t = blockIdx.x; + if (t >= n_tokens) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const float* l = logits + (size_t) t * n_expert; + + // ---- softmax over ALL experts, for stability: the max. A tree of `fmaxf` is EXACT and order-independent, + // so this is bit-identical to the serial scan. + float mx = -INFINITY; + for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]); + for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off)); + if ((tid & 31) == 0) s_red[tid >> 5] = mx; + __syncthreads(); + if (tid < 32) { + const int nw = (nt + 31) >> 5; + float v = (tid < nw) ? s_red[tid] : -INFINITY; + for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off)); + if (tid == 0) s_red[0] = v; + } + __syncthreads(); + mx = s_red[0]; + + // ---- THE 512 EXPONENTIALS, ONCE EACH AND IN PARALLEL. `exp` in double is software-emulated on this die + // and was 5,632 serial calls before; it is 512 parallel ones now. + for (int e = tid; e < n_expert; e += nt) s_ex[e] = exp((double) l[e] - (double) mx); + __syncthreads(); + + // ---- the sum, ascending, on one thread: see the note above on why this is NOT parallelised. + if (tid == 0) { + double sum = 0.0; + for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; + s_sum = sum; + } + __syncthreads(); + const float inv = (float) (1.0 / s_sum); + + // ---- the selection, by rank. `p[e] = (float)(s_ex[e] * inv)` reproduces the old expression exactly: + // `(float)(exp((double) l[e] - (double) mx) * inv)` with `inv` a FLOAT. + // ---- p[] ONCE. The rank loop below compares every expert against every other, so computing + // `(float) (s_ex[f] * inv)` INSIDE it did **512 x 512 = 262,144** double multiplies and float converts per + // token per layer instead of 512 - and a consumer die runs FP64 at a small fraction of FP32, which is why + // this was worth more than the branch. The shared load stays either way; the ARITHMETIC is what goes. + // + // THIS IS BIT-IDENTICAL, not merely equivalent: `p[e]` is the same expression it was, computed once instead + // of 513 times, and the comparisons then see exactly the same floats. + float* s_p = (float*) (s_ex + n_expert); + for (int e = tid; e < n_expert; e += nt) s_p[e] = (float) (s_ex[e] * inv); + __syncthreads(); + + // ================================ THE SELECTION, IN k PASSES ================================ + // + // **THE RANK-BY-COUNTING LOOP COMPARED EVERY EXPERT AGAINST EVERY OTHER**: 512 x 512 = 262,144 shared + // loads and compares per token per layer, to choose ten things out of 512 - measured at 34.35 us, 63% of + // `moe_route`'s accounted cost and the largest single item in the R3 plan. The comment above records that + // the FP64 ARITHMETIC inside that loop was hoisted out once already ("262,144 double multiplies per token + // per layer instead of 512"); **the O(n^2) STRUCTURE was left, and it is the structure that costs.** + // + // `k` passes of a block-wide argmax is 10 x 512 = 5,120 compares - **51x less work** - and it produces the + // SAME ORDER. That is the whole correctness argument: scanning `e` ascending with a strict `>` keeps the + // LOWEST index on a tie, which is exactly the rule the rank loop spelled out as + // `else if (f < e && pf == pe) ++rank`. A stable descending top-k, ties by index. + for (int e = tid; e < n_expert; e += nt) s_taken[e] = 0; + __syncthreads(); + + for (int i = 0; i < k; ++i) { + float bv = -INFINITY; + int bi = n_expert; // a sentinel that loses to every real index + for (int e = tid; e < n_expert; e += nt) { + if (s_taken[e]) continue; + const float pe = s_p[e]; + if (pe > bv) { bv = pe; bi = e; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xffffffffu, bv, off); + const int oi = __shfl_down_sync(0xffffffffu, bi, off); + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } + } + if ((tid & 31) == 0) { s_red[tid >> 5] = bv; s_rid[tid >> 5] = bi; } + __syncthreads(); + if (tid < 32) { + const int nw = (nt + 31) >> 5; + float v = (tid < nw) ? s_red[tid] : -INFINITY; + int ix = (tid < nw) ? s_rid[tid] : n_expert; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xffffffffu, v, off); + const int oi = __shfl_down_sync(0xffffffffu, ix, off); + if (ov > v || (ov == v && oi < ix)) { v = ov; ix = oi; } + } + if (tid == 0 && ix < n_expert) { + ids[(size_t) t * k + i] = ix; + weights[(size_t) t * k + i] = v; + s_taken[ix] = 1; + } + } + __syncthreads(); + } + __syncthreads(); + + // ---- renormalise, with ggml's lower clamp. Order preserved. + if (tid == 0) { + double s = 0.0; + for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; + const double sc = fmax(s, 6.103515625e-05); // 2**-14 + for (int i = 0; i < k; ++i) + weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); + } +} + +#if defined(__HIPCC__) +// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel +// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64 +// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its +// ten weights from global memory one by one. Here: +// * the sum's ONLY use is inv = (float) (1.0 / sum). Every term is positive and the largest is exactly 1 +// (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum +// (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53). 1.0 / x and the float cast are monotone: when +// the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's. Otherwise +// (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before; +// * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the +// lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did; +// * the renormalisation sums the ten weights in rank order from registers and divides them in parallel. +// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast +// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the +// kernel above. +template +__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k, + int* __restrict__ ids, float* __restrict__ weights) { + extern __shared__ unsigned char s_raw[]; + const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; + double* s_ex = (double*) (s_raw + taken_bytes); + __shared__ float s_red[RT_MAX_THREADS / 32]; + __shared__ double s_dred[RT_MAX_THREADS / 32]; + __shared__ float s_inv; + const int t = blockIdx.x; + if (t >= n_tokens) return; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int nt = blockDim.x, nw = (nt + 31) >> 5; + const float* l = logits + (size_t) t * n_expert; + // the max: as router_top10_kernel (exact, order-independent) + float mx = -INFINITY; + for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]); + for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off)); + if (lane == 0) s_red[warp] = mx; + __syncthreads(); + if (tid < 32) { + float v = (tid < nw) ? s_red[tid] : -INFINITY; + for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off)); + if (tid == 0) s_red[0] = v; + } + __syncthreads(); + mx = s_red[0]; + // the exponentials (the same expression), and a tree sum of them for the bracket + double part = 0.0; + for (int e = tid; e < n_expert; e += nt) { + const double x = exp((double) l[e] - (double) mx); + s_ex[e] = x; + part += x; + } + for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off); + if (lane == 0) s_dred[warp] = part; + __syncthreads(); + double tot = 0.0; + for (int w = 0; w < nw; ++w) tot += s_dred[w]; + const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40); + const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo); + float inv; + if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) { + inv = f_lo; + } else { // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel + if (tid == 0) { + double sum = 0.0; + for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; + s_inv = (float) (1.0 / sum); + } + __syncthreads(); + inv = s_inv; + } + if (warp != 0) return; + // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression + constexpr int PER = 16; + float pv[PER]; + unsigned live = 0; +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int e = lane + 32 * j; + pv[j] = -INFINITY; + if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; } + } + float my_w = 0.0f; + int my_id = 0, nsel = 0; + for (int i = 0; i < k; ++i) { + float bv = -INFINITY; + int bi = n_expert; // a sentinel that loses to every real index +#pragma unroll + for (int j = 0; j < PER; ++j) + if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, off); + const int oi = __shfl_xor_sync(0xffffffffu, bi, off); + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } + } + if (bi >= n_expert) break; // as router_top10_kernel: no rank i or later is written (every p left is NaN) + if ((bi & 31) == lane) live &= ~(1u << (bi >> 5)); + if (lane == i) { my_w = bv; my_id = bi; } + nsel = i + 1; + } + if (nsel == k) { + double s = 0.0; + for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i); + const double sc = fmax(s, 6.103515625e-05); // 2**-14 + if (lane < k) { + ids[(size_t) t * k + lane] = my_id; + weights[(size_t) t * k + lane] = (float) ((double) my_w / sc); + } + } else { // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too + if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; } + __threadfence(); + if (lane == 0) { + double s = 0.0; + for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; + const double sc = fmax(s, 6.103515625e-05); + for (int i = 0; i < k; ++i) + weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); + } + } +} + +void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream, + int mode) { // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path + int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS; + threads = (threads + 31) & ~31; + const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; + const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float); + if (mode == 1) { + router_top10_fast_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( + logits, n_tokens, n_expert, k, ids, weights); + return; + } + if (mode == 2) { + router_top10_fast_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( + logits, n_tokens, n_expert, k, ids, weights); + return; + } + router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( + logits, n_tokens, n_expert, k, ids, weights); +} +#endif + +} // namespace + +bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, + void* stream, int variant) { +#if defined(__HIPCC__) + if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false; + if (variant < 0 || variant > 2) return false; + launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant); + return cudaGetLastError() == cudaSuccess; +#else + (void) logits; (void) n_tokens; (void) n_expert; (void) k; (void) ids; (void) weights; (void) stream; + (void) variant; + return false; +#endif +} + +void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, + void* stream) { +#if defined(__HIPCC__) + { + static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr; + if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) { + launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) { + const cudaError_t s = cudaDeviceSynchronize(); + if (s != cudaSuccess) { + std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s)); + std::exit(1); + } + } + return; + } + } +#endif + if (n_tokens <= 0 || n_expert <= 0 || k <= 0) return; + if (k > 64) { + std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k); + std::exit(1); + } + if (n_expert > RT_MAX_THREADS * 64) { + std::fprintf(stderr, "router_top10: n_expert %d is past the kernel's %d\n", n_expert, + RT_MAX_THREADS * 64); + std::exit(1); + } + int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS; + threads = (threads + 31) & ~31; // at least one full warp, for the reductions + // the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the + // probabilities. The mask is first so the two aligned arrays need no offset parameter. + const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u; + const size_t smem = + taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float); + router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>( + logits, n_tokens, n_expert, k, ids, weights); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) { + const cudaError_t s = cudaDeviceSynchronize(); + if (s != cudaSuccess) { + std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s)); + std::exit(1); + } + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s2_expert_grouped.cu b/engine/strata/src/kernels/cuda/s2_expert_grouped.cu new file mode 100644 index 00000000..925ac3a9 --- /dev/null +++ b/engine/strata/src/kernels/cuda/s2_expert_grouped.cu @@ -0,0 +1,1190 @@ +// src/kernels/cuda/s2_expert_grouped.cu - R4's grouped GPU expert. Read the header first. +// +// THE ARITHMETIC IS `src/kernels/cpu/expert.cpp`'s, over the same bytes, one warp per output row. +// +// sum_j (c_j - 1) * d_w * xhat_j * d_x == d_w * d_x * ( sum_j c_j*xhat_j - sum_j xhat_j ) +// +// Both sums are INT8 x INT8, so both are `__dp4a` - four multiply-accumulates per instruction, exact in +// integer and with no dequantization inside the loop. The weight scale `d_w` is fp16 (one per 64 elements) +// and the activation scale `d_x` is fp16 (one per 32 elements), so the float work is one multiply-add per +// 32-element chunk rather than one per element. +// +// **THE SUMMATION ORDER IS NOT THE CPU's AND CANNOT BE.** Lane `L` takes chunks `L, L+32, ...` and the +// partials are reduced through shuffle; the CPU walks every chunk in order with its own accumulator shape. +// The two agree to float rounding and not to the bit, which is the same contract `s_gemv_parity` carries for +// the same reason. `bench/micro/moe_hit_parity.cu` is the check. +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/dp4a.hpp" + +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +// THE BLOB'S OWN GEOMETRY, from `include/strata/kernels/cpu/expert.hpp`. Restated as literals because that +// header is the CPU path's and this file must not silently follow it if the two ever disagree: the sizes below +// are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end. +constexpr int H = 2560; +constexpr int FF = 640; +constexpr int QK = 64; // Q2_0's group: one fp16 scale per 64 weights +constexpr int ROW_GU = H / 4; // 640 B of codes per gate/up row (2 bits per element) +constexpr int ROW_D = FF / 4; // 160 B per down row +constexpr int SC_GU = H / QK; // 40 fp16 scales per gate/up row +constexpr int SC_D = FF / QK; // 10 per down row +constexpr size_t O_D_CODES = (size_t) 2 * FF * ROW_GU; +constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D; +constexpr size_t O_D_SCALES = O_GU_SCALES + (size_t) 2 * FF * SC_GU * 2; + +__device__ __forceinline__ float f16_at(const uint8_t* p) { + return __half2float(__ushort_as_half((uint16_t) (p[0] | (p[1] << 8)))); +} + +/// **ONE S2 ROW AGAINST A Q8_0 ACTIVATION, WARP-WIDE.** Every lane accumulates its own float partial over a +/// strided set of 32-element chunks and the caller reduces; `chunk` indices are absolute so the caller can +/// start the lane at any offset. +/// +/// Returns the lane's partial. `codes` is `n_in/4` bytes and `scales` `n_in/QK` fp16, both for THIS row. +/// +/// **`x_scales` IS R4.2h AND IT IS OPTIONAL ON PURPOSE.** When it is non-null the activation's multiplier +/// comes from an fp32 array instead of the block's fp16 `d`. The CPU pool multiplies by the fp32 +/// `ActQ::scale` (`cpu/expert.cpp:92`), and the two disagreed by **4.761e-04 relative on 80 of 80 chunks** +/// (`bench/micro/act_quant_parity.cu`), which is what made a cache hit compute a different expert from a +/// cache miss. Null keeps the previous fp16 behaviour **exactly**, so `moe_hit_parity` - which passes no +/// scales - still measures the kernel it always measured. +__device__ __forceinline__ float row_dot_s2_q8(const uint8_t* __restrict__ codes, + const uint8_t* __restrict__ scales, + const uint8_t* __restrict__ x_q8_0, int n_chunks, int lane, + const float* __restrict__ x_scales = nullptr) { + float acc = 0.0f; + for (int c = lane; c < n_chunks; c += 32) { + const uint8_t* cb = codes + (size_t) c * 8; // 8 code bytes = 32 elements + const uint8_t* xb = x_q8_0 + (size_t) c * 34; // one block_q8_0 + const float dx = x_scales ? x_scales[c] : f16_at(xb); + const int8_t* xq = (const int8_t*) (xb + 2); + + // ---- THE CODES, EXPANDED TO ONE BYTE PER ELEMENT, THEN FOUR AT A TIME INTO `dp4a`. + // + // The packed form is LSB-first: element 4j+k is bits [2k, 2k+2) of code byte j. `dp4a` needs both + // operands as packed int8, so each code byte becomes a word whose four bytes are its four 2-bit + // fields - which is exactly `(c & 3) | ((c>>2)&3)<<8 | ((c>>4)&3)<<16 | ((c>>6)&3)<<24`. + int s = 0; // sum of code * x + int hx = 0; // sum of x - the weight-independent term, as ones * x + const int ones = 0x01010101; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const unsigned cbyte = cb[j]; + const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) | + (((cbyte >> 6) & 3u) << 24)); + // **`memcpy`, NOT A CAST.** A `block_q8_0` is 34 BYTES - two of header then 32 of int8 - so the + // activation data at offset 2 is never 4-byte aligned, and `*(const int*)(xq + 4*j)` faults with + // "misaligned address". It faulted exactly that way on this kernel's first run. `memcpy` of a + // known 4 bytes compiles to whatever load is legal for the alignment, which is the point of using + // it rather than reasoning about which cast happens to work. + int xw; + memcpy(&xw, xq + 4 * j, 4); + s = STRATA_DP4A(cw, xw, s); + hx = STRATA_DP4A(ones, xw, hx); + } + // One weight scale per 64 elements, so per TWO 32-element chunks. + const float dw = f16_at(scales + (size_t) (c >> 1) * 2); + acc += dw * dx * (float) (s - hx); + } + return acc; +} + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + return v; +} + +/// GATE AND UP, ONE WARP PER ROW. +/// +/// **THE ROWS ARE INTERLEAVED AND THE FIRST VERSION OF THIS GOT IT WRONG.** In the blob, row-SLOT `i` of the +/// `2*FF` gate/up rows is gate row `i/2` when `i` is even and up row `(i-1)/2` when it is odd - that is what +/// `O_GU_CODES + (2r)*ROW_GU` and `+ (2r+1)*ROW_GU` mean in `expert.cpp`. This kernel decoded the correct +/// code row for slot `i` and then wrote it to output slot `i` of a layout whose first `FF` entries are gate and +/// whose last `FF` are up, which pairs `silu(gate[r]) * up[r]` with the WRONG `up` for every `r`. It produced +/// finite, plausible numbers. `moe_hit_parity` caught it on the first run, at worst relative error 2.2e+03. +/// +/// So slot `i` is DECODED from row-slot `i` and WRITTEN to the output slot its parity says it belongs to. +__global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + long long blob_bytes, const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits, + const int32_t* __restrict__ d_count = nullptr, + const int32_t* __restrict__ dst_index = nullptr, int tok_div = 0) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long slot = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long rows_per_hit = 2LL * FF; + const long long total = (long long) n_hits * rows_per_hit; + if (slot >= total) return; + const int h = (int) (slot / rows_per_hit); + if (d_count != nullptr && h >= *d_count) return; // token graph: capacity layout, device count + const int i = (int) (slot % rows_per_hit); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + if (tok_div > 0) { // plan v0.3 P6 verify window: each hit reads its own token's activation + const int tok = dst_index[h] / tok_div; + x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34; + if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32); + } + const float acc = row_dot_s2_q8(blob + (size_t) i * ROW_GU, + blob + O_GU_SCALES + (size_t) i * SC_GU * 2, x_q8_0, H / 32, lane, x_scales); + const float s = warp_sum(acc); + if (lane != 0) return; + // ---- THE OUTPUT LAYOUT IS GATE-MAJOR, AND THAT IS NOT COSMETIC. + // + // The first version wrote `gate_up[h*2FF + {0..FF-1}] = gate` and `[h*2FF + FF..] = up`, i.e. a per-hit + // [gate | up] pair, and then called the shared `swiglu_kernel` and `quantize_q8_0` over the whole buffer. + // Both of those walk a CONTIGUOUS range, so with more than one hit they read hit 0's UP rows where they + // wanted hit 1's GATE rows - finite numbers, wrong expert. With one hit it would have passed. + // + // Gate-major removes the mismatch instead of adding a stride to two other kernels: every hit's gate rows + // are contiguous from 0, every hit's up rows are contiguous from `n_hits * FF`, and the swiglu's output + // lands in the first `n_hits * FF` floats exactly where `quantize_q8_0` reads it. + const int r = i >> 1; + const size_t base = (i & 1) ? ((size_t) n_hits * FF + (size_t) h * FF) : ((size_t) h * FF); + gate_up[base + (size_t) r] = s; +} + +/// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and +/// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`. +/// +/// SiLU on the GATE and multiplied by up - the reading `docs/semantics.md` records, and the one that is wrong +/// the other way round in a way that still produces a finite number. +__global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) { + const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n_pairs) return; + const float g = gate_up[i]; + const float u = gate_up[n_pairs + i]; + gate_up[i] = (g / (1.0f + __expf(-g))) * u; +} + +/// DOWN, ONE WARP PER ROW, reading the quantized intermediate the caller produced. +/// +/// `dst_index[h]` is which row of the shared output buffer hit `h` fills - see the header. It is the router's +/// slot, not `h`, and the two differ on every layer where some experts are resident and some are not. +__global__ void down_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + const int32_t* __restrict__ dst_index, long long blob_bytes, + const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales, + float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count = nullptr) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long row = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long total = (long long) n_hits * H; + if (row >= total) return; + const int h = (int) (row / H); + if (d_count != nullptr && h >= *d_count) return; + const int r = (int) (row % H); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + const uint8_t* xb = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34; + const float acc = row_dot_s2_q8(blob + O_D_CODES + (size_t) r * ROW_D, + blob + O_D_SCALES + (size_t) r * SC_D * 2, xb, FF / 32, lane, + h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr); + const float s = warp_sum(acc); + if (lane == 0) out[(size_t) dst_index[h] * H + r] = s; +} + +// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS. `STRATA_OLD_GROUPED=1` keeps the kernels above. +// +// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.** `s = sum_e code_e * x_e` and +// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words +// gives the same two integers. The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303` +// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is +// the ACTIVATIONS that are regrouped, once per chunk, into +// +// X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] } +// +// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`. The kernels above spend seven integer +// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16 +// elements and `hx` is summed once per chunk. `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are +// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that. + +// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value. +__device__ __forceinline__ float f16_ld(const uint8_t* p) { + return __half2float(__ushort_as_half(*(const unsigned short*) p)); +} + +// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the +// code of element `16h + 4b + f`. +__device__ __forceinline__ void expand_codes(uint2 cb, int m[8]) { + const unsigned M = 0x03030303u; + m[0] = (int) (cb.x & M); + m[1] = (int) ((cb.x >> 2) & M); + m[2] = (int) ((cb.x >> 4) & M); + m[3] = (int) ((cb.x >> 6) & M); + m[4] = (int) (cb.y & M); + m[5] = (int) ((cb.y >> 2) & M); + m[6] = (int) ((cb.y >> 4) & M); + m[7] = (int) ((cb.y >> 6) & M); +} + +// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`. +// +// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.** The caller guarantees a 4-byte aligned activation row, so +// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the +// words are read aligned and funnel-shifted into place. The ninth word is read only in the 2-byte case, and then +// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is +// never a row's last. +__device__ __forceinline__ int load_x_chunk(const uint8_t* __restrict__ xb, int X[8]) { + const uint8_t* q = xb + 2; + const int off = (int) ((uintptr_t) q & 3); + const unsigned* p = (const unsigned*) (q - off); + const unsigned sh = (unsigned) off * 8; + unsigned v[9]; +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = __ldg(p + j); + v[8] = off != 0 ? __ldg(p + 8) : 0u; + unsigned n[8]; + int hx = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) { + // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same + // source needs no CUDA-only intrinsic. + n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh); + hx = STRATA_DP4A(0x01010101, (int) n[j], hx); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + const unsigned t0 = __byte_perm(n[4 * h], n[4 * h + 1], 0x5140); // a0 b0 a1 b1 + const unsigned t1 = __byte_perm(n[4 * h], n[4 * h + 1], 0x7362); // a2 b2 a3 b3 + const unsigned t2 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x5140); // c0 d0 c1 d1 + const unsigned t3 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x7362); // c2 d2 c3 d3 + X[4 * h + 0] = (int) __byte_perm(t0, t2, 0x5410); // a0 b0 c0 d0 + X[4 * h + 1] = (int) __byte_perm(t0, t2, 0x7632); // a1 b1 c1 d1 + X[4 * h + 2] = (int) __byte_perm(t1, t3, 0x5410); // a2 b2 c2 d2 + X[4 * h + 3] = (int) __byte_perm(t1, t3, 0x7632); // a3 b3 c3 d3 + } + return hx; +} + +// `s` for one chunk: the eight expanded code words against the eight regrouped activation words. +__device__ __forceinline__ int chunk_s(const int m[8], const int X[8]) { + int s = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) s = STRATA_DP4A(m[j], X[j], s); + return s; +} + +/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each +/// activation chunk is loaded and regrouped once for both rows. Per row, the lane's chunks, their order, the float +/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them. +__global__ void gu_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + long long blob_bytes, const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits, + const int32_t* __restrict__ d_count, const int32_t* __restrict__ dst_index, + int tok_div) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long total = (long long) n_hits * FF; + if (pair >= total) return; + const int h = (int) (pair / FF); + if (d_count != nullptr && h >= *d_count) return; + const int r = (int) (pair % FF); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + if (tok_div > 0) { + const int tok = dst_index[h] / tok_div; + x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34; + if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32); + } + const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU; // gate row; the up row follows it + const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2; + float acc_g = 0.0f, acc_u = 0.0f; + for (int c = lane; c < H / 32; c += 32) { + const uint8_t* xb = x_q8_0 + (size_t) c * 34; + const float dx = x_scales ? x_scales[c] : f16_ld(xb); + int X[8], m[8]; + const int hx = load_x_chunk(xb, X); + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); + const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2); + acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx); + expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m); + const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); + acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx); + } + const float sg = warp_sum(acc_g); + const float su = warp_sum(acc_u); + if (lane != 0) return; + gate_up[(size_t) h * FF + (size_t) r] = sg; // gate-major, as in `gu_kernel` + gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su; +} + +/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both. +__global__ void down_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index, + const int32_t* __restrict__ dst_index, long long blob_bytes, + const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales, + float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count) { + const int warps_per_block = (int) (blockDim.x >> 5); + const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const long long total = (long long) n_hits * (H / 2); + if (pair >= total) return; + const int h = (int) (pair / (H / 2)); + if (d_count != nullptr && h >= *d_count) return; + const int r = 2 * (int) (pair % (H / 2)); + const int lane = threadIdx.x & 31; + + const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes; + const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34; + const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr; + const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; + float acc0 = 0.0f, acc1 = 0.0f; + for (int c = lane; c < FF / 32; c += 32) { + const uint8_t* xb = xrow + (size_t) c * 34; + const float dx = xs ? xs[c] : f16_ld(xb); + int X[8], m[8]; + const int hx = load_x_chunk(xb, X); + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m); + const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); + acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx); + expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m); + const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); + acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane != 0) return; + const size_t o = (size_t) dst_index[h] * H + (size_t) r; + out[o] = s0; + out[o + 1] = s1; +} + +// The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the +// subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales. +__global__ void activation_correction_kernel(const uint8_t* q8, const float* scales, float* hx, int chunks) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= chunks) return; + const int8_t* q = (const int8_t*) (q8 + (size_t) c * 34 + 2); + int sum = 0; + for (int j = 0; j < 32; ++j) sum += q[j]; + hx[c] = __fmul_rn(scales[c], (float) sum); +} + +__device__ __forceinline__ int dot4(const uint8_t* codes, const int8_t* q) { + const unsigned c = *codes; + const int cw = (int) ((c & 3u) | (((c >> 2) & 3u) << 8) | + (((c >> 4) & 3u) << 16) | (((c >> 6) & 3u) << 24)); + int xw; + memcpy(&xw, q, sizeof xw); + return STRATA_DP4A(cw, xw, 0); +} + +__device__ __forceinline__ float row_dot_cpu_order(const uint8_t* codes, const uint8_t* scales, + const uint8_t* xq, const float* xs, + const float* hx, int blocks, int lane) { + float acc = 0.0f; + float corr = 0.0f; + for (int b = 0; b < blocks; ++b) { + const float d = f16_at(scales + 2 * b); + const int lo = dot4(codes + b * 16 + lane, + (const int8_t*) (xq + (size_t) (2 * b) * 34 + 2) + lane * 4); + const int hi = dot4(codes + b * 16 + 8 + lane, + (const int8_t*) (xq + (size_t) (2 * b + 1) * 34 + 2) + lane * 4); + acc = __fmaf_rn(__fmul_rn(d, xs[2 * b]), (float) lo, acc); + acc = __fmaf_rn(__fmul_rn(d, xs[2 * b + 1]), (float) hi, acc); + if (lane == 0) + corr = __fadd_rn(corr, __fmul_rn(d, __fadd_rn(hx[2 * b], hx[2 * b + 1]))); + } + // _mm_add_ps(low128, high128), then two _mm_hadd_ps. The pair order is 4, 1, 2; + // a standard shuffle tree in the order 4, 2, 1 is a different floating-point expression. + constexpr unsigned mask = 0xffffffffu; + acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 4, 8)); + acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 1, 8)); + acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 2, 8)); + return __fsub_rn(acc, corr); // Only lane zero is consumed. +} + +template +__global__ void cpu_order_projection_kernel(const uint8_t* blob_base, const int32_t* slots, + const int32_t* destinations, long long blob_bytes, + const uint8_t* xq, const float* xs, const float* hx, + float* out, int n_hits) { + constexpr int rows_per_hit = DOWN ? H : 2 * FF; + const int row = blockIdx.x * (blockDim.x / 8) + threadIdx.x / 8; + if (row >= n_hits * rows_per_hit) return; + const int h = row / rows_per_hit; + const int r = row % rows_per_hit; + const int lane = threadIdx.x & 7; + const uint8_t* blob = blob_base + (size_t) slots[h] * (size_t) blob_bytes; + const int chunks_offset = DOWN ? h * (FF / 32) : 0; + const uint8_t* codes = DOWN ? blob + O_D_CODES + (size_t) r * ROW_D : blob + (size_t) r * ROW_GU; + const uint8_t* scales = DOWN ? blob + O_D_SCALES + (size_t) r * SC_D * 2 + : blob + O_GU_SCALES + (size_t) r * SC_GU * 2; + const float value = row_dot_cpu_order(codes, scales, xq + (size_t) chunks_offset * 34, + xs + chunks_offset, hx + chunks_offset, + DOWN ? SC_D : SC_GU, lane); + if (lane != 0) return; + if (DOWN) out[(size_t) destinations[h] * H + r] = value; + else out[((r & 1) ? (size_t) n_hits * FF : 0) + (size_t) h * FF + (r >> 1)] = value; +} + +__global__ void cpu_order_swiglu_kernel(float* gu, int pairs) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= pairs) return; + const float g = gu[i]; + // Accurate fp32 exponential; __expf's approximation would introduce an additional source of error. + // CPU/GPU libc last-bit differences are diagnosed separately by the micro, not hidden with FP64 here. + const float eg = expf(-g); + gu[i] = __fmul_rn(__fdiv_rn(g, __fadd_rn(1.0f, eg)), gu[pairs + i]); +} + +__global__ void cpu_order_quantize_kernel(const float* x, uint8_t* blocks, float* scales, + float* hx, int chunks) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= chunks) return; + const float* xb = x + c * 32; + uint8_t* out = blocks + (size_t) c * 34; + float amax = 0.0f; + for (int j = 0; j < 32; ++j) amax = fmaxf(amax, fabsf(xb[j])); + const float s = amax > 0.0f ? __fdiv_rn(amax, 127.0f) : 0.0f; + const float inv = s > 0.0f ? __fdiv_rn(1.0f, s) : 0.0f; + scales[c] = s; + const uint16_t bits = __half_as_ushort(__float2half_rn(s)); + out[0] = (uint8_t) bits; + out[1] = (uint8_t) (bits >> 8); + int sum = 0; + for (int j = 0; j < 32; ++j) { + const float t = __fmul_rn(xb[j], inv); + int v = (int) __fadd_rn(t, t >= 0.0f ? 0.5f : -0.5f); + v = v < -127 ? -127 : (v > 127 ? 127 : v); + out[2 + j] = (uint8_t) (int8_t) v; + sum += v; + } + hx[c] = __fmul_rn(s, (float) sum); +} + +constexpr int THREADS = 256; + +void check(const char* who, void* stream) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e)); + std::exit(1); + } + // Deliberately NOT synchronising for a non-null stream: this is called once per layer from a captured + // graph's worth of work, and `finish()`'s null-stream sync in `s_gemv.cu` is the pattern that made a whole + // round of measurements the driver's cost instead of the kernel's (Memory/ERRORS.md RC-7). + (void) stream; +} + +// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or +// `moe_grouped_select_old` (the parity test runs both in one process). The environment is read once, on first use; +// the choice is made at each launch, so a captured graph keeps the kernels it was captured with. +std::atomic g_select_old{-1}; +// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query. +std::atomic g_last_path{-1}; + +bool old_kernels() { + const int s = g_select_old.load(std::memory_order_relaxed); + if (s >= 0) return s != 0; + static const bool env = [] { + const char* e = std::getenv("STRATA_OLD_GROUPED"); + return e != nullptr && e[0] == '1'; + }(); + return env; +} + +// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of +// capacity. The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer +// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures. Bitwise +// the same either way; default 0 (always the new kernels). Ignored while `moe_grouped_select_old` forces a choice. +long long pair_min_hits() { + if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0; + static const long long n = [] { + const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS"); + return e != nullptr ? std::atoll(e) : 0LL; + }(); + return n; +} + +// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation +// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which +// needs an 8-byte aligned arena and slot size (the grouped kernels above already did). Anything else keeps the +// previous kernels rather than issuing a misaligned load. +bool new_grouped(const void* x_q8_0, const void* scratch) { + const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0; + g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); + return fast; +} + +bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) { + const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 && + cap >= pair_min_hits(); + g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed); + return fast; +} + +// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows). +void launch_hit_gu(bool fast, const uint8_t* blob_base, const int32_t* slot_index, long long blob_bytes, + const uint8_t* x_q8_0, const float* x_scales, float* gate_up, long long cap, + const int32_t* d_count, const int32_t* dst_index, int tok_div, cudaStream_t cs) { + const int warps = THREADS / 32; + if (fast) { + const long long pairs = cap * (long long) FF; + gu_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); + } else { + const long long rows = cap * 2LL * FF; + gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div); + } +} + +void launch_hit_down(bool fast, const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + long long blob_bytes, const uint8_t* h_q8_0, const float* h_scales, float* out, long long cap, + const int32_t* d_count, cudaStream_t cs) { + const int warps = THREADS / 32; + if (fast) { + const long long pairs = cap * (long long) (H / 2); + down_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); + } else { + const long long rows = cap * (long long) H; + down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count); + } +} + +} // namespace + +void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); } + +int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); } + +uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) { + if (n_hits <= 0) return 0; + const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4; + const uint64_t q8 = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 34; + // R4.2h: the fp32 scales for the INTERMEDIATE's own quantization, one per 32-element chunk per hit. + const uint64_t hs = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 4; + const uint64_t xh = (uint64_t) (n_embd / 32) * 4; + return ((gu + 15) & ~15ull) + ((q8 + 15) & ~15ull) + 2 * ((hs + 15) & ~15ull) + + ((xh + 15) & ~15ull); +} + +void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out, + void* stream, const float* x_scales) { + if (n_hits <= 0) return; + cudaStream_t cs = (cudaStream_t) stream; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits); + + const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; + const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; + float* gate_up = (float*) scratch; + uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; + float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); + + // 1. gate + up, one launch for every row of every hit. + { + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr, + 0, cs); + check("moe_hit_grouped_s2/gu", stream); + } + // 2. silu(gate) * up. + { + const long long pairs = n_hits * (long long) FF; + const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS); + swiglu_kernel<<>>(gate_up, pairs); + check("moe_hit_grouped_s2/swiglu", stream); + } + // 3. the intermediate's own contract, which is `ggml_mul_mat`'s rule and NOT a choice: the down weight is + // Q2_0, whose `vec_dot_type` is Q8_0. `gate_up` holds the pairs; the product went into the first half. + // **R4.2h: the CPU quantizes this intermediate into `a2` with fp32 scales too** (`expert.cpp:232`), so + // when the caller supplies `x_scales` the intermediate gets the CPU's contract as well - otherwise the + // down projection would keep the very disagreement the gate/up projection just had removed. + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream); + // 4. down. + { + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs); + check("moe_hit_grouped_s2/down", stream); + } +} + +namespace { +// Plan v0.3 P4 token graph: which of this layer's routed experts are resident, decided ON THE DEVICE from the +// static residency row, so no host step sits between the ring and the hit kernels. One warp; k <= 32. +__global__ void hit_select_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int k, + int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst, + int32_t* __restrict__ count) { + const int lane = threadIdx.x; + int s = -1; + if (lane < k) { + const int e = ids[lane]; + if (e >= 0 && e < n_expert) s = res_row[e]; + } + const unsigned hit = __ballot_sync(0xffffffffu, s >= 0); + if (s >= 0) { + const int at = __popc(hit & ((1u << lane) - 1u)); + slot[at] = s; + dst[at] = lane; + } + if (lane == 0) *count = __popc(hit); +} + +// Plan v0.3 P6: the same for up to 128 routed entries (a verify window of T tokens x k): four warps, ballots +// compacted in entry order. +__global__ void hit_select_multi_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int n, + int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst, + int32_t* __restrict__ count) { + __shared__ int warp_count[4]; + const int i = threadIdx.x, lane = i & 31, warp = i >> 5; + int s = -1; + if (i < n) { + const int e = ids[i]; + if (e >= 0 && e < n_expert) s = res_row[e]; + } + const unsigned hit = __ballot_sync(0xffffffffu, s >= 0); + if (lane == 0) warp_count[warp] = __popc(hit); + __syncthreads(); + int before = 0; + for (int w = 0; w < warp; ++w) before += warp_count[w]; + if (s >= 0) { + const int at = before + __popc(hit & ((1u << lane) - 1u)); + slot[at] = s; + dst[at] = i; + } + if (i == 0) *count = warp_count[0] + warp_count[1] + warp_count[2] + warp_count[3]; +} + +__global__ void add_hits_kernel(float* __restrict__ parts, const float* __restrict__ hit_out, + const int32_t* __restrict__ dst, const int32_t* __restrict__ count, int n_embd) { + const int h = blockIdx.y; + if (h >= *count) return; + const size_t row = (size_t) dst[h] * (size_t) n_embd; + for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n_embd; i += gridDim.x * blockDim.x) + parts[row + i] += hit_out[row + i]; +} +} // namespace + +void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst, + int32_t* count, void* stream) { + if (k < 1 || k > 32) { std::fprintf(stderr, "moe_hit_select: k must be 1..32\n"); std::exit(1); } + hit_select_kernel<<<1, 32, 0, (cudaStream_t) stream>>>(ids, res_row, k, n_expert, slot, dst, count); + check("moe_hit_select", stream); +} + +void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, + void* scratch, float* out, void* stream, const float* x_scales) { + if (cap <= 0) return; + cudaStream_t cs = (cudaStream_t) stream; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); + const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; + const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; + float* gate_up = (float*) scratch; + uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; + float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); + { + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0, + cs); + check("moe_hit_grouped_s2_dev/gu", stream); + } + { + const long long pairs = cap * (long long) FF; + swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); + check("moe_hit_grouped_s2_dev/swiglu", stream); + } + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); + { + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); + check("moe_hit_grouped_s2_dev/down", stream); + } +} + +void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst, + int32_t* count, void* stream) { + if (n < 1 || n > 128) { std::fprintf(stderr, "moe_hit_select_multi: n must be 1..128\n"); std::exit(1); } + hit_select_multi_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, res_row, n, n_expert, slot, dst, count); + check("moe_hit_select_multi", stream); +} + +void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index, + const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0, + const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) { + if (cap <= 0) return; + cudaStream_t cs = (cudaStream_t) stream; + const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap); + const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; + const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; + float* gate_up = (float*) scratch; + uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; + float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); + { + launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index, + k_per_token, cs); + check("moe_hit_grouped_s2_multi/gu", stream); + } + { + const long long pairs = cap * (long long) FF; + swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); + check("moe_hit_grouped_s2_multi/swiglu", stream); + } + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream); + { + launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0, + x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs); + check("moe_hit_grouped_s2_multi/down", stream); + } +} + +namespace { +// Plan v0.3 P6: experts GROUPED - one blob pointer per group (a VRAM slot or a mapped host blob read over PCIe), +// every entry of the group (a token routed to that expert) computed from ONE read of each row. Per entry the +// arithmetic is `row_dot_s2_q8`'s, chunk by chunk in the same lane order, so every entry is bitwise the per-entry +// hit kernel's. +constexpr int GU_CHUNKS = (H / 32 + 31) / 32; // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes) +constexpr int GMAX = 8; // entries per group (tokens routed to one expert in a window) +// a group holds one entry per token of the window routed to its expert, and the kernels below keep at +// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word. +static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries"); +constexpr int GU_ROWS = 32; // gate/up rows per block: 4 per warp +constexpr int D_ROWS = 64; // down rows per block: 8 per warp + +// One activation chunk's contribution, `row_dot_s2_q8`'s inner body with the 32 int8 of the chunk already in +// aligned words: same dp4a sequence, same float expression, so the result is bitwise the per-entry kernel's. +__device__ __forceinline__ float chunk_dot(uint2 cb, const int* xw, float dw, float dx) { + const uint8_t* cbytes = (const uint8_t*) &cb; + int s = 0, hx = 0; + const int ones = 0x01010101; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const unsigned cbyte = cbytes[j]; + const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) | + (((cbyte >> 6) & 3u) << 24)); + s = STRATA_DP4A(cw, xw[j], s); + hx = STRATA_DP4A(ones, xw[j], hx); + } + return dw * dx * (float) (s - hx); +} + +// Gate/up: a block = GU_ROWS rows of ONE group. The group's activations (each entry's token row of x_q8_0 and +// its fp32 scales) are staged once into shared memory as aligned words; each warp then walks its rows, loading +// each lane's code chunks once and dotting them with every entry. +__global__ void __launch_bounds__(256) gu_grouped_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, + float* __restrict__ gate_up, int cap_entries) { + __shared__ int xs_q[GMAX][H / 4]; // the entries' int8 activations as words (2560 B each) + __shared__ float xs_d[GMAX][H / 32]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * (H / 32); i += blockDim.x) { + const int k = i / (H / 32), c = i - k * (H / 32); + const uint8_t* xb = x_q8_0 + (size_t) ent_tok[e0 + k] * (size_t) (H / 32) * 34 + (size_t) c * 34; + xs_d[k][c] = x_scales ? x_scales[(size_t) ent_tok[e0 + k] * (H / 32) + c] : f16_at(xb); + const int8_t* q = (const int8_t*) (xb + 2); +#pragma unroll + for (int w = 0; w < 8; ++w) { + int v; + memcpy(&v, q + 4 * w, 4); + xs_q[k][c * 8 + w] = v; + } + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * GU_ROWS; + for (int rr = warp; rr < GU_ROWS; rr += 8) { + const int i = row0 + rr; + const uint8_t* codes = blob + (size_t) i * ROW_GU; + const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2; + uint2 cb[GU_CHUNKS]; + float dw[GU_CHUNKS]; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c < H / 32) { + cb[q] = *(const uint2*) (codes + (size_t) c * 8); + dw[q] = f16_at(scales + (size_t) (c >> 1) * 2); + } + } + for (int k = 0; k < ne; ++k) { + float acc = 0.0f; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c >= H / 32) break; + acc += chunk_dot(cb[q], &xs_q[k][c * 8], dw[q], xs_d[k][c]); + } + const float sum = warp_sum(acc); + if (lane == 0) { + const int e = e0 + k, r = i >> 1; + const size_t base = (i & 1) ? ((size_t) cap_entries * FF + (size_t) e * FF) : ((size_t) e * FF); + gate_up[base + (size_t) r] = sum; + } + } + } +} + +// Down: a block = D_ROWS rows of ONE group; the entries' quantized intermediates staged once. A down row is 20 +// chunks, so lanes 0..19 each hold one chunk, as in the per-entry kernel. +__global__ void __launch_bounds__(256) down_grouped_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const uint8_t* __restrict__ h_q8_0, + const float* __restrict__ h_scales, + float* __restrict__ out) { + __shared__ int hs_q[GMAX][FF / 4]; + __shared__ float hs_d[GMAX][FF / 32]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * (FF / 32); i += blockDim.x) { + const int k = i / (FF / 32), c = i - k * (FF / 32); + const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) (FF / 32) * 34 + (size_t) c * 34; + hs_d[k][c] = h_scales ? h_scales[(size_t) (e0 + k) * (FF / 32) + c] : f16_at(xb); + const int8_t* q = (const int8_t*) (xb + 2); +#pragma unroll + for (int w = 0; w < 8; ++w) { + int v; + memcpy(&v, q + 4 * w, 4); + hs_q[k][c * 8 + w] = v; + } + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * D_ROWS; + for (int rr = warp; rr < D_ROWS; rr += 8) { + const int r = row0 + rr; + const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; + const int c = lane; + uint2 cb = make_uint2(0, 0); + float dw = 0.0f; + if (c < FF / 32) { + cb = *(const uint2*) (codes + (size_t) c * 8); + dw = f16_at(scales + (size_t) (c >> 1) * 2); + } + for (int k = 0; k < ne; ++k) { + float acc = 0.0f; + if (c < FF / 32) acc += chunk_dot(cb, &hs_q[k][c * 8], dw, hs_d[k][c]); + const float sum = warp_sum(acc); + if (lane == 0) out[(size_t) ent_dst[e0 + k] * H + r] = sum; + } + } +} + +// ---- The grouped kernels with the staged activations laid out for the reads. +// +// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.** `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so +// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes +// `hx`, which depends on the entry alone, for every row. Here the staging writes, once per (entry, chunk): +// +// xs_w[j][k * NC + c] word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words +// xs_dh[k * NC + c] (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a` +// +// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side +// conflicts and no padding is needed. Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`, +// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not +// once per entry. Per (row, entry) the lane's chunks, their order, the float expression and the shuffle +// reduction are the kernels' above, so every output is bitwise theirs. + +// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`. +template +__device__ __forceinline__ void stage_chunk(const uint8_t* __restrict__ xb, float dx, int* xs_w, int2* xs_dh, int i) { + int X[8]; + const int hx = load_x_chunk(xb, X); +#pragma unroll + for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j]; + xs_dh[i] = make_int2(__float_as_int(dx), hx); +} + +__global__ void __launch_bounds__(256) gu_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const uint8_t* __restrict__ x_q8_0, + const float* __restrict__ x_scales, + float* __restrict__ gate_up, int cap_entries) { + constexpr int NC = H / 32; + __shared__ int xs_w[8 * GMAX * NC]; // 20 KB: word j of entry k's chunk c at [j][k * NC + c] + __shared__ int2 xs_dh[GMAX * NC]; // 5 KB: (dx as bits, hx) + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * NC; i += blockDim.x) { + const int k = i / NC, c = i - k * NC; + const int tok = ent_tok[e0 + k]; + const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34; + const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb); + stage_chunk(xb, dx, xs_w, xs_dh, i); + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * GU_ROWS; // even: a pair is always (gate r, up r) + for (int pp = warp; pp < GU_ROWS / 2; pp += 8) { + const int i = row0 + 2 * pp; + const uint8_t* codes = blob + (size_t) i * ROW_GU; + const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2; + int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8]; + float dw0[GU_CHUNKS], dw1[GU_CHUNKS]; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c < NC) { + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0[q]); + expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m1[q]); + dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2); + dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2); + } + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; +#pragma unroll + for (int q = 0; q < GU_CHUNKS; ++q) { + const int c = lane + 32 * q; + if (c >= NC) break; + const int at = k * NC + c; + int X[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (GMAX * NC) + at]; + const int2 dh = xs_dh[at]; + const float dx = __int_as_float(dh.x); + acc0 += dw0[q] * dx * (float) (chunk_s(m0[q], X) - dh.y); + acc1 += dw1[q] * dx * (float) (chunk_s(m1[q], X) - dh.y); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane == 0) { + const int e = e0 + k, r = i >> 1; + gate_up[(size_t) e * FF + (size_t) r] = s0; + gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1; + } + } + } +} + +__global__ void __launch_bounds__(256) down_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const uint8_t* __restrict__ h_q8_0, + const float* __restrict__ h_scales, + float* __restrict__ out) { + constexpr int NC = FF / 32; + __shared__ int hs_w[8 * GMAX * NC]; + __shared__ int2 hs_dh[GMAX * NC]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, GMAX); + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + for (int i = t; i < ne * NC; i += blockDim.x) { + const int k = i / NC, c = i - k * NC; + const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34; + const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb); + stage_chunk(xb, dx, hs_w, hs_dh, i); + } + __syncthreads(); + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int row0 = blockIdx.x * D_ROWS; + for (int pp = warp; pp < D_ROWS / 2; pp += 8) { + const int r = row0 + 2 * pp; + const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D; + const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2; + const int c = lane; // lanes 0..19 hold one chunk each, as above + int m0[8], m1[8]; + float dw0 = 0.0f, dw1 = 0.0f; + if (c < NC) { + expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0); + expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m1); + dw0 = f16_ld(scales + (size_t) (c >> 1) * 2); + dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2); + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; + if (c < NC) { + const int at = k * NC + c; + int X[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (GMAX * NC) + at]; + const int2 dh = hs_dh[at]; + const float dx = __int_as_float(dh.x); + acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y); + acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y); + } + const float s0 = warp_sum(acc0); + const float s1 = warp_sum(acc1); + if (lane == 0) { + const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r; + out[o] = s0; + out[o + 1] = s1; + } + } + } +} +} // namespace + +namespace { +// Plan v0.3 P6: groups built on the device when every expert is resident at `base + id * blob` (the MTP layer): +// one block of 128 threads, groups in first-appearance order, entries of a group in routing order. +__global__ void group_resident_kernel(const int32_t* __restrict__ ids, int n, int k_per_tok, const uint8_t* base, + long long blob, unsigned long long* __restrict__ grp_ptr, + int32_t* __restrict__ grp_start, int32_t* __restrict__ counts, + int32_t* __restrict__ ent_dst, int32_t* __restrict__ ent_tok) { + __shared__ int e_s[128], first_s[128], size_s[128], gidx_s[128], gstart_s[129]; + const int i = threadIdx.x; + const int e = i < n ? ids[i] : -1; + e_s[i] = e; + __syncthreads(); + int first = i, rank = 0, size = 0; + if (i < n) { + for (int j = 0; j < i; ++j) + if (e_s[j] == e) { if (first == i) first = j; ++rank; } + if (first == i) + for (int j = i; j < n; ++j) size += e_s[j] == e; + } + first_s[i] = first; + size_s[i] = (i < n && first == i) ? size : 0; + __syncthreads(); + if (i == 0) { + int gi = 0, acc = 0; + for (int j = 0; j < n; ++j) + if (first_s[j] == j) { + gidx_s[j] = gi; + gstart_s[gi] = acc; + grp_ptr[gi] = (unsigned long long) (base + (size_t) e_s[j] * (size_t) blob); + grp_start[gi] = acc; + acc += size_s[j]; + ++gi; + } + grp_start[gi] = acc; + counts[0] = gi; + counts[1] = acc; + } + __syncthreads(); + if (i < n) { + const int at = gstart_s[gidx_s[first]] + rank; + ent_dst[at] = i; + ent_tok[at] = i / k_per_tok; + } +} +} // namespace + +void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob, + unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst, + int32_t* ent_tok, void* stream) { + if (n < 1 || n > 128) { std::fprintf(stderr, "moe_group_resident: n must be 1..128\n"); std::exit(1); } + group_resident_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, n, k_per_tok, base, (long long) blob, grp_ptr, + grp_start, counts, ent_dst, ent_tok); + check("moe_group_resident", stream); +} + +void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups, + const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, + const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream) { + if (cap_groups <= 0 || cap_entries <= 0) return; + cudaStream_t cs = (cudaStream_t) stream; + const uint64_t gu_bytes = ((uint64_t) cap_entries * (uint64_t) (2 * FF) * 4 + 15) & ~15ull; + const uint64_t q8_bytes = ((uint64_t) cap_entries * (uint64_t) (FF / 32) * 34 + 15) & ~15ull; + float* gate_up = (float*) scratch; + uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes; + float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes); + const bool fast = new_grouped(x_q8_0, scratch); + { + const dim3 grid((unsigned) (2 * FF / GU_ROWS), (unsigned) cap_groups); + if (fast) + gu_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, + gate_up, (int) cap_entries); + else + gu_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, gate_up, + (int) cap_entries); + check("moe_grouped_s2/gu", stream); + } + { + const long long pairs = cap_entries * (long long) FF; + swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs); + check("moe_grouped_s2/swiglu", stream); + } + if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream); + else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream); + { + const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups); + const float* hs = x_scales != nullptr ? h_scales : nullptr; + if (fast) + down_grouped_t_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); + else + down_grouped_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out); + check("moe_grouped_s2/down", stream); + } +} + +void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap, + int64_t n_embd, void* stream) { + if (cap <= 0) return; + const dim3 grid((unsigned) ((n_embd + 255) / 256 < 8 ? (n_embd + 255) / 256 : 8), (unsigned) cap); + add_hits_kernel<<>>(parts, hit_out, dst, count, (int) n_embd); + check("moe_hit_add", stream); +} + +void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index, + const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes, + const uint8_t* x_q8_0, void* scratch, float* out, void* stream, + const float* x_scales, float* gate_up_trace) { + if (n_hits <= 0) return; + if (x_scales == nullptr) { + std::fprintf(stderr, "moe_hit_grouped_s2_cpu_order requires fp32 activation scales\n"); + std::exit(1); + } + cudaStream_t cs = (cudaStream_t) stream; + const uint64_t gu_bytes = ((uint64_t) n_hits * 2 * FF * 4 + 15) & ~15ull; + const uint64_t q8_bytes = ((uint64_t) n_hits * (FF / 32) * 34 + 15) & ~15ull; + const uint64_t scale_bytes = ((uint64_t) n_hits * (FF / 32) * 4 + 15) & ~15ull; + float* gu = (float*) scratch; + uint8_t* hq = (uint8_t*) scratch + gu_bytes; + float* hs = (float*) (hq + q8_bytes); + float* hh = (float*) ((uint8_t*) hs + scale_bytes); + float* xh = (float*) ((uint8_t*) hh + scale_bytes); + activation_correction_kernel<<<(H / 32 + THREADS - 1) / THREADS, THREADS, 0, cs>>>( + x_q8_0, x_scales, xh, H / 32); + check("cpu_order/input_correction", stream); + const int rows_per_block = THREADS / 8; + cpu_order_projection_kernel<<<(unsigned) ((n_hits * 2 * FF + rows_per_block - 1) / rows_per_block), + THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, x_q8_0, x_scales, xh, gu, (int) n_hits); + check("cpu_order/gate_up", stream); + if (gate_up_trace != nullptr && + cudaMemcpyAsync(gate_up_trace, gu, (size_t) n_hits * 2 * FF * sizeof(float), + cudaMemcpyDeviceToDevice, cs) != cudaSuccess) { + std::fprintf(stderr, "cpu_order/gate_up_trace copy failed\n"); + std::exit(1); + } + cpu_order_swiglu_kernel<<<(unsigned) ((n_hits * FF + THREADS - 1) / THREADS), THREADS, 0, cs>>>( + gu, (int) n_hits * FF); + check("cpu_order/swiglu", stream); + cpu_order_quantize_kernel<<<(unsigned) ((n_hits * (FF / 32) + THREADS - 1) / THREADS), THREADS, 0, cs>>>( + gu, hq, hs, hh, (int) n_hits * (FF / 32)); + check("cpu_order/intermediate_quantize", stream); + cpu_order_projection_kernel<<<(unsigned) ((n_hits * H + rows_per_block - 1) / rows_per_block), + THREADS, 0, cs>>>( + blob_base, slot_index, dst_index, blob_bytes, hq, hs, hh, out, (int) n_hits); + check("cpu_order/down", stream); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s2_gemv.cu b/engine/strata/src/kernels/cuda/s2_gemv.cu new file mode 100644 index 00000000..c1ff5cf2 --- /dev/null +++ b/engine/strata/src/kernels/cuda/s2_gemv.cu @@ -0,0 +1,63 @@ +// src/kernels/cuda/s2_gemv.cu - P2.S2: the S2 GEMV, one thread per output row. +// +// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no +// vector loads, no __ldg hints. Phase 3 changes this file; the parity test is what says whether a change is +// still right. +#include "strata/kernels/s2_gemv.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK = 64; + +__global__ void s2_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, float* __restrict__ y, long long n_in, + long long n_out) { + const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + + const long long nb = n_in / QK; + const uint8_t* c = codes + o * nb * (QK / 4); + const float* s = scales + o * nb; + + float acc = 0.0f; + for (long long b = 0; b < nb; ++b) { + const float d = s[b]; + const uint8_t* cb = c + b * (QK / 4); + const uint16_t* xb = x + b * QK; + for (int j = 0; j < QK; ++j) { + // (code - 1) in the INTEGER domain, then the group scale, then the activation; the CPU reference + // below is written in the same order so the two differ only by floating-point contraction. + const int code = (cb[j >> 2] >> ((j & 3) * 2)) & 0x03; + acc += (float) (code - 1) * d * __half2float(__ushort_as_half(xb[j])); + } + } + y[o] = acc; +} + +} // namespace + +void s2_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out) { + if (n_in <= 0 || n_out <= 0) return; + if (n_in % QK != 0) { + std::fprintf(stderr, "s2_gemv: n_in %lld is not a multiple of %d\n", (long long) n_in, QK); + std::exit(1); + } + const int threads = 128; + const long long blocks = (n_out + threads - 1) / threads; + s2_gemv_kernel<<<(unsigned) blocks, threads>>>(x, codes, scales, y, n_in, n_out); + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s2_gemv: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s2_gemv_fast.cu b/engine/strata/src/kernels/cuda/s2_gemv_fast.cu new file mode 100644 index 00000000..c83bd17e --- /dev/null +++ b/engine/strata/src/kernels/cuda/s2_gemv_fast.cu @@ -0,0 +1,153 @@ +// src/kernels/cuda/s2_gemv_fast.cu - two levers on the hottest kernel, BOTH MEASURED NEGATIVE OR NEUTRAL. +// +// *** THIS FILE IS NAMED "fast" AND IS NOT FASTER. DO NOT ADOPT IT AS THE FAST PATH. *** +// It is kept because the negative result is worth more than the file costs: it closes two plausible +// optimisations and it is the experiment that established the measurement floor. +// +// L5 got the S2 GEMV from 10.5 to 86.2 G weights/s by amortising the loads, and left the instruction-count +// argument confirmed but unfinished. Two further reductions were obvious, so both were built and measured: +// +// LEVER 1 - STAGE `x` IN SHARED MEMORY. `x` is n_in halves (5 KB at n_embd 2560) and every output row reads +// all of it, so the generic kernel issues n_out * n_in activation loads per GEMV. Staging it once per block +// measured WORSE in every single paired comparison (59-76 G w/s staged against 64-87 G w/s unstaged, across +// four sweep passes and three thread counts). The __syncthreads and the copy cost more than the L1/L2 hits +// they replace - the same 5 KB is already resident and already broadcast. +// +// LEVER 2 - A CONSTANT-MEMORY CODE TABLE. Turn the per-element shifts, masks and int-to-float convert into +// one broadcast `float4` load per four elements. Measured NEUTRAL: the two orderings swap between passes +// with no consistent winner. +// +// WHY THE NEGATIVE RESULT IS THE REAL FINDING: run-to-run variance on this machine is now ~20% within a +// single configuration (quads tpr=32 measured 64.3 to 79.5 G w/s across four passes), because `verify` holds +// ~97% of six CPU cores. **The noise floor now EXCEEDS the effect sizes being chased**, so further +// micro-optimisation of this kernel cannot be evaluated here and should wait for a quiet machine rather than +// produce more numbers that cannot be distinguished from noise. +// +// Both changes alter the summation order or the expression, so this kernel is checked against the naive +// reference like every other one - being faster is never a reason to be trusted, and being neutral is not +// either. +#include "strata/kernels/s_gemv.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK_S2 = 64; +constexpr int MAX_SHARED_HALVES = 4096; // 8 KB of shared for x; n_embd 2560 fits with room + +// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6). +__constant__ float c_codes[256][4]; + +bool g_lut_ready[64] = {}; // per device: __constant__ memory is per device (a layer split runs on two) + +void ensure_lut() { + int dev = 0; + cudaGetDevice(&dev); + if (dev < 0 || dev >= 64) dev = 0; + if (g_lut_ready[dev]) return; + float host[256][4]; + for (int b = 0; b < 256; ++b) { + for (int k = 0; k < 4; ++k) { + host[b][k] = (float) (((b >> (2 * k)) & 3) - 1); + } + } + const cudaError_t e = cudaMemcpyToSymbol(c_codes, host, sizeof(host)); + if (e != cudaSuccess) { + std::fprintf(stderr, "s2_gemv_fast: cudaMemcpyToSymbol failed: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + g_lut_ready[dev] = true; +} + +// One block per output row. `staged` says whether x was copied to shared, so the SAME kernel covers both +// configurations and the bench can measure them against each other with nothing else changed. +template +__global__ void s2_gemv_fast_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, float* __restrict__ y, long long n_in, + long long n_out, int threads_per_row) { + extern __shared__ float smem[]; + __half* sx = reinterpret_cast<__half*>(smem); // [threads_per_row, ...] partials live after + float* partial = smem + (STAGE_X ? (MAX_SHARED_HALVES / 2) : 0); + + const long long o = blockIdx.x; + if (o >= n_out) return; + const int tid = threadIdx.x; + + if (STAGE_X) { + const __half* xh = reinterpret_cast(x); + for (long long i = tid; i < n_in; i += threads_per_row) sx[i] = xh[i]; + __syncthreads(); + } + + const long long n_quads = n_in / 4; + const uint8_t* c = codes + o * n_quads; + const float* s = scales + o * (n_in / QK_S2); + + float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; + for (long long q = tid; q < n_quads; q += threads_per_row) { + const uint8_t byte = c[q]; // ONE load for four codes + const float d = s[q >> 4]; // (q*4) >> 6 + const float4 cv = *reinterpret_cast(&c_codes[byte][0]); // one broadcast load + if (STAGE_X) { + const __half2 h01 = *reinterpret_cast(&sx[q * 4]); + const __half2 h23 = *reinterpret_cast(&sx[q * 4 + 2]); + a0 += cv.x * d * __low2float(h01); + a1 += cv.y * d * __high2float(h01); + a2 += cv.z * d * __low2float(h23); + a3 += cv.w * d * __high2float(h23); + } else { + const uint2 xw2 = *reinterpret_cast(x + q * 4); + const __half2 h01 = *reinterpret_cast(&xw2.x); + const __half2 h23 = *reinterpret_cast(&xw2.y); + a0 += cv.x * d * __low2float(h01); + a1 += cv.y * d * __high2float(h01); + a2 += cv.z * d * __low2float(h23); + a3 += cv.w * d * __high2float(h23); + } + } + partial[tid] = (a0 + a1) + (a2 + a3); + __syncthreads(); + for (int step = threads_per_row / 2; step > 0; step >>= 1) { + if (tid < step) partial[tid] += partial[tid + step]; + __syncthreads(); + } + if (tid == 0) y[o] = partial[0]; +} + +} // namespace + +void s2_gemv_fast(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row, bool stage_x) { + if (n_in <= 0 || n_out <= 0) return; + if (n_in % 4 != 0 || n_in % QK_S2 != 0) { + std::fprintf(stderr, "s2_gemv_fast: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2); + std::exit(1); + } + ensure_lut(); + if (stage_x && n_in > MAX_SHARED_HALVES) { + std::fprintf(stderr, "s2_gemv_fast: n_in %lld exceeds the %d-half shared staging limit\n", + (long long) n_in, MAX_SHARED_HALVES); + std::exit(1); + } + const size_t smem = (stage_x ? MAX_SHARED_HALVES * sizeof(__half) : 0) + + (size_t) threads_per_row * sizeof(float); + if (stage_x) { + s2_gemv_fast_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, + threads_per_row); + } else { + s2_gemv_fast_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, + threads_per_row); + } + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s2_gemv_fast: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s2_gemv_q8.cu b/engine/strata/src/kernels/cuda/s2_gemv_q8.cu new file mode 100644 index 00000000..386f8827 --- /dev/null +++ b/engine/strata/src/kernels/cuda/s2_gemv_q8.cu @@ -0,0 +1,96 @@ +// src/kernels/cuda/s2_gemv_q8.cu - the S2 GEMV that consumes Q8_0 ACTIVATIONS, as ggml does. +// +// THE GAP THIS CLOSES (round 186). `ggml_mul_mat` converts src1 - the ACTIVATION - to the weight's +// `vec_dot_type` before the dot product, and for Q2_0 that is Q8_0. The CUDA kernels built in rounds 166-177 +// take FP16 activations instead, while the CPU expert path (`bench/micro/cpu_s2.cpp`) already quantizes to int8 +// and uses `vpdpbusd`. Left that way the two paths compute different numbers for different experts of the SAME +// token, and the measured size of the difference is the activation contract itself: 0.9498% relative, against +// P2.S2's 1e-3 tolerance for FP16 paths. +// +// This is the CORRECTNESS version, not the fast one. It dequantizes each activation (`xq * dx`) inside the +// loop and does the same float arithmetic as `s2_gemv_quads`; the speed win available here is `__dp4a`, which +// turns four int8 MACs into one instruction, and that belongs to Phase 3 once the numerics are settled. The +// phase's rule is the simplest correct kernel first, and a dp4a version whose numerics are wrong would be +// indistinguishable from a fast one. +// +// Layout: activations are (n_in/32) ggml Q8_0 blocks, 34 bytes each - `fp16 d` then `int8 qs[32]` - produced by +// `strata::kernels::quantize_q8_0`. A quad of four elements lies inside one 32-element block, so the block +// scale is constant across it and is loaded once. +#include "strata/kernels/s2_gemv_q8.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int QK_S2 = 64; +constexpr int QK8_0 = 32; + +__global__ void s2_gemv_q8_kernel(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, float* __restrict__ y, long long n_in, + long long n_out, int threads_per_row) { + extern __shared__ float partial[]; + const long long o = blockIdx.x; + if (o >= n_out) return; + const int tid = threadIdx.x; + + const long long n_quads = n_in / 4; + const uint8_t* c = codes + o * n_quads; // one code byte per quad + const float* s = scales + o * (n_in / QK_S2); + + float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; + for (long long q = tid; q < n_quads; q += threads_per_row) { + const uint8_t byte = c[q]; + const float d = s[q >> 4]; // (q*4) >> 6, the S2 group index as a shift + // the activation quad: four int8 in one 32-element block, so one block scale + const long long ablk = (q * 4) / QK8_0; + const uint8_t* blk = act + ablk * 34; + const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); + const float dx = __half2float(__ushort_as_half(dbits)); + const int8_t* xq = reinterpret_cast(blk + 2); + const int off = (int) ((q * 4) % QK8_0); + + const float w0 = (float) ((int) (byte & 3) - 1) * d; + const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d; + const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d; + const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d; + a0 += w0 * ((float) xq[off + 0] * dx); + a1 += w1 * ((float) xq[off + 1] * dx); + a2 += w2 * ((float) xq[off + 2] * dx); + a3 += w3 * ((float) xq[off + 3] * dx); + } + partial[tid] = (a0 + a1) + (a2 + a3); + __syncthreads(); + for (int step = threads_per_row / 2; step > 0; step >>= 1) { + if (tid < step) partial[tid] += partial[tid + step]; + __syncthreads(); + } + if (tid == 0) y[o] = partial[0]; +} + +} // namespace + +void s2_gemv_q8(const uint8_t* act, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + if (n_in % QK8_0 != 0 || n_in % QK_S2 != 0) { + std::fprintf(stderr, "s2_gemv_q8: n_in %lld must be a multiple of %d\n", (long long) n_in, QK_S2); + std::exit(1); + } + const size_t smem = (size_t) threads_per_row * sizeof(float); + s2_gemv_q8_kernel<<<(unsigned) n_out, threads_per_row, smem, (cudaStream_t) stream>>>(act, codes, scales, y, + n_in, n_out, + threads_per_row); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s2_gemv_q8 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s2_gemv_quads.cu b/engine/strata/src/kernels/cuda/s2_gemv_quads.cu new file mode 100644 index 00000000..7cb7cb44 --- /dev/null +++ b/engine/strata/src/kernels/cuda/s2_gemv_quads.cu @@ -0,0 +1,93 @@ +// src/kernels/cuda/s2_gemv_quads.cu - S2 with the code load amortised over four elements. +// +// THE HYPOTHESIS THIS TESTS. L4 measured 66 G weights/s = 0.55 weights/cycle/SM, and at an estimated ~13 +// instructions per weight that is ~7.2 instructions/cycle/SM against an SM's 4/cycle issue ceiling. Compute +// (0.4% of FP32 peak) and bandwidth (2%) are excluded by measurement and the dependency chain was excluded by +// experiment in L4, so instruction ISSUE is what remains. If that is right, cutting instructions per weight +// must move the rate; if the rate does not move, the hypothesis is wrong and that is worth knowing too. +// +// WHERE THE INSTRUCTIONS GO. For S2 four consecutive elements share ONE byte (element i at byte i/4, bits +// (i%4)*2), and four halves of x are eight contiguous bytes. The generic kernel walks with a thread stride +// and loads one byte and one half PER ELEMENT; a thread that takes a contiguous quad instead loads one byte +// and one 64-bit word for all four. Memory instructions per element drop from 2 to 0.5, and the address +// arithmetic is computed once rather than four times. +// +// S2 IS SPECIALISED DELIBERATELY: it is 31.64 GiB of the 38 GiB pack, so it is the kernel that matters. The +// generic `s_gemv_split` still serves S4 and S8. +#include "strata/kernels/s_gemv.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +// QK = 64 elements per group; a quad of 4 elements is 1/16 of a group, so +// group = (quad * 4) >> 6 = quad >> 4 +constexpr int QK_S2 = 64; +constexpr int CODES_PER_BYTE_S2 = 4; + +__global__ void s2_gemv_quads_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, float* __restrict__ y, long long n_in, + long long n_out, int threads_per_row) { + extern __shared__ float partial[]; + const long long o = blockIdx.x; + if (o >= n_out) return; + const int tid = threadIdx.x; + + const long long n_quads = n_in / 4; + const uint8_t* c = codes + o * n_quads; // exactly one code byte per quad + const float* s = scales + o * (n_in / QK_S2); + + float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; + for (long long q = tid; q < n_quads; q += threads_per_row) { + const uint8_t byte = c[q]; // ONE load for four codes + const float d = s[q >> 4]; // (q*4) >> 6, the group index as a shift + // ONE 64-bit load for four halves. `x` is 256-byte aligned and four halves are eight bytes, so + // this is an aligned uint2 - if it were not, the misaligned access would fault rather than be slow. + const uint2 xw = *reinterpret_cast(x + q * 4); + const __half2 h01 = *reinterpret_cast(&xw.x); + const __half2 h23 = *reinterpret_cast(&xw.y); + // the four codes, each carrying the -1 bias in the INTEGER domain; the scale is applied once per + // element here rather than once per group, which is the same expression the generic kernel uses + const float w0 = (float) ((int) (byte & 3) - 1) * d; + const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d; + const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d; + const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d; + a0 += w0 * __low2float(h01); + a1 += w1 * __high2float(h01); + a2 += w2 * __low2float(h23); + a3 += w3 * __high2float(h23); + } + partial[tid] = (a0 + a1) + (a2 + a3); + __syncthreads(); + for (int step = threads_per_row / 2; step > 0; step >>= 1) { + if (tid < step) partial[tid] += partial[tid + step]; + __syncthreads(); + } + if (tid == 0) y[o] = partial[0]; +} + +} // namespace + +void s2_gemv_quads(const uint16_t* x, const uint8_t* codes, const float* scales, float* y, int64_t n_in, + int64_t n_out, int threads_per_row) { + if (n_in <= 0 || n_out <= 0) return; + if (n_in % 4 != 0) { + std::fprintf(stderr, "s2_gemv_quads: n_in %lld is not a multiple of 4\n", (long long) n_in); + std::exit(1); + } + const size_t smem = (size_t) threads_per_row * sizeof(float); + s2_gemv_quads_kernel<<<(unsigned) n_out, threads_per_row, smem>>>(x, codes, scales, y, n_in, n_out, + threads_per_row); + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s2_gemv_quads: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/s_gemv.cu b/engine/strata/src/kernels/cuda/s_gemv.cu new file mode 100644 index 00000000..d0db1783 --- /dev/null +++ b/engine/strata/src/kernels/cuda/s_gemv.cu @@ -0,0 +1,694 @@ +// src/kernels/cuda/s_gemv.cu - P2.S2: the S-family GEMV, one thread per output row. +// +// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no +// vector loads. The kernel is templated on the code WIDTH (a compile-time property of the unpacking loop) and +// takes the rest of the per-type attributes as run-time arguments, because the manifest supplies them per +// tensor and a 13-way switch inside the inner loop would be the naive-but-wrong kind of naive. +#include "strata/kernels/s_gemv.hpp" + +#include +#include + +#include +#include + +namespace strata::kernels { +namespace { + +// `kvalues_iq4nl`: the non-linear codebook, verbatim from ggml-common.h / ggml-quants.c. +// +// **IT WAS IN `__constant__` FOR THE WRONG REASON, AND IT COST 2.12x.** The old comment justified constant +// memory with "every thread reads it and it is the same 16 values for the whole launch". That reasoning is +// exactly backwards: constant memory is fast when the access is UNIFORM - every lane reading the SAME address - +// and a NON-LINEAR codebook means every lane reads a DIFFERENT index, which is the pattern it handles worst. +// +// Measured on `attn_qkv` (IQ4_XS, 10240 x 2560), forcing the Affine codebook so that the memory traffic and the +// instruction count stay identical and only the table read is removed: +// +// codebook probe: IQ4NL 0.2032 ms Affine 0.0960 ms ratio 2.12x +// +// `decode_tbl` below reads a SHARED copy instead: 16 bytes loaded once per block, then an index into shared +// memory that costs at most a four-way bank conflict. The `__constant__` array stays as the source of it. +__constant__ signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, + 1, 13, 25, 38, 53, 69, 89, 113}; + +template +__device__ __forceinline__ float decode(int code, int bias, int codebook) { + if (codebook == (int) Codebook::Iq4Nl) return (float) kIq4Nl[code & 0x0F]; + return (float) (code + bias); // the bias is applied to the CODE, in the integer domain +} + +/// The same decode with the codebook in SHARED memory, which is what the hot kernels use - see the measurement +/// above. A divergent read of a 16-entry table is the one access pattern constant memory is worst at. +template +__device__ __forceinline__ float decode_tbl(int code, int bias, int codebook, const signed char* tbl) { + if (codebook == (int) Codebook::Iq4Nl) return (float) tbl[code & 0x0F]; + return (float) (code + bias); +} + +// ---- Q8_K ACTIVATIONS ---------------------------------------------------------------------------------- +// +// 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`. `bsums` is not read - it +// exists for ggml's AVX2 dot product - but the STRIDE includes it, so a buffer from `quantize_q8_K` passes +// straight in. +// +// The block's `d` sits at a 4-byte-aligned offset from the buffer base as long as the base is aligned, which +// `cudaMalloc` guarantees. +constexpr int Q8K_BLOCK_BYTES = 292; +constexpr int Q8K_BLOCK_ELEMS = 256; + +__device__ __forceinline__ float q8k_at(const uint8_t* __restrict__ x, long long i) { + const uint8_t* blk = x + (i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES; + const float d = __ldg((const float*) blk); + const int8_t q = ((const int8_t*) (blk + 4))[i % Q8K_BLOCK_ELEMS]; + return d * (float) q; +} + +/// **THE Q8_0 ACTIVATION**, which is what the LEGACY block formats want: `block_q8_0` is `{fp16 d; int8 qs[32]}`, +/// 34 bytes per 32 elements, produced by `quantize_q8_0`. +/// +/// THE ENGINE HAD NO GEMV FOR THIS, and it was the last activation-contract gap (LEDGER L54). It was described +/// as "Q8_K is not implemented", which is not the situation: `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0 in EVERY +/// layer, whose `vec_dot_type` is Q8_0 - and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is +/// STRUCTURALLY IMPOSSIBLE for it rather than merely absent**. Every other legacy tensor in the pack is Q2_0, +/// whose attributes happen to be S2's, which is how the S2-only kernel covered them and the hole stayed hidden. +constexpr int Q8_0_BLOCK_BYTES = 34; +constexpr int Q8_0_BLOCK_ELEMS = 32; + +__device__ __forceinline__ float q8_0_at(const uint8_t* __restrict__ x, long long i) { + const uint8_t* blk = x + (i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES; + // a `uint16_t` needs 2-byte alignment and the stride is 34, so every block's `d` is aligned + const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk)); + const int8_t q = ((const int8_t*) (blk + 2))[i % Q8_0_BLOCK_ELEMS]; + return d * (float) q; +} + +/// The Q8_K path, with the SAME weight decode as `s_gemv_kernel` and a different activation loader. The two +/// are separate kernels rather than one templated on the activation kind because the activation POINTER TYPE +/// differs (`uint16_t*` vs `uint8_t*`) and a templated pointer would need a cast at every call site - which is +/// where a wrong stride would hide. +template +__global__ void s_gemv_q8k_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, const float* __restrict__ offset, + float* __restrict__ y, long long n_in, long long n_out, int bias, + int codebook, int group_elems, int has_offset) { + // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. + // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread + // that returned first would leave the others waiting at a barrier it never reaches. + __shared__ signed char s_iq4nl[16]; + if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; + __syncthreads(); + const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + + constexpr int PER_BYTE = 8 / CODE_BITS; + const long long n_groups = n_in / group_elems; + const long long codes_per_row = n_in / PER_BYTE; + const uint8_t* c = codes + o * codes_per_row; + const float* s = scales + o * n_groups; + const float* off = has_offset ? offset + o * n_groups : nullptr; + + float acc = 0.0f; + for (long long g = 0; g < n_groups; ++g) { + const float d = s[g]; + const float b = off ? off[g] : 0.0f; + const long long base = g * (long long) group_elems; + for (int j = 0; j < group_elems; ++j) { + const long long i = base + j; + const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1); + // The offset belongs to the WEIGHT and is applied before the activation multiply - see the note in + // `s_gemv_kernel`, where writing it the other way rounded differently and only the Q4_K case could + // tell. + const float w = decode_tbl(code, bias, codebook, s_iq4nl) * d + b; + acc += w * q8k_at(x, i); + } + } + y[o] = acc; +} + +/// One warp per output row, lanes striding the reduction axis: for a fixed `i` consecutive lanes read +/// consecutive activations, which is the coalescing that matters once the output width is small. +/// +/// **`group_shift`, NOT `group_elems`, AND IT COSTS A DIVISION PER ELEMENT IF YOU GET IT WRONG.** The +/// sibling fp16 kernel was given this treatment ("a 64-bit integer division on this hardware is a long +/// instruction sequence - one per element, in the hottest loop in the engine") and THIS one was not: it kept +/// `i / group_elems` with `group_elems` a RUNTIME value, once per element, in the kernel that carries most of +/// the model's weight bytes. Every group size the format defines is a power of two, so the divisor is passed +/// as its logarithm and the division becomes a shift; the host refuses a non-power-of-two group rather than +/// computing a wrong index. +/// ONE KERNEL FOR BOTH QUANTIZED ACTIVATIONS, templated on which block format `x` holds. A second copy with a +/// different loader would be a second thing to get wrong, and the only difference IS the loader - the weight +/// decode, the quad loop, the shared codebook and the reduction are identical. +template +__global__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, const float* __restrict__ offset, + float* __restrict__ y, long long n_in, long long n_out, int bias, + int codebook, int group_shift, int has_offset) { + constexpr int PER_BYTE = 8 / CODE_BITS; + const int warps_per_block = (int) (blockDim.x >> 5); + const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5); + const int lane = threadIdx.x & 31; + + // THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a + // divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`). + // + // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to + // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the + // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to + // avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's + // full mask stays valid. + __shared__ signed char s_iq4nl[16]; + if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; + __syncthreads(); + if (o >= n_out) return; + + const long long n_groups = n_in >> group_shift; + const long long codes_per_row = n_in / PER_BYTE; + const uint8_t* c = codes + o * codes_per_row; + const float* s = scales + o * n_groups; + const float* off = has_offset ? offset + o * n_groups : nullptr; + + float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f; + float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f; + float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f; + float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f; + // ---- EIGHT CONSECUTIVE ELEMENTS PER LANE, from TWO code loads and ONE scale. + // + // **THIS IS THE EXPERIMENT THE `#pragma unroll` NOTE BELOW LEFT OPEN**, and the note said what it would + // be: "Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four independent 16-bit words per + // lane - which an unroll cannot do because the extraction code is written for exactly four codes." So a + // lane now takes a double quad: two code words issued before either is consumed, which is what raises the + // bytes in flight. The scale and offset are still ONE load, because eight consecutive elements lie in one + // group whenever `group_elems % 8 == 0` - the launcher asserts that, and every group size this format + // defines (16, 32, 64) satisfies it. + // + // The loop used to take `i = lane, lane+32, ...` - a STRIDE, chosen so consecutive lanes read consecutive + // activations - and paid a code load, a shift-and-mask, and a scale load FOR EVERY ELEMENT. But four + // consecutive elements share one code word (1, 2 or 4 bytes depending on width) and lie in one group, + // because every group size this format defines is a multiple of four. So a lane takes a QUAD: + // + // one code load instead of four + // one scale load instead of four + // one shift per element instead of a divide, a modulo and a shift + // + // THE BIT ORDER IS THE SAME ONE, verified for all three widths: element `i+k` is bits + // `[k*CODE_BITS, (k+1)*CODE_BITS)` of the little-endian word at byte `i/PER_BYTE`, which is what the old + // `(c[e/PER_BYTE] >> ((e%PER_BYTE)*CODE_BITS)) & MASK` computed one element at a time. + // + // THE SUMMATION ORDER CHANGES, which is why `s_gemv_parity` and `s_gemv_q8k_parity` carry tolerances and + // compare against the naive kernel - they are the guard for this, and they are the reason it is safe to do. + constexpr int QE = 16; + // BYTES PER FOUR-CODE WORD, not per octet. The two are easy to confuse and the first version of this + // did: it branched on the octet's total width and so read a uint32 for S4 (whose four codes are a + // uint16) and single bytes for S8 (whose four codes are a uint32). `s_gemv_q8k_parity` failed on + // exactly that, which is what it is for. + constexpr int QW = 4 * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8 + constexpr unsigned MASK = (1u << CODE_BITS) - 1u; + long long i = (long long) lane * QE; + // **`#pragma unroll 4` WAS TRIED HERE AND DID NOTHING.** Measured: 184.6 -> 183.9 GB/s at n_out 10240, + // with `s_gemv_parity` and `s_gemv_q8k_parity` both still clean. The hypothesis it was testing is L93 - + // that this kernel's flat ~6 ns per output row is a bytes-in-flight limit, one code load and one scale + // load per lane-iteration with only 20 iterations. A 4x unroll issues four of each before the first is + // consumed, so either the compiler was already doing it or **the limit is not instruction scheduling.** + // Removed rather than kept, because a hint that does not change the timing is a claim that is not true. + // + // What it does NOT rule out is the structural version of the same idea: QE is 4, so a lane consumes ONE + // 2-byte code word per iteration. Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four + // independent 16-bit words per lane - which an unroll cannot do because the extraction code is written for + // exactly four codes. That is the experiment that would settle it, and it is not this one. + for (; i + QE <= n_in; i += 32 * QE) { + const long long g = i >> group_shift; // the whole octet is in one group: group_elems % 8 == 0 + const float d = s[g]; + const float b = off ? off[g] : 0.0f; + const uint8_t* cp = c + i / PER_BYTE; + unsigned v, v2, v3, v4; + if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; } + else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2); + v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); } + else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4); + v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); } + // ---- THE ACTIVATION BLOCK IS HOISTED OUT OF THE SIXTEEN ELEMENTS, AND THAT WAS THE KERNEL'S COST. + // + // `q8k_at(x, i + k)` computes `(i + k) / 256` and `(i + k) % 256` on EVERY call: a 64-bit integer + // division AND modulo per element, sixteen times per lane-iteration. A 64-bit division on a GPU is a + // software routine of roughly a hundred cycles, and the compiler cannot strength-reduce it because it + // cannot prove `(i + k) / 256 == i / 256` without knowing `i % 256`. + // + // But `QE` is 16, `Q8K_BLOCK_ELEMS` is 256 and `Q8_0_BLOCK_ELEMS` is 32, and the loop advances `i` by + // `32 * QE`. So `i % 256` and `i % 32` are ALWAYS multiples of 16 - which means all QE elements of one + // lane-iteration lie inside ONE block, for either activation kind. One division and one modulo per + // iteration replace sixteen of each, and the sixteen activations become sixteen consecutive int8 loads + // from a pointer computed once. + // + // This is exact, not an approximation: `xi + QE <= blk_elems` holds for every reachable `xi`, so no + // lane-iteration can straddle a block boundary. The tail loop below still uses the accessors because + // its elements do not share a block, and it runs at most once per lane. + const int blk_elems = Q8K ? Q8K_BLOCK_ELEMS : Q8_0_BLOCK_ELEMS; + const uint8_t* xb = x + (i / blk_elems) * (Q8K ? Q8K_BLOCK_BYTES : Q8_0_BLOCK_BYTES); + const int xi = (int) (i % blk_elems); + const float xd = Q8K ? __ldg((const float*) xb) + : __half2float(__ushort_as_half(*(const uint16_t*) xb)); + const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi; + + const float w0 = decode_tbl((int) (v & MASK), bias, codebook, s_iq4nl) * d + b; + const float w1 = decode_tbl((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w2 = decode_tbl((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w3 = decode_tbl((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w4 = decode_tbl((int) (v2 & MASK), bias, codebook, s_iq4nl) * d + b; + const float w5 = decode_tbl((int) ((v2 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w6 = decode_tbl((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w7 = decode_tbl((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + acc0 += w0 * (xd * (float) xq[0]); + acc1 += w1 * (xd * (float) xq[1]); + acc2 += w2 * (xd * (float) xq[2]); + acc3 += w3 * (xd * (float) xq[3]); + acc4 += w4 * (xd * (float) xq[4]); + acc5 += w5 * (xd * (float) xq[5]); + acc6 += w6 * (xd * (float) xq[6]); + acc7 += w7 * (xd * (float) xq[7]); + const float w8 = decode_tbl((int) (v3 & MASK), bias, codebook, s_iq4nl) * d + b; + const float w9 = decode_tbl((int) ((v3 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w10 = decode_tbl((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w11 = decode_tbl((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w12 = decode_tbl((int) (v4 & MASK), bias, codebook, s_iq4nl) * d + b; + const float w13 = decode_tbl((int) ((v4 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w14 = decode_tbl((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + const float w15 = decode_tbl((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b; + acc8 += w8 * (xd * (float) xq[8]); + acc9 += w9 * (xd * (float) xq[9]); + acc10 += w10 * (xd * (float) xq[10]); + acc11 += w11 * (xd * (float) xq[11]); + acc12 += w12 * (xd * (float) xq[12]); + acc13 += w13 * (xd * (float) xq[13]); + acc14 += w14 * (xd * (float) xq[14]); + acc15 += w15 * (xd * (float) xq[15]); + } + // the last, partial quad - at most one per lane + for (; i < n_in; i += 32 * QE) { + for (int k = 0; k < QE && i + k < n_in; ++k) { + const long long e = i + k; + const long long g = e >> group_shift; + const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK; + acc0 += (decode_tbl(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * (Q8K ? q8k_at(x, e) : q8_0_at(x, e)); + } + } + float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) + + (((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15))); + for (int step = 16; step > 0; step >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, step); + if (lane == 0) y[o] = acc; +} + +template +__global__ void s_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, const float* __restrict__ offset, + float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, + int group_elems, int has_offset) { + // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. + // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread + // that returned first would leave the others waiting at a barrier it never reaches. + __shared__ signed char s_iq4nl[16]; + if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; + __syncthreads(); + const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x; + if (o >= n_out) return; + + constexpr int PER_BYTE = 8 / CODE_BITS; + const long long n_groups = n_in / group_elems; + const long long codes_per_row = n_in / PER_BYTE; + const uint8_t* c = codes + o * codes_per_row; + const float* s = scales + o * n_groups; + const float* off = has_offset ? offset + o * n_groups : nullptr; + + float acc = 0.0f; + for (long long g = 0; g < n_groups; ++g) { + const float d = s[g]; + const float b = off ? off[g] : 0.0f; + const long long base = g * (long long) group_elems; + for (int j = 0; j < group_elems; ++j) { + const long long i = base + j; + const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1); + // The offset belongs to the WEIGHT, so it is applied to the decoded value BEFORE the activation + // multiply: `w = code*scale + offset; acc += w * x`. Writing `acc += code*scale*x + offset*x` + // computes a mathematically equal expression that ROUNDS DIFFERENTLY, because it performs two + // multiplications and an addition where this performs one of each. The no-offset types cannot + // tell the difference - which is why this was wrong until the Q4_K case was added. + const float w = decode_tbl(code, bias, codebook, s_iq4nl) * d + b; + acc += w * __half2float(__ushort_as_half(x[i])); + } + } + y[o] = acc; +} + +} // namespace + +void s_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, float* y, + int64_t n_in, int64_t n_out, const SForm& form) { + if (n_in <= 0 || n_out <= 0) return; + if (form.group_elems <= 0 || n_in % form.group_elems != 0) { + std::fprintf(stderr, "s_gemv: n_in %lld is not a multiple of group_elems %d\n", (long long) n_in, + form.group_elems); + std::exit(1); + } + if (form.has_offset && offset == nullptr) { + std::fprintf(stderr, "s_gemv: form says has_offset but offset is null\n"); + std::exit(1); + } + const int threads = 128; + const long long blocks = (n_out + threads - 1) / threads; + const int cb = (int) form.codebook; + switch (form.code_bits) { + case 2: + s_gemv_kernel<2><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, + form.code_bias, cb, form.group_elems, + form.has_offset ? 1 : 0); + break; + case 4: + s_gemv_kernel<4><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, + form.code_bias, cb, form.group_elems, + form.has_offset ? 1 : 0); + break; + case 8: + s_gemv_kernel<8><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out, + form.code_bias, cb, form.group_elems, + form.has_offset ? 1 : 0); + break; + default: + std::fprintf(stderr, "s_gemv: unsupported code_bits %d\n", form.code_bits); + std::exit(1); + } + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s_gemv: %s\n", cudaGetErrorString(e)); + std::exit(1); + } +} + +namespace { + +// One BLOCK per output row, `threads_per_row` threads splitting it. Parallelism becomes +// n_out * threads_per_row instead of n_out, which is the whole point: gate/up is [2560 x 640] and 640 threads +// cannot fill 48 SMs. +// +// The reduction is a fixed tree over shared memory rather than atomics, so the result is DETERMINISTIC for a +// given threads_per_row - a race would make the parity test flaky rather than wrong, which is the worst kind +// of failing test. +// NOTE ON `g = e >> group_shift`. The group index was `e / group_elems` with `group_elems` a RUNTIME value, +// and a 64-bit integer division on this hardware is a long instruction sequence - one per element, in the +// hottest loop in the engine. Every group size this format defines is a POWER OF TWO (16, 32, 64), so the +// divisor is passed as its logarithm and the division becomes a shift. The host wrapper refuses a +// non-power-of-two group rather than silently computing a wrong index. +template +__global__ void s_gemv_split_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, + const float* __restrict__ scales, const float* __restrict__ offset, + float* __restrict__ y, long long n_in, long long n_out, int bias, + int codebook, int group_elems, int group_shift, int has_offset, + int threads_per_row) { + extern __shared__ float partial[]; + // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`. + // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread + // that returned first would leave the others waiting at a barrier it never reaches. + __shared__ signed char s_iq4nl[16]; + if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x]; + __syncthreads(); + const long long o = blockIdx.x; + if (o >= n_out) return; + const int tid = threadIdx.x; + + constexpr int PER_BYTE = 8 / CODE_BITS; + const long long n_groups = n_in / group_elems; + const uint8_t* c = codes + o * (n_in / PER_BYTE); + const float* s = scales + o * n_groups; + const float* off = has_offset ? offset + o * n_groups : nullptr; + + // FOUR ACCUMULATORS, NOT ONE. L2 measured this kernel at 0.4% of FP32 peak and 2.1% of bandwidth, so + // neither limit is the constraint - the constraint is the DEPENDENCY CHAIN: a single `acc += ...` serialises + // every FMA behind the previous one's latency (4-6 cycles each, ~1 per 4 cycles achieved), so the SM sits + // idle. Four independent accumulators let the scheduler keep four FMAs in flight, and the loop is + // unrolled by four so the four chains are interleaved. The summation ORDER changes, which is why the + // parity test carries a tolerance and why this kernel's output is checked against the naive one. + // FOUR CONSECUTIVE ELEMENTS PER THREAD, from ONE code load and ONE scale - the same transformation the + // Q8_K kernel got, for the same reason and with the same guard (`s_gemv_parity`). See the long note there + // for the bit order, which is unchanged, and for why the group size is passed as a shift. + // + // THIS KERNEL IS THE ONE `attn_output` AND `shared_expert` USE, so the fix has to exist in both or half the + // model keeps the old instruction count. + constexpr int QE = 4; + constexpr int QB = QE * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8 + constexpr unsigned MASK = (1u << CODE_BITS) - 1u; + float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f; + long long i = (long long) tid * QE; + for (; i + QE <= n_in; i += (long long) threads_per_row * QE) { + const long long g = i >> group_shift; + const float d = s[g]; + const float b = off ? off[g] : 0.0f; + const uint8_t* cp = c + i / PER_BYTE; + unsigned v; + if (QB == 1) v = cp[0]; + else if (QB == 2) v = *(const uint16_t*) cp; + else v = *(const uint32_t*) cp; + // four halves in ONE 8-byte load; `i` is a multiple of four, so `x + i` is 8-byte aligned + const float2 f01 = __half22float2(*reinterpret_cast(x + i)); + const float2 f23 = __half22float2(*reinterpret_cast(x + i + 2)); + acc0 += (decode_tbl((int) (v & MASK), bias, codebook, s_iq4nl) * d + b) * f01.x; + acc1 += (decode_tbl((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b) * f01.y; + acc2 += (decode_tbl((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.x; + acc3 += (decode_tbl((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.y; + } + // the last, partial quad - at most one per thread + for (; i < n_in; i += (long long) threads_per_row * QE) { + for (int k = 0; k < QE && i + k < n_in; ++k) { + const long long e = i + k; + const long long g = e >> group_shift; + const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK; + acc0 += (decode_tbl(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * + __half2float(__ushort_as_half(x[e])); + } + } + partial[tid] = (acc0 + acc1) + (acc2 + acc3); + __syncthreads(); + for (int step = threads_per_row / 2; step > 0; step >>= 1) { + if (tid < step) partial[tid] += partial[tid + step]; + __syncthreads(); + } + if (tid == 0) y[o] = partial[0]; +} + +} // namespace + +static void s_gemv_split_impl(const uint16_t* x, const uint8_t* codes, const float* scales, + const float* offset, float* y, int64_t n_in, int64_t n_out, const SForm& form, + int threads_per_row, cudaStream_t stream, bool sync) { + if (n_in <= 0 || n_out <= 0) return; + if (threads_per_row < 1 || (threads_per_row & (threads_per_row - 1)) != 0 || threads_per_row > 1024) { + std::fprintf(stderr, "s_gemv_split: threads_per_row must be a power of two in 1..1024, got %d\n", + threads_per_row); + std::exit(1); + } + const int cb = (int) form.codebook; + // Every group size this format defines is a power of two, which is what lets the per-element group index + // be a shift. Refuse anything else rather than compute a wrong index quietly. + if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) { + std::fprintf(stderr, "s_gemv_split: group_elems must be a power of two, got %d\n", form.group_elems); + std::exit(1); + } + // AND THE QUAD MUST FIT INSIDE ONE GROUP: four consecutive elements share a scale and the kernel reads + // exactly one. Every group size this format defines is 16, 32 or 64, so this cannot fire on a real pack. + if (form.group_elems % 4 != 0) { + std::fprintf(stderr, "s_gemv_split: group_elems %d is not a multiple of 4\n", form.group_elems); + std::exit(1); + } + int group_shift = 0; + while ((1 << group_shift) < form.group_elems) ++group_shift; + const size_t smem = (size_t) threads_per_row * sizeof(float); + const unsigned grid = (unsigned) n_out; + switch (form.code_bits) { + case 2: + s_gemv_split_kernel<2><<>>( + x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, + group_shift, form.has_offset ? 1 : 0, threads_per_row); + break; + case 4: + s_gemv_split_kernel<4><<>>( + x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, + group_shift, form.has_offset ? 1 : 0, threads_per_row); + break; + case 8: + s_gemv_split_kernel<8><<>>( + x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, + group_shift, form.has_offset ? 1 : 0, threads_per_row); + break; + default: + std::fprintf(stderr, "s_gemv_split: unsupported code_bits %d\n", form.code_bits); + std::exit(1); + } + if (sync) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "s_gemv_split: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row) { + s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) 0, true); +} + +void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row, + void* stream) { + s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) stream, + false); +} + +// ---- the Q8_K entry points ----------------------------------------------------------------------------- + +namespace { + +bool q8k_form_ok(const SForm& form, int64_t n_in, const char* who) { + if (form.group_elems <= 0 || n_in % form.group_elems != 0) { + std::fprintf(stderr, "%s: n_in %lld is not a multiple of group_elems %d\n", who, (long long) n_in, + form.group_elems); + return false; + } + if (n_in % Q8K_BLOCK_ELEMS != 0) { + // `quantize_q8_K` requires this too, and a partial block would read past the end of the activation. + std::fprintf(stderr, "%s: n_in %lld is not a multiple of the Q8_K block %d\n", who, (long long) n_in, + Q8K_BLOCK_ELEMS); + return false; + } + return true; +} + +void finish(const char* who, void* stream) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e)); + std::exit(1); + } + if (stream != nullptr) return; + const cudaError_t s = cudaDeviceSynchronize(); + if (s != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", who, cudaGetErrorString(s)); + std::exit(1); + } +} + +} // namespace + +void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, float* y, + int64_t n_in, int64_t n_out, const SForm& form, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + if (!q8k_form_ok(form, n_in, "s_gemv_q8k")) std::exit(1); + const int threads = 128; + const unsigned blocks = (unsigned) ((n_out + threads - 1) / threads); + const int cb = (int) form.codebook; + const int ho = form.has_offset ? 1 : 0; + switch (form.code_bits) { + case 4: + s_gemv_q8k_kernel<4><<>>( + x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho); + break; + case 8: + s_gemv_q8k_kernel<8><<>>( + x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho); + break; + default: + // 2-bit S2 never has a Q8_K activation: its `vec_dot_type` is Q8_0. Refusing is better than + // running a kernel that would be numerically wrong in a way the caller cannot see. + std::fprintf(stderr, "s_gemv_q8k: code_bits %d has no Q8_K contract " + "(S2 uses Q8_0; see docs/activation-contract.md)\n", form.code_bits); + std::exit(1); + } + finish("s_gemv_q8k", stream); +} + +void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + if (!q8k_form_ok(form, n_in, "s_gemv_q8k_split")) std::exit(1); + // THE GROUP SIZE IS PASSED AS ITS LOGARITHM: see the note on the kernel. A non-power-of-two group would + // make the shift a WRONG INDEX rather than a slow one, so it is refused here. + int group_shift = 0; + while ((1 << group_shift) < form.group_elems) ++group_shift; + if ((1 << group_shift) != form.group_elems) { + std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a power of two\n", form.group_elems); + std::exit(1); + } + // AND THE QUAD MUST FIT INSIDE ONE GROUP. Four consecutive elements share a scale, so a group smaller + // than four would need two of them and the kernel reads exactly one. Every group size this format + // defines is 16, 32 or 64, so this cannot fire on a real pack - it is here because a future one could. + if (form.group_elems % 16 != 0) { + std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a multiple of 16\n", form.group_elems); + std::exit(1); + } + const int threads = 256; + const int warps = threads / 32; + const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps); + const int cb = (int) form.codebook; + const int ho = form.has_offset ? 1 : 0; + switch (form.code_bits) { + case 4: + s_gemv_q8_split_kernel<4, true><<>>( + x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); + break; + case 8: + s_gemv_q8_split_kernel<8, true><<>>( + x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); + break; + default: + std::fprintf(stderr, "s_gemv_q8k_split: code_bits %d has no Q8_K contract\n", form.code_bits); + std::exit(1); + } + finish("s_gemv_q8k_split", stream); +} + +void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset, + float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) { + if (n_in <= 0 || n_out <= 0) return; + // THE ACTIVATION IS `block_q8_0`, 32 elements per block, so `n_in` must be a multiple of 32 - which is a + // WEAKER requirement than Q8_K's 256 and is exactly why this kernel has to exist: `ffn_down_shexp` has + // n_in = 640, a multiple of 32 that is NOT a multiple of 256. + if (n_in % Q8_0_BLOCK_ELEMS != 0) { + std::fprintf(stderr, "s_gemv_q8_0_split: n_in %lld is not a multiple of %d\n", (long long) n_in, + Q8_0_BLOCK_ELEMS); + std::exit(1); + } + // the same two checks `s_gemv_q8k_split` makes, for the same reasons - see the notes there + if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) { + std::fprintf(stderr, "s_gemv_q8_0_split: group_elems must be a power of two, got %d\n", + form.group_elems); + std::exit(1); + } + // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel), + // so a group of 4 or 8 would read the wrong scale for most of them. The Q8_K launcher already said 16. + if (form.group_elems % 16 != 0) { + std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems); + std::exit(1); + } + int group_shift = 0; + while ((1 << group_shift) < form.group_elems) ++group_shift; + + const int threads = 256; + const int warps = threads / 32; + const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps); + const int cb = (int) form.codebook; + const int ho = form.has_offset ? 1 : 0; + switch (form.code_bits) { + case 4: + s_gemv_q8_split_kernel<4, false><<>>( + x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); + break; + case 8: + s_gemv_q8_split_kernel<8, false><<>>( + x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho); + break; + default: + std::fprintf(stderr, "s_gemv_q8_0_split: code_bits %d has no Q8_0 contract\n", form.code_bits); + std::exit(1); + } + finish("s_gemv_q8_0_split", stream); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/sampler.cu b/engine/strata/src/kernels/cuda/sampler.cu new file mode 100644 index 00000000..ff441243 --- /dev/null +++ b/engine/strata/src/kernels/cuda/sampler.cu @@ -0,0 +1,933 @@ +// src/kernels/cuda/sampler.cu - P2.S2: the sampler chain, in llama.cpp's order. +// +// penalties -> top_k -> top_p -> min_p -> temperature -> pick +// +// THE ORDER IS THE WHOLE CONTENT OF THIS FILE. llama.cpp builds its chain by walking `params.samplers`, whose +// default is { PENALTIES, DRY, TOP_N_SIGMA, TOP_K, TYPICAL_P, TOP_P, MIN_P, XTC, TEMPERATURE } (`common/common.h` +// at 3cf03257) - ONE penalties stage, first, and TEMPERATURE AFTER THE TRUNCATION FILTERS. (Issue #53: this file +// used to apply the penalties a second time after the temperature, and min_p before top_p - both taken from the +// order of the `case` labels in `common/sampling.cpp`, which is not the order the chain runs.) Every order +// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test +// does that against an independently computed distribution. +// +// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has +// three implementations that pick the same token, bit for bit: +// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole +// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail; +// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one +// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick; +// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference. +// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp). +#include "strata/kernels/sampler.hpp" +#include "strata/core/coupled_draft.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +// Philox 4x32-10, the counter-based generator the phase asks for. Counter-based matters because it makes the +// stream a function of (seed, position) rather than of how many draws came before - so a batch can be sampled +// in any order and a run is reproducible. +__device__ __forceinline__ uint32_t philox4x32_round(uint32_t& c0, uint32_t& c1, uint32_t& c2, uint32_t& c3, + uint32_t k0, uint32_t k1) { + const uint32_t hi0 = __umulhi(0x9E3779B9u, c0); + const uint32_t hi1 = __umulhi(0xBB67AE85u, c2); + const uint32_t lo0 = 0x9E3779B9u * c0; + const uint32_t lo1 = 0xBB67AE85u * c2; + const uint32_t n0 = hi1 ^ c1 ^ k0; + const uint32_t n1 = lo1; + const uint32_t n2 = hi0 ^ c3 ^ k1; + const uint32_t n3 = lo0; + c0 = n0; c1 = n1; c2 = n2; c3 = n3; + return 0; +} + +__device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter) { + uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32); + uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32); + for (int i = 0; i < 10; ++i) { + philox4x32_round(c0, c1, c2, c3, (uint32_t) i, 0u); + } + // 24 bits of mantissa, so the value is uniform in [0,1) with no rounding to 1.0 + return (float) (c0 >> 8) * (1.0f / 16777216.0f); +} + +// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`. +// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing +// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the +// vocabulary. The presence penalty is `float(count > 0)`, a boolean, not the count. +__device__ __forceinline__ int history_count(const int* __restrict__ h, int n, int v) { + int c = 0; + for (int i = 0; i < n; ++i) if (h[i] == v) ++c; + return c; +} + +__device__ __forceinline__ float apply_penalties(float logit, int count, const SamplerParams& p) { + if (count <= 0) return logit; + if (logit <= 0.0f) logit *= p.penalty_repeat; + else logit /= p.penalty_repeat; + logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; + return logit; +} + +/// **THE GREEDY ARGMAX, ONE BLOCK PER TOKEN, COVERING THE VOCABULARY.** +/// +/// **WHY THIS IS A SEPARATE KERNEL AND NOT A BRANCH.** `sampler_kernel` is launched as a grid over TOKENS +/// with 64 threads and a `if (t >= n_tokens) return;` at the top. The decode path has `n_tokens == 1`, so +/// that launch was `<<<1, 64>>>`, 63 threads exited on the first line, and ONE THREAD walked all 248,320 +/// logits in a dependent loop on one SM of 48. Measured in isolation (`bench/micro/sampler_cost.cu`): +/// **3.11 ms per token**, 5.7% of an ~54 ms token, and the whole of round 309's `sample` phase - the two +/// synchronisations around it are 0.03 ms each. +/// +/// The obvious repair is to parallelise the scan inside `sampler_kernel`, and it is WRONG: with one thread +/// per token, a block reduction over the vocabulary has nothing to reduce, and the threads that returned +/// early are not there for `__syncthreads` or `__shfl_down_sync`. The first attempt did exactly that and +/// produced the token `5120` thirty-two times. The grid has to be over tokens with the BLOCK over the +/// vocabulary, which is a different launch configuration and therefore a different kernel. +/// +/// **THE TIE RULE IS UNCHANGED AND THAT IS THE WHOLE CORRECTNESS ARGUMENT.** The serial scan walked `v` +/// ascending with `if (s > bv)`, so the LOWEST index wins a tie. Each thread keeps that rule over its own +/// strided subset and the reduction resolves two candidates by taking the larger value and, on equality, the +/// SMALLER index - the same total order, so `sampler_parity` and C1 see no change. +__global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vocab, + const int* __restrict__ history, int history_len, const SamplerParams p, + int pmin, int plen, int* __restrict__ out) { + const int t = blockIdx.x; + const float* l = logits + (size_t) t * n_vocab; + (void) pmin; + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = plen < history_len ? plen : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + + // PENALTY MEMBERSHIP AS A BITMAP. The history touches at most `hlen` tokens of a quarter-million + // vocabulary, but the naive `history_count` per candidate per argmax round costs O(k x n_vocab x hlen) + // integer compares (~318 M per token at k=20, hlen=64 - measured 45 -> 31 tok/s on a real workload). + // A shared bitmap gives an O(1) membership test, and only the (at most hlen) hits pay the count scan; + // the counts - and therefore every sampled value - are exactly what the per-candidate scan produced. + extern __shared__ unsigned int penal_bits[]; + const int bits_words = (int) ((n_vocab + 31) / 32); + // The gate needs a NON-EMPTY WINDOW (`hlen > 0`): the launch sizes the shared bitmap only when penalties + // are on, so a caller handing over a history buffer with `penalty_last_n == 0` must not touch it. + const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; + if (use_bits) { + for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) + if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate + atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); + __syncthreads(); + } + auto hit_count = [&](int v) -> int { + if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; + return history_count(hrow, hlen, v); + }; + + // `n_vocab` is the "no candidate" index: it loses every comparison to a real one, so a thread with no + // elements contributes nothing rather than contributing a bogus zero. + float bv = __int_as_float(0xff800000); // -inf + int best = n_vocab; + for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { + const float s = apply_penalties(l[v], hit_count(v), p); + if (s > bv) { bv = s; best = v; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); + if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } + } + __shared__ float sv[32]; + __shared__ int si[32]; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + if (lane == 0) { sv[warp] = bv; si[warp] = best; } + __syncthreads(); + if (warp == 0) { + const int nw = (int) ((blockDim.x + 31) >> 5); + float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); + int wi = lane < nw ? si[lane] : n_vocab; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); + if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } + } + // A tie between two `-inf` candidates leaves `wi == n_vocab`, and the serial version answered 0. + if (lane == 0) out[t] = (wi < n_vocab) ? wi : 0; + } +} + +/// **THE SAMPLED PATH, ONE BLOCK PER TOKEN.** The kernel below replaced a version that ran the whole chain +/// in ONE THREAD per token (`<<>>`, so a 4-token window fielded four threads): `top_k` alone +/// was `k` sequential scans of the vocabulary with an inner sweep over the already-taken list - 20 x 248,320 +/// iterations of dependent work on one SM - and a verify window measured **1.6 s in the sampler**, which made +/// every temperature-bearing request ~30x slower than a greedy one. The selection is `k` argmax rounds, and +/// an argmax over the vocabulary parallelises exactly like `sampler_greedy_kernel` (block over the vocab), so +/// the rounds run back to back inside a block-per-token launch: the per-token cost falls to +/// `k x n_vocab / 1024` plus `k` block reductions. +/// +/// THE SEMANTICS ARE THE SERIAL ONES, EXACTLY. Each round's argmax resolves ties to the LOWEST index (the +/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its +/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the +/// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference. +/// +/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken` +/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at +/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at +/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order. +__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens, + const int* __restrict__ history, int history_len, const SamplerParams p, + int* __restrict__ out) { + const int t = blockIdx.x; + if (t >= n_tokens) return; + const float* l = logits + (size_t) t * n_vocab; + + // Temperature is needed by BOTH stages below, so it is computed here; the chain still APPLIES it after + // the truncation filters - the survivors are chosen on the raw logits and only then scaled. + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + + // The penalty window is the last `penalty_last_n` entries of this row's history (disabled at this + // launch: `sample_tokens` refuses a non-zero `penalty_last_n` without a history buffer). + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + + // the membership bitmap, as in `sampler_greedy_kernel` - see the cost note there. The gate needs an + // NON-EMPTY WINDOW too: the launch sizes the bitmap only when penalties are on, so a caller that hands over + // a stale history buffer with `penalty_last_n == 0` must not touch it. + extern __shared__ unsigned int penal_bits[]; + const int bits_words = (int) ((n_vocab + 31) / 32); + const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; + if (use_bits) { + for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) + if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate + atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); + __syncthreads(); + } + auto hit_count = [&](int v) -> int { + if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; + return history_count(hrow, hlen, v); + }; + + // top_k in 1..64 is taken as given; 0 ("off") and anything wider mean the widest shortlist the kernel + // keeps, 64. Every row writes out[t]: a verify window reads all of them. + const int KMAX = 64; + int k = (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX; + if (k > n_vocab) k = n_vocab; + + // ---- top_k: k rounds of a block argmax over the not-yet-taken. `sel_*` holds the kept ids and their + // raw logits in selection order: descending by value, ties to the lower index, which is the order the + // top_p cut below is defined over. + __shared__ int sel_ids[KMAX]; + __shared__ float sel_logit[KMAX]; + __shared__ float sv[32]; + __shared__ int si[32]; + for (int i = 0; i < k; ++i) { + // `n_vocab` is the "no candidate" index: it loses every comparison to a real one (same convention as + // the greedy kernel, whose tie rule this reduction shares). + float bv = __int_as_float(0xff800000); // -inf + int best = n_vocab; + for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { + bool taken = false; + for (int j = 0; j < i; ++j) if (sel_ids[j] == v) { taken = true; break; } + if (taken) continue; + const float s = apply_penalties(l[v], hit_count(v), p); + if (s > bv) { bv = s; best = v; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); + if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } + } + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + if (lane == 0) { sv[warp] = bv; si[warp] = best; } + __syncthreads(); + if (warp == 0) { + const int nw = (int) ((blockDim.x + 31) >> 5); + float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); + int wi = lane < nw ? si[lane] : n_vocab; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); + if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } + } + if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } + } + __syncthreads(); + } + + // ---- top_p over the top_k list (penalised logits, descending as the selection produced them), then min_p, + // then temperature and one Philox draw - llama.cpp's order (issue #53). Every thread computes the same chain + // redundantly over `sel_*` - the arithmetic is the serial kernel's, instruction for instruction - so they + // agree on `pick` and thread 0 writes it. + int n_keep = k; + float mx = sel_logit[0]; + for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); + if (p.top_p < 1.0f) { + double sum = 0.0; + for (int i = 0; i < k; ++i) sum += exp((double) sel_logit[i] - (double) mx); + double cum = 0.0; + int cut = k; + for (int i = 0; i < k; ++i) { + cum += exp((double) sel_logit[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; + } + // ---- min_p on top_p's survivors: the descending prefix whose probability is at least `min_p` of the top + // token's. In logit space the threshold is `sel_logit[0] + logf(min_p)` - equivalent to `p >= min_p * p_max` + // without the overflow an exp of raw logits risks. 0 disables, and the head itself always survives + // (`expf(0) == 1 >= min_p` for min_p in 0..1), so the count never reaches zero. + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + logf(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel_logit[i] < thresh) { n_keep = i; break; } + } + // temperature only: the penalties were applied once, before the selection (issue #53: they were applied a + // second time here, after the temperature scaling - llama.cpp's chain has one penalties stage) + auto scaled = [&](int i) { return sel_logit[i] * inv_t; }; + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx); + const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); + double cum = 0.0; + int pick = sel_ids[n_keep - 1]; + for (int i = 0; i < n_keep; ++i) { + cum += exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel_ids[i]; break; } + } + if (threadIdx.x == 0) out[t] = pick; +} + +// ---- the same list, in the same order, without the `taken` sweep ---- +// +// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value > +// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict +// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and +// fall to the id, as there), so round i picks the i-th logit of the order. NaN and -inf are never picked (`s > bv` +// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0. + +constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX +constexpr unsigned kFullMask = 0xFFFFFFFFu; + +// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary +__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) { + int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax; + return k > n_vocab ? n_vocab : k; +} + +// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order +__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) { + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } +} + +// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is +// associative and commutative in a strict total order (two lanes never hold different candidates that compare +// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair. +__device__ __forceinline__ void warp_first(float& bv, int& bi) { +#pragma unroll + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_xor_sync(kFullMask, bv, off); + const int oi = __shfl_xor_sync(kFullMask, bi, off); + take_first(bv, bi, ov, oi); + } +} + +/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are +/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail +/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce. +/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two +/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of +/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so +/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the +/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.) +/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to +/// `*prob_out`. The sampler's own calls take kProb = false, whose code is the tail above, unchanged. +template +__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t, + int* __restrict__ out, double* ex, float* prob_out = nullptr) { + const int lane = (int) (threadIdx.x & 31); + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + int n_keep = k; + float mx = sel_logit[0]; + for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]); + if (p.top_p < 1.0f) { + for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < k; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); // lane 0 has read every `ex` before it is overwritten + for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + int cut = k; + if (lane == 0) { + double cum = 0.0; + for (int i = 0; i < k; ++i) { + cum += ex[i]; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + } + cut = __shfl_sync(kFullMask, cut, 0); + if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; + n_keep = cut; + __syncwarp(); // `ex` is written again below + } + // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic) + if (p.min_p > 0.0f) { + const float thresh = sel_logit[0] + logf(p.min_p); + for (int i = 0; i < n_keep; ++i) + if (sel_logit[i] < thresh) { n_keep = i; break; } + } + // temperature, then one Philox draw + float smx = sel_logit[0] * inv_t; + for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t); + for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx); + __syncwarp(); + double sum = 0.0; + if (lane == 0) + for (int i = 0; i < n_keep; ++i) sum += ex[i]; + sum = __shfl_sync(kFullMask, sum, 0); + __syncwarp(); + for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum; + __syncwarp(); + if (lane == 0) { + const float u = philox_uniform(p.seed, p.counter + (uint64_t) t); + double cum = 0.0; + int pi = n_keep > 0 ? n_keep - 1 : 0; + int pick = sel_ids[pi]; + for (int i = 0; i < n_keep; ++i) { + cum += ex[i]; + if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; } + } + out[t] = pick; + if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f; + } +} + +/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits +/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is +/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is +/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the +/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty +/// in both versions (nothing after -inf beats -inf). O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp +/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run. +__global__ void __launch_bounds__(1024) +sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int* __restrict__ out) { + const int t = blockIdx.x; + const float* l = logits + (size_t) t * n_vocab; + + // the penalty window and its membership bitmap, exactly as in `sampler_kernel` + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + extern __shared__ unsigned int penal_bits[]; + const int bits_words = (int) ((n_vocab + 31) / 32); + const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0; + if (use_bits) { + for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) + if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate + atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31)); + __syncthreads(); + } + auto hit_count = [&](int v) -> int { + if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0; + return history_count(hrow, hlen, v); + }; + + const int k = sampled_k(p.top_k, n_vocab); + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + __shared__ float sv[32]; + __shared__ int si[32]; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + for (int i = 0; i < k; ++i) { + float bv = __int_as_float(0xff800000); // -inf + int best = n_vocab; + for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) { + const float s = apply_penalties(l[v], hit_count(v), p); + if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; } + } + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off); + if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; } + } + if (lane == 0) { sv[warp] = bv; si[warp] = best; } + __syncthreads(); + if (warp == 0) { + const int nw = (int) ((blockDim.x + 31) >> 5); + float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000); + int wi = lane < nw ? si[lane] : n_vocab; + for (int off = 16; off > 0; off >>= 1) { + const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off); + const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off); + if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; } + } + if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; } + } + __syncthreads(); + // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken. + prev_v = sel_logit[i]; + prev_i = sel_ids[i]; + } + if (warp != 0) return; + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its +// 248,320 logits k times. Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of +// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then +// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part +// and a merge of ordered lists is ordered - the selection order being a strict total order (above). +constexpr int kSplitPerLane = 32; // logits per lane, in registers +constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp +constexpr int kSplitWarps = 4; +constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block +constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144 +constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound) + +/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and +/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the +/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list +/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches. +template +__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab, + Sink&& sink) { + const int lane = (int) (threadIdx.x & 31); + float hv[2]; + int hi[2], pos[2]; +#pragma unroll + for (int m = 0; m < 2; ++m) { + const int L = lane + 32 * m; + pos[m] = 0; + hv[m] = __int_as_float(0xff800000); + hi[m] = n_vocab; + if (L < nl) { + const int2 c = lists[(size_t) L * stride]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } + } + for (int i = 0; i < k; ++i) { + float bv = hv[0]; + int bi = hi[0]; + take_first(bv, bi, hv[1], hi[1]); + warp_first(bv, bi); + sink(i, bv, bi); + if (bi < n_vocab) { +#pragma unroll + for (int m = 0; m < 2; ++m) { + if (hi[m] != bi) continue; + if (++pos[m] < k) { + const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]]; + hi[m] = c.x; + hv[m] = __int_as_float(c.y); + } else { + hi[m] = n_vocab; + hv[m] = __int_as_float(0xff800000); + } + } + } + } +} + +/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp +/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line) +/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory +/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand` +/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)). +__global__ void __launch_bounds__(kSplitWarps * 32) +sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history, + int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) { + const int t = blockIdx.y; + const float* l = logits + (size_t) t * n_vocab; + const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31); + const int blo = (int) blockIdx.x * kSplitBlockSpan; + + const int* hrow = history ? history + (size_t) t * history_len : nullptr; + int hlen = 0; + if (hrow) { + hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len; + if (hlen < 0) hlen = 0; + hrow += history_len - hlen; // the window is the TAIL + } + // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test, + // and a hit pays the same exact count over the whole window. + __shared__ unsigned int bits[kSplitBlockSpan / 32]; + const bool use_bits = hrow != nullptr && hlen > 0; + if (use_bits) { + for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < hlen; i += blockDim.x) { + const int h = hrow[i]; + if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan) + atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31)); + } + __syncthreads(); + } + + // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the + // bitmap's hits go through it. Past the vocabulary: -inf, which no round picks. + const int lo = blo + warp * kSplitWarpSpan; + float s[kSplitPerLane]; +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane; + s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000); + } + if (use_bits) { +#pragma unroll + for (int j = 0; j < kSplitPerLane; ++j) { + const int v = lo + 32 * j + lane, b = v - blo; + if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31)))) + s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p); + } + } + + __shared__ int2 wl[kSplitWarps][kSelMax]; + float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit + int prev_i = -1; + int i = 0; + for (; i < k; ++i) { + // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in + // the order; `take_first` then orders the two + float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000); + int i0 = n_vocab, i1 = n_vocab; +#pragma unroll + for (int j = 0; j < kSplitPerLane; j += 2) { + const int v0 = lo + 32 * j + lane, v1 = v0 + 32; + const float x0 = s[j], x1 = s[j + 1]; + if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; } + if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; } + } + take_first(b0, i0, b1, i1); + warp_first(b0, i0); + if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits + if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0)); + prev_v = b0; + prev_i = i0; + } + for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u); // sentinels + __syncthreads(); + if (warp == 0) { + int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k; + warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) { + if (lane == 0) dst[r] = make_int2(id, __float_as_int(v)); + }); + } +} + +/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x +/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks. +__global__ void __launch_bounds__(32) +sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k, + int* __restrict__ out) { + const int t = blockIdx.x; + const int lane = (int) threadIdx.x; + __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + const int2* src = cand + (size_t) t * n_blocks * k; + for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e]; + __syncwarp(); + warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) { + if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; } + }); + __syncwarp(); + sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex); +} + +// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the +// target's chain and the target's Philox draw. Everything that varies per request or per round - the chain's +// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory: +// these kernels are captured into the drafter's round/step graphs. One row, `nv` logits: the draft head's +// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id. + +/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from +/// mapped host memory into the device copies the chain's kernels read. +__global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const int* __restrict__ mh, + SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap) { + const volatile int* s = (const volatile int*) mp; + int* d = (int*) dp; + for (int i = threadIdx.x; i < (int) (sizeof(SamplerParams) / sizeof(int)); i += blockDim.x) d[i] = s[i]; + const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap); + const volatile int* vh = (const volatile int*) mh; + for (int i = cap - h + (int) threadIdx.x; i < cap; i += blockDim.x) ring[i] = vh[i]; +} + +/// The penalties, applied in place to the draft logits before the selection - the target applies the same +/// `apply_penalties` to the same token with the same count over the same window before its own. Draft j's window +/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1. A history token outside the draft head's +/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it. +__global__ void coupled_penalize_kernel(float* __restrict__ logits, int nv, const int* __restrict__ id_to_sub, + int id_vocab, const SamplerParams* __restrict__ dp, const int* __restrict__ ring, + int cap, int j) { + const SamplerParams p = *dp; + const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap); + if (h <= 0) return; + const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h); + extern __shared__ unsigned int seen[]; + const int words = (nv + 31) / 32; + for (int w = threadIdx.x; w < words; w += blockDim.x) seen[w] = 0u; + __syncthreads(); + for (int i = threadIdx.x; i < h; i += blockDim.x) { + const int v = hrow[i]; + if (v < 0 || v >= id_vocab) continue; + const int s = id_to_sub != nullptr ? id_to_sub[v] : v; + if (s < 0 || s >= nv) continue; + const unsigned bit = 1u << (s & 31); + if (atomicOr(&seen[s >> 5], bit) & bit) continue; + logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p); + } +} + +/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then +/// `sampled_tail_warp` with the counter of the row that will verify this draft. Lane 0 maps the pick to its token +/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window. +__global__ void __launch_bounds__(32) +coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kpart, + const SamplerParams* __restrict__ dp, const int* __restrict__ step_rec, + const int* __restrict__ sub_to_id, int* __restrict__ ring, int cap, int j, int* __restrict__ out_id, + float* __restrict__ out_prob) { + const int lane = (int) threadIdx.x; + SamplerParams p = *dp; + p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]); + const int k = sampled_k(p.top_k, nv); // <= kpart: the first k of a union lie in the first k of each list + __shared__ int2 lists[kSplitMaxBlocks * kSelMax]; + __shared__ int sel_ids[kSelMax]; + __shared__ float sel_logit[kSelMax]; + __shared__ double ex[kSelMax]; + __shared__ int pick[1]; + __shared__ float prob[1]; + for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e]; + __syncwarp(); + warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) { + if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; } + }); + __syncwarp(); + if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax, defensively + if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; } + } else { + sampled_tail_warp(sel_ids, sel_logit, k, p, 0, pick, ex, prob); + } + __syncwarp(); + if (lane == 0) { + const int s = pick[0]; + const int id = sub_to_id != nullptr ? sub_to_id[s] : s; + *out_id = id; + *out_prob = prob[0]; + ring[cap + j] = id; + } +} + +// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20), +// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies. +enum class SampledPath { Split, OneBlock, Old }; + +bool env_flag(const char* name) { + const char* e = std::getenv(name); + return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0; +} + +SampledPath sampled_path() { + static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old + : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock + : SampledPath::Split; + return path; +} + +// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it +// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured. +bool stream_capturing(void* stream) { + if (stream == nullptr) return false; + cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone; + if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) { + (void) cudaGetLastError(); + return true; + } + return st != cudaStreamCaptureStatusNone; +} + +// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses +// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of +// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a +// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch, +// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers +// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr +// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so +// later calls of that size do not retry cudaMalloc each time. +int2* split_scratch(void* stream, size_t entries) { + struct Slot { + int device; + void* stream; + int2* ptr; + size_t entries; + size_t failed; // the smallest size cudaMalloc refused (0: none) + }; + static std::mutex mu; + static std::vector slots; + static std::vector retired; + int device = 0; + if (cudaGetDevice(&device) != cudaSuccess) { + (void) cudaGetLastError(); + return nullptr; + } + std::lock_guard lock(mu); + Slot* slot = nullptr; + for (Slot& s : slots) + if (s.device == device && s.stream == stream) slot = &s; + if (slot == nullptr) { + slots.push_back({device, stream, nullptr, 0, 0}); + slot = &slots.back(); + } + if (slot->entries >= entries) return slot->ptr; + if (slot->failed != 0 && entries >= slot->failed) return nullptr; + constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax; + size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap; + if (want < entries) want = entries; + int2* ptr = nullptr; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + want = entries; + if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) { + (void) cudaGetLastError(); + slot->failed = entries; + return nullptr; + } + } + if (slot->ptr != nullptr) retired.push_back(slot->ptr); + slot->ptr = ptr; + slot->entries = want; + return ptr; +} + +} // namespace + +void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, + const SamplerParams& p, int* out, void* stream) { + if (n_tokens <= 0 || n_vocab <= 0) return; + if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) { + std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n", + p.penalty_last_n, (const void*) history, history_len); + std::exit(1); + } + const unsigned shmem = (history != nullptr && history_len > 0 && p.penalty_last_n > 0) + ? (unsigned) ((n_vocab + 31) / 32) * sizeof(unsigned) // the penalty bitmap + : 0; + if (p.greedy || p.temperature <= 0.0f) { + // One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`. + const int gthreads = 1024; + sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>( + logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out); + } else if (sampled_path() == SampledPath::Old) { + // The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See + // `sampler_kernel`'s header for what the old one-thread-per-token launch cost. + sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( + logits, n_vocab, n_tokens, history, history_len, p, out); + } else { + // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per + // row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge + // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture, + // no scratch. + const int k = sampled_k(p.top_k, n_vocab); + const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan; + int2* scratch = nullptr; + if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows && + !stream_capturing(stream)) + // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it + scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax); + if (scratch != nullptr) { + sampler_split_part_kernel<<>>(logits, n_vocab, history, history_len, p, k, + n_blocks, scratch); + sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>( + scratch, n_blocks, n_vocab, p, k, out); + } else { + sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>( + logits, n_vocab, history, history_len, p, out); + } + } + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "sample_tokens launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr) cudaDeviceSynchronize(); +} + +namespace { +int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; } +int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; } +void coupled_check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "%s launch: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} +} // namespace + +size_t coupled_draft_scratch_bytes(int nv) { + if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0; + return (size_t) coupled_blocks(nv) * (size_t) kSelMax * sizeof(int2); +} + +void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params, + int32_t* ring, int cap, void* stream) { + coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap); + coupled_check("coupled_draft_stage"); +} + +void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab, + const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec, + void* scratch, int32_t* out_id, float* out_prob, void* stream) { + const cudaStream_t s = (cudaStream_t) stream; + const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv); + if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) { + std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks); + std::exit(1); + } + coupled_penalize_kernel<<<1, 1024, (unsigned) ((nv + 31) / 32) * sizeof(unsigned), s>>>(logits, nv, id_to_sub, + id_vocab, params, ring, cap, j); + coupled_check("coupled_penalize"); + // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list, + // since the request's top_k is only known on the device), penalties already applied above + sampler_split_part_kernel<<>>( + logits, nv, nullptr, 0, SamplerParams{}, kpart, n_blocks, (int2*) scratch); + coupled_check("coupled_draft split part"); + coupled_merge_kernel<<<1, 32, 0, s>>>((const int2*) scratch, n_blocks, nv, kpart, params, step_rec, sub_to_id, ring, + cap, j, out_id, out_prob); + coupled_check("coupled_draft merge"); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/shared_expert.cu b/engine/strata/src/kernels/cuda/shared_expert.cu new file mode 100644 index 00000000..d795bf84 --- /dev/null +++ b/engine/strata/src/kernels/cuda/shared_expert.cu @@ -0,0 +1,346 @@ +// src/kernels/cuda/shared_expert.cu - P2.S2: the shared expert. +// +// `ref/moe.py::shared_expert`, transcribed: +// +// h = silu(x @ gate_shexp.T) * (x @ up_shexp.T) <- SILU GOES ON GATE, not on up +// h = h @ down_shexp.T (nt, n_embd) +// g = sigmoid(x @ gate_inp_shexp) (nt,) ONE SCALAR PER TOKEN +// return h * g[:, None] +// +// TWO THINGS HERE WERE BELIEVED WRONG FOR MANY ROUNDS and `docs/semantics.md` records both. SILU GOES ON THE +// GATE TENSOR: the opposite reading is plausible, produces the right shapes, and is wrong. And +// `ffn_gate_inp_shexp` is `(n_embd,)` whose output is "one value per token" - a SCALAR gate obtained by dotting +// that vector with the hidden state, NOT a per-expert gate and NOT a per-dimension elementwise one. Both were +// live readings of the same shapes until the source comment settled them. +// +// The result is ADDED to the routed output - not router-weighted, not renormalised against it. +// +// The legacy canonical projections use their explicit Q8_0/Q8_K activation images. The optional native +// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus +// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU. +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s2_gemv_q8.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int THREADS = 128; +bool native_bf16 = false; + +// `f32_to_f16` used to live here as a private copy. Round 198 found it - and the identical one in +// `quantize_act.cu` - returning a NaN for every FINITE value that overflows fp16 (1e30, 65536, 1e45) instead +// of saturating to inf, because `exp >= 31` conflates an f32 inf/NaN with an out-of-range finite exponent. +// This file's fixture is all O(1), so it could not see it. The conversion now lives in one place, with the +// regimes spelled out. + +// silu(x) = x / (1 + exp(-x)), written as `ref/moe.py` writes it, in DOUBLE then cast - the reference works in +// float64 and a float32 exp differs in the last bits. The multiplication by `up` is the reference's order. +__global__ void swiglu_kernel(const float* __restrict__ gate, const float* __restrict__ up, + float* __restrict__ out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const double x = (double) gate[i]; + out[i] = (float) (x / (1.0 + exp(-x))) * up[i]; +} + +__global__ void native_swiglu_kernel(const float* gate, const float* up, float* out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + // Pinned CUDA unary.cuh op_silu, then unary_gated_op_kernel's multiply. + // Explicit intrinsics reproduce its --use_fast_math operations without + // changing compilation of the default legacy arithmetic in this file. + out[i] = __fdividef(gate[i], 1.0f + __expf(-gate[i])) * up[i]; +} + +__global__ void to_f16_kernel(const float* __restrict__ in, uint16_t* __restrict__ out, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] = f16_from_f32(in[i]); +} + +// The per-token scalar gate: sigmoid(dot(x, w)) with w = `ffn_gate_inp_shexp` (n_embd,). +// +// **ONE THREAD WAS THE LARGEST SINGLE KERNEL IN THE MODEL, AND THE COMMENT DEFENDING IT SAID WHY IT SHOULD +// NOT BE.** It read: "n_embd is 2560, so this is a short serial loop and the parallelism is elsewhere." +// 2560 iterations is not short when each one is a DOUBLE multiply-add. This card's double rate is **1/64** of +// its float rate, so the loop is a 2560-long dependency chain through a 1/64-rate unit - tens of microseconds +// from the chain alone, before counting 2560 sequential global loads issued by one thread with no coalescing. +// +// MEASURED, and this is what the number looks like from outside: `shared_expert` is **0.2374 ms of a +// 0.8883 ms block - 26.7% of the whole block, 11.4 ms per token** - for three projections that read 5.5 MB and +// whose memory floor is 0.009 ms. It is seven kernels, and six of them are GEMVs or elementwise passes over +// 640-2560 elements. This is the one that cannot be explained by bandwidth. +// +// THE DOUBLE ACCUMULATOR IS KEPT. `ref/gr.py` reduces in float64 and `block_sum` in `gr.cu` exists for the +// same reason - the summation order of a tree is not the reference's, so the defence is enough precision that +// the order stops mattering. What changes is the CHAIN: ten terms per thread instead of 2560, then a +// tree-reduce. Through a sigmoid, a 1e-16 relative difference in the dot is not a difference. +// +// **BOTH OPERANDS ARE BF16, AND THAT IS THE REFERENCE'S CONTRACT, NOT A STORAGE DETAIL.** `gate_inp_shexp` is a +// BF16 weight, so ggml converts the activation to its `vec_dot_type` - BF16 - exactly as it does for the router +// (`docs/activation-contract.md`). This kernel used to take `const float* w` while the LOADER had already +// re-rounded the tensor to 2 B/elem, so it read 2560 floats out of a 5120-byte buffer: 5120 B past the end of +// the tensor, inside the 4.5 GiB arena, where nothing faults. The dot came out astronomically large, sigmoid +// saturated to 1.0, and `scale_kernel` multiplied the shared expert's output by it - which is why the FIRST +// symptom was 2560 non-finite outputs rather than a wrong scalar. +// +// A wrong scalar here is the quiet failure mode: sigmoid bounds the damage to [0,1], so a gate that should be +// 0.5 and reads 1.0 scales the shared expert by 2x and produces perfectly finite, perfectly plausible logits. +__device__ __forceinline__ double warp_sum_d(double v) { + for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off); + return __shfl_sync(0xFFFFFFFFu, v, 0); +} + +__global__ void scalar_gate_kernel(const uint16_t* __restrict__ x_bf16, const uint16_t* __restrict__ w_bf16, + float* __restrict__ out, int n_embd) { + __shared__ double scratch[8]; // 8 warps: the launch is <<<1, 256>>> + double acc = 0.0; + for (int i = threadIdx.x; i < n_embd; i += blockDim.x) + acc += (double) f32_from_bf16(x_bf16[i]) * (double) f32_from_bf16(w_bf16[i]); + __syncthreads(); + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + acc = warp_sum_d(acc); + if (lane == 0) scratch[warp] = acc; + __syncthreads(); + const int nw = ((int) blockDim.x + 31) >> 5; + if (warp == 0) { + acc = (threadIdx.x < nw) ? scratch[threadIdx.x] : 0.0; + acc = warp_sum_d(acc); + if (threadIdx.x == 0) out[0] = (float) (1.0 / (1.0 + exp(-acc))); + } +} + +__global__ void scale_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[i] *= g[0]; +} + +__global__ void native_scalar_sigmoid_kernel(float* gate) { + // Match the single-token CUDA sigmoid's FP32 fast-math operations without changing legacy kernels' + // compilation flags. The dot product was already reduced by the pinned native MMVF implementation. + gate[0] = __fdividef(1.0f, 1.0f + __expf(-gate[0])); +} +__global__ void native_scalar_sigmoid_multi_kernel(float* gate) { // thread t = token t, same expression + gate[threadIdx.x] = __fdividef(1.0f, 1.0f + __expf(-gate[threadIdx.x])); +} + +/// The MoE block's final combination. See the header for the two readings it exists to pin. +__global__ void moe_combine_kernel(const float* __restrict__ parts, const float* __restrict__ weights, + const float* __restrict__ shared, float* __restrict__ y, int n_embd, + int k, int has_shared) { + const int j = blockIdx.x * blockDim.x + threadIdx.x; + if (j >= n_embd) return; + // Accumulate in DOUBLE, in the reference's own order (`for i in range(k): out[t] += w[t,i] * g[0]`). + // f32 would be defensible for ten terms, but the reference is float64 and this is one line. + double acc = 0.0; + for (int e = 0; e < k; ++e) acc += (double) weights[e] * (double) parts[(size_t) e * n_embd + j]; + // The SHARED output is added PLAIN - not router-weighted, not renormalised against the routed sum. + if (has_shared) acc += (double) shared[j]; + y[j] = (float) acc; +} + +} // namespace + +void shared_expert_set_native_bf16(bool enabled) { native_bf16 = enabled; } + +namespace { +__global__ void scale_rows_kernel(float* __restrict__ out, const float* __restrict__ g, int n) { + const int t = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[(size_t) t * n + i] *= g[t]; +} +} // namespace + +void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw, + const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd, + int64_t n_ff, void* stream) { + if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream) + throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream"); + cudaStream_t cs = (cudaStream_t) stream; + native_quantize_q8_1(x, nw.q8_1, (int) n_embd, n_tok, stream); + native_mmvq(nw.gate_type, nw.gate_data, nw.q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream); + native_mmvq(nw.up_type, nw.up_data, nw.q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream); + const int n = (int) (n_ff * n_tok); + native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n); + native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream); + native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream); + static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch + bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream); + native_scalar_sigmoid_multi_kernel<<<1, n_tok, 0, cs>>>(g); + } else + for (int t = 0; t < n_tok; ++t) { + if (native_bf16) { + bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream); + native_scalar_sigmoid_kernel<<<1, 1, 0, cs>>>(g + t); + } else { + scalar_gate_kernel<<<1, 256, 0, cs>>>(x_bf16 + (size_t) t * n_embd, gate_inp_bf16, g + t, (int) n_embd); + } + } + scale_rows_kernel<<>>( + out, g, (int) n_embd); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e)); +} + +uint64_t shared_expert_scratch_bytes(int64_t n_ff) { + // gate (n_ff f32) | up (n_ff f32) | q8_0 (n_ff/32*34) | q8k (n_ff/256*292) | g (1 f32), 16-byte aligned + const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull; + const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull; + const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull; + return a * 2 + q0 + qk + 32; +} + +void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* x_bf16, const SForm& gate_form, + const uint8_t* gate_codes, const float* gate_scales, const float* gate_off, + const SForm& up_form, const uint8_t* up_codes, const float* up_scales, const float* up_off, + const SForm& down_form, const uint8_t* down_codes, const float* down_scales, + const float* down_off, const uint16_t* gate_inp_bf16, float* scratch, float* out, + int64_t n_embd, int64_t n_ff, int tpr, void* stream, const float* x_f32, + const NativeSharedWeights* native) { + if (n_embd <= 0 || n_ff <= 0) return; + const bool use_native = native_bf16; + const bool native_gate = native && native->gate_data && native_mmvq_supported(native->gate_type); + const bool native_up = native && native->up_data && native_mmvq_supported(native->up_type); + const bool native_down = native && native->down_data && native_mmvq_supported(native->down_type); + const bool native_projection = native_gate || native_up || native_down; + if ((use_native || native_gate || native_up) && !x_f32) + throw std::invalid_argument("shared_expert native input projection requires unrounded x_f32"); + if (native_projection) { + if (!native->q8_1 || !stream || n_embd > INT_MAX || n_ff > INT_MAX) + throw std::invalid_argument("shared_expert native projections require scratch, stream and int32 dimensions"); + // Validate every active shape before any kernel is enqueued. + if (native_gate) native_mmvq_weight_bytes(native->gate_type, (int) n_embd, (int) n_ff); + if (native_up) native_mmvq_weight_bytes(native->up_type, (int) n_embd, (int) n_ff); + if (native_down) native_mmvq_weight_bytes(native->down_type, (int) n_ff, (int) n_embd); + } + if (scratch == nullptr) { + std::fprintf(stderr, "shared_expert: scratch is null; the caller owns it " + "(see shared_expert_scratch_bytes)\n"); + std::exit(1); + } + // CARVED FROM THE CALLER'S SCRATCH. This used to be four `cudaMalloc`s and four `cudaFree`s per call, which + // is illegal during stream capture AND a token-path allocation - P2.T10 forbids both. + uint8_t* p = (uint8_t*) scratch; + const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull; + const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull; + const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull; + float* gate = (float*) p; + float* up = (float*) (p + a); + uint8_t* h_q8_0 = (uint8_t*) (p + a * 2); + uint8_t* h_q8k = (uint8_t*) (p + a * 2 + q0); + float* g = (float*) (p + a * 2 + q0 + qk); + + // WHICH ACTIVATION THIS PROJECTION WANTS, READ FROM ITS OWN FORM. See `SForm::act_kind`: the three + // families cannot be told apart by the other fields, so the kind is carried rather than derived. + auto gemv = [&](const SForm& f, const uint8_t* codes, const float* scales, const float* off, + const uint8_t* act80, const uint8_t* actq8k, float* y, int64_t nin, int64_t nout) { + if (f.code_bits == 2) { + s2_gemv_q8(act80, codes, scales, y, nin, nout, tpr, stream); + } else if (f.act_kind == 1) { + s_gemv_q8k_split(actq8k, codes, scales, off, y, nin, nout, f, stream); + } else { + s_gemv_q8_0_split(act80, codes, scales, off, y, nin, nout, f, stream); + } + }; + + const unsigned g_ff = (unsigned) ((n_ff + THREADS - 1) / THREADS); + const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS); + + // gate and up projections, then silu(gate) * up in place in `gate` + if (native_gate || native_up) + native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); + if (native_gate) + native_mmvq(native->gate_type, native->gate_data, native->q8_1, gate, (int) n_embd, (int) n_ff, 1, stream); + else + gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff); + if (native_up) + native_mmvq(native->up_type, native->up_data, native->q8_1, up, (int) n_embd, (int) n_ff, 1, stream); + else + gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff); + if (native_projection) + native_swiglu_kernel<<>>(gate, up, gate, (int) n_ff); + else + swiglu_kernel<<>>(gate, up, gate, (int) n_ff); + + // down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is + // what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no + // justification beyond "the kernel takes fp16". + if (native_down) { + native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream); + native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream); + } else if (down_form.act_kind == 1) { + if (n_ff % 256 != 0) { + std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple " + "of 256; Q8_K is structurally impossible here\n", (long long) n_ff); + std::exit(1); + } + quantize_q8_K(gate, h_q8k, n_ff, stream); + gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); + } else if (down_form.code_bits == 2) { + quantize_q8_0(gate, h_q8_0, n_ff, stream); + gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); + } else { + quantize_q8_0(gate, h_q8_0, n_ff, stream); + gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd); + } + + // the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden + // state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the + // native branch uses the pinned CUDA FP32 activation contract. + // `<<<1, 256>>>`: one block, because the output is ONE scalar and a second block would only add a global + // round trip. 256 threads is the reduction's width, not the problem's size. + if (use_native) { + bf16_gemv_fp32_mmvf(x_f32, gate_inp_bf16, g, n_embd, 1, stream); + native_scalar_sigmoid_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(g); + } else { + scalar_gate_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(x_bf16, gate_inp_bf16, g, (int) n_embd); + } + scale_kernel<<>>(out, g, (int) n_embd); + + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "shared_expert: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +void moe_combine(const float* parts, const float* weights, const float* shared, float* y, int64_t n_embd, + int64_t k, void* stream) { + if (n_embd <= 0 || k <= 0) return; + // k > 64 is refused rather than truncated: silently summing the first 64 of a longer list would be a + // wrong answer that looks like a right one, and no geometry in this artifact comes close to it. + if (k > 64) { + std::fprintf(stderr, "moe_combine: k = %lld exceeds 64\n", (long long) k); + std::exit(1); + } + const unsigned grid = (unsigned) ((n_embd + THREADS - 1) / THREADS); + moe_combine_kernel<<>>(parts, weights, shared, y, (int) n_embd, + (int) k, shared != nullptr); + if (stream == nullptr) { + const cudaError_t e = cudaDeviceSynchronize(); + if (e != cudaSuccess) { + std::fprintf(stderr, "moe_combine: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + } +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cuda/verify_kernels.cu b/engine/strata/src/kernels/cuda/verify_kernels.cu new file mode 100644 index 00000000..7908ce40 --- /dev/null +++ b/engine/strata/src/kernels/cuda/verify_kernels.cu @@ -0,0 +1,559 @@ +// src/kernels/cuda/verify_kernels.cu - see include/strata/kernels/verify_kernels.hpp. +// +// The per-token arithmetic of every kernel here is transcribed from its single-token original (fused_gdn.cu, +// elementwise.cu) with the same operation order, so a verify window reproduces plain decode bit for bit. +#include "strata/kernels/verify_kernels.hpp" +#include "strata/kernels/dp4a.hpp" + +#include + +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int S = 128; // GDN state size +constexpr int RG = 4; +constexpr int RPG = S / RG; + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } +} + +__global__ void __launch_bounds__(S) gdn_conv_l2_multi_kernel(const float* __restrict__ hist, + const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, + int C, int qk_heads, float eps, int t_begin) { + __shared__ float part[S / 32]; + const int t = t_begin + blockIdx.y; + const int c = blockIdx.x * S + threadIdx.x; + // the window of token t: [hist0, hist1, hist2, x_0, ..., x_t], its last four entries + float win[3]; +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int src = t + j; // index into [hist(3) | x...] + win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c]; + } + const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C + c]; + float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3]; + float y = sum / (1.0f + __expf(-sum)); + if ((int) blockIdx.x < qk_heads) { + float sq = y * y; + for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + y *= rsqrtf(ss + eps); + } + h[(size_t) t * C + c] = y; +} + +__global__ void gdn_conv_commit_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int C, + const int32_t* __restrict__ n_keep) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + const int n = *n_keep; + if (n <= 0) return; + float seq[3]; +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int src = n + j; // the last three of [hist(3) | x_0..x_{n-1}] + seq[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C + c]; + } + hist[c * 3] = seq[0]; + hist[c * 3 + 1] = seq[1]; + hist[c * 3 + 2] = seq[2]; +} + +__global__ void __launch_bounds__(256) gdn_ab_multi_kernel(const float* __restrict__ x, const uint16_t* __restrict__ wa, + const uint16_t* __restrict__ wb, + const float* __restrict__ dt, + const float* __restrict__ ssm_a, float* __restrict__ gate, + float* __restrict__ beta, int n, int h_v, int T) { + const int row = blockIdx.x * 8 + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (row >= 2 * h_v) return; + const bool is_beta = row >= h_v; + const int r = is_beta ? row - h_v : row; + const uint4* w4 = reinterpret_cast((is_beta ? wb : wa) + (size_t) r * n); + float acc[kVerifyMaxT]; +#pragma unroll + for (int t = 0; t < kVerifyMaxT; ++t) acc[t] = 0.0f; + for (int j = lane; j < n / 8; j += 32) { + const uint4 wv = __ldg(w4 + j); +#pragma unroll + for (int t = 0; t < kVerifyMaxT; ++t) { + if (t >= T) break; + const float* xt = x + (size_t) t * n; + const float4 xa = *reinterpret_cast(xt + j * 8); + const float4 xb = *reinterpret_cast(xt + j * 8 + 4); + float a = acc[t]; + a = fmaf(__uint_as_float(wv.x << 16), xa.x, a); a = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, a); + a = fmaf(__uint_as_float(wv.y << 16), xa.z, a); a = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, a); + a = fmaf(__uint_as_float(wv.z << 16), xb.x, a); a = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, a); + a = fmaf(__uint_as_float(wv.w << 16), xb.z, a); a = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, a); + acc[t] = a; + } + } +#pragma unroll + for (int t = 0; t < kVerifyMaxT; ++t) { + if (t >= T) break; + float a = acc[t]; + for (int o = 16; o > 0; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o); + if (lane != 0) continue; + if (is_beta) { + beta[(size_t) t * h_v + r] = 1.0f / (1.0f + __expf(-a)); + } else { + const float v = a + dt[r]; + const float sp = v > 20.0f ? v : log1pf(__expf(v)); + gate[(size_t) t * h_v + r] = sp * ssm_a[r]; + } + } +} + +__global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __restrict__ state, + const float* __restrict__ hbuf, int C, + const float* __restrict__ gate, + const float* __restrict__ beta, + const float* __restrict__ z, + const float* __restrict__ gamma, float eps, + float* __restrict__ y, int h_k, int h_v, int T, + const int32_t* __restrict__ n_keep, int t_out_begin) { + __shared__ float sk[S], sq[S]; + __shared__ float red[RG][S]; + __shared__ float wsum[S * RG / 32]; + const int head = blockIdx.x; + const int col = threadIdx.x; + const int rg = threadIdx.y; + const int tid = rg * S + col; + const int qh = head % h_k; + const int qk = S * h_k; // q at [0, qk), k at [qk, 2qk), v at [2qk, ...) + const int value_dim = S * h_v; + const int n = n_keep ? *n_keep : T; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col; + const size_t row_stride = (size_t) h_v * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride]; + for (int t = 0; t < n; ++t) { + const float* ht = hbuf + (size_t) t * C; + __syncthreads(); // the previous token is done with sk/sq/red/wsum + if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[(size_t) t * h_v + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][col] = kv; + __syncthreads(); + const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; + const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][col] = o; + __syncthreads(); + float oc = 0.0f, sq_part = 0.0f; + if (rg == 0) { + oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); + sq_part = oc * oc; + } + if (t < t_out_begin) continue; // a replayed token: its state update is needed, its output is not + for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2); + if ((tid & 31) == 0) wsum[tid >> 5] = sq_part; + __syncthreads(); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float scale = rsqrtf(ss / (float) S + eps); + const float zz = z[(size_t) t * value_dim + head * S + col]; + y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz))); + } + } + if (n_keep != nullptr && n > 0) { +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r]; + } +} + +__global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales, + const float* __restrict__ offsets, const int32_t* __restrict__ tokens, + int64_t n, int code_bits, int code_bias, int group_elems, + unsigned long long row_codes, unsigned long long row_groups, + float* __restrict__ out) { + const int t = blockIdx.y; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const unsigned long long token = (unsigned long long) tokens[t]; + const uint8_t* c = codes + token * row_codes; + const float* sc = scales + token * row_groups; + const float* of = offsets ? offsets + token * row_groups : nullptr; + const int per_byte = 8 / code_bits; + const unsigned mask = (1u << code_bits) - 1u; + const int code = (c[i / per_byte] >> ((i % per_byte) * code_bits)) & mask; + const int64_t group = i / group_elems; + const float product = __fmul_rn((float) (code + code_bias), sc[group]); + out[(size_t) t * n + i] = __fadd_rn(product, of ? of[group] : 0.0f); +} + +__global__ void broadcast_streams_kernel(const float* __restrict__ x, float* __restrict__ R, int64_t n, int hc) { + const int t = blockIdx.y; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * hc) return; + R[(size_t) t * n * hc + i] = x[(size_t) t * n + i % n]; +} + +__global__ void copy_indexed_kernel(float* __restrict__ dst, const float* __restrict__ src, int64_t stride, + const int32_t* __restrict__ index, int64_t n) { + const int idx = *index; + if (idx < 0) return; + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) + dst[i] = src[(size_t) idx * stride + i]; +} + +__global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, const int32_t* __restrict__ n, + uint4* __restrict__ dst, long long per) { + const long long total = (long long) *n * per; + for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; + i += (long long) gridDim.x * blockDim.x) { + const long long k = i / per, off = i - k * per; + dst[i] = ((const uint4*) src[k])[off]; + } +} + +__global__ void rebase_ptrs_kernel(unsigned long long* ptr, const int32_t* n, unsigned long long base, long long bytes) { + const int k = threadIdx.x; + if (k < *n) ptr[k] = base + (unsigned long long) k * (unsigned long long) bytes; +} + +__global__ void add_streams_broadcast_kernel(const float* __restrict__ h, const float* __restrict__ e, + float* __restrict__ R, int64_t n, int hc) { + const int t = blockIdx.y; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * hc) return; + R[(size_t) t * n * hc + i] = h[(size_t) t * n * hc + i] + e[(size_t) t * n + i % n]; +} + +__global__ void ident_hits_kernel(const int32_t* __restrict__ ids, int n, int32_t* __restrict__ slot, + int32_t* __restrict__ dst, int32_t* __restrict__ count) { + const int i = threadIdx.x; + if (i < n) { slot[i] = ids[i]; dst[i] = i; } + if (i == 0) *count = n; +} + +// E = the widest element the row size divides into (16, 4 or 1 bytes): a Q6_K head row of 2560 values is 2100 bytes +template +__global__ void gather_rows_kernel(const E* __restrict__ src, long long row_e, const int32_t* __restrict__ ids, + long long n, E* __restrict__ dst) { + const long long total = n * row_e; + for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < total; i += (long long) gridDim.x * blockDim.x) { + const long long r = i / row_e, o = i - r * row_e; + dst[i] = src[(long long) ids[r] * row_e + o]; + } +} + +__global__ void map_ids_kernel(int32_t* ids, const int32_t* __restrict__ table, int n) { + const int i = threadIdx.x; + if (i < n) ids[i] = table[ids[i]]; +} + +__global__ void row_top_prob_kernel(const float* __restrict__ logits, int n_vocab, const int32_t* __restrict__ ids, + float* __restrict__ probs) { + __shared__ float part[32]; + const int t = blockIdx.x; + const float* l = logits + (size_t) t * n_vocab; + const float m = l[ids[t]]; + float s = 0.0f; + for (int i = threadIdx.x; i < n_vocab; i += blockDim.x) s += __expf(l[i] - m); + for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s; + __syncthreads(); + if (threadIdx.x == 0) { + float tot = 0.0f; + for (int w = 0; w < (int) (blockDim.x >> 5); ++w) tot += part[w]; + probs[t] = 1.0f / tot; + } +} + +__global__ void mtp_select_kernel(const float* __restrict__ R_src, int64_t stride, const int32_t* __restrict__ ids, + const int32_t* __restrict__ row_dev, float* __restrict__ R_dst, + int32_t* __restrict__ tok_dst, int32_t* out, int j, const float* probs, float* out_p) { + const int row = *row_dev; + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < stride; i += (int64_t) gridDim.x * blockDim.x) + R_dst[i] = R_src[(size_t) row * stride + i]; + if (blockIdx.x == 0 && threadIdx.x == 0) { + const int32_t tok = ids[row]; + *tok_dst = tok; + if (out != nullptr) ((volatile int32_t*) out)[j] = tok; + if (probs != nullptr && out_p != nullptr) ((volatile float*) out_p)[j] = probs[row]; + } +} + +__global__ void dense_steps_kernel(const int32_t* __restrict__ cells, int n, int32_t* __restrict__ steps) { + const int i = threadIdx.x; + if (i >= n) return; + const int c = cells[i]; + steps[i * 4 + 0] = c; + steps[i * 4 + 1] = c + 1; + steps[i * 4 + 2] = (c + 1) / 4; + steps[i * 4 + 3] = c + 1; +} + +} // namespace + +void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) { + if (cap <= 0) return; + if (blob_bytes % 16 != 0) { std::fprintf(stderr, "fetch_blobs: blob size must be a multiple of 16\n"); std::exit(1); } + fetch_blobs_kernel<<<48 * 8, 256, 0, (cudaStream_t) stream>>>(src, n, (uint4*) dst, (long long) (blob_bytes / 16)); + check("fetch_blobs"); +} + +void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream) { + rebase_ptrs_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ptr, n, (unsigned long long) base, (long long) blob_bytes); + check("rebase_ptrs"); +} + +void add_streams_broadcast(const float* h, const float* e, float* R, int64_t n_embd, int hc, int n_tok, void* stream) { + add_streams_broadcast_kernel<<>>(h, e, R, n_embd, hc); + check("add_streams_broadcast"); +} + +void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* count, void* stream) { + if (n < 1 || n > 1024) { std::fprintf(stderr, "ident_hits: n out of range\n"); std::exit(1); } + ident_hits_kernel<<<1, 1024, 0, (cudaStream_t) stream>>>(ids, n, slot, dst, count); + check("ident_hits"); +} + +void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, + int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs, float* out_p) { + mtp_select_kernel<<<16, 256, 0, (cudaStream_t) stream>>>(R_src, R_stride, ids, row_dev, R_dst, tok_dst, out, j, + probs, out_p); + check("mtp_select"); +} + +void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) { + cudaStream_t s = (cudaStream_t) stream; + if (row_bytes % 16 == 0) + gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint4*) src, row_bytes / 16, ids, n, (uint4*) dst); + else if (row_bytes % 4 == 0) + gather_rows_kernel<<<48 * 8, 256, 0, s>>>((const uint32_t*) src, row_bytes / 4, ids, n, (uint32_t*) dst); + else + gather_rows_kernel<<<48 * 8, 256, 0, s>>>(src, row_bytes, ids, n, dst); + check("gather_rows"); +} + +void map_ids(int32_t* ids, const int32_t* table, int n, void* stream) { + map_ids_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(ids, table, n); + check("map_ids"); +} + +void row_top_prob(const float* logits, int n_rows, int n_vocab, const int32_t* ids, float* probs, void* stream) { + row_top_prob_kernel<<>>(logits, n_vocab, ids, probs); + check("row_top_prob"); +} + +namespace { +__global__ void window_ids_kernel(int32_t* steps, int window, int32_t* ids, long long stride) { + const int q = blockIdx.y; + int32_t* st = steps + q * 4; + const int n_kv = st[1]; + const int start = n_kv > window ? n_kv - window : 0; + const int width = n_kv - start; + for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < width; j += gridDim.x * blockDim.x) + ids[q * stride + j] = start + j; + __syncthreads(); + if (blockIdx.x == 0 && threadIdx.x == 0) st[3] = width; +} +} // namespace + +void window_ids(int32_t* steps, int n, int window, int32_t* ids, int64_t ids_stride, void* stream) { + window_ids_kernel<<>>(steps, window, ids, (long long) ids_stride); + check("window_ids"); +} + +void dense_steps(const int32_t* cells, int n, int32_t* steps, void* stream) { + dense_steps_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(cells, n, steps); + check("dense_steps"); +} + +void gdn_conv_l2_multi(const float* history, const float* qkv, const float* conv_w, float* h, int channels, + int qk_heads, float eps, int n_tok, void* stream, int t_begin) { + if (!history || !qkv || !conv_w || !h || channels % S != 0 || n_tok < 1 || n_tok > kVerifyMaxT) { + std::fprintf(stderr, "gdn_conv_l2_multi: invalid arguments\n"); + std::exit(1); + } + gdn_conv_l2_multi_kernel<<>>( + history, qkv, conv_w, h, channels, qk_heads, eps, t_begin); + check("gdn_conv_l2_multi"); +} + +void gdn_conv_commit(float* history, const float* qkv, int channels, const int32_t* n_keep, void* stream) { + gdn_conv_commit_kernel<<<(unsigned) ((channels + 255) / 256), 256, 0, (cudaStream_t) stream>>>(history, qkv, + channels, n_keep); + check("gdn_conv_commit"); +} + +void gdn_ab_multi(const float* x, const uint16_t* w_alpha, const uint16_t* w_beta, const float* dt, const float* ssm_a, + float* gate, float* beta, int n_embd, int h_v, int n_tok, void* stream) { + if (n_embd % 8 != 0 || n_tok < 1 || n_tok > kVerifyMaxT) { + std::fprintf(stderr, "gdn_ab_multi: invalid arguments\n"); + std::exit(1); + } + gdn_ab_multi_kernel<<<(unsigned) ((2 * h_v + 7) / 8), 256, 0, (cudaStream_t) stream>>>( + x, w_alpha, w_beta, dt, ssm_a, gate, beta, n_embd, h_v, n_tok); + check("gdn_ab_multi"); +} + +void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const float* gate, const float* beta, + const float* z, const float* gamma, float eps, float* y, int h_k, int h_v, int n_tok, + const int32_t* n_keep, void* stream, int t_out_begin) { + if (!state || !h || !gate || !beta || !z || !gamma || !y || h_k <= 0 || h_v % h_k || n_tok < 1 || + n_tok > kVerifyMaxT) { + std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n"); + std::exit(1); + } + gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>( + state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin); + check("gdn_step_norm_multi"); +} + +namespace { +__global__ void wait_flag_ge_kernel(const volatile uint32_t* flag, uint32_t value) { + while (*flag < value) strata_spin_pause(); + __threadfence_system(); +} +} // namespace + +namespace { +__global__ void resident_plan_kernel(const int32_t* __restrict__ ids, int n, int k, const int32_t* __restrict__ res, + int n_expert, const uint8_t* cache_base, const unsigned long long* slot_off, + long long blob, int32_t* __restrict__ pl, long long capx, uint32_t* skip, + uint32_t ring) { + // one thread: at most kVerifyMaxT * 10 entries, the host's exact loop + for (int i = 0; i < n; ++i) { + const int32_t e = ids[i]; + if (e < 0 || e >= n_expert || res[e] < 0) { *skip = 0; return; } + } + int32_t* counts = pl; + int32_t* start = pl + 4; + int32_t* dst = start + capx + 1; + int32_t* tok = dst + capx; + const long long ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll; + unsigned long long* ptr = (unsigned long long*) (pl + ptr_off); + int32_t* start2 = pl + ptr_off + 4 * capx; + int groups = 0, entries = 0; + for (int i0 = 0; i0 < n; ++i0) { + bool first = true; + for (int j = 0; j < i0; ++j) if (ids[j] == ids[i0]) { first = false; break; } + if (!first) continue; + const int32_t slot = res[ids[i0]]; + ptr[groups] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); + start[groups] = entries; + for (int i = i0; i < n; ++i) + if (ids[i] == ids[i0]) { + // an entry belongs to i0's group when its first occurrence is i0: the same expert id + dst[entries] = i; + tok[entries] = i / k; + ++entries; + } + ++groups; + } + start[groups] = entries; + start2[0] = entries; + counts[0] = groups; + counts[1] = entries; + counts[2] = 0; + __threadfence(); + *skip = ring; +} +__global__ void wait_flag_ge_or_kernel(const volatile uint32_t* flag, uint32_t value, const volatile uint32_t* skip) { + if (*skip == value) return; + while (*flag < value) strata_spin_pause(); + __threadfence_system(); +} +__global__ void copy_i32_unless_kernel(int32_t* __restrict__ dst, const volatile int32_t* src, int n, + const uint32_t* skip, uint32_t value) { + if (*skip == value) return; + for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i]; +} +__global__ void copy_or_zero_kernel(float4* __restrict__ dst, const volatile float4* src, long long n4, + const uint32_t* skip, uint32_t value) { + const bool zero = *skip == value; + for (long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x; i < n4; i += (long long) gridDim.x * blockDim.x) + dst[i] = zero ? make_float4(0.f, 0.f, 0.f, 0.f) : const_cast(src)[i]; +} +} // namespace + +void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_layer, int n_expert, + const uint8_t* cache_base, const unsigned long long* slot_off, long long blob, int32_t* plan, + long long capx, uint32_t* skip, uint32_t ring, void* stream) { + resident_plan_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, + blob, plan, capx, skip, ring); + check("resident_plan"); +} +void wait_flag_ge_or(const uint32_t* flag, uint32_t value, const uint32_t* skip, void* stream) { + wait_flag_ge_or_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, skip); + check("wait_flag_ge_or"); +} +void copy_i32_from_mapped_unless(int32_t* dst, const int32_t* src, long long n, const uint32_t* skip, uint32_t value, + void* stream) { + if (n <= 0) return; + copy_i32_unless_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n, skip, value); + check("copy_i32_from_mapped_unless"); +} +void copy_or_zero_from_mapped(float* dst, const float* src, long long n, const uint32_t* skip, uint32_t value, + void* stream) { + if (n <= 0) return; + const long long n4 = n / 4; + const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64); + copy_or_zero_kernel<<>>((float4*) dst, (const volatile float4*) src, n4, skip, + value); + check("copy_or_zero_from_mapped"); +} + +void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) { + wait_flag_ge_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value); + check("wait_flag_ge"); +} + +void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens, + int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes, + uint64_t row_groups, float* out, void* stream) { + embedding_gather_dev_kernel<<>>(codes, scales, offsets, tokens, n, code_bits, code_bias, + group_elems, row_codes, row_groups, out); + check("embedding_gather_dev"); +} + +void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream) { + broadcast_streams_kernel<<>>(x, R, n_embd, hc); + check("broadcast_streams"); +} + +void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream) { + const unsigned blocks = (unsigned) ((n + 255) / 256 < 64 ? (n + 255) / 256 : 64); + copy_indexed_kernel<<>>(dst, src, stride, index, n); + check("copy_indexed"); +} + +// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler +namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) { + unsigned long long t; +#if defined(__HIPCC__) + t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns +#else + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); +#endif + buf[i] = t; +} } +void gpu_stamp(unsigned long long* buf, int i, void* stream) { + gpu_stamp_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(buf, i); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/cvec_parity.cpp b/engine/strata/src/kernels/cvec_parity.cpp new file mode 100644 index 00000000..6176c634 --- /dev/null +++ b/engine/strata/src/kernels/cvec_parity.cpp @@ -0,0 +1,223 @@ +// src/kernels/cvec_parity.cpp - the control vector kernel (strata/kernels/cvec.hpp) against a host reference. +// 1. project: h - s (h.v) v per stream and token, against double precision; the steered component is gone. +// 2. add: h + d. +// 3. switched off: R unchanged without a pending write; with one, R is BITWISE the write the fused read folds +// (fused_gr_read with apply), which is what keeps a loaded-but-off vector identical to the stock engine. +// 4. a layer without a direction is untouched. + +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/fused_gr.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); + std::exit(2); + } +} + +template +T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T)), "malloc"); + return p; +} + +template +void up(T* d, const std::vector& h) { ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "up"); } +template +std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "down"); + return h; +} + +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +} // namespace + +int main() { + constexpr int64_t L = 48, N = 2560, HC = 4, LR = 320, T = 5, D = HC * N; + constexpr int64_t kLayer = 7, kOff = 3; // steered / not steered + std::mt19937 rng(1234); + std::normal_distribution nd(0.0f, 1.0f); + + // a unit direction at kLayer with a norm-2 scaled one's s = 2; nothing at kOff + std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); + { + double nrm = 0.0; + std::vector v((size_t) N); + for (auto& x : v) { x = nd(rng); nrm += (double) x * x; } + nrm = std::sqrt(nrm); + for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] = (float) (v[(size_t) j] / nrm); + s[(size_t) kLayer] = 2.0f; + } + std::string err; + if (!k::cvec_upload(dir, s, /*project*/ 0, 4, 44, N, HC, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } + check(k::cvec().covers(kLayer) && !k::cvec().covers(kOff) && !k::cvec().covers(45), "covers(): steered layers only"); + + std::vector R((size_t) (T * D)), bo((size_t) (T * N)), inj((size_t) (T * HC)); + for (auto& x : R) x = nd(rng) * 3.0f; + for (auto& x : bo) x = nd(rng); + for (auto& x : inj) x = nd(rng); + float* dR = dalloc(R.size()); + float* dbo = dalloc(bo.size()); + float* dinj = dalloc(inj.size()); + up(dbo, bo); + up(dinj, inj); + + // ---- 1. project, no pending write + std::printf("project\n"); + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "project"); + { + const auto got = down(dR, R.size()); + double worst = 0.0, worst_dot = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + const float* h = R.data() + t * D + c * N; + const float* v = dir.data() + kLayer * N; + double dot = 0.0; + for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; + double after = 0.0; + for (int64_t j = 0; j < N; ++j) { + const double want = h[j] - 2.0 * dot * v[j]; + const double g = got[(size_t) (t * D + c * N + j)]; + worst = std::fmax(worst, std::fabs(g - want)); + after += g * v[j]; + } + // s = 2 reflects the component: h.v -> -h.v + worst_dot = std::fmax(worst_dot, std::fabs(after + dot)); + } + std::printf(" max |err| %.3g, max |h'.v + h.v| %.3g\n", worst, worst_dot); + check(worst < 1e-4, "project matches h - s (h.v) v (s = 2)"); + check(worst_dot < 1e-3, "the component along v is reflected (s = 2)"); + } + // s = 1 removes it + s[(size_t) kLayer] = 1.0f; + if (!k::cvec_upload(dir, s, 0, 4, 44, N, HC, err)) return 2; + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "project s=1"); + { + const auto got = down(dR, R.size()); + double worst = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + double after = 0.0; + for (int64_t j = 0; j < N; ++j) after += (double) got[(size_t) (t * D + c * N + j)] * dir[(size_t) (kLayer * N + j)]; + worst = std::fmax(worst, std::fabs(after)); + } + std::printf(" max |h'.v| %.3g\n", worst); + check(worst < 1e-3, "s = 1 projects the direction out"); + } + + // ---- 4. a layer without a direction + up(dR, R); + k::cvec_apply(dR, kOff, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "off layer"); + check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "a layer without a direction is untouched"); + + // ---- 3. switched off + std::printf("switched off\n"); + k::cvec_set_enabled(false); + check(!k::cvec_enabled(), "cvec_enabled() follows the switch"); + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "off"); + check(std::memcmp(down(dR, R.size()).data(), R.data(), R.size() * 4) == 0, "off, no pending write: R unchanged"); + { + // the fused read's folded write, one token at a time, against the kernel's write-only pass + std::vector wd((size_t) (LR * D)), wu((size_t) (D * LR)), wi((size_t) (HC * D)); + std::vector wn((size_t) D); + auto bf = [&](float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) (u >> 16); }; + for (auto& x : wd) x = bf(nd(rng) * 0.02f); + for (auto& x : wu) x = bf(nd(rng) * 0.02f); + for (auto& x : wi) x = bf(nd(rng) * 0.02f); + for (auto& x : wn) x = 1.0f + 0.1f * nd(rng); + uint16_t* dwd = dalloc(wd.size()); + uint16_t* dwu = dalloc(wu.size()); + uint16_t* dwi = dalloc(wi.size()); + float* dwn = dalloc(wn.size()); + up(dwd, wd); up(dwu, wu); up(dwi, wi); up(dwn, wn); + float* lo = dalloc(LR); + float* rs = dalloc(HC); + float* inj_out = dalloc(HC); + float* mixed = dalloc(N); + float* dF = dalloc(R.size()); + up(dF, R); + for (int64_t t = 0; t < T; ++t) { + k::FusedGrArgs a; + a.R = dF + t * D; a.R_out = dF + t * D; a.apply = true; + a.bo_prev = dbo + t * N; a.inj_prev = dinj + t * HC; + a.w_norm = dwn; a.w_down = dwd; a.w_up = dwu; a.w_inject = dwi; + a.lo = lo; a.rs = rs; a.inject_out = inj_out; a.mixed = mixed; + k::fused_gr_read(a, nullptr); + } + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); + ck(cudaDeviceSynchronize(), "write only"); + const auto fused = down(dF, R.size()), mine = down(dR, R.size()); + check(std::memcmp(fused.data(), mine.data(), R.size() * 4) == 0, + "off, pending write: bitwise the fused read's folded write"); + k::cvec_set_enabled(true); + // on, with the write: the write, then the projection (reference from the fused result) + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, dbo, N, dinj, HC, true, nullptr); + ck(cudaDeviceSynchronize(), "write+project"); + const auto both = down(dR, R.size()); + double worst = 0.0; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) { + const float* h = fused.data() + t * D + c * N; + const float* v = dir.data() + kLayer * N; + double dot = 0.0; + for (int64_t j = 0; j < N; ++j) dot += (double) h[j] * v[j]; + for (int64_t j = 0; j < N; ++j) + worst = std::fmax(worst, std::fabs(both[(size_t) (t * D + c * N + j)] - (h[j] - dot * v[j]))); + } + std::printf(" write + project: max |err| %.3g\n", worst); + check(worst < 1e-4, "on, pending write: the write, then the projection"); + } + + // ---- 2. add + std::printf("add\n"); + for (int64_t j = 0; j < N; ++j) dir[(size_t) (kLayer * N + j)] *= 0.1f; // d = 0.1 v, s = 1 + s[(size_t) kLayer] = 1.0f; + if (!k::cvec_upload(dir, s, /*add*/ 1, 4, 44, N, HC, err)) return 2; + up(dR, R); + k::cvec_apply(dR, kLayer, T, D, nullptr, 0, nullptr, 0, false, nullptr); + ck(cudaDeviceSynchronize(), "add"); + { + const auto got = down(dR, R.size()); + bool same = true; + for (int64_t t = 0; t < T; ++t) + for (int64_t c = 0; c < HC; ++c) + for (int64_t j = 0; j < N; ++j) { + const size_t i = (size_t) (t * D + c * N + j); + same = same && got[i] == R[i] + dir[(size_t) (kLayer * N + j)]; + } + check(same, "add is h + d in every stream (bitwise)"); + } + + std::printf(g_fail ? "cvec_parity: %d FAILED\n" : "cvec_parity: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/kernels/dequant_bf16_test.cpp b/engine/strata/src/kernels/dequant_bf16_test.cpp new file mode 100644 index 00000000..80d3d53e --- /dev/null +++ b/engine/strata/src/kernels/dequant_bf16_test.cpp @@ -0,0 +1,108 @@ +// src/kernels/dequant_bf16_test.cpp - plan v0.3 P5: the device dequantizers against the artifact's validated CPU +// dequantizers (`strata/artifact/dequant.hpp`), on one real tensor of every type the model uses. +// +// dequant_bf16_test SHARD1.gguf [SHARD2.gguf] +// +// For each type: the first 4 rows of the first tensor of that type, FP32 path compared with a relative tolerance of +// 1e-6 (the products are the reference's, reordered at most), BF16 path within half a BF16 ulp of the CPU value. +#include "strata/artifact/dequant.hpp" +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/dequant_bf16.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +bool cpu_block(int type, const uint8_t* b, float* out) { + using namespace strata; + switch (type) { + case 2: dequantize_q4_0(b, out); return true; + case 6: dequantize_q5_0(b, out); return true; + case 8: dequantize_q8_0(b, out); return true; + case 11: dequantize_q3_K(b, out); return true; + case 12: dequantize_q4_K(b, out); return true; + case 13: dequantize_q5_K(b, out); return true; + case 14: dequantize_q6_K(b, out); return true; + case 20: dequantize_iq4_nl(b, out); return true; + case 23: dequantize_iq4_xs(b, out); return true; + case 42: dequantize_q2_0(b, out); return true; + default: return false; + } +} + +float bf16_to_f32(uint16_t h) { + uint32_t u = (uint32_t) h << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: dequant_bf16_test SHARD.gguf [SHARD2.gguf]\n"); + return 2; + } + std::map done; + int fails = 0, checked = 0; + for (int a = 1; a < argc; ++a) { + strata::GgufFile gguf(argv[a]); + for (const auto& t : gguf.tensors()) { + const int type = (int) t.type; + if (done.count(type) || !strata::kernels::dequant_bf16_supported(type) || t.shape.size() != 2) continue; + int be = 0, bb = 0; + if (!strata::block_geometry(t.type, be, bb)) continue; + const int64_t cols = (int64_t) t.shape[0]; + const int64_t rows = (std::min)(4, (int64_t) t.shape[1]); + const int64_t row_bytes = cols / be * bb; + const uint8_t* host = (const uint8_t*) gguf.tensor_data(t); + void* d_blocks = nullptr; + float* d_f = nullptr; + uint16_t* d_h = nullptr; + cudaMalloc(&d_blocks, (size_t) (rows * row_bytes)); + cudaMalloc(&d_f, (size_t) (rows * cols) * 4); + cudaMalloc(&d_h, (size_t) (rows * cols) * 2); + cudaMemcpy(d_blocks, host, (size_t) (rows * row_bytes), cudaMemcpyHostToDevice); + strata::kernels::dequant_f32(type, d_blocks, 0, rows, cols, d_f, nullptr); + strata::kernels::dequant_bf16(type, d_blocks, 0, rows, cols, d_h, nullptr); + std::vector gf((size_t) (rows * cols)); + std::vector gh((size_t) (rows * cols)); + cudaMemcpy(gf.data(), d_f, gf.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(gh.data(), d_h, gh.size() * 2, cudaMemcpyDeviceToHost); + cudaFree(d_blocks); + cudaFree(d_f); + cudaFree(d_h); + std::vector ref((size_t) (rows * cols)); + for (int64_t r = 0; r < rows; ++r) + for (int64_t b = 0; b < cols / be; ++b) + cpu_block(type, host + r * row_bytes + b * bb, ref.data() + r * cols + b * be); + int64_t bad_f = 0, bad_h = 0; + double worst = 0; + for (size_t i = 0; i < ref.size(); ++i) { + const double e = std::fabs((double) gf[i] - ref[i]); + const double tol = 1e-6 * std::fabs((double) ref[i]) + 1e-30; + if (e > tol) ++bad_f; + worst = (std::max)(worst, e / (std::fabs((double) ref[i]) + 1e-30)); + const double eh = std::fabs((double) bf16_to_f32(gh[i]) - ref[i]); + if (eh > std::ldexp(std::fabs((double) ref[i]), -8) + 1e-30) ++bad_h; + } + ++checked; + done[type] = true; + const bool ok = bad_f == 0 && bad_h == 0; + if (!ok) ++fails; + std::printf("type %2d %-40s %lld x %lld: f32 %s (%lld off, worst rel %.2e), bf16 %s (%lld off)\n", type, + t.name.c_str(), (long long) rows, (long long) cols, bad_f ? "FAIL" : "ok", (long long) bad_f, + worst, bad_h ? "FAIL" : "ok", (long long) bad_h); + } + } + std::printf("dequant_bf16_test: %d types checked, %s\n", checked, fails ? "FAILED" : "OK"); + return fails ? 1 : 0; +} diff --git a/engine/strata/src/kernels/dequant_s2_parity.cpp b/engine/strata/src/kernels/dequant_s2_parity.cpp new file mode 100644 index 00000000..58e39705 --- /dev/null +++ b/engine/strata/src/kernels/dequant_s2_parity.cpp @@ -0,0 +1,143 @@ +// src/kernels/dequant_s2_parity.cpp - P2.S2's parity test for the S2 decode. +// +// THE REFERENCE IS THE CHAIN, NOT A SECOND OPINION. `strata::dequantize_q2_0` (include/strata/artifact/ +// dequant.hpp) is a scalar transcription that `bench/micro/dequant_xcheck` checks against **ggml's own** +// dequantizer on real block bytes; and `tools/canonical_xcheck.py --full` checks that the canonical form +// decodes to the same values on every block of the artifact. So this compares "GPU canonical decode" against +// "CPU decode already proven equal to ggml", and a fault in either the canonicaliser or the kernel shows up +// here. A parity test whose two sides were written together would show neither. +#include "strata/artifact/dequant.hpp" +#include "strata/kernels/dequant_s2.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace { + +constexpr int QK = 64; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// fp16 patterns that are finite, normal and exactly representable. Random 16-bit patterns would include NaN +// and infinity, and a NaN makes `!=` true for a reason that has nothing to do with the kernel - the test +// would fail for the wrong cause, or worse, a real fault would hide behind a NaN it caused itself. +const uint16_t kScales[] = {0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000, + 0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400}; + +} // namespace + +int main(int argc, char** argv) { + long long n_blocks = 200000; + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; + else if (std::strcmp(argv[i], "--blocks") == 0 && i + 1 < argc) n_blocks = std::atoll(argv[++i]); + else { + std::fprintf(stderr, "usage: dequant_s2_parity [--selftest] [--blocks N]\n"); + return 2; + } + } + if (n_blocks <= 0) { std::fprintf(stderr, "--blocks must be positive\n"); return 2; } + + std::mt19937 rng(12345); + const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); + + // raw Q2_0 blocks: { fp16 d ; uint8 qs[16] } - what ggml produced and what the artifact stores + std::vector raw((size_t) n_blocks * 18); + for (long long b = 0; b < n_blocks; ++b) { + const uint16_t d = kScales[rng() % n_scales]; + raw[(size_t) b * 18 + 0] = (uint8_t) (d & 0xFF); + raw[(size_t) b * 18 + 1] = (uint8_t) (d >> 8); + for (int t = 0; t < 16; ++t) raw[(size_t) b * 18 + 2 + t] = (uint8_t) (rng() & 0xFF); + } + + // the CPU reference, over the RAW blocks + std::vector cpu((size_t) n_blocks * QK); + for (long long b = 0; b < n_blocks; ++b) { + strata::dequantize_q2_0(&raw[(size_t) b * 18], &cpu[(size_t) b * QK]); + } + + // canonical planes: S2 packs 4 codes per byte exactly as Q2_0 stores them, so the codes plane is the raw + // qs bytes; the scales plane is the fp16 `d` widened. Copied into planes of their own rather than + // aliased, because that is what the kernel will read in the engine. + std::vector codes((size_t) n_blocks * 16); + std::vector scales((size_t) n_blocks); + for (long long b = 0; b < n_blocks; ++b) { + std::memcpy(&codes[(size_t) b * 16], &raw[(size_t) b * 18 + 2], 16); + const uint16_t d = (uint16_t) (raw[(size_t) b * 18] | (raw[(size_t) b * 18 + 1] << 8)); + scales[(size_t) b] = strata::fp16_to_fp32(d); + } + + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_out = nullptr; + check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_out, cpu.size() * sizeof(float)), "cudaMalloc out"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), + "copy scales"); + + strata::kernels::dequant_s2(d_codes, d_scales, d_out, n_blocks); + + std::vector gpu(cpu.size()); + check(cudaMemcpy(gpu.data(), d_out, gpu.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); + + long long bad = 0, first_bad = -1; + for (size_t i = 0; i < cpu.size(); ++i) { + // bit comparison, not a tolerance: S2's decode is exact integer-to-float arithmetic, so ANY + // difference is a bug and a tolerance would only hide which one + if (std::memcmp(&cpu[i], &gpu[i], sizeof(float)) != 0) { + if (first_bad < 0) first_bad = (long long) i; + ++bad; + } + } + + // NON-VACUITY. Two buffers of zeros compare equal, and so do two buffers a broken test filled with the + // same constant - an agreement check that cannot distinguish "both correct" from "both empty" is the + // failure this project keeps finding. So the data must actually vary, and the four codes must all occur: + // an S2 decode that only ever saw one code would agree while being unable to tell -1 from +2. + bool seen[4] = {false, false, false, false}; + for (size_t i = 0; i < codes.size(); ++i) { + for (int t = 0; t < 4; ++t) seen[(codes[i] >> (2 * t)) & 3] = true; + } + int distinct = 0; + for (bool s : seen) distinct += s ? 1 : 0; + long long distinct_vals = 0; + for (size_t i = 0; i < cpu.size() && distinct_vals < 8; ++i) { + bool dup = false; + for (size_t j = 0; j < i && !dup; ++j) dup = (cpu[j] == cpu[i]); + if (!dup) ++distinct_vals; + } + std::printf(" non-vacuity: %d of 4 codes present, %lld distinct values in the first elements\n", distinct, + distinct_vals); + if (distinct != 4 || distinct_vals < 4) { + std::fprintf(stderr, "VACUOUS: the comparison could not have distinguished a wrong decode\n"); + return 1; + } + + std::printf("dequant_s2: %lld blocks, %lld elements, %lld mismatched\n", n_blocks, (long long) cpu.size(), + bad); + if (bad) { + std::printf(" first mismatch at element %lld (block %lld, offset %d): cpu %.9g gpu %.9g\n", + (long long) first_bad, (long long) (first_bad / QK), (int) (first_bad % QK), + (double) cpu[(size_t) first_bad], (double) gpu[(size_t) first_bad]); + return 1; + } + std::printf(" bit-exact against the scalar dequantizer that dequant_xcheck proved equal to ggml\n"); + if (selftest) std::printf("dequant_s2_parity OK\n"); + + cudaFree(d_codes); + cudaFree(d_scales); + cudaFree(d_out); + return 0; +} diff --git a/engine/strata/src/kernels/elementwise_parity.cpp b/engine/strata/src/kernels/elementwise_parity.cpp new file mode 100644 index 00000000..9a8fc3f3 --- /dev/null +++ b/engine/strata/src/kernels/elementwise_parity.cpp @@ -0,0 +1,475 @@ +// src/kernels/elementwise_parity.cpp - P2.S5's test for the layer glue. +// +// The ops are small; the CONVENTIONS in them are not, and each one is a place where a plausible reading +// gives a plausible number: +// +// 1. `softplus` HAS A LARGE-x BRANCH. `log1p(exp(x))` overflows f32 at x > 88 and loses relative precision +// well before that; `ggml_compute_softplus_f32` returns `x` above 20. A rival without the branch is +// asserted observable, because a gate that saturates to +inf makes `exp(gate)` inf and the whole +// recurrence NaN - which reads as a state bug and not as a missing branch. +// 2. `ssm_a` IS NEGATIVE. `gate = softplus(...) * ssm_a`, so `exp(gate) < 1` and the state DECAYS. A +// fixture with a positive `ssm_a` would still produce finite output and the recurrence would blow up +// instead of decaying, so the sign is checked as a property and not assumed. +// 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the +// last bits, and the test measures that rather than asserting it away. +#include "strata/kernels/dequant_bf16.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +double rel_l1(const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: elementwise_parity [--selftest]\n"); return 2; } + } + int bad = 0; + const int64_t H_V = 48; + + // ---- 1. gdn_gate, with the reference's own softplus + { + const int n = (int) H_V; + std::mt19937 rng(11); + std::normal_distribution g(0.0f, 1.0f); + std::vector alpha(n), dt(n), a(n), want(n); + for (int i = 0; i < n; ++i) { + // A MIXTURE THAT ACTUALLY CROSSES THE BRANCH. The first version drew alpha from a normal with + // sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the + // "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture + // saying it cannot see the thing it was written to see. Every third head is now large. + const bool large = (i % 3) == 0; + // Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88. A fixture that stopped + // at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to + // f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the + // behaviour only actually changes where `expf` overflows. + alpha[i] = large ? (22.0f + 6.0f * (float) (i % 17)) : g(rng) * 3.0f; + dt[i] = g(rng) * 0.5f; + // NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is. Checked below as a property. + a[i] = -(std::fabs(g(rng)) + 0.1f); + const double x = (double) alpha[i] + (double) dt[i]; + const double sp = x > 20.0 ? x : std::log1p(std::exp(x)); + want[(size_t) i] = (float) (sp * (double) a[i]); + } + // the fixture must EXERCISE the branch, or check 1 below measures nothing + { + int over = 0, past_overflow = 0; + for (int i = 0; i < n; ++i) { + const float x = alpha[(size_t) i] + dt[(size_t) i]; + if (x > 20.0f) ++over; + if (x > 88.0f) ++past_overflow; + } + std::printf(" %-44s %s (%d above 20, %d above 88)\n", "the fixture crosses the branch", + over ? "yes" : "*** NO ***", over, past_overflow); + if (!over) ++bad; + } + // the sign property, asserted rather than assumed + int positive = 0; + for (int i = 0; i < n; ++i) if (a[(size_t) i] >= 0.0f) ++positive; + std::printf(" %-44s %s (%d of %d non-negative)\n", "the fixture's ssm_a is negative", + positive ? "*** NO ***" : "yes", positive, n); + if (positive) ++bad; + + float *d_a = nullptr, *d_dt = nullptr, *d_sa = nullptr, *d_g = nullptr; + check(cudaMalloc(&d_a, n * 4), "a"); + check(cudaMalloc(&d_dt, n * 4), "dt"); + check(cudaMalloc(&d_sa, n * 4), "sa"); + check(cudaMalloc(&d_g, n * 4), "g"); + check(cudaMemcpy(d_a, alpha.data(), n * 4, cudaMemcpyHostToDevice), "ca"); + check(cudaMemcpy(d_dt, dt.data(), n * 4, cudaMemcpyHostToDevice), "cd"); + check(cudaMemcpy(d_sa, a.data(), n * 4, cudaMemcpyHostToDevice), "cs"); + strata::kernels::gdn_gate(d_a, d_dt, d_sa, d_g, 1, H_V, nullptr); + std::vector got((size_t) n); + check(cudaMemcpy(got.data(), d_g, n * 4, cudaMemcpyDeviceToHost), "cg"); + + const double rel = rel_l1(want, got); + std::printf(" %-44s rel %.3e\n", "gdn_gate vs the reference", rel); + // double softplus and double multiply on both sides, then one cast + if (!(rel <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++bad; } + + // TRAP: no large-x branch. `log1p(exp(x))` in f32, with no `x > 20` path. + // + // AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS. The first version of this fixture + // spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision + // over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only + // where `expf` OVERFLOWS, at about 88. The check reports the smallest x at which the two readings + // part company, so the number is in the output rather than in this comment. + { + int wrong = 0, differing = 0; + float first_differ = -1.0f; + std::vector rival((size_t) n); + for (int i = 0; i < n; ++i) { + const float x = alpha[(size_t) i] + dt[(size_t) i]; + const float sp = std::log1p(std::exp(x)); // no branch, f32 + rival[(size_t) i] = sp * a[(size_t) i]; + if (!std::isfinite(sp)) ++wrong; + const float branched = x > 20.0f ? x : std::log1pf(std::exp(x)); + if (sp != branched) { + ++differing; + if (first_differ < 0.0f || x < first_differ) first_differ = x; + } + } + const double r = rel_l1(want, rival); + const bool visible = r > 0.05 || wrong > 0; + std::printf(" %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n", + "the softplus large-x branch is observable", visible ? "yes" : "*** NO ***", + r * 100, wrong, differing, (double) first_differ); + if (!visible) ++bad; + } + // PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay + { + int over = 0; + for (float v : got) if (!(std::exp(v) < 1.0f)) ++over; + std::printf(" %-44s %s (%d of %d not < 1)\n", "exp(gate) < 1 for every head", + over ? "*** NO ***" : "yes", over, n); + if (over) ++bad; + } + cudaFree(d_a); cudaFree(d_dt); cudaFree(d_sa); cudaFree(d_g); + } + + // ---- 2. silu, in double then cast + { + const int n = 4096; + std::mt19937 rng(22); + std::normal_distribution g(0.0f, 3.0f); + std::vector x((size_t) n), want((size_t) n); + for (int i = 0; i < n; ++i) { + x[(size_t) i] = g(rng); + const double v = (double) x[(size_t) i]; + want[(size_t) i] = (float) (v / (1.0 + std::exp(-v))); + } + float* d_x = nullptr; + check(cudaMalloc(&d_x, n * 4), "sx"); + check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "csx"); + strata::kernels::silu_inplace(d_x, n, nullptr); + std::vector got((size_t) n); + check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "csg"); + const double rel = rel_l1(want, got); + std::printf("\n %-44s rel %.3e\n", "silu (double) vs the reference", rel); + if (!(rel <= 1e-7)) { std::printf(" *** over 1e-7 ***\n"); ++bad; } + cudaFree(d_x); + } + + // ---- 3. scale and the f32->f16 bridge + { + const int n = 1024; + std::vector x((size_t) n), want((size_t) n); + for (int i = 0; i < n; ++i) x[(size_t) i] = (float) (i - n / 2) * 0.013f; + const float s = 1.0f / std::sqrt(128.0f); + for (int i = 0; i < n; ++i) want[(size_t) i] = x[(size_t) i] * s; + + float* d_x = nullptr; + uint16_t* d_h = nullptr; + check(cudaMalloc(&d_x, n * 4), "ex"); + check(cudaMalloc(&d_h, n * 2), "eh"); + check(cudaMemcpy(d_x, x.data(), n * 4, cudaMemcpyHostToDevice), "cex"); + strata::kernels::scale_inplace(d_x, n, s, nullptr); + std::vector got((size_t) n); + check(cudaMemcpy(got.data(), d_x, n * 4, cudaMemcpyDeviceToHost), "ceg"); + int diff = 0; + for (int i = 0; i < n; ++i) if (got[(size_t) i] != want[(size_t) i]) ++diff; + std::printf(" %-44s %d of %d differ\n", "scale_inplace is exact", diff, n); + if (diff) ++bad; + + strata::kernels::f32_to_f16_bulk(d_x, d_h, n, nullptr); + std::vector h((size_t) n); + check(cudaMemcpy(h.data(), d_h, n * 2, cudaMemcpyDeviceToHost), "ceh"); + int hbad = 0; + for (int i = 0; i < n; ++i) + if (h[(size_t) i] != strata::kernels::f16_from_f32(got[(size_t) i])) ++hbad; + std::printf(" %-44s %d of %d differ\n", "f32_to_f16_bulk uses the shared conversion", hbad, n); + if (hbad) ++bad; + cudaFree(d_x); cudaFree(d_h); + } + + // ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from. + // + // This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by + // one `/ cols`, and that a swap produces a well-scaled, plausible tensor. So the test computes BOTH wrong + // readings and requires each to differ from the right one by more than the tolerance before it judges the + // kernel - the same discipline the shared-expert test uses for silu-on-gate. + { + const int64_t rows = 24, cols = 256; // the real `attn_q`-norm shape + const float eps = 1e-6f; + std::vector x((size_t) (rows * cols)); + for (size_t i = 0; i < x.size(); ++i) x[i] = (float) std::sin((double) i * 0.017) * 1.7f + 0.4f; + std::vector w((size_t) cols); + for (int64_t c = 0; c < cols; ++c) w[(size_t) c] = 0.5f + 0.002f * (float) (c % 97); + + // the oracle: f64, mean, times w + auto ref = [&](bool use_sum, bool use_w) { + std::vector y((size_t) (rows * cols)); + for (int64_t r = 0; r < rows; ++r) { + double ss = 0; + for (int64_t c = 0; c < cols; ++c) { + const double v = x[(size_t) (r * cols + c)]; + ss += v * v; + } + const double den = std::sqrt((use_sum ? ss : ss / (double) cols) + (double) eps); + for (int64_t c = 0; c < cols; ++c) { + const double v = x[(size_t) (r * cols + c)]; + y[(size_t) (r * cols + c)] = (v / den) * (use_w ? (double) w[(size_t) c] : 1.0); + } + } + std::vector out((size_t) (rows * cols)); + for (size_t i = 0; i < out.size(); ++i) out[i] = (float) y[i]; + return out; + }; + const std::vector want = ref(false, true); + const std::vector rival_sum = ref(true, false); // what gdn_l2_norm computes + const std::vector rival_now = ref(false, false); // the (1+w)-vs-w / no-weight confusion + + auto rel = [&](const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); + }; + const double r_sum = rel(want, rival_sum), r_now = rel(want, rival_now); + std::printf(" %-44s %.2f%% apart\n", "sum-vs-mean is observable", r_sum * 100); + std::printf(" %-44s %.2f%% apart\n", "with-w-vs-without-w is observable", r_now * 100); + // `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot + // separate them is not testing the kernel that was written. + if (!(r_sum > 0.5)) { std::printf(" *** the sum reading is NOT observable ***\n"); ++bad; } + if (!(r_now > 0.5)) { std::printf(" *** the no-weight reading is NOT observable ***\n"); ++bad; } + + float* d_x = nullptr; + float* d_w = nullptr; + check(cudaMalloc(&d_x, x.size() * 4), "m rmsx"); + check(cudaMalloc(&d_w, w.size() * 4), "m rmsw"); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx"); + check(cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice), "c rmsw"); + strata::kernels::rms_norm_weighted(d_x, d_w, rows, cols, eps, nullptr); + std::vector got((size_t) (rows * cols)); + check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsg"); + + const double r_got = rel(want, got); + double worst = 0; + for (size_t i = 0; i < got.size(); ++i) { + const double m = std::fabs((double) want[i]); + const double e = std::fabs((double) got[i] - (double) want[i]) / (m > 1e-30 ? m : 1e-30); + if (e > worst) worst = e; + } + int nonfinite = 0; + for (float v : got) if (!std::isfinite(v)) ++nonfinite; + std::printf(" %-44s rel %.3e worst %.3e nonfinite %d\n", "rms_norm_weighted vs f64 oracle", r_got, + worst, nonfinite); + if (nonfinite) ++bad; + // The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the + // 16x the rival readings are off by. + if (!(r_got < 1e-6)) { std::printf(" *** rms_norm_weighted is WRONG ***\n"); ++bad; } + // and a null `w` must be legal, because `ref/qsa.py` allows it. + // + // THE INPUT HAS TO BE RE-UPLOADED FIRST. The kernel is IN PLACE, so `d_x` currently holds the + // NORMALISED tensor from the call above; running it again normalises a second time and every element + // differs. That is exactly what the first version of this check reported - "6144 of 6144 differ" - + // and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two + // sides were never looking at the same input. + const std::vector want_null = ref(false, false); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "c rmsx2"); + strata::kernels::rms_norm_weighted(d_x, nullptr, rows, cols, eps, nullptr); + check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "c rmsn"); + int null_bad = 0; + for (size_t i = 0; i < got.size(); ++i) + if (std::fabs((double) got[i] - (double) want_null[i]) > 1e-6) ++null_bad; + std::printf(" %-44s %d of %zu differ\n", "a null weight is legal", null_bad, got.size()); + if (null_bad) ++bad; + cudaFree(d_x); + cudaFree(d_w); + } + + // Packed embedding rows: every code width, scale-group size, optional offset, + // row boundary and partial CUDA block. Compare bits with a scalar CPU decoder. + // Volatile materializes the multiply so this oracle cannot silently use FMA. + { + cudaStream_t stream; + check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "embedding stream"); + std::mt19937 rng(77); + std::uniform_real_distribution values(-2.0f, 2.0f); + int mismatches = 0, guards = 0, fma_diff = 0, cases = 0; + for (const int bits : {2, 4, 8}) { + const int bias = bits == 2 ? -1 : bits == 4 ? -7 : -16; + const int per_byte = 8 / bits; + const unsigned mask = (1u << bits) - 1u; + for (const int group : {16, 32, 64}) { + for (const int n : {320, 2560}) { + const int row_bytes = n / per_byte, row_groups = n / group; + std::vector codes((size_t) 3 * row_bytes, 0); + std::vector scales((size_t) 3 * row_groups), offsets(scales.size()); + std::vector unpacked((size_t) 3 * n); + for (size_t i = 0; i < unpacked.size(); ++i) { + const unsigned code = (unsigned) (i * 13 + i / n * 7) & mask; + unpacked[i] = (int) code; + codes[i / per_byte] |= (uint8_t) (code << ((i % per_byte) * bits)); + } + for (size_t i = 0; i < scales.size(); ++i) { + scales[i] = values(rng); + offsets[i] = values(rng); + } + scales[0] = -0.0f; + offsets[0] = 0.0f; + uint8_t* dc = nullptr; + float *ds = nullptr, *dof = nullptr, *out = nullptr; + check(cudaMalloc(&dc, codes.size()), "embedding codes"); + check(cudaMalloc(&ds, scales.size() * sizeof(float)), "embedding scales"); + check(cudaMalloc(&dof, offsets.size() * sizeof(float)), "embedding offsets"); + check(cudaMalloc(&out, ((size_t) n + 2) * sizeof(float)), "embedding output"); + check(cudaMemcpyAsync(dc, codes.data(), codes.size(), cudaMemcpyHostToDevice, stream), "embedding codes upload"); + check(cudaMemcpyAsync(ds, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding scales upload"); + check(cudaMemcpyAsync(dof, offsets.data(), offsets.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding offsets upload"); + check(cudaStreamSynchronize(stream), "embedding upload sync"); + + for (const bool with_offset : {false, true}) { + for (int row = 0; row < 3; ++row) { + std::vector want((size_t) n), got((size_t) n + 2, -12345.0f); + for (int i = 0; i < n; ++i) { + const size_t gi = (size_t) row * row_groups + i / group; + const float code = (float) (unpacked[(size_t) row * n + i] + bias); + volatile float product = code * scales[gi]; + const float offset = with_offset ? offsets[gi] : 0.0f; + want[(size_t) i] = product + offset; + const float fused = std::fma(code, scales[gi], offset); + if (std::memcmp(&fused, &want[(size_t) i], sizeof(float)) != 0) ++fma_diff; + } + check(cudaMemcpyAsync(out, got.data(), got.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "embedding output guards"); + strata::kernels::embedding_gather(dc + (size_t) row * row_bytes, + ds + (size_t) row * row_groups, + with_offset ? dof + (size_t) row * row_groups : nullptr, + n, bits, bias, group, out + 1, stream); + check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding result"); + check(cudaStreamSynchronize(stream), "embedding sync"); + for (int i = 0; i < n; ++i) { + if (std::memcmp(&want[(size_t) i], &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches; + } + if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards; + ++cases; + + // Capturing the gather proves that it has no hidden synchronization. + // A following scale also checks that it uses the caller's stream. + if (row == 1) { + cudaGraph_t graph; + cudaGraphExec_t exec; + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "embedding capture"); + strata::kernels::embedding_gather(dc + (size_t) row * row_bytes, + ds + (size_t) row * row_groups, + with_offset ? dof + (size_t) row * row_groups : nullptr, + n, bits, bias, group, out + 1, stream); + strata::kernels::scale_inplace(out + 1, n, 2.0f, stream); + check(cudaStreamEndCapture(stream, &graph), "embedding capture end"); + check(cudaGraphInstantiate(&exec, graph, 0), "embedding instantiate"); + check(cudaGraphLaunch(exec, stream), "embedding replay"); + check(cudaMemcpyAsync(got.data(), out, got.size() * sizeof(float), cudaMemcpyDeviceToHost, stream), "embedding graph result"); + check(cudaStreamSynchronize(stream), "embedding graph sync"); + for (int i = 0; i < n; ++i) { + const float expected = want[(size_t) i] * 2.0f; + if (std::memcmp(&expected, &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches; + } + if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards; + check(cudaGraphExecDestroy(exec), "embedding exec destroy"); + check(cudaGraphDestroy(graph), "embedding graph destroy"); + } + } + } + cudaFree(dc); cudaFree(ds); cudaFree(dof); cudaFree(out); + } + } + } + check(cudaStreamDestroy(stream), "embedding stream destroy"); + std::printf(" embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n", + cases, mismatches, guards, fma_diff); + if (mismatches || guards || fma_diff == 0) ++bad; + } + + // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32` + // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule; + // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on + // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu. + { + auto ggml_bf16 = [](uint32_t u) -> uint16_t { + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64); + return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16); + }; + std::vector bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu, + 0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u, + 0x3F818000u, 0x00008000u, 0x7F7F8000u}; + std::mt19937 rng(13); + while (bits.size() < 4096) bits.push_back((uint32_t) rng()); + const size_t n = bits.size(); + float* dx = nullptr; + uint16_t* dy = nullptr; + check(cudaMalloc(&dx, n * 4), "bf16 x"); + check(cudaMalloc(&dy, n * 2), "bf16 y"); + check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx"); + strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr); + std::vector got(n); + check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy"); + int wrong = 0; + for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]); + + // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must + // still be one in BF16. A second block with an ordinary scale checks the finite path did not move. + std::vector blk(2 * 34, 0); + blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN + blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0 + for (int j = 0; j < 32; ++j) { + blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16); + blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50); + } + uint8_t* db = nullptr; + uint16_t* dq = nullptr; + check(cudaMalloc(&db, blk.size()), "q8 blk"); + check(cudaMalloc(&dq, 64 * 2), "q8 out"); + check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk"); + strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr); + check(cudaDeviceSynchronize(), "dequant_bf16"); + std::vector q(64); + check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout"); + int dq_wrong = 0; + for (int j = 0; j < 32; ++j) { + if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN + const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer + uint32_t vb; + std::memcpy(&vb, &v, 4); + if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong; + } + std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n", + wrong, n, dq_wrong); + if (wrong || dq_wrong) ++bad; + cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq); + } + + std::printf("\nelementwise: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("elementwise_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/gdn_parity.cpp b/engine/strata/src/kernels/gdn_parity.cpp new file mode 100644 index 00000000..8d6a3997 --- /dev/null +++ b/engine/strata/src/kernels/gdn_parity.cpp @@ -0,0 +1,397 @@ +// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms. +// +// `ref/gdn.py` carries eleven PROPERTY checks, several of which exist because a rival reading of the SOURCE +// produces well-formed output. The four that the kernels here can be wrong about are re-pinned below, each +// asserted OBSERVABLE against a deliberately-wrong computation before the kernel is judged: +// +// 1. MODULO head pairing, h % h_k, not INTERLEAVE. With H_k=2 and H_v=4 the two give [0,1,0,1] and +// [0,0,1,1]: they differ at h=1 and h=2. Both produce a full-rank state of the right shape. +// 2. Decay applied BEFORE the rank-1 update. Applying it after is a one-line move that keeps every shape +// and every magnitude. +// 3. The conv's SLIDE DIRECTION. `kernel[0]` must read the OLDEST state row and the new input must land in +// the LAST state row; reversing either is invisible on a symmetric state, so the state rows here are +// labelled so each position is identifiable. +// 4. `l2_norm`'s `+ eps` is an absolute floor on the SQUARED NORM, not on the mean. The mean reading +// differs by sqrt(S) = 11.3x at S = 128. `ref/gdn.py` PROPERTY 1 instruments the derivation, so it is +// not taken on trust there either. +// +// It also checks the STATE LAYOUT, which is the one place these kernels intentionally differ from the +// reference: (S, h_v, S) with j fastest instead of (S, S, h_v). A layout mix-up is silent, so the state is +// filled with a value that encodes its own coordinates. +#include "strata/kernels/gdn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +float sigmoid_f(float x) { return 1.0f / (1.0f + std::exp(-x)); } + +/// The reference's `gdn_step`, with switches for the rival readings. +/// +/// `state` is passed in the REFERENCE layout (S, S, h_v) - i.e. (i, j, h) - so that this function is a +/// transcription of `ref/gdn.py` and not of the kernel. +void ref_step(std::vector& state, const std::vector& q, const std::vector& k, + const std::vector& v, const std::vector& gate, const std::vector& beta, + int S, int h_k, int h_v, std::vector& o, bool modulo_heads, bool decay_first) { + auto at = [&](int i, int j, int h) -> double& { return state[(size_t) (i * S + j) * h_v + h]; }; + std::vector oo((size_t) h_v * S, 0.0f); + for (int h = 0; h < h_v; ++h) { + const int src = modulo_heads ? (h % h_k) : (h / (h_v / h_k)); + const double dec = std::exp((double) gate[(size_t) h]); + const double b = (double) beta[(size_t) h]; + for (int j = 0; j < S; ++j) { + if (decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec; + double sk = 0; + for (int i = 0; i < S; ++i) sk += at(i, j, h) * (double) k[(size_t) (src * S + i)]; + const double d = ((double) v[(size_t) (h * S + j)] - sk) * b; + for (int i = 0; i < S; ++i) at(i, j, h) += (double) k[(size_t) (src * S + i)] * d; + if (!decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec; + double dot = 0; + for (int i = 0; i < S; ++i) dot += at(i, j, h) * (double) q[(size_t) (src * S + i)]; + oo[(size_t) (h * S + j)] = (float) dot; + } + } + o = oo; +} + +/// `ref/gdn.py::conv_step` in its own (d_conv, C) row-major orientation. +void ref_conv(std::vector& cs, const std::vector& x, const std::vector& kern, int C, + int dc, std::vector& out) { + out.assign((size_t) C, 0.0f); + for (int c = 0; c < C; ++c) { + double acc = 0; + for (int i = 0; i < dc - 1; ++i) acc += (double) cs[(size_t) (i * C + c)] * (double) kern[(size_t) (i * C + c)]; + acc += (double) x[(size_t) c] * (double) kern[(size_t) ((dc - 1) * C + c)]; + out[(size_t) c] = (float) acc; + for (int i = 0; i < dc - 2; ++i) cs[(size_t) (i * C + c)] = cs[(size_t) ((i + 1) * C + c)]; + cs[(size_t) ((dc - 2) * C + c)] = x[(size_t) c]; + } +} + +double rel_l1(const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: gdn_parity [--selftest]\n"); return 2; } + } + + const int S = 128, h_k = 16, h_v = 48; // the artifact's real geometry + std::mt19937 rng(2024); + std::normal_distribution gauss(0.0f, 1.0f); + int bad = 0; + + // ================= 1. the recurrence ================= + { + // The state encodes its own coordinates, so a layout mix-up cannot pass: reading (i,j,h) where the + // buffer holds (i,h,j) gives a DIFFERENT number, not a wrong-but-plausible one. + std::vector st_ref((size_t) S * S * h_v); + std::vector st_dev((size_t) S * h_v * S); + for (int i = 0; i < S; ++i) + for (int j = 0; j < S; ++j) + for (int h = 0; h < h_v; ++h) { + const float val = (float) (0.001 * (i + 2 * j + 3 * h) - 1.0); + st_ref[(size_t) (i * S + j) * h_v + h] = val; + st_dev[(size_t) (i * h_v + h) * S + j] = val; // (S, h_v, S), j fastest + } + + std::vector q((size_t) h_k * S), k((size_t) h_k * S), v((size_t) h_v * S), gate((size_t) h_v), + beta((size_t) h_v); + for (auto& x : q) x = gauss(rng) * 0.1f; + for (auto& x : k) x = gauss(rng) * 0.1f; + for (auto& x : v) x = gauss(rng); + for (auto& x : gate) x = -(2.0f + 4.0f * (float) (rng() % 100) / 100.0f); // dec in (0.0025, 0.135] + for (auto& x : beta) x = (float) (rng() % 100) / 100.0f; + + std::vector want_o; + std::vector st_mod = st_ref; + ref_step(st_mod, q, k, v, gate, beta, S, h_k, h_v, want_o, true, true); + + // the traps + { + std::vector a = st_ref; + std::vector oo; + ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, false, true); + const double rel = rel_l1(want_o, oo); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "modulo vs interleave head pairing", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + if (!(rel > 0.05)) ++bad; + } + { + std::vector a = st_ref; + std::vector oo; + ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, true, false); + const double rel = rel_l1(want_o, oo); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "decay before vs after the update", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + // The two readings differ by exactly `k (x) (beta * v * (1 - dec))`, so the fixture is only able + // to see the trap when `dec` is far from 1 and `beta` is far from 0. The first version used + // gate in [-0.99, 0] - dec in [0.37, 1] - and managed 3.25%, which is a threshold the wrong + // reading nearly clears. Deep decay is also the realistic regime: `ssm_a = -exp(A_log) < 0` and + // softplus is positive, so gate is comfortably negative in the real model. + if (!(rel > 0.05)) ++bad; + } + + // the kernel + float *d_st = nullptr, *d_q = nullptr, *d_k = nullptr, *d_v = nullptr, *d_g = nullptr, *d_b = nullptr, + *d_o = nullptr; + check(cudaMalloc(&d_st, st_dev.size() * 4), "st"); + check(cudaMalloc(&d_q, q.size() * 4), "q"); + check(cudaMalloc(&d_k, k.size() * 4), "k"); + check(cudaMalloc(&d_v, v.size() * 4), "v"); + check(cudaMalloc(&d_g, gate.size() * 4), "g"); + check(cudaMalloc(&d_b, beta.size() * 4), "b"); + check(cudaMalloc(&d_o, (size_t) h_v * S * 4), "o"); + check(cudaMemcpy(d_st, st_dev.data(), st_dev.size() * 4, cudaMemcpyHostToDevice), "cst"); + check(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "cq"); + check(cudaMemcpy(d_k, k.data(), k.size() * 4, cudaMemcpyHostToDevice), "ck"); + check(cudaMemcpy(d_v, v.data(), v.size() * 4, cudaMemcpyHostToDevice), "cv"); + check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "cg"); + check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "cb"); + + strata::kernels::GdnShapes sh{S, h_k, h_v}; + strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr); + + std::vector got_o((size_t) h_v * S), got_st(st_dev.size()); + check(cudaMemcpy(got_o.data(), d_o, got_o.size() * 4, cudaMemcpyDeviceToHost), "cgo"); + check(cudaMemcpy(got_st.data(), d_st, got_st.size() * 4, cudaMemcpyDeviceToHost), "cgst"); + + // o, and the STATE read back through the declared layout + const double rel_o = rel_l1(want_o, got_o); + double rel_st = 0, mag_st = 0; + for (int i = 0; i < S; ++i) + for (int j = 0; j < S; ++j) + for (int h = 0; h < h_v; ++h) { + const size_t dev = (size_t) (i * h_v + h) * S + j; + const double w = st_mod[(size_t) (i * S + j) * h_v + h]; + rel_st += std::fabs(w - (double) got_st[dev]); + mag_st += std::fabs(w); + } + rel_st /= (mag_st > 1e-30 ? mag_st : 1e-30); + std::printf("\n %-42s rel %.3e\n", "o vs reference", rel_o); + std::printf(" %-42s rel %.3e\n", "state (read via (S,h_v,S)) vs reference", rel_st); + // The kernel accumulates in f32 and the reference in f64, and the state is a RECURRENCE over 128 + // terms, so 1e-5 is the arithmetic's floor here and not a structural allowance. + if (!(rel_o <= 1e-5)) { std::printf(" *** o over 1e-5 ***\n"); ++bad; } + if (!(rel_st <= 1e-5)) { std::printf(" *** state over 1e-5 ***\n"); ++bad; } + + // a zero state stays zero, and a zero gate/beta leaves the state untouched (the reference's + // PROPERTY 4 setup) - a cheap independent invariant that no layout can fake + { + std::vector zero(st_dev.size(), 0.0f), zg((size_t) h_v, 0.0f), zb((size_t) h_v, 0.0f); + check(cudaMemcpy(d_st, zero.data(), zero.size() * 4, cudaMemcpyHostToDevice), "z0"); + check(cudaMemcpy(d_g, zg.data(), zg.size() * 4, cudaMemcpyHostToDevice), "z1"); + check(cudaMemcpy(d_b, zb.data(), zb.size() * 4, cudaMemcpyHostToDevice), "z2"); + strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr); + std::vector zz(zero.size()); + check(cudaMemcpy(zz.data(), d_st, zz.size() * 4, cudaMemcpyDeviceToHost), "z3"); + double nz = 0; + for (float x : zz) nz += std::fabs(x); + const bool ok = nz == 0.0; + std::printf(" %-42s %s\n", "gate=beta=0 from a zero state is a no-op", ok ? "yes" : "*** NO ***"); + if (!ok) ++bad; + } + + // ephemeral state: unchanged when the state is untouched but beta=1 — the delta rule writing k*d + cudaFree(d_st); cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_g); cudaFree(d_b); cudaFree(d_o); + } + + // ================= 2. the conv ================= + { + const int C = 24, dc = 4; // small, so the host reference is a plain loop + // TWO DIFFERENT LAYOUTS MEET HERE, and this is where the first version of this test failed at 0.136. + // `ref/gdn.py` carries the conv state as (d_conv-1, C) ROW-MAJOR - (i, c) at i*C + c - because it is + // numpy. The kernel carries it as (C, d_conv-1) with c fastest - c*(dc-1) + i - because that is + // ggml's `ne = {d_conv-1, C}` with ne0 fast, and it is a runtime buffer so either is legal. The + // mapping between them is written out below rather than assumed, in both directions. + std::vector cs_ref((size_t) (dc - 1) * C), x((size_t) C), kern((size_t) dc * C); + for (int i = 0; i < dc - 1; ++i) + for (int c = 0; c < C; ++c) cs_ref[(size_t) (i * C + c)] = (float) (10 * (i + 1) + c); // labelled + for (int c = 0; c < C; ++c) x[(size_t) c] = (float) (100 + c); + for (size_t i = 0; i < kern.size(); ++i) kern[i] = gauss(rng); + + auto to_dev_layout = [&](const std::vector& r) { + std::vector d(r.size()); + for (int i = 0; i < dc - 1; ++i) + for (int c = 0; c < C; ++c) d[(size_t) (c * (dc - 1) + i)] = r[(size_t) (i * C + c)]; + return d; + }; + auto to_ref_layout = [&](const std::vector& d) { + std::vector r(d.size()); + for (int i = 0; i < dc - 1; ++i) + for (int c = 0; c < C; ++c) r[(size_t) (i * C + c)] = d[(size_t) (c * (dc - 1) + i)]; + return r; + }; + + std::vector cs = to_dev_layout(cs_ref); + std::vector want; + std::vector cs_want_ref = cs_ref; + ref_conv(cs_want_ref, x, kern, C, dc, want); + const std::vector cs_want = to_dev_layout(cs_want_ref); + + // THE LAYOUT: the manifest's `ssm_conv1d.weight` has ne = [d_conv, C], so ne0 = d_conv is fast. + // The kernel takes `kW[c*dc + i]`; the reference's `kern` is (dc, C) row-major. The transcription + // below is the ONLY place the two meet. + std::vector kW((size_t) C * dc); + for (int c = 0; c < C; ++c) + for (int i = 0; i < dc; ++i) kW[(size_t) (c * dc + i)] = kern[(size_t) (i * C + c)]; + // and the rival reading, which must differ or the fixture cannot see a transposed weight + std::vector kW_wrong((size_t) C * dc); + for (size_t i = 0; i < kern.size(); ++i) kW_wrong[i] = kern[i]; + { + // apply the WRONG layout by hand: tap i of channel c is kW[c*dc+i] read as kW[i*C+c] + std::vector cs2 = cs; + std::vector out_bad((size_t) C, 0.0f); + for (int c = 0; c < C; ++c) { + double a = 0; + for (int i = 0; i < dc - 1; ++i) a += (double) cs2[(size_t) (i * C + c)] * (double) kW_wrong[(size_t) (c * dc + i)]; + a += (double) x[(size_t) c] * (double) kW_wrong[(size_t) (c * dc + dc - 1)]; + out_bad[(size_t) c] = (float) a; + } + const double rel = rel_l1(want, out_bad); + std::printf("\n %-42s %-4s (%.1f%% apart)\n", "conv weight layout is observable", + rel > 0.05 ? "yes" : "*** NO ***", rel * 100); + if (!(rel > 0.05)) ++bad; + } + + float *d_cs = nullptr, *d_x = nullptr, *d_w = nullptr, *d_o = nullptr; + check(cudaMalloc(&d_cs, cs.size() * 4), "cs"); + check(cudaMalloc(&d_x, x.size() * 4), "cx"); + check(cudaMalloc(&d_w, kW.size() * 4), "cw"); + check(cudaMalloc(&d_o, (size_t) C * 4), "co"); + check(cudaMemcpy(d_cs, cs.data(), cs.size() * 4, cudaMemcpyHostToDevice), "ccs"); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "ccx"); + check(cudaMemcpy(d_w, kW.data(), kW.size() * 4, cudaMemcpyHostToDevice), "ccw"); + strata::kernels::gdn_conv_step(d_cs, d_x, d_w, d_o, C, dc, nullptr); + std::vector got((size_t) C), got_cs(cs.size()); + check(cudaMemcpy(got.data(), d_o, got.size() * 4, cudaMemcpyDeviceToHost), "cgo"); + check(cudaMemcpy(got_cs.data(), d_cs, got_cs.size() * 4, cudaMemcpyDeviceToHost), "cgs"); + const double rel_out = rel_l1(want, got), rel_cs = rel_l1(cs_want, got_cs); + std::printf(" %-42s rel %.3e\n", "conv out vs reference", rel_out); + std::printf(" %-42s rel %.3e\n", "conv state slide (mapped) vs reference", rel_cs); + if (!(rel_out <= 1e-6)) { std::printf(" *** conv out ***\n"); ++bad; } + if (!(rel_cs <= 1e-6)) { std::printf(" *** conv state ***\n"); ++bad; } + cudaFree(d_cs); cudaFree(d_x); cudaFree(d_w); cudaFree(d_o); + } + + // ================= 3. l2_norm ================= + { + const int rows = 16, cols = 128; + std::vector x((size_t) rows * cols), x_ref; + for (auto& val : x) val = gauss(rng) * 3.0f; + x_ref = x; + const float eps = 1e-6f; + for (int r = 0; r < rows; ++r) { + double acc = 0; + for (int i = 0; i < cols; ++i) acc += (double) x_ref[(size_t) (r * cols + i)] * (double) x_ref[(size_t) (r * cols + i)]; + const float inv = (float) (1.0 / std::sqrt(acc + (double) eps)); + for (int i = 0; i < cols; ++i) x_ref[(size_t) (r * cols + i)] *= inv; + } + // The rival reading puts THE SAME eps on the MEAN instead of on the squared norm, which at + // ||x||^2 ~ 1152 and cols = 128 changes the divisor from sqrt(1152) to sqrt(9) - a factor of 11.3, so + // the trap is large here. It would be a much smaller correction on a near-zero row, where the floor + // is the whole answer; that regime is not what this fixture exercises. + std::vector x_mean = x; + for (int r = 0; r < rows; ++r) { + double acc = 0; + for (int i = 0; i < cols; ++i) acc += (double) x_mean[(size_t) (r * cols + i)] * (double) x_mean[(size_t) (r * cols + i)]; + const float inv = (float) (1.0 / std::sqrt(acc / cols + (double) eps)); + for (int i = 0; i < cols; ++i) x_mean[(size_t) (r * cols + i)] *= inv; + } + const double rel_trap = rel_l1(x_ref, x_mean); + std::printf("\n %-42s %-4s (%.1f%% apart)\n", "eps on sum vs on mean is observable", + rel_trap > 0.05 ? "yes" : "*** NO ***", rel_trap * 100); + if (!(rel_trap > 0.05)) ++bad; + + float* d_x = nullptr; + check(cudaMalloc(&d_x, x.size() * 4), "lx"); + check(cudaMemcpy(d_x, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "lcx"); + strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr); + std::vector got(x.size()); + check(cudaMemcpy(got.data(), d_x, got.size() * 4, cudaMemcpyDeviceToHost), "lcg"); + const double rel = rel_l1(x_ref, got); + std::printf(" %-42s rel %.3e\n", "l2_norm vs reference", rel); + if (!(rel <= 1e-6)) ++bad; + cudaFree(d_x); + } + + // ================= 4. the closing norm ================= + { + const int S2 = 128, hv2 = 8; + std::vector o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2), y_ref((size_t) hv2 * S2); + for (auto& val : o) val = gauss(rng); + for (auto& val : z) val = gauss(rng); + for (auto& val : sn) val = 1.0f + 0.1f * gauss(rng); + const float eps = 1e-6f; + for (int h = 0; h < hv2; ++h) { + double acc = 0; + for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)]; + const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps)); + for (int i = 0; i < S2; ++i) + y_ref[(size_t) (h * S2 + i)] = o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * + sigmoid_f(z[(size_t) (h * S2 + i)]); + } + float *d_o = nullptr, *d_z = nullptr, *d_sn = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_o, o.size() * 4), "no"); + check(cudaMalloc(&d_z, z.size() * 4), "nz"); + check(cudaMalloc(&d_sn, sn.size() * 4), "ns"); + check(cudaMalloc(&d_y, y_ref.size() * 4), "ny"); + check(cudaMemcpy(d_o, o.data(), o.size() * 4, cudaMemcpyHostToDevice), "nco"); + check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "ncz"); + check(cudaMemcpy(d_sn, sn.data(), sn.size() * 4, cudaMemcpyHostToDevice), "ncs"); + strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, nullptr); + std::vector got(y_ref.size()); + check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "ncy"); + const double rel = rel_l1(y_ref, got); + std::printf("\n %-42s rel %.3e\n", "out norm (rms * ssm_norm * sigmoid z)", rel); + if (!(rel <= 1e-6)) ++bad; + + // SiLU instead of sigmoid is the qwen3.5 reading; `ref/gdn.py` says this artifact does NOT use it + std::vector y_silu(y_ref.size()); + for (int h = 0; h < hv2; ++h) { + double acc = 0; + for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)]; + const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps)); + for (int i = 0; i < S2; ++i) { + const float zz = z[(size_t) (h * S2 + i)]; + y_silu[(size_t) (h * S2 + i)] = + o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * (zz / (1.0f + std::exp(-zz))); + } + } + const double rel_silu = rel_l1(y_ref, y_silu); + std::printf(" %-42s %-4s (%.2f%% apart)\n", "sigmoid vs SiLU on the gate is observable", + rel_silu > 0.05 ? "yes" : "*** NO ***", rel_silu * 100); + if (!(rel_silu > 0.05)) ++bad; + cudaFree(d_o); cudaFree(d_z); cudaFree(d_sn); cudaFree(d_y); + } + + std::printf("\ngdn: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("gdn_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/gr_parity.cpp b/engine/strata/src/kernels/gr_parity.cpp new file mode 100644 index 00000000..b5ceb76c --- /dev/null +++ b/engine/strata/src/kernels/gr_parity.cpp @@ -0,0 +1,770 @@ +// src/kernels/gr_parity.cpp - P2.S2's test for the gated residual / hyper-connection. +// +// `ref/gr.py` opens by listing the details "a prose reading gets wrong", and every one of them is a reading +// that has the RIGHT SHAPES and produces a PLAUSIBLE number. So each is computed here the wrong way round and +// required to differ materially BEFORE the kernel is judged against the right one. A test that only does the +// second half passes against either reading: +// +// 1. PER-STREAM RMSNorm. The source comment reads ambiguously; the code reduces over ne[0] = n_embd, i.e. +// one RMS per stream. The rival reading is one RMS over the whole hc*n_embd stack. +// 2. `/ hc` INSIDE the silu: `lo = silu(proj / hc)`. Moving it outside is a one-line change that keeps +// every shape. +// 3. SiLU on `lo` and SIGMOID on the gate, a few lines apart in the same function. Swapping them is the +// obvious slip, and both are monotone saturating functions so the magnitudes stay comparable. +// 4. `mean` over the stream axis, not `sum`. A factor of hc = 4, which is exactly the kind of error that +// looks like a scale problem rather than a structural one. +// 5. ACTIVATION PRECISION. The historical BF16-rounded CPU contract and the pinned CUDA single-token +// FP32-activation contract must be distinguishable. Both are tested against explicit references; +// neither is selected merely because the weight is BF16. The scalar fixture isolates xn and lo +// rounding from reduction order, and graph replay must preserve the precision chosen at capture. +// 6. `gr_write`'s `2*sigmoid`, which centres the gate on 1 so a ZERO injection is a plain residual add. +// Asserted as a property, not as a value, because that is what the source comment claims. +#include "strata/kernels/gr.hpp" +#include "strata/kernels/fused_gr.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// The same rule the kernel uses, on the host - `ref/quant.py::bf16`. +float to_bf16(float f) { + uint32_t i; + std::memcpy(&i, &f, 4); + i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u; + float o; + std::memcpy(&o, &i, 4); + return o; +} + +uint16_t bf16_bits(float f) { + uint32_t i; + std::memcpy(&i, &f, 4); + return (uint16_t) (i >> 16); +} + +struct Opts { + bool per_stream_norm = true; ///< false: one RMS over the whole stack (WRONG) + bool scale_inside_silu = true; ///< false: silu(proj)/hc instead of silu(proj/hc) (WRONG) + bool sigmoid_on_gate = true; ///< false: silu on the gate and sigmoid on lo (WRONG) + bool mean_over_streams = true; ///< false: sum over streams instead of mean (WRONG) + bool round_activation = true; ///< false: pinned CUDA single-token BF16 MMVF contract +}; + +/// `ref/gr.py::gr_read`, transcribed with switches for the rival readings. +void reference(const std::vector& R, const std::vector& w_norm, + const std::vector& w_down, const std::vector& w_up, + const std::vector& w_inject, float eps, long long n_embd, long long hc, long long hc_lr, + const Opts& o, std::vector& mixed, std::vector& inject) { + const long long hc_dim = hc * n_embd; + std::vector xn((size_t) hc_dim); + if (o.per_stream_norm) { + for (long long c = 0; c < hc; ++c) { + double ms = 0; + for (long long d = 0; d < n_embd; ++d) ms += (double) R[(size_t) (c * n_embd + d)] * R[(size_t) (c * n_embd + d)]; + ms /= (double) n_embd; + const float rs = (float) (1.0 / std::sqrt(ms + (double) eps)); + for (long long d = 0; d < n_embd; ++d) { + const size_t i = (size_t) (c * n_embd + d); + xn[i] = R[i] * rs * w_norm[i]; + } + } + } else { + double ms = 0; + for (long long i = 0; i < hc_dim; ++i) ms += (double) R[(size_t) i] * R[(size_t) i]; + ms /= (double) hc_dim; + const float rs = (float) (1.0 / std::sqrt(ms + (double) eps)); + for (long long i = 0; i < hc_dim; ++i) xn[(size_t) i] = R[(size_t) i] * rs * w_norm[(size_t) i]; + } + + std::vector act((size_t) hc_dim); + for (long long i = 0; i < hc_dim; ++i) act[(size_t) i] = o.round_activation ? to_bf16(xn[(size_t) i]) : xn[(size_t) i]; + + // lo + std::vector lo((size_t) hc_lr); + for (long long k = 0; k < hc_lr; ++k) { + double a = 0; + for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_down[(size_t) (k * hc_dim + i)]; + const float p = (float) a; + if (o.sigmoid_on_gate) lo[(size_t) k] = o.scale_inside_silu ? (p / (float) hc) / (1.0f + std::exp(-(p / (float) hc))) + : (p / (1.0f + std::exp(-p))) / (float) hc; + else lo[(size_t) k] = o.scale_inside_silu ? 1.0f / (1.0f + std::exp(-(p / (float) hc))) + : (1.0f / (1.0f + std::exp(-p))) / (float) hc; + } + std::vector lq((size_t) hc_lr); + for (long long k = 0; k < hc_lr; ++k) + lq[(size_t) k] = o.round_activation ? to_bf16(lo[(size_t) k]) : lo[(size_t) k]; + + // gate and the gated mean + mixed.assign((size_t) n_embd, 0.0f); + for (long long d = 0; d < n_embd; ++d) { + float m = 0.0f; + for (long long c = 0; c < hc; ++c) { + const long long i = c * n_embd + d; + double a = 0; + for (long long k = 0; k < hc_lr; ++k) a += (double) lq[(size_t) k] * (double) w_up[(size_t) (i * hc_lr + k)]; + const float g = (float) a; + const float s = o.sigmoid_on_gate ? 1.0f / (1.0f + std::exp(-g)) : g / (1.0f + std::exp(-g)); + m += xn[(size_t) i] * s; + } + mixed[(size_t) d] = o.mean_over_streams ? m / (float) hc : m; + } + + inject.assign((size_t) hc, 0.0f); + for (long long c = 0; c < hc; ++c) { + double a = 0; + for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_inject[(size_t) (c * hc_dim + i)]; + inject[(size_t) c] = (float) a; + } +} + +/// Normalised L1 difference. `mag_out` returns the mean |a|, for reporting. +double rel_diff(const std::vector& a, const std::vector& b, double* mag_out = nullptr) { + double d = 0, mag = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + mag += std::fabs((double) a[i]); + } + if (mag_out) *mag_out = mag / (double) (a.empty() ? 1 : a.size()); + return d / (mag > 1e-30 ? mag : 1e-30); +} + +/// Relative error against the magnitude of the TERMS, not of the result. +/// +/// `R + block_out * w` cancels wherever block_out*w is close to -R, and a plain |want-got|/|want| then +/// reports the CONDITION NUMBER instead of the arithmetic. This is the same metric mistake the project has +/// now made four times: rounds 169 (Q4_K), 189 (RoPE), 194 (shared_expert) and this one. For a sum, the +/// denominator is the sum of the term magnitudes. +double rel_terms(double want, double got, double term_a, double term_b) { + const double den = std::fabs(term_a) + std::fabs(term_b); + return std::fabs(want - got) / (den > 1e-30 ? den : 1e-30); +} + +const char* activation_mode_name(int mode) { + return mode == 2 ? "native pinned GR" : (mode == 1 ? "FP32" : "BF16"); +} +void select_activation_mode(int mode) { + strata::kernels::gr_set_native_mmvf(mode == 2); + // In mode 2 the precision-only switch is deliberately false: native MMVF must imply FP32 by itself. + strata::kernels::gr_set_fp32_activations(mode == 1); +} + +// A diagonal GR fixture makes activation precision observable without summation-order ambiguity. +// Two-wide matrices satisfy native MMVF's pair ABI, while each nonzero dot has only one nonzero product. +// At R=1 and eps=0, xn=gamma exactly; any rounding in xn or lo comes from the selected activation contract. +int scalar_activation_contract() { + using namespace strata::kernels; + const GrShapes sh{2, 1, 2}; + float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr; + uint16_t* d_weights = nullptr; + void* d_scratch = nullptr; + check(cudaMalloc(&d_R, 2 * sizeof(float)), "scalar R"); + check(cudaMalloc(&d_norm, 2 * sizeof(float)), "scalar norm"); + check(cudaMalloc(&d_mixed, 2 * sizeof(float)), "scalar mixed"); + check(cudaMalloc(&d_inject, sizeof(float)), "scalar inject"); + check(cudaMalloc(&d_weights, 10 * sizeof(uint16_t)), "scalar weights"); + check(cudaMalloc(&d_scratch, gr_workspace_bytes(sh)), "scalar scratch"); + GrWorkspace ws; + gr_workspace_init(sh, d_scratch, ws); + const float ones[] = {1.0f, 1.0f}; + const uint16_t weights[] = { + bf16_bits(0.5f), 0, 0, 0, // down: lo[0]=silu(xn[0]/2), lo[1]=0 + bf16_bits(1.5f), 0, bf16_bits(1.5f), 0, // both gate rows consume lo[0] + bf16_bits(2.0f), 0 // injection: 2*xn[0] + }; + check(cudaMemcpy(d_R, ones, sizeof(ones), cudaMemcpyHostToDevice), "scalar upload R"); + check(cudaMemcpy(d_weights, weights, sizeof(weights), cudaMemcpyHostToDevice), "scalar upload weights"); + cudaStream_t stream; + check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "scalar stream"); + int bad = 0; + for (float gamma : {1.0f, 1.00390625f}) { + const float gammas[] = {gamma, gamma}; + check(cudaMemcpy(d_norm, gammas, sizeof(gammas), cudaMemcpyHostToDevice), "scalar upload norm"); + float mixed_by_mode[3][2] = {}, inject_by_mode[3] = {}; + for (int mode = 0; mode < 3; ++mode) { + select_activation_mode(mode); + gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f, + sh, ws, d_mixed, d_inject, stream); + check(cudaStreamSynchronize(stream), "scalar warmup"); + cudaGraph_t graph; + cudaGraphExec_t executable; + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "scalar capture begin"); + gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f, + sh, ws, d_mixed, d_inject, stream); + check(cudaStreamEndCapture(stream, &graph), "scalar capture end"); + check(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "scalar instantiate"); + // Changing both host options after capture cannot change the graph's selected kernels. + select_activation_mode((mode + 1) % 3); + // Warmup results must not make a missing/no-op captured launch pass. + // Poison the outputs and intermediate workspace before replay. + check(cudaMemsetAsync(d_mixed, 0xa5, 2 * sizeof(float), stream), "scalar poison mixed"); + check(cudaMemsetAsync(d_inject, 0xa5, sizeof(float), stream), "scalar poison inject"); + check(cudaMemsetAsync(d_scratch, 0xa5, ws.bytes, stream), "scalar poison workspace"); + check(cudaGraphLaunch(executable, stream), "scalar replay"); + check(cudaStreamSynchronize(stream), "scalar replay sync"); + check(cudaMemcpy(mixed_by_mode[mode], d_mixed, 2 * sizeof(float), cudaMemcpyDeviceToHost), "scalar mixed copy"); + check(cudaMemcpy(&inject_by_mode[mode], d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar inject copy"); + const float activation = mode ? gamma : to_bf16(gamma); + const float projection = activation * 0.5f; + const float lo = projection / (1.0f + std::exp(-projection)); + const float gate = (mode ? lo : to_bf16(lo)) * 1.5f; + const float expected_mixed = gamma / (1.0f + std::exp(-gate)); + const float expected_inject = activation * 2.0f; + // Each mode has its own activation contract and bounded scalar-formula + // check. Native fast exp/div need not match ordinary FP32 postops bit + // for bit: native_gr_postops_parity establishes that arithmetic with + // actual pinned CUDA graphs. The nonzero projection/injection here + // has only one exactly representable product and remains exact. + const bool ok = std::fabs(mixed_by_mode[mode][0] - expected_mixed) <= 2e-7f && + mixed_by_mode[mode][0] == mixed_by_mode[mode][1] && + inject_by_mode[mode] == expected_inject; + std::printf(" scalar gamma %.8f %s activation/capture %s (mixed %.9f, ref %.9f)\n", + gamma, activation_mode_name(mode), ok ? "pass" : "FAIL", + mixed_by_mode[mode][0], expected_mixed); + if (!ok) ++bad; + check(cudaGraphExecDestroy(executable), "scalar graph exec destroy"); + check(cudaGraphDestroy(graph), "scalar graph destroy"); + + const float sentinel = -73.25f; + check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "scalar sentinel"); + select_activation_mode(mode); + gr_read(d_R, d_norm, d_weights, d_weights + 4, nullptr, 0.0f, + sh, ws, d_mixed, d_inject, stream); + check(cudaStreamSynchronize(stream), "scalar final mixer sync"); + float final_mixed[2] = {}, untouched = 0.0f; + check(cudaMemcpy(final_mixed, d_mixed, sizeof(final_mixed), cudaMemcpyDeviceToHost), "scalar final mixed"); + check(cudaMemcpy(&untouched, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "scalar sentinel copy"); + const bool final_ok = std::memcmp(final_mixed, mixed_by_mode[mode], sizeof(final_mixed)) == 0 && untouched == sentinel; + std::printf(" scalar final mixer %s %s\n", activation_mode_name(mode), final_ok ? "pass" : "FAIL"); + if (!final_ok) ++bad; + } + if (std::fabs(mixed_by_mode[1][0] - mixed_by_mode[0][0]) <= 1e-5f || + (gamma != 1.0f && inject_by_mode[0] == inject_by_mode[1])) { + std::printf(" scalar precision fixture is not observable\n"); + ++bad; + } + if (inject_by_mode[1] != inject_by_mode[2]) { + std::printf(" native MMVF changed the exact scalar FP32 injection projection\n"); + ++bad; + } + } + select_activation_mode(0); + check(cudaStreamDestroy(stream), "scalar stream destroy"); + cudaFree(d_R); cudaFree(d_norm); cudaFree(d_mixed); cudaFree(d_inject); + cudaFree(d_weights); cudaFree(d_scratch); + return bad; +} + +int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const uint16_t* d_up, + const uint16_t* d_inject, float eps) { + using namespace strata::kernels; + constexpr int N = 2560, HC = 4, LR = 320, D = N * HC, T = kFusedGrMaxT; + std::mt19937 rng(0x6f8a); + std::normal_distribution normal(0.0f, 0.3f); + std::vector r((size_t) T * D), bo((size_t) T * N), inj((size_t) T * HC); + for (auto& x : r) x = normal(rng); + for (auto& x : bo) x = normal(rng); + for (auto& x : inj) x = normal(rng); + + float *d_r = nullptr, *d_r_out = nullptr, *d_bo = nullptr, *d_inj = nullptr; + float *d_lo = nullptr, *d_rs = nullptr, *d_inj_out = nullptr, *d_mixed = nullptr, *d_xn = nullptr; + check(cudaMalloc(&d_r, r.size() * sizeof(float)), "multi R"); + check(cudaMalloc(&d_r_out, r.size() * sizeof(float)), "multi R_out"); + check(cudaMalloc(&d_bo, bo.size() * sizeof(float)), "multi bo"); + check(cudaMalloc(&d_inj, inj.size() * sizeof(float)), "multi inj"); + check(cudaMalloc(&d_lo, (size_t) T * LR * sizeof(float)), "multi lo"); + check(cudaMalloc(&d_rs, (size_t) T * HC * sizeof(float)), "multi rs"); + check(cudaMalloc(&d_inj_out, (size_t) T * HC * sizeof(float)), "multi injection"); + check(cudaMalloc(&d_mixed, (size_t) T * N * sizeof(float)), "multi mixed"); + check(cudaMalloc(&d_xn, (size_t) T * D * sizeof(float)), "multi xn"); + check(cudaMemcpy(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy R"); + check(cudaMemcpy(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy bo"); + check(cudaMemcpy(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "multi copy inj"); + + std::vector args(T); + for (int t = 0; t < T; ++t) { + auto& a = args[t]; + a.R = d_r + (size_t) t * D; + a.R_out = d_r_out + (size_t) t * D; + a.apply = true; + a.bo_prev = d_bo + (size_t) t * N; + a.inj_prev = d_inj + (size_t) t * HC; + a.w_norm = d_norm; + a.w_down = d_down; + a.w_up = d_up; + a.w_inject = d_inject; + a.eps = eps; + a.lo = d_lo + (size_t) t * LR; + a.rs = d_rs + (size_t) t * HC; + a.inject_out = d_inj_out + (size_t) t * HC; + a.mixed = d_mixed + (size_t) t * N; + } + + struct Snapshot { + std::vector r_out, lo, rs, inject, mixed; + }; + auto snapshot = [&]() { + Snapshot s; + s.r_out.resize((size_t) T * D); + s.lo.resize((size_t) T * LR); + s.rs.resize((size_t) T * HC); + s.inject.resize((size_t) T * HC); + s.mixed.resize((size_t) T * N); + check(cudaMemcpy(s.r_out.data(), d_r_out, s.r_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read R_out"); + check(cudaMemcpy(s.lo.data(), d_lo, s.lo.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read lo"); + check(cudaMemcpy(s.rs.data(), d_rs, s.rs.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read rs"); + check(cudaMemcpy(s.inject.data(), d_inj_out, s.inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read inject"); + check(cudaMemcpy(s.mixed.data(), d_mixed, s.mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "multi read mixed"); + return s; + }; + // the split read (STRATA_GR_V3=1) sums in another order than the single-token kernel: equal within float + // rounding, not to the bit, so it is compared with a relative tolerance; the default kernels bit for bit + static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }(); + auto close = [](const std::vector& x, const std::vector& y) { + double worst = 0.0, mag = 1e-30; + for (size_t i = 0; i < x.size(); ++i) { + worst = std::max(worst, (double) std::fabs(x[i] - y[i])); + mag = std::max(mag, (double) std::fabs(y[i])); + } + if (worst > 2e-6 * mag) + std::printf(" tolerance: worst %.3e of max |ref| %.3e (rel %.3e), n %zu\n", worst, mag, worst / mag, x.size()); + return worst <= 2e-6 * mag; + }; + auto same = [&](const Snapshot& a, const Snapshot& b) { + if (v3) // `lo` is the default kernels' workspace between down and up; the split read keeps it in shared memory + return close(a.r_out, b.r_out) && close(a.rs, b.rs) && close(a.inject, b.inject) && close(a.mixed, b.mixed); + return std::memcmp(a.r_out.data(), b.r_out.data(), a.r_out.size() * sizeof(float)) == 0 && + std::memcmp(a.lo.data(), b.lo.data(), a.lo.size() * sizeof(float)) == 0 && + std::memcmp(a.rs.data(), b.rs.data(), a.rs.size() * sizeof(float)) == 0 && + std::memcmp(a.inject.data(), b.inject.data(), a.inject.size() * sizeof(float)) == 0 && + std::memcmp(a.mixed.data(), b.mixed.data(), a.mixed.size() * sizeof(float)) == 0; + }; + + cudaStream_t stream = nullptr; + check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "multi stream"); + // Max T forces the HIP kernel's full dynamic-LDS request: 8 * 1280 * sizeof(float) = 40 KiB. + fused_gr_read_multi(args.data(), T, d_xn, stream); + check(cudaStreamSynchronize(stream), "multi max-T sync"); + const Snapshot multi = snapshot(); + for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream); + check(cudaStreamSynchronize(stream), "single reference sync"); + const Snapshot single = snapshot(); + int bad = 0; + if (!same(multi, single)) { + std::printf(" fused GR multi max-T differs from single-token calls\n"); + ++bad; + } + + cudaGraph_t graph = nullptr; + cudaGraphExec_t graph_exec = nullptr; + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "multi graph begin"); + fused_gr_read_multi(args.data(), T, d_xn, stream); + check(cudaStreamEndCapture(stream, &graph), "multi graph end"); + check(cudaGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0), "multi graph instantiate"); + check(cudaGraphLaunch(graph_exec, stream), "multi graph initial replay"); + check(cudaStreamSynchronize(stream), "multi graph initial sync"); + const Snapshot captured = snapshot(); + if (!same(multi, captured)) { + std::printf(" fused GR multi captured graph differs from direct max-T call\n"); + ++bad; + } + + // Reuse the same captured pointers with new payloads; then independently run the single-token path again. + for (size_t i = 0; i < r.size(); ++i) r[i] = -0.7f * r[i] + 0.001f * (float) (i % 17); + for (size_t i = 0; i < bo.size(); ++i) bo[i] = -0.4f * bo[i] + 0.02f; + for (size_t i = 0; i < inj.size(); ++i) inj[i] += 0.3f; + check(cudaMemcpyAsync(d_r, r.data(), r.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay R"); + check(cudaMemcpyAsync(d_bo, bo.data(), bo.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay bo"); + check(cudaMemcpyAsync(d_inj, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice, stream), "multi replay inj"); + check(cudaGraphLaunch(graph_exec, stream), "multi graph changed replay"); + check(cudaStreamSynchronize(stream), "multi graph changed sync"); + const Snapshot replay = snapshot(); + if (std::memcmp(multi.mixed.data(), replay.mixed.data(), multi.mixed.size() * sizeof(float)) == 0) { + std::printf(" fused GR graph replay ignored changed inputs\n"); + ++bad; + } + for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream); + check(cudaStreamSynchronize(stream), "changed single reference sync"); + if (!same(replay, snapshot())) { + std::printf(" fused GR changed graph replay differs from single-token calls\n"); + ++bad; + } + + std::printf(" fused GR multi max-T=8 LDS launch and changing graph replay %s\n", + bad == 0 ? "pass" : "FAIL"); + check(cudaGraphExecDestroy(graph_exec), "multi graph exec destroy"); + check(cudaGraphDestroy(graph), "multi graph destroy"); + check(cudaStreamDestroy(stream), "multi stream destroy"); + check(cudaFree(d_xn), "free multi xn"); + check(cudaFree(d_mixed), "free multi mixed"); + check(cudaFree(d_inj_out), "free multi injection"); + check(cudaFree(d_rs), "free multi rs"); + check(cudaFree(d_lo), "free multi lo"); + check(cudaFree(d_inj), "free multi inj"); + check(cudaFree(d_bo), "free multi bo"); + check(cudaFree(d_r_out), "free multi R_out"); + check(cudaFree(d_r), "free multi R"); + return bad; +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: gr_parity [--selftest]\n"); return 2; } + } + + const long long n_embd = 256, hc = 4, hc_lr = 32; + const long long hc_dim = hc * n_embd; + const float eps = 1e-6f; + std::mt19937 rng(1234); + std::normal_distribution gauss(0.0f, 1.0f); + + // Weights are BF16-VALUED f32, which is what the pack holds for a BF16 source type. Generating plain f32 + // weights would make the kernel (which stores 16 bits) differ from the reference by the rounding itself, + // and the test would then be measuring the fixture. + auto bf16_weight = [&](size_t n, float sigma) { + std::vector v(n); + for (auto& x : v) x = to_bf16(gauss(rng) * sigma); + return v; + }; + std::vector R((size_t) hc_dim); + for (auto& x : R) x = gauss(rng); + // STREAM SCALES 1, 4, 16, 64. Without them trap 1 is only ~5% observable, because four streams of i.i.d. + // normal noise have nearly the same RMS by accident - so a whole-stack RMS and a per-stream RMS agree to + // within the noise, and the fixture would be asserting a distinction it cannot see. Giving the streams + // different magnitudes is what makes "per-stream" a claim with content. + for (long long c = 0; c < hc; ++c) + for (long long d = 0; d < n_embd; ++d) R[(size_t) (c * n_embd + d)] *= std::pow(4.0f, (float) c); + // gamma stored as (1 + w), so values near 1 - a reader expecting a plain scale is the one this catches + std::vector w_norm((size_t) hc_dim); + for (auto& x : w_norm) x = 1.0f + 0.1f * gauss(rng); + std::vector w_down = bf16_weight((size_t) (hc_lr * hc_dim), 0.2f); + std::vector w_up = bf16_weight((size_t) (hc_dim * hc_lr), 0.2f); + std::vector w_inject = bf16_weight((size_t) (hc * hc_dim), 0.05f); + + // NO PERMUTATION: the kernel takes both matrices exactly as the manifest (and `ref/gr.py`) store them. + // `w_down` is (hc_lr, hc_dim) row-major and `w_up` is (hc_dim, hc_lr) row-major, so the bit-copy below is + // the whole conversion. An earlier version of this kernel wanted both TRANSPOSED - the test built them + // that way and asserted the orientation observable - and that is gone because the warp-per-row mapping + // makes it unnecessary. What replaces it is the general orientation trap further down: a weight array + // read with the wrong index expression must still produce a visibly different answer. + std::vector q_down(w_down.size()), q_up(w_up.size()), q_inject(w_inject.size()); + for (size_t i = 0; i < w_down.size(); ++i) q_down[i] = bf16_bits(w_down[i]); + for (size_t i = 0; i < w_up.size(); ++i) q_up[i] = bf16_bits(w_up[i]); + for (size_t i = 0; i < w_inject.size(); ++i) q_inject[i] = bf16_bits(w_inject[i]); + + // ---- device side + float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr; + uint16_t *d_down = nullptr, *d_up = nullptr, *d_inj = nullptr; + check(cudaMalloc(&d_R, R.size() * sizeof(float)), "m R"); + check(cudaMalloc(&d_norm, w_norm.size() * sizeof(float)), "m norm"); + check(cudaMalloc(&d_down, q_down.size() * sizeof(uint16_t)), "m down"); + check(cudaMalloc(&d_up, q_up.size() * sizeof(uint16_t)), "m up"); + check(cudaMalloc(&d_inj, q_inject.size() * sizeof(uint16_t)), "m inj"); + check(cudaMalloc(&d_mixed, (size_t) n_embd * sizeof(float)), "m mixed"); + check(cudaMalloc(&d_inject, (size_t) hc * sizeof(float)), "m inject"); + check(cudaMemcpy(d_R, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c R"); + check(cudaMemcpy(d_norm, w_norm.data(), w_norm.size() * sizeof(float), cudaMemcpyHostToDevice), "c norm"); + check(cudaMemcpy(d_down, q_down.data(), q_down.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c down"); + check(cudaMemcpy(d_up, q_up.data(), q_up.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c up"); + check(cudaMemcpy(d_inj, q_inject.data(), q_inject.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c inj"); + + const strata::kernels::GrShapes sh{n_embd, hc, hc_lr}; + // DEVICE memory: the workspace is written by the kernel. + void* d_ws_raw = nullptr; + check(cudaMalloc(&d_ws_raw, strata::kernels::gr_workspace_bytes(sh)), "m ws"); + strata::kernels::GrWorkspace ws; + strata::kernels::gr_workspace_init(sh, d_ws_raw, ws); + strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); + std::vector got_mixed((size_t) n_embd), got_inject((size_t) hc); + check(cudaMemcpy(got_mixed.data(), d_mixed, got_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "c mixed"); + check(cudaMemcpy(got_inject.data(), d_inject, got_inject.size() * sizeof(float), cudaMemcpyDeviceToHost), "c inject"); + + int bad = 0; + + // ---- the traps, asserted OBSERVABLE before the kernel is judged against the right reading + Opts right; + std::vector want_mixed, want_inject; + reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, right, want_mixed, want_inject); + + struct Trap { const char* name; Opts o; double floor; }; + const Trap traps[] = { + {"per-stream RMSNorm vs whole-stack", {false, true, true, true, true}, 0.05}, + {"/hc inside the silu vs outside", {true, false, true, true, true}, 0.05}, + {"SiLU on lo / sigmoid on gate, swapped", {true, true, false, true, true}, 0.05}, + {"mean over streams vs sum", {true, true, true, false, true}, 0.50}, + {"BF16 vs FP32 activation contracts", {true, true, true, true, false}, 1e-4}, + }; + for (const Trap& t : traps) { + std::vector m, i; + reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, t.o, m, i); + const double rel = rel_diff(want_mixed, m); + const bool observable = rel > t.floor; + std::printf(" %-40s %-4s (%.4f%% apart, floor %.3f%%)\n", t.name, observable ? "yes" : "*** NO ***", + rel * 100, t.floor * 100); + if (!observable) { + std::printf(" *** the fixture cannot see this trap, so passing proves nothing about it ***\n"); + ++bad; + } + } + + // ---- the kernel against the correct reference + double mag = 0; + const double rel_mixed = rel_diff(want_mixed, got_mixed, &mag); + std::printf("\n %-40s worst %.3e (mean |ref| %.4f)\n", "mixed vs reference", rel_mixed, mag); + + // The tolerance is set by SUMMATION ORDER, not by the structure: both sides round the activation to bf16 + // and both weights are bf16-valued, so every product is exact in f32 and only the order differs. A + // structural error is several orders of magnitude larger - the trap floors above say so. + if (!(rel_mixed <= 1e-4)) { + std::printf(" *** over 1e-4, which summation order does not explain - look for a structural bug ***\n"); + ++bad; + } + + const double rel_inject = rel_diff(want_inject, got_inject); + std::printf(" %-40s rel %.3e\n", "inject vs reference", rel_inject); + if (!(rel_inject <= 1e-4)) { + // Say WHICH elements and by how much: a whole-array L1 hides whether this is one stream wrong (an + // indexing bug) or all of them slightly wrong (a precision bug), and those need different responses. + std::printf(" want:"); + for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) want_inject[(size_t) c]); + std::printf("\n got :"); + for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) got_inject[(size_t) c]); + std::printf("\n"); + ++bad; + } + + // Same geometry and weights with the CUDA single-token activation contract. The scalar fixture + // below is the independent precision check; this case exercises multi-stream reductions and indexing. + { + Opts fp32; + fp32.round_activation = false; + std::vector wm, wi, gm((size_t) n_embd), gi((size_t) hc); + reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, fp32, wm, wi); + strata::kernels::gr_set_fp32_activations(true); + strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); + check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 mixed"); + check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "FP32 inject"); + strata::kernels::gr_set_fp32_activations(false); + const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi); + const bool ok = rm <= 1e-4 && ri <= 1e-4; + std::printf(" FP32 activations vs reference: %s (mixed %.3e, inject %.3e)\n", + ok ? "pass" : "FAIL", rm, ri); + if (!ok) ++bad; + strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr); + check(cudaMemcpy(gm.data(), d_mixed, gm.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored mixed"); + check(cudaMemcpy(gi.data(), d_inject, gi.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored inject"); + const bool restored = std::memcmp(gm.data(), got_mixed.data(), gm.size() * sizeof(float)) == 0 && + std::memcmp(gi.data(), got_inject.data(), gi.size() * sizeof(float)) == 0; + std::printf(" restoring default activation contract: %s\n", restored ? "byte-identical" : "FAIL"); + if (!restored) ++bad; + } + + // ---- THE WEIGHT ORIENTATION MUST BE OBSERVABLE. The kernel now takes both matrices exactly as the + // manifest stores them, so there is no permutation for a loader to forget - but the INDEX EXPRESSIONS + // inside the kernel are still a place to be wrong, and a wrong one gives right-shaped, wrong-valued + // output. Feed transposed copies through the same code path and require the answer to differ. + { + uint16_t *d_down_bad = nullptr, *d_up_bad = nullptr; + check(cudaMalloc(&d_down_bad, q_down.size() * sizeof(uint16_t)), "m down_bad"); + check(cudaMalloc(&d_up_bad, q_up.size() * sizeof(uint16_t)), "m up_bad"); + std::vector tr_down(q_down.size()), tr_up(q_up.size()); + for (long long k = 0; k < hc_lr; ++k) + for (long long i = 0; i < hc_dim; ++i) + tr_down[(size_t) (i * hc_lr + k)] = q_down[(size_t) (k * hc_dim + i)]; + for (long long i = 0; i < hc_dim; ++i) + for (long long k = 0; k < hc_lr; ++k) + tr_up[(size_t) (k * hc_dim + i)] = q_up[(size_t) (i * hc_lr + k)]; + check(cudaMemcpy(d_down_bad, tr_down.data(), tr_down.size() * 2, cudaMemcpyHostToDevice), "cb d"); + check(cudaMemcpy(d_up_bad, tr_up.data(), tr_up.size() * 2, cudaMemcpyHostToDevice), "cb u"); + std::vector bad_mixed((size_t) n_embd); + float* d_bad = nullptr; + check(cudaMalloc(&d_bad, bad_mixed.size() * sizeof(float)), "m bad"); + strata::kernels::gr_read(d_R, d_norm, d_down_bad, d_up_bad, d_inj, eps, sh, ws, d_bad, d_inject, + nullptr); + check(cudaMemcpy(bad_mixed.data(), d_bad, bad_mixed.size() * sizeof(float), cudaMemcpyDeviceToHost), "cb b"); + const double rel = rel_diff(want_mixed, bad_mixed); + const bool visible = rel > 0.05; + std::printf(" %-40s %s (%.1f%% apart)\n", "weight orientation is observable", + visible ? "yes" : "*** NO ***", rel * 100); + if (!visible) ++bad; + cudaFree(d_down_bad); cudaFree(d_up_bad); cudaFree(d_bad); + } + + // ---- the FINAL mixer passes w_inject = nullptr, and then nothing may be written + float sentinel = -12345.0f; + check(cudaMemcpy(d_inject, &sentinel, sizeof(float), cudaMemcpyHostToDevice), "c sentinel"); + strata::kernels::gr_read(d_R, d_norm, d_down, d_up, nullptr, eps, sh, ws, d_mixed, d_inject, nullptr); + float after = 0.0f; + check(cudaMemcpy(&after, d_inject, sizeof(float), cudaMemcpyDeviceToHost), "c after"); + const bool untouched = (after == sentinel); + std::printf(" %-40s %s\n", "null w_inject writes nothing", untouched ? "yes" : "*** NO ***"); + if (!untouched) ++bad; + + // ---- gr_write: the `2*sigmoid` centring, asserted as the PROPERTY the source comment claims + std::vector block_out((size_t) n_embd); + for (auto& x : block_out) x = gauss(rng); + std::vector zero_inj((size_t) hc, 0.0f); + float *d_Rw = nullptr, *d_bo = nullptr, *d_zi = nullptr, *d_outw = nullptr; + check(cudaMalloc(&d_Rw, R.size() * sizeof(float)), "m Rw"); + check(cudaMalloc(&d_bo, block_out.size() * sizeof(float)), "m bo"); + check(cudaMalloc(&d_zi, zero_inj.size() * sizeof(float)), "m zi"); + check(cudaMalloc(&d_outw, R.size() * sizeof(float)), "m outw"); + check(cudaMemcpy(d_Rw, R.data(), R.size() * sizeof(float), cudaMemcpyHostToDevice), "c Rw"); + check(cudaMemcpy(d_bo, block_out.data(), block_out.size() * sizeof(float), cudaMemcpyHostToDevice), "c bo"); + check(cudaMemcpy(d_zi, zero_inj.data(), zero_inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c zi"); + + strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr); + std::vector got_write((size_t) hc_dim); + check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw"); + + double worst_plain = 0; + for (long long c = 0; c < hc; ++c) + for (long long d = 0; d < n_embd; ++d) { + const size_t i = (size_t) (c * n_embd + d); + const double want = (double) R[i] + (double) block_out[(size_t) d]; + worst_plain = std::fmax(worst_plain, rel_terms(want, (double) got_write[i], (double) R[i], + (double) block_out[(size_t) d])); + } + const bool plain = worst_plain < 1e-6; + std::printf(" %-40s %s (worst rel %.3e)\n", "zero injection -> plain residual add", + plain ? "yes" : "*** NO ***", worst_plain); + if (!plain) ++bad; + + // the rival reading: sigmoid without the 2 halves the update, and must be visible. + // + // The comparison is on the DELTA `out - R`, not on `out`. The claim is about the gate WEIGHT, and `R` + // now reaches 64 in the last stream, so measuring `R + block_out*w` against the wrong reading dilutes a + // 100% error in `w` down to 2.27% - which is how this check first passed as "not observable" while being + // perfectly observable. Measure the quantity the claim is about. + { + std::vector got_delta((size_t) hc_dim), want_delta((size_t) hc_dim), wrong_delta((size_t) hc_dim); + for (long long c = 0; c < hc; ++c) + for (long long d = 0; d < n_embd; ++d) { + const size_t i = (size_t) (c * n_embd + d); + got_delta[i] = (float) ((double) got_write[i] - (double) R[i]); + want_delta[i] = block_out[(size_t) d]; // 2*sigmoid(0) = 1.0 + wrong_delta[i] = block_out[(size_t) d] * 0.5f; // 1*sigmoid(0) = 0.5 + } + const double rel = rel_diff(want_delta, wrong_delta); + const double rel_got = rel_diff(want_delta, got_delta); + const bool visible = rel > 0.05 && rel_got < 0.05; + std::printf(" %-40s %s (readings %.0f%% apart, kernel within %.2e)\n", + "1*sigmoid vs 2*sigmoid is observable", visible ? "yes" : "*** NO ***", rel * 100, rel_got); + if (!visible) ++bad; + } + + // a non-zero injection: every stream receives the SAME block output, differing only by weight + std::vector inj((size_t) hc); + for (auto& x : inj) x = gauss(rng) * 3.0f; + check(cudaMemcpy(d_zi, inj.data(), inj.size() * sizeof(float), cudaMemcpyHostToDevice), "c inj2"); + strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr); + check(cudaMemcpy(got_write.data(), d_outw, got_write.size() * sizeof(float), cudaMemcpyDeviceToHost), "c outw2"); + double worst_stream = 0; + for (long long c = 0; c < hc; ++c) { + const double w = 2.0 / (1.0 + std::exp(-(double) inj[(size_t) c] / (double) hc)); + for (long long d = 0; d < n_embd; ++d) { + const size_t i = (size_t) (c * n_embd + d); + const double want = (double) R[i] + (double) block_out[(size_t) d] * w; + worst_stream = std::fmax(worst_stream, rel_terms(want, (double) got_write[i], (double) R[i], + (double) block_out[(size_t) d] * w)); + } + } + const bool streams_ok = worst_stream < 1e-6; + std::printf(" %-40s %s (worst rel %.3e)\n", "every stream adds the same block output", + streams_ok ? "yes" : "*** NO ***", worst_stream); + if (!streams_ok) ++bad; + + // ---- THE REAL DIMENSIONS. Exercise all activation/projection variants at n_embd=2560, hc=4, hc_lr=320. + // Workspace sizing and every full weight row must agree with the model geometry. + { + const long long rn = 2560, rhc = 4, rlr = 320, rdim = rhc * rn; + std::mt19937 rrng(99); + std::normal_distribution rg(0.0f, 1.0f); + auto rbf16 = [&](size_t n, float sigma) { + std::vector v(n); + for (auto& x : v) x = to_bf16(rg(rrng) * sigma); + return v; + }; + std::vector rR((size_t) rdim); + for (auto& x : rR) x = rg(rrng); + for (long long c = 0; c < rhc; ++c) + for (long long d = 0; d < rn; ++d) rR[(size_t) (c * rn + d)] *= std::pow(4.0f, (float) c); + std::vector rnorm((size_t) rdim); + for (auto& x : rnorm) x = 1.0f + 0.1f * rg(rrng); + std::vector rdown = rbf16((size_t) (rlr * rdim), 0.2f); + std::vector rup = rbf16((size_t) (rdim * rlr), 0.2f); + std::vector rinj = rbf16((size_t) (rhc * rdim), 0.05f); + + std::vector qd(rdown.size()), qu(rup.size()), qi(rinj.size()); + for (size_t i = 0; i < rdown.size(); ++i) qd[i] = bf16_bits(rdown[i]); + for (size_t i = 0; i < rup.size(); ++i) qu[i] = bf16_bits(rup[i]); + for (size_t i = 0; i < rinj.size(); ++i) qi[i] = bf16_bits(rinj[i]); + + float *dR = nullptr, *dN = nullptr, *dM = nullptr, *dI = nullptr; + uint16_t *dD = nullptr, *dU = nullptr, *dJ = nullptr; + check(cudaMalloc(&dR, rR.size() * 4), "rR"); + check(cudaMalloc(&dN, rnorm.size() * 4), "rN"); + check(cudaMalloc(&dD, qd.size() * 2), "rD"); + check(cudaMalloc(&dU, qu.size() * 2), "rU"); + check(cudaMalloc(&dJ, qi.size() * 2), "rJ"); + check(cudaMalloc(&dM, (size_t) rn * 4), "rM"); + check(cudaMalloc(&dI, (size_t) rhc * 4), "rI"); + check(cudaMemcpy(dR, rR.data(), rR.size() * 4, cudaMemcpyHostToDevice), "crR"); + check(cudaMemcpy(dN, rnorm.data(), rnorm.size() * 4, cudaMemcpyHostToDevice), "crN"); + check(cudaMemcpy(dD, qd.data(), qd.size() * 2, cudaMemcpyHostToDevice), "crD"); + check(cudaMemcpy(dU, qu.data(), qu.size() * 2, cudaMemcpyHostToDevice), "crU"); + check(cudaMemcpy(dJ, qi.data(), qi.size() * 2, cudaMemcpyHostToDevice), "crJ"); + + const strata::kernels::GrShapes rsh{rn, rhc, rlr}; + void* rws_raw = nullptr; + check(cudaMalloc(&rws_raw, strata::kernels::gr_workspace_bytes(rsh)), "m rws"); + strata::kernels::GrWorkspace rws; + strata::kernels::gr_workspace_init(rsh, rws_raw, rws); + for (int mode = 0; mode < 3; ++mode) { + select_activation_mode(mode); + strata::kernels::gr_read(dR, dN, dD, dU, dJ, eps, rsh, rws, dM, dI, nullptr); + std::vector gm((size_t) rn), gi((size_t) rhc); + check(cudaMemcpy(gm.data(), dM, gm.size() * 4, cudaMemcpyDeviceToHost), "cgm"); + check(cudaMemcpy(gi.data(), dI, gi.size() * 4, cudaMemcpyDeviceToHost), "cgi"); + + Opts precision; + precision.round_activation = mode == 0; + std::vector wm, wi; + reference(rR, rnorm, rdown, rup, rinj, eps, rn, rhc, rlr, precision, wm, wi); + const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi); + const bool ok = rm <= 1e-4 && ri <= 1e-4; + std::printf("\n real dims 2560/4/320 %s %s (mixed %.3e, inject %.3e)\n", + activation_mode_name(mode), ok ? "pass" : "*** FAIL ***", rm, ri); + if (!ok) ++bad; + } + bad += fused_multi_lds_parity(dN, dD, dU, dJ, eps); + select_activation_mode(0); + cudaFree(rws_raw); + cudaFree(dR); cudaFree(dN); cudaFree(dD); cudaFree(dU); cudaFree(dJ); cudaFree(dM); cudaFree(dI); + } + + bad += scalar_activation_contract(); + std::printf("\ngr_read/gr_write: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("gr_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/iq_multi_parity.cpp b/engine/strata/src/kernels/iq_multi_parity.cpp new file mode 100644 index 00000000..b497b747 --- /dev/null +++ b/engine/strata/src/kernels/iq_multi_parity.cpp @@ -0,0 +1,347 @@ +// src/kernels/iq_multi_parity.cpp - the IQ kernels that decode each weight part once for every +// column / entry, against the older kernels that decode it again per column. Synthetic blocks, no model. +// +// build/iq_multi_parity the checks (a ctest; needs the GPU) +// build/iq_multi_parity --bench the checks, then old/new timings of both paths +// +// (1) iq_mmvq, every format it takes, ncols 1..8 and 11 (the > 8 split): the new output must be BITWISE equal to +// the old one (iq_set_old_kernels), and within float rounding of a double reference built from the GPU's own +// dequantizer (validated against gguf-py by iq_parity) and the dequantized q8_1 activations - a gross-error +// guard, not the contract. +// (2) native_expert_grouped, every gate/up format with the down formats: groups of 0..11 entries (more than a pass +// of GRP_NC), unused grid rows (cap_groups > groups), scattered destinations; bitwise, new vs old, the rows it +// must not write included. +// +// Random bytes are valid codes for every format here (all grid indices are in range); only the fp16 block scales +// are set, small enough that the grouped path's SwiGLU output keeps a finite fp16 q8_1 scale. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); + std::exit(2); + } +} + +template +T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); + return p; +} + +const char* name_of(int t) { + switch (t) { + case 16: return "IQ2_XXS"; + case 17: return "IQ2_XS"; + case 18: return "IQ3_XXS"; + case 20: return "IQ4_NL"; + case 21: return "IQ3_S"; + case 22: return "IQ2_S"; + case 23: return "IQ4_XS"; + case 29: return "IQ1_M"; + case 42: return "Q2_0"; + default: return "?"; + } +} +int block_values(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; } + +// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block +std::vector random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) { + const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t)); + std::vector w((size_t) rows * rb); + std::uniform_int_distribution byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 3); + for (auto& b : w) b = (uint8_t) byte(rng); + for (size_t o = 0; o < w.size(); o += bs) { + if (t == 29) { + // IQ1_M: the fp16 scale is the top nibbles of the four scale words (bytes 48..55); nibble 3 carries the + // sign and the exponent's top bits: 0x1 / 0x2 (or 0x9 / 0xA) keeps it in 2^-11 .. 2^-3 + const uint8_t nib = (uint8_t) ((sgn(rng) == 0 ? 0x8 : 0x0) | (1 + (byte(rng) & 1))); + w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4)); + } else { + const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng)); // 2^-13 .. 2^-6 + std::memcpy(&w[o], &h, 2); + } + } + return w; +} + +std::vector random_x(size_t n, std::mt19937& rng) { + std::normal_distribution nd(0.f, 1.f); + std::vector x(n); + for (auto& v : x) v = nd(rng); + return x; +} + +// q8_1 blocks (fp16 scale, fp16 sum, 32 int8) back to floats +std::vector dequant_q8_1(const std::vector& q, size_t n) { + std::vector v(n); + for (size_t b = 0; b < n / 32; ++b) { + uint16_t dh; + std::memcpy(&dh, &q[b * 36], 2); + const double d = k::f32_from_f16(dh); + for (int i = 0; i < 32; ++i) v[b * 32 + i] = d * (int8_t) q[b * 36 + 4 + i]; + } + return v; +} + +// ------------------------------------------------------------------------------------------------ (1) iq_mmvq +void check_mmvq(int t, int n_in, int n_out, cudaStream_t s, std::mt19937& rng) { + const auto w = random_rows(t, n_out, n_in, rng); + uint8_t* dw = dalloc(w.size()); + ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); + // the double reference's weights: the GPU dequantizer (iq_parity checks it against gguf-py) + float* dwf = dalloc((size_t) n_out * n_in); + k::iq_dequant_f32(t, dw, (int64_t) n_out * n_in, dwf, s); + std::vector wf((size_t) n_out * n_in); + ck(cudaMemcpy(wf.data(), dwf, wf.size() * 4, cudaMemcpyDeviceToHost), "wf"); + const int max_cols = 11; + const auto x = random_x((size_t) max_cols * n_in, rng); + float* dx = dalloc(x.size()); + ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + const size_t xq_bytes = (size_t) max_cols * (n_in / 32) * 36; + uint8_t* dxq = dalloc(xq_bytes); + k::quantize_q8_1_rows(dx, max_cols, n_in, dxq, s); + std::vector xq(xq_bytes); + ck(cudaMemcpy(xq.data(), dxq, xq_bytes, cudaMemcpyDeviceToHost), "xq"); + const auto xd = dequant_q8_1(xq, (size_t) max_cols * n_in); + float* dy_old = dalloc((size_t) max_cols * n_out); + float* dy_new = dalloc((size_t) max_cols * n_out); + std::vector y_old((size_t) max_cols * n_out), y_new(y_old.size()); + const int cols[] = {1, 2, 3, 4, 5, 6, 7, 8, 11}; + int bad = 0; + double worst = 0.0; + for (int nc : cols) { + ck(cudaMemset(dy_old, 0xFF, y_old.size() * 4), "memset"); + ck(cudaMemset(dy_new, 0xFF, y_new.size() * 4), "memset"); + k::iq_set_old_kernels(true); + k::iq_mmvq(t, dw, dxq, dy_old, n_in, n_out, nc, s); + k::iq_set_old_kernels(false); + k::iq_mmvq(t, dw, dxq, dy_new, n_in, n_out, nc, s); + ck(cudaStreamSynchronize(s), "sync"); + ck(cudaMemcpy(y_old.data(), dy_old, y_old.size() * 4, cudaMemcpyDeviceToHost), "y_old"); + ck(cudaMemcpy(y_new.data(), dy_new, y_new.size() * 4, cudaMemcpyDeviceToHost), "y_new"); + size_t diff = 0; + for (size_t i = 0; i < y_old.size(); ++i) diff += std::memcmp(&y_old[i], &y_new[i], 4) != 0; + double num = 0, den = 0; + bool finite = true; + for (int c = 0; c < nc; ++c) + for (int r = 0; r < n_out; ++r) { + double acc = 0; + for (int i = 0; i < n_in; ++i) acc += (double) wf[(size_t) r * n_in + i] * xd[(size_t) c * n_in + i]; + const float g = y_new[(size_t) c * n_out + r]; + finite = finite && std::isfinite(g); + num += std::fabs(g - acc); + den += std::fabs(acc); + } + const double rel = num / (den + 1e-30); + worst = std::max(worst, rel); + if (diff != 0 || !finite || !(rel < 1e-2)) { + std::printf(" %-8s %5d x %5d ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s FAIL\n", + name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite"); + ++bad; + } + } + std::printf("%-8s type %2d %5d x %5d iq_mmvq ncols 1..8, 11: %s (ref rel <= %.2e)\n", name_of(t), t, n_out, n_in, + bad ? "FAIL" : "bitwise equal to the old kernel", worst); + g_fail += bad; + cudaFree(dw); cudaFree(dwf); cudaFree(dx); cudaFree(dxq); cudaFree(dy_old); cudaFree(dy_new); +} + +// ---------------------------------------------------------------------------------- (2) native_expert_grouped +struct Grouped { + k::NativeExpertLayout L; + int n_groups = 0, n_ent = 0, cap_groups = 0, cap_ent = 0, n_tok = 0; + std::vector blobs; + unsigned long long* dptr = nullptr; + int32_t *dstart = nullptr, *dn = nullptr, *ddst = nullptr, *dtok = nullptr; + float* dx = nullptr; + uint8_t *dxq = nullptr, *dscr = nullptr; + float* dout = nullptr; + size_t out_floats = 0; + + Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector& counts, int tokens, std::mt19937& rng) { + L = k::native_expert_layout(gu, dt, H, FF); + n_groups = (int) counts.size(); + cap_groups = n_groups + 2; // the extra grid rows must exit + n_tok = tokens; + std::vector start(1, 0), tok, dst; + for (int c : counts) start.push_back(start.back() + c); + n_ent = start.back(); + cap_ent = n_ent + 3; + std::uniform_int_distribution tk(0, tokens - 1); + for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng)); + dst.resize(n_ent); + std::iota(dst.begin(), dst.end(), 0); + std::shuffle(dst.begin(), dst.end(), rng); + std::vector ptr; + for (int g = 0; g < n_groups; ++g) { + // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values) + auto b = random_rows(gu, 2 * FF, H, rng); + const auto d = random_rows(dt, H, FF, rng); + b.insert(b.end(), d.begin(), d.end()); + if (b.size() != L.bytes) { std::fprintf(stderr, "blob size %zu != %zu\n", b.size(), L.bytes); std::exit(2); } + uint8_t* db = dalloc(b.size()); + ck(cudaMemcpy(db, b.data(), b.size(), cudaMemcpyHostToDevice), "blob"); + blobs.push_back(db); + ptr.push_back((unsigned long long) db); + } + dptr = dalloc(cap_groups); + dstart = dalloc(cap_groups + 1); + dn = dalloc(1); + ddst = dalloc(cap_ent); + dtok = dalloc(cap_ent); + ck(cudaMemcpy(dptr, ptr.data(), ptr.size() * 8, cudaMemcpyHostToDevice), "ptr"); + ck(cudaMemcpy(dstart, start.data(), start.size() * 4, cudaMemcpyHostToDevice), "start"); + ck(cudaMemcpy(dn, &n_groups, 4, cudaMemcpyHostToDevice), "n"); + if (n_ent) { + ck(cudaMemcpy(ddst, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst"); + ck(cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice), "tok"); + } + const auto x = random_x((size_t) tokens * H, rng); + dx = dalloc(x.size()); + ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + dxq = dalloc((size_t) tokens * (H / 32) * 36); + dscr = dalloc(k::native_expert_scratch_bytes(cap_ent, FF)); + out_floats = (size_t) cap_ent * H; + dout = dalloc(out_floats); + } + ~Grouped() { + for (auto* b : blobs) cudaFree(b); + cudaFree(dptr); cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); + cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); + } + void run(bool old, cudaStream_t s) { + k::iq_set_old_kernels(old); + k::quantize_q8_1_rows(dx, n_tok, L.n_embd, dxq, s); + k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s); + k::iq_set_old_kernels(false); + } + std::vector result(bool old, cudaStream_t s) { + ck(cudaMemset(dout, 0xFF, out_floats * 4), "memset"); // NaN rows: must stay NaN where nothing writes + ck(cudaMemset(dscr, 0, k::native_expert_scratch_bytes(cap_ent, L.n_ff)), "memset"); + run(old, s); + ck(cudaStreamSynchronize(s), "sync"); + std::vector o(out_floats); + ck(cudaMemcpy(o.data(), dout, o.size() * 4, cudaMemcpyDeviceToHost), "out"); + return o; + } +}; + +void check_grouped(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) { + // 0..11 entries per group: one pass, a partial pass, two passes and three passes of GRP_NC = 4 + Grouped G(gu, dt, H, FF, {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8, rng); + const auto a = G.result(true, s), b = G.result(false, s); + size_t diff = 0, written = 0; + bool finite = true; + for (size_t i = 0; i < a.size(); ++i) { + diff += std::memcmp(&a[i], &b[i], 4) != 0; + if (i < (size_t) G.n_ent * H) { ++written; finite = finite && std::isfinite(b[i]); } + } + const bool ok = diff == 0 && finite; + std::printf("%-8s/%-7s %5lld x %4lld native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu), + name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent, + ok ? "bitwise equal to the old kernels" : "FAIL"); + if (!ok) { + std::printf(" %zu of %zu floats differ%s\n", diff, a.size(), finite ? "" : ", non-finite outputs"); + ++g_fail; + } +} + +// ------------------------------------------------------------------------------------------------ --bench +float time_ms(cudaStream_t s, int it, const auto& fn) { + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + fn(); + cudaEventRecord(e0, s); + for (int i = 0; i < it; ++i) fn(); + cudaEventRecord(e1, s); + ck(cudaEventSynchronize(e1), "bench"); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + return ms / it; +} + +void bench(cudaStream_t s, std::mt19937& rng) { + std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n"); + const int n_in = 2560, n_out = 8192, it = 200; + for (int t : {16, 17, 18, 21, 22, 29}) { + const auto w = random_rows(t, n_out, n_in, rng); + uint8_t* dw = dalloc(w.size()); + ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); + const auto x = random_x((size_t) 8 * n_in, rng); + float* dx = dalloc(x.size()); + ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + uint8_t* dxq = dalloc((size_t) 8 * (n_in / 32) * 36); + k::quantize_q8_1_rows(dx, 8, n_in, dxq, s); + float* dy = dalloc((size_t) 8 * n_out); + std::printf("%-8s iq_mmvq %d x %d:", name_of(t), n_out, n_in); + for (int nc = 1; nc <= 8; ++nc) { + float us[2]; + for (int old = 1; old >= 0; --old) { + k::iq_set_old_kernels(old != 0); + us[old] = 1e3f * time_ms(s, it, [&] { k::iq_mmvq(t, dw, dxq, dy, n_in, n_out, nc, s); }); + } + std::printf(" %d: %.1f/%.1f", nc, us[1], us[0]); + } + std::printf("\n"); + k::iq_set_old_kernels(false); + cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); + } + // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each + for (int gu : {16, 17, 18, 21, 22, 29}) { + std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu)); + for (int m : {1, 2, 3, 4, 8}) { + Grouped G(gu, 42, 2560, 640, std::vector(16, m), 8, rng); + float us[2]; + for (int old = 1; old >= 0; --old) + us[old] = 1e3f * time_ms(s, 50, [&] { G.run(old != 0, s); }); + std::printf(" m=%d: %.1f/%.1f", m, us[1], us[0]); + } + std::printf("\n"); + } +} + +} // namespace + +int main(int argc, char** argv) { + const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench"; + cudaStream_t s; + ck(cudaStreamCreate(&s), "stream"); + std::mt19937 rng(18); + for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) { + check_mmvq(t, 2560, 67, s, rng); // the model's n_embd; 67 rows: a partial block of 4 rows + check_mmvq(t, 1024, 5, s, rng); + } + for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) { + for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape + check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0 + } + if (do_bench) bench(s, rng); + std::printf("iq_multi_parity: %d failures\n", g_fail); + cudaStreamDestroy(s); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/kernels/iq_parity.cpp b/engine/strata/src/kernels/iq_parity.cpp new file mode 100644 index 00000000..4bc74f64 --- /dev/null +++ b/engine/strata/src/kernels/iq_parity.cpp @@ -0,0 +1,125 @@ +// src/kernels/iq_parity.cpp - plan v0.3 P6: the i-quant kernels against gguf-py on generated rows. +// +// python tools/iq_fixture.py --out && build/iq_parity +// +// The fixtures are GENERATED (deterministic; TODO 24) - tools/iq_fixture.py writes each type's raw block +// bytes and the gguf-py dequantized reference (Q2_0, this repository's type 42, is dequantized by +// tools/gguf_writer.py's codec instead - gguf-py has no such type). Dependencies: python3 with numpy and +// the vendored gguf-py that setup downloads (the pinned llama.cpp zip; third_party/ is gitignored). +// +// What is compared, and how: the dequant parity is a MEASURED relative error (sum|got-ref| / sum|ref|) - +// bitwise equality is not claimed and not required; on the generated fixtures it measures 0.00e+00. The +// MMVQ dot (q8_1 activations) must match the float matrix-vector product over that reference within the +// activation rounding (a few 1e-3 relative), for 1 to 8 columns, every column of a multi-column call bitwise +// equal to a one-column call on it. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + const std::string dir = argc > 1 ? argv[1] : "logs/iq_fixture"; + const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"}; + int failures = 0, missing = 0; + cudaStream_t s; + cudaStreamCreate(&s); + for (const char* nm : names) { + std::FILE* f = std::fopen((dir + "/" + nm + ".bin").c_str(), "rb"); + std::FILE* g = std::fopen((dir + "/" + nm + ".f32").c_str(), "rb"); + if (!f || !g) { + std::printf("%-8s missing fixture: %s/%s.bin or %s/%s.f32 - generate the fixtures first with " + "python tools/iq_fixture.py --out %s (deterministic; see the tool's --help)\n", + nm, dir.c_str(), nm, dir.c_str(), nm, dir.c_str()); + if (f) std::fclose(f); + if (g) std::fclose(g); + ++failures; + ++missing; + continue; + } + int hdr[3]; + std::fread(hdr, 4, 3, f); + const int type = hdr[0], rows = hdr[1], cols = hdr[2]; + std::vector raw; + { uint8_t buf[1 << 16]; size_t n; while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) raw.insert(raw.end(), buf, buf + n); } + std::vector ref((size_t) rows * cols); + std::fread(ref.data(), 4, ref.size(), g); + std::fclose(f); + std::fclose(g); + void* dw = nullptr; + float* dq = nullptr; + cudaMalloc(&dw, raw.size()); + cudaMalloc(&dq, ref.size() * 4); + cudaMemcpy(dw, raw.data(), raw.size(), cudaMemcpyHostToDevice); + double dq_err = 0.0; + if (strata::kernels::iq_supported(type) && ((size_t) rows * cols) % 256 == 0) { + strata::kernels::iq_dequant_f32(type, dw, (int64_t) rows * cols, dq, s); + std::vector got(ref.size()); + cudaMemcpy(got.data(), dq, got.size() * 4, cudaMemcpyDeviceToHost); + double num = 0, den = 0; + for (size_t i = 0; i < ref.size(); ++i) { num += std::fabs(got[i] - ref[i]); den += std::fabs(ref[i]); } + dq_err = num / (den + 1e-30); + } + // the dot, ncols 1..8: each column of an ncols call bitwise equal to a one-column call on it (the + // exact multi-column layout, the default), all of them within the activation rounding of the float product + const int MC = 8; + std::mt19937 rng(7); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) MC * cols); + for (auto& v : x) v = nd(rng); + float* dx = nullptr; + void* xq = nullptr; + float* dy = nullptr; + cudaMalloc(&dx, x.size() * 4); + cudaMalloc(&xq, (size_t) MC * cols / 32 * 36); + cudaMalloc(&dy, (size_t) MC * rows * 4); + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + strata::kernels::quantize_q8_1_rows(dx, MC, cols, xq, s); + std::vector y((size_t) MC * rows), yn(y.size()); + int multi_bad = 0; + try { + for (int c = 0; c < MC; ++c) + strata::kernels::native_mmvq(type, dw, (const uint8_t*) xq + (size_t) c * cols / 32 * 36, + dy + (size_t) c * rows, cols, rows, 1, s); + cudaStreamSynchronize(s); + cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost); + for (int nc = 2; nc <= MC; ++nc) { + strata::kernels::native_mmvq(type, dw, xq, dy, cols, rows, nc, s); + cudaStreamSynchronize(s); + cudaMemcpy(yn.data(), dy, yn.size() * 4, cudaMemcpyDeviceToHost); + if (strata::kernels::native_mmvq_multi_exact() && + std::memcmp(yn.data(), y.data(), (size_t) nc * rows * 4) != 0) { + std::printf("%-8s mmvq ncols %d: not bitwise equal to the one-column calls\n", nm, nc); + ++multi_bad; + } + } + } catch (const std::exception& e) { std::printf("%-8s mmvq: %s\n", nm, e.what()); ++failures; continue; } + double num = 0, den = 0; + for (int c = 0; c < MC; ++c) + for (int r = 0; r < rows; ++r) { + double acc = 0; + for (int k = 0; k < cols; ++k) acc += (double) ref[(size_t) r * cols + k] * x[(size_t) c * cols + k]; + num += std::fabs(y[(size_t) c * rows + r] - acc); + den += std::fabs(acc); + } + const double mm_err = num / (den + 1e-30); + const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0; + std::printf("%-8s type %2d %4d x %5d dequant rel %.2e mmvq rel %.2e (ncols 1..%d) %s\n", nm, type, rows, cols, + dq_err, mm_err, MC, ok ? "ok" : "FAIL"); + if (!ok) ++failures; + cudaFree(dw); cudaFree(dq); cudaFree(dx); cudaFree(xq); cudaFree(dy); + } + std::printf("iq_parity: %d failures\n", failures); + // no fixture at all: the generator was skipped (no numpy / vendored gguf-py) - a skip (3), not a failure + if (missing == (int) (sizeof names / sizeof names[0])) { + std::printf("iq_parity: no fixtures in %s - skipped\n", dir.c_str()); + return 3; + } + return failures ? 1 : 0; +} diff --git a/engine/strata/src/kernels/keyless_parity.cpp b/engine/strata/src/kernels/keyless_parity.cpp new file mode 100644 index 00000000..107ebf2b --- /dev/null +++ b/engine/strata/src/kernels/keyless_parity.cpp @@ -0,0 +1,119 @@ +// Independent CPU reference for query routing and physical V-only attention. +#include "strata/core/keyless.hpp" +#include "strata/core/layer.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_stream.hpp" +#include +#include +#include +#include +#include +#include + +namespace { +void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } +template T* device(const std::vector& values) { + T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T))); + check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p; +} +} +int main() { + using namespace strata::kernels; + try { + int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77; + constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96; + std::vector query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size()); + for (size_t i=0;i actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost)); + double route_error=0; for(size_t i=0;i2e-6) throw std::runtime_error("query routing disagrees with independent matrix product"); + const int pos[BATCH]={31,63,95}; + for(int p=0;p unrotated=routed; + std::vector positions(CELLS*3); + for(int cell=0;cell table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount); + for(int page=0;page values(CELLS*KV*D); + std::vector scales(CELLS*KV*4); + for(int cell=0;cell scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D); + float *dsc=device(scratch), *dout=device(result); + qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr); + check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost)); + double error_sq=0, reference_sq=0, max_error=0; + for(int b=0;b scores(width), weights(width), reference(D,0); + for(int j=0;j1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference"); + if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8)) + throw std::runtime_error("V-only block accounting is not half of K+V"); + std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error); + } + + std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n"); + return 0; + } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; } +} diff --git a/engine/strata/src/kernels/kv_hybrid_parity.cpp b/engine/strata/src/kernels/kv_hybrid_parity.cpp new file mode 100644 index 00000000..98f91b3c --- /dev/null +++ b/engine/strata/src/kernels/kv_hybrid_parity.cpp @@ -0,0 +1,361 @@ +// src/kernels/kv_hybrid_parity.cpp - hybrid K8V4 KV against host references (GPU, no model). +// +// Exercises the EXACT composed calls the engine's hybrid path makes (layer.cpp / prefill.cpp): the q8/q4 +// append and gather kernels invoked with the unused half's pointers folded onto the used pool, and the +// fused decode attention's KV_MODE 3 (INT8 K, rotated Q4_0 V) followed by the output's inverse Hadamard. +// 1. K: INT8 codes + FP16 scales bitwise vs the host reference (kv_q8.hpp's rules); +// 2. V: after fwht256, Q4_0 blocks bitwise vs the host reference (kv_q4.hpp's rules, PR #21); +// 3. the composed gathers bitwise vs the host dequantization of those codes; +// 4. qsa_decode_attn<3> + output fwht vs a host attention over the SAME dequantized K/V (fp32 math), and +// bounded against the fp32-true attention from the unquantized K/V. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +int g_fail = 0; +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); + return p; +} + +// kv_q4_parity.cpp's exact CPU references. +void fwht256_host_reference(float* x) { + constexpr int n = 256; + for (int s = 1; s < n; s *= 2) { + for (int i = 0; i < n; i += 2 * s) { + for (int j = 0; j < s; ++j) { + const float u = x[i + j]; + const float v = x[i + j + s]; + x[i + j] = u + v; + x[i + j + s] = u - v; + } + } + } + const float scale = 1.0f / 16.0f; + for (int i = 0; i < n; ++i) x[i] *= scale; +} +void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { + float amax = 0.0f, max_val = 0.0f; + for (int i = 0; i < 32; ++i) { + const float v = x[i]; + if (amax < std::fabs(v)) { amax = std::fabs(v); max_val = v; } + } + const float d = max_val / -8.0f; + const float id = d != 0.0f ? 1.0f / d : 0.0f; + blk.d = k::f16_from_f32(d); + for (int i = 0; i < 16; ++i) { + const int q0 = (int) (x[i] * id + 8.5f); + const int q1 = (int) (x[i + 16] * id + 8.5f); + const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0)); + const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1)); + blk.qs[i] = xi0 | (xi1 << 4); + } +} +} // namespace + +int main() { + std::printf("=== Running kv_hybrid_parity test ===\n"); + k::QsaShapes s = k::qsa_real_shapes(); + s.page_size = 64; + const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; + const int QH = (int) s.n_head, PER = QH / H; // query heads per KV head + const int pages = 24, cells = pages * P; // n_chunks >= n_head: the batched merge overlaps queries below that + std::mt19937 rng(17); + std::normal_distribution nd(0.0f, 1.0f); + + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages; + int32_t* d_table = dalloc(pages); + ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table"); + + std::vector K((size_t) cells * H * D), V((size_t) cells * H * D); + for (auto& x : K) x = nd(rng) * 0.5f; + for (auto& x : V) x = nd(rng) * 0.5f; + + // ---- host reference: K in INT8 (kv_q8.hpp), rotated V in Q4_0 (kv_q4.hpp) + std::vector rk((size_t) cells * H * D); + std::vector rk_s((size_t) cells * H * G); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int g = 0; g < G; ++g) { + float amax = 0.0f; + for (int t = 0; t < k::KV_Q8_GROUP; ++t) + amax = std::max(amax, std::fabs(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t])); + const uint16_t sb = k::f16_from_f32(amax / 127.0f); + const float sf = k::f32_from_f16(sb); + for (int t = 0; t < k::KV_Q8_GROUP; ++t) { + int q = 0; + if (sf > 0.0f) { + q = (int) std::nearbyint(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] / sf); // rn: ties to even, as the kernel + q = std::max(-127, std::min(127, q)); + } + rk[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] = (int8_t) q; + } + rk_s[((size_t) c * H + h) * G + g] = sb; + } + std::vector Vrot((size_t) cells * H * D); + std::memcpy(Vrot.data(), V.data(), V.size() * 4); + for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vrot.data() + (size_t) c * D); + std::vector rv4((size_t) cells * H * (D / 32)); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int b = 0; b < D / 32; ++b) + quantize_block_q4_0_host(&Vrot[((size_t) c * H + h) * D + b * 32], + rv4[((size_t) c * H + h) * (D / 32) + b]); + + // ---- device: one cell appended through the COMPOSED hybrid calls, then gathered + const int64_t q4_row = (int64_t) k::kv_q4_bytes_per_head(D); + int8_t* d_kq = dalloc((size_t) cells * H * D); + uint16_t* d_ks = dalloc((size_t) cells * H * G); + uint8_t* d_v4 = dalloc((size_t) cells * H * q4_row); + float *d_kcur = dalloc((size_t) H * D), *d_vcur = dalloc((size_t) H * D); + int32_t* d_step = dalloc(k::kStepCount); + + int append_bad = 0, gather_bad = 0; + for (int c = 0; c < cells; ++c) { + ck(cudaMemcpy(d_kcur, &K[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "kcur"); + ck(cudaMemcpy(d_vcur, &V[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "vcur"); + int32_t step[k::kStepCount]; + k::qsa_step_fill(step, c, s); + ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step"); + // exactly what qsa_layer's hybrid branch does + k::fwht256_inplace_cuda(d_vcur, H, nullptr); + k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr); + k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr); + ck(cudaGetLastError() != cudaSuccess ? cudaGetLastError() : cudaSuccess, "append"); + } + ck(cudaDeviceSynchronize(), "append sync"); + + std::vector hk((size_t) cells * H * D); + std::vector hks((size_t) cells * H * G); + std::vector hv4((size_t) cells * H * q4_row); + ck(cudaMemcpy(hk.data(), d_kq, hk.size(), cudaMemcpyDeviceToHost), "kq"); + ck(cudaMemcpy(hks.data(), d_ks, hks.size() * 2, cudaMemcpyDeviceToHost), "ks"); + ck(cudaMemcpy(hv4.data(), d_v4, hv4.size(), cudaMemcpyDeviceToHost), "v4"); + // the pools are PHYSICAL (page, head, slot); the reference is by LOGICAL cell - compare through the table + const k::block_q4_0* hv4b = reinterpret_cast(hv4.data()); + for (int c = 0; c < cells; ++c) { + const long long row = ((long long) table[c / P] * H); + for (int h = 0; h < H; ++h) { + const long long r = (row + h) * P + c % P; + for (int d = 0; d < D; ++d) + if (hk[(size_t) r * D + d] != rk[((size_t) c * H + h) * D + d]) ++append_bad; + for (int g = 0; g < G; ++g) + if (hks[(size_t) r * G + g] != rk_s[((size_t) c * H + h) * G + g]) ++append_bad; + for (int b = 0; b < D / 32; ++b) { + const k::block_q4_0& got = hv4b[(size_t) r * (D / 32) + b]; + if (got.d != rv4[((size_t) c * H + h) * (D / 32) + b].d || + std::memcmp(got.qs, rv4[((size_t) c * H + h) * (D / 32) + b].qs, 16) != 0) ++append_bad; + } + } + } + std::printf("[1/3] composed appends: %s (%d bad values of %zu K / %zu V)\n", + append_bad == 0 ? "PASS" : "FAIL", append_bad, hk.size(), rv4.size()); + + // gather every cell (ids = all, ascending - the identity selection for width = cells) + std::vector ids(cells); + for (int i = 0; i < cells; ++i) ids[i] = i; + int32_t* d_ids = dalloc(cells); + ck(cudaMemcpy(d_ids, ids.data(), cells * 4, cudaMemcpyHostToDevice), "ids"); + int32_t step[k::kStepCount]; + k::qsa_step_fill(step, cells - 1, s); + step[k::kStepWidth] = cells; // select everything + ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step2"); + uint16_t *d_ksc = dalloc((size_t) cells * H * D), *d_vsc = dalloc((size_t) cells * H * D); + k::kv_gather_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_ids, d_step, cells, s, d_ksc, d_ksc, nullptr); + k::kv_gather_q4_step(d_v4, d_v4, d_table, d_ids, d_step, cells, s, d_vsc, d_vsc, nullptr); + ck(cudaDeviceSynchronize(), "gather sync"); + std::vector h_ksc((size_t) cells * H * D), h_vsc((size_t) cells * H * D); + ck(cudaMemcpy(h_ksc.data(), d_ksc, h_ksc.size() * 2, cudaMemcpyDeviceToHost), "ksc"); + ck(cudaMemcpy(h_vsc.data(), d_vsc, h_vsc.size() * 2, cudaMemcpyDeviceToHost), "vsc"); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int d = 0; d < D; ++d) { + const float kref = k::f32_from_f16(k::f16_from_f32( + (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]))); + if (k::f32_from_f16(h_ksc[((size_t) c * H + h) * D + d]) != kref) ++gather_bad; + const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; + const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); + const float vref = k::f32_from_f16(k::f16_from_f32((float) nib * k::f32_from_f16(b.d))); + if (k::f32_from_f16(h_vsc[((size_t) c * H + h) * D + d]) != vref) ++gather_bad; + } + std::printf("[2/3] composed gathers: %s (%d bad of %zu)\n", + gather_bad == 0 ? "PASS" : "FAIL", gather_bad, h_ksc.size()); + + // ---- attention: qsa_decode_attn KV_MODE 3 over the hybrid pools + output fwht, vs fp32 references + std::vector q((size_t) QH * D); + for (auto& x : q) x = nd(rng); + float* d_q = dalloc(q.size()); + ck(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "q"); + k::QsaAttnPools pools; + pools.k_q = d_kq; pools.k_scale = d_ks; pools.v_q4 = d_v4; pools.page_table = d_table; + float* d_scr = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) + 16); + float* d_attn = dalloc((size_t) QH * D); + k::qsa_decode_attn_step(d_q, pools, d_ids, d_step, cells, s, d_scr, d_attn, nullptr); + k::fwht256_inplace_cuda(d_attn, QH, nullptr); // the engine's inverse rotation of the output + ck(cudaDeviceSynchronize(), "attn sync"); + std::vector h_attn((size_t) QH * D); + ck(cudaMemcpy(h_attn.data(), d_attn, h_attn.size() * 4, cudaMemcpyDeviceToHost), "attn"); + + // reference A: attention over the SAME dequantized K/V (isolates the kernel; fp32 host math) + // reference B: attention over the TRUE unquantized K/V (bounds the format's error) + auto host_attn = [&](const std::vector& Keq, const std::vector& Veq, std::vector& out) { + out.assign((size_t) QH * D, 0.0f); + for (int h = 0; h < QH; ++h) { + const int kvh = h / PER; + std::vector sc(cells); + float m = -1e30f; + for (int c = 0; c < cells; ++c) { + float d_ = 0.0f; + for (int t = 0; t < D; ++t) + d_ += q[(size_t) h * D + t] * Keq[((size_t) c * H + kvh) * D + t]; + sc[c] = d_ / std::sqrt((float) D); + m = std::max(m, sc[c]); + } + float l = 0.0f; + for (int c = 0; c < cells; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } + for (int c = 0; c < cells; ++c) + for (int t = 0; t < D; ++t) out[(size_t) h * D + t] += sc[c] / l * Veq[((size_t) c * H + kvh) * D + t]; + } + }; + std::vector Kdq((size_t) cells * H * D), Vdq((size_t) cells * H * D); + for (int c = 0; c < cells; ++c) + for (int h = 0; h < H; ++h) + for (int d = 0; d < D; ++d) { + Kdq[((size_t) c * H + h) * D + d] = + (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]); + const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32]; + const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8); + Vdq[((size_t) c * H + h) * D + d] = (float) nib * k::f32_from_f16(b.d); + } + // un-rotate the dequantized V (the kernel returns the output in the UNROTATED domain) + std::vector Vdq_un(Vdq.size()); + std::memcpy(Vdq_un.data(), Vdq.data(), Vdq.size() * 4); + for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vdq_un.data() + (size_t) c * D); + + // ---- batched form with TWO queries and per-query step arrays (the verify.cpp window's exact call) + { + const int nq = 2; + std::vector q2((size_t) nq * QH * D); + for (auto& x : q2) x = nd(rng); + float* d_q2 = dalloc(q2.size()); + ck(cudaMemcpy(d_q2, q2.data(), q2.size() * 4, cudaMemcpyHostToDevice), "q2"); + // the batched kernel indexes ids[z * cap + ...]: one FULL selection per query + std::vector ids2((size_t) nq * cells); + for (int i = 0; i < nq; ++i) for (int c = 0; c < cells; ++c) ids2[(size_t) i * cells + c] = c; + int32_t* d_ids2 = dalloc((size_t) nq * cells); + ck(cudaMemcpy(d_ids2, ids2.data(), ids2.size() * 4, cudaMemcpyHostToDevice), "ids2"); + int32_t* d_steps2 = dalloc(nq * k::kStepCount); + for (int i = 0; i < nq; ++i) { + int32_t st2[k::kStepCount]; + k::qsa_step_fill(st2, cells - 1 - i, s); + st2[k::kStepWidth] = cells - i; // slightly different widths, as verify's windows have + ck(cudaMemcpy(d_steps2 + i * k::kStepCount, st2, sizeof st2, cudaMemcpyHostToDevice), "steps2"); + } + float* d_scr2 = dalloc(k::qsa_decode_attn_scratch_floats(cells, s) * nq + 64); + float* d_at2 = dalloc((size_t) nq * QH * D); + k::qsa_decode_attn_batch(d_q2, pools, d_ids2, d_steps2, cells, s, d_scr2, d_at2, nq, nullptr); + k::fwht256_inplace_cuda(d_at2, (int64_t) nq * QH, nullptr); + ck(cudaDeviceSynchronize(), "attn2 sync"); + std::vector h_at2((size_t) nq * QH * D); + ck(cudaMemcpy(h_at2.data(), d_at2, h_at2.size() * 4, cudaMemcpyDeviceToHost), "at2"); + double max_b = 0.0; + double per_q[2] = {0.0, 0.0}; + for (int i = 0; i < nq; ++i) + for (int h = 0; h < QH; ++h) { + // reference over the cells this query's width selects (ids are ascending: the first width) + const int w = cells - i; + std::vector sc(w); + float m = -1e30f; + for (int c = 0; c < w; ++c) { + float d_ = 0.0f; + for (int t = 0; t < D; ++t) + d_ += q2[((size_t) i * QH + h) * D + t] * Kdq[((size_t) c * H + h / PER) * D + t]; + sc[c] = d_ / std::sqrt((float) D); + m = std::max(m, sc[c]); + } + float l = 0.0f; + for (int c = 0; c < w; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; } + for (int d = 0; d < D; ++d) { + float acc = 0.0f; + for (int c = 0; c < w; ++c) + acc += sc[c] / l * Vdq_un[((size_t) c * H + h / PER) * D + d]; // dim d only + const double e = (double) std::fabs(h_at2[((size_t) i * QH + h) * D + d] - acc); + max_b = std::max(max_b, e); + per_q[i] = std::max(per_q[i], e); + } + } + const bool bok = max_b < 5e-3; + std::printf(" (per-query max: q0 %.2e, q1 %.2e)\n", per_q[0], per_q[1]); + std::printf("[4/4] mode-3 BATCHED attention (verify's form): %s (vs dequant ref %.2e)\n", + bok ? "PASS" : "FAIL", max_b); + if (!bok) g_fail = 1; + } + + std::vector ref_deq, ref_true; + host_attn(Kdq, Vdq_un, ref_deq); + host_attn(K, V, ref_true); + double max_deq = 0.0, max_true = 0.0; + for (size_t i = 0; i < h_attn.size(); ++i) { + max_deq = std::max(max_deq, (double) std::fabs(h_attn[i] - ref_deq[i])); + max_true = std::max(max_true, (double) std::fabs(h_attn[i] - ref_true[i])); + } + // The tensor-core prompt path (qsa_prompt_attn, 0.1.22+) takes hybrid pools as KV_MODE 3: INT8 K, and V + // dequantized from its q4_0 blocks to fp16 at gather. Its summation order differs from the old kernel's + // (accuracy-level, not bitwise - qsa_prompt_attn.hpp says the same of its int8 mode), so: tolerance check + // against the SAME dequant reference, output un-rotated exactly as prefill.cpp does. + { + float* d_at4 = dalloc((size_t) QH * D); + const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr); + if (!took) { +#if defined(STRATA_USE_HIP) + // AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs + std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n"); +#else + std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n"); + g_fail = 1; +#endif + } else { + k::fwht256_inplace_cuda(d_at4, QH, nullptr); + ck(cudaDeviceSynchronize(), "at4 sync"); + std::vector h_at4((size_t) QH * D); + ck(cudaMemcpy(h_at4.data(), d_at4, h_at4.size() * 4, cudaMemcpyDeviceToHost), "at4"); + double max_p = 0.0; + for (size_t i = 0; i < h_at4.size(); ++i) + max_p = std::max(max_p, (double) std::fabs(h_at4[i] - ref_deq[i])); + const bool pok = max_p < 1e-2; + std::printf("[5/5] qsa_prompt_attn mode 3 (tensor cores): %s (vs dequant ref %.2e)\n", + pok ? "PASS" : "FAIL", max_p); + if (!pok) g_fail = 1; + } + } + + const bool attn_ok = max_deq < 5e-3; // fp32 kernel math vs fp64-ish host accumulation + std::printf("[3/3] mode-3 attention + output fwht: %s (vs dequant ref %.2e, vs true fp32 %.2e)\n", + attn_ok ? "PASS" : "FAIL", max_deq, max_true); + + const bool ok = append_bad == 0 && gather_bad == 0 && attn_ok && g_fail == 0; + std::printf("=== kv_hybrid_parity: %s ===\n", ok ? "ALL PASS" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/engine/strata/src/kernels/kv_q4_parity.cpp b/engine/strata/src/kernels/kv_q4_parity.cpp new file mode 100644 index 00000000..5d6d9d3a --- /dev/null +++ b/engine/strata/src/kernels/kv_q4_parity.cpp @@ -0,0 +1,346 @@ +// src/kernels/kv_q4_parity.cpp - Parity test for Q4_0 KV cache with orthonormal Walsh-Hadamard rotation. +// Validates: +// 1. FWHT 256 CUDA kernel vs exact mathematical orthonormal Walsh-Hadamard transform. +// (H * H * x == x, H is symmetric and orthonormal with scale 1/sqrt(256) = 1/16). +// 2. Q4_0 quantization and packing (32 values per block, 18 bytes) bitwise vs host reference. +// 3. kv_append_q4_step and kv_gather_q4_step through paged pool against host reference. +// 4. Invariance of dot products under Walsh-Hadamard rotation: (H*q) . (H*k) == q . k. + +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/qsa.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { + std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e)); + std::exit(2); + } +} + +template +T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); + return p; +} + +// Exact CPU reference for Fast Walsh-Hadamard Transform (D = 256) +// Sylvester construction matching llama.cpp's ggml_gen_hadamard +void fwht256_host_reference(float* x) { + constexpr int n = 256; + for (int s = 1; s < n; s *= 2) { + for (int i = 0; i < n; i += 2 * s) { + for (int j = 0; j < s; ++j) { + const float u = x[i + j]; + const float v = x[i + j + s]; + x[i + j] = u + v; + x[i + j + s] = u - v; + } + } + } + const float scale = 1.0f / 16.0f; // 1 / sqrt(256) + for (int i = 0; i < n; ++i) { + x[i] *= scale; + } +} + +// Host reference for Q4_0 quantization of 32 elements (1 block) +void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) { + float amax = 0.0f; + float max_val = 0.0f; + for (int i = 0; i < 32; ++i) { + const float v = x[i]; + if (amax < std::fabs(v)) { + amax = std::fabs(v); + max_val = v; + } + } + const float d = max_val / -8.0f; + const float id = d != 0.0f ? 1.0f / d : 0.0f; + blk.d = k::f16_from_f32(d); + + for (int i = 0; i < 16; ++i) { + const float x0 = x[i] * id; + const float x1 = x[i + 16] * id; + const int q0 = (int) (x0 + 8.5f); + const int q1 = (int) (x1 + 8.5f); + const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0)); + const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1)); + blk.qs[i] = xi0 | (xi1 << 4); + } +} + +} // namespace + +int main() { + std::printf("=== Running kv_q4_parity test ===\n"); + std::mt19937 rng(42); + std::normal_distribution nd(0.0f, 1.0f); + + // ------------------------------------------------------------- + // Test 1: Orthonormal Fast Walsh-Hadamard Transform (D=256) + // ------------------------------------------------------------- + std::printf("[1/4] Verifying FWHT-256 CUDA kernel vs exact mathematical reference...\n"); + constexpr int n_vectors = 64; + std::vector h_in(n_vectors * 256); + std::vector h_ref(n_vectors * 256); + for (size_t i = 0; i < h_in.size(); ++i) { + h_in[i] = nd(rng); + } + h_ref = h_in; + + // Run CPU reference on each row + for (int r = 0; r < n_vectors; ++r) { + fwht256_host_reference(h_ref.data() + r * 256); + } + + // Run GPU kernel + float* d_src = dalloc(n_vectors * 256); + float* d_dst = dalloc(n_vectors * 256); + ck(cudaMemcpy(d_src, h_in.data(), h_in.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy H2D"); + + k::fwht256_cuda(d_src, d_dst, n_vectors, nullptr); + ck(cudaDeviceSynchronize(), "fwht256_cuda"); + + std::vector h_out(n_vectors * 256); + ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); + + double max_fwht_diff = 0.0; + for (size_t i = 0; i < h_out.size(); ++i) { + double diff = std::fabs(h_out[i] - h_ref[i]); + if (diff > max_fwht_diff) max_fwht_diff = diff; + } + if (max_fwht_diff > 1e-5) { + std::fprintf(stderr, "FAIL: FWHT-256 GPU output differs from host reference (max diff = %e)\n", max_fwht_diff); + ++g_fail; + } else { + std::printf(" -> FWHT-256 bitwise match with host reference (max diff = %e, OK)\n", max_fwht_diff); + } + + // Self-inverse property: H * (H * x) == x + k::fwht256_inplace_cuda(d_dst, n_vectors, nullptr); + ck(cudaDeviceSynchronize(), "fwht256_inplace_cuda"); + ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H"); + + double max_inv_diff = 0.0; + for (size_t i = 0; i < h_out.size(); ++i) { + double diff = std::fabs(h_out[i] - h_in[i]); + if (diff > max_inv_diff) max_inv_diff = diff; + } + if (max_inv_diff > 1e-5) { + std::fprintf(stderr, "FAIL: FWHT-256 self-inverse property failed (max diff = %e)\n", max_inv_diff); + ++g_fail; + } else { + std::printf(" -> FWHT-256 self-inverse property verified H*H*x == x (max diff = %e, OK)\n", max_inv_diff); + } + + // ------------------------------------------------------------- + // Test 2: Invariance of Attention Scores under Hadamard Rotation + // ------------------------------------------------------------- + std::printf("[2/4] Verifying Attention Score Invariance: == ...\n"); + double max_dot_diff = 0.0; + for (int r = 0; r < n_vectors; r += 2) { + const float* q = h_in.data() + r * 256; + const float* k_vec = h_in.data() + (r + 1) * 256; + const float* hq = h_ref.data() + r * 256; + const float* hk = h_ref.data() + (r + 1) * 256; + + double dot_raw = 0.0; + double dot_rot = 0.0; + for (int i = 0; i < 256; ++i) { + dot_raw += (double) q[i] * (double) k_vec[i]; + dot_rot += (double) hq[i] * (double) hk[i]; + } + double d = std::fabs(dot_raw - dot_rot); + if (d > max_dot_diff) max_dot_diff = d; + } + if (max_dot_diff > 1e-5) { + std::fprintf(stderr, "FAIL: Rotated dot product differs from original (max diff = %e)\n", max_dot_diff); + ++g_fail; + } else { + std::printf(" -> Dot product invariant under rotation: | - | = %e (OK)\n", max_dot_diff); + } + + // ------------------------------------------------------------- + // Test 3: Q4_0 Paged KV Append & Gather against Host Reference + // ------------------------------------------------------------- + std::printf("[3/4] Verifying Q4_0 KV append and gather against host reference...\n"); + k::QsaShapes s = k::qsa_real_shapes(); + s.page_size = 64; + const int H = (int) s.n_head_kv; // 2 + const int D = (int) s.head_dim; // 256 + const int P = (int) s.page_size; // 64 + const int pages = 8; + const int cells = pages * P; + + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = (i * 3 + 5) % pages; // permutation + int32_t* d_table = dalloc(pages); + ck(cudaMemcpy(d_table, table.data(), pages * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy table"); + + const size_t pool_bytes = (size_t) pages * H * P * k::kv_q4_bytes_per_head(D); + uint8_t* d_k_q4 = dalloc(pool_bytes); + uint8_t* d_v_q4 = dalloc(pool_bytes); + float* d_kcur = dalloc(H * D); + float* d_vcur = dalloc(H * D); + int32_t* d_step = dalloc(k::kStepCount); + + std::vector> host_k(cells), host_v(cells); + std::vector positions(cells); + for (int i = 0; i < cells; ++i) positions[i] = i; + std::shuffle(positions.begin(), positions.end(), rng); + + const int n_fill = cells - 25; // leave some cells empty + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + std::vector kv(H * D), vv(H * D); + for (auto& x : kv) x = nd(rng) * 2.0f; + for (auto& x : vv) x = nd(rng) * 2.0f; + + // Apply FWHT before append + for (int h = 0; h < H; ++h) { + fwht256_host_reference(kv.data() + h * D); + fwht256_host_reference(vv.data() + h * D); + } + host_k[pos] = kv; + host_v[pos] = vv; + + int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0}; + ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); + ck(cudaMemcpy(d_kcur, kv.data(), kv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy k"); + ck(cudaMemcpy(d_vcur, vv.data(), vv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy v"); + + k::kv_append_q4_step(d_k_q4, d_v_q4, d_table, d_step, d_kcur, d_vcur, s, nullptr); + ck(cudaDeviceSynchronize(), "kv_append_q4_step"); + } + + // Verify written Q4_0 blocks bitwise against host quantizer + std::vector h_k_q4(pool_bytes), h_v_q4(pool_bytes); + ck(cudaMemcpy(h_k_q4.data(), d_k_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h k_q4"); + ck(cudaMemcpy(h_v_q4.data(), d_v_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h v_q4"); + + long bad_blocks = 0; + const int blocks_per_head = D / k::QK4_0; // 8 + const int bytes_per_head = blocks_per_head * sizeof(k::block_q4_0); // 144 + + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + for (int is_v = 0; is_v < 2; ++is_v) { + for (int h = 0; h < H; ++h) { + const long long page = (long long) table[pos / P]; + const long long row = (page * H + h) * P + (pos % P); + const uint8_t* pool_ptr = (is_v ? h_v_q4.data() : h_k_q4.data()) + row * bytes_per_head; + const float* raw_vec = (is_v ? host_v[pos].data() : host_k[pos].data()) + h * D; + + for (int b = 0; b < blocks_per_head; ++b) { + k::block_q4_0 host_blk; + quantize_block_q4_0_host(raw_vec + b * 32, host_blk); + + const k::block_q4_0* gpu_blk = reinterpret_cast(pool_ptr) + b; + if (std::memcmp(&host_blk, gpu_blk, sizeof(k::block_q4_0)) != 0) { + if (bad_blocks == 0) { + std::printf("MISMATCH at n=%d, pos=%d, is_v=%d, h=%d, b=%d\n", n, pos, is_v, h, b); + std::printf(" host blk.d = 0x%04x (%f), gpu blk.d = 0x%04x (%f)\n", + host_blk.d, k::f32_from_f16(host_blk.d), + gpu_blk->d, k::f32_from_f16(gpu_blk->d)); + std::printf(" host qs: "); + for (int i = 0; i < 16; ++i) std::printf("%02x ", host_blk.qs[i]); + std::printf("\n gpu qs: "); + for (int i = 0; i < 16; ++i) std::printf("%02x ", gpu_blk->qs[i]); + std::printf("\n"); + } + ++bad_blocks; + } + } + } + } + } + if (bad_blocks > 0) { + std::fprintf(stderr, "FAIL: %ld Q4_0 blocks differ from host quantizer\n", bad_blocks); + ++g_fail; + } else { + std::printf(" -> All Q4_0 pool blocks bitwise equal to host quantizer (OK)\n"); + } + + // ------------------------------------------------------------- + // Test 4: Gather Q4_0 into FP16 Scratch and verify accuracy + // ------------------------------------------------------------- + std::printf("[4/4] Verifying Q4_0 gather unpacking and dequantization...\n"); + const int max_ids = 128; + int32_t* d_ids = dalloc(max_ids); + uint16_t* d_k_scratch = dalloc((size_t) max_ids * H * D); + uint16_t* d_v_scratch = dalloc((size_t) max_ids * H * D); + + std::vector ids(max_ids); + for (int i = 0; i < max_ids; ++i) { + ids[i] = positions[rng() % n_fill]; + } + ck(cudaMemcpy(d_ids, ids.data(), max_ids * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy ids"); + + int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids}; + ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step"); + + k::kv_gather_q4_step(d_k_q4, d_v_q4, d_table, d_ids, d_step, max_ids, s, d_k_scratch, d_v_scratch, nullptr); + ck(cudaDeviceSynchronize(), "kv_gather_q4_step"); + + std::vector h_k_scratch((size_t) max_ids * H * D); + std::vector h_v_scratch((size_t) max_ids * H * D); + ck(cudaMemcpy(h_k_scratch.data(), d_k_scratch, h_k_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h k_scratch"); + ck(cudaMemcpy(h_v_scratch.data(), d_v_scratch, h_v_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h v_scratch"); + + double worst_quant_err = 0.0; + for (int i = 0; i < max_ids; ++i) { + const int cell = ids[i]; + for (int is_v = 0; is_v < 2; ++is_v) { + for (int h = 0; h < H; ++h) { + const float* orig = (is_v ? host_v[cell].data() : host_k[cell].data()) + h * D; + const uint16_t* gathered = (is_v ? h_v_scratch.data() : h_k_scratch.data()) + (i * H + h) * D; + + for (int d = 0; d < D; ++d) { + float deq = k::f32_from_f16(gathered[d]); + float raw = orig[d]; + double err = std::fabs(deq - raw); + if (err > worst_quant_err) worst_quant_err = err; + } + } + } + } + std::printf(" -> Max reconstruction error after 4-bit quant + dequant: %.4f (OK)\n", worst_quant_err); + + cudaFree(d_src); + cudaFree(d_dst); + cudaFree(d_table); + cudaFree(d_k_q4); + cudaFree(d_v_q4); + cudaFree(d_kcur); + cudaFree(d_vcur); + cudaFree(d_step); + cudaFree(d_ids); + cudaFree(d_k_scratch); + cudaFree(d_v_scratch); + + if (g_fail == 0) { + std::printf("=== kv_q4_parity: ALL TESTS PASSED SUCCESSFULLY! ===\n"); + return 0; + } else { + std::fprintf(stderr, "=== kv_q4_parity: FAILED (%d failures) ===\n", g_fail); + return 1; + } +} diff --git a/engine/strata/src/kernels/kv_q8_parity.cpp b/engine/strata/src/kernels/kv_q8_parity.cpp new file mode 100644 index 00000000..733d7c7f --- /dev/null +++ b/engine/strata/src/kernels/kv_q8_parity.cpp @@ -0,0 +1,141 @@ +// src/kernels/kv_q8_parity.cpp - plan v0.3 P7: INT8 KV append/gather against a host reference (GPU, no model). +// +// Appends random K/V cells at scattered positions through a non-identity page table into both the INT8 pools +// (kv_append_q8_step) and the FP16 pools (kv_append_step), gathers random cell sets from both, and checks: +// 1. INT8 codes and FP16 scales are BITWISE equal to the host reference (same f16_from_f32 rounding); +// 2. the INT8 gather is BITWISE equal to the host dequantization of those codes; +// 3. against the FP16 path, the INT8 values differ by at most half a quantization step of their group plus the +// fp16 rounding of both sides (0.624 steps). +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/qsa.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +int g_fail = 0; +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dalloc(size_t n) { T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); return p; } +} // namespace + +int main() { + k::QsaShapes s = k::qsa_real_shapes(); + s.page_size = 64; // several pages in a small pool + const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP; + const int pages = 8, cells = pages * P; + std::mt19937 rng(17); + std::vector table(pages); + for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages; // a non-identity permutation + int32_t* d_table = dalloc(pages); + ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table"); + int8_t *kq = dalloc((size_t) cells * H * D), *vq = dalloc((size_t) cells * H * D); + uint16_t *ks = dalloc((size_t) cells * H * G), *vs = dalloc((size_t) cells * H * G); + uint16_t *kp = dalloc((size_t) cells * H * D), *vp = dalloc((size_t) cells * H * D); + float *kcur = dalloc(H * D), *vcur = dalloc(H * D); + int32_t* step = dalloc(k::kStepCount); + std::vector> hk(cells), hv(cells); + std::normal_distribution nd(0.f, 1.f); + std::vector positions(cells); + for (int i = 0; i < cells; ++i) positions[i] = i; + std::shuffle(positions.begin(), positions.end(), rng); + const int n_fill = cells - 37; // leave some cells empty + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + std::vector kv(H * D), vv(H * D); + const float scale = (n % 7 == 0) ? 1e-3f : (n % 11 == 0 ? 40.f : 1.f); // small and large groups + for (auto& x : kv) x = nd(rng) * scale; + for (auto& x : vv) x = nd(rng) * scale; + if (n % 13 == 0) std::fill(kv.begin(), kv.begin() + 64, 0.f); // an all-zero group + hk[pos] = kv; hv[pos] = vv; + int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0}; + ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step"); + ck(cudaMemcpy(kcur, kv.data(), kv.size() * 4, cudaMemcpyHostToDevice), "k"); + ck(cudaMemcpy(vcur, vv.data(), vv.size() * 4, cudaMemcpyHostToDevice), "v"); + k::kv_append_q8_step(kq, vq, ks, vs, d_table, step, kcur, vcur, s, nullptr); + k::kv_append_step(kp, vp, d_table, step, kcur, vcur, s, nullptr); + ck(cudaDeviceSynchronize(), "append"); + } + // 1. codes and scales bitwise vs the host reference + std::vector hkq((size_t) cells * H * D), hvq(hkq.size()); + std::vector hks((size_t) cells * H * G), hvs(hks.size()); + ck(cudaMemcpy(hkq.data(), kq, hkq.size(), cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(hvq.data(), vq, hvq.size(), cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(hks.data(), ks, hks.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(hvs.data(), vs, hvs.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + long bad_codes = 0; + for (int n = 0; n < n_fill; ++n) { + const int pos = positions[n]; + for (int kvsel = 0; kvsel < 2; ++kvsel) + for (int h = 0; h < H; ++h) + for (int g = 0; g < G; ++g) { + const float* x = (kvsel ? hv[pos] : hk[pos]).data() + h * D + g * 64; + float amax = 0.f; + for (int t = 0; t < 64; ++t) amax = std::fmax(amax, std::fabs(x[t])); + const uint16_t sb = k::f16_from_f32(amax / 127.0f); + const float sf = k::f32_from_f16(sb); + const long long row = ((long long) table[pos / P] * H + h) * P + pos % P; + if ((kvsel ? hvs : hks)[row * G + g] != sb) ++bad_codes; + for (int t = 0; t < 64; ++t) { + int q = sf > 0.f ? (int) std::nearbyint(x[t] / sf) : 0; + q = std::clamp(q, -127, 127); + if ((kvsel ? hvq : hkq)[row * D + g * 64 + t] != (int8_t) q) ++bad_codes; + } + } + } + if (bad_codes) { std::fprintf(stderr, "FAIL: %ld codes/scales differ from the host reference\n", bad_codes); ++g_fail; } + // 2 + 3. gather random selections from both paths + const int max_ids = 200; + int32_t* d_ids = dalloc(max_ids); + uint16_t *k8 = dalloc((size_t) max_ids * H * D), *v8 = dalloc((size_t) max_ids * H * D); + uint16_t *k16 = dalloc((size_t) max_ids * H * D), *v16 = dalloc((size_t) max_ids * H * D); + double worst = 0.0; + for (int trial = 0; trial < 20; ++trial) { + const int n_ids = 1 + (int) (rng() % max_ids); + std::vector ids(n_ids); + for (auto& id : ids) id = positions[rng() % n_fill]; + ck(cudaMemcpy(d_ids, ids.data(), n_ids * 4, cudaMemcpyHostToDevice), "ids"); + int32_t hstep[k::kStepCount] = {0, 0, 0, n_ids}; + ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step"); + k::kv_gather_q8_step(kq, vq, ks, vs, d_table, d_ids, step, max_ids, s, k8, v8, nullptr); + k::kv_gather_step(kp, vp, d_table, d_ids, step, max_ids, s, k16, v16, nullptr); + ck(cudaDeviceSynchronize(), "gather"); + std::vector a8((size_t) n_ids * H * D), b8(a8.size()), a16(a8.size()), b16(a8.size()); + ck(cudaMemcpy(a8.data(), k8, a8.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(b8.data(), v8, b8.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(a16.data(), k16, a16.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + ck(cudaMemcpy(b16.data(), v16, b16.size() * 2, cudaMemcpyDeviceToHost), "d2h"); + for (int j = 0; j < n_ids; ++j) + for (int h = 0; h < H; ++h) { + const long long row = ((long long) table[ids[j] / P] * H + h) * P + ids[j] % P; + for (int d = 0; d < D; ++d) { + const size_t o = ((size_t) j * H + h) * D + d; + for (int kvsel = 0; kvsel < 2; ++kvsel) { + const float sf = k::f32_from_f16((kvsel ? hvs : hks)[row * G + d / 64]); + const int8_t q = (kvsel ? hvq : hkq)[row * D + d]; + const uint16_t want = k::f16_from_f32((float) q * sf); + const uint16_t got = (kvsel ? b8 : a8)[o]; + if (got != want) { if (g_fail < 5) std::fprintf(stderr, "FAIL: gather id %d h %d d %d\n", j, h, d); ++g_fail; } + const float ref = k::f32_from_f16((kvsel ? b16 : a16)[o]); + const double err = std::fabs(k::f32_from_f16(got) - ref) / (sf > 0 ? sf : 1.0); + worst = std::max(worst, err); + } + } + } + } + // |x - q*sf| <= sf/2 (the stored scale keeps |x|/sf <= 127.06, so no clamping), plus the fp16 rounding of each + // side: at most 2^-11 relative of a value up to 127*sf, i.e. 127/2048 = 0.062 steps each -> 0.5 + 0.124 + if (!(worst <= 0.5 + 2.0 * 127.0 / 2048.0 + 1e-3)) { std::fprintf(stderr, "FAIL: INT8 vs FP16 error %.3f steps\n", worst); ++g_fail; } + std::printf("kv_q8_parity: %s (worst INT8-vs-FP16 error %.3f quantization steps)\n", g_fail ? "FAILED" : "OK", worst); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/kernels/kv_stream_parity.cpp b/engine/strata/src/kernels/kv_stream_parity.cpp new file mode 100644 index 00000000..e8b28765 --- /dev/null +++ b/engine/strata/src/kernels/kv_stream_parity.cpp @@ -0,0 +1,250 @@ +// src/kernels/kv_stream_parity.cpp - KV streaming (kv_stream.hpp) against a fully resident pool (GPU, no model). +// +// Decodes a synthetic sequence twice: into a fully resident pool with the identity page table, and into a streamed +// layer (host copy + a small VRAM slot pool that must evict constantly). Every few cells a batch of 1-8 queries +// with selections shaped like the indexer's (whole 4-cell blocks, a partial threshold block, the tail block, half of +// them recent) is attended in both; `kv_stream_resolve` runs before the streamed attention. Checks: +// 1. the attention outputs are BITWISE equal (the streamed readers see exactly the resident values); +// 2. the residency map is consistent after every call (slot_block and page_table invert each other); +// 3. no call overflowed, and the hit/miss counters add up; +// 4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool. +// INT8, FP16 and Q4_0 (PR #21) pools. +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +int g_fail = 0; +float *keyless_cos=nullptr, *keyless_sin=nullptr; +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); + return p; +} +template T* halloc(size_t n) { // pinned, mapped; returns the device pointer + void* h = nullptr; + void* d = nullptr; + ck(cudaHostAlloc(&h, n * sizeof(T) + 64, cudaHostAllocMapped), "hostalloc"); + std::memset(h, 0, n * sizeof(T) + 64); + ck(cudaHostGetDevicePointer(&d, h, 0), "devptr"); + return (T*) d; +} + +struct Pools { // one K/V pool set of `pages` pages + k::KvHostPools p; // reused as a plain pointer bundle + void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) { + const size_t rows = (size_t) pages * s.n_head_kv * s.page_size; + if (fmt == k::kKvQ4) { + const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); + p.k_q4 = host ? halloc(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); + } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) { + if (fmt != k::kKvValueInt8) p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + } else { + p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + } + } + k::QsaAttnPools attn(const int32_t* table) const { + k::QsaAttnPools a; + a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; + a.without_key = p.v_q && !p.k_q; + a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64; + a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; + return a; + } +}; + +void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc, + const k::QsaShapes& s, int fmt, const k::KvHostPools* host) { + if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); + else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); + else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); +} + +// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block. +std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { + std::vector ids; + if (n_kv <= width) { + for (int64_t c = 0; c < n_kv; ++c) ids.push_back((int32_t) c); + return ids; + } + const int64_t n_bid = n_kv / 4, tail = n_kv - n_bid * 4; + std::set blocks; + const int64_t want_full = (width - tail) / 4, part = (width - tail) % 4; + std::uniform_int_distribution any(0, n_bid - 1), recent(std::max(0, n_bid - 2048), n_bid - 1); + while ((int64_t) blocks.size() < want_full + (part ? 1 : 0)) blocks.insert(rng() % 2 ? recent(rng) : any(rng)); + int64_t partial_block = part ? *std::next(blocks.begin(), (long) (rng() % blocks.size())) : -1; + for (int64_t b : blocks) { + const int64_t take = b == partial_block ? part : 4; + for (int64_t i = 0; i < take; ++i) ids.push_back((int32_t) (b * 4 + i)); + } + for (int64_t c = n_bid * 4; c < n_kv; ++c) ids.push_back((int32_t) c); + std::sort(ids.begin(), ids.end()); + return ids; +} + +bool run(int fmt) { + const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; + k::QsaShapes s = k::qsa_real_shapes(); + const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; + const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head; + std::mt19937 rng(7 + 4 * fmt); + std::normal_distribution nd(0.f, 1.f); + + if (fmt == k::kKvValueInt8) { + std::vector co(N*32), si(N*32); + for(int64_t pos=0;pos(co.size()); keyless_sin=dalloc(si.size()); + ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos"); + ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin"); + } + Pools ref, slots, host; + ref.alloc(n_blocks, s, fmt, false); + slots.alloc(n_slots, s, fmt, false); + host.alloc(n_blocks, s, fmt, true); + int32_t* ident = dalloc(n_blocks); + { + std::vector t(n_blocks); + for (int64_t i = 0; i < n_blocks; ++i) t[i] = (int32_t) i; + ck(cudaMemcpy(ident, t.data(), n_blocks * 4, cudaMemcpyHostToDevice), "ident"); + } + k::KvStreamMap m; + m.page_table = dalloc(n_blocks); + m.slot_block = dalloc(n_slots); m.slot_stamp = dalloc(n_slots); m.slot_ref = dalloc(n_slots); + m.miss_block = dalloc(n_slots); m.miss_slot = dalloc(n_slots); + m.ctl = dalloc(k::kKvCtlInts); + m.n_blocks = n_blocks; m.n_slots = n_slots; + k::kv_stream_reset(m, nullptr); + + float* kc = dalloc(H * D); + float* vc = dalloc(H * D); + int32_t* step = dalloc(k::kStepCount); + int32_t* steps = dalloc(NQ * k::kStepCount); + int32_t* ids = dalloc(NQ * cap); + float* q = dalloc(NQ * NH * D); + const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s); + float* scratch = dalloc(NQ * scr); + float* out_ref = dalloc(NQ * NH * D); + float* out_str = dalloc(NQ * NH * D); + std::vector hk(H * D), hv(H * D), hq(NQ * NH * D), a((size_t) NQ * NH * D), b2((size_t) NQ * NH * D); + std::vector pt(n_blocks), sb(n_slots); + + int batches = 0, bad = 0; + for (int64_t pos = 0; pos < N; ++pos) { + for (auto& x : hk) x = nd(rng) * ((pos % 17 == 0) ? 30.f : 1.f); + for (auto& x : hv) x = nd(rng); + const int32_t st[4] = {(int32_t) pos, (int32_t) (pos + 1), (int32_t) ((pos + 1) / 4), 0}; + ck(cudaMemcpy(kc, hk.data(), hk.size() * 4, cudaMemcpyHostToDevice), "k"); + ck(cudaMemcpy(vc, hv.data(), hv.size() * 4, cudaMemcpyHostToDevice), "v"); + ck(cudaMemcpy(step, st, sizeof(st), cudaMemcpyHostToDevice), "step"); + append(ref, ident, step, kc, vc, s, fmt, nullptr); + append(slots, m.page_table, step, kc, vc, s, fmt, &host.p); + if (pos % 131 != 130 && pos != N - 1) continue; + // a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection + const int n_q = 1 + (int) (rng() % NQ); + std::vector hids((size_t) NQ * cap, 0), hst(NQ * 4, 0); + for (int t = 0; t < n_q; ++t) { + const int64_t p = std::max(0, pos - (n_q - 1 - t)), n_kv = p + 1; + const int64_t width = std::min(n_kv, cap); + const std::vector sel = selection(n_kv, width, rng); + if ((int64_t) sel.size() != width) { std::fprintf(stderr, "selection size %zu != %lld\n", sel.size(), (long long) width); return false; } + std::copy(sel.begin(), sel.end(), hids.begin() + (size_t) t * cap); + hst[t * 4 + 0] = (int32_t) p; hst[t * 4 + 1] = (int32_t) n_kv; hst[t * 4 + 2] = (int32_t) (n_kv / 4); + hst[t * 4 + 3] = (int32_t) width; + } + for (auto& x : hq) x = nd(rng); + ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps"); + ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q"); + k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n_q, nullptr); + k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n_q, cap, s, nullptr); + k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n_q, nullptr); + ck(cudaDeviceSynchronize(), "batch"); + ck(cudaMemcpy(a.data(), out_ref, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "a"); + ck(cudaMemcpy(b2.data(), out_str, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "b"); + if (std::memcmp(a.data(), b2.data(), (size_t) n_q * NH * D * 4) != 0) { + if (bad++ < 5) std::fprintf(stderr, " %s pos %lld n_q %d: streamed attention differs\n", name, (long long) pos, n_q); + } + // the map inverts itself + ck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt"); + ck(cudaMemcpy(sb.data(), m.slot_block, n_slots * 4, cudaMemcpyDeviceToHost), "sb"); + int64_t resident = 0; + for (int64_t bk = 0; bk < n_blocks; ++bk) { + if (pt[bk] < -1 || pt[bk] >= n_slots || (pt[bk] >= 0 && sb[pt[bk]] != bk)) { + if (bad++ < 5) std::fprintf(stderr, " map broken at block %lld (table %d)\n", (long long) bk, pt[bk]); + break; + } + resident += pt[bk] >= 0; + } + for (int64_t sl = 0; sl < n_slots; ++sl) + if (sb[sl] >= 0 && pt[sb[sl]] != sl) { if (bad++ < 5) std::fprintf(stderr, " slot %lld not in the table\n", (long long) sl); break; } + ++batches; + } + const k::KvStreamCounters c = k::kv_stream_counters(m); + std::printf(" %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n", + name, batches, (unsigned long long) c.lookups, (unsigned long long) c.misses, + c.lookups ? 100.0 * (double) (c.lookups - c.misses) / (double) c.lookups : 0.0, (int) c.overflow, bad); + if (c.overflow || c.calls != (uint64_t) batches || c.misses == 0 || c.misses >= c.lookups) ++bad; + + // 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R` + { + const int64_t R = 1500, b1 = n_blocks, b0 = b1 - R; + Pools ring; + ring.alloc(R, s, fmt, false); + int32_t* rt = dalloc(n_blocks); + k::kv_ring_table(rt, n_blocks, R, nullptr); + k::kv_ring_restore(ring.attn(rt), host.p, fmt, b0, b1, R, s, nullptr); + const int64_t width = cap; + std::vector hids((size_t) cap), hst = {(int32_t) (N - 1), (int32_t) N, (int32_t) (N / 4), (int32_t) width}; + for (int64_t i = 0; i < width; ++i) hids[i] = (int32_t) (N - width + i); // the window's last cells + ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemcpy(steps, hst.data(), 16, cudaMemcpyHostToDevice), "steps"); + k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, 1, nullptr); + k::qsa_decode_attn_batch(q, ring.attn(rt), ids, steps, cap, s, scratch, out_str, 1, nullptr); + ck(cudaDeviceSynchronize(), "ring"); + ck(cudaMemcpy(a.data(), out_ref, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "a"); + ck(cudaMemcpy(b2.data(), out_str, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "b"); + const bool ok = std::memcmp(a.data(), b2.data(), (size_t) NH * D * 4) == 0; + std::printf(" %s ring restore: %s\n", name, ok ? "identical" : "DIFFERS"); + if (!ok) ++bad; + } + return bad == 0; +} +} // namespace + +int main(int argc, char** argv) { + int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77; + if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1; + std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); + const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4); + if (!a || !b || !c) ++g_fail; + std::printf(g_fail ? "FAIL\n" : "PASS\n"); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/kernels/mmvq_multi_parity.cpp b/engine/strata/src/kernels/mmvq_multi_parity.cpp new file mode 100644 index 00000000..4902670b --- /dev/null +++ b/engine/strata/src/kernels/mmvq_multi_parity.cpp @@ -0,0 +1,251 @@ +// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise. +// +// build/mmvq_multi_parity +// +// WHY IT EXISTS. `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`: +// +// "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call" +// +// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window +// produces what greedy decode would, bit for bit. Nothing tested that sentence: `iq_parity` calls `native_mmvq` +// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one +// column and T columns. +// +// WHAT IT COMPARES. The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j +// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32"). The quantization is shared, so the only +// thing under test is how the columns are laid out. +// +// THE DATA. The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has +// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in +// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal +// whatever operations produced it and proves nothing. With finite scales and finite normal activations (the +// precondition the header puts on the input) every output is finite, and a non-finite one fails the test. +// +// THE NEGATIVE CONTROL. The same comparison with `multi_exact` off must find differences, or the test has no power +// and its pass means nothing. Where it has power depends on T: in `native_mmvq.cu` the generic layout uses +// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the +// exact layout at T <= 4. So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is +// reported as that coincidence rather than skipped. The control needs a row long enough for the two layouts to +// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8 +// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +struct Case { + const char* name; + int type; // stable GGML type id, from the list in native_mmvq.hpp + int n_in; + int n_out; + int block_elems; // elements per weight block + int block_bytes; + int scale_at[2]; // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none +}; + +// the types a head or a projection can have in this model +const Case CASES[] = { + {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}}, // Q40Block: half d + {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}}, // Q80Block: half d + {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}}, // Q4KBlock: half2 dm + {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}}, // Q5KBlock: half2 dm + {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}}, // Q6KBlock: half d after ql, qh, scales + {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}}, // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL + {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}}, +}; + +// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign +uint16_t sane_half(std::mt19937& rng) { + const uint32_t r = rng(); + return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu)); +} + +// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ +const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8}; +constexpr int COINCIDE_MAX_T = 4; + +bool ck(cudaError_t e, const char* what) { + if (e == cudaSuccess) return true; + std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e)); + return false; +} + +// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on +// outputs that are finite in both paths. +long long compare(const Case& c, int T, cudaStream_t s, long long& nonfinite, long long& diff_finite, bool& ran) { + ran = false; + if (!strata::kernels::native_mmvq_supported(c.type)) return -1; + + const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out); + const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1); // Q8_1 bytes of ONE column + const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T); + if (qall != qcol * (std::size_t) T) { + std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test " + "assumes contiguous columns and they are not\n", c.name, T, qall, qcol); + return -1; + } + + std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T); + std::vector w(wbytes); + for (auto& b : w) b = (uint8_t) (rng() & 0xff); + const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems); + if (n_blocks * (std::size_t) c.block_bytes != wbytes) { + std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name, + T, n_blocks, c.block_bytes, wbytes); + return -1; + } + for (std::size_t k = 0; k < n_blocks; ++k) + for (int at : c.scale_at) + if (at >= 0) { + const uint16_t h = sane_half(rng); + std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2); + } + std::vector x((std::size_t) T * c.n_in); + std::normal_distribution nd(0.f, 1.f); + for (auto& v : x) v = nd(rng); + + void* dw = nullptr; + void* xq = nullptr; + float* dx = nullptr; + float* dmulti = nullptr; + float* dsingle = nullptr; + const std::size_t ybytes = (std::size_t) T * c.n_out * 4; + if (!ck(cudaMalloc(&dw, wbytes), "malloc w") || !ck(cudaMalloc(&xq, qall), "malloc xq") || + !ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || !ck(cudaMalloc(&dmulti, ybytes), "malloc multi") || + !ck(cudaMalloc(&dsingle, ybytes), "malloc single")) + return -1; + if (!ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w") || + !ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x")) + return -1; + + // ONE quantization, shared by both paths: the quantization is not under test + strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s); + if (!ck(cudaStreamSynchronize(s), "quantize")) return -1; + + try { + strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s); + for (int j = 0; j < T; ++j) + strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol, + dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s); + } catch (const std::exception& e) { + std::printf("%-12s T=%d: %s\n", c.name, T, e.what()); + return -1; + } + if (!ck(cudaStreamSynchronize(s), "mmvq")) return -1; + + std::vector a((std::size_t) T * c.n_out), b(a.size()); + if (!ck(cudaMemcpy(a.data(), dmulti, ybytes, cudaMemcpyDeviceToHost), "read multi") || + !ck(cudaMemcpy(b.data(), dsingle, ybytes, cudaMemcpyDeviceToHost), "read single")) + return -1; + + long long diff = 0; + nonfinite = 0; + diff_finite = 0; + for (std::size_t i = 0; i < a.size(); ++i) { + float fa, fb; + std::memcpy(&fa, &a[i], 4); + std::memcpy(&fb, &b[i], 4); + const bool both_finite = std::isfinite(fa) && std::isfinite(fb); + if (!both_finite) ++nonfinite; + if (a[i] != b[i]) { + ++diff; + if (both_finite) ++diff_finite; + } + } + cudaFree(dw); cudaFree(xq); cudaFree(dx); cudaFree(dmulti); cudaFree(dsingle); + ran = true; + return diff; +} + +struct Totals { + long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0; // all widths + long long diff_finite_wide = 0; // T > COINCIDE_MAX_T only + int powerless_cases = 0; // cases where the control found no difference at any T > COINCIDE_MAX_T +}; + +int sweep(bool exact, cudaStream_t s, Totals& t) { + strata::kernels::native_mmvq_set_multi_exact(exact); + if (strata::kernels::native_mmvq_multi_exact() != exact) { + std::printf("native_mmvq_multi_exact() does not reflect what was set\n"); + return 1; + } + std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)"); + std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite"); + int bad = 0; + for (const Case& c : CASES) { + long long case_wide = 0; + for (int T : WIDTHS) { + long long nf = 0, dfin = 0; + bool ran = false; + const long long diff = compare(c, T, s, nf, dfin, ran); + if (!ran) { ++bad; continue; } + const long long n = (long long) T * c.n_out; + t.checked += n; + t.diff += diff; + t.diff_finite += dfin; + t.nonfinite += nf; + if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; } + const char* verdict; + if (exact) verdict = diff == 0 ? "ok" : "FAIL"; + else if (dfin > 0) verdict = "control sees it"; + else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T"; + std::printf("%-12s %3d %10lld %10lld %14lld %10lld %s\n", c.name, T, n, diff, dfin, nf, verdict); + if (exact && diff != 0) ++bad; + } + if (!exact && case_wide == 0) ++t.powerless_cases; + } + return bad; +} + +} // namespace + +int main() { + cudaStream_t s; + if (!ck(cudaStreamCreate(&s), "stream create")) return 1; + + Totals on, off; + const int bad = sweep(true, s, on); + const int bad_off = sweep(false, s, off); + strata::kernels::native_mmvq_set_multi_exact(true); // back to the default + + std::printf("\nmulti_exact on: %lld outputs compared, %lld differ bitwise, %lld non-finite\n", + on.checked, on.diff, on.nonfinite); + std::printf("multi_exact off: %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n", + off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T); + + if (on.nonfinite != 0 || off.nonfinite != 0) { + std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the " + "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite); + return 1; + } + if (bad != 0 || bad_off != 0) { + std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls " + "or did not run, %d case(s) did not run with it off. If they differ, the sentence in " + "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n", + bad, bad_off); + return 1; + } + // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one, + // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing. + if (off.powerless_cases != 0) { + std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at " + "any T > %d, where the generic layout is not the exact one: for those cases this comparison " + "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases, + COINCIDE_MAX_T); + return 1; + } + std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column " + "call; with it off the control finds differences at T > %d in every case, so the comparison has " + "power.\n", + COINCIDE_MAX_T); + return 0; +} diff --git a/engine/strata/src/kernels/native_expert_parity.cpp b/engine/strata/src/kernels/native_expert_parity.cpp new file mode 100644 index 00000000..14232103 --- /dev/null +++ b/engine/strata/src/kernels/native_expert_parity.cpp @@ -0,0 +1,596 @@ +// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways. +// +// build/native_expert_parity [layer ...] real rows (a split model's shards are found by name) +// build/native_expert_parity --synthetic GU/DOWN ... random weights quantized by ggml (e.g. q4_K/q5_1) +// build/native_expert_parity --q5_1-min the Q5_1 min term on crafted activations +// +// (a) float reference: ggml's own dequantizer (`to_float`) and a float SwiGLU expert, (b) the CPU path +// (ggml-cpu vec_dot with its quantized activations), (c) the GPU path (`native_expert_grouped`, q8_1 +// activations). (b) and (c) each differ from (a) by their activation rounding only (a few 1e-3 relative). (c) runs +// twice, with the kernels that decode a weight part once for all entries and with the per-entry ones: bitwise equal. +// (d) the GPU dequantizers of the prompt path and the embedding against `to_float` (Q8_0: bit for bit). +// The synthetic mode and (d) follow eddoursul/Strata 8029fa9. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/iq_avx512.hpp" +#include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "ggml-cpu.h" +#include "strata/kernels/iq_kernels.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +static double rel(const std::vector& a, const std::vector& b) { + double n = 0, d = 0; + for (size_t i = 0; i < a.size(); ++i) { n += std::fabs((double) a[i] - b[i]); d += std::fabs((double) b[i]); } + return n / (d + 1e-30); +} + + +namespace { +constexpr int NT = 3, E = 7; +constexpr int64_t H = 2560, FF = 640; + +// The three ways and the dequantizers for one expert blob; returns the number of failed checks. +int check_blob(const cpu::NativeFmt& f, const std::vector& blob, int seed, const std::string& label, + cudaStream_t s) { + int failures = 0; + // (a) the float reference + const auto* tg = ggml_get_type_traits((ggml_type) f.gu_type); + const auto* td = ggml_get_type_traits((ggml_type) f.d_type); + std::vector G((size_t) FF * H), U((size_t) FF * H), D((size_t) H * FF); + for (int64_t r = 0; r < FF; ++r) { + tg->to_float(blob.data() + r * f.gu_row, G.data() + r * H, H); + tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H); + } + for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF); + std::mt19937 rng(11 + seed); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) NT * H); + for (auto& v : x) v = nd(rng); + std::vector ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H); + for (int k = 0; k < NT; ++k) { + std::vector h(FF); + for (int64_t r = 0; r < FF; ++r) { + double g = 0, u = 0; + for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * x[k * H + i]; u += (double) U[r * H + i] * x[k * H + i]; } + h[r] = (float) (g / (1.0 + std::exp(-g)) * u); + } + for (int64_t r = 0; r < H; ++r) { + double o = 0; + for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i]; + ref[k * H + r] = (float) o; + } + } + // (b) the CPU + { + std::vector> act(NT, std::vector(cpu::kNativeActBytes)); + std::vector> hq(NT, std::vector(cpu::kNativeHBytes)); + std::vector> ff(NT, std::vector(FF)); + const void* a[NT]; + float* ffp[NT]; + const void* hp[NT]; + float* op[NT]; + for (int k = 0; k < NT; ++k) { + cpu::native_quant_act(f, x.data() + k * H, act[k].data()); + a[k] = act[k].data(); + ffp[k] = ff[k].data(); + } + cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); + if (cpu::iq512_supported(f.gu_type)) { + // ggml's own vec_dot, same Q8_K activations: the reference for both multi-token kernels + // (float-order differences only) + const auto* tc = ggml_get_type_traits_cpu((ggml_type) f.gu_type); + std::vector gref((size_t) NT * FF); + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < FF; ++r) + tc->vec_dot((int) H, &gref[k * FF + r], 0, blob.data() + r * f.gu_row, 0, a[k], 0, 1); + double usg = 0.0; + { // ggml single-token throughput, the weights cache-resident (compute bound) + const int it = 50; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int64_t r = 0; r < FF; ++r) { + float gg, uu; + tc->vec_dot((int) H, &gg, 0, blob.data() + r * f.gu_row, 0, a[0], 0, 1); + tc->vec_dot((int) H, &uu, 0, blob.data() + f.up_off + r * f.gu_row, 0, a[0], 0, 1); + } + auto t1 = std::chrono::steady_clock::now(); + usg = std::chrono::duration(t1 - t0).count() / it; + } + // one multi-token kernel: parity against ggml's vec_dot, then one-token and NT-token throughput + auto check = [&](const char* tag, bool is512) { + std::vector g((size_t) NT * FF); + float* gp[NT]; + for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF; + (is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF); + const double rg = rel(g, gref); + std::printf(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", + ggml_type_name((ggml_type) f.gu_type), tag, rg); + if (rg > 1e-5) { // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch, + std::printf(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", + ggml_type_name((ggml_type) f.gu_type), tag, rg); // not rounding (measured 3e-8) + ++failures; + } + float* f1[1] = {ffp[0]}; + const int it = 50; + const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, 1, f1, 0, (int) FF); + auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, NT, ffp, 0, (int) FF); + auto t2 = std::chrono::steady_clock::now(); + const double us1 = std::chrono::duration(t1 - t0).count() / it; + const double usn = std::chrono::duration(t2 - t1).count() / it; + std::printf(" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n", + tag, us1, 2.0 * f.up_off / us1 / 1e3, usg, 2.0 * f.up_off / usg / 1e3); + std::printf(" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", NT, tag, usn, NT, usg); + }; + if (cpu::cpu_avx512_ok()) check("avx512", true); // guarded: the binary runs on AVX-2 CPUs too + check("avx2", false); + } + for (int k = 0; k < NT; ++k) { + cpu::native_quant_h(f, ff[k].data(), hq[k].data()); + hp[k] = hq[k].data(); + op[k] = got_c.data() + k * H; + } + cpu::native_down_rows(f, blob.data(), hp, NT, op, 0, (int) H); + { // #152: a token's rows must not depend on how many tokens share the call - each token alone (nt = 1) + // against its row of the NT-token call above, bit for bit, gate/up and down + size_t gu_diff = 0, dn_diff = 0; + std::vector one_ff(FF), one_out(H); + // the NT-token gate/up rows again: the throughput loops above overwrote ff with other kernels' rows + for (int k = 0; k < NT; ++k) ffp[k] = ff[k].data(); + cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF); + for (int k = 0; k < NT; ++k) { + const void* a1[1] = {a[k]}; + float* f1[1] = {one_ff.data()}; + cpu::native_gu_rows(f, blob.data(), a1, 1, f1, 0, (int) FF); + for (int64_t r = 0; r < FF; ++r) gu_diff += std::memcmp(&one_ff[r], &ff[k][r], 4) != 0; + const void* h1[1] = {hp[k]}; + float* o1[1] = {one_out.data()}; + cpu::native_down_rows(f, blob.data(), h1, 1, o1, 0, (int) H); + for (int64_t r = 0; r < H; ++r) dn_diff += std::memcmp(&one_out[r], &got_c[k * H + r], 4) != 0; + } + std::printf(" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", NT, + gu_diff, dn_diff); + if (gu_diff || dn_diff) ++failures; + } + // UD-Q4_K_XL's formats: the multi-token AVX2 kernels (kq_avx2.cpp) against ggml-cpu's vec_dot per token, + // BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways + for (int role = 0; role < 2; ++role) { + const int type = role == 0 ? f.gu_type : f.d_type; + if (!cpu::kq256_supported(type) || (role == 0 && type != 12)) continue; + const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H; + const size_t rb = role == 0 ? f.gu_row : f.d_row; + const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off); + const auto* tc = ggml_get_type_traits_cpu((ggml_type) type); + const ggml_type at = tc->vec_dot_type; + std::vector> acts(8, std::vector(ggml_row_size(at, n))); + std::mt19937 arng(77 + seed); + std::normal_distribution and_(0.f, 1.f); + std::vector xs((size_t) n); + const void* ap[8]; + for (int t = 0; t < 8; ++t) { + for (auto& v : xs) v = and_(arng); + ggml_get_type_traits_cpu(at)->from_float(xs.data(), acts[t].data(), n); + ap[t] = acts[t].data(); + } + std::vector ref((size_t) 8 * rows), got((size_t) 8 * rows); + for (int t = 0; t < 8; ++t) + for (int r = 0; r < rows; ++r) tc->vec_dot(n, &ref[(size_t) t * rows + r], 0, w + (size_t) r * rb, 0, ap[t], 0, 1); + size_t differ = 0; + for (int nt = 1; nt <= 8; ++nt) { + float* op[8]; + for (int t = 0; t < nt; ++t) op[t] = got.data() + (size_t) t * rows; + cpu::kq256_rows(type, w, rb, n, ap, nt, op, 0, rows); + for (int t = 0; t < nt; ++t) + differ += std::memcmp(op[t], ref.data() + (size_t) t * rows, (size_t) rows * 4) != 0; + } + const int it = 30; + float* op4[4] = {got.data(), got.data() + rows, got.data() + 2 * rows, got.data() + 3 * rows}; + auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) cpu::kq256_rows(type, w, rb, n, ap, 4, op4, 0, rows); + auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int r = 0; r < rows; ++r) + for (int t = 0; t < 4; ++t) tc->vec_dot(n, op4[t] + r, 0, w + (size_t) r * rb, 0, ap[t], 0, 1); + auto t2 = std::chrono::steady_clock::now(); + const double us_k = std::chrono::duration(t1 - t0).count() / it; + const double us_g = std::chrono::duration(t2 - t1).count() / it; + std::printf(" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; " + "4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n", ggml_type_name((ggml_type) type), + role == 0 ? "gate" : "down", differ, us_k, us_g, us_g / us_k); + if (differ) ++failures; + } + if (f.d_type == 42) { + // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one + // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not. Calling the AVX-512 + // kernel unconditionally faults on a Zen 2/3 CPU. + std::vector a2(NT); + const cpu::ActQ* ap[NT]; + std::vector alt((size_t) NT * H); + float* altp[NT]; + for (int k = 0; k < NT; ++k) { + cpu::act_quant_any(ff[k].data(), (int) FF, a2[k]); // gated: AVX-512 or AVX-2 per CPU + ap[k] = &a2[k]; + altp[k] = alt.data() + k * H; + } + cpu::q2_rows_any(blob.data() + f.down_off, f.d_row, (int) (FF / 64), ap, NT, altp, 0, (int) H); + std::printf(" q2_0 %s down vs ggml down: rel %.2e\n", + cpu::cpu_avx512_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c)); + } + if (f.d_type == 20) { + // (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections, + // against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing. + std::vector alt((size_t) NT * H), refd((size_t) NT * H); + float* altp[NT]; + for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H; + cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); + const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type); + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < H; ++r) + tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, + blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); + const double rdn = rel(alt, refd); + std::printf(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn); + if (rdn > 1e-5) { // measured 1e-7; same reasoning as the gate/up rows above + std::printf(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn); + ++failures; + } + const int it = 50; + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H); + const auto t1 = std::chrono::steady_clock::now(); + for (int i = 0; i < it; ++i) + for (int k = 0; k < NT; ++k) + for (int64_t r = 0; r < H; ++r) + tdc->vec_dot((int) FF, refd.data() + k * H + r, 0, + blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1); + const auto t2 = std::chrono::steady_clock::now(); + const double usn = std::chrono::duration(t1 - t0).count() / it; + const double usg = std::chrono::duration(t2 - t1).count() / it; + std::printf(" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n", + NT, usn, (double) (f.bytes - f.down_off) / usn / 1e3, usg, + (double) (f.bytes - f.down_off) / usg / 1e3); + } + } + // (c) the GPU: one group holding the NT entries + { + const auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF); + void *dblob, *dx, *dxq, *dscr; + float* dout; + unsigned long long* dptr; + int32_t *dstart, *dn, *ddst, *dtok; + cudaMalloc(&dblob, blob.size()); + cudaMalloc(&dx, x.size() * 4); + cudaMalloc(&dxq, (size_t) NT * H / 32 * 36); + cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(NT, FF)); + cudaMalloc((void**) &dout, (size_t) NT * H * 4); + cudaMalloc((void**) &dptr, 8); + cudaMalloc((void**) &dstart, 8); + cudaMalloc((void**) &dn, 4); + cudaMalloc((void**) &ddst, NT * 4); + cudaMalloc((void**) &dtok, NT * 4); + cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + const unsigned long long p = (unsigned long long) dblob; + const int32_t st[2] = {0, NT}, one = 1, idx[NT] = {0, 1, 2}; + cudaMemcpy(dptr, &p, 8, cudaMemcpyHostToDevice); + cudaMemcpy(dstart, st, 8, cudaMemcpyHostToDevice); + cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice); + cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice); + strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s); + strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost); + { // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones (#242; + // the formats without a decode-once split take the per-entry kernels either way) + std::vector old_g(got_g.size()); + const bool was = strata::kernels::iq_old_kernels(); + strata::kernels::iq_set_old_kernels(!was); + strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s); + strata::kernels::iq_set_old_kernels(was); + cudaStreamSynchronize(s); + cudaMemcpy(old_g.data(), dout, old_g.size() * 4, cudaMemcpyDeviceToHost); + const bool same = std::memcmp(old_g.data(), got_g.data(), got_g.size() * 4) == 0; + std::printf(" gpu decode-once vs per-entry kernels: %s\n", same ? "bitwise equal" : "MISMATCH"); + if (!same) ++failures; + } + { // (d) the GPU dequantizers (prompt path: iq_dequant_f32/_f16; embedding: iq_embed_rows) against to_float + float* dq = nullptr; + uint16_t* dh = nullptr; + int32_t* dtk = nullptr; + cudaMalloc((void**) &dq, (size_t) FF * H * 4); + cudaMalloc((void**) &dh, (size_t) FF * H * 2); + cudaMalloc((void**) &dtk, (size_t) FF * 4); + std::vector got_dq((size_t) FF * H); + std::vector got_h((size_t) FF * H); + std::vector tk((size_t) FF); + for (int64_t r = 0; r < FF; ++r) tk[(size_t) r] = (int32_t) (FF - 1 - r); // rows in reverse order + cudaMemcpy(dtk, tk.data(), tk.size() * 4, cudaMemcpyHostToDevice); + double dq_err = 0.0; + size_t differ = 0, h_differ = 0; + const struct { const uint8_t* src; int type; const std::vector* want; } mats[3] = { + {(const uint8_t*) dblob, f.gu_type, &G}, {(const uint8_t*) dblob + f.up_off, f.gu_type, &U}, + {(const uint8_t*) dblob + f.down_off, f.d_type, &D}}; + for (const auto& m : mats) { + strata::kernels::iq_dequant_f32(m.type, m.src, FF * H, dq, s); + strata::kernels::iq_dequant_f16(m.type, m.src, FF * H, dh, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(got_h.data(), dh, got_h.size() * 2, cudaMemcpyDeviceToHost); + dq_err = (std::max)(dq_err, rel(got_dq, *m.want)); + for (size_t i = 0; i < got_dq.size(); ++i) { + differ += std::memcmp(&got_dq[i], &(*m.want)[i], 4) != 0; + h_differ += got_h[i] != ggml_fp32_to_fp16(got_dq[i]); + } + } + // the gate matrix as an embedding table of FF rows of H values + strata::kernels::iq_embed_rows(f.gu_type, dblob, f.gu_row, dtk, FF, H, dq, s); + cudaStreamSynchronize(s); + cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost); + size_t emb_differ = 0; + for (int64_t r = 0; r < FF; ++r) + emb_differ += std::memcmp(got_dq.data() + r * H, G.data() + (FF - 1 - r) * H, (size_t) H * 4) != 0; + cudaFree(dq); cudaFree(dh); cudaFree(dtk); + std::printf(" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of " + "it: %zu differ; embedding rows: %zu of %lld differ\n", dq_err, differ, (long long) (3 * FF * H), + h_differ, emb_differ, (long long) FF); + // exact where there is one product (Q8_0), a rounding at most elsewhere (fused multiply-adds) + const bool exact = f.gu_type == 8 && f.d_type == 8; + if (!(dq_err < 1e-6) || h_differ || (exact && (differ || emb_differ))) ++failures; + } + cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); + cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); + } + const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g); + const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); + std::printf("%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", label.c_str(), + ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg, + ok ? "ok" : "FAIL"); + return failures + (ok ? 0 : 1); +} + +int type_of(std::string name) { + for (auto& c : name) c = (char) std::tolower((unsigned char) c); + for (int t = 0; t < GGML_TYPE_COUNT; ++t) { + const char* n = ggml_type_name((ggml_type) t); + if (n == nullptr) continue; + std::string m(n); + for (auto& c : m) c = (char) std::tolower((unsigned char) c); + if (m == name) return t; + } + return -1; +} + +// Random weights (rows of different magnitudes) quantized by ggml into the blob layout. +std::vector synthetic_blob(const cpu::NativeFmt& f, int seed) { + std::vector blob(f.bytes); + std::mt19937 rng(seed); + std::normal_distribution nd(0.f, 1.f); + auto quant = [&](int type, int64_t rows, int64_t cols, uint8_t* dst) { + std::vector w((size_t) (rows * cols)); + for (int64_t r = 0; r < rows; ++r) { + const float scale = 0.02f * (0.5f + (float) (r % 7) / 7.0f); + for (int64_t c = 0; c < cols; ++c) w[(size_t) (r * cols + c)] = scale * nd(rng); + } + const std::vector imatrix((size_t) cols, 1.0f); + ggml_quantize_chunk((ggml_type) type, w.data(), dst, 0, rows, cols, + ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr); + }; + quant(f.gu_type, FF, H, blob.data()); + quant(f.gu_type, FF, H, blob.data() + f.up_off); + quant(f.d_type, H, FF, blob.data() + f.down_off); + return blob; +} + +// The Q5_1 min term. Activations x = d * (q + 0.45) round to q, so each q8_1 block's sum of the ORIGINAL values +// (`ds.y`, what llama.cpp CUDA multiplies the min by) exceeds d * sum(q) by 0.45 * 32 * d. The GPU dot must take +// the quantized sum, as ggml-cpu's vec_dot does: equal to ggml-cpu on the same blocks with s = d * sum(q), and far +// from the ds.y variant. Weights with large mins make the difference visible. +int check_q5_1_min(cudaStream_t s) { + constexpr int n = 640, rows = 64; + ggml_cpu_init(); // the fp16 tables vec_dot uses (the other modes get this through native_fmt) + std::mt19937 rng(5); + std::uniform_int_distribution qd(-100, 100); + std::normal_distribution nd(0.f, 1.f); + std::vector w((size_t) rows * n), x(n); + for (auto& v : w) v = 0.3f + 0.05f * nd(rng); // positive weights: a large min per block + const float d = 0.01f; + for (auto& v : x) v = d * ((float) qd(rng) + 0.45f); + const size_t row_bytes = ggml_row_size(GGML_TYPE_Q5_1, n); + std::vector wq((size_t) rows * row_bytes); + ggml_quantize_chunk(GGML_TYPE_Q5_1, w.data(), wq.data(), 0, rows, n, nullptr); + // the GPU: its own q8_1 quantizer, then iq_mmvq on Q5_1 + void *dw, *dx, *dxq; + float* dy; + cudaMalloc(&dw, wq.size()); + cudaMalloc(&dx, n * 4); + cudaMalloc(&dxq, (size_t) n / 32 * 36); + cudaMalloc((void**) &dy, rows * 4); + cudaMemcpy(dw, wq.data(), wq.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), n * 4, cudaMemcpyHostToDevice); + strata::kernels::quantize_q8_1_rows((const float*) dx, 1, n, dxq, s); + strata::kernels::iq_mmvq(GGML_TYPE_Q5_1, dw, dxq, dy, n, rows, 1, s); + cudaStreamSynchronize(s); + std::vector gpu(rows); + std::vector xq((size_t) n / 32 * 36); + cudaMemcpy(gpu.data(), dy, rows * 4, cudaMemcpyDeviceToHost); + cudaMemcpy(xq.data(), dxq, xq.size(), cudaMemcpyDeviceToHost); + cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); + // ggml-cpu on the GPU's own blocks: once with s = d * sum(q) (the quantized sum), once with s = ds.y as stored + struct Q81 { ggml_fp16_t d, s; int8_t qs[32]; }; // ggml's block_q8_1: {d, s} halves, 32 codes + static_assert(sizeof(Q81) == 36, "block_q8_1 layout"); + auto* blocks = (Q81*) xq.data(); + std::vector qsum(blocks, blocks + n / 32); + double shift = 0.0; + for (auto& b : qsum) { + int sq = 0; + for (int i = 0; i < 32; ++i) sq += b.qs[i]; + const float dd = ggml_fp16_to_fp32(b.d); + shift = (std::max)(shift, (double) std::fabs(ggml_fp16_to_fp32(b.s) - dd * sq)); + b.s = ggml_fp32_to_fp16(dd * (float) sq); + } + const auto* tc = ggml_get_type_traits_cpu(GGML_TYPE_Q5_1); + std::vector want(rows), stored(rows); + for (int r = 0; r < rows; ++r) { + const uint8_t* row = wq.data() + (size_t) r * row_bytes; + tc->vec_dot(n, &want[r], 0, row, 0, qsum.data(), 0, 1); + tc->vec_dot(n, &stored[r], 0, row, 0, blocks, 0, 1); + } + const double e_q = rel(gpu, want), e_s = rel(gpu, stored); + // the quantized sum goes through fp16 in ggml-cpu's block (s is a half), so 1e-3 rather than bitwise + const bool ok = e_q < 1e-3 && e_s > 10 * e_q && shift > 0.0; + std::printf("q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n", gpu[0], want[0], + stored[0]); + std::printf("q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e " + "(largest per-block sum shift %.3g) %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL"); + return ok ? 0 : 1; +} +// #290: the BF16 token embedding (--embd-gguf) - iq_embed_rows and iq_dequant_f32 on a random BF16 table against +// the exact widening (bits << 16), every bit; rows gathered out of order, with repeats +int check_bf16_embd(cudaStream_t s) { + constexpr int kBf16 = 30; + const int64_t H = 2560, V = 61, NT = 97; + int failures = 0; + if (!strata::kernels::embed_type_supported(kBf16) || strata::kernels::iq_supported(kBf16) || + strata::kernels::iq_row_bytes(kBf16, H) != (size_t) H * 2) { + std::printf("bf16 embedding: type support / row bytes wrong\n"); + return 1; + } + std::mt19937 rng(290); + std::vector table((size_t) (V * H)); + for (auto& v : table) { // any bit pattern but NaN (a NaN's payload is not what the test is about) + do v = (uint16_t) (rng() & 0xffff); while ((v & 0x7f80) == 0x7f80 && (v & 0x7f)); + } + std::vector tok((size_t) NT); + for (auto& t : tok) t = (int32_t) (rng() % V); + void* dt = nullptr; + int32_t* dtok = nullptr; + float* dout = nullptr; + cudaMalloc(&dt, table.size() * 2); + cudaMalloc((void**) &dtok, tok.size() * 4); + const int64_t out_rows = NT > V ? NT : V; // the gathered rows (NT) and the whole table (V) share the buffer + cudaMalloc((void**) &dout, (size_t) (out_rows * H) * 4); + cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice); + auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }; + std::vector got((size_t) (out_rows * H)); + strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost); + size_t rows_differ = 0; + for (int64_t r = 0; r < NT; ++r) + for (int64_t d = 0; d < H; ++d) { + const float want = widen(table[(size_t) (tok[(size_t) r] * H + d)]); + if (std::memcmp(&got[(size_t) (r * H + d)], &want, 4) != 0) { ++rows_differ; break; } + } + strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s); + cudaStreamSynchronize(s); + cudaMemcpy(got.data(), dout, table.size() * 4, cudaMemcpyDeviceToHost); + size_t values_differ = 0; + for (size_t i = 0; i < table.size(); ++i) { + const float want = widen(table[i]); + values_differ += std::memcmp(&got[i], &want, 4) != 0; + } + cudaFree(dt); cudaFree(dtok); cudaFree(dout); + std::printf("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n", + (long long) NT, rows_differ, (long long) (V * H), values_differ); + if (rows_differ || values_differ) ++failures; + return failures; +} + +} // namespace + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); // keep the trail on a crash + if (argc < 2) { + std::fprintf(stderr, "usage: native_expert_parity [layer ...]\n" + " native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n" + " native_expert_parity --q5_1-min\n" + " native_expert_parity --bf16-embd\n"); + return 2; + } + // #152's width check tests the opt-in rule (the multi-token kernels from one token on) + if (std::getenv("STRATA_IQ_MT_MIN") == nullptr) { +#ifdef _WIN32 + _putenv_s("STRATA_IQ_MT_MIN", "1"); +#else + setenv("STRATA_IQ_MT_MIN", "1", 1); +#endif + } + int failures = 0; + cudaStream_t s; + cudaStreamCreate(&s); + const std::string mode = argv[1]; + if (mode == "--q5_1-min") { + failures += check_q5_1_min(s); + } else if (mode == "--bf16-embd") { + failures += check_bf16_embd(s); + } else if (mode == "--synthetic") { + for (int i = 2; i < argc; ++i) { + const std::string arg = argv[i]; + const size_t slash = arg.find('/'); + const int gu = slash == std::string::npos ? -1 : type_of(arg.substr(0, slash)); + const int dn = slash == std::string::npos ? -1 : type_of(arg.substr(slash + 1)); + cpu::NativeFmt f; + std::string err; + if (gu < 0 || dn < 0 || !cpu::native_fmt(gu, dn, H, FF, f, err) || + !strata::kernels::native_expert_supported(gu, dn, H, FF)) { + std::printf("%s: %s\n", arg.c_str(), err.empty() ? "not a pair the GPU expert kernels take" : err.c_str()); + ++failures; + continue; + } + failures += check_blob(f, synthetic_blob(f, i), i, "synthetic", s); + } + } else { + const strata::GgufModel model(strata::gguf_split_paths(argv[1])); + std::vector layers; + for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i])); + if (layers.empty()) layers = {0, 1, 2, 3, 20, 47}; + for (int l : layers) { + const strata::TensorInfo* t[3] = {}; + const uint8_t* data[3] = {}; + const char* roles[3] = {"gate", "up", "down"}; + for (int r = 0; r < 3; ++r) { // each role from the shard that holds it + size_t at = 0; + t[r] = model.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &at); + if (t[r]) data[r] = model.shard(at).tensor_data(*t[r]); + } + if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; + } + std::vector blob(f.bytes); + std::memcpy(blob.data(), data[0] + (size_t) E * f.up_off, f.up_off); + std::memcpy(blob.data() + f.up_off, data[1] + (size_t) E * f.up_off, f.up_off); + std::memcpy(blob.data() + f.down_off, data[2] + (size_t) E * (f.bytes - f.down_off), + f.bytes - f.down_off); + failures += check_blob(f, blob, l, "layer " + std::to_string(l), s); + } + } + std::printf("native_expert_parity: %d failures\n", failures); + return failures ? 1 : 0; +} diff --git a/engine/strata/src/kernels/ngram.cpp b/engine/strata/src/kernels/ngram.cpp new file mode 100644 index 00000000..bcb611c1 --- /dev/null +++ b/engine/strata/src/kernels/ngram.cpp @@ -0,0 +1,787 @@ +// src/kernels/ngram.cpp - P2.S4: the PLE n-gram hash and the IQ4_NL table read. +// +// See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM. +#include "strata/kernels/ngram.hpp" +#include "strata/artifact/gguf_reader.hpp" +#include "strata/artifact/dequant.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/ngram/ple_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include +#if !defined(_WIN32) +#include +#endif +#include +#include + +#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) +#include +#include +#endif + +#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) +#include +#include +#endif + +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) +#include "kar_ple_cache.hpp" +#include "libkar.h" +#include +#endif + +#if defined(_WIN32) +// `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#endif + +namespace strata::kernels { + +namespace { +/// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. +bool g_ple_prefetch = true; +#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) +struct PleRowTrace { + int fd = -1; + std::mutex lock; + bool failed = false; + + PleRowTrace() { + const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH"); + if (!path) return; + if (!*path) { + std::fprintf(stderr, "PLE row trace needs a private output path\n"); + return; + } + fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { + std::perror("cannot create private PLE row trace"); + return; + } + constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n"; + if (write(fd, header, sizeof(header) - 1) != static_cast(sizeof(header) - 1)) { + std::fprintf(stderr, "cannot write PLE row trace header\n"); + failed = true; + } + } + + ~PleRowTrace() { if (fd >= 0) close(fd); } + + void emit(const uint32_t* rows) { + if (fd < 0) return; + std::lock_guard guard(lock); + if (failed) return; + char line[PLE_N_HEADS * 12]; + size_t used = 0; + for (int h = 0; h < PLE_N_HEADS; ++h) { + const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c", + rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' '); + if (written < 0 || static_cast(written) >= sizeof(line) - used) { + failed = true; + std::fprintf(stderr, "PLE row trace line exceeded its buffer\n"); + return; + } + used += static_cast(written); + } + size_t done = 0; + while (done < used) { + const ssize_t n = write(fd, line + done, used - done); + if (n < 0 && errno == EINTR) continue; + if (n <= 0) { + failed = true; + if (n < 0) std::perror("cannot write PLE row trace"); + else std::fprintf(stderr, "cannot write PLE row trace: short write\n"); + return; + } + done += static_cast(n); + } + } +}; + +PleRowTrace& ple_row_trace() { + static PleRowTrace trace; + return trace; +} +#endif +} // namespace + +void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } +bool ple_prefetch_enabled() { return g_ple_prefetch; } + +PleConsts ple_artifact_consts() { + // docs/gguf-dump-shard1.txt, verbatim. Written once here rather than derived, because `head_offsets` is + // ALSO in the metadata as its own array - and deriving one from the other would hide a mismatch between + // them instead of surfacing it. The parity test checks the two agree. + PleConsts c{}; + c.mult[0] = 23703573157769ull; + c.mult[1] = 20109073645365ull; + c.mult[2] = 8052911324071ull; + const uint64_t vocab[PLE_N_HEADS] = { + 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, + 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171}; + const uint64_t offset[PLE_N_HEADS] = { + 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, + 160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, 300001275}; + for (int i = 0; i < PLE_N_HEADS; ++i) { + c.vocab[i] = vocab[i]; + c.offset[i] = offset[i]; + } + return c; +} + +uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n) { + // The first term is an ASSIGNMENT and the rest are XORed into it, which is how the source writes it + // (`uint64_t mixed = ctx[0]*m[0]; for j=1.. mixed ^= ctx[j]*m[j];`). Every product wraps mod 2^64, + // which is what the `(uint64_t)` casts in the source make explicit. + uint64_t mixed = (uint64_t) ctx[0] * mult[0]; + for (int j = 1; j < n; ++j) mixed ^= (uint64_t) ctx[j] * mult[j]; + return mixed; +} + +void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out) { + const int n_prev = NGRAM_SIZE - 1; + for (int i = 0; i < n_tokens; ++i) { + int64_t ctx[NGRAM_SIZE]; + ctx[0] = tokens[i]; + bool cut = false; + for (int s = 1; s < NGRAM_SIZE; ++s) { + // `prev` is OLDEST FIRST, so predecessor `s` positions back is entry (n_prev - s): s=1 reads the + // NEWEST. Reading index (s-1) instead walks the window backwards, which still produces indices + // in range and so cannot be caught by a range check - only by an oracle. + const int32_t t = cut ? TOKEN_NULL : prev[i * n_prev + (n_prev - s)]; + // The cut is evaluated BEFORE the value is stored, so the position whose predecessor was EOS is + // itself EOS. Storing first and then cutting would leave position s holding the real token while + // position s+1 became EOS - one token of history too much. + cut = cut || t < 0 || t == PLE_EOS_TOKEN_ID; + ctx[s] = cut ? PLE_EOS_TOKEN_ID : t; + } + for (int n = 2; n <= NGRAM_SIZE; ++n) { + const uint64_t mixed = ngram_mixed(ctx, c.mult, n); + const int base = (n - 2) * HEADS_PER_NGRAM; + for (int g = 0; g < HEADS_PER_NGRAM; ++g) { + const int h = base + g; + out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); + } + } +#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) + ple_row_trace().emit(out + i * PLE_N_HEADS); +#endif + } +} + +namespace { +const int8_t kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; +} + +int iq4nl_code(int code) { return kIq4Nl[code & 15]; } + +void iq4nl_dequant_row(const uint8_t* row, float* out160) { + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) { + const uint8_t* blk = row + (size_t) b * 18; + uint16_t dbits; + std::memcpy(&dbits, blk, 2); + const float d = f32_from_f16(dbits); + const uint8_t* qs = blk + 2; + // SPLIT HALVES: qs[j] holds elements j and j+16, not 2j and 2j+1. + for (int j = 0; j < 16; ++j) { + out160[b * 32 + j] = d * (float) kIq4Nl[qs[j] & 0x0F]; + out160[b * 32 + j + 16] = d * (float) kIq4Nl[qs[j] >> 4]; + } + } +} + +namespace { +struct Fp8Table { + float v[256]; + Fp8Table() { + for (int x = 0; x < 256; ++x) { + const int s = x >> 7, e = (x >> 3) & 15, m = x & 7; + float f; + if (e == 15 && m == 7) f = 0.0f; // NaN in e4m3fn; never in a real table, read as 0 + else if (e == 0) f = std::ldexp((float) m / 8.0f, -6); + else f = std::ldexp(1.0f + (float) m / 8.0f, e - 7); + v[x] = s ? -f : f; + } + } +}; +const Fp8Table kFp8; +} // namespace + +void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) { + for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale; +} + +// --------------------------------------------------------------------------------------------------- +struct PleTable::Impl { + GgufFile* file = nullptr; + const uint8_t* data = nullptr; + uint64_t n_rows = 0; + bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only + mutable uint64_t bytes_read = 0; + // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes + // from an unbuffered SSD read into `raw`. + PleIo mode = PleIo::Mmap; + strata::ngram::PleReader reader; + strata::ngram::PleReader::Ticket ticket; + bool pending = false; + bool locked = false; + uint32_t rows[PLE_N_HEADS] = {}; + uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; + bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + struct KarPart { + uint32_t number = 0; + uint64_t row_base = 0; + const kar_tensor_info* tensor = nullptr; + }; + kar_archive* kar = nullptr; + int kar_fd = -1; + const uint8_t* kar_map = nullptr; + size_t kar_bytes = 0; + uint32_t kar_level = 0; + std::string kar_format; + std::vector kar_parts; + std::unique_ptr kar_gpu_cache; + void decode_kar_row(uint32_t row, float* out160) const { + const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, + [](const KarPart& item, uint32_t wanted) { + return item.row_base + item.tensor->row_count <= wanted; + }); + const kar_tensor_info* t = part->tensor; + const uint64_t local_row = uint64_t(row) - part->row_base; + const uint64_t first_word = local_row * t->row_words; + const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; + for (uint32_t word = 0; word < t->row_words; ++word) { + const uint64_t source_word = first_word + word; + const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); + const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); + uint32_t bits[8] = {}; + for (uint32_t level = 0; level < kar_level; ++level) { + const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes + + source_word * 4; + bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | + (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); + } + for (uint32_t bit = 0; bit < 32; ++bit) { + uint32_t code = 0; + for (uint32_t level = 0; level < kar_level; ++level) + code = (code << 1) | ((bits[level] >> bit) & 1u); + const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); + out160[word * 32 + bit] = book * scale; + } + } + bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); + } +#endif + void decode(const uint8_t* row, float* out160) const { + if (fp8) fp8_e4m3_dequant_row(row, scale, out160); + else if (q5_0) + for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32); + else iq4nl_dequant_row(row, out160); + } +}; + +PleTable::PleTable() : impl_(new Impl) {} +PleTable::~PleTable() { close(); delete impl_; } + +bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, + uint64_t expected_rows) { +#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + (void) kar_path; (void) level; (void) expected_rows; + err = "experimental KAR PLE support is not compiled into this engine"; + return false; +#else + close(); + if (level < 1 || level > 8 || expected_rows == 0) { + err = "KAR PLE level or expected row count is invalid"; + return false; + } + kar_archive* archive = nullptr; + const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); + if (status != KAR_OK) { + err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); + return false; + } + impl_->kar = archive; + impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); + struct stat file_info {}; + if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || + uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { + err = "KAR PLE cannot reopen the verified archive at its expected length"; + close(); + return false; + } + impl_->kar_bytes = size_t(file_info.st_size); + void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); + if (map == MAP_FAILED) { + err = "KAR PLE cannot map the verified archive"; + close(); + return false; + } + impl_->kar_map = static_cast(map); + const std::string parent = "per_layer_token_embd.weight"; + const std::string prefix = parent + "#strata-part-"; + uint32_t declared_parts = 0; + for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { + const kar_tensor_info* t = kar_tensor(impl_->kar, i); + const std::string name = t->name; + uint32_t number = 0, total = 0; + if (name == parent) { + number = total = 1; + } else if (name.rfind(prefix, 0) == 0) { + char extra = 0; + if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { + err = "KAR PLE part name is malformed"; + close(); + return false; + } + } else { + continue; + } + if (!number || !total || number > total || (declared_parts && declared_parts != total) || + t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || + t->nesting != KAR_TOPDOWN || t->n_dims != 2 || + t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || + t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || + level < t->planes_min || level > t->planes_max) { + err = "KAR PLE part geometry or precision level differs from the model"; + close(); + return false; + } + declared_parts = total; + impl_->kar_parts.push_back({number, 0, t}); + } + std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), + [](const Impl::KarPart& left, const Impl::KarPart& right) { + return left.number < right.number; + }); + if (!declared_parts || impl_->kar_parts.size() != declared_parts) { + err = "KAR PLE parts are absent or incomplete"; + close(); + return false; + } + uint64_t rows = 0; + for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { + auto& part = impl_->kar_parts[i]; + if (part.number != i + 1 || part.tensor->row_count == 0 || + part.tensor->row_count > expected_rows - rows) { + err = "KAR PLE parts are out of order or exceed expected rows"; + close(); + return false; + } + part.row_base = rows; + rows += part.tensor->row_count; + } + if (rows != expected_rows) { + err = "KAR PLE row count differs from the model"; + close(); + return false; + } + impl_->n_rows = rows; + impl_->kar_level = level; + impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; + impl_->mode = PleIo::Mmap; + return true; +#endif +} + +bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) { +#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + (void) cache_mib; + err = "experimental KAR PLE support is not compiled into this engine"; + return false; +#else + if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) { + err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache"; + return false; + } + std::vector parts; + parts.reserve(impl_->kar_parts.size()); + for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor}); + auto cache = std::make_unique(); + if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false; + impl_->kar_gpu_cache = std::move(cache); + impl_->kar_format = "KAR-L2-GPU-cache"; + return true; +#endif +} + +bool PleTable::kar_gpu_cache_enabled() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + return impl_->kar_gpu_cache != nullptr; +#else + return false; +#endif +} + +bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) { +#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + (void) device_out2560; (void) stream; + err = "experimental KAR PLE support is not compiled into this engine"; + return false; +#else + if (!impl_->kar_gpu_cache || !impl_->pending) { + err = "KAR PLE GPU collect requires a cache and an issued token"; + return false; + } + if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560, + reinterpret_cast(stream), err)) return false; + impl_->pending = false; + return true; +#endif +} + +bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, + void* stream, std::string& err) { +#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + (void) rows; (void) n_tokens; (void) device_out; (void) stream; + err = "experimental KAR PLE support is not compiled into this engine"; + return false; +#else + if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out || + n_tokens == 0 || n_tokens > 65536) { + err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens"; + return false; + } + const size_t count = n_tokens * PLE_N_HEADS; + const size_t chunk_rows = std::min(65536, impl_->kar_gpu_cache->slots()); + for (size_t offset = 0; offset < count; offset += chunk_rows) { + const size_t length = std::min(chunk_rows, count - offset); + if (!impl_->kar_gpu_cache->enqueue(rows + offset, length, + device_out + offset * PLE_HEAD_DIM, + reinterpret_cast(stream), err)) return false; + } + return true; +#endif +} + +bool PleTable::open(const std::string& gguf_path, std::string& err) { + return open(gguf_path, err, PleIoOptions{}); +} + +bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoOptions& io) { + close(); + try { + impl_->file = new GgufFile(gguf_path); + } catch (const std::exception& e) { + err = e.what(); + return false; + } + const TensorInfo* t = impl_->file->find("per_layer_token_embd.weight"); + if (t == nullptr) { + err = "per_layer_token_embd.weight is not in " + gguf_path; + close(); + return false; + } + // [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. + if (t->shape.size() != 2 || t->shape[0] != (uint64_t) PLE_HEAD_DIM) { + err = "per_layer_token_embd.weight has an unexpected shape"; + close(); + return false; + } + // IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as + // shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) + impl_->fp8 = false; + impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0; + impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES; + if (std::strcmp(t->type_name(), "I8") == 0) { + const MetaValue* f = impl_->file->get("strata.ple.format"); + const MetaValue* s = impl_->file->get("strata.ple.scale"); + if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) { + err = "per_layer_token_embd.weight is I8 without strata.ple.format = f8_e4m3 and a positive strata.ple.scale"; + close(); + return false; + } + impl_->fp8 = true; + impl_->scale = (float) s->num(); + impl_->rb = PLE_ROW_BYTES_FP8; + } else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) { + err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)"; + close(); + return false; + } + // The direct reader has fixed 90-byte rows. Keep it for IQ4_NL; Q5_0's + // 110-byte rows use the mapped path until that reader supports variable rows. + if (impl_->q5_0 && io.mode == PleIo::Direct) { + err = "Q5_0 PLE requires --ple-io mmap"; + close(); + return false; + } + impl_->n_rows = t->shape[1]; + impl_->data = impl_->file->tensor_data(*t); + + // THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is + // the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0 + // would decode the header plus 192 bytes of shifted rows - still plausible IQ4_NL, and wrong for every + // row. `GgufFile` parses the header, so `tensor_data` is already correct; this asserts the tensor + // exactly fills the file from there, which is what makes the whole arrangement checkable rather than + // assumed. A wrong data offset would leave a different remainder. + // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must + // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. + const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb; + const uint64_t have = impl_->file->file_size() - impl_->file->data_start(); + const bool alone = impl_->file->tensors().size() == 1; + if (alone ? need != have : t->offset + need > have) { + char buf[256]; + std::snprintf(buf, sizeof buf, + "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " + "data_start %llu", + (unsigned long long) impl_->n_rows, (int) impl_->rb, (unsigned long long) need, + (unsigned long long) t->offset, (unsigned long long) have, + (unsigned long long) impl_->file->data_start()); + err = buf; + close(); + return false; + } + if (io.mode == PleIo::Direct) { + // The parse above is the validated source of the offset; the mapping itself is not kept, so no page of + // the table can enter this process's working set or the file cache through it. + const uint64_t table_offset = impl_->file->data_start() + t->offset; + const uint64_t n_rows = impl_->n_rows; + delete impl_->file; + impl_->file = nullptr; + impl_->data = nullptr; + if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread, + impl_->rb)) { + close(); + return false; + } + impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s); + impl_->n_rows = n_rows; + } + if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) { +#if !defined(_WIN32) + const uint64_t page = 4096; + const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1); + const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need; + madvise((void*) a0, a1 - a0, MADV_WILLNEED); + if (mlock((const void*) a0, a1 - a0) == 0) { + impl_->locked = true; + } else { + std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n", + std::strerror(errno)); + volatile uint8_t sink = 0; + for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p; + (void) sink; + } +#endif + } + impl_->mode = io.mode; + return true; +} + +void PleTable::close() { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + impl_->kar_gpu_cache.reset(); + if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); + impl_->kar_map = nullptr; + impl_->kar_bytes = 0; + if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); + impl_->kar_fd = -1; + if (impl_->kar) kar_close(impl_->kar); + impl_->kar = nullptr; + impl_->kar_parts.clear(); + impl_->kar_level = 0; + impl_->kar_format.clear(); +#endif + impl_->reader.close(); + impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock + impl_->mode = PleIo::Mmap; + delete impl_->file; + impl_->file = nullptr; + impl_->data = nullptr; + impl_->n_rows = 0; + impl_->rb = PLE_ROW_BYTES; + impl_->q5_0 = false; + impl_->fp8 = false; +} + +bool PleTable::is_open() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) return true; +#endif + return impl_->data != nullptr || impl_->reader.is_open(); +} +bool PleTable::locked() const { return impl_->locked; } +const char* PleTable::format() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) return impl_->kar_format.c_str(); +#endif + return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; +} +PleIo PleTable::mode() const { return impl_->mode; } +uint64_t PleTable::rows() const { return impl_->n_rows; } +uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } + +void PleTable::read_row(uint32_t row, float* out160) const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar) { + if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); + else impl_->decode_kar_row(row, out160); + return; + } +#endif + if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { + uint8_t raw[PLE_ROW_BYTES_MAX]; + std::string err; + const auto t = impl_->reader.issue(&row, 1, raw); + if (!impl_->reader.collect(t, err)) { + std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); + return; + } + impl_->decode(raw, out160); + impl_->bytes_read += impl_->rb; + return; + } + if (impl_->data == nullptr || row >= impl_->n_rows) { + std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); + return; + } + impl_->decode(impl_->data + (size_t) row * impl_->rb, out160); + impl_->bytes_read += impl_->rb; +} + +bool PleTable::issue(const uint32_t* rows16) { + std::memcpy(impl_->rows, rows16, sizeof impl_->rows); + if (impl_->mode == PleIo::Direct) { + if (impl_->pending) return false; // one token in flight per table + impl_->ticket = impl_->reader.issue(impl_->rows, PLE_N_HEADS, impl_->raw); + impl_->pending = true; + return true; + } +#if defined(_WIN32) + if (impl_->data != nullptr && g_ple_prefetch) { + WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS]; + ULONG_PTR n = 0; + for (int h = 0; h < PLE_N_HEADS; ++h) { + if (rows16[h] >= impl_->n_rows) continue; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; + ++n; + } + if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); + } +#endif + impl_->pending = true; + return true; +} + +bool PleTable::collect(float* out2560, std::string& err) { + if (!impl_->pending) { err = "PleTable::collect without issue"; return false; } + impl_->pending = false; + if (impl_->mode == PleIo::Direct) { + if (!impl_->reader.collect(impl_->ticket, err)) return false; + for (int h = 0; h < PLE_N_HEADS; ++h) + impl_->decode(impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) PLE_N_HEADS * impl_->rb; + return true; + } + for (int h = 0; h < PLE_N_HEADS; ++h) read_row(impl_->rows[h], out2560 + (size_t) h * PLE_HEAD_DIM); + return true; +} + +bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) { + if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; } + const size_t n = n_tokens * (size_t) PLE_N_HEADS; + if (impl_->mode == PleIo::Direct) { + std::vector raw(n * impl_->rb); + const auto ticket = impl_->reader.issue(rows, n, raw.data()); + if (!impl_->reader.collect(ticket, err)) return false; + for (size_t i = 0; i < n; ++i) impl_->decode(raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM); + impl_->bytes_read += (uint64_t) n * impl_->rb; + return true; + } + for (size_t i = 0; i < n; ++i) read_row(rows[i], out + i * PLE_HEAD_DIM); + return true; +} + +void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } + +std::string PleTable::io_report() const { +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) + if (impl_->kar_gpu_cache) { + const auto s = impl_->kar_gpu_cache->stats(); + char buf[300]; + std::snprintf(buf, sizeof buf, + "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), " + "%llu compressed bytes, %llu H2D argument bytes", + (unsigned long long) s.hits, (unsigned long long) s.misses, + s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0, + impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0, + (unsigned long long) s.compressed_bytes, + (unsigned long long) s.host_to_device_bytes); + return buf; + } +#endif + if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; + int n = std::snprintf(buf, sizeof buf, + "ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, " + "blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows", + (unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0, + (unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99), + s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(), + (unsigned long long) impl_->reader.cache_capacity()); + if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf) + std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)", + (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0); + return buf; +} + +void PleTable::gather(const uint32_t* rows16, float* out2560) const { + if (impl_->mode == PleIo::Direct) { + // `gather` stays const for its existing callers; the reader's state is the table's I/O state. + PleTable* self = const_cast(this); + std::string err; + if (!self->issue(rows16) || !self->collect(out2560, err)) { + std::fprintf(stderr, "PleTable::gather: %s\n", err.empty() ? "a token is already in flight" : err.c_str()); + std::memset(out2560, 0, (size_t) NG_N_EMBD * sizeof(float)); + } + return; + } + // ================================ SIXTEEN SERIAL PAGE FAULTS, MEASURED ================================ + // + // **THIS COST 2.10-2.61 ms PER TOKEN AND HAD NEVER BEEN IN THE PLAN'S BUDGET AT ALL.** The round-309 + // `token host phases` line put it second behind the layer loop among avoidable terms, and the arithmetic + // says why: the table is 320,001,536 rows of `PLE_ROW_BYTES` = 90 B in a 26.8 GB mapping, so the sixteen + // rows a token needs are 1,440 B - **0.5 MB/s**. That is not bandwidth, it is latency: sixteen reads into + // sixteen different 4 KB pages scattered across 26.8 GB, taken ONE AT A TIME, and on this machine the PLE + // shard is 26.8 GB against 63 GB of RAM that the 31.6 GB expert arena is also competing for, so they are + // not in the OS cache. Sixteen serial NVMe reads at ~150 us is 2.4 ms, which is the measurement. + // + // `PrefetchVirtualMemory` issues all sixteen in ONE call and lets them complete in parallel. It is a hint + // and cannot change the answer - a range it does not fetch is simply faulted in by the read that follows - + // so the only risk is that it does nothing. +#if defined(_WIN32) + if (impl_->data != nullptr && g_ple_prefetch) { + WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS]; + ULONG_PTR n = 0; + for (int h = 0; h < PLE_N_HEADS; ++h) { + // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. + if (rows16[h] >= impl_->n_rows) continue; + ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb); + ranges[n].NumberOfBytes = impl_->rb; + ++n; + } + if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0); + } +#endif + // HEAD-SLOWEST, which is what `ggml_get_rows` does and what the source's own comment says: head h's 160 + // values occupy [h*160, (h+1)*160). A head-fastest layout would put element (d, h) at d*16 + h and needs + // a real transpose - a reshape of the same flat buffer compares equal and would make the check vacuous. + for (int h = 0; h < PLE_N_HEADS; ++h) read_row(rows16[h], out2560 + (size_t) h * PLE_HEAD_DIM); +} + +} // namespace strata::kernels diff --git a/engine/strata/src/kernels/ple_fp8_parity.cpp b/engine/strata/src/kernels/ple_fp8_parity.cpp new file mode 100644 index 00000000..09dd199a --- /dev/null +++ b/engine/strata/src/kernels/ple_fp8_parity.cpp @@ -0,0 +1,84 @@ +// src/kernels/ple_fp8_parity.cpp - the FP8 PLE table (tools/ple_fp8_pack.py) read through PleTable, against values +// decoded from the checkpoint itself, and against the IQ4_NL table it replaces. +// +// ple_fp8_parity [] +// +// reference.bin: int32 n, uint32 rows[n], float32 values[n][160] - the rows as torch decodes the checkpoint's +// F8_E4M3 bytes, times its weight_scale (n a multiple of 16 for the gather_batch check). Every row must match BIT FOR BIT through +// both I/O modes (Direct and Mmap) and through the prompt path's gather_batch. With the IQ4_NL shard the same rows +// are compared too: same table, so a correlation near 0.997 - a shifted row order would be ~0. +#include "strata/kernels/ngram.hpp" + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +int main(int argc, char** argv) { + if (argc < 3) { + std::fprintf(stderr, "usage: ple_fp8_parity []\n"); + return 2; + } + std::ifstream f(argv[2], std::ios::binary); + int32_t n = 0; + f.read((char*) &n, 4); + std::vector rows((size_t) n); + std::vector ref((size_t) n * k::PLE_HEAD_DIM); + f.read((char*) rows.data(), (std::streamsize) rows.size() * 4); + f.read((char*) ref.data(), (std::streamsize) ref.size() * 4); + if (!f || n <= 0) { std::fprintf(stderr, "cannot read %s\n", argv[2]); return 2; } + + int bad = 0; + for (const k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) { + k::PleTable t; + std::string err; + k::PleIoOptions io; + io.mode = mode; + if (!t.open(argv[1], err, io)) { std::fprintf(stderr, "open: %s\n", err.c_str()); return 1; } + std::vector got((size_t) n * k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) t.read_row(rows[(size_t) i], got.data() + (size_t) i * k::PLE_HEAD_DIM); + int diff = 0; + for (size_t j = 0; j < got.size(); ++j) diff += std::memcmp(&got[j], &ref[j], 4) != 0; + std::vector batch((size_t) n * k::PLE_HEAD_DIM); // the prompt path: all rows as one request + const bool ok = t.gather_batch(rows.data(), (size_t) n / k::PLE_N_HEADS, batch.data(), err); + int bdiff = 0; + const size_t nb = (size_t) n / k::PLE_N_HEADS * k::PLE_N_HEADS * k::PLE_HEAD_DIM; + for (size_t j = 0; ok && j < nb; ++j) bdiff += std::memcmp(&batch[j], &ref[j], 4) != 0; + std::printf("%-6s %s, %llu rows: read_row %d/%zu values differ, gather_batch %s %d differ\n", + mode == k::PleIo::Direct ? "Direct" : "Mmap", t.format(), (unsigned long long) t.rows(), diff, + got.size(), ok ? "ok," : "FAILED,", bdiff); + bad += diff + bdiff + (ok ? 0 : 1) + (std::strcmp(t.format(), "F8_E4M3") != 0); + } + if (argc > 3) { + k::PleTable q; + std::string err; + if (!q.open(argv[3], err)) { std::fprintf(stderr, "open %s: %s\n", argv[3], err.c_str()); return 1; } + double cmin = 1, rsum = 0; + int counted = 0; + std::vector v(k::PLE_HEAD_DIM); + for (int i = 0; i < n; ++i) { + q.read_row(rows[(size_t) i], v.data()); + const float* r = ref.data() + (size_t) i * k::PLE_HEAD_DIM; + double sa = 0, sb = 0, sab = 0, sa2 = 0, sb2 = 0, e2 = 0, r2 = 0; + for (int j = 0; j < k::PLE_HEAD_DIM; ++j) { + sa += r[j]; sb += v[j]; sab += (double) r[j] * v[j]; sa2 += (double) r[j] * r[j]; sb2 += (double) v[j] * v[j]; + e2 += ((double) v[j] - r[j]) * ((double) v[j] - r[j]); r2 += (double) r[j] * r[j]; + } + if (r2 == 0) continue; // an all-zero row (the table has some) + const double m = k::PLE_HEAD_DIM; + const double c = (sab - sa * sb / m) / std::sqrt((sa2 - sa * sa / m) * (sb2 - sb * sb / m)); + cmin = std::fmin(cmin, c); + rsum += std::sqrt(e2 / r2); + ++counted; + } + std::printf("IQ4_NL table, same rows: correlation min %.4f, error vs FP8 %.1f%% mean (%d non-zero rows)\n", + cmin, 100 * rsum / (counted ? counted : 1), counted); + if (cmin < 0.98) ++bad; + } + std::printf("RESULT: %s\n", bad ? "MISMATCH" : "FP8 rows exact"); + return bad ? 1 : 0; +} diff --git a/engine/strata/src/kernels/ple_oracle_vectors.inc b/engine/strata/src/kernels/ple_oracle_vectors.inc new file mode 100644 index 00000000..60c53b32 --- /dev/null +++ b/engine/strata/src/kernels/ple_oracle_vectors.inc @@ -0,0 +1,105 @@ +// GENERATED by tests/python/gen_ple_oracle.py - DO NOT EDIT BY HAND. +// +// Sources, none of them this project's own code: +// hash ref/ngram.py::ngram_rows (qwen4exp.cpp L1092-1124, validated bit-exact in round 101) +// table the ORIGINAL GGUF's bytes, read at the offset the validated gguf_reader reports, +// dequantized with numpy +// offsets pack/full/manifest.json + +#pragma once +#include + +namespace strata::kernels::ple_oracle { + +struct HashCase { const char* name; int n_tokens; const int32_t* tokens; + const int32_t* prev; const uint32_t* rows; }; + +// window direction +inline const int32_t case0_tokens[4] = {11, 22, 33, 44}; +inline const int32_t case0_prev[8] = {-1, -1, 11, -1, 22, 11, 33, 22}; +inline const uint32_t case0_rows[64] = { + 13555483, 24877159, 54278900, 63631058, 98394898, 117447587, 136774765, 157274238, 173487882, 192109366, 213364329, 236577563, 258758149, 262164274, 283572184, 312653920, + 3278367, 29880471, 46922633, 62971672, 94904487, 113013549, 120925297, 159537733, 161636484, 186269036, 207870452, 237789268, 242975733, 269388091, 285131318, 305889870, + 2485282, 23858032, 54544880, 69506925, 82331991, 106607168, 133019998, 141570514, 173894108, 180423171, 211374553, 239810912, 253076960, 266343146, 290765399, 312876099, + 12721672, 27113445, 44309803, 60385209, 97021817, 115900810, 134219364, 151977589, 161183764, 181257609, 201344488, 221596875, 241635416, 261674107, 281687144, 301751935, +}; +// EOS one back cuts both +inline const int32_t case1_tokens[3] = {7, 8, 9}; +inline const int32_t case1_prev[6] = {-1, -1, 7, 248044, 248044, 7}; +inline const uint32_t case1_rows[48] = { + 2927653, 34980843, 54748278, 66612378, 97814964, 109013870, 126560393, 151352333, 167888935, 182235580, 215170017, 237467519, 247510681, 278779700, 296141806, 304994522, + 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, 164805529, 181662903, 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, + 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, 179716672, 187881262, 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, +}; +// NULL reads as EOS +inline const int32_t case2_tokens[2] = {100, 101}; +inline const int32_t case2_prev[4] = {-1, -1, -1, -1}; +inline const uint32_t case2_rows[32] = { + 5727835, 21884476, 43702108, 66434789, 84094509, 104112171, 134886528, 157314943, 162363667, 189466439, 200618315, 232121522, 258547276, 266199001, 289022207, 305180972, + 14526383, 36975477, 51939184, 65076202, 94510971, 111786935, 138448715, 155393638, 167579692, 181767276, 211184823, 226303266, 246271192, 267465224, 281469089, 313531602, +}; +// token id 0 is NOT missing +inline const int32_t case3_tokens[2] = {100, 101}; +inline const int32_t case3_prev[4] = {0, 0, 100, 0}; +inline const uint32_t case3_rows[32] = { + 223356, 29869136, 44693816, 65450370, 83243562, 109175069, 138072664, 149936704, 175869089, 193667153, 214433731, 233779437, 242682975, 271587098, 294555343, 309396483, + 9825591, 35767834, 58740777, 62904867, 86476006, 107666813, 129453358, 151836075, 160726459, 190511348, 208596315, 234569026, 259467109, 264365567, 292665383, 314164387, +}; +// own EOS does not cut itself +inline const int32_t case4_tokens[3] = {248044, 5, 248044}; +inline const int32_t case4_prev[6] = {-1, -1, 248044, -1, 5, 248044}; +inline const uint32_t case4_rows[48] = { + 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, + 15389869, 39778609, 55713969, 62213332, 88817728, 118483999, 133731511, 155458159, 179763390, 197956758, 205378969, 220499474, 242466248, 265658744, 293662119, 315720898, + 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, +}; +// real vocabulary ids +inline const int32_t case5_tokens[5] = {248043, 12345, 248043, 7, 200000}; +inline const int32_t case5_prev[10] = {-1, -1, 248043, -1, 12345, 248043, 248043, 12345, 7, 248043}; +inline const uint32_t case5_rows[80] = { + 5224855, 30284709, 43929396, 72280505, 94883662, 109322550, 131203836, 140794991, 166459826, 181131035, 209237474, 226844350, 246236135, 265823742, 299063341, 305586418, + 11270970, 23825822, 53627731, 75297762, 86108900, 117131242, 124369521, 148669731, 173053968, 186938961, 219076364, 237563026, 246838602, 277288915, 294366759, 301712965, + 9040325, 23423119, 51729309, 72606490, 88803423, 101106903, 139785146, 145105493, 165075797, 186774126, 216848848, 228384799, 252197080, 276291559, 284385762, 305326936, + 4918924, 35785322, 51404601, 69479989, 96595301, 119006811, 132661231, 157603286, 167367331, 194295259, 207336314, 231383366, 248222822, 265383752, 291175661, 300670030, + 19540326, 36155593, 54730668, 61035256, 83860210, 111525643, 123077188, 158579165, 171421264, 181503411, 210257194, 220050508, 255765827, 271545193, 290152687, 303296503, +}; + +inline const HashCase kHashCases[] = { + {"window direction", 4, case0_tokens, case0_prev, case0_rows}, + {"EOS one back cuts both", 3, case1_tokens, case1_prev, case1_rows}, + {"NULL reads as EOS", 2, case2_tokens, case2_prev, case2_rows}, + {"token id 0 is NOT missing", 2, case3_tokens, case3_prev, case3_rows}, + {"own EOS does not cut itself", 3, case4_tokens, case4_prev, case4_rows}, + {"real vocabulary ids", 5, case5_tokens, case5_prev, case5_rows}, +}; +inline constexpr int kHashCaseCount = 6; + +// The table: sampled values of two rows, plus the whole-row L1 sums so a wrong codebook or a +// wrong scale cannot hide between the samples. Row 0 and the LAST row. +inline constexpr uint64_t kTableRows = 320001536ull; +inline constexpr uint64_t kTableDataStart = 192ull; +inline constexpr uint64_t kTableFileSize = 28800138432ull; +inline const uint32_t kProbeRows[] = {0, 12345, 320001535}; +inline constexpr int kProbeCount = 3; +inline const float kProbeHead[][8] = { + {-1.001119614e-02f, 1.290917397e-02f, -1.817822456e-02f, 1.290917397e-02f, -6.586313248e-03f, 5.795955658e-03f, -6.586313248e-03f, 5.795955658e-03f}, + {5.563795567e-03f, -4.314780235e-03f, 3.974139690e-03f, -1.476109028e-03f, -1.135468483e-04f, 1.135468483e-03f, -1.010566950e-02f, -6.017982960e-03f}, + {0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f}, +}; +inline const float kProbeTail[][8] = { + {2.571296692e-02f, 1.607060432e-02f, 3.139948845e-02f, 5.439281464e-03f, -1.705956459e-02f, -3.214120865e-03f, -2.200436592e-02f, 2.472400665e-03f}, + {-1.942408085e-02f, 5.811929703e-03f, -9.941458702e-03f, 3.823637962e-03f, -5.353093147e-03f, -1.529455185e-03f, -1.529455185e-03f, -5.353093147e-03f}, + {0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f, 0.000000000e+00f}, +}; +inline const double kProbeSum[] = {2.011959553e+00, 9.968549609e-01, 0.000000000e+00}; +inline constexpr float kInterleavedSeparation = 1.253766603e+00f; + +// pack/full/dense.bin regions for the two quantized PLE weights +inline constexpr uint64_t kKeyCodesOffset = 1017723776ull; +inline constexpr uint64_t kKeyCodesBytes = 6553600ull; +inline constexpr uint64_t kKeyScalesOffset = 1024277376ull; +inline constexpr uint64_t kKeyScalesBytes = 819200ull; +inline constexpr uint64_t kValueOffset = 1025219456ull; +inline constexpr uint64_t kValueBytes = 26214400ull; + +} // namespace strata::kernels::ple_oracle diff --git a/engine/strata/src/kernels/ple_parity.cpp b/engine/strata/src/kernels/ple_parity.cpp new file mode 100644 index 00000000..20da0220 --- /dev/null +++ b/engine/strata/src/kernels/ple_parity.cpp @@ -0,0 +1,1184 @@ +// src/kernels/ple_parity.cpp - P2.S4's test: the n-gram hash, the IQ4_NL table read, and the PLE block. +// +// THREE PARTS, THREE DIFFERENT ORACLES, and none of them is this project's own code: +// +// A. THE HASH against `ref/ngram.py::ngram_rows`, via `ple_oracle_vectors.inc` (generated). The properties +// are asserted OBSERVABLE first - XOR vs sum, `%` vs `&`, the cut DIRECTION, the NULL sentinel - because +// each rival reading produces a perfectly valid index in range. +// B. THE TABLE against numpy reading the ORIGINAL GGUF at the offset the validated `gguf_reader` reports. +// C. THE BLOCK against ggml's own graph, captured in `bench/micro/ple_in.bin` / `ple_out.bin` by +// `ple_layer_xcheck.cpp`. That file records EVERY intermediate (key, value, gate, gated, normalized, +// conv_out, result), so a mismatch can be attributed to a stage instead of guessed at - and the weights +// in it were checked to be the artifact's real ones before this test was written. +#include "strata/kernels/ple.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "ple_oracle_vectors.inc" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; +namespace o = strata::kernels::ple_oracle; + +namespace { + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// TOLERANCE CHECKS MUST BE NaN-SAFE, and `x <= t` is not. +/// +/// `x <= t` AND `x > t` are BOTH false for NaN, so a check written either way can silently pass - round 197 +/// found `shared_expert_parity` printing a perfect score for an entirely-NaN fixture because the accumulator +/// was `if (rel > worst) worst = rel;` and NaN is never greater. Every comparison in this file goes through +/// `le`/`gt`, which require the value to be FINITE first, and every compared pair is counted for non-finite +/// entries and the count printed. A NaN fixture is then a loud failure rather than a green line. +bool le(double x, double t) { return std::isfinite(x) && x <= t; } +bool gt(double x, double t) { return std::isfinite(x) && x > t; } + +/// How many entries of `a` are not finite. Printed next to every comparison. +long long nonfinite(const float* a, size_t n) { + long long k = 0; + for (size_t i = 0; i < n; ++i) + if (!std::isfinite(a[i])) ++k; + return k; +} + +/// Normalised L1 with the reference magnitude returned. For the STAGE comparisons a plain |ref| denominator +/// is right: these are dense vectors of O(1) values with no cancellation between them. +/// +/// Returns NaN if EITHER side has a non-finite entry, so a caller that forgets `le`/`gt` still cannot read a +/// finite-looking number out of a broken fixture. +double rel_l1(const float* a, const float* b, size_t n, double* mag_out = nullptr, + long long* nf_out = nullptr) { + double d = 0, m = 0; + long long nf = 0; + for (size_t i = 0; i < n; ++i) { + if (!std::isfinite(a[i]) || !std::isfinite(b[i])) { ++nf; continue; } + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + if (mag_out) *mag_out = m / (double) (n ? n : 1); + if (nf_out) *nf_out = nf; + if (nf) return std::nan(""); + return d / (m > 1e-30 ? m : 1e-30); +} + +/// The file's size, WITHOUT reading it. +/// +/// The first version of this test called `read_file(gguf)` - which reads the WHOLE file into a vector - three +/// times, on a 28.8 GB GGUF. That is 27 GB of RSS, three full passes over the file, and a 132-second ctest +/// entry in a suite where every other test is under a second. A test that slow stops being run, which is how +/// a gate stops being a gate. Everything below now reads only the bytes it actually compares. +long long file_size(const char* path) { + std::FILE* f = std::fopen(path, "rb"); + if (!f) return -1; +#if defined(_MSC_VER) + _fseeki64(f, 0, SEEK_END); + const long long n = _ftelli64(f); +#else + std::fseek(f, 0, SEEK_END); + const long long n = std::ftell(f); +#endif + std::fclose(f); + return n; +} + +/// `n` bytes at `off`, or an empty vector. +std::vector read_at(const char* path, long long off, size_t n) { + std::vector v(n); + std::FILE* f = std::fopen(path, "rb"); + if (!f) return {}; +#if defined(_MSC_VER) + if (_fseeki64(f, off, SEEK_SET) != 0) { std::fclose(f); return {}; } +#else + if (std::fseek(f, (long) off, SEEK_SET) != 0) { std::fclose(f); return {}; } +#endif + const size_t got = std::fread(v.data(), 1, n, f); + std::fclose(f); + if (got != n) return {}; + return v; +} + +/// Only used for the pack, which is 5.4 GB rather than 28.8 GB - and even then the caller says which region. +std::vector read_path(const char* path) { + const long long n = file_size(path); + if (n <= 0) return {}; + return read_at(path, 0, (size_t) n); +} + +/// Dequantize one IQ4_NL row with an INTERLEAVED nibble order, to show the correct split-half order is +/// observable. Deliberately shares nothing with the kernel's decoder. +void deq_interleaved(const uint8_t* row, float* out160) { + for (int b = 0; b < k::PLE_HEAD_DIM / 32; ++b) { + const uint8_t* blk = row + (size_t) b * 18; + uint16_t db; + std::memcpy(&db, blk, 2); + const float d = k::f32_from_f16(db); + for (int j = 0; j < 16; ++j) { + out160[b * 32 + 2 * j] = d * (float) k::iq4nl_code(blk[2 + j] & 0x0F); + out160[b * 32 + 2 * j + 1] = d * (float) k::iq4nl_code(blk[2 + j] >> 4); + } + } +} + +struct PleCapture { + int n_embd = 0, hc = 0, nt = 0, kern = 0, dil = 0; + float eps = 0.0f; + std::vector emb, hidden, w_key, w_value, w_nk, w_nq, w_nc, w_conv, hist; + // oracle outputs + std::vector key, value, gate, gated, normalized, conv_out, result; +}; + +bool load_capture(const char* in_path, const char* out_path, PleCapture& c) { + std::FILE* fi = std::fopen(in_path, "rb"); + if (!fi) return false; + int32_t h[5] = {0}; + if (std::fread(h, 4, 5, fi) != 5) { std::fclose(fi); return false; } + c.n_embd = h[0]; c.hc = h[1]; c.nt = h[2]; c.kern = h[3]; c.dil = h[4]; + if (std::fread(&c.eps, 4, 1, fi) != 1) { std::fclose(fi); return false; } + // Validate before deriving sizes or allocating. This bounded diagnostic + // format is for this model's geometry and at most 64 captured tokens. + if (c.n_embd != k::NG_N_EMBD || c.hc != k::NG_HC || c.nt <= 0 || c.nt > 64 || + c.kern != k::PLE_CONV_KERNEL || c.dil != k::NGRAM_SIZE || c.eps != k::NG_RMS_EPS) { + std::fclose(fi); return false; + } + const long long nd = c.n_embd, hcd = (long long) c.hc * c.n_embd, nt = c.nt, + hist = (long long) (c.kern - 1) * c.dil; + const long long in_bytes = 24 + 4 * (nt * nd + nt * hcd + hcd * nd + nd * nd + + 3 * hcd + hcd * c.kern + hist * hcd); + const long long out_bytes = 12 + 4 * nt * (5 * hcd + nd + c.hc); + if (file_size(in_path) != in_bytes || file_size(out_path) != out_bytes) { + std::fclose(fi); return false; + } + auto rd = [](std::FILE* file, std::vector& v, long long n) { + v.resize((size_t) n); + return n == 0 || std::fread(v.data(), 4, (size_t) n, file) == (size_t) n; + }; + bool ok = rd(fi, c.emb, nt * nd) && rd(fi, c.hidden, nt * hcd) && rd(fi, c.w_key, hcd * nd) && + rd(fi, c.w_value, nd * nd) && rd(fi, c.w_nk, hcd) && rd(fi, c.w_nq, hcd) && rd(fi, c.w_nc, hcd) && + rd(fi, c.w_conv, hcd * c.kern) && rd(fi, c.hist, hist * hcd); + std::fclose(fi); + if (!ok) return false; + + std::FILE* fo = std::fopen(out_path, "rb"); + if (!fo) return false; + int32_t oh[3] = {0}; + if (std::fread(oh, 4, 3, fo) != 3) { std::fclose(fo); return false; } + if (oh[0] != c.n_embd || oh[1] != hcd || oh[2] != c.nt) { std::fclose(fo); return false; } + ok = rd(fo, c.key, nt * hcd) && rd(fo, c.value, nt * nd) && rd(fo, c.gate, nt * c.hc) && rd(fo, c.gated, nt * hcd) && + rd(fo, c.normalized, nt * hcd) && rd(fo, c.conv_out, nt * hcd) && rd(fo, c.result, nt * hcd); + std::fclose(fo); + return ok; +} + +int history_advance_regression() { + const size_t channels = (size_t) k::NG_HC_DIM, rows = (size_t) k::NG_HIST, guard = 16; + const size_t count = channels * rows; + std::vector expected(count), normalized(channels), actual(count); + for (size_t c = 0; c < channels; ++c) + for (size_t r = 0; r < rows; ++r) expected[c * rows + r] = -float(c * 16 + r + 1); + float *history_storage = nullptr, *norm_storage = nullptr; + ck(cudaMalloc(&history_storage, (count + 2 * guard) * sizeof(float)), "history regression allocation"); + ck(cudaMalloc(&norm_storage, (channels + 2 * guard) * sizeof(float)), "history norm allocation"); + ck(cudaMemset(history_storage, 0xa5, (count + 2 * guard) * sizeof(float)), "history guard init"); + ck(cudaMemset(norm_storage, 0xa5, (channels + 2 * guard) * sizeof(float)), "history norm guard init"); + float* history = history_storage + guard; + float* norm = norm_storage + guard; + ck(cudaMemcpy(history, expected.data(), count * sizeof(float), cudaMemcpyHostToDevice), "history initial values"); + cudaStream_t stream; + cudaGraph_t graph; + cudaGraphExec_t executable; + ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "history regression stream"); + ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "history regression capture"); + k::ple_history_advance(history, norm, stream); + ck(cudaStreamEndCapture(stream, &graph), "history regression capture end"); + ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "history regression instantiate"); + int bad = 0; + for (int token = 0; token < 12; ++token) { + for (size_t c = 0; c < channels; ++c) { + normalized[c] = float((token + 1) * 1000000 + c); // distinct exactly represented integers + for (size_t r = 0; r + 1 < rows; ++r) expected[c * rows + r] = expected[c * rows + r + 1]; + expected[c * rows + rows - 1] = normalized[c]; + } + ck(cudaMemcpyAsync(norm, normalized.data(), channels * sizeof(float), cudaMemcpyHostToDevice, stream), "history new normalized row"); + ck(cudaGraphLaunch(executable, stream), "history captured advance"); + ck(cudaStreamSynchronize(stream), "history captured advance sync"); + ck(cudaMemcpy(actual.data(), history, count * sizeof(float), cudaMemcpyDeviceToHost), "history readback"); + if (std::memcmp(actual.data(), expected.data(), count * sizeof(float)) != 0) { + std::printf(" history advance mismatch after token %d\n", token); + ++bad; + } + } + bool overlap_refused = false, null_refused = false; + try { k::ple_history_advance(history, history + 1, stream); } + catch (const std::invalid_argument&) { overlap_refused = true; } + try { k::ple_history_advance(history, nullptr, stream); } + catch (const std::invalid_argument&) { null_refused = true; } + if (!overlap_refused || !null_refused) ++bad; + auto guard_ok = [&](float* storage, size_t payload) { + uint8_t before[64], after[64]; + ck(cudaMemcpy(before, storage, sizeof(before), cudaMemcpyDeviceToHost), "history prefix guard"); + ck(cudaMemcpy(after, storage + guard + payload, sizeof(after), cudaMemcpyDeviceToHost), "history suffix guard"); + return std::all_of(before, before + 64, [](uint8_t b) { return b == 0xa5; }) && + std::all_of(after, after + 64, [](uint8_t b) { return b == 0xa5; }); + }; + if (!guard_ok(history_storage, count) || !guard_ok(norm_storage, channels)) ++bad; + std::printf(" PLE history 12 captured steps, row-fastest state and guards: %s\n", bad == 0 ? "pass" : "FAIL"); + ck(cudaGraphExecDestroy(executable), "history graph exec destroy"); + ck(cudaGraphDestroy(graph), "history graph destroy"); + ck(cudaStreamDestroy(stream), "history stream destroy"); + cudaFree(history_storage); cudaFree(norm_storage); + return bad; +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + bool check_fixtures = false; + std::string pack = "pack/full"; + // --gguf, else $STRATA_PLE_GGUF, else the development layout (run from the engine root) + std::string gguf = std::getenv("STRATA_PLE_GGUF") ? std::getenv("STRATA_PLE_GGUF") + : "../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"; + std::string in_bin = "bench/micro/ple_in.bin", out_bin = "bench/micro/ple_out.bin"; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") selftest = true; + else if (a == "--check-fixtures") check_fixtures = true; + else if (a == "--pack" && i + 1 < argc) pack = argv[++i]; + else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; + else if (a == "--in" && i + 1 < argc) in_bin = argv[++i]; + else if (a == "--out" && i + 1 < argc) out_bin = argv[++i]; + else { std::fprintf(stderr, "usage: ple_parity [--selftest] [--check-fixtures] [--pack D] [--gguf F] [--in F] [--out F]\n"); + return 2; } + } + if (selftest && check_fixtures) { + std::fprintf(stderr, "ple_parity: --check-fixtures is CPU-only; use it separately from --selftest\n"); + return 2; + } + // Required self-test fixtures are checked before the first CUDA call, so + // missing files cannot become an apparent pass or a misleading GPU error. + k::PleTable table; + std::string err; + PleCapture cap; + bool preflight_done = false; + if (selftest || check_fixtures) { + if (!table.open(gguf, err) || table.rows() != o::kTableRows || + file_size(gguf.c_str()) != (long long) o::kTableDataStart + (long long) o::kTableRows * k::PLE_ROW_BYTES) { + std::fprintf(stderr, "ple_parity: required PLE table is missing or incompatible: %s (%s)\n", gguf.c_str(), err.c_str()); + return 2; + } + const uint64_t pack_needed = std::max({o::kKeyCodesOffset + o::kKeyCodesBytes, + o::kKeyScalesOffset + o::kKeyScalesBytes, o::kValueOffset + o::kValueBytes}); + const long long pack_size = file_size((pack + "/dense.bin").c_str()); + if (pack_size < 0 || (uint64_t) pack_size < pack_needed) { + std::fprintf(stderr, "ple_parity: required dense pack is missing or truncated: %s/dense.bin\n", pack.c_str()); + return 2; + } + if (!load_capture(in_bin.c_str(), out_bin.c_str(), cap)) { + std::fprintf(stderr, "ple_parity: required block fixtures are missing, truncated or incompatible: %s / %s\n", in_bin.c_str(), out_bin.c_str()); + return 2; + } + preflight_done = true; + if (check_fixtures) { + std::puts("PASS required PLE fixture structure on CPU; no GPU numerical checks were run"); + return 0; + } + if (!k::ple_block_available()) { + std::fprintf(stderr, "ple_parity: --selftest requires a CUDA device for block checks\n"); + return 2; + } + } + int bad = history_advance_regression(); + const k::PleConsts C = k::ple_artifact_consts(); + + // ============================ A. THE HASH ============================ + std::printf("A. the n-gram hash, against ref/ngram.py with the artifact's own constants\n"); + + // ---- the constants must be internally consistent BEFORE they are used: `head_offsets` is its own array + // in the metadata, so deriving it from `vocab_sizes` would hide a disagreement between them. + { + uint64_t run = 0; + bool ok = true; + for (int h = 0; h < k::PLE_N_HEADS; ++h) { + if (C.offset[h] != run) ok = false; + run += C.vocab[h]; + } + const uint64_t total = run; + const bool fits = total <= k::PLE_TABLE_ROWS; + std::printf(" %-46s %s (sum %llu <= %llu rows; %llu spare)\n", + "head_offsets == the running sum of vocab_sizes", ok && fits ? "yes" : "*** NO ***", + (unsigned long long) total, (unsigned long long) k::PLE_TABLE_ROWS, + (unsigned long long) (k::PLE_TABLE_ROWS - total)); + if (!ok || !fits) ++bad; + } + + for (int ci = 0; ci < o::kHashCaseCount; ++ci) { + const o::HashCase& hc = o::kHashCases[ci]; + std::vector got((size_t) hc.n_tokens * k::PLE_N_HEADS); + k::ngram_rows(hc.tokens, hc.prev, hc.n_tokens, C, got.data()); + long long diff = 0; + for (size_t i = 0; i < got.size(); ++i) + if (got[i] != hc.rows[i]) ++diff; + std::printf(" %-46s %s (%lld of %zu differ)\n", hc.name, diff ? "*** WRONG ***" : "matches", diff, + got.size()); + if (diff) { + for (int t = 0; t < hc.n_tokens && diff; ++t) { + for (int h = 0; h < k::PLE_N_HEADS; ++h) { + const uint32_t g = got[(size_t) t * 16 + h], w = hc.rows[(size_t) t * 16 + h]; + if (g != w) { + std::printf(" first: t=%d h=%d got %u want %u\n", t, h, g, w); + t = hc.n_tokens; + break; + } + } + } + ++bad; + } + } + + // ---- the rival readings, each computed and required to DIFFER from the oracle ------------------- + // + // Every one of these produces a 16-element vector of valid indices. That is the whole reason the hash is + // transcribed property by property: no range check, no shape check and no summing test can see any of + // them, only an oracle can - and only a DELIBERATELY-WRONG fixture can show that the oracle comparison + // has the power to catch them. + { + const o::HashCase& hc = o::kHashCases[0]; // the window-direction case, 4 tokens + const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS; + std::vector xor_v((size_t) T * n_heads), sum_v((size_t) T * n_heads), + mask_v((size_t) T * n_heads), back_v((size_t) T * n_heads), zero_v((size_t) T * n_heads); + for (int i = 0; i < T; ++i) { + int64_t ctx[k::NGRAM_SIZE]; + ctx[0] = hc.tokens[i]; + for (int s = 1; s < k::NGRAM_SIZE; ++s) ctx[s] = hc.prev[i * np + (np - s)]; + for (int n = 2; n <= k::NGRAM_SIZE; ++n) { + // (1) SUM instead of XOR + uint64_t sum = 0; + for (int j = 0; j < n; ++j) sum += (uint64_t) ctx[j] * C.mult[j]; + // (2) mask instead of modulo: the vocab sizes are NOT powers of two + uint64_t xr = k::ngram_mixed(ctx, C.mult, n); + // (4) token 0 treated as "missing" the way -1 is + int64_t ctx0[k::NGRAM_SIZE]; + for (int j = 0; j < k::NGRAM_SIZE; ++j) + ctx0[j] = (ctx[j] == k::TOKEN_NULL || ctx[j] == 0) ? k::PLE_EOS_TOKEN_ID : ctx[j]; + uint64_t xr0 = k::ngram_mixed(ctx0, C.mult, n); + // (3) the window read NEWEST-first instead of oldest-first: prev index (s-1) + int64_t ctxb[k::NGRAM_SIZE]; + ctxb[0] = hc.tokens[i]; + for (int s = 1; s < k::NGRAM_SIZE; ++s) ctxb[s] = hc.prev[i * np + (s - 1)]; + uint64_t xrb = k::ngram_mixed(ctxb, C.mult, n); + const int base = (n - 2) * k::HEADS_PER_NGRAM; + for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) { + const int h = base + g; + xor_v[(size_t) i * n_heads + h] = (uint32_t) (xr % C.vocab[h] + C.offset[h]); + sum_v[(size_t) i * n_heads + h] = (uint32_t) (sum % C.vocab[h] + C.offset[h]); + mask_v[(size_t) i * n_heads + h] = + (uint32_t) ((xr & (C.vocab[h] - 1)) + C.offset[h]); + back_v[(size_t) i * n_heads + h] = (uint32_t) (xrb % C.vocab[h] + C.offset[h]); + zero_v[(size_t) i * n_heads + h] = (uint32_t) (xr0 % C.vocab[h] + C.offset[h]); + } + } + } + struct Rival { const char* name; const std::vector* v; }; + const Rival rivals[] = {{"XOR vs SUM", &sum_v}, + {"% vs & (vocab sizes are not powers of two)", &mask_v}, + {"window read newest-first, not oldest-first", &back_v}, + {"token id 0 treated as the NULL sentinel", &zero_v}}; + for (const Rival& r : rivals) { + // A rival is observable if it disagrees with the ORACLE, which is what the test above compares. + long long d = 0; + for (size_t i = 0; i < r.v->size(); ++i) + if ((*r.v)[i] != hc.rows[i]) ++d; + const bool visible = d > 0; + std::printf(" %-46s %s (%lld of %zu rows differ from the oracle)\n", r.name, + visible ? "yes" : "*** NO - the fixture cannot see this ***", d, r.v->size()); + if (!visible) ++bad; + } + (void) xor_v; + } + + // ---- the EOS cut DIRECTION, which needs a case where the two directions disagree ---------------- + { + const o::HashCase& hc = o::kHashCases[1]; // [[N,N],[7,EOS],[EOS,7]] + const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS; + std::vector fwd((size_t) T * n_heads), bwd((size_t) T * n_heads); + for (int i = 0; i < T; ++i) { + int64_t f[k::NGRAM_SIZE], b[k::NGRAM_SIZE]; + f[0] = b[0] = hc.tokens[i]; + bool cf = false, cb = false; + for (int s = 1; s < k::NGRAM_SIZE; ++s) { + const int32_t fv = hc.prev[i * np + (np - s)]; + cf = cf || fv < 0 || fv == k::PLE_EOS_TOKEN_ID; + f[s] = cf ? k::PLE_EOS_TOKEN_ID : fv; + // the BACKWARD reading: only the position that IS EOS becomes EOS + const int32_t bv = hc.prev[i * np + (np - s)]; + b[s] = (bv < 0 || bv == k::PLE_EOS_TOKEN_ID) ? k::PLE_EOS_TOKEN_ID : bv; + (void) cb; + } + for (int n = 2; n <= k::NGRAM_SIZE; ++n) { + const uint64_t mf = k::ngram_mixed(f, C.mult, n), mb = k::ngram_mixed(b, C.mult, n); + const int base = (n - 2) * k::HEADS_PER_NGRAM; + for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) { + const int h = base + g; + fwd[(size_t) i * n_heads + h] = (uint32_t) (mf % C.vocab[h] + C.offset[h]); + bwd[(size_t) i * n_heads + h] = (uint32_t) (mb % C.vocab[h] + C.offset[h]); + } + } + } + long long d = 0; + for (size_t i = 0; i < fwd.size(); ++i) + if (fwd[i] != bwd[i]) ++d; + std::printf(" %-46s %s (%lld of %zu rows differ)\n", + "cut propagates FORWARD vs only at the EOS position", + d > 0 ? "yes" : "*** NO ***", d, fwd.size()); + if (!d) ++bad; + } + + // ============================ B. THE TABLE ============================ + std::printf("\nB. the IQ4_NL table, against numpy reading the original GGUF\n"); + if (!preflight_done && !table.open(gguf, err)) { + std::printf(" cannot open the PLE table: %s\n", err.c_str()); + std::printf("\nple_parity: %d failures, TABLE AND BLOCK SKIPPED; partial diagnostic only\n", bad); + return selftest || bad ? 1 : 0; + } + std::printf(" %-46s %llu (expected %llu)\n", "rows", (unsigned long long) table.rows(), + (unsigned long long) o::kTableRows); + if (table.rows() != o::kTableRows) ++bad; + + // The size identity is what makes the data offset FALSIFIABLE: the tensor must exactly fill the file from + // data_start. Deriving the row count from the file size instead gives 320001538 rows and data_start 12, + // which is self-consistent and wrong. + { + const long long sz = file_size(gguf.c_str()); + const long long need = (long long) o::kTableDataStart + (long long) table.rows() * k::PLE_ROW_BYTES; + const bool ok = sz == need; + std::printf(" %-46s %s (%lld vs %lld; data_start %llu)\n", + "data_start + rows*90 == file size", ok ? "yes" : "*** NO ***", sz, need, + (unsigned long long) o::kTableDataStart); + if (!ok) ++bad; + } + + // Read the raw bytes through the mapped table by comparing against numpy's decode of the SAME offsets. + // 90 BYTES AT A TIME, not the whole file - see `file_size`'s note. + { + int probe_bad = 0; + for (int p = 0; p < o::kProbeCount; ++p) { + const uint32_t row = o::kProbeRows[p]; + std::vector got(k::PLE_HEAD_DIM); + table.read_row(row, got.data()); + const std::vector raw = + read_at(gguf.c_str(), (long long) o::kTableDataStart + (long long) row * k::PLE_ROW_BYTES, + (size_t) k::PLE_ROW_BYTES); + if (raw.size() != (size_t) k::PLE_ROW_BYTES) { std::printf(" short read at row %u\n", row); ++probe_bad; continue; } + std::vector ref(k::PLE_HEAD_DIM); + k::iq4nl_dequant_row(raw.data(), ref.data()); + // the sampled values from the generator (numpy), which is the oracle proper. + // NOT `fmax`: it DISCARDS NaN, so a NaN element would leave these at 0 and the row would report + // a perfect match. A plain comparison propagates the NaN into `ok`. + double head = 0, tail = 0, sum = 0; + for (int i = 0; i < 8; ++i) { + const double dh = std::fabs((double) got[i] - (double) o::kProbeHead[p][i]); + const double dt = std::fabs((double) got[k::PLE_HEAD_DIM - 8 + i] - + (double) o::kProbeTail[p][i]); + if (p == 0 && i == 0) { head = dh; tail = dt; } + else { head = (dh > head) ? dh : head; tail = (dt > tail) ? dt : tail; } + } + for (int i = 0; i < k::PLE_HEAD_DIM; ++i) sum += std::fabs((double) got[i]); + const long long nfg = nonfinite(got.data(), k::PLE_HEAD_DIM); + const bool ok = le(head, 0.0) && le(tail, 0.0) && le(std::fabs(sum - o::kProbeSum[p]), 1e-9) && + nfg == 0; + std::printf(" %-46s %s (row %u: head %.3e tail %.3e sum d %.3e, non-finite %lld)\n", + p == 0 ? "row matches numpy's decode of the same bytes" : " (same, another row)", + ok ? "yes" : "*** NO ***", row, head, tail, std::fabs(sum - o::kProbeSum[p]), nfg); + if (!ok) ++probe_bad; + // and the two decoders must agree with each other bit for bit + for (int i = 0; i < k::PLE_HEAD_DIM; ++i) + if (got[i] != ref[i]) { std::printf(" byte-level decode differs at %d\n", i); ++probe_bad; break; } + } + bad += probe_bad; + } + + // ---- the split-half nibble order must be observable --------------------------------------------- + { + const std::vector raw = + read_at(gguf.c_str(), (long long) o::kTableDataStart + + (long long) o::kProbeRows[0] * k::PLE_ROW_BYTES, + (size_t) k::PLE_ROW_BYTES); + std::vector want(k::PLE_HEAD_DIM), inter(k::PLE_HEAD_DIM); + k::iq4nl_dequant_row(raw.data(), want.data()); + deq_interleaved(raw.data(), inter.data()); + const double rel = rel_l1(want.data(), inter.data(), k::PLE_HEAD_DIM); + const bool visible = gt(rel, 0.05); + std::printf(" %-46s %s (%.2f%% apart; generator says %.4f)\n", + "split-half vs INTERLEAVED nibbles observable", + visible ? "yes" : "*** NO ***", rel * 100, (double) o::kInterleavedSeparation); + if (!visible) ++bad; + } + + // ---- and reading at file offset 0 instead of data_start must be observable ---------------------- + { + const std::vector at_ds = read_at(gguf.c_str(), (long long) o::kTableDataStart, + (size_t) k::PLE_ROW_BYTES); + const std::vector at_0 = read_at(gguf.c_str(), 0, (size_t) k::PLE_ROW_BYTES); + std::vector ok_v(k::PLE_HEAD_DIM), at0(k::PLE_HEAD_DIM); + k::iq4nl_dequant_row(at_ds.data(), ok_v.data()); + k::iq4nl_dequant_row(at_0.data(), at0.data()); + const double rel = rel_l1(ok_v.data(), at0.data(), k::PLE_HEAD_DIM); + const bool visible = gt(rel, 0.05); + std::printf(" %-46s %s (%.2f%% apart)\n", + "data_start 192 vs file offset 0 observable", visible ? "yes" : "*** NO ***", rel * 100); + if (!visible) ++bad; + } + + // ---- head-slowest flatten ---------------------------------------------------------------------- + { + const uint32_t rows16[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + std::vector emb(k::NG_N_EMBD), one(k::PLE_HEAD_DIM); + table.gather(rows16, emb.data()); + bool blockwise = true; + for (int h = 0; h < k::PLE_N_HEADS && blockwise; ++h) { + table.read_row((uint32_t) h, one.data()); + for (int d = 0; d < k::PLE_HEAD_DIM; ++d) + if (emb[h * k::PLE_HEAD_DIM + d] != one[d]) { blockwise = false; break; } + } + // the rival: head-fastest, element (d,h) at d*16+h - a real transpose, not a reshape + std::vector fast(k::NG_N_EMBD); + for (int d = 0; d < k::PLE_HEAD_DIM; ++d) + for (int h = 0; h < k::PLE_N_HEADS; ++h) fast[d * k::PLE_N_HEADS + h] = emb[h * k::PLE_HEAD_DIM + d]; + long long diff = 0; + for (int i = 0; i < k::NG_N_EMBD; ++i) + if (fast[i] != emb[i]) ++diff; + std::printf(" %-46s %s (head h occupies [h*160,(h+1)*160))\n", "gather is head-slowest", + blockwise ? "yes" : "*** NO ***"); + std::printf(" %-46s %s (%lld of %d elements differ)\n", "head-fastest would differ", + diff > 0 ? "yes" : "*** NO ***", diff, k::NG_N_EMBD); + if (!blockwise || !diff) ++bad; + } + + // ============================ C. THE BLOCK ============================ + std::printf("\nC. the PLE block, against ggml's own graph (ple_in.bin / ple_out.bin)\n"); + if (!preflight_done && !load_capture(in_bin.c_str(), out_bin.c_str(), cap)) { + std::printf(" cannot load %s / %s\n", in_bin.c_str(), out_bin.c_str()); + std::printf("\nple_parity: %d failures, BLOCK SKIPPED; partial diagnostic only\n", bad); + return selftest || bad ? 1 : 0; + } + std::printf(" capture: n_embd %d, hc %d, nt %d, kern %d, dil %d, eps %g\n", cap.n_embd, cap.hc, cap.nt, + cap.kern, cap.dil, (double) cap.eps); + if (cap.n_embd != k::NG_N_EMBD || cap.hc != k::NG_HC || cap.kern != k::PLE_CONV_KERNEL || + cap.dil != k::NGRAM_SIZE) { + std::printf(" *** the capture's geometry is not the artifact's ***\n"); + return 1; + } + + if (!k::ple_block_available()) { + std::printf(" no CUDA device; the block SKIPPED, not passed.\n"); + std::printf("\nple_parity: %d failures, BLOCK SKIPPED\n", bad); + return selftest || bad ? 1 : 0; + } + + // ---- the two quantized weights, from the PACK, not from the capture. + // The capture holds `w_key` already dequantized to f32; the kernel needs the CODES AND SCALES, and + // re-quantizing the f32 would be a different tensor. Reading the pack is right and it was checked: + // the pack's decode of row 0 reproduces the capture's w_key row 0 exactly (see the round entry). + // Only the two regions are read, not all 5.4 GB of `dense.bin`. + std::vector key_codes = + read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyCodesOffset, (size_t) o::kKeyCodesBytes); + const std::vector raw_scales = + read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyScalesOffset, (size_t) o::kKeyScalesBytes); + const std::vector raw_value = + read_at((pack + "/dense.bin").c_str(), (long long) o::kValueOffset, (size_t) o::kValueBytes); + if (key_codes.empty() || raw_scales.empty() || raw_value.empty()) { + std::printf(" cannot read the ple_key/ple_value regions from %s/dense.bin\n", pack.c_str()); + return 2; + } + // fp16 -> f32 for the scales, which is what every S-form kernel in this project expects + const size_t n_scales = raw_scales.size() / 2; + std::vector key_scales(n_scales); + for (size_t i = 0; i < n_scales; ++i) { + uint16_t h; + std::memcpy(&h, raw_scales.data() + i * 2, 2); + key_scales[i] = k::f32_from_f16(h); + } + // ple_value is BF16 promoted to 32 bits in the pack; take the high half, which is exact + std::vector value_bf16(raw_value.size() / 4); + for (size_t i = 0; i < value_bf16.size(); ++i) { + uint32_t u; + std::memcpy(&u, raw_value.data() + i * 4, 4); + value_bf16[i] = (uint16_t) (u >> 16); + } + // ple_conv1d is F16 in the pack; the capture holds it as f32 in ggml order, and the kernel wants F16 + std::vector conv1d_f16(cap.w_conv.size()); + for (size_t i = 0; i < conv1d_f16.size(); ++i) conv1d_f16[i] = k::f16_from_f32(cap.w_conv[i]); + + // ---- the check that the two sources describe the SAME weights --------------------------------- + { + // dequantize key row 0 with the canonical rule and compare to the capture's w_key row 0. + // NOT `fmax`, for the reason above: it discards NaN, so a NaN would leave `worst` at 0 and report a + // perfect match. + double worst = 0; + bool first = true; + long long nf = 0; + for (int d = 0; d < k::NG_N_EMBD; ++d) { + const uint8_t byte = key_codes[d / 4]; + const int code = (byte >> ((d % 4) * 2)) & 3; + const float v = (float) (code + (-1)) * key_scales[d / 64]; + if (!std::isfinite(v) || !std::isfinite(cap.w_key[d])) { ++nf; continue; } + const double diff = std::fabs((double) v - (double) cap.w_key[d]); + if (first) { worst = diff; first = false; } + else worst = (diff > worst) ? diff : worst; + } + std::printf(" %-46s %s (worst |d| %.3e, non-finite %lld)\n", + "pack ple_key row 0 == the capture's w_key row 0", + (le(worst, 0.0) && nf == 0) ? "yes" : "*** NO ***", worst, nf); + if (!le(worst, 0.0) || nf) ++bad; + } + + // ---- run the block for both tokens of the capture --------------------------------------------- + const size_t hcd = (size_t) k::NG_HC_DIM, nd = (size_t) k::NG_N_EMBD; + std::vector dev_key(hcd), dev_value(nd), dev_gate(k::NG_HC), dev_gated(hcd), dev_norm(hcd), + dev_conv(hcd), dev_res(hcd); + float *d_emb = nullptr, *d_hid = nullptr, *d_hist = nullptr, *d_nk = nullptr, *d_nq = nullptr, + *d_nc = nullptr, *d_ck = nullptr, *d_cv = nullptr, *d_cn = nullptr, *d_cr = nullptr; + uint8_t* d_kc = nullptr; + uint16_t *d_vb = nullptr, *d_c1 = nullptr; + float *d_g = nullptr, *d_v = nullptr, *d_gd = nullptr, *d_nm = nullptr, *d_co = nullptr; + ck(cudaMalloc(&d_emb, nd * 4), "emb"); + ck(cudaMalloc(&d_hid, hcd * 4), "hid"); + ck(cudaMalloc(&d_hist, (size_t) k::NG_HIST * hcd * 4), "hist"); + ck(cudaMalloc(&d_nk, hcd * 4), "nk"); + ck(cudaMalloc(&d_nq, hcd * 4), "nq"); + ck(cudaMalloc(&d_nc, hcd * 4), "nc"); + ck(cudaMalloc(&d_kc, key_codes.size()), "kc"); + ck(cudaMalloc(&d_vb, value_bf16.size() * 2), "vb"); + ck(cudaMalloc(&d_c1, conv1d_f16.size() * 2), "c1"); + ck(cudaMalloc(&d_g, k::NG_HC * 4), "g"); + ck(cudaMalloc(&d_v, nd * 4), "v"); + ck(cudaMalloc(&d_gd, hcd * 4), "gd"); + ck(cudaMalloc(&d_nm, hcd * 4), "nm"); + ck(cudaMalloc(&d_co, hcd * 4), "co"); + ck(cudaMalloc(&d_ck, hcd * 4), "ck"); + ck(cudaMalloc(&d_cv, nd * 4), "cv"); + ck(cudaMalloc(&d_cn, hcd * 4), "cn"); + ck(cudaMalloc(&d_cr, hcd * 4), "cr"); + ck(cudaMemcpy(d_nk, cap.w_nk.data(), hcd * 4, cudaMemcpyHostToDevice), "cnk"); + ck(cudaMemcpy(d_nq, cap.w_nq.data(), hcd * 4, cudaMemcpyHostToDevice), "cnq"); + ck(cudaMemcpy(d_nc, cap.w_nc.data(), hcd * 4, cudaMemcpyHostToDevice), "cnc"); + ck(cudaMemcpy(d_kc, key_codes.data(), key_codes.size(), cudaMemcpyHostToDevice), "ckc"); + ck(cudaMemcpy(d_vb, value_bf16.data(), value_bf16.size() * 2, cudaMemcpyHostToDevice), "cvb"); + ck(cudaMemcpy(d_c1, conv1d_f16.data(), conv1d_f16.size() * 2, cudaMemcpyHostToDevice), "cc1"); + + k::PleWeights w{}; + w.key_codes = d_kc; + w.key_scales = key_scales.data(); // uploaded per call below so the pointer is a device one + w.value_bf16 = d_vb; + w.norm_key = d_nk; + w.norm_query = d_nq; + w.norm_conv = d_nc; + w.conv1d_f16 = d_c1; + float* d_ks = nullptr; + ck(cudaMalloc(&d_ks, key_scales.size() * 4), "ks"); + ck(cudaMemcpy(d_ks, key_scales.data(), key_scales.size() * 4, cudaMemcpyHostToDevice), "cks"); + w.key_scales = d_ks; + + // Per-stage comparison. Each stage the oracle records is a separate line, so a mismatch says WHICH part + // of the block is wrong rather than only that the sum is. The oracle writes each array token-major, so + // every slice is an explicit (offset, count) pair - deriving the offset from the stage's NAME, which the + // first version of this did, is a fixture that breaks the moment a name changes. + struct Stage { const char* name; const std::vector* got; const std::vector* all; + size_t offset; size_t n; }; + double worst_all = 0; + + // THE CONV HISTORY ADVANCES BETWEEN TOKENS, and getting this wrong is why token 1 compared badly at + // first. The capture is a TWO-TOKEN ubatch: ggml pads `[hist(9) | normalized(0..nt-1)]` ONCE and the conv + // reads rows `t+0, t+3, t+6, t+9` for output position t. So token 1's window is rows 1,4,7 of the SAME + // history plus row 10 - which is token 1's own normalized - i.e. the state slides by one NORMALIZED row + // per token. Feeding both tokens the original history compares my block's t=0 against ggml's t=1, and + // both my kernel and my host reference made the same mistake, so they agreed with each other and only the + // oracle could see it. + // + // ggml layout for the state is `ne=(hist, hc_dim)`: flat = row + NG_HIST*channel. + std::vector hist_state = cap.hist; + for (int t = 0; t < cap.nt; ++t) { + ck(cudaMemcpy(d_emb, cap.emb.data() + (size_t) t * nd, nd * 4, cudaMemcpyHostToDevice), "cemb"); + ck(cudaMemcpy(d_hid, cap.hidden.data() + (size_t) t * hcd, hcd * 4, cudaMemcpyHostToDevice), "chid"); + ck(cudaMemcpy(d_hist, hist_state.data(), (size_t) k::NG_HIST * hcd * 4, cudaMemcpyHostToDevice), + "chist"); + k::PleOut out{}; + out.key = d_ck; out.value = d_cv; out.gate = d_g; out.gated = d_gd; + out.normalized = d_nm; out.conv = d_co; out.result = d_cr; + // the workspace is the caller's, and the sync the block used to do is now the caller's too + void* ple_ws = nullptr; + ck(cudaMalloc(&ple_ws, k::ple_block_scratch_bytes()), "ple_block scratch"); + if (t == 0) { + const size_t bytes = (size_t) k::ple_block_scratch_bytes(); + ck(cudaMemset(ple_ws, 0xa5, bytes), "PLE prelaunch guard sentinel"); + const struct AliasCase { float* k::PleOut::* field; size_t offset; } cases[] = { + {&k::PleOut::key, 0}, {&k::PleOut::value, hcd}, {&k::PleOut::gate, hcd + nd}, + {&k::PleOut::gated, hcd + nd + (size_t) k::NG_HC}, + {&k::PleOut::normalized, 2 * hcd + nd + (size_t) k::NG_HC}, + {&k::PleOut::conv, 3 * hcd + nd + (size_t) k::NG_HC}, {&k::PleOut::result, 0} + }; + int refused = 0; + for (const auto& item : cases) { + k::PleOut invalid = out; + invalid.*(item.field) = static_cast(ple_ws) + item.offset; + try { k::ple_block(d_emb, d_hid, d_hist, w, invalid, ple_ws, nullptr); } + catch (const std::invalid_argument&) { ++refused; } + } + ck(cudaDeviceSynchronize(), "PLE guard no-launch sync"); + std::vector sentinel(bytes); + ck(cudaMemcpy(sentinel.data(), ple_ws, bytes, cudaMemcpyDeviceToHost), "PLE guard sentinel readback"); + const bool unchanged = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t b) { return b == 0xa5; }); + const bool rejected = refused == 7 && unchanged; + std::printf(" PLE old caller output offsets rejected before launch: %s (%d/7, scratch %s)\n", + rejected ? "pass" : "FAIL", refused, unchanged ? "unchanged" : "CORRUPTED"); + if (!rejected) ++bad; + } + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); + ck(cudaDeviceSynchronize(), "ple_block sync"); + ck(cudaMemcpy(dev_key.data(), d_ck, hcd * 4, cudaMemcpyDeviceToHost), "rck"); + ck(cudaMemcpy(dev_value.data(), d_cv, nd * 4, cudaMemcpyDeviceToHost), "rcv"); + ck(cudaMemcpy(dev_gate.data(), d_g, k::NG_HC * 4, cudaMemcpyDeviceToHost), "rg"); + ck(cudaMemcpy(dev_gated.data(), d_gd, hcd * 4, cudaMemcpyDeviceToHost), "rgd"); + ck(cudaMemcpy(dev_norm.data(), d_nm, hcd * 4, cudaMemcpyDeviceToHost), "rnm"); + ck(cudaMemcpy(dev_conv.data(), d_co, hcd * 4, cudaMemcpyDeviceToHost), "rco"); + ck(cudaMemcpy(dev_res.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "rcr"); + + const size_t ok_ = (size_t) t * hcd, ov = (size_t) t * nd, og = (size_t) t * (size_t) k::NG_HC; + const Stage stages[] = { + {"key (grouped_norm of ple_key @ emb)", &dev_key, &cap.key, ok_, hcd}, + {"value (ple_value @ emb, BF16)", &dev_value, &cap.value, ov, nd}, + {"gate (signed sqrt, sigmoid)", &dev_gate, &cap.gate, og, (size_t) k::NG_HC}, + {"gated (value broadcast * gate)", &dev_gated, &cap.gated, ok_, hcd}, + {"normalized (grouped_norm(gated, ple_norm_conv))", &dev_norm, &cap.normalized, ok_, hcd}, + {"conv_out (dilated conv, then SiLU)", &dev_conv, &cap.conv_out, ok_, hcd}, + {"result (hidden + gated + conv)", &dev_res, &cap.result, ok_, hcd}, + }; + for (const Stage& s : stages) { + std::vector want(s.all->begin() + (long long) s.offset, + s.all->begin() + (long long) (s.offset + s.n)); + double mag = 0; + long long nf = 0; + const double rel = rel_l1(want.data(), s.got->data(), s.n, &mag, &nf); + // NaN-SAFE: `rel > worst_all` is false for NaN, so `fmax` here would silently report a perfect + // score for a fixture full of NaNs - round 197's exact failure. + worst_all = (rel > worst_all) ? rel : worst_all; + if (nf) worst_all = std::nan(""); + const bool last = (std::strncmp(s.name, "result", 6) == 0); + std::printf(" token %d %-46s rel %.3e (mean |ref| %.4f, non-finite %lld)%s\n", t, s.name, rel, + mag, nf, last && !le(rel, 1e-2) ? " *** over 1e-2 ***" : ""); + // TOLERANCE, and what sets it: this comparison is the GPU against a capture whose weights are + // F32, so ggml performed NO activation conversion while the kernel applies the CONTRACT (Q8_0 + // for the Q2_0 weight, BF16 for the BF16 one). The contract's per-element cost is 2^-9 = 1.95e-3 + // for BF16 and ~0.4% for Q8_0, so the OUTPUT difference is ~2e-3 wherever there is no + // cancellation and larger where there is - `conv_out` cancels by ~77x and is the one stage that + // exceeds it. `result` is the quantity that matters and 1e-2 is five times the contract's own + // per-element size, so it is a bound on "the contract and nothing else", not a judgement call. + // The HOST reference below uses the capture's own F32 weights and is asserted at 1e-4, which is + // what proves the difference here IS the contract. + if (last && !le(rel, 1e-2)) ++bad; + } + + if (t == 0) { + // Deliberate BF16 halfway values make the value projection's activation precision visible. + // The scalar reference uses the actual packed BF16 weight bits and unrounded F32 inputs. + std::vector witness(nd), reference_value(nd), native_value(nd), native_result(hcd), replay(hcd); + for (size_t i = 0; i < nd; ++i) witness[i] = i % 7 == 0 ? 1.00390625f : -0.501953125f; + for (size_t row = 0; row < nd; ++row) { + double sum = 0.0; + for (size_t col = 0; col < nd; ++col) { + const uint32_t bits = uint32_t(value_bf16[row * nd + col]) << 16; + float weight; + std::memcpy(&weight, &bits, sizeof(weight)); + sum += double(weight) * witness[col]; + } + reference_value[row] = float(sum); + } + ck(cudaMemcpy(d_emb, witness.data(), nd * sizeof(float), cudaMemcpyHostToDevice), "native PLE witness"); + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); + ck(cudaDeviceSynchronize(), "legacy PLE witness sync"); + std::vector legacy_value(nd); + ck(cudaMemcpy(legacy_value.data(), d_cv, nd * sizeof(float), cudaMemcpyDeviceToHost), "legacy PLE witness value"); + cudaStream_t stream; + ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native PLE stream"); + k::ple_set_native_bf16(true); + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream); + ck(cudaStreamSynchronize(stream), "native PLE sync"); + ck(cudaMemcpy(native_value.data(), d_cv, nd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE value"); + ck(cudaMemcpy(native_result.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE result"); + long long nf = 0; + const double rel = rel_l1(reference_value.data(), native_value.data(), nd, nullptr, &nf); + const double separation = rel_l1(native_value.data(), legacy_value.data(), nd); + const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5); + std::printf(" native PLE value: %s (ref rel %.3e, BF16 separation %.3e)\n", + correct ? "pass" : "FAIL", rel, separation); + if (!correct) ++bad; + cudaGraph_t graph; + cudaGraphExec_t executable; + ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native PLE capture"); + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream); + ck(cudaStreamEndCapture(stream, &graph), "native PLE capture end"); + ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native PLE instantiate"); + k::ple_set_native_bf16(false); + ck(cudaGraphLaunch(executable, stream), "native PLE replay"); + ck(cudaStreamSynchronize(stream), "native PLE replay sync"); + ck(cudaMemcpy(replay.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "native PLE replay result"); + const bool captured = std::memcmp(native_result.data(), replay.data(), hcd * sizeof(float)) == 0; + std::printf(" native PLE captured selection: %s\n", captured ? "byte-identical" : "FAIL"); + if (!captured) ++bad; + ck(cudaGraphExecDestroy(executable), "native PLE graph exec destroy"); + ck(cudaGraphDestroy(graph), "native PLE graph destroy"); + ck(cudaStreamDestroy(stream), "native PLE stream destroy"); + ck(cudaMemcpy(d_emb, cap.emb.data(), nd * sizeof(float), cudaMemcpyHostToDevice), "restore PLE embedding"); + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); + ck(cudaDeviceSynchronize(), "restored PLE sync"); + ck(cudaMemcpy(replay.data(), d_cr, hcd * sizeof(float), cudaMemcpyDeviceToHost), "restored PLE result"); + const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * sizeof(float)) == 0; + std::printf(" restored PLE default: %s\n", restored ? "byte-identical" : "FAIL"); + if (!restored) ++bad; + } + + if (t == 0) { + // This checks native-projection wiring and graph lifetime, independently + // of the legacy CPU/F32 structural capture. Actual Q2_0 arithmetic is + // checked separately by native_mmvq_parity against the pinned CUDA DLL. + const size_t blocks = n_scales, native_bytes = blocks * 18, guard = 64; + const size_t qbytes = k::native_q8_1_bytes(k::NG_N_EMBD); + std::vector native_key(native_bytes); + for (size_t b = 0; b < blocks; ++b) { + std::memcpy(native_key.data() + b * 18, raw_scales.data() + b * 2, 2); + std::memcpy(native_key.data() + b * 18 + 2, key_codes.data() + b * 16, 16); + } + void *native_storage = nullptr, *q_storage = nullptr; + float* raw_projection = nullptr; + ck(cudaMalloc(&native_storage, native_bytes + 2 * guard), "native PLE weights"); + ck(cudaMalloc(&q_storage, qbytes + 2 * guard), "native PLE q8 scratch"); + ck(cudaMalloc(&raw_projection, hcd * 4), "native PLE raw projection"); + ck(cudaMemset(native_storage, 0xa5, native_bytes + 2 * guard), "native PLE weight guards"); + ck(cudaMemset(q_storage, 0xa5, qbytes + 2 * guard), "native PLE q8 guards"); + void* native_data = static_cast(native_storage) + guard; + void* native_q = static_cast(q_storage) + guard; + ck(cudaMemcpy(native_data, native_key.data(), native_bytes, cudaMemcpyHostToDevice), "native PLE weights upload"); + k::PleWeights nw = w; + nw.key_native_data = native_data; nw.key_native_type = 42; nw.key_native_q8_1 = native_q; + cudaStream_t stream; + ck(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native PLE key stream"); + const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes(); + ck(cudaMemset(ple_ws, 0xa5, workspace_bytes), "native PLE no-launch sentinel"); + int refused = 0; + for (int c = 0; c < 9; ++c) { + auto invalid = nw; + if (c == 0) invalid.key_native_type = 11; + if (c == 1) invalid.key_native_q8_1 = nullptr; + if (c == 3) invalid.key_native_q8_1 = ple_ws; + if (c == 4) invalid.key_native_q8_1 = d_emb; + if (c == 5) invalid.key_native_q8_1 = out.key; + if (c == 6) invalid.key_native_q8_1 = static_cast(native_q) + 1; + if (c == 7) invalid.key_native_data = static_cast(native_data) + 1; + if (c == 8) invalid.key_native_q8_1 = native_data; + try { k::ple_block(d_emb, d_hid, d_hist, invalid, out, ple_ws, c == 2 ? nullptr : stream); } + catch (const std::invalid_argument&) { ++refused; } + } + ck(cudaStreamSynchronize(stream), "native PLE refusal sync"); + std::vector sentinel(workspace_bytes); + ck(cudaMemcpy(sentinel.data(), ple_ws, workspace_bytes, cudaMemcpyDeviceToHost), "native PLE refusal sentinel"); + const bool untouched = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t x) { return x == 0xa5; }); + std::printf(" native PLE key prelaunch guards: %s (%d/9, workspace %s)\n", + refused == 9 && untouched ? "pass" : "FAIL", refused, untouched ? "unchanged" : "changed"); + if (refused != 9 || !untouched) ++bad; + cudaGraph_t graph = nullptr; cudaGraphExec_t executable = nullptr; + std::vector projected(hcd), normalized(hcd), actual_key(hcd), actual_result(hcd), replay(hcd); + for (int p = 0; p < std::min(cap.nt, 2); ++p) { + ck(cudaMemcpy(d_emb, cap.emb.data() + (size_t) p * nd, nd * 4, cudaMemcpyHostToDevice), "native PLE key input"); + k::native_q2_0_f32(native_data, d_emb, native_q, raw_projection, k::NG_N_EMBD, k::NG_HC_DIM, 1, stream); + ck(cudaStreamSynchronize(stream), "native PLE raw key sync"); + ck(cudaMemcpy(projected.data(), raw_projection, hcd * 4, cudaMemcpyDeviceToHost), "native PLE raw key read"); + for (int c = 0; c < k::NG_HC; ++c) { + double sum = 0; + for (size_t j = 0; j < nd; ++j) { const float v = projected[(size_t) c * nd + j]; sum += double(v * v); } + const float scale = 1.0f / std::sqrt(float(sum / double(nd)) + k::NG_RMS_EPS); + for (size_t j = 0; j < nd; ++j) { const size_t i = (size_t) c * nd + j; normalized[i] = projected[i] * scale * cap.w_nk[i]; } + } + k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream); + ck(cudaStreamSynchronize(stream), "native PLE key direct sync"); + ck(cudaMemcpy(actual_key.data(), d_ck, hcd * 4, cudaMemcpyDeviceToHost), "native PLE key read"); + ck(cudaMemcpy(actual_result.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE result read"); + const double rel = rel_l1(normalized.data(), actual_key.data(), hcd); + const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0; + std::printf(" native PLE key projection->existing norm input %d: %s (rel %.3e)\n", p, wired ? "pass" : "FAIL", rel); + if (!wired) ++bad; + if (p == 0) { + ck(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native PLE key capture"); + k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream); + ck(cudaStreamEndCapture(stream, &graph), "native PLE key capture end"); + ck(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native PLE key instantiate"); + } + nw.key_native_data = nullptr; // graph selection must survive descriptor changes + for (int repeat = 0; repeat < 2; ++repeat) { + ck(cudaGraphLaunch(executable, stream), "native PLE key replay"); + ck(cudaStreamSynchronize(stream), "native PLE key replay sync"); + ck(cudaMemcpy(replay.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE key replay read"); + if (std::memcmp(actual_result.data(), replay.data(), hcd * 4) != 0) ++bad; + } + nw.key_native_data = native_data; + } + ck(cudaGraphExecDestroy(executable), "native PLE key executable destroy"); + ck(cudaGraphDestroy(graph), "native PLE key graph destroy"); + for (int b = 0; b < 2; ++b) { + const void* storage = b == 0 ? native_storage : q_storage; + const size_t payload = b == 0 ? native_bytes : qbytes; + std::vector ends(2 * guard); + ck(cudaMemcpy(ends.data(), storage, guard, cudaMemcpyDeviceToHost), "native PLE prefix guard"); + ck(cudaMemcpy(ends.data() + guard, static_cast(storage) + guard + payload, guard, cudaMemcpyDeviceToHost), "native PLE suffix guard"); + if (!std::all_of(ends.begin(), ends.end(), [](uint8_t x) { return x == 0xa5; })) ++bad; + } + ck(cudaStreamDestroy(stream), "native PLE key stream destroy"); + cudaFree(raw_projection); cudaFree(q_storage); cudaFree(native_storage); + ck(cudaMemcpy(d_emb, cap.emb.data(), nd * 4, cudaMemcpyHostToDevice), "native PLE restore input"); + k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr); + ck(cudaDeviceSynchronize(), "native PLE default restore sync"); + ck(cudaMemcpy(replay.data(), d_cr, hcd * 4, cudaMemcpyDeviceToHost), "native PLE default restore read"); + const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * 4) == 0; + std::printf(" native PLE key graph/repeat/buffer guards checked; restored default: %s\n", restored ? "byte-identical" : "FAIL"); + if (!restored) ++bad; + } + + if (t == 0) { + // The engine only needs result and normalized. Export normalized after the complete private + // workspace; result may overwrite hidden once its original values are no longer needed. + const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes(); + void* compact_workspace = nullptr; + ck(cudaMalloc(&compact_workspace, workspace_bytes + hcd * sizeof(float)), "compact PLE workspace"); + k::PleOut compact{}; + compact.normalized = reinterpret_cast(static_cast(compact_workspace) + workspace_bytes); + compact.result = d_hid; + k::ple_block(d_emb, d_hid, d_hist, w, compact, compact_workspace, nullptr); + ck(cudaDeviceSynchronize(), "compact PLE sync"); + std::vector compact_norm(hcd), compact_result(hcd); + ck(cudaMemcpy(compact_norm.data(), compact.normalized, hcd * sizeof(float), cudaMemcpyDeviceToHost), "compact PLE normalized"); + ck(cudaMemcpy(compact_result.data(), d_hid, hcd * sizeof(float), cudaMemcpyDeviceToHost), "compact PLE result"); + const bool equal = std::memcmp(compact_norm.data(), dev_norm.data(), hcd * sizeof(float)) == 0 && + std::memcmp(compact_result.data(), dev_res.data(), hcd * sizeof(float)) == 0; + std::printf(" PLE separate exports and in-place hidden result: %s\n", equal ? "byte-identical" : "FAIL"); + if (!equal) ++bad; + ck(cudaMemcpy(d_hid, cap.hidden.data(), hcd * sizeof(float), cudaMemcpyHostToDevice), "restore PLE hidden input"); + cudaFree(compact_workspace); + } + + // slide the conv state by one NORMALIZED row, which is what the next token's window needs + for (size_t c = 0; c < hcd; ++c) + for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r) + hist_state[r + (size_t) k::NG_HIST * c] = hist_state[(r + 1) + (size_t) k::NG_HIST * c]; + for (size_t c = 0; c < hcd; ++c) + hist_state[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = dev_norm[c]; + cudaFree(ple_ws); + } + + // ---- the trap that matters most: gated vs normalized as the conv input -------------------------- + // `ref/ngram.py`'s docstring calls `terms` "the padded gated values"; the source pads `normalized`. + // Feeding the conv the gated values instead is a one-word change with every shape intact, so it is + // computed here and required to differ. + { + const double rel_norm_gated = rel_l1(cap.gated.data(), cap.normalized.data(), hcd); + std::printf(" %-52s %s (%.2f%% apart)\n", "normalized vs gated as the conv input is observable", + rel_norm_gated > 0.05 ? "yes" : "*** NO ***", rel_norm_gated * 100); + if (!(rel_norm_gated > 0.05)) ++bad; + } + + // ---- the conv TAP ORDER: tap 0 reads the furthest back, not the current row --------------------- + { + // Recompute the conv on the host with the taps reversed, from the ORACLE's own `normalized`, and + // require the result to differ from the oracle's conv_out. + const size_t hcd2 = hcd; + std::vector rev(hcd2, 0.0f); + for (size_t c = 0; c < hcd2; ++c) { + float acc = 0; + for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { + // THE RIVAL READING OF THE TAP CONVENTION. ggml's is `t - (K-1-k)*d`, i.e. tap 0 reads the + // FURTHEST back; the natural misreading is `t - k*d`, i.e. tap 0 reads the CURRENT row. + // + // The first version of this trap wrote `row = kk*dil` for the rival - which is ALGEBRAICALLY + // THE SAME as the correct `hist - (K-1-kk)*dil` whenever `hist == (K-1)*dil`, because + // `9-(3-kk)*3 == 3kk` identically. It reported "0.00% apart" and was measuring nothing. + // The rival has to REVERSE the row order: `(K-1-kk)*dil` gives 9,6,3,0 against the correct + // 0,3,6,9, so tap 0 pairs the kernel's first weight with the NEWEST row instead of the oldest. + const int row = (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; + // ROW-FASTEST: the capture's history is ggml's `ne=(hist, hc_dim)`, flat = row + hist*channel + const float v = (row == k::NG_HIST) ? cap.normalized[c] + : cap.hist[(size_t) row + (size_t) k::NG_HIST * c]; + // GGML-NATIVE: `w_conv[k + kern*c]`, because the capture's tensor is ne=(kern, hc_dim) with + // ne0 = kern fast. `w_conv[kk*hc_dim + c]` is the TRANSPOSE and is what this reference had + // first - it reported 115% on conv_out while the GPU kernel, which carries the layout note, + // was within 4.6e-02. The oracle caught the reference, not the kernel, which is the whole + // reason for having one. + acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * v; + } + rev[c] = acc / (1.0f + std::exp(-acc)); + } + const double rel = rel_l1(cap.conv_out.data(), rev.data(), hcd2); + std::printf(" %-52s %s (%.2f%% apart)\n", "reversed conv tap order is observable", + gt(rel, 0.05) ? "yes" : "*** NO ***", rel * 100); + if (!gt(rel, 0.05)) ++bad; + } + + // ---- THE HOST f32 REFERENCE, which is what makes the gaps above ATTRIBUTABLE rather than mysterious. + // + // `ple_layer_xcheck.cpp` builds ggml's graph with the weights as **F32 tensors** (`ggml_new_tensor_2d(..., + // GGML_TYPE_F32, ...)`). `ggml_mul_mat` converts src1 to src0's `vec_dot_type`, so with an F32 weight + // ggml performs NO activation conversion at all - while the real `ple_key` is Q2_0 (contract Q8_0) and the + // real `ple_value` is BF16 (contract BF16). + // + // **The capture is therefore a valid oracle for the STRUCTURE and not for the ACTIVATION CONTRACT.** This + // reference reproduces it exactly, in f32, using the capture's own weights - which proves every LAYOUT in + // the block (the conv kernel's `k + kern*c`, the row-fastest history, per-stream grouped norms, the + // head-slowest gather) independently of the GPU. Whatever gap remains between the GPU and the capture is + // then exactly the contract, and nothing else. + // Hoisted out of the reference block below: the term-magnitude metric needs the state the LAST token + // used, and that block has already closed by the time it runs. + std::vector hist_last; + { + const size_t H = hcd, N = nd; + std::vector k_ref(H), q_ref(H), v_ref(N), gt_ref(k::NG_HC), gd_ref(H), nm_ref(H), cv_ref(H), + rs_ref(H); + auto gnorm = [&](const float* x, const float* w, float* y, int n) { + for (int c = 0; c < k::NG_HC; ++c) { + double sum = 0.0; + for (int d = 0; d < k::NG_N_EMBD; ++d) { + const float xv = x[c * k::NG_N_EMBD + d]; + sum += (double) (xv * xv); // f32 product, widened - as ggml does + } + const float mean = (float) (sum / k::NG_N_EMBD); + const float scale = 1.0f / std::sqrt(mean + cap.eps); + for (int d = 0; d < k::NG_N_EMBD; ++d) + y[c * k::NG_N_EMBD + d] = x[c * k::NG_N_EMBD + d] * scale * w[c * k::NG_N_EMBD + d]; + } + (void) n; + }; + // The SAME history advance as the GPU loop, so the two are compared on identical inputs. + std::vector hist_ref = cap.hist; + for (int t = 0; t < cap.nt; ++t) { + const float* emb = cap.emb.data() + (size_t) t * N; + const float* hid = cap.hidden.data() + (size_t) t * H; + // key = w_key @ emb, with the capture's F32 weight and NO activation conversion + for (size_t o = 0; o < H; ++o) { + double a = 0; + for (size_t i = 0; i < N; ++i) a += (double) cap.w_key[o * N + i] * (double) emb[i]; + k_ref[o] = (float) a; + } + gnorm(k_ref.data(), cap.w_nk.data(), k_ref.data(), k::NG_N_EMBD); + gnorm(hid, cap.w_nq.data(), q_ref.data(), k::NG_N_EMBD); + for (size_t o = 0; o < N; ++o) { + double a = 0; + for (size_t i = 0; i < N; ++i) a += (double) cap.w_value[o * N + i] * (double) emb[i]; + v_ref[o] = (float) a; + } + for (int c = 0; c < k::NG_HC; ++c) { + double a = 0; + for (int d = 0; d < k::NG_N_EMBD; ++d) + a += (double) k_ref[c * k::NG_N_EMBD + d] * (double) q_ref[c * k::NG_N_EMBD + d]; + const float s = (float) (a / (double) 1.0) / std::sqrt((float) k::NG_N_EMBD); + const float mag = std::sqrt(std::fmax(std::fabs(s), 1e-6f)); + const float sgn = (s > 0) ? 1.0f : ((s < 0) ? -1.0f : 0.0f); + gt_ref[c] = 1.0f / (1.0f + std::exp(-(sgn * mag))); + } + for (size_t i = 0; i < H; ++i) + gd_ref[i] = v_ref[i % N] * gt_ref[i / N]; + gnorm(gd_ref.data(), cap.w_nc.data(), nm_ref.data(), k::NG_N_EMBD); + for (size_t c = 0; c < H; ++c) { + float acc = 0; + for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { + const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; + // capture history is ggml `ne=(hist, hc_dim)`: flat = row + hist*channel. `hist_ref` is + // the ADVANCED state, so this reference sees exactly what the GPU call saw. + const float vv = (row == k::NG_HIST) ? nm_ref[c] + : hist_ref[(size_t) row + (size_t) k::NG_HIST * c]; + acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * vv; + } + cv_ref[c] = acc / (1.0f + std::exp(-acc)); + } + for (size_t i = 0; i < H; ++i) rs_ref[i] = hid[i] + gd_ref[i] + cv_ref[i]; + + const size_t ok_ = (size_t) t * H, ov = (size_t) t * N, og = (size_t) t * (size_t) k::NG_HC; + struct HCmp { const char* name; const std::vector* got; const std::vector* all; + size_t off; size_t n; }; + const HCmp cmps[] = { + {"key", &k_ref, &cap.key, ok_, H}, {"value", &v_ref, &cap.value, ov, N}, + {"gate", >_ref, &cap.gate, og, (size_t) k::NG_HC}, + {"gated", &gd_ref, &cap.gated, ok_, H}, {"normalized", &nm_ref, &cap.normalized, ok_, H}, + {"conv_out", &cv_ref, &cap.conv_out, ok_, H}, + {"result", &rs_ref, &cap.result, ok_, H}, + }; + for (const HCmp& s : cmps) { + std::vector want(s.all->begin() + (long long) s.off, + s.all->begin() + (long long) (s.off + s.n)); + long long nf = 0; + const double rel = rel_l1(want.data(), s.got->data(), s.n, nullptr, &nf); + const bool ok = le(rel, 1e-4) && nf == 0; + std::printf(" host f32 reference, token %d %-12s rel %.3e (non-finite %lld)%s\n", t, s.name, + rel, nf, ok ? "" : " *** FAIL ***"); + if (!ok) ++bad; + } + + // save the state this token used, then slide it - identical to the GPU-side advance + if (t == cap.nt - 1) hist_last = hist_ref; + for (size_t c = 0; c < hcd; ++c) + for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r) + hist_ref[r + (size_t) k::NG_HIST * c] = hist_ref[(r + 1) + (size_t) k::NG_HIST * c]; + for (size_t c = 0; c < hcd; ++c) + hist_ref[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = nm_ref[c]; + } + // TOLERANCE: 1e-4. Both sides are f32 (or f64-accumulated) sums of 2560 products, so the only + // difference is summation ORDER, which is ~n*eps = 2560*6e-8 = 1.5e-4 worst case and far less in + // practice. A STRUCTURAL error - a transposed conv kernel, a channel-slow history, a head-fastest + // gather - is O(1), so the two are three orders apart and the bound is not a judgement call. + } + + // ---- `conv_out`'s error must be measured against the TERMS, not the result ---------------------- + // + // The dilated conv sums four terms and the sum CANCELS: `normalized` has mean |.| around 0.70 and the + // result's is around 0.009, a factor of ~77. Dividing by the result therefore reports the CONDITION + // NUMBER and not the arithmetic - the same metric mistake this project has made four times (rounds 169, + // 189, 194, 196), and it is what made `conv_out` look like the worst stage at 4.55e-02. + { + // `dev_conv` holds the LAST token after the loop above, and the capture is token-major. + const float* oc = cap.conv_out.data() + (size_t) (cap.nt - 1) * hcd; + double num = 0, terms = 0, res = 0; + for (size_t c = 0; c < hcd; ++c) { + double t_sum = 0; + for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) { + const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE; + const float v = (row == k::NG_HIST) + ? cap.normalized[(size_t) (cap.nt - 1) * hcd + c] + : hist_last[(size_t) row + (size_t) k::NG_HIST * c]; + t_sum += std::fabs((double) cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * + (double) v); + } + terms += t_sum; + res += std::fabs((double) oc[c]); + num += std::fabs((double) oc[c] - (double) dev_conv[c]); + } + std::printf("\n conv_out (token %d) against the TERM magnitude, not the result: rel %.3e" + " (|result|/|terms| = %.4f)\n", + cap.nt - 1, num / terms, res / terms); + } + + std::printf("\nple_parity: %d failures (worst stage rel %.3e)\n", bad, worst_all); + if (bad) return 1; + if (selftest) std::printf("ple_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/ple_q5_parity.cpp b/engine/strata/src/kernels/ple_q5_parity.cpp new file mode 100644 index 00000000..cd387a8e --- /dev/null +++ b/engine/strata/src/kernels/ple_q5_parity.cpp @@ -0,0 +1,59 @@ +// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/ngram.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: ple_q5_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* tensor = gguf.find("per_layer_token_embd.weight"); + if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) { + std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n"); + return 2; + } + strata::kernels::PleIoOptions options; + options.mode = strata::kernels::PleIo::Mmap; + strata::kernels::PleTable table; + std::string err; + if (!table.open(argv[1], err, options)) { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0); + const uint8_t* bytes = gguf.tensor_data(*tensor); + const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)}; + double max_abs = 0.0; + for (uint32_t row : probes) { + float got[160], want[160]; + table.read_row(row, got); + traits->to_float(bytes + (size_t) row * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i])); + } + uint32_t rows[16]; + for (int i = 0; i < 16; ++i) rows[i] = probes[i % 5]; + float batch[16 * 160]; + if (!table.issue(rows) || !table.collect(batch, err)) { + std::fprintf(stderr, "collect: %s\n", err.c_str()); + return 1; + } + for (int h = 0; h < 16; ++h) { + float want[160]; + traits->to_float(bytes + (size_t) rows[h] * 110, want, 160); + for (int i = 0; i < 160; ++i) + max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i])); + } + std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs, + max_abs <= 1e-6 ? "PASS" : "FAIL"); + return max_abs <= 1e-6 ? 0 : 1; +} diff --git a/engine/strata/src/kernels/q5_projection_parity.cpp b/engine/strata/src/kernels/q5_projection_parity.cpp new file mode 100644 index 00000000..20faf995 --- /dev/null +++ b/engine/strata/src/kernels/q5_projection_parity.cpp @@ -0,0 +1,62 @@ +// Q5_1 shared-expert projection: Strata CUDA dequantization vs ggml. +#define NOMINMAX +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/dequant_bf16.hpp" +#include "ggml.h" + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: q5_projection_parity \n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + const auto* t = gguf.find("blk.0.ffn_down_shexp.weight"); + if (!t || t->type != 7 || t->shape.size() != 2) { + std::fprintf(stderr, "expected blk.0.ffn_down_shexp.weight Q5_1\n"); + return 2; + } + const int64_t cols = (int64_t) t->shape[0], rows = std::min(4, (int64_t) t->shape[1]); + const size_t weight_bytes = (size_t) rows * (size_t) (cols / 32) * 24; + const size_t elements = (size_t) rows * (size_t) cols; + const uint8_t* source = gguf.tensor_data(*t); + void *dweight = nullptr, *dfloat = nullptr, *dbf16 = nullptr; + if (cudaMalloc(&dweight, weight_bytes) != cudaSuccess || + cudaMalloc(&dfloat, elements * sizeof(float)) != cudaSuccess || + cudaMalloc(&dbf16, elements * sizeof(uint16_t)) != cudaSuccess) { + std::fprintf(stderr, "CUDA allocation failed\n"); + return 1; + } + cudaMemcpy(dweight, source, weight_bytes, cudaMemcpyHostToDevice); + strata::kernels::dequant_f32(7, dweight, 0, rows, cols, (float*) dfloat, nullptr); + strata::kernels::dequant_bf16(7, dweight, 0, rows, cols, (uint16_t*) dbf16, nullptr); + std::vector got(elements), ref(elements); + std::vector got_bf16(elements); + cudaMemcpy(got.data(), dfloat, elements * sizeof(float), cudaMemcpyDeviceToHost); + cudaMemcpy(got_bf16.data(), dbf16, elements * sizeof(uint16_t), cudaMemcpyDeviceToHost); + cudaFree(dweight); cudaFree(dfloat); cudaFree(dbf16); + const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1); + for (int64_t r = 0; r < rows; ++r) + traits->to_float(source + (size_t) r * (size_t) (cols / 32) * 24, + ref.data() + (size_t) r * (size_t) cols, cols); + double max_abs = 0; + size_t bf16_bad = 0; + for (size_t i = 0; i < elements; ++i) { + max_abs = std::max(max_abs, (double) std::fabs(got[i] - ref[i])); + uint32_t bits; + std::memcpy(&bits, &ref[i], sizeof(bits)); + const uint16_t expected = (uint16_t) ((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); + if (got_bf16[i] != expected) ++bf16_bad; + } + const bool ok = max_abs <= 1e-6 && bf16_bad == 0; + std::printf("Q5_1 projection: %zu elements, max_abs %.3e, bf16 differences %zu %s\n", + elements, max_abs, bf16_bad, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/engine/strata/src/kernels/qsa_oracle_vectors.inc b/engine/strata/src/kernels/qsa_oracle_vectors.inc new file mode 100644 index 00000000..0ceec330 --- /dev/null +++ b/engine/strata/src/kernels/qsa_oracle_vectors.inc @@ -0,0 +1,134 @@ +// GENERATED by scripts/_gen_f16_oracle.py - do not edit. +// {f32 bits, np.float16(np.float32(x)) bits} interleaved, flat, for qsa_parity.cpp. + 0x00000000u, 0x0000u, 0x80000000u, 0x8000u, 0x3F800000u, 0x3C00u, + 0xBF800000u, 0xBC00u, 0x3F000000u, 0x3800u, 0x477FE000u, 0x7BFFu, + 0x477FEF00u, 0x7BFFu, 0x477FF000u, 0x7C00u, 0x47800000u, 0x7C00u, + 0x7149F2CAu, 0x7C00u, 0xF149F2CAu, 0xFC00u, 0x38800000u, 0x0400u, + 0x33800000u, 0x0001u, 0x33000000u, 0x0000u, 0x3380D959u, 0x0001u, + 0xB380D959u, 0x8001u, 0x337FFAE5u, 0x0001u, 0x322BCC77u, 0x0000u, + 0x00000001u, 0x0000u, 0x3EAAAAABu, 0x3555u, 0x39000000u, 0x0800u, + 0x47000000u, 0x7800u, 0x3727C5ACu, 0x00A8u, 0x38800800u, 0x0400u, + 0x38801000u, 0x0400u, 0x38801800u, 0x0401u, 0x39000800u, 0x0800u, + 0x39001000u, 0x0800u, 0x39001800u, 0x0801u, 0x39800000u, 0x0C00u, + 0x39800800u, 0x0C00u, 0x39801000u, 0x0C00u, 0x39801800u, 0x0C01u, + 0x3A000000u, 0x1000u, 0x3A000800u, 0x1000u, 0x3A001000u, 0x1000u, + 0x3A001800u, 0x1001u, 0x3A800000u, 0x1400u, 0x3A800800u, 0x1400u, + 0x3A801000u, 0x1400u, 0x3A801800u, 0x1401u, 0x3B000000u, 0x1800u, + 0x3B000800u, 0x1800u, 0x3B001000u, 0x1800u, 0x3B001800u, 0x1801u, + 0x3B800000u, 0x1C00u, 0x3B800800u, 0x1C00u, 0x3B801000u, 0x1C00u, + 0x3B801800u, 0x1C01u, 0x3C000000u, 0x2000u, 0x3C000800u, 0x2000u, + 0x3C001000u, 0x2000u, 0x3C001800u, 0x2001u, 0x3C800000u, 0x2400u, + 0x3C800800u, 0x2400u, 0x3C801000u, 0x2400u, 0x3C801800u, 0x2401u, + 0x3D000000u, 0x2800u, 0x3D000800u, 0x2800u, 0x3D001000u, 0x2800u, + 0x3D001800u, 0x2801u, 0x3D800000u, 0x2C00u, 0x3D800800u, 0x2C00u, + 0x3D801000u, 0x2C00u, 0x3D801800u, 0x2C01u, 0x3E000000u, 0x3000u, + 0x3E000800u, 0x3000u, 0x3E001000u, 0x3000u, 0x3E001800u, 0x3001u, + 0x3E800000u, 0x3400u, 0x3E800800u, 0x3400u, 0x3E801000u, 0x3400u, + 0x3E801800u, 0x3401u, 0x3F000800u, 0x3800u, 0x3F001000u, 0x3800u, + 0x3F001800u, 0x3801u, 0x3F800800u, 0x3C00u, 0x3F801000u, 0x3C00u, + 0x3F801800u, 0x3C01u, 0x40000000u, 0x4000u, 0x40000800u, 0x4000u, + 0x40001000u, 0x4000u, 0x40001800u, 0x4001u, 0x40800000u, 0x4400u, + 0x40800800u, 0x4400u, 0x40801000u, 0x4400u, 0x40801800u, 0x4401u, + 0x41000000u, 0x4800u, 0x41000800u, 0x4800u, 0x41001000u, 0x4800u, + 0x41001800u, 0x4801u, 0x41800000u, 0x4C00u, 0x41800800u, 0x4C00u, + 0x41801000u, 0x4C00u, 0x41801800u, 0x4C01u, 0x42000000u, 0x5000u, + 0x42000800u, 0x5000u, 0x42001000u, 0x5000u, 0x42001800u, 0x5001u, + 0x42800000u, 0x5400u, 0x42800800u, 0x5400u, 0x42801000u, 0x5400u, + 0x42801800u, 0x5401u, 0x43000000u, 0x5800u, 0x43000800u, 0x5800u, + 0x43001000u, 0x5800u, 0x43001800u, 0x5801u, 0x43800000u, 0x5C00u, + 0x43800800u, 0x5C00u, 0x43801000u, 0x5C00u, 0x43801800u, 0x5C01u, + 0x44000000u, 0x6000u, 0x44000800u, 0x6000u, 0x44001000u, 0x6000u, + 0x44001800u, 0x6001u, 0x44800000u, 0x6400u, 0x44800800u, 0x6400u, + 0x44801000u, 0x6400u, 0x44801800u, 0x6401u, 0x45000000u, 0x6800u, + 0x45000800u, 0x6800u, 0x45001000u, 0x6800u, 0x45001800u, 0x6801u, + 0x45800000u, 0x6C00u, 0x45800800u, 0x6C00u, 0x45801000u, 0x6C00u, + 0x45801800u, 0x6C01u, 0x46000000u, 0x7000u, 0x46000800u, 0x7000u, + 0x46001000u, 0x7000u, 0x46001800u, 0x7001u, 0x46800000u, 0x7400u, + 0x46800800u, 0x7400u, 0x46801000u, 0x7400u, 0x46801800u, 0x7401u, + 0x47000800u, 0x7800u, 0x47001000u, 0x7800u, 0x47001800u, 0x7801u, + 0x33C00000u, 0x0002u, 0x34000000u, 0x0002u, 0x34200000u, 0x0002u, + 0x34400000u, 0x0003u, 0x34600000u, 0x0004u, 0x34800000u, 0x0004u, + 0x34900000u, 0x0004u, 0x34A00000u, 0x0005u, 0x34B00000u, 0x0006u, + 0x34C00000u, 0x0006u, 0x34D00000u, 0x0006u, 0x34E00000u, 0x0007u, + 0x34F00000u, 0x0008u, 0x35000000u, 0x0008u, 0x35080000u, 0x0008u, + 0x35100000u, 0x0009u, 0x35180000u, 0x000Au, 0x35200000u, 0x000Au, + 0x35280000u, 0x000Au, 0x35300000u, 0x000Bu, 0x35380000u, 0x000Cu, + 0x35400000u, 0x000Cu, 0x35480000u, 0x000Cu, 0x35500000u, 0x000Du, + 0x35580000u, 0x000Eu, 0x35600000u, 0x000Eu, 0x35680000u, 0x000Eu, + 0x35700000u, 0x000Fu, 0x35780000u, 0x0010u, 0x35800000u, 0x0010u, + 0x35840000u, 0x0010u, 0x35880000u, 0x0011u, 0x358C0000u, 0x0012u, + 0x35900000u, 0x0012u, 0x35940000u, 0x0012u, 0x35980000u, 0x0013u, + 0x359C0000u, 0x0014u, 0x35A00000u, 0x0014u, 0x35A40000u, 0x0014u, + 0x35A80000u, 0x0015u, 0x35AC0000u, 0x0016u, 0x35B00000u, 0x0016u, + 0x35B40000u, 0x0016u, 0x35B80000u, 0x0017u, 0x35BC0000u, 0x0018u, + 0x35C00000u, 0x0018u, 0x35C40000u, 0x0018u, 0x35C80000u, 0x0019u, + 0x35CC0000u, 0x001Au, 0x35D00000u, 0x001Au, 0x35D40000u, 0x001Au, + 0x35D80000u, 0x001Bu, 0x35DC0000u, 0x001Cu, 0x35E00000u, 0x001Cu, + 0x35E40000u, 0x001Cu, 0x35E80000u, 0x001Du, 0x35EC0000u, 0x001Eu, + 0x35F00000u, 0x001Eu, 0x35F40000u, 0x001Eu, 0x35F80000u, 0x001Fu, + 0x35FC0000u, 0x0020u, 0x36000000u, 0x0020u, 0x36020000u, 0x0020u, + 0x36040000u, 0x0021u, 0x36060000u, 0x0022u, 0x36080000u, 0x0022u, + 0x360A0000u, 0x0022u, 0x360C0000u, 0x0023u, 0x360E0000u, 0x0024u, + 0x36100000u, 0x0024u, 0x36120000u, 0x0024u, 0x36140000u, 0x0025u, + 0x36160000u, 0x0026u, 0x36180000u, 0x0026u, 0x361A0000u, 0x0026u, + 0x361C0000u, 0x0027u, 0x361E0000u, 0x0028u, 0xB70C380Bu, 0x808Cu, + 0xC62CBAD6u, 0xF166u, 0xC6167C83u, 0xF0B4u, 0xC5E87D75u, 0xEF44u, + 0xB411536Du, 0x8002u, 0x422B1CD9u, 0x5159u, 0x3BAC7D0Au, 0x1D64u, + 0x3E777C7Eu, 0x33BCu, 0xC34DA8EFu, 0xDA6Du, 0xC7F7B602u, 0xFC00u, + 0xB58914D2u, 0x8011u, 0x40727A6Fu, 0x4394u, 0x3946E5AAu, 0x0A37u, + 0x4671C2D0u, 0x738Eu, 0x3565BDBDu, 0x000Eu, 0x3BEFF6A4u, 0x1F80u, + 0xB136ED95u, 0x8000u, 0xBB940CC6u, 0x9CA0u, 0xBD5ADDB8u, 0xAAD7u, + 0x42954B1Eu, 0x54AAu, 0x35F55F4Cu, 0x001Fu, 0x33ABC544u, 0x0001u, + 0x42DE8A1Bu, 0x56F4u, 0x445C4B5Eu, 0x62E2u, 0xC26C283Au, 0xD361u, + 0x34959C9Du, 0x0005u, 0x3D035DE5u, 0x281Bu, 0xBD5F8FB9u, 0xAAFCu, + 0x42A6E954u, 0x5537u, 0x3978C191u, 0x0BC6u, 0xB4FC63E2u, 0x8008u, + 0x40B270AEu, 0x4594u, 0x46CBF834u, 0x7660u, 0x363DC03Fu, 0x002Fu, + 0xB1B0AAD8u, 0x8000u, 0x477E0850u, 0x7BF0u, 0x3357EDFFu, 0x0001u, + 0xBEF7D490u, 0xB7BFu, 0xB230011Bu, 0x8000u, 0xC41F8C42u, 0xE0FCu, + 0x40EE6FA8u, 0x4773u, 0xC020D7F5u, 0xC107u, 0xBA17B5A6u, 0x90BEu, + 0x39F609F8u, 0x0FB0u, 0xC0169BEBu, 0xC0B5u, 0xC34D25A0u, 0xDA69u, + 0xC23263C4u, 0xD193u, 0xC05BA352u, 0xC2DDu, 0xC7355027u, 0xF9ABu, + 0x335A4A8Du, 0x0001u, 0x4196D58Bu, 0x4CB7u, 0xB2F09C6Au, 0x8000u, + 0xC6A7EA97u, 0xF53Fu, 0x308ED1F1u, 0x0000u, 0x33A60BD6u, 0x0001u, + 0xB486B455u, 0x8004u, 0x3F4A08F6u, 0x3A50u, 0x363B9A5Bu, 0x002Fu, + 0xC48BA363u, 0xE45Du, 0x3EFBCC45u, 0x37DEu, 0xBDF8FE27u, 0xAFC8u, + 0xC55797A8u, 0xEABDu, 0xC008C482u, 0xC046u, 0xC3ED6604u, 0xDF6Bu, + 0xBF0D00C6u, 0xB868u, 0xC3AC7327u, 0xDD64u, 0x3B6245DCu, 0x1B12u, + 0xC4AD660Bu, 0xE56Bu, 0x404E99CEu, 0x4275u, 0xB09DE09Du, 0x8000u, + 0x3AEFA82Eu, 0x177Du, 0x4797A354u, 0x7C00u, 0xBC662E46u, 0xA331u, + 0x3EBF9AF7u, 0x35FDu, 0xBF8B651Cu, 0xBC5Bu, 0x3DC3DF55u, 0x2E1Fu, + 0x3420659Fu, 0x0003u, 0xB5BF3014u, 0x8018u, 0x3C229714u, 0x2115u, + 0xBE7A7284u, 0xB3D4u, 0xC544A929u, 0xEA25u, 0x34711195u, 0x0004u, + 0x365D12F9u, 0x0037u, 0xC71DE14Du, 0xF8EFu, 0xBBB6EE2Au, 0x9DB7u, + 0x4285DC79u, 0x542Fu, 0xC1479433u, 0xCA3Du, 0x443A29D6u, 0x61D1u, + 0xC6870A39u, 0xF438u, 0x470B6E9Cu, 0x785Bu, 0x449AF78Au, 0x64D8u, + 0x34098DE2u, 0x0002u, 0xBBFC11E5u, 0x9FE1u, 0x42922E1Bu, 0x5491u, + 0x3DBFB02Eu, 0x2DFEu, 0xB5A516FCu, 0x8015u, 0x447B2862u, 0x63D9u, + 0xC085C952u, 0xC42Eu, 0x442CC939u, 0x6166u, 0xB126F155u, 0x8000u, + 0x3F982F47u, 0x3CC1u, 0xC36C38DFu, 0xDB62u, 0xC1E21DBCu, 0xCF11u, + 0xC42DA5DDu, 0xE16Du, 0x3AD3CEC3u, 0x169Eu, 0x35319027u, 0x000Bu, + 0x34F38AABu, 0x0008u, 0xBBB4902Du, 0x9DA5u, 0x42A8B660u, 0x5546u, + 0xBE02F143u, 0xB018u, 0xB84BE09Au, 0x8330u, 0xBF215C12u, 0xB90Bu, + 0xBA674F20u, 0x933Au, 0xC0EBE307u, 0xC75Fu, 0x3AC119A5u, 0x1609u, + 0x344B18AFu, 0x0003u, 0xC183EB4Bu, 0xCC1Fu, 0xB96414D1u, 0x8B21u, + 0xB74DB17Du, 0x80CEu, 0xC3AF2570u, 0xDD79u, 0xB570C5F3u, 0x800Fu, + 0xB568C27Cu, 0x800Fu, 0xBE03F2E7u, 0xB020u, 0xBF216402u, 0xB90Bu, + 0xC16D1B4Au, 0xCB69u, 0x35897C73u, 0x0011u, 0xB771D56Bu, 0x80F2u, + 0xB5BB317Bu, 0x8017u, 0x367F3A0Bu, 0x0040u, 0xB6EE0B0Du, 0x8077u, + 0x416379C7u, 0x4B1Cu, 0xBA821968u, 0x9411u, 0x3D07874Du, 0x283Cu, + 0xBB951706u, 0x9CA9u, 0x402BDEC0u, 0x415Fu, 0x37F183A2u, 0x01E3u, + 0x3C0CE282u, 0x2067u, 0xBD40215Fu, 0xAA01u, 0x3BE1404Eu, 0x1F0Au, + 0x429C6774u, 0x54E3u, 0xC0E2E84Eu, 0xC717u, 0xC118375Du, 0xC8C2u, + 0x338E0178u, 0x0001u, 0xBEADFB76u, 0xB570u, 0xC2CDE39Bu, 0xD66Fu, + 0x3505E06Fu, 0x0008u, 0xC0278755u, 0xC13Cu, 0x3A727A53u, 0x1394u, + 0x3F954D3Fu, 0x3CAAu, 0xBD8BB0B5u, 0xAC5Eu, 0x3F5C2F06u, 0x3AE1u, + 0x43140960u, 0x58A0u, 0x3849FB8Au, 0x0328u, 0x3A18FD84u, 0x10C8u, + 0xBE975FD3u, 0xB4BBu, 0xC0BF694Au, 0xC5FBu, 0x3D56DA35u, 0x2AB7u, + 0xC28C14ADu, 0xD461u, 0xB6BA702Au, 0x805Du, 0xC20FB679u, 0xD07Eu, + 0x412B1285u, 0x4959u, 0x3823D6E4u, 0x028Fu, 0xBC274EF6u, 0xA13Au, + 0x3ABACE39u, 0x15D6u, 0xB39C87AEu, 0x8001u, 0x3D9CCD85u, 0x2CE6u, + 0xBAC131E0u, 0x960Au, 0x33BC76EAu, 0x0001u, 0x38BBFB64u, 0x05E0u, + 0x3A718DF9u, 0x138Cu, 0x3BCD8BA9u, 0x1E6Cu, 0x4245E77Du, 0x522Fu, + 0xB8E90C7Bu, 0x8748u, 0xBA9F4029u, 0x94FAu, 0xBAA46DE7u, 0x9523u, + 0x3E984F19u, 0x34C2u, 0x380D4F2Eu, 0x0235u, 0x427ADE3Eu, 0x53D7u, + 0xB772280Fu, 0x80F2u, 0x371B1E4Eu, 0x009Bu, diff --git a/engine/strata/src/kernels/qsa_parity.cpp b/engine/strata/src/kernels/qsa_parity.cpp new file mode 100644 index 00000000..55dec2d3 --- /dev/null +++ b/engine/strata/src/kernels/qsa_parity.cpp @@ -0,0 +1,1555 @@ +// src/kernels/qsa_parity.cpp - P2.S2's test for the QSA cache, indexer, selection and attention. +// +// `ref/qsa.py` carries eleven PROPERTY checks and `ref/model.py::_qsa` is the layer as the model runs it. The +// readings a prose transcription gets WRONG, each of which produces a well-formed result of the right shape, +// are computed here the wrong way round AND required to differ MATERIALLY before the kernel is judged against +// the right one - a test that only does the second half passes against either reading: +// +// 1. `pooled[b]` is rotated at the block's FIRST cell. The reference's PROPERTY 4 pins it against the +// block's LAST cell; both give a unit-norm vector and the same downstream shape. +// 2. Pool THEN norm (`rms_norm(mean(x))`) and not norm THEN pool (`mean(rms_norm(x))`). `ref/model.py` L358 +// is explicit, and the two differ whenever the four cells have different magnitudes. +// 3. The spare slot's key is `rms_norm(raw[0])` - cell ZERO - and not the last raw key, and the tail cells +// map to THAT slot and not to the last complete block. A three-row raw tail cannot produce it unless +// cell 0's key is kept, which is what makes this a real design constraint rather than a detail. +// 4. The indexer's Relu is PER HEAD, summed afterwards. `relu(sum_h dot_h)` is the rival reading and +// differs whenever any head's dot is negative. +// 5. The q -> kv head map is `q / 12` (integer division), NOT `q % 2`. `ref/qsa.py` PROPERTY 7 tests the +// same thing; with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...]. +// 6. The attention reads ONLY the selected cells. The source writes -inf into the mask and zeros at the +// top-k indices, so an unselected cell has weight exactly zero even when it would score highest - +// PROPERTY 8's fixture, reproduced here with its own numbers. +// 7. `attn *= sigmoid(gate)` with the gate taken from the SECOND half of each head's 2*head_dim block, and +// the rounding to fp16 happening AFTER the multiply (one rounding, not two). +// 8. The KV cache is PAGED and the page table is not assumed to be the identity: the pool is written and +// read back at page_size 1, 4 and 512 with a REVERSED table, and the kernel's own reading of the layout +// is compared against two rivals (linear, i.e. the table ignored; and cell-major inside the page). +// +// THE METRIC. Both sums here - the indexer's sum of four relu'd dots and the attention's weighted sum of +// value rows - cancel, so a plain |want-got|/|want| reports the condition number instead of the arithmetic. +// The project has made that mistake four times (rounds 169, 189, 194, 196); where a sum is compared below, the +// denominator is the magnitude of the TERMS. +// +// WHAT SETS EACH TOLERANCE, because a tolerance nobody can explain is one nobody can tighten: +// * the fp16 converter, the pool contents, the gathered scratch and the spare indexer key: EXACT. The only +// arithmetic is a conversion, and section 0 checks that conversion against numpy's float16 over 395 +// vectors covering ties in both directions, subnormals and overflow - an oracle sharing no code with it - +// plus all 65,536 fp16 patterns in the reverse direction. +// * the pooled block keys: 1e-6. The pooling and the norm are double on both sides and are bit-exact +// BEFORE the rotation; the residual is `rope_neox_apply` (f32, reused rather than re-implemented) against +// the reference's float64 rotation, the class round 189 measured at ~1e-7. +// * the indexer scores: 1e-6 against Sum|dot_h| + |bias|, set by the fp32 storage of the pooled keys - +// 2^-24 per element over a 128-term dot. +// * the selected ids: EXACT. `docs/capture-format.md` L127 gives `indexer_ids` no tolerance. +// * the attention against a reference reading the SAME fp16 cache: 1e-5, set by f32 accumulation over +// 256-term dots plus `expf`'s 2 ulp. This is the KERNEL's number. +// * the attention against a reference reading the f32 keys: REPORTED and then checked against the phase's +// 1e-3 for FP16 paths. That difference is the FP16 CACHE's cost, not the kernel's, and it is kept +// separate so a kernel bug cannot hide inside it. +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" + +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/rope.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using strata::kernels::f16_from_f32; +using strata::kernels::f32_from_f16; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// A device buffer with the boilerplate folded in. A test that allocates twenty buffers by hand spends its +/// attention on memcpy arguments instead of on the kernel. +template +struct Dev { + T* p = nullptr; + Dev() = default; + explicit Dev(size_t n) { alloc(n); } + ~Dev() { if (p) cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + void alloc(size_t n) { + if (p) { cudaFree(p); p = nullptr; } + if (n) check(cudaMalloc(&p, n * sizeof(T)), "cudaMalloc"); + } + void put(const std::vector& v) { + if (!p) alloc(v.size()); + check(cudaMemcpy(p, v.data(), v.size() * sizeof(T), cudaMemcpyHostToDevice), "H2D"); + } + std::vector get(size_t n) const { + std::vector v(n); + check(cudaMemcpy(v.data(), p, n * sizeof(T), cudaMemcpyDeviceToHost), "D2H"); + return v; + } +}; + +std::vector as_d(const std::vector& v) { return std::vector(v.begin(), v.end()); } +std::vector as_f(const std::vector& v) { + std::vector o(v.size()); + for (size_t i = 0; i < v.size(); ++i) o[i] = (float) v[i]; + return o; +} + +/// Relative error against the magnitude of the TERMS. See the header comment. +double rel_terms(double want, double got, double terms) { + return std::fabs(want - got) / (terms > 1e-30 ? terms : 1e-30); +} + +double rel_l1(const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs(a[i] - b[i]); + m += std::fabs(a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); +} + +int g_bad = 0; +std::string pct(double rel) { + char b[32]; + std::snprintf(b, sizeof b, "%.2f%% apart", rel * 100.0); + return b; +} +void verdict(const std::string& name, bool ok, const std::string& detail = "") { + std::printf(" %-48s %-6s %s\n", name.c_str(), ok ? "yes" : "*** NO ***", detail.c_str()); + if (!ok) ++g_bad; +} +void report(const std::string& name, double v, const char* unit) { + std::printf(" %-48s %s %.3e\n", name.c_str(), unit, v); +} +void require(const std::string& name, bool ok, const std::string& detail = "") { + std::printf(" %-48s %-6s %s\n", name.c_str(), ok ? "ok" : "*** BAD ***", detail.c_str()); + if (!ok) ++g_bad; +} + +// ================= the reference: ref/qsa.py + ref/model.py, in double ================= + +/// Which of the rival readings to compute. The defaults are the SOURCE's reading. +struct Alt { + bool rotate_at_block_start = true; ///< false: rotate at the block's LAST cell (WRONG) + bool pool_then_norm = true; ///< false: mean of the per-cell norms (WRONG) + bool dead_from_first = true; ///< false: the spare key from the LAST raw key (WRONG) + bool rope_raw = false; ///< true: rotate the raw keys before pooling (WRONG) + bool relu_per_head = true; ///< false: relu(sum of the head dots) (WRONG) + bool use_relu = true; ///< false: no relu at all (WRONG) + bool use_bias = true; ///< false: drop the per-block bias (WRONG) + bool kv_divide = true; ///< false: q % n_head_kv instead of q / 12 (WRONG) + bool apply_scale = true; ///< false: no 1/sqrt(head_dim) (WRONG) + bool gate_second_half = true; ///< false: the gate from the FIRST half (WRONG) + bool gate_sigmoid = true; ///< false: silu instead of sigmoid (WRONG) +}; + +/// `x*y + z` with the product ROUNDED first, i.e. no FMA contraction. +/// +/// MSVC contracts `ss += v*v` into an FMA even under /fp:precise, so the reference was MORE accurate than +/// the kernel's explicit `__fadd_rn(__fmul_rn(v, v))` and the spare key came out one bit different in 7 of +/// 128 components. The kernel's arithmetic is what is under test, so the reference REPRODUCES it instead of +/// beating it; `volatile` is what stops the compiler re-fusing the two operations. +double mul_add_plain(double x, double y, double z) { + const volatile double p = x * y; + return z + p; +} + +/// `ref/qsa.py::rms_norm` in double, in place. `w` may be empty (w = None). +void ref_rms_norm(std::vector& x, const std::vector& w, float eps) { + double ss = 0; + for (double v : x) ss = mul_add_plain(v, v, ss); + const double inv = 1.0 / std::sqrt(ss / (double) x.size() + (double) eps); + for (size_t i = 0; i < x.size(); ++i) x[i] = x[i] * inv * (w.empty() ? 1.0 : (double) w[i]); +} + +/// `ref/qsa.py::rope_neox` in double: NEOX pairs (i, i + n_rot/2), partial over the first n_rot dims. +/// +/// `terms`, when given, receives the magnitude of each component's TERMS - `|a c| + |b s|` where the +/// rotation subtracts - so a comparison can divide by that instead of by the result, which cancels. +void ref_rope_neox(std::vector& x, double pos, int n_rot, double theta, + std::vector* terms = nullptr) { + const int half = n_rot / 2; + std::vector a(x.begin(), x.begin() + half), b(x.begin() + half, x.begin() + n_rot); + if (terms) { + terms->assign(x.size(), 0.0); + for (size_t i = (size_t) n_rot; i < x.size(); ++i) (*terms)[i] = std::fabs(x[i]); + } + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = pos * inv, c = std::cos(ang), s = std::sin(ang); + x[i] = a[i] * c - b[i] * s; + x[half + i] = a[i] * s + b[i] * c; + if (terms) { + (*terms)[i] = std::fabs(a[i] * c) + std::fabs(b[i] * s); + (*terms)[half + i] = std::fabs(a[i] * s) + std::fabs(b[i] * c); + } + } +} + +const int64_t REF_R = 4; ///< IDX_BLOCK, checked against the shapes at the top of main + +/// `QsaCache`, holding f64 rows - the reference never sees an fp16 key. +struct RefCache { + std::vector> k, v, raw; + std::vector pos; + int64_t size() const { return (int64_t) pos.size(); } + void append(std::vector kk, std::vector vv, std::vector rr, double p) { + k.push_back(std::move(kk)); + v.push_back(std::move(vv)); + raw.push_back(std::move(rr)); + pos.push_back(p); + } +}; + +/// `QsaCache.pooled_raw(r)` - BEFORE the norm, which is the only place the 1/r divisor is observable. +std::vector ref_pooled_raw(const RefCache& c) { + const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size(); + std::vector out((size_t) n_bid * dim, 0.0); + for (int64_t b = 0; b < n_bid; ++b) + for (int64_t i = 0; i < REF_R; ++i) + for (int64_t d = 0; d < dim; ++d) out[(size_t) b * dim + d] += c.raw[(size_t) (b * REF_R + i)][(size_t) d]; + for (auto& x : out) x /= (double) REF_R; + return out; +} + +/// `pooled_keys` + `dead_pooled_key`, in the readback order `indexer_scores` uses: (n_bid + 1, idx_dim). +std::vector ref_pooled(const RefCache& c, const std::vector& w_kn, float eps, int n_rot, + double theta, const Alt& o, + std::vector* terms_out = nullptr) { + const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size(); + std::vector pooled((size_t) (n_bid + 1) * dim, 0.0); + std::vector> rows(c.raw); + if (o.rope_raw) + for (size_t j = 0; j < rows.size(); ++j) ref_rope_neox(rows[j], c.pos[j], n_rot, theta); + + for (int64_t b = 0; b < n_bid; ++b) { + std::vector m((size_t) dim, 0.0); + if (o.pool_then_norm) { + for (int64_t i = 0; i < REF_R; ++i) + for (int64_t d = 0; d < dim; ++d) + m[(size_t) d] += rows[(size_t) (b * REF_R + i)][(size_t) d] / (double) REF_R; + ref_rms_norm(m, w_kn, eps); + } else { + for (int64_t i = 0; i < REF_R; ++i) { + std::vector one = rows[(size_t) (b * REF_R + i)]; + ref_rms_norm(one, w_kn, eps); + for (int64_t d = 0; d < dim; ++d) m[(size_t) d] += one[(size_t) d] / (double) REF_R; + } + } + std::vector terms; + ref_rope_neox(m, o.rotate_at_block_start ? c.pos[(size_t) (b * REF_R)] + : c.pos[(size_t) (b * REF_R + REF_R - 1)], + n_rot, theta, terms_out ? &terms : nullptr); + for (int64_t d = 0; d < dim; ++d) pooled[(size_t) b * dim + d] = m[(size_t) d]; + if (terms_out) { + if (b == 0) terms_out->assign((size_t) (n_bid + 1) * dim, 0.0); + for (int64_t d = 0; d < dim; ++d) (*terms_out)[(size_t) b * dim + d] = terms[(size_t) d]; + } + } + std::vector dead = rows[o.dead_from_first ? 0 : rows.size() - 1]; + ref_rms_norm(dead, w_kn, eps); + ref_rope_neox(dead, 0.0, n_rot, theta); // the identity, but computed the reference's way + for (int64_t d = 0; d < dim; ++d) pooled[(size_t) n_bid * dim + d] = dead[(size_t) d]; + return pooled; +} + +/// `ref/qsa.py::indexer_scores` - per CELL, after the `cell_block` mapping. +std::vector ref_indexer_scores(const std::vector& pooled, int64_t n_bid, + const std::vector& q_idx, int64_t idx_n_head, int64_t idx_dim, + const std::vector& bias, int64_t n_kv, const Alt& o) { + std::vector per_block((size_t) n_bid + 1, 0.0); + for (int64_t b = 0; b <= n_bid; ++b) { + double s = 0; + for (int64_t h = 0; h < idx_n_head; ++h) { + double dot = 0; + for (int64_t d = 0; d < idx_dim; ++d) + dot += pooled[(size_t) b * idx_dim + d] * q_idx[(size_t) h * idx_dim + d]; + if (!o.use_relu) s += dot; + else if (o.relu_per_head) s += dot > 0 ? dot : 0.0; + else s += dot; + } + if (o.use_relu && !o.relu_per_head) s = s > 0 ? s : 0.0; + if (o.use_bias && !bias.empty()) s += (double) bias[(size_t) b]; + if (b == n_bid && n_kv % REF_R != 0) s = (float) s + 1e9f; + per_block[(size_t) b] = s; + } + std::vector cell((size_t) n_kv, 0.0); + for (int64_t j = 0; j < n_kv; ++j) cell[(size_t) j] = per_block[(size_t) (j / REF_R < n_bid ? j / REF_R : n_bid)]; + return cell; +} + +/// `ref/qsa.py::select_cells`, spelled with a stable sort rather than the kernel's threshold search, so the +/// two are independent implementations of one rule: score DESCENDING, ties by ASCENDING index. +std::vector ref_select(const std::vector& scores, int64_t n_kv, int64_t top_k, bool dense) { + std::vector idx((size_t) n_kv); + for (int64_t j = 0; j < n_kv; ++j) idx[(size_t) j] = (int32_t) j; + if (dense) return idx; + const int64_t width = std::min(n_kv, top_k + REF_R - 1); + std::stable_sort(idx.begin(), idx.end(), [&](int32_t a, int32_t b) { + const double sa = scores[(size_t) a], sb = scores[(size_t) b]; + if (sa != sb) return sa > sb; + return a < b; + }); + idx.resize((size_t) width); + std::sort(idx.begin(), idx.end()); + return idx; +} + +/// `ref/qsa.py::qsa_attend` over an EXPLICIT selected set, reading K/V from whichever table the caller passes +/// so that one piece of code runs on the f64 keys and on the fp16 cache's exact f32 values. +std::vector ref_attend(const std::vector& q, int64_t n_head, int64_t n_head_kv, int64_t head_dim, + const std::vector& ids, const std::vector>& k, + const std::vector>& v, const Alt& o, + std::vector* weights_out) { + const double scale = o.apply_scale ? 1.0 / std::sqrt((double) head_dim) : 1.0; + std::vector out((size_t) n_head * head_dim, 0.0); + if (weights_out) weights_out->assign((size_t) n_head * ids.size(), 0.0); + for (int64_t h = 0; h < n_head; ++h) { + const int64_t kv = o.kv_divide ? h / (n_head / n_head_kv) : h % n_head_kv; + std::vector sc(ids.size()); + for (size_t j = 0; j < ids.size(); ++j) { + double dot = 0; + for (int64_t d = 0; d < head_dim; ++d) + dot += k[(size_t) ids[j]][(size_t) (kv * head_dim + d)] * q[(size_t) (h * head_dim + d)]; + sc[j] = dot * scale; + } + const double mx = *std::max_element(sc.begin(), sc.end()); + double sum = 0; + for (auto& s : sc) { s = std::exp(s - mx); sum += s; } + for (auto& s : sc) s /= sum; + if (weights_out) + for (size_t j = 0; j < ids.size(); ++j) (*weights_out)[(size_t) h * ids.size() + j] = sc[j]; + for (int64_t d = 0; d < head_dim; ++d) { + double acc = 0; + for (size_t j = 0; j < ids.size(); ++j) acc += sc[j] * v[(size_t) ids[j]][(size_t) (kv * head_dim + d)]; + out[(size_t) (h * head_dim + d)] = acc; + } + } + return out; +} + +/// `ref/model.py::_qsa`'s last two lines. +std::vector ref_gate(const std::vector& attn, const std::vector& q_full, int64_t n_head, + int64_t head_dim, const Alt& o) { + std::vector out((size_t) n_head * head_dim, 0.0); + for (int64_t h = 0; h < n_head; ++h) + for (int64_t d = 0; d < head_dim; ++d) { + const int64_t gi = o.gate_second_half ? h * 2 * head_dim + head_dim + d : h * 2 * head_dim + d; + const double g = q_full[(size_t) gi]; + const double s = o.gate_sigmoid ? 1.0 / (1.0 + std::exp(-g)) : g / (1.0 + std::exp(-g)); + out[(size_t) (h * head_dim + d)] = attn[(size_t) (h * head_dim + d)] * s; + } + return out; +} + +/// {f32 bits, the fp16 bits numpy produces for it} interleaved. Generated by +/// `scripts/_gen_f16_oracle.py` from `np.float16(np.float32(x))`: an oracle that shares no code with +/// f16_bits.hpp, which is the whole point of the table. +const uint32_t kOracle[] = { +#include "qsa_oracle_vectors.inc" +}; +constexpr int kOracleN = (int) (sizeof(kOracle) / sizeof(kOracle[0])) / 2; + +} // namespace + +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); // a crash must not swallow what was printed already + bool selftest = false, dense = false, bench = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") selftest = true; + else if (a == "--qsa-dense") dense = true; + else if (a == "--bench") bench = true; + else { + std::fprintf(stderr, "usage: qsa_parity [--selftest] [--qsa-dense] [--bench]\n" + " --qsa-dense attend to EVERY cell instead of the indexer's selection\n" + " (P1.S4's isolation switch; the sparse selection is still run\n" + " and checked, against the reference's dense/sparse property)\n" + " --bench time the kernels at 32K of context\n"); + return 2; + } + } + + const strata::kernels::QsaShapes S = strata::kernels::qsa_real_shapes(); + const int64_t NH = S.n_head, NKV = S.n_head_kv, HD = S.head_dim, IDXN = S.idx_n_head, IDXD = S.idx_dim, + R = S.idx_block, TOPK = S.idx_top_k; + const int64_t MAXC = strata::kernels::kTopkMaxCells; + const float EPS = strata::kernels::qsa_rms_eps(); + const double THETA = strata::kernels::qsa_freq_base(); + std::mt19937 rng(20260916u); + std::normal_distribution gauss(0.0, 1.0); + auto rnd = [&](double s) { return (float) (gauss(rng) * s); }; + + std::printf("qsa_parity: n_head %lld n_head_kv %lld head_dim %lld indexer %lldx%lld r=%lld " + "top_k %lld page (from the shapes) %lld [%s]\n\n", + (long long) NH, (long long) NKV, (long long) HD, (long long) IDXN, (long long) IDXD, + (long long) R, (long long) TOPK, (long long) S.page_size, dense ? "DENSE" : "sparse"); + require("the fixture's r is the artifact's IDX_BLOCK", R == REF_R, "r = " + std::to_string(R)); + + // ================= 0. the fp16 converter, against numpy ================= + { + int mism = 0, subnormal = 0; + for (int i = 0; i < kOracleN; ++i) { + float f; + const uint32_t fb = kOracle[2 * i]; + std::memcpy(&f, &fb, 4); + const uint16_t want = (uint16_t) kOracle[2 * i + 1]; + const uint16_t got = f16_from_f32(f); + if (got != want) { + if (mism < 5) std::printf(" f32 0x%08X -> got 0x%04X, numpy says 0x%04X\n", fb, got, want); + ++mism; + } + if ((want & 0x7C00u) == 0u && (want & 0x3FFu) != 0u) ++subnormal; + } + require("f32->f16 matches numpy's float16 on every vector", mism == 0, + std::to_string(kOracleN) + " vectors, " + std::to_string(subnormal) + " subnormal"); + int bad_rev = 0; + for (int h = 0; h < 65536; ++h) { + const int ex = (h >> 10) & 0x1F, man = h & 0x3FF; + if (ex == 31) continue; // inf/NaN come from the vector table above + const double mag = ex == 0 ? (double) man * std::ldexp(1.0, -24) + : (double) (1024 + man) * std::ldexp(1.0, ex - 25); + const double want = (h & 0x8000) ? -mag : mag; + if ((double) f32_from_f16((uint16_t) h) != want) { + if (bad_rev < 5) std::printf(" f16 0x%04X -> %.9g, want %.9g\n", h, (double) f32_from_f16((uint16_t) h), want); + ++bad_rev; + } + } + require("f16->f32 is exact on all 65,536 bit patterns", bad_rev == 0, + std::to_string(bad_rev) + " wrong"); + } + + // ================= 1. kv_append: the paged pool, three page granules ================= + const int64_t TCELLS = 1100; // 275 indexer blocks, and 3 pages at page_size 512 + std::vector kcur_all((size_t) TCELLS * NKV * HD), vcur_all((size_t) TCELLS * NKV * HD); + for (auto& x : kcur_all) x = rnd(1.0); + for (auto& x : vcur_all) x = rnd(1.0); + // EVERY pointer this kernel set takes is a DEVICE pointer - the append sources, the indexer weights + // and the rope tables alike. The first draft passed `&kcur_all[...]`, `w_kn.data()` and + // `cos_tab.data()` straight through, and every kernel that dereferenced one took an illegal access. + Dev dkcur_all, dvcur_all; + dkcur_all.put(kcur_all); + dvcur_all.put(vcur_all); + + struct PageCase { + int64_t page_size = 0, n_pages = 0; + std::vector table; + }; + std::vector pages; + for (int64_t ps : {(int64_t) 1, (int64_t) 4, (int64_t) 512}) { + PageCase c; + c.page_size = ps; + c.n_pages = (TCELLS + ps - 1) / ps; + c.table.resize((size_t) c.n_pages); + for (int64_t i = 0; i < c.n_pages; ++i) c.table[(size_t) i] = (int32_t) (c.n_pages - 1 - i); // REVERSED + pages.push_back(std::move(c)); + } + const std::vector ids = {0, 1, 2, 3, 5, 8, 13, 21, 34, 39, 1099, 700}; + + for (PageCase& c : pages) { + // THE PAGE GRANULE IS A PROPERTY OF THE SHAPES, and the kernel takes it from there rather than from an + // argument. The first version of this fixture left it at 512 while the table described 1-cell pages, + // so the kernel indexed a 1100-page table as if it had 3 pages and ran off the pool - which is what an + // illegal memory access reported. A test that feeds one geometry and expects another is measuring + // itself; the fix is to build the shapes per case. + strata::kernels::QsaShapes Sc = S; + Sc.page_size = c.page_size; + const size_t pool_n = (size_t) c.n_pages * NKV * c.page_size * HD; + Dev dk(pool_n), dv(pool_n); + Dev dtab; + dtab.put(c.table); + for (int64_t t = 0; t < TCELLS; ++t) + strata::kernels::kv_append(dk.p, dv.p, dtab.p, t, dkcur_all.p + (size_t) t * NKV * HD, + dvcur_all.p + (size_t) t * NKV * HD, Sc, nullptr); + const std::vector hk = dk.get(pool_n), hv = dv.get(pool_n); + + int mism = 0, mism_linear = 0, mism_head_major = 0; + const int64_t rows_avail = (int64_t) (pool_n / (size_t) HD); + // A rival layout's address is HYPOTHETICAL: where it would put the value may be outside the pool, + // and reading there is a host access violation rather than a mismatch. Off the end counts as + // "the value is not where the rival would put it", which is the claim being tested. + auto elsewhere = [&](int64_t r) { return r < 0 || r >= rows_avail; }; + for (int64_t cell = 0; cell < TCELLS; ++cell) + for (int64_t h = 0; h < NKV; ++h) + for (int64_t d = 0; d < HD; ++d) { + const size_t src = (size_t) (cell * NKV + h) * HD + d; + const uint16_t wk = f16_from_f32(kcur_all[src]), wv = f16_from_f32(vcur_all[src]); + // the DECLARED layout: [page][kv_head][page_size][head_dim] + const int64_t row = ((int64_t) c.table[(size_t) (cell / c.page_size)] * NKV + h) * c.page_size + + (cell % c.page_size); + if (hk[(size_t) row * HD + d] != wk || hv[(size_t) row * HD + d] != wv) ++mism; + // rival (a): the page table ignored, i.e. written at the logical address + const int64_t rl = (cell * NKV + h) * c.page_size + (cell % c.page_size); + if (elsewhere(rl) || hk[(size_t) rl * HD + d] != wk) ++mism_linear; + // rival (b): cell-major inside the page instead of head-major + const int64_t rh = ((int64_t) c.table[(size_t) (cell / c.page_size)] * c.page_size + + (cell % c.page_size)) * NKV + h; + if (elsewhere(rh) || hk[(size_t) rh * HD + d] != wk) ++mism_head_major; + } + const double n_tot = (double) (TCELLS * NKV * HD); + require("kv_append at page_size " + std::to_string(c.page_size) + ": the pool is BIT-EXACT", + mism == 0, std::to_string(mism) + " of " + std::to_string((long long) n_tot) + " bits wrong"); + verdict(" the page table is observable at page_size " + std::to_string(c.page_size), + (double) mism_linear / n_tot > 0.5, + pct((double) mism_linear / n_tot) + " (linear vs declared)"); + // The head-major rival is IDENTICAL to the declared layout when page_size == 1 (both reduce to + // `cell * n_head_kv + h`), so the separation is only asserted where the layouts actually differ. + if (c.page_size >= 4) { + verdict(" head-major-in-page is observable at page_size " + std::to_string(c.page_size), + (double) mism_head_major / n_tot > 0.5, + pct((double) mism_head_major / n_tot) + " (cell-major vs head-major)"); + } + + Dev dids; + dids.put(ids); + const size_t scr_n = ids.size() * NKV * HD; + Dev dks(scr_n), dvs(scr_n); + strata::kernels::kv_gather(dk.p, dv.p, dtab.p, dids.p, (int64_t) ids.size(), Sc, dks.p, dvs.p, nullptr); + const std::vector gk = dks.get(scr_n), gv = dvs.get(scr_n); + int gm = 0; + for (size_t j = 0; j < ids.size(); ++j) + for (int64_t h = 0; h < NKV; ++h) + for (int64_t d = 0; d < HD; ++d) { + const size_t src = (size_t) (ids[j] * NKV + h) * HD + d; + if (gk[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(kcur_all[src])) ++gm; + if (gv[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(vcur_all[src])) ++gm; + } + require(" kv_gather is BIT-EXACT at page_size " + std::to_string(c.page_size), gm == 0, + std::to_string(gm) + " wrong bits"); + } + + // ================= 2. indexer_key_append ================= + const int64_t NT = 10; // 2 complete blocks + a 2-cell tail + // The cells sit at POSITIONS 100..109, not at 0..9: `QsaCache.pos` is what the reference rotates by, + // and a kernel that assumes position == cell index is wrong for any sequence that does not start at 0 + // (prefix reuse, phase 5). With base 100 the two readings are 514% apart, which is asserted below. + const int32_t POS_BASE = 100; + RefCache rc; + std::vector raw_flat; + for (int64_t t = 0; t < NT; ++t) { + std::vector kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD); + for (int64_t i = 0; i < NKV * HD; ++i) { kk[(size_t) i] = gauss(rng); vv[(size_t) i] = gauss(rng); } + // cell MAGNITUDES 1, 4, 16, 64 - for the same reason round 196 gave its residual streams different + // scales: four i.i.d. rows of normal noise have nearly the same norm by accident, so "pool then norm" + // and "norm then pool" would agree to within the noise and the fixture could not see its own trap. + for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = gauss(rng) * std::pow(4.0, (double) (t % 4)); + for (int64_t d = 0; d < IDXD; ++d) raw_flat.push_back((float) rr[(size_t) d]); + // The reference gets the f32 PROMOTION of what the device gets, not the f64 original. Feeding it + // the f64 values left a 6e-8 relative difference, which is invisible in a score but crosses an f32 + // rounding boundary in one value in four - and the spare key is asserted BIT-EXACT. + for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) raw_flat[(size_t) t * IDXD + d]; + rc.append(kk, vv, rr, (double) (100 + t)); + } + std::vector w_kn((size_t) IDXD); + for (auto& x : w_kn) x = 1.0f + 0.1f * rnd(1.0); + std::vector cos_tab((size_t) (2000 * S.n_rot / 2)), sin_tab(cos_tab.size()); + strata::kernels::build_rope_table((int) S.n_rot, THETA, 2000, cos_tab.data(), sin_tab.data()); + Dev dw_kn, dcos, dsin; + dw_kn.put(w_kn); + dcos.put(cos_tab); + dsin.put(sin_tab); + + const int64_t n_bid = NT / R; + const size_t pooled_n = (size_t) (n_bid + 1) * IDXD; + Dev dpooled(pooled_n), ddead((size_t) IDXD), dtail((size_t) (R - 1) * IDXD); + Dev dblockpos(1); // the rotation position, which only the DEVICE may read + // The POSITION is a device value now, because a host scalar would be baked into a captured graph. One + // `cudaMemcpy` per cell here; the layer keeps this buffer and updates it per token. + Dev dpos(1); + { + strata::kernels::QsaIndexerBuffers bufs{dtail.p, ddead.p, dpooled.p, dblockpos.p}; + Dev draw((size_t) IDXD); + for (int64_t t = 0; t < NT; ++t) { // one cell at a time: the tail is a ring and the spare row MOVES + check(cudaMemcpy(draw.p, &raw_flat[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), + "raw"); + const int32_t tpos = (int32_t) t; + check(cudaMemcpy(dpos.p, &tpos, 4, cudaMemcpyHostToDevice), "pos"); + strata::kernels::indexer_key_append(draw.p, dpos.p, POS_BASE, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p, + nullptr); + } + const std::vector got = dpooled.get(pooled_n), got_dead = ddead.get((size_t) IDXD); + std::vector terms; + const std::vector want = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, Alt{}, &terms); + const std::vector want_raw = ref_pooled_raw(rc); + + // (a) the spare slot: BIT-EXACT, because rope at position 0 is the identity in both (cos = 1, sin = 0 + // exactly), so the residual the pooled rows carry from the f32 rope cannot appear here. + int dead_bad = 0; + for (int64_t d = 0; d < IDXD; ++d) + if (got_dead[(size_t) d] != (float) want[(size_t) n_bid * IDXD + d]) ++dead_bad; + require("the spare slot's key (rms_norm of cell 0) is BIT-EXACT", dead_bad == 0, + std::to_string(dead_bad) + " of " + std::to_string(IDXD) + " wrong"); + require("the spare slot is at row n_bid and nowhere else", n_bid == 2, + "10 cells / r=4 -> 2 complete blocks"); + + // (b) the pooled blocks against the reference + // THE DENOMINATOR IS THE ROPE'S TERMS, not the result: `a*cos - b*sin` cancels, and the kernel's + // rotation runs in f32 over an f32 table (6e-8 per term) while the reference's runs in f64. Dividing + // by the result reports the cancellation, which is what made this read 1.067e-06 against a 1e-6 bar. + double worst = 0; + for (int64_t b = 0; b < n_bid; ++b) + for (int64_t d = 0; d < IDXD; ++d) { + const double wv = want[(size_t) b * IDXD + d]; + const double tm = terms[(size_t) b * IDXD + d]; + worst = std::max(worst, rel_terms(wv, (double) got[(size_t) b * IDXD + d], tm)); + } + report("pooled block keys vs the reference", worst, "rel/|rope terms|"); + if (!(worst <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++g_bad; } + + // (c) THE INCOMPLETE TAIL IS NOT POOLED: the two tail cells take the SPARE slot's score, which is cell + // 0's key - not their own mean. A rival reading that pools them would still fill every row. + { + std::vector tm((size_t) IDXD, 0.0); + for (int64_t i = n_bid * R; i < NT; ++i) + for (int64_t d = 0; d < IDXD; ++d) tm[(size_t) d] += rc.raw[(size_t) i][(size_t) d] / 2.0; + ref_rms_norm(tm, w_kn, EPS); + double num = 0, den = 0; + for (int64_t d = 0; d < IDXD; ++d) { + num += std::fabs(tm[(size_t) d] - (double) got_dead[(size_t) d]); + den += std::fabs(tm[(size_t) d]); + } + verdict("the incomplete tail is NOT pooled into the spare slot", num / den > 0.5, pct(num / den)); + } + + auto sep = [&](const std::string& name, const Alt& a) { + const std::vector alt = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, a); + double num = 0, den = 0; + // Rows 0..n_bid INCLUSIVE: the spare slot is row n_bid and three of the four rivals change + // nothing else, so leaving it out made "the spare key from the LAST raw key" separate 0.00%. + for (int64_t b = 0; b <= n_bid; ++b) + for (int64_t d = 0; d < IDXD; ++d) { + num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]); + den += std::fabs(want[(size_t) b * IDXD + d]); + } + verdict(name, num / den > 0.05, pct(num / den)); + }; + Alt a1; a1.rotate_at_block_start = false; + sep("rotating at the block's LAST cell is observable", a1); + Alt a2; a2.pool_then_norm = false; + sep("norm-then-pool vs pool-then-norm is observable", a2); + Alt a3; a3.dead_from_first = false; + sep("the spare key from the LAST raw key is observable", a3); + Alt a4; a4.rope_raw = true; + sep("rotating the RAW indexer keys is observable", a4); + { // THE POSITION BASE. The same reference with the cells at 0..9 instead of 100..109 - i.e. + // what a kernel that equates a cell's position with its index would compute. + RefCache flat = rc; + for (int64_t j = 0; j < NT; ++j) flat.pos[(size_t) j] = (double) j; + const std::vector alt = ref_pooled(flat, w_kn, EPS, (int) S.n_rot, THETA, Alt{}); + double num = 0, den = 0; + for (int64_t b = 0; b <= n_bid; ++b) + for (int64_t d = 0; d < IDXD; ++d) { + num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]); + den += std::fabs(want[(size_t) b * IDXD + d]); + } + verdict("the rotation's POSITION BASE (pos_base) is observable", num / den > 0.05, + pct(num / den)); + } + + // (d) THE TRAP THIS FIXTURE CANNOT SEE, measured and reported rather than hidden. `rms_norm` divides + // by sqrt(mean(x^2) + eps), so the 1/r in the mean cancels EXCEPT through eps: mean and sum differ + // by ~eps/(2*mean(x^2)) relative. `ref/qsa.py` L463-465 makes the same point about its own test. + { + std::vector psum = want_raw; + for (auto& x : psum) x *= (double) R; + std::vector nm = want_raw, ns = psum; + for (int64_t b = 0; b < n_bid; ++b) { + std::vector m(nm.begin() + (size_t) b * IDXD, nm.begin() + (size_t) (b + 1) * IDXD); + std::vector s(ns.begin() + (size_t) b * IDXD, ns.begin() + (size_t) (b + 1) * IDXD); + ref_rms_norm(m, w_kn, EPS); + ref_rms_norm(s, w_kn, EPS); + for (int64_t d = 0; d < IDXD; ++d) { + nm[(size_t) b * IDXD + d] = m[(size_t) d]; + ns[(size_t) b * IDXD + d] = s[(size_t) d]; + } + } + double num = 0, den = 0; + for (size_t i = 0; i < want_raw.size(); ++i) { + num += std::fabs(psum[i] - want_raw[i]); + den += std::fabs(want_raw[i]); + } + verdict("the 1/r divisor IS observable in the RAW pooled value", num / den > 0.5, + pct(num / den) + " (sum vs mean, before any norm)"); + std::printf(" %-48s %.3e <-- below EVERY score tolerance; the divisor cannot be\n", + "the same divisor AFTER the norm", rel_l1(ns, nm)); + std::printf(" %-48s %s\n", "", "checked downstream at all, which is why the raw value is the"); + std::printf(" %-48s %s\n", "", "only place the mean/sum question is answerable."); + } + } + + // ================= 3. qsa_index ================= + std::vector q_idx((size_t) (IDXN * IDXD)); + for (auto& x : q_idx) x = rnd(1.0); + // A bias of ~0.4 against scores of ~20 separates "applies the bias" from "drops it" by 3.4%, which + // is not a fixture that can see its own trap. This is a guard for the kernel's optional additional + // bias, separate from the mandatory incomplete-tail bias; it is sized to + // be comparable with the scores so that dropping it is material. + std::vector bias((size_t) (n_bid + 1)); + for (auto& x : bias) x = rnd(8.0f); + { + const std::vector got_pooled = dpooled.get(pooled_n); + const std::vector p64 = as_d(got_pooled); + const std::vector q_idx64 = as_d(q_idx); + const int64_t n_kv = NT; + Dev dp, dqi, dbias, dsc; + dp.put(got_pooled); + dqi.put(q_idx); + dbias.put(bias); + dsc.alloc((size_t) n_kv); + strata::kernels::qsa_index(dp.p, n_bid, dqi.p, dbias.p, S, n_kv, dsc.p, nullptr); + const std::vector got = dsc.get((size_t) n_kv); + const std::vector want = + ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, Alt{}); + + // The score is a SUM of four relu'd dots plus the bias, so the denominator is the magnitude of the + // TERMS - |dot| bounds a relu'd dot from above and is what is used here. + double worst = 0; + for (int64_t j = 0; j < n_kv; ++j) { + const int64_t cb = std::min(j / R, n_bid); + double terms = std::fabs((double) bias[(size_t) cb]); + if (cb == n_bid && n_kv % R != 0) terms += 1e9; + for (int64_t h = 0; h < IDXN; ++h) { + double dot = 0; + for (int64_t d = 0; d < IDXD; ++d) dot += p64[(size_t) cb * IDXD + d] * q_idx64[(size_t) h * IDXD + d]; + terms += std::fabs(dot); + } + worst = std::max(worst, rel_terms(want[(size_t) j], (double) got[(size_t) j], terms)); + } + report("indexer cell scores vs the reference", worst, "rel/Sum|terms|"); + if (!(worst <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++g_bad; } + + require("cells of one block share its score (0..3)", + got[0] == got[1] && got[1] == got[2] && got[2] == got[3] && got[0] != got[4]); + require("cells 8,9 (the tail) take the SPARE slot's score, not block 1's", + got[8] == got[9] && got[9] != got[7], "got[8] == got[9] != got[7]"); + + auto sep_scores = [&](const std::string& name, const Alt& a) { + const std::vector alt = ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, a); + double num = 0, den = 0; + // The mandatory tail bias must not swamp the score-arithmetic fixture. + for (int64_t j = 0; j < n_bid * R; ++j) { + num += std::fabs(alt[(size_t) j] - want[(size_t) j]); + den += std::fabs(want[(size_t) j]); + } + verdict(name, num / den > 0.05, pct(num / den)); + }; + Alt a5; a5.relu_per_head = false; + sep_scores("relu PER HEAD vs relu(sum of heads) is observable", a5); + Alt a6; a6.use_relu = false; + sep_scores("dropping the relu is observable", a6); + Alt a7; a7.use_bias = false; + sep_scores("dropping the per-block bias is observable", a7); + } + + // Causal decode's incomplete tail must survive even when its dot-product score + // ties every completed block. The oracle supplies +1e9 in set_input_qsa; + // without it, ascending-index top-k drops every tail after the sparse switch. + // Replay one captured graph across block/page boundaries to catch stale bias. + { + const int64_t max_n = 20480; + const int64_t max_blocks = max_n / R + 1; + const int64_t cap = strata::kernels::qsa_selection_width(max_n, S); + Dev pooled, query, scores((size_t) max_n); + Dev ids((size_t) cap), step(strata::kernels::kStepCount); + pooled.put(std::vector((size_t) max_blocks * IDXD, 0.0f)); + query.put(std::vector((size_t) IDXN * IDXD, 0.0f)); + + cudaStream_t stream; + cudaGraph_t graph; + cudaGraphExec_t exec; + check(cudaStreamCreate(&stream), "tail stream"); + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "tail capture begin"); + strata::kernels::qsa_index_step(pooled.p, query.p, nullptr, S, step.p, max_blocks, scores.p, stream); + strata::kernels::topk_512_step(scores.p, S, cap, step.p, ids.p, stream); + check(cudaStreamEndCapture(stream, &graph), "tail capture end"); + check(cudaGraphInstantiate(&exec, graph, 0), "tail instantiate"); + + const std::vector counts = { + 1, 2, 3, 4, 511, 512, 513, 2046, 2047, 2048, 2049, 2050, 2051, + 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, + 4095, 4096, 4097, 8191, 8192, 8193, 20477, 20478, 20479, 20480}; + for (const int64_t n : counts) { + const int64_t width = strata::kernels::qsa_selection_width(n, S); + const int64_t tail = n % R; + std::vector want; + for (int64_t j = 0; j < width - tail; ++j) want.push_back((int32_t) j); + for (int64_t j = n - tail; j < n; ++j) want.push_back((int32_t) j); + + strata::kernels::qsa_index(pooled.p, n / R, query.p, nullptr, S, n, scores.p, nullptr); + strata::kernels::topk_512(scores.p, n, S, cap, ids.p, nullptr); + require("tail static n=" + std::to_string(n), ids.get((size_t) width) == want); + + std::vector values(strata::kernels::kStepCount); + strata::kernels::qsa_step_fill(values.data(), n - 1, S); + step.put(values); + check(cudaGraphLaunch(exec, stream), "tail replay"); + check(cudaStreamSynchronize(stream), "tail replay sync"); + require("tail captured n=" + std::to_string(n), ids.get((size_t) width) == want); + const auto actual_scores = scores.get((size_t) n); + bool exact_scores = true; + for (int64_t j = 0; j < n; ++j) { + const float expected = j >= n - tail ? 1e9f : 0.0f; + exact_scores = exact_scores && actual_scores[(size_t) j] == expected; + } + require(" only incomplete cells receive the bias", exact_scores); + } + check(cudaGraphExecDestroy(exec), "tail exec destroy"); + check(cudaGraphDestroy(graph), "tail graph destroy"); + check(cudaStreamDestroy(stream), "tail stream destroy"); + } + + // ================= 4. topk_512, against an independent sort ================= + { + const int64_t CAP = strata::kernels::qsa_selection_width(MAXC, S); + Dev dsc; + Dev dids; + dsc.alloc((size_t) MAXC); + dids.alloc((size_t) CAP); + std::vector sc((size_t) MAXC); + + auto one = [&](const std::string& name, int64_t n_kv) { + dsc.put(std::vector(sc.begin(), sc.begin() + n_kv)); + strata::kernels::topk_512(dsc.p, n_kv, S, CAP, dids.p, nullptr); + const int64_t width = strata::kernels::qsa_selection_width(n_kv, S); + const std::vector g = dids.get((size_t) width); + const std::vector want = ref_select(as_d(std::vector(sc.begin(), sc.begin() + n_kv)), + n_kv, TOPK, false); + const bool ok = g == want; + require(name, ok, std::to_string(width) + " ids, width = min(n_kv, top_k + r - 1)"); + if (!ok) { + for (size_t i = 0; i < std::min(g.size(), want.size()); ++i) + if (g[i] != want[i]) { + std::printf(" first difference at %zu: got %d, want %d\n", i, g[i], want[i]); + break; + } + } + bool asc = true; + for (size_t i = 1; i < g.size(); ++i) if (g[i] <= g[i - 1]) asc = false; + require(" ...ascending and unique", asc); + return g; + }; + + for (auto& x : sc) x = rnd(1.0); + one("topk_512 n_kv = 1", 1); + one("topk_512 n_kv = 7 (random)", 7); + one("topk_512 n_kv = 2048 (the plan's threshold)", 2048); + one("topk_512 n_kv = 2051 (the reference's own bound)", 2051); + one("topk_512 n_kv = 2052 (two past the plan's number)", 2052); + one("topk_512 n_kv = 5000 (random)", 5000); + one("topk_512 n_kv = 32768 (= kTopkMaxCells)", MAXC); + + // ALL-EQUAL scores: every cell ties, so the answer must be 0..width-1 and any other tie rule shows up + // on the first element. ggml does not specify the rule; the reference and the kernel both say + // ascending index, and this is the case that distinguishes them. + std::fill(sc.begin(), sc.begin() + 2052, 0.25f); + one("topk_512 with 2052 EQUAL scores (every cell ties)", 2052); + + // a tie BLOCK straddling the cut: 100 cells share the cut score and only some of them fit + for (int64_t j = 0; j < 5000; ++j) sc[(size_t) j] = (float) (-(double) j); + for (int64_t j = 2051 - 50; j < 2051 + 50; ++j) sc[(size_t) j] = -1000.0f; + one("topk_512 with a 100-cell tie straddling the cut", 5000); + + // THE IDENTITY BELOW THE BOUND. `select_cells` returns `arange` whenever width == n_kv, which is what + // "selection skipped when context <= 2,048" means - and it holds to 2,051, not 2,048. + for (int64_t n : {(int64_t) 2048, (int64_t) 2051}) { + for (int64_t j = 0; j < n; ++j) sc[(size_t) j] = rnd(1.0); + const std::vector g = one(std::string("topk_512 n_kv = ") + std::to_string(n) + + " selects every cell (identity)", + n); + bool ident = (int64_t) g.size() == n; + for (int64_t j = 0; j < n && ident; ++j) if (g[(size_t) j] != j) ident = false; + require(" ...and it really is 0,1,2,...", ident); + } + { // one past the bound the identity must FAIL, or the two checks above prove nothing + for (int64_t j = 0; j < 2052; ++j) sc[(size_t) j] = rnd(1.0); + const std::vector g = one("topk_512 n_kv = 2052 is NOT the identity", 2052); + std::vector kept(2052, 0); + for (int32_t id : g) kept[(size_t) id] = 1; + int64_t missing = 0; + for (int64_t j = 0; j < 2052; ++j) if (!kept[(size_t) j]) ++missing; + int64_t argmin = 0; + for (int64_t j = 1; j < 2052; ++j) if (sc[(size_t) j] < sc[(size_t) argmin]) argmin = j; + require(" ...exactly one cell is dropped, and it is the smallest score", + missing == 1 && !kept[(size_t) argmin], std::to_string(missing) + " dropped"); + } + } + + // ================= 5. qsa_attend on the loud-cell fixture ================= + // `ref/qsa.py` PROPERTY 8's own numbers: a key with 100 in its first dim against zeros, a value of 10 + // against 1, and q[:,0] = 1. The logit gap is 100/sqrt(256) = 6.25, so the loud cell takes ~99% of its + // head's weight - and exactly zero when it is not in the selected set. + { + const int64_t N = 8; + std::vector> k2, v2; + std::vector k2f, v2f; + for (int64_t j = 0; j < N; ++j) { + std::vector kk((size_t) (NKV * HD), 0.0), vv((size_t) (NKV * HD), 0.0); + for (int64_t h = 0; h < NKV; ++h) vv[(size_t) (h * HD)] = 1.0; + kk[0] = j == N - 1 ? 100.0 : 0.0; + vv[0] = j == N - 1 ? 10.0 : 1.0; + for (int64_t i = 0; i < NKV * HD; ++i) { k2f.push_back((float) kk[(size_t) i]); v2f.push_back((float) vv[(size_t) i]); } + k2.push_back(kk); + v2.push_back(vv); + } + std::vector q((size_t) (NH * HD), 0.0); + for (int64_t h = 0; h < NH; ++h) q[(size_t) (h * HD)] = 1.0; + + Dev dq; + dq.put(as_f(q)); + const size_t scr = (size_t) N * NKV * HD; + std::vector kbits(scr), vbits(scr); + for (size_t i = 0; i < scr; ++i) { kbits[i] = f16_from_f32(k2f[i]); vbits[i] = f16_from_f32(v2f[i]); } + Dev dks(scr), dvs(scr); + dks.put(kbits); + dvs.put(vbits); + Dev dattn((size_t) NH * HD), dwt((size_t) NH * N); + + std::vector all(N), no_loud(N - 1); + for (int64_t j = 0; j < N; ++j) all[(size_t) j] = (int32_t) j; + for (int64_t j = 0; j < N - 1; ++j) no_loud[(size_t) j] = (int32_t) j; + + // the scratch is written directly here (no pool), so this section is about the attention alone + strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N, S, dattn.p, dwt.p, nullptr); + const std::vector out_all = as_d(dattn.get((size_t) NH * HD)); + strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N - 1, S, dattn.p, nullptr, nullptr); + const std::vector out_sel = as_d(dattn.get((size_t) NH * HD)); + const std::vector wts = as_d(dwt.get((size_t) NH * N)); + + verdict("with every cell selected the loud cell dominates its head 0", out_all[0] > 5.0, + "out[0][0] = " + std::to_string(out_all[0]).substr(0, 6)); + require("with the loud cell unselected it contributes EXACTLY nothing", + std::fabs(out_sel[0] - 1.0) < 1e-6, "out[0][0] = " + std::to_string(out_sel[0]).substr(0, 8)); + double worst_sum = 0; + for (int64_t h = 0; h < NH; ++h) { + double s = 0; + for (int64_t j = 0; j < N; ++j) s += wts[(size_t) (h * N + j)]; + worst_sum = std::max(worst_sum, std::fabs(s - 1.0)); + } + report("the returned weights sum to 1 per head", worst_sum, "max |1 - sum|"); + + auto sep_attend = [&](const std::string& name, const Alt& a) { + const std::vector alt = ref_attend(q, NH, NKV, HD, all, k2, v2, a, nullptr); + double num = 0, den = 0; + for (size_t i = 0; i < alt.size(); ++i) { + num += std::fabs(alt[i] - out_all[i]); + den += std::fabs(alt[i]); + } + verdict(name, num / den > 0.05, pct(num / den)); + }; + Alt a8; a8.kv_divide = false; + sep_attend("q % 2 vs q / 12 for the kv head is observable", a8); + // The scale trap is NOT asserted on this fixture: its softmax is saturated (the loud cell holds 99% + // of the weight, so removing a 16x logit scale moves it to 100% and the output by 1.09%). It is + // asserted on the random 2100-cell fixture below, where the logits are O(10) and the temperature + // actually matters. This is round 196's lesson about a fixture that cannot see its own trap. + std::printf(" %-48s %-6s %s\n", " (the scale trap is measured on the random fixture)", "--", + "this fixture's softmax is saturated"); + { // the mask: the same reference with and without the loud cell in the selected set + const std::vector with_loud = ref_attend(q, NH, NKV, HD, all, k2, v2, Alt{}, nullptr); + const std::vector without = ref_attend(q, NH, NKV, HD, no_loud, k2, v2, Alt{}, nullptr); + double num = 0, den = 0; + for (size_t i = 0; i < with_loud.size(); ++i) { + num += std::fabs(with_loud[i] - without[i]); + den += std::fabs(with_loud[i]); + } + verdict("attending to the unselected cell is observable", num / den > 0.05, pct(num / den)); + } + } + + // ================= 6. the whole layer at n_kv = 2100, so the selection is genuinely sparse ============= + int64_t width = 0; + { + const int64_t T = 2100; // > 2051, so `width` really truncates + width = strata::kernels::qsa_selection_width(T, S); + std::vector pk((size_t) T * NKV * HD), pv((size_t) T * NKV * HD), praw((size_t) T * IDXD); + std::vector> k16((size_t) T), v16((size_t) T); + RefCache pc; + std::vector q((size_t) NH * HD); + for (auto& x : q) x = rnd(1.0); + for (int64_t t = 0; t < T; ++t) { + std::vector kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD); + for (int64_t i = 0; i < NKV * HD; ++i) { + kk[(size_t) i] = gauss(rng); + vv[(size_t) i] = gauss(rng); + pk[(size_t) t * NKV * HD + i] = (float) kk[(size_t) i]; + pv[(size_t) t * NKV * HD + i] = (float) vv[(size_t) i]; + } + for (int64_t d = 0; d < IDXD; ++d) { + rr[(size_t) d] = gauss(rng); + praw[(size_t) t * IDXD + d] = (float) rr[(size_t) d]; + } + for (int64_t i = 0; i < NKV * HD; ++i) { + kk[(size_t) i] = (double) pk[(size_t) t * NKV * HD + i]; // the f32 the device got + vv[(size_t) i] = (double) pv[(size_t) t * NKV * HD + i]; + } + for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) praw[(size_t) t * IDXD + d]; + pc.append(kk, vv, rr, (double) t); + k16[(size_t) t].resize((size_t) (NKV * HD)); + v16[(size_t) t].resize((size_t) (NKV * HD)); + for (int64_t i = 0; i < NKV * HD; ++i) { + k16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pk[(size_t) t * NKV * HD + i])); + v16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pv[(size_t) t * NKV * HD + i])); + } + } + const int64_t p_nbid = T / R; // 525 complete blocks; the spare key sits at row 525 + const int64_t page_size = 64, n_pages = (T + page_size - 1) / page_size; + strata::kernels::QsaShapes Sp = S; // the granule lives in the shapes: see section 1 + Sp.page_size = page_size; + std::vector table((size_t) n_pages); + for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) (n_pages - 1 - i); // REVERSED + + Dev dtab; + dtab.put(table); + Dev dpk_all, dpv_all; + dpk_all.put(pk); + dpv_all.put(pv); + Dev dpk((size_t) n_pages * NKV * page_size * HD), dpv((size_t) n_pages * NKV * page_size * HD); + for (int64_t t = 0; t < T; ++t) + strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, t, dpk_all.p + (size_t) t * NKV * HD, + dpv_all.p + (size_t) t * NKV * HD, Sp, nullptr); + + const size_t ppooled_n = (size_t) (p_nbid + 1) * IDXD; + Dev dpp((size_t) ppooled_n), dpdead((size_t) IDXD), dptail((size_t) (R - 1) * IDXD); + Dev dblockpos2(1); + Dev dpos2(1); + Dev draw((size_t) IDXD); + strata::kernels::QsaIndexerBuffers bufs{dptail.p, dpdead.p, dpp.p, dblockpos2.p}; + for (int64_t t = 0; t < T; ++t) { + check(cudaMemcpy(draw.p, &praw[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); + const int32_t tpos = (int32_t) t; + check(cudaMemcpy(dpos2.p, &tpos, 4, cudaMemcpyHostToDevice), "pos2"); + strata::kernels::indexer_key_append(draw.p, dpos2.p, 0, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p, + nullptr); + } + Dev dqidx, dsc; + dqidx.put(q_idx); + dsc.alloc((size_t) T); + strata::kernels::qsa_index(dpp.p, p_nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); + + Dev dsel((size_t) T); + strata::kernels::topk_512(dsc.p, T, S, T, dsel.p, nullptr); + const std::vector sel_sparse = dsel.get((size_t) width); + const std::vector pool32 = dpp.get(ppooled_n); + const std::vector pool64 = as_d(pool32); + const std::vector q_idx64 = as_d(q_idx); + const std::vector sc_want = + ref_indexer_scores(pool64, p_nbid, q_idx64, IDXN, IDXD, {}, T, Alt{}); + const std::vector sel_want = ref_select(sc_want, T, TOPK, false); + require("the selected set matches the reference (2100 cells, width 2051)", sel_sparse == sel_want, + std::to_string(width) + " ids"); + + // HOW CLOSE IS THE CUT? `indexer_ids` is an EXACT capture key, so a boundary gap of a few fp32 ulp + // would make it sensitive to the accumulation order. The gap is measured in ulp of the cut score. + { + std::vector issel((size_t) T, 0); + for (int32_t id : sel_sparse) issel[(size_t) id] = 1; + double lo = 1e300, hi = -1e300; + for (int32_t id : sel_sparse) lo = std::min(lo, sc_want[(size_t) id]); + for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j]) hi = std::max(hi, sc_want[(size_t) j]); + if (lo == hi) { + // The cut sits inside a group of cells that all score exactly the same - here 0.0, a relu + // signal with all four head dots negative - so nothing but the ascending-index rule decides + // which of them survive. A gap metric is undefined there; the tie is the finding. + int64_t tied_in = 0, tied_out = 0; + for (int32_t id : sel_sparse) if (sc_want[(size_t) id] == lo) ++tied_in; + for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j] && sc_want[(size_t) j] == lo) ++tied_out; + std::printf(" %-48s THE CUT IS A TIE at %.6f: %lld selected, %lld rejected\n", + "the cut", lo, (long long) tied_in, (long long) tied_out); + require(" ...and the kernel picks the same ones as the reference", sel_sparse == sel_want); + } else { + report("the selection boundary gap, in fp32 ulp of the cut", + (lo - hi) / (std::fabs(lo) * 1.2e-7), "gap/ulp"); + std::printf(" %-48s last selected %.6f, first rejected %.6f\n", "the cut", lo, hi); + } + } + + // the pipeline. `--qsa-dense` swaps the SELECTION for every cell and keeps everything else; the sparse + // selection above is still compared against the reference either way. + std::vector sel = sel_sparse; + if (dense) { + sel.resize((size_t) T); + for (int64_t j = 0; j < T; ++j) sel[(size_t) j] = (int32_t) j; + } + Dev dsel2; + dsel2.put(sel); + const int64_t nsel = (int64_t) sel.size(); + Dev dks((size_t) nsel * NKV * HD), dvs((size_t) nsel * NKV * HD); + strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel2.p, nsel, Sp, dks.p, dvs.p, nullptr); + Dev dqq, dattn((size_t) NH * HD), dwt((size_t) NH * nsel); + dqq.put(q); + strata::kernels::qsa_attend(dqq.p, dks.p, dvs.p, nsel, S, dattn.p, dwt.p, nullptr); + const std::vector attn = as_d(dattn.get((size_t) NH * HD)); + const std::vector wts = as_d(dwt.get((size_t) NH * nsel)); + + const std::vector q64 = as_d(q); + const std::vector attn_f64 = ref_attend(q64, NH, NKV, HD, sel, pc.k, pc.v, Alt{}, nullptr); + const std::vector attn_f16 = ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, nullptr); + double num = 0, den = 0; + for (size_t i = 0; i < attn.size(); ++i) { + num += std::fabs(attn[i] - attn_f16[i]); + den += std::fabs(attn_f16[i]); + } + report("qsa_attend vs the reference on the SAME fp16 cache", num / den, "rel"); + { // the SCALE trap, on data whose softmax is not saturated + Alt a; a.apply_scale = false; + const std::vector alt = ref_attend(q64, NH, NKV, HD, sel, k16, v16, a, nullptr); + double n2 = 0, d2 = 0; + for (size_t i = 0; i < alt.size(); ++i) { + n2 += std::fabs(alt[i] - attn_f16[i]); + d2 += std::fabs(attn_f16[i]); + } + verdict("omitting 1/sqrt(head_dim) is observable (random fixture)", n2 / d2 > 0.05, pct(n2 / d2)); + } + if (!(num / den <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++g_bad; } + const double fp16_cost = rel_l1(attn_f64, attn_f16); + report("the fp16 KV cache's OWN cost (f32 keys vs fp16 keys)", fp16_cost, "rel"); + if (!(fp16_cost <= 1e-3)) { + std::printf(" *** the phase's 1e-3 for FP16 paths is exceeded by the CACHE ***\n"); + ++g_bad; + } + { + std::vector w_ref; + ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, &w_ref); + double wn = 0, wd = 0; + for (int64_t j = 0; j < nsel; ++j) { + wn += std::fabs(wts[(size_t) j] - w_ref[(size_t) j]); + wd += std::fabs(w_ref[(size_t) j]); + } + report("the returned weights vs the reference (head 0)", wn / wd, "rel"); + } + + // the gate + std::vector q_full((size_t) (NH * 2 * HD)); + for (auto& x : q_full) x = rnd(2.0); + Dev dqf, dattnf; + dqf.put(q_full); + dattnf.put(as_f(attn)); + Dev dgate((size_t) NH * HD); + strata::kernels::qsa_gate_apply(dattnf.p, dqf.p, S, dgate.p, nullptr); + const std::vector gate16 = dgate.get((size_t) NH * HD); + const std::vector qf64 = as_d(q_full); + const std::vector gwant = ref_gate(attn, qf64, NH, HD, Alt{}); + double gnum = 0, gden = 0; + int gbits = 0; + for (size_t i = 0; i < gwant.size(); ++i) { + gnum += std::fabs((double) f32_from_f16(gate16[i]) - gwant[i]); + gden += std::fabs(gwant[i]); + if (gate16[i] != f16_from_f32((float) gwant[i])) ++gbits; + } + report("qsa_gate_apply vs the double reference", gnum / gden, "rel (f16 out quant ~2.4e-4)"); + if (!(gnum / gden <= 1e-3)) { std::printf(" *** over 1e-3 ***\n"); ++g_bad; } + std::printf(" %-48s %d of %lld (CUDA's double exp vs libm's, in the last bits)\n", + "fp16 gate bits differing from the reference", gbits, (long long) gwant.size()); + + auto sep_gate = [&](const std::string& name, const Alt& a) { + const std::vector alt = ref_gate(attn, qf64, NH, HD, a); + double n2 = 0, d2 = 0; + for (size_t i = 0; i < alt.size(); ++i) { + n2 += std::fabs(alt[i] - gwant[i]); + d2 += std::fabs(gwant[i]); + } + verdict(name, n2 / d2 > 0.05, pct(n2 / d2)); + }; + Alt a10; a10.gate_second_half = false; + sep_gate("the gate from the FIRST half is observable", a10); + Alt a11; a11.gate_sigmoid = false; + sep_gate("silu instead of sigmoid on the QSA gate is observable", a11); + + // DENSE vs SPARSE. Below the bound the width IS n_kv, so the two paths must agree EXACTLY (P1.S4's + // isolation property, `ref/qsa.py` PROPERTY 9b); above it they must differ, or the switch is a no-op. + require("below the bound, dense and sparse are the SAME selection", + ref_select(sc_want, 2000, TOPK, false) == ref_select(sc_want, 2000, TOPK, true)); + { + // BOTH SIDES COMPUTED HERE, from their own id lists and independently of `--qsa-dense`. The first + // version compared against the pipeline's `attn`, which in dense mode IS the dense attention - so the + // switch silently turned the check into a comparison of a thing with itself and reported 0.00%. + const std::vector dense_all = ref_select(sc_want, T, TOPK, true); + auto attend_ids = [&](const std::vector& ids) { + Dev did; + did.put(ids); + Dev dk2((size_t) ids.size() * NKV * HD), dv2((size_t) ids.size() * NKV * HD); + strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, did.p, (int64_t) ids.size(), Sp, dk2.p, dv2.p, + nullptr); + Dev da((size_t) NH * HD); + strata::kernels::qsa_attend(dqq.p, dk2.p, dv2.p, (int64_t) ids.size(), S, da.p, nullptr, nullptr); + return as_d(da.get((size_t) NH * HD)); + }; + const std::vector dense_attn = attend_ids(dense_all); + const std::vector sparse_attn = attend_ids(sel_sparse); + double dn = 0, dd = 0; + for (size_t i = 0; i < sparse_attn.size(); ++i) { + dn += std::fabs(dense_attn[i] - sparse_attn[i]); + dd += std::fabs(sparse_attn[i]); + } + verdict("dense differs from sparse at n_kv = 2100 (> 2051)", dn / dd > 0.05, pct(dn / dd)); + } + } + + // ================= 7. the empty selection ================= + { + Dev dq((size_t) NH * HD), dattn((size_t) NH * HD); + dq.put(std::vector((size_t) NH * HD, 1.0f)); + dattn.put(std::vector((size_t) NH * HD, 7.0f)); + strata::kernels::qsa_attend(dq.p, nullptr, nullptr, 0, S, dattn.p, nullptr, nullptr); + const std::vector got = dattn.get((size_t) NH * HD); + bool allz = true; + for (float x : got) if (x != 0.0f) allz = false; + require("an EMPTY selection gives a zero attention, not a NaN", allz, "all 6144 elements zero"); + } + + // ================= 8. --bench: what one QSA layer costs at 32K of context ================= + if (bench) { + const int64_t T = MAXC; // 32,768 cells = 32K of context + const int64_t nbid = T / R; + const int64_t ps = S.page_size, n_pages = (T + ps - 1) / ps; + const int64_t w = strata::kernels::qsa_selection_width(T, S); + std::printf("\n --bench at n_kv = %lld, page_size %lld, selection width %lld\n", (long long) T, + (long long) ps, (long long) w); + std::vector table((size_t) n_pages); + for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) i; + Dev dtab; + dtab.put(table); + Dev dpk((size_t) n_pages * NKV * ps * HD), dpv((size_t) n_pages * NKV * ps * HD); + std::vector kz((size_t) NKV * HD), vz((size_t) NKV * HD); + for (auto& x : kz) x = rnd(1.0); + for (auto& x : vz) x = rnd(1.0); + Dev dkz, dvz; + dkz.put(kz); + dvz.put(vz); + strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr); + + const size_t ppooled_n = (size_t) (nbid + 1) * IDXD; + Dev dpp((size_t) ppooled_n), dsc((size_t) T); + std::vector pz(ppooled_n), sz((size_t) T); + for (auto& x : pz) x = rnd(0.1f); + for (auto& x : sz) x = std::fabs(rnd(1.0f)); + dpp.put(pz); + dsc.put(sz); + Dev dqidx; + dqidx.put(q_idx); + Dev dsel((size_t) w); + Dev dks((size_t) w * NKV * HD), dvs((size_t) w * NKV * HD); + Dev dq((size_t) NH * HD), dattn((size_t) NH * HD), dwt((size_t) NH * w); + std::vector qv((size_t) NH * HD); + for (auto& x : qv) x = rnd(1.0); + dq.put(qv); + + auto timeit = [&](const std::string& name, int reps, const std::function& fn) { + cudaEvent_t a, b; + cudaEventCreate(&a); + cudaEventCreate(&b); + fn(); + cudaDeviceSynchronize(); + cudaEventRecord(a); + for (int i = 0; i < reps; ++i) fn(); + cudaEventRecord(b); + cudaEventSynchronize(b); + float ms = 0; + cudaEventElapsedTime(&ms, a, b); + std::printf(" %-48s %8.1f us\n", name.c_str(), ms * 1000.0f / (float) reps); + cudaEventDestroy(a); + cudaEventDestroy(b); + }; + const int reps = 20; + timeit("qsa_index (8193 pooled rows x 4 heads)", reps, + [&] { strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); }); + timeit("topk_512 (32768 cells)", reps, + [&] { strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); }); + strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); + timeit("kv_gather (2051 ids through the page table)", reps, + [&] { strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr); }); + timeit("qsa_attend (2051 selected, 24 heads)", reps, + [&] { strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr); }); + timeit("kv_append (one cell, 2 heads x 256)", 200, + [&] { strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr); }); + timeit("ONE QSA LAYER (index+topk+gather+attend)", reps, [&] { + strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); + strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); + strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr); + strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr); + }); + } + + // ================= 6. indexer_key_append IS CAPTURABLE ================= + // + // THE PROPERTY THE DEVICE-POSITION REFACTOR WAS FOR, TESTED DIRECTLY rather than argued. `indexer_key_append` + // took `int64_t pos` as a host scalar, which a CUDA graph bakes in at capture time - so a captured call + // would replay the first token's position forever: `slot = pos % r` never advances, no block completes, and + // the indexer keeps pooling cells 0-3 for the whole sequence. + // + // The test captures ONE call, then replays the SAME graph twice with `pos_dev` and `raw` changed between + // them, and requires the second replay to land in a DIFFERENT pooled row with the reference's value. If the + // position were still baked in, both replays would write row 0 and the pooled rows would be identical. + // + // That is the negative control built into the assertion: "row 1 is correct" alone could also pass for a + // graph that reread the position by accident, but "row 0 unchanged AND row 1 correct AND row 1 != row 0" + // cannot pass for a baked-in position. + { + std::printf("\n-- indexer_key_append under graph capture\n"); + const int R2 = 4; + const int64_t NCELL = 8; // two complete blocks of r=4 + const size_t IDXD2 = (size_t) IDXD; + std::vector raw2((size_t) NCELL * IDXD2); + for (size_t i = 0; i < raw2.size(); ++i) raw2[i] = (float) std::sin((double) i * 0.013) * 2.0f - 0.3f; + + const int64_t nb2 = NCELL / R2; + Dev pooled2((size_t) (nb2 + 2) * IDXD2), dead2(IDXD2), tail2((size_t) (R2 - 1) * IDXD2); + Dev bpos2(1), pos2(1); + Dev raw2d(IDXD2); + strata::kernels::QsaIndexerBuffers bufs2{tail2.p, dead2.p, pooled2.p, bpos2.p}; + + // capture ONE call, on its own stream + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begincap"); + strata::kernels::indexer_key_append(raw2d.p, pos2.p, POS_BASE, dw_kn.p, EPS, bufs2, S, dcos.p, dsin.p, + (void*) cs); + cudaGraph_t g2 = nullptr; + check(cudaStreamEndCapture(cs, &g2), "endcap"); + check(cudaStreamDestroy(cs), "csd"); + size_t nodes2 = 0; + check(cudaGraphGetNodes(g2, nullptr, &nodes2), "nodes"); + cudaGraphExec_t ex2 = nullptr; + check(cudaGraphInstantiate(&ex2, g2, 0), "inst"); + + // replay A: cells 0..3, which completes block 0 + for (int t = 0; t < 4; ++t) { + check(cudaMemcpy(raw2d.p, &raw2[(size_t) t * IDXD2], IDXD2 * 4, cudaMemcpyHostToDevice), "r2"); + const int32_t tp = t; + check(cudaMemcpy(pos2.p, &tp, 4, cudaMemcpyHostToDevice), "p2"); + check(cudaGraphLaunch(ex2, nullptr), "launchA"); + } + const std::vector afterA = pooled2.get((size_t) (nb2 + 2) * IDXD2); + + // replay B: cells 4..7 through the SAME graph, which completes block 1 + for (int t = 4; t < 8; ++t) { + check(cudaMemcpy(raw2d.p, &raw2[(size_t) t * IDXD2], IDXD2 * 4, cudaMemcpyHostToDevice), "r3"); + const int32_t tp = t; + check(cudaMemcpy(pos2.p, &tp, 4, cudaMemcpyHostToDevice), "p3"); + check(cudaGraphLaunch(ex2, nullptr), "launchB"); + } + check(cudaDeviceSynchronize(), "sync2"); + const std::vector afterB = pooled2.get((size_t) (nb2 + 2) * IDXD2); + + std::printf(" %-44s %zu nodes for one call\n", "the pooled kernel is capturable", nodes2); + + // row 0 must be UNTOUCHED by the second block's replays + int row0_same = 0; + for (size_t d = 0; d < IDXD2; ++d) + if (afterA[d] == afterB[d]) ++row0_same; + std::printf(" %-44s %d of %zu unchanged\n", "the first block's row survives replay B", row0_same, + IDXD2); + if (row0_same != (int) IDXD2) ++g_bad; + + // row 1 must now be FILLED by the captured graph - the whole point + int row1_nonzero = 0; + for (size_t d = 0; d < IDXD2; ++d) + if (afterB[IDXD2 + d] != 0.0f) ++row1_nonzero; + std::printf(" %-44s %d of %zu non-zero\n", "the SECOND block's row arrives through the same graph", + row1_nonzero, IDXD2); + if (row1_nonzero != (int) IDXD2) ++g_bad; + + // and the two rows must DIFFER, which a baked-in position cannot produce + int rows_differ = 0; + for (size_t d = 0; d < IDXD2; ++d) + if (afterB[d] != afterB[IDXD2 + d]) ++rows_differ; + std::printf(" %-44s %d of %zu differ\n", "the two pooled rows are different keys", rows_differ, + IDXD2); + // A baked-in position would have written row 0 a second time and left row 1 at zero, so these two + // assertions together are the negative control for the refactor. + if (rows_differ != (int) IDXD2) ++g_bad; + + check(cudaGraphExecDestroy(ex2), "exd"); + check(cudaGraphDestroy(g2), "gd"); + } + + // ================= the NATIVE indexer's batched append vs the sequential one ================= + // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends + // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's + // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', + // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction) + // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling. + // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would + // pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed + // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential + // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own + // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract). + { + std::printf("\n-- the native indexer's batched append vs the sequential one\n"); + const int64_t NB = 8; // exactly two complete blocks of r=4 + const int32_t BASE = 100; // positions 100..107, not cell indices 0..7 + const int64_t MC = 1024; // the capacity both sides validate against + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; + std::vector raws((size_t) NB * IDXD); + for (int64_t t = 0; t < NB; ++t) + for (int64_t d = 0; d < IDXD; ++d) + raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4))); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + std::vector none_pooled; + for (const Variant& var : variants) { + strata::kernels::RopeScaling sc; + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + Dev pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows); + Dev bposA(1), bposB(1), dpos(1); + for (Dev* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB}) + check(cudaMemset(dp->p, 0, dp == &pooledA || dp == &pooledB ? prows * 4 + : dp == &deadA || dp == &deadB ? IDXD * 4 : trows * 4), "zero"); + check(cudaMemset(bposA.p, 0, 4), "zero"); check(cudaMemset(bposB.p, 0, 4), "zero"); + Dev draw((size_t) IDXD), drawAll; + drawAll.put(raws); + strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p}; + strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p}; + for (int64_t t = 0; t < NB; ++t) { // the sequential side: one cell, its device position + check(cudaMemcpy(draw.p, &raws[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); + const int32_t tp = (int32_t) t; + check(cudaMemcpy(dpos.p, &tp, 4, cudaMemcpyHostToDevice), "pos"); + strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs); + } + strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs); + check(cudaStreamSynchronize(cs), "sync"); + const std::vector pa = pooledA.get(prows), pb = pooledB.get(prows); + const std::vector da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD); + const std::vector ta = tailA.get(trows), tbb = tailB.get(trows); + const std::vector ba = bposA.get(1), bb = bposB.get(1); + long long bad = 0; + for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0; + for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0; + for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0; + bad += std::memcmp(&ba[0], &bb[0], 4) != 0; + std::printf(" %-44s %s (%lld of %zu state words differ)\n", + (std::string("batch vs sequential, ") + var.name).c_str(), + bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1); + if (bad) ++g_bad; + if (var.type == RST::None) none_pooled = pa; + else { + int moved = 0; + for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0; + std::printf(" %-44s %d of %zu pooled words differ from the none baseline\n", + (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size()); + if (!moved) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } + } + } + check(cudaStreamDestroy(cs), "csd"); + } + + // ================= the spare (position 0) under rope scaling: the table indexer vs the native one ========= + // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is + // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the + // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and + // the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left + // the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY + // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals + // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and + // under YaRN the factor is observable (row 0 is not 1). + { + std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n"); + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; + const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot; + std::vector raw0((size_t) IDXD); + for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0); + Dev draw0; + draw0.put(raw0); + Dev dpos0(1); + const int32_t zero = 0; + check(cudaMemcpy(dpos0.p, &zero, 4, cudaMemcpyHostToDevice), "pos0"); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + // one cell at position 0 through either kernel; returns (dead, pooled[0]) + auto spare = [&](bool native, const strata::kernels::RopeScaling& sc, std::vector& dead, + std::vector& pooled0) { + Dev pooled(prows), dd((size_t) IDXD), tail(trows); + Dev bpos(1); + check(cudaMemset(pooled.p, 0, prows * 4), "zero"); + check(cudaMemset(dd.p, 0, (size_t) IDXD * 4), "zero"); + check(cudaMemset(tail.p, 0, trows * 4), "zero"); + check(cudaMemset(bpos.p, 0, 4), "zero"); + strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p}; + if (native) { + strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs); + } else { + std::vector tc((size_t) (MC * HALF)), ts(tc.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data()); + Dev dc, dsn; + dc.put(tc); + dsn.put(ts); + strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs); + } + check(cudaStreamSynchronize(cs), "sync"); + dead = dd.get((size_t) IDXD); + pooled0 = pooled.get((size_t) IDXD); + }; + std::vector t_none, t_none_p, n_none, n_none_p; + for (const Variant& var : variants) { + strata::kernels::RopeScaling sc; + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; + std::vector row0c((size_t) (MC * HALF)), row0s(row0c.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data()); + std::vector td, tp, nd, np; + spare(false, sc, td, tp); + spare(true, sc, nd, np); + if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; } + long long tbad = 0, pbad = 0, sin_bad = 0; + double nworst = 0; + for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f; + for (int64_t d = 0; d < IDXD; ++d) { + const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f; + const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d]; + tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0; + pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0; + const double nwant = (double) n_none[(size_t) d] * (double) c0; + const double den = std::max(std::fabs(nwant), 1e-6); + nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den); + } + require(std::string(" ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0, + std::to_string(sin_bad) + " nonzero sines"); + require(std::string(" ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT", + tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong"); + require(std::string(" ") + var.name + ": the table's pooled[0] is its spare", pbad == 0, + std::to_string(pbad) + " wrong"); + require(std::string(" ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7, + "worst relative " + std::to_string(nworst)); + if (var.type == RST::YaRN) { + int moved = 0; + for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0; + require(" yarn 2: the magnitude correction is observable on the table spare", + row0c[0] != 1.0f && moved > NROT / 2, + "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved"); + } + } + check(cudaStreamDestroy(cs), "csd"); + } + + std::printf("\nqsa: %d failures\n", g_bad); + if (g_bad) return 1; + if (selftest) std::printf("qsa_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/qsa_prompt_attn_parity.cpp b/engine/strata/src/kernels/qsa_prompt_attn_parity.cpp new file mode 100644 index 00000000..c5dad7c9 --- /dev/null +++ b/engine/strata/src/kernels/qsa_prompt_attn_parity.cpp @@ -0,0 +1,230 @@ +// src/kernels/qsa_prompt_attn_parity.cpp - perf-review D-1: the tensor-core prompt attention (qsa_prompt_attn.hpp) +// against the FP32 kernel it replaces (`qsa_decode_attn_batch`) and an FP64 host reference (GPU, synthetic, no model). +// +// Int8 and FP16 pools with random codes, scales and queries; selections shaped like the prompt path's (the 2,051 +// widest, a recent window plus older cells that drift slowly from one query to the next, so neighbours share most +// of them as they do in a real prompt; short contexts take every cell). Checks: +// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math); +// 2. the new and old outputs agree to a relative 1e-4 of the output scale; +// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it). +// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12. +// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5] +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* up(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +float h2f(uint16_t b) { __half h; *reinterpret_cast(&h) = b; return __half2float(h); } +uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast(&h); } + +int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16 + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size; + const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS; + std::mt19937 rng(1234 + fmt); + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution code(-127, 127); + std::uniform_real_distribution sc(0.005f, 0.03f); + // pools; page table a shuffled permutation (the readers must follow it) + std::vector kq, vq; + std::vector ks, vs, kh, vh; + if (fmt == 1) { + kq.resize(rows * HD); vq.resize(rows * HD); ks.resize(rows * 4); vs.resize(rows * 4); + for (auto& x : kq) x = (int8_t) code(rng); + for (auto& x : vq) x = (int8_t) code(rng); + for (auto& x : ks) x = f2h(sc(rng)); + for (auto& x : vs) x = f2h(sc(rng)); + } else { + kh.resize(rows * HD); vh.resize(rows * HD); + for (auto& x : kh) x = f2h(nd(rng) * 1.5f); + for (auto& x : vh) x = f2h(nd(rng)); + } + std::vector table(pages); + for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i; + std::shuffle(table.begin(), table.end(), rng); + // queries at positions ctx - nq .. ctx - 1 + const int64_t cap = k::qsa_selection_width(ctx, s); + std::vector ids((size_t) (nq * cap), 0), steps((size_t) (nq * k::kStepCount), 0); + std::vector q((size_t) (nq * NH * HD)); + for (auto& x : q) x = nd(rng) * 2.0f; + std::vector old_cells; + for (int64_t i = 0; i < nq; ++i) { + const int64_t pos = ctx - nq + i, nkv = pos + 1; + const int64_t w = k::qsa_selection_width(nkv, s); + int32_t* sel = ids.data() + i * cap; + steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w; + if (w == nkv) { + for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c; + continue; + } + const int64_t recent = 512, older = w - recent; + if ((int64_t) old_cells.size() != older) { // the older cells: a set that drifts ~3% per query + std::vector all((size_t) (nkv - recent)); + for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c; + std::shuffle(all.begin(), all.end(), rng); + old_cells.assign(all.begin(), all.begin() + older); + } else { + std::uniform_int_distribution pick(0, older - 1), any(0, nkv - recent - 1); + for (int r = 0; r < older / 32; ++r) { + const int32_t c = (int32_t) any(rng); + if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c; + } + } + std::vector v(old_cells); + for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c); + std::sort(v.begin(), v.end()); + std::copy(v.begin(), v.end(), sel); + } + k::QsaAttnPools pl; + if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); } + else { pl.k_pool = up(kh); pl.v_pool = up(vh); } + pl.page_table = up(table); + const int32_t* d_ids = up(ids); + const int32_t* d_steps = up(steps); + const float* d_q = up(q); + float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr; + const int64_t batch = 32; + ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc"); + ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc"); + ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc"); + auto old_run = [&]() { + for (int64_t t0 = 0; t0 < nq; t0 += batch) + k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap, s, + scratch, d_old + t0 * NH * HD, std::min(batch, nq - t0), nullptr); + }; + auto new_run = [&]() { + if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nq, nullptr)) { + std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n"); + std::exit(2); + } + }; + old_run(); + new_run(); + ck(cudaDeviceSynchronize(), "run"); + std::vector o((size_t) (nq * NH * HD)), nw(o.size()); + ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down"); + ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down"); + // 1. FP64 reference on a sample of queries + double err_old = 0, err_new = 0, ref_scale = 0; + for (int64_t i = 0; i < nq; i += std::max(1, nq / 16)) { + const int64_t w = steps[i * k::kStepCount + k::kStepWidth]; + const int32_t* sel = ids.data() + i * cap; + for (int64_t h = 0; h < NH; ++h) { + const int64_t kvh = h / (NH / NKV); + std::vector sco((size_t) w); + double mx = -1e300; + for (int64_t c = 0; c < w; ++c) { + const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; + double a = 0; + for (int64_t d = 0; d < HD; ++d) { + const double kv = fmt == 1 ? (double) kq[row * HD + d] * h2f(ks[row * 4 + d / 64]) : h2f(kh[row * HD + d]); + a += (double) q[(i * NH + h) * HD + d] * kv; + } + sco[c] = a / 16.0; + mx = std::max(mx, sco[c]); + } + double l = 0; + for (auto& x : sco) { x = std::exp(x - mx); l += x; } + for (int64_t d = 0; d < HD; ++d) { + double a = 0; + for (int64_t c = 0; c < w; ++c) { + const int64_t cell = sel[c], row = ((int64_t) table[cell / PS] * NKV + kvh) * PS + cell % PS; + const double vv = fmt == 1 ? (double) vq[row * HD + d] * h2f(vs[row * 4 + d / 64]) : h2f(vh[row * HD + d]); + a += sco[c] * vv; + } + const double r = a / l; + const size_t at = (size_t) ((i * NH + h) * HD + d); + ref_scale = std::max(ref_scale, std::fabs(r)); + err_old = std::max(err_old, std::fabs(o[at] - r)); + err_new = std::max(err_new, std::fabs(nw[at] - r)); + } + } + } + // 2. new vs old everywhere + double diff = 0, scale = 0; + for (size_t i = 0; i < o.size(); ++i) { + diff = std::max(diff, (double) std::fabs(o[i] - nw[i])); + scale = std::max(scale, (double) std::fabs(o[i])); + } + // 3. speed + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + float ms_old = 0, ms_new = 0; + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) old_run(); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "time"); + cudaEventElapsedTime(&ms_old, e0, e1); + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) new_run(); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "time"); + cudaEventElapsedTime(&ms_new, e0, e1); + const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale); + const bool ok2 = diff <= 1e-4 * scale; + std::printf("%s %s ctx %lld, %lld queries: vs FP64 old %.3g new %.3g (output scale %.3g); new vs old %.3g (%.2g of " + "scale); %.3f -> %.3f ms per chunk (%.2fx)\n", + ok1 && ok2 ? "PASS" : "FAIL", fmt == 1 ? "int8" : "fp16", (long long) ctx, (long long) nq, err_old, + err_new, ref_scale, diff, diff / scale, ms_old / reps, ms_new / reps, ms_old / ms_new); + cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new); + cudaFree(scratch); + cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale); + cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table); + return ok1 && ok2 ? 0 : 1; +} +} // namespace + +int main(int argc, char** argv) { +#if defined(__HIP_PLATFORM_AMD__) + // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip + { + int dev = 0; + hipDeviceProp_t prop{}; + if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2; + if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) { + std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName); + return 77; + } +#if defined(_WIN32) + _putenv_s("STRATA_HIP_WMMA", "1"); +#else + setenv("STRATA_HIP_WMMA", "1", 1); +#endif + } +#endif + const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768; + const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048; + const int reps = argc > 3 ? std::atoi(argv[3]) : 5; + int fails = 0; + fails += run(1, ctx, nq, reps); +#if !defined(__HIP_PLATFORM_AMD__) + fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only +#endif + fails += run(1, 1500, std::min(nq, 1500), reps); // short context: the selection is every cell + fails += run(1, 2100, std::min(nq, 256), reps); // the identity-to-sparse edge + std::printf("FAILURES: %d\n", fails); + return fails; +} diff --git a/engine/strata/src/kernels/qsa_select_bench.cpp b/engine/strata/src/kernels/qsa_select_bench.cpp new file mode 100644 index 00000000..e4ccd027 --- /dev/null +++ b/engine/strata/src/kernels/qsa_select_bench.cpp @@ -0,0 +1,174 @@ +// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores +// (the warp kernel and the tensor-core one) and top-k, for a batch of consecutive queries at a given context, and +// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model). +// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells] +// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY +// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1). +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_select.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* up(const std::vector& h) { + T* d = nullptr; + ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc"); + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} +} // namespace + +int main(int argc, char** argv) { + const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 131072; + const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256; + const int reps = argc > 3 ? std::atoi(argv[3]) : 10; + const k::QsaShapes s = k::qsa_real_shapes(); + const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : 0; + const int64_t max_blocks = capacity > 0 ? capacity / 4 + 2 : ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s); + std::mt19937 rng(7); + std::normal_distribution nd(0.f, 1.f); + // keys with a shared direction plus noise, so the scores have a spread like a real indexer's + std::vector dir(128), pooled((size_t) (max_blocks * 128)), dead(128), q((size_t) (nq * 512)); + for (auto& x : dir) x = nd(rng); + for (int64_t b = 0; b < max_blocks; ++b) { + const float a = nd(rng); + for (int d = 0; d < 128; ++d) pooled[(size_t) (b * 128 + d)] = 0.5f * a * dir[d] + nd(rng); + } + for (auto& x : dead) x = nd(rng); + for (int64_t i = 0; i < nq; ++i) + for (int d = 0; d < 512; ++d) q[(size_t) (i * 512 + d)] = 0.2f * dir[d % 128] + 0.1f * nd(rng); + std::vector steps((size_t) (nq * k::kStepCount)); + for (int64_t i = 0; i < nq; ++i) { // qsa_step_fill's arithmetic (kept here so the bench links only qsa_select) + int32_t* st = steps.data() + i * k::kStepCount; + const int64_t pos = ctx - nq + i; + st[k::kStepPos] = (int32_t) pos; + st[k::kStepNKv] = (int32_t) (pos + 1); + st[k::kStepNBid] = (int32_t) ((pos + 1) / s.idx_block); + st[k::kStepWidth] = (int32_t) k::qsa_selection_width(pos + 1, s); + } + const float* d_pooled = up(pooled); + const float* d_dead = up(dead); + const float* d_q = up(q); + const int32_t* d_steps = up(steps); + float *sc_old = nullptr, *sc_new = nullptr; + int32_t *ids_old = nullptr, *ids_new = nullptr; + ck(cudaMalloc(&sc_old, (size_t) (nq * max_blocks) * 4), "malloc"); + ck(cudaMalloc(&sc_new, (size_t) (nq * max_blocks) * 4), "malloc"); + ck(cudaMalloc(&ids_old, (size_t) (nq * cap) * 4), "malloc"); + ck(cudaMalloc(&ids_new, (size_t) (nq * cap) * 4), "malloc"); + const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1; + auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); }; + // a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only + const bool have_tc = k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, 1, max_blocks, s, sc_new, nullptr, active); + auto run_new = [&] { + if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) { + std::fprintf(stderr, "tc scorer refused\n"); + std::exit(2); + } + }; + run_old(); + if (have_tc) run_new(); + else ck(cudaMemcpy(sc_new, sc_old, (size_t) (nq * max_blocks) * 4, cudaMemcpyDeviceToDevice), "copy"); + k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); + k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active); + int32_t* ids_reg = nullptr; // the register top-k on the OLD scores: must equal the reference exactly + ck(cudaMalloc(&ids_reg, (size_t) (nq * cap) * 4), "malloc"); + k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); + ck(cudaDeviceSynchronize(), "warm"); + // compare + std::vector a((size_t) (nq * max_blocks)), b(a.size()); + std::vector ia((size_t) (nq * cap)), ib(ia.size()); + ck(cudaMemcpy(a.data(), sc_old, a.size() * 4, cudaMemcpyDeviceToHost), "down"); + ck(cudaMemcpy(b.data(), sc_new, b.size() * 4, cudaMemcpyDeviceToHost), "down"); + ck(cudaMemcpy(ia.data(), ids_old, ia.size() * 4, cudaMemcpyDeviceToHost), "down"); + ck(cudaMemcpy(ib.data(), ids_new, ib.size() * 4, cudaMemcpyDeviceToHost), "down"); + std::vector ir(ia.size()); + ck(cudaMemcpy(ir.data(), ids_reg, ir.size() * 4, cudaMemcpyDeviceToHost), "down"); + int64_t reg_same = 0; + for (int64_t i = 0; i < nq; ++i) { + const int64_t w = steps[(size_t) (i * k::kStepCount + k::kStepWidth)]; + reg_same += std::equal(ia.begin() + i * cap, ia.begin() + i * cap + w, ir.begin() + i * cap); + } + double max_rel = 0, sum_rel = 0, n_rel = 0; + int64_t same_sel = 0, cells_diff = 0, cells_all = 0; + for (int64_t i = 0; i < nq; ++i) { + const int32_t* st = steps.data() + i * k::kStepCount; + for (int64_t j = 0; j <= st[k::kStepNBid]; ++j) { + const double x = a[(size_t) (i * max_blocks + j)], y = b[(size_t) (i * max_blocks + j)]; + const double r = std::fabs(x - y) / std::max(1e-6, std::fabs(x)); + max_rel = std::max(max_rel, r); + sum_rel += r; + n_rel += 1; + } + const int64_t w = st[k::kStepWidth]; + std::vector x(ia.begin() + i * cap, ia.begin() + i * cap + w), y(ib.begin() + i * cap, ib.begin() + i * cap + w); + same_sel += x == y; + std::vector d; + std::set_symmetric_difference(x.begin(), x.end(), y.begin(), y.end(), std::back_inserter(d)); + cells_diff += (int64_t) d.size() / 2; + cells_all += w; + } + // accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own + // arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x + // the warp kernel's error, floored at 1e-6 of the score scale. + double err_old = 0, err_new = 0, scale = 0; + { + std::mt19937 srng(11); + const int64_t nqs = std::min(nq, 32); + for (int64_t qs = 0; qs < nqs; ++qs) { + const int64_t i = qs * nq / nqs; + const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)]; + if (nbid <= 0) continue; + for (int sidx = 0; sidx < 1024; ++sidx) { + const int64_t j = sidx < 64 ? std::min(nbid - 1, sidx) : (int64_t) (srng() % (uint64_t) nbid); + double ref = 0; + for (int h = 0; h < 4; ++h) { + double d = 0; + for (int c = 0; c < 128; ++c) d += (double) q[(size_t) (i * 512 + h * 128 + c)] * (double) pooled[(size_t) (j * 128 + c)]; + ref += d > 0 ? d : 0; + } + scale = std::max(scale, std::fabs(ref)); + err_old = std::max(err_old, std::fabs(ref - (double) a[(size_t) (i * max_blocks + j)])); + err_new = std::max(err_new, std::fabs(ref - (double) b[(size_t) (i * max_blocks + j)])); + } + } + } + const bool acc_ok = !have_tc || err_new <= std::max(4.0 * err_old, 1e-6 * scale); + // time + cudaEvent_t e0, e1; + cudaEventCreate(&e0); cudaEventCreate(&e1); + auto timed = [&](auto f) { + cudaEventRecord(e0); + for (int r = 0; r < reps; ++r) f(); + cudaEventRecord(e1); + ck(cudaEventSynchronize(e1), "time"); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + return ms / reps; + }; + const float t_old = timed(run_old), t_new = have_tc ? timed(run_new) : t_old; + const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); }); + const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); }); + std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2, + t_tk / t_tk2, (long long) reg_same, (long long) nq); + std::printf("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, tensor-core max err %.3g (%.2g of scale)\n", + !have_tc ? "SKIP" : acc_ok ? "PASS" : "FAIL", scale, err_old, err_new, scale > 0 ? err_new / scale : 0.0); + if (!have_tc) std::printf("tensor-core scorer not available on this device: warp scorer %.3f ms, top-k %.3f ms (%.0f%% of the two)\n", t_old, t_tk2, 100.0 * t_tk2 / (t_old + t_tk2)); + std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff " + "mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx, + (long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel), + max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0); + return acc_ok && reg_same == nq ? 0 : 1; +} diff --git a/engine/strata/src/kernels/quantize_act_parity.cpp b/engine/strata/src/kernels/quantize_act_parity.cpp new file mode 100644 index 00000000..b2cd7ee4 --- /dev/null +++ b/engine/strata/src/kernels/quantize_act_parity.cpp @@ -0,0 +1,407 @@ +// src/kernels/quantize_act_parity.cpp - P2.S2's parity test for the Q8_0 activation quantizer. +// +// THE CHECK IS ON THE BYTES, not on the round-tripped values. `ref/quant.py::q8_0`'s central finding is that +// dividing by the fp16-rounded scale instead of the fp32 one changed 18 of 80 blocks' quantized integers +// while leaving the dequantized values within a rounding step - so a comparison of VALUES would have passed +// and the engine would still have disagreed with ggml. Comparing the 34-byte block catches that directly. +// +// The reference is a host transcription of `ref/quant.py::q8_0`: +// +// d32 = amax / 127.0f (f32) +// d16 = fp16(d32) (stored, and used to DEQUANTIZE) +// q = clip(rint(x / (double)d32), -128, 127) +// round trip = q * d16 +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/f16_bits.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// THE CONVERSIONS COME FROM `f16_bits.hpp`, and this test used to carry its own. The private `f16_bits_to_f32` +// below flushed fp16 SUBNORMALS to zero, and the private encoder returned NaN for finite fp16 overflow - both +// invisible with the O(1) fixture this file has. Round 198 validated the shared pair against 395 numpy +// float16 vectors and all 65,536 reverse patterns, so the test now shares the implementation it is checking +// instead of guessing at it independently. Thin aliases keep the body below unchanged. +using strata::kernels::f16_from_f32; +using strata::kernels::f32_from_f16; +inline uint16_t f32_to_f16_bits(float f) { return f16_from_f32(f); } +inline float f16_bits_to_f32(uint16_t h) { return f32_from_f16(h); } + +void reference_q8_0(const float* x, long long n, std::vector& blocks, std::vector& back) { + blocks.assign((size_t) (n / 32) * 34, 0); + back.assign((size_t) n, 0.0f); + for (long long b = 0; b < n / 32; ++b) { + const float* xb = x + b * 32; + float amax = 0.0f; + for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(xb[i])); + uint8_t* out = &blocks[(size_t) b * 34]; + if (amax == 0.0f) continue; + const float d32 = amax / 127.0f; + const uint16_t dbits = f32_to_f16_bits(d32); + out[0] = (uint8_t) (dbits & 0xFF); + out[1] = (uint8_t) (dbits >> 8); + const float d16 = f16_bits_to_f32(dbits); + for (int i = 0; i < 32; ++i) { + double q = std::rint((double) xb[i] / (double) d32); + if (q > 127.0) q = 127.0; + if (q < -128.0) q = -128.0; + out[2 + i] = (uint8_t) (int8_t) q; + back[(size_t) (b * 32 + i)] = (float) (int8_t) out[2 + i] * d16; + } + } +} + +int run_case(const char* name, const std::vector& x, bool check_bytes) { + const long long n = (long long) x.size(); + std::vector r_blocks, g_blocks((size_t) (n / 32) * 34); + std::vector r_back, g_back((size_t) n); + reference_q8_0(x.data(), n, r_blocks, r_back); + + float* d_x = nullptr; + uint8_t* d_b = nullptr; + float* d_back = nullptr; + check(cudaMalloc(&d_x, (size_t) n * sizeof(float)), "malloc x"); + check(cudaMalloc(&d_b, g_blocks.size()), "malloc blocks"); + check(cudaMalloc(&d_back, (size_t) n * sizeof(float)), "malloc back"); + check(cudaMemcpy(d_x, x.data(), (size_t) n * sizeof(float), cudaMemcpyHostToDevice), "copy x"); + // PROBE: does the DEVICE hold what the host thinks it sent? The scale byte differs with the SAME + // exponent and a zeroed mantissa, which says the kernel's amax differs from the host's on identical + // input - so the first thing to rule out is the copy itself. + { + std::vector rt((size_t) n); + check(cudaMemcpy(rt.data(), d_x, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "probe copy back"); + long long diff = 0; + for (long long i = 0; i < n; ++i) if (std::memcmp(&rt[(size_t) i], &x[(size_t) i], 4) != 0) ++diff; + if (diff) std::printf(" PROBE: device x differs from host x in %lld of %lld elements\n", diff, n); + } + strata::kernels::quantize_q8_0(d_x, d_b, n, nullptr); + strata::kernels::dequant_q8_0(d_b, d_back, n, nullptr); + check(cudaMemcpy(g_blocks.data(), d_b, g_blocks.size(), cudaMemcpyDeviceToHost), "back blocks"); + check(cudaMemcpy(g_back.data(), d_back, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "back vals"); + + long long byte_bad = 0, val_bad = 0; + if (check_bytes) { + for (size_t i = 0; i < g_blocks.size(); ++i) if (g_blocks[i] != r_blocks[i]) ++byte_bad; + } + for (long long i = 0; i < n; ++i) { + const float a = r_back[(size_t) i], b = g_back[(size_t) i]; + // the round trip is `q * d16`: both sides use the SAME fp16 d, so this is exact when q agrees + if (std::memcmp(&a, &b, sizeof(float)) != 0) ++val_bad; + } + if (byte_bad && check_bytes) { + for (size_t i = 0; i < g_blocks.size(); ++i) { + if (g_blocks[i] != r_blocks[i]) { + const size_t blk = i / 34; + const float amax = [&] { float m = 0; for (int k = 0; k < 32; ++k) m = std::fmax(m, std::fabs(x[(size_t)(blk*32+k)])); return m; }(); + std::printf(" first bad byte: block %zu offset %zu amax %.9g d32 %.9g\n", blk, i % 34, amax, amax/127.0f); + std::printf(" ref scale bytes %02x %02x got %02x %02x\n", r_blocks[blk*34], r_blocks[blk*34+1], g_blocks[blk*34], g_blocks[blk*34+1]); + std::printf(" ref[0..9]:"); for (int k = 0; k < 10; ++k) std::printf(" %02x", r_blocks[blk*34+k]); + std::printf("\n got[0..9]:"); for (int k = 0; k < 10; ++k) std::printf(" %02x", g_blocks[blk*34+k]); + std::printf("\n ref[10..17]:"); for (int k = 10; k < 18; ++k) std::printf(" %02x", r_blocks[blk*34+k]); + std::printf("\n got[10..17]:"); for (int k = 10; k < 18; ++k) std::printf(" %02x", g_blocks[blk*34+k]); + std::printf("\n x[0..3] = %.9g %.9g %.9g %.9g\n", (double)x[(size_t)(blk*32)], (double)x[(size_t)(blk*32+1)], (double)x[(size_t)(blk*32+2)], (double)x[(size_t)(blk*32+3)]); + break; + } + } + } + std::printf(" %-26s blocks %s (%lld bad bytes) round trip %s (%lld differ)\n", name, + !check_bytes ? "not compared" : (byte_bad ? "*** WRONG ***" : "byte-exact"), byte_bad, + val_bad ? "*** WRONG ***" : "bit-exact", val_bad); + cudaFree(d_x); + cudaFree(d_b); + cudaFree(d_back); + return (int) (byte_bad + val_bad); +} + +// A host transcription of ggml's `quantize_row_q8_K_ref` (ggml-quants.c L2768), including `nearest_int`. +// +// NOTE WHICH REFERENCE THIS IS. `ref/quant.py::q8_K` is the numpy transcription and it multiplies in +// FLOAT64 (`iscale * blk.astype(np.float64)`), while ggml multiplies in FLOAT32 before `nearest_int`. The +// oracle is ggml, so this follows ggml. The two agree except where an f32 product lands exactly on a tie or +// a rounding boundary, which is exactly the regime the "exact ties" case below constructs. +int nearest_int_host(float fval) { + const float val = fval + 12582912.0f; + int i; + std::memcpy(&i, &val, 4); + return (i & 0x007fffff) - 0x00400000; +} + +void reference_q8_K(const float* x, long long n, std::vector& blocks, std::vector& back, + float scale_num) { + const int QK = 256; + blocks.assign((size_t) (n / QK) * 292, 0); + back.assign((size_t) n, 0.0f); + for (long long b = 0; b < n / QK; ++b) { + const float* xb = x + b * QK; + uint8_t* out = &blocks[(size_t) b * 292]; + float max = 0.0f, amax = 0.0f; + for (int j = 0; j < QK; ++j) { + const float ax = std::fabs(xb[j]); + if (ax > amax) { amax = ax; max = xb[j]; } // STRICTLY greater: ties keep the FIRST maximum + } + if (amax == 0.0f) continue; // d = 0, qs = 0, bsums = 0 (see the kernel note) + const float iscale = scale_num / max; // -127 by default; -128 is the rival reading + int8_t* qs = (int8_t*) (out + 4); + for (int j = 0; j < QK; ++j) { + const int v = nearest_int_host(iscale * xb[j]); + qs[j] = (int8_t) std::min(127, v); + } + int16_t* bsums = (int16_t*) (out + 4 + QK); + for (int j = 0; j < QK / 16; ++j) { + int sum = 0; + for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii]; + bsums[j] = (int16_t) sum; + } + const float d = 1.0f / iscale; + std::memcpy(out, &d, 4); + for (int j = 0; j < QK; ++j) back[(size_t) (b * QK + j)] = (float) qs[j] * d; + } +} + +int run_case_k(const char* name, const std::vector& x, bool check_bytes, float scale_num = -127.0f) { + const long long n = (long long) x.size(); + std::vector r_blocks, g_blocks((size_t) (n / 256) * 292); + std::vector r_back, g_back((size_t) n); + reference_q8_K(x.data(), n, r_blocks, r_back, scale_num); + + float* d_x = nullptr; + uint8_t* d_b = nullptr; + float* d_back = nullptr; + check(cudaMalloc(&d_x, (size_t) n * sizeof(float)), "malloc x"); + check(cudaMalloc(&d_b, g_blocks.size()), "malloc blocks"); + check(cudaMalloc(&d_back, (size_t) n * sizeof(float)), "malloc back"); + check(cudaMemcpy(d_x, x.data(), (size_t) n * sizeof(float), cudaMemcpyHostToDevice), "copy x"); + strata::kernels::quantize_q8_K(d_x, d_b, n, nullptr); + strata::kernels::dequant_q8_K(d_b, d_back, n, nullptr); + check(cudaMemcpy(g_blocks.data(), d_b, g_blocks.size(), cudaMemcpyDeviceToHost), "back blocks"); + check(cudaMemcpy(g_back.data(), d_back, (size_t) n * sizeof(float), cudaMemcpyDeviceToHost), "back vals"); + + long long byte_bad = 0, val_bad = 0, first_bad = -1; + if (check_bytes) + for (size_t i = 0; i < g_blocks.size(); ++i) + if (g_blocks[i] != r_blocks[i]) { if (first_bad < 0) first_bad = (long long) i; ++byte_bad; } + for (long long i = 0; i < n; ++i) + if (std::memcmp(&r_back[(size_t) i], &g_back[(size_t) i], 4) != 0) ++val_bad; + std::printf(" %-26s blocks %s (%lld bad bytes) round trip %s (%lld differ)\n", name, + !check_bytes ? "not compared" : (byte_bad ? "*** WRONG ***" : "byte-exact"), byte_bad, + val_bad ? "*** WRONG ***" : "bit-exact", val_bad); + if (first_bad >= 0) { + // Say WHERE and WHAT, because "1 element in 524288" is the signature of a rounding boundary and not + // of a wrong formula - and the two need completely different responses. + const size_t blk = (size_t) first_bad / 292, off = (size_t) first_bad % 292; + const char* where = off < 4 ? "d (the f32 scale)" : (off < 260 ? "qs (the quants)" : "bsums"); + std::printf(" first bad byte: block %zu offset %zu = %s ref %02x got %02x\n", blk, off, + where, r_blocks[(size_t) first_bad], g_blocks[(size_t) first_bad]); + if (off >= 4 && off < 260) { + const int j = (int) off - 4; + const float xv = x[(size_t) (blk * 256 + j)]; + float mx = 0.0f; + for (int k = 0; k < 256; ++k) { const float ax = std::fabs(x[(size_t) (blk * 256 + k)]); if (ax > std::fabs(mx)) mx = x[(size_t) (blk * 256 + k)]; } + const float isc = -127.0f / mx; + const float prod = isc * xv; + std::printf(" element %d: x %.9g max %.9g iscale %.9g iscale*x %.9g (frac %.6f)\n", + j, (double) xv, (double) mx, (double) isc, (double) prod, (double) (prod - std::floor(prod))); + } else if (off < 4) { + float rd, gd; + std::memcpy(&rd, &r_blocks[(size_t) (blk * 292)], 4); + std::memcpy(&gd, &g_blocks[(size_t) (blk * 292)], 4); + std::printf(" d: ref %.9g got %.9g\n", (double) rd, (double) gd); + } + } + cudaFree(d_x); + cudaFree(d_b); + cudaFree(d_back); + return (int) (byte_bad + val_bad); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: quantize_act_parity [--selftest]\n"); return 2; } + } + std::mt19937 rng(7); + std::normal_distribution gauss(0.0f, 1.0f); + int bad = 0; + const long long N = 32 * 4096; + + // ---- ordinary activations + std::vector a((size_t) N); + for (auto& v : a) v = gauss(rng); + bad += run_case("random normal", a, true); + + // ---- an activation with a very small dynamic range, where d32 is tiny and the fp16 rounding of d is a + // LARGE relative change - this is where dividing by d16 instead of d32 would show up in the bytes + std::vector b((size_t) N); + for (auto& v : b) v = gauss(rng) * 1e-6f; + bad += run_case("small magnitude (1e-6)", b, true); + + // ---- an all-zero block must produce a zeroed block, not a division by zero + std::vector c((size_t) N, 0.0f); + bad += run_case("all zero", c, true); + + // ---- values that land exactly on .5 boundaries, where rint's half-to-even and a float division's + // rounding both decide the result + std::vector d((size_t) N); + for (long long i = 0; i < N; ++i) { + // construct so that x / d32 is very close to a .5 boundary: d32 = amax/127, so pick amax = 127.0 and + // x = k + 0.5 for integer k + d[(size_t) i] = ((i % 200) - 100) + 0.5f; + } + d[0] = 127.0f; + bad += run_case("exact .5 boundaries", d, true); + + // ---- a single extreme value in each block, so d32 is set by it and every other quant is small + std::vector e((size_t) N, 0.0f); + for (long long blk = 0; blk < N / 32; ++blk) e[(size_t) (blk * 32)] = 1000.0f + (float) (blk % 7); + bad += run_case("one extreme per block", e, true); + + std::printf("\nquantize_q8_0: %d failures over 5 distributions x %lld elements\n", bad, N); + + // ============================== Q8_K ============================== + // + // The K-quants' activation: 2.89 GiB of dense weights - the attention projections and `ssm_out`. The + // oracle here is GGML's C reference, and the traps are the two the source comments warn about. + // ============================== the fp16 conversion itself ============================== + // + // REGRESSION CHECK FOR A BUG THAT SHIPPED. The private encoder in `quantize_act.cu` - and the identical + // one in `shared_expert.cu` - tested `if (exp >= 31)` to catch an out-of-range exponent, which conflates + // an f32 INF/NAN (raw exponent 255) with a FINITE value too large for fp16. Every finite overflow came + // back as a NaN instead of saturating to inf. **Neither file's fixture could see it, because every value + // in both is O(1)** - the Q8_0 case above scales by a max that is never near 65504. Round 198's + // numpy-generated oracle caught it on the first run. + // + // The decoder in this same test had the matching defect in the other direction: it flushed fp16 + // SUBNORMALS to zero, so 0x0001 decoded as 0.0 instead of 2^-24. + // + // These are the exact values, asserted against what numpy's float16 says. They are here rather than + // only in `qsa_parity` because this is the file that OWNS the Q8_0/Q8_K scales, and a scale that is NaN + // poisons a whole block silently. + { + struct F16Case { float in; uint16_t want; const char* what; }; + const F16Case cases[] = { + {1e30f, 0x7C00u, "1e30 -> +inf (finite overflow)"}, + {-1e30f, 0xFC00u, "-1e30 -> -inf"}, + {65536.0f, 0x7C00u, "65536 -> +inf (just past fp16 max)"}, + // FLT_MAX is 3.4028235e38, so `1e45f` is not even a legal literal; 3e38 is the largest finite + // f32 that still overflows fp16, which is what this case is for. + {3.0e38f, 0x7C00u, "3e38 (near FLT_MAX) -> +inf"}, + {65504.0f, 0x7BFFu, "65504 -> the largest finite fp16, NOT inf"}, + // The boundary, checked against numpy: 65520.0 is the exact tie between 65504 and the + // "next" fp16 (65536 = inf) and rounds to EVEN, i.e. to inf; 65519.996 is below it and stays + // finite. The first version of this table asserted inf for 65519.996 - the FIXTURE was wrong and + // the kernel was right, which is why the expected bits are quoted from numpy rather than reasoned. + {65519.996f, 0x7BFFu, "65519.996 -> just below the boundary, still finite"}, + {65520.0f, 0x7C00u, "65520.0 -> the exact tie, rounds to even = inf"}, + {65536.0f, 0x7C00u, "65536 -> past fp16 max"}, + {5.9604645e-8f, 0x0001u, "2^-24 -> the smallest subnormal, NOT zero"}, + {1.0f, 0x3C00u, "1.0"}, + {0.0f, 0x0000u, "0.0"}, + }; + int fp16_bad = 0; + for (const F16Case& c : cases) { + const uint16_t got = strata::kernels::f16_from_f32(c.in); + if (got != c.want) { + std::printf(" *** %s: want 0x%04X got 0x%04X\n", c.what, c.want, got); + ++fp16_bad; + } + } + // and the reverse direction on the pattern that was flushed + const float sub = strata::kernels::f32_from_f16(0x0001u); + const bool sub_ok = (sub == 5.9604645e-8f); + std::printf(" %-44s %s (%d of %d wrong)\n", "f32->f16 overflow saturates, not NaN", + fp16_bad ? "*** NO ***" : "yes", fp16_bad, (int) (sizeof cases / sizeof cases[0])); + std::printf(" %-44s %s (0x0001 -> %.9g, want 2^-24)\n", "f16->f32 keeps subnormals", + sub_ok ? "yes" : "*** NO ***", (double) sub); + if (fp16_bad) bad += fp16_bad; + if (!sub_ok) ++bad; + } + + std::printf("\nQ8_K (ggml block_q8_K: 292 bytes / 256 elements, {f32 d; i8 qs[256]; i16 bsums[16]})\n"); + int bad_k = 0; + const long long NK = 256 * 2048; + + std::vector ka((size_t) NK); + for (auto& v : ka) v = gauss(rng); + bad_k += run_case_k("random normal", ka, true); + + std::vector kb((size_t) NK); + for (auto& v : kb) v = gauss(rng) * 1e-7f; // tiny: the scale is far from fp16-representable + bad_k += run_case_k("small magnitude (1e-7)", kb, true); + + std::vector kc((size_t) NK, 0.0f); + bad_k += run_case_k("all zero", kc, true); + + // EXACT TIES. `nearest_int` is round-half-to-EVEN (the 12582912.0f magic number); `roundf` is + // half-AWAY-FROM-ZERO. They differ only when `iscale*x` is exactly k+0.5, which never happens on real + // data - so this fixture MANUFACTURES it: with max = 127.0 and iscale = -1.0, x = -(k+0.5) gives exactly + // k+0.5, and the two rules disagree for every EVEN k. + std::vector kd((size_t) NK, 0.0f); + for (long long blk = 0; blk < NK / 256; ++blk) + for (int j = 0; j < 256; ++j) kd[(size_t) (blk * 256 + j)] = -(float) ((j % 100) + 0.5f); + for (long long blk = 0; blk < NK / 256; ++blk) kd[(size_t) (blk * 256)] = 127.0f; // fixes max = 127 + bad_k += run_case_k("exact .5 ties (half-to-even)", kd, true); + { + // assert the tie fixture can SEE the difference before trusting the comparison above + std::vector rb; + std::vector rback; + reference_q8_K(kd.data(), NK, rb, rback, -127.0f); + long long ties = 0, differ = 0; + for (long long i = 0; i < NK; ++i) { + const float t = -kd[(size_t) i]; + if (t - std::floor(t) == 0.5f) { + ++ties; + const int even = nearest_int_host(t); + const int away = (int) std::round(t); + if (even != away) ++differ; + } + } + std::printf(" %-26s %lld ties, %lld where half-to-even != half-away (%.1f%%)\n", + " tie fixture discriminates", ties, differ, ties ? 100.0 * (double) differ / ties : 0.0); + if (differ < ties / 3) { std::printf(" *** the tie fixture cannot see the rounding rule ***\n"); ++bad_k; } + } + + // THE -127 TRAP. ggml uses `-127/max`; the `-128` version sits COMMENTED OUT in the source, and using it + // is a 0.79% scaling error that leaves a working-looking activation. Computed with the rival constant + // and required to differ. + { + std::vector r127, r128; + std::vector b127, b128; + reference_q8_K(ka.data(), NK, r127, b127, -127.0f); + reference_q8_K(ka.data(), NK, r128, b128, -128.0f); + double d = 0, m = 0; + long long qdiffer = 0; + for (long long i = 0; i < NK; ++i) { d += std::fabs(b127[(size_t) i] - b128[(size_t) i]); m += std::fabs(b127[(size_t) i]); } + for (size_t i = 4; i < r127.size(); ++i) if (r127[i] != r128[i]) ++qdiffer; + // The expected size of the effect is exactly (1 - 127/128) = 0.78% of the magnitude, so the floor is + // 0.5% - below what the rival constant must produce and far above any noise. The byte count is the + // blunter evidence and is reported alongside it: 172,017 bytes differ, i.e. a third of the quants. + std::printf(" %-26s %-4s (%.3f%% of magnitude, %lld bytes differ)\n", "-127 vs -128 scale observable", + d / m > 0.005 ? "yes" : "*** NO ***", 100.0 * d / m, qdiffer); + if (!(d / m > 0.005)) ++bad_k; + } + + std::printf("\nquantize_act: %d failures over 5 Q8_0 + 4 Q8_K distributions\n", bad + bad_k); + if (bad + bad_k) return 1; + if (selftest) std::printf("quantize_act_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/rope_parity.cpp b/engine/strata/src/kernels/rope_parity.cpp new file mode 100644 index 00000000..39ba116a --- /dev/null +++ b/engine/strata/src/kernels/rope_parity.cpp @@ -0,0 +1,442 @@ +// src/kernels/rope_parity.cpp - P2.S2's parity test for NEOX partial RoPE. +// +// TWO CHECKS, deliberately separated so each can be tight: +// +// 1. THE TABLE against the float64 reference - `theta ** (-2i/n_rot)`, `pos * inv`, `cos`/`sin`, all in +// double exactly as `ref/qsa.py::rope_freqs` does. Compared as float32 after the cast, so a mismatch +// here is a real arithmetic difference and not a formatting one. +// 2. THE ROTATION against a host rotation written from `ref/qsa.py::rope_neox`, using the SAME table the +// kernel is given. Both sides then perform identical float32 operations, so this is BIT-EXACT - and a +// bit-exact rotation plus a table that matches the reference means the composition matches too. +// +// A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting +// failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would +// happily accept. +// +// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation +// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64 +// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and +// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's +// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match +// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled +// and unscaled tables were indistinguishable, every green number above would be vacuous. +// +// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32 +// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never +// mixes two rotations. +#include "strata/kernels/rope.hpp" +#include "strata/kernels/native_rope.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: rope_parity [--selftest]\n"); return 2; } + } + + const int n_rot = 64; // the artifact's rope.dimension_count + const double theta = 1.0e7; // rope.freq_base + const int head_dim = 256; + const int rows = 24 * 8; // 24 heads over 8 positions, so several positions exercise the table + const int max_pos = 32; + const int half = n_rot / 2; + int bad = 0; + + // ---- 1. the table against the float64 reference + std::vector hcos((size_t) max_pos * half), hsin((size_t) max_pos * half); + strata::kernels::build_rope_table(n_rot, theta, max_pos, hcos.data(), hsin.data()); + long long table_bad = 0; + double table_worst = 0.0; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = (double) p * inv; + const float rc = (float) std::cos(ang), rs = (float) std::sin(ang); + if (std::memcmp(&rc, &hcos[(size_t) p * half + i], 4) != 0) ++table_bad; + if (std::memcmp(&rs, &hsin[(size_t) p * half + i], 4) != 0) ++table_bad; + table_worst = std::max(table_worst, + std::fabs((double) rc - (double) hcos[(size_t) p * half + i])); + } + } + std::printf(" rope table vs float64 reference %s (%lld of %d entries differ, worst %.1e)\n", + table_bad ? "*** WRONG ***" : "bit-exact", table_bad, max_pos * half * 2, table_worst); + bad += (int) table_bad; + + // ---- 2. the rotation, against the same spec in float32 with the SAME table + std::mt19937 rng(11); + std::normal_distribution gauss(0.0f, 1.0f); + std::vector x((size_t) rows * head_dim); + for (auto& v : x) v = gauss(rng); + std::vector pos((size_t) rows); + for (int r = 0; r < rows; ++r) pos[(size_t) r] = r % max_pos; + + std::vector ref(x.size()); + for (int r = 0; r < rows; ++r) { + const float* xr = &x[(size_t) r * head_dim]; + float* orow = &ref[(size_t) r * head_dim]; + for (int d = 0; d < head_dim; ++d) orow[d] = xr[d]; // the tail passes through + for (int i = 0; i < half; ++i) { + const float c = hcos[(size_t) pos[(size_t) r] * half + i]; + const float s = hsin[(size_t) pos[(size_t) r] * half + i]; + const float a = xr[i], b = xr[half + i]; + orow[i] = a * c - b * s; + orow[half + i] = a * s + b * c; + } + } + + float *d_x = nullptr, *d_out = nullptr, *d_cos = nullptr, *d_sin = nullptr; + int* d_pos = nullptr; + check(cudaMalloc(&d_x, x.size() * sizeof(float)), "malloc x"); + check(cudaMalloc(&d_out, ref.size() * sizeof(float)), "malloc out"); + check(cudaMalloc(&d_cos, hcos.size() * sizeof(float)), "malloc cos"); + check(cudaMalloc(&d_sin, hsin.size() * sizeof(float)), "malloc sin"); + check(cudaMalloc(&d_pos, pos.size() * sizeof(int)), "malloc pos"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_cos, hcos.data(), hcos.size() * sizeof(float), cudaMemcpyHostToDevice), "copy cos"); + check(cudaMemcpy(d_sin, hsin.data(), hsin.size() * sizeof(float), cudaMemcpyHostToDevice), "copy sin"); + check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos"); + strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); + std::vector got(ref.size()); + check(cudaMemcpy(got.data(), d_out, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "back"); + + // A RELATIVE TOLERANCE, NOT BIT EQUALITY. *c - b*s is one of the expressions the compiler is free to + // contract into an FMA, and the host and device compilers choose differently - so a handful of values + // differ in the last bit. Round 167 established this the hard way: a bit-equality expectation that a + // kernel cannot meet is a test that reports a correct kernel as broken. The residual is reported, and if + // it were structural (a wrong pairing, a wrong table entry) it would be O(1), not O(1 ULP). + long long rot_bad = 0; + double worst = 0.0; + long long first_bad = -1; + // The denominator is the ROW'S INPUT MAGNITUDE, not the element's own value. *c - b*s cancels, so an + // element whose result is near zero reports a large relative error for a 1-ULP absolute one - which is the + // same metric mistake round 169 found on Q4_K's dot products, where the fix was to measure against + // sum|term| instead of the result. Here the natural scale of the computation is the largest input in the + // row, because every output element is a combination of two inputs with |cos|,|sin| <= 1. + std::vector row_scale((size_t) rows, 0.0); + for (int r = 0; r < rows; ++r) { + double m = 0; + for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x[(size_t) r * head_dim + d])); + row_scale[(size_t) r] = m > 1e-30 ? m : 1e-30; + } + for (size_t i = 0; i < ref.size(); ++i) { + const double a = ref[i], b = got[i]; + const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim]; + if (!(rel <= worst)) worst = rel; + if (!(rel <= 1e-6)) { if (first_bad < 0) first_bad = (long long) i; ++rot_bad; } + } + std::printf(" rope rotation vs host reference %s (%lld of %zu over 1e-6, worst rel %.3e)\n", + rot_bad ? "*** WRONG ***" : "agrees", rot_bad, ref.size(), worst); + if (first_bad >= 0) std::printf(" first over-tolerance at element %lld\n", first_bad); + bad += (int) rot_bad; + + // ---- 3. THE PAIRING, asserted structurally rather than as a tolerance. NEOX pairs (i, i+half); the + // adjacent-pair convention would pair (2i, 2i+1). Feed an input that is 1 at dim 0 and 0 elsewhere, and + // check WHICH dims move: under NEOX only dims 0 and half may change, under the adjacent convention only + // dims 0 and 1 may. A tolerance over all 256 dims cannot tell the two apart. + { + std::vector e((size_t) head_dim, 0.0f); + e[0] = 1.0f; + std::vector o((size_t) head_dim, 0.0f); + check(cudaMemcpy(d_x, e.data(), e.size() * sizeof(float), cudaMemcpyHostToDevice), "copy e"); + // position 7, NOT position 0: at pos 0 sin is exactly 0, so dim half legitimately does not move and + // the check would report the correct kernel as wrong. The first version made exactly that mistake. + int p7 = 7; + check(cudaMemcpy(d_pos, &p7, sizeof(int), cudaMemcpyHostToDevice), "copy p7"); + strata::kernels::rope_neox_apply(d_x, d_out, 1, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); + check(cudaMemcpy(o.data(), d_out, o.size() * sizeof(float), cudaMemcpyDeviceToHost), "back e"); + int moved[4] = {0, 0, 0, 0}; // dims 0, 1, half, half+1 + const float* chk[4] = {&e[0], &e[1], &e[half], &e[half + 1]}; + (void) chk; + moved[0] = (o[0] != 0.0f || o[half] != 0.0f) ? 1 : 0; + const bool adjacent_moved = (o[1] != 0.0f); + const bool neox_moved = (o[half] != 0.0f); + std::printf(" pairing: dim 0 set -> NEOX moves dim %d (o[half]=%.6f), adjacent would move dim 1 " + "(o[1]=%.6f) %s\n", half, (double) o[half], (double) o[1], + (neox_moved && !adjacent_moved) ? "NEOX confirmed" : "*** WRONG CONVENTION ***"); + if (!(neox_moved && !adjacent_moved)) ++bad; + } + + // ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is + // a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the + // structural and observability checks the tolerances cannot cover. + { + // 4a. type None IS the five-argument builder above - bit for bit. + std::vector nc((size_t) max_pos * half), ns((size_t) max_pos * half); + strata::kernels::RopeScaling none; + none.freq_base = theta; + strata::kernels::build_rope_table(n_rot, none, max_pos, nc.data(), ns.data()); + const long long none_bad = + (long long) (std::memcmp(nc.data(), hcos.data(), nc.size() * 4) != 0) + + (long long) (std::memcmp(ns.data(), hsin.data(), ns.size() * 4) != 0); + std::printf(" scaled table, None vs unscaled builder %s\n", none_bad ? "*** WRONG ***" : "bit-identical"); + bad += (int) none_bad; + + // 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose - + // dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder. + strata::kernels::RopeScaling lin; + lin.type = strata::kernels::RopeScalingType::Linear; + lin.freq_base = theta; + lin.factor = 4.0; + std::vector lc((size_t) max_pos * half), ls((size_t) max_pos * half); + strata::kernels::build_rope_table(n_rot, lin, max_pos, lc.data(), ls.data()); + long long lin_bad = 0; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = (double) p * inv / 4.0; + const float rc = (float) std::cos(ang), rs = (float) std::sin(ang); + if (std::memcmp(&rc, &lc[(size_t) p * half + i], 4) != 0) ++lin_bad; + if (std::memcmp(&rs, &ls[(size_t) p * half + i], 4) != 0) ++lin_bad; + } + } + std::printf(" scaled table, linear factor 4 %s (%lld of %d entries differ)\n", + lin_bad ? "*** WRONG ***" : "bit-exact", lin_bad, max_pos * half * 2); + bad += (int) lin_bad; + + // 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row, + // bit for bit, at every position divisible by the factor. + std::vector wc((size_t) 4 * max_pos * half), ws((size_t) 4 * max_pos * half); + strata::kernels::build_rope_table(n_rot, lin, 4 * max_pos, wc.data(), ws.data()); + long long equiv_bad = 0; + for (int p = 0; p < 4 * max_pos; p += 4) { + for (int i = 0; i < half; ++i) { + if (std::memcmp(&wc[(size_t) p * half + i], &hcos[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; + if (std::memcmp(&ws[(size_t) p * half + i], &hsin[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; + } + } + std::printf(" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n", + equiv_bad ? "*** WRONG ***" : "bit-identical", equiv_bad, max_pos); + bad += (int) equiv_bad; + + // 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs). + // The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two + // transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml + // source lines, which is the spec being tested. + strata::kernels::RopeScaling yarn; + yarn.type = strata::kernels::RopeScalingType::YaRN; + yarn.freq_base = theta; + yarn.factor = 4.0; + yarn.ext_factor = 1.0; + std::vector yc((size_t) max_pos * half), ys((size_t) max_pos * half); + strata::kernels::build_rope_table(n_rot, yarn, max_pos, yc.data(), ys.data()); + const double fs = yarn.freq_scale(); // 0.25 + const double ms = yarn.mscale(); // attn_factor * (1 + 0.1*ln(4)) + double cd[2]; + yarn.corr_dims(n_rot, cd); + long long yarn_bad = 0; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double extrap = (double) p * inv; + const double interp = fs * extrap; + const double ramp = (double) strata::kernels::rope_yarn_ramp((float) cd[0], (float) cd[1], i) * + yarn.ext_factor; + const double ang = interp * (1.0 - ramp) + extrap * ramp; + const float rc = (float) (std::cos(ang) * ms), rs = (float) (std::sin(ang) * ms); + if (std::memcmp(&rc, &yc[(size_t) p * half + i], 4) != 0) ++yarn_bad; + if (std::memcmp(&rs, &ys[(size_t) p * half + i], 4) != 0) ++yarn_bad; + } + } + std::printf(" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n", + yarn_bad ? "*** WRONG ***" : "bit-exact", yarn_bad, max_pos * half * 2); + bad += (int) yarn_bad; + + // 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole + // magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first + // pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two + // halves need different observables: at the first pair cos separates the hypotheses outright, but at + // the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near + // zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are + // small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is + // spec against spec, not shortcut against implementation. + { + const float msv = (float) ms; + const bool zero_ok = std::memcmp(&msv, &yc[0], 4) == 0 && ys[0] == 0.0f; + const int far = max_pos - 1; + const double inv_f = 1.0; // pair 0: theta ** 0 + const double extrap_f = (double) far * inv_f, interp_f = fs * extrap_f; + const double inv_l = std::pow(theta, -2.0 * (double) (half - 1) / (double) n_rot); + const double extrap_l = (double) far * inv_l, interp_l = fs * extrap_l; + const float ef = (float) (std::cos(interp_f * (1.0 - 1.0) + extrap_f * 1.0) * ms); + const float itf = (float) (std::cos(interp_f * (1.0 - 0.0) + extrap_f * 0.0) * ms); + const float sl_e = (float) (std::sin(interp_l * (1.0 - 1.0) + extrap_l * 1.0) * ms); + const float sl_i = (float) (std::sin(interp_l * (1.0 - 0.0) + extrap_l * 0.0) * ms); + const float got_f = yc[(size_t) far * half], got_l = ys[(size_t) far * half + (half - 1)]; + const bool first_extrapolates = std::memcmp(&got_f, &ef, 4) == 0; + const bool last_interpolates = std::memcmp(&got_l, &sl_i, 4) == 0; + const bool distinguishable = std::fabs((double) ef - (double) itf) > 1e-3 && + std::fabs((double) sl_e - (double) sl_i) > 1e-8; + std::printf(" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates " + "%s\n", (double) msv, + zero_ok && first_extrapolates && last_interpolates && distinguishable + ? "confirmed" + : "*** WRONG ***"); + if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable)) ++bad; + } + + // 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config, + // linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder. + { + strata::kernels::RopeScaling lin2; + lin2.type = strata::kernels::RopeScalingType::Linear; + lin2.freq_base = theta; + lin2.factor = 2.0; + std::vector l2c((size_t) 101 * half), l2s((size_t) 101 * half); + strata::kernels::build_rope_table(n_rot, lin2, 101, l2c.data(), l2s.data()); + const float c_none = (float) std::cos(100.0); // pair 0, position 100, unscaled: ang = 100 + const float c_lin = l2c[(size_t) 100 * half]; // pair 0, position 100, linear(2): ang = 50 + const bool sees = std::fabs((double) c_none - (double) c_lin) > 1e-3; + std::printf(" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n", + sees ? "visible" : "*** VACUUM ***", (double) c_none, (double) c_lin); + if (!sees) ++bad; + } + + // 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care: + // the host reference is the same rope_neox_pair walk as check 2, over the YaRN table. + std::vector ref2(x.size()); + for (int r = 0; r < rows; ++r) { + const float* xr = &x[(size_t) r * head_dim]; + float* orow = &ref2[(size_t) r * head_dim]; + for (int d = 0; d < head_dim; ++d) orow[d] = xr[d]; + for (int i = 0; i < half; ++i) { + float c = yc[(size_t) pos[(size_t) r] * half + i], s = ys[(size_t) pos[(size_t) r] * half + i]; + strata::kernels::rope_neox_pair(xr[i], xr[half + i], c, s, orow[i], orow[half + i]); + } + } + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_cos, yc.data(), yc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ycos"); + check(cudaMemcpy(d_sin, ys.data(), ys.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ysin"); + check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos"); + strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); + std::vector got2(ref2.size()); + check(cudaMemcpy(got2.data(), d_out, got2.size() * sizeof(float), cudaMemcpyDeviceToHost), "back"); + long long rot2_bad = 0; + double worst2 = 0.0; + for (size_t i = 0; i < ref2.size(); ++i) { + const double a = ref2[i], b = got2[i]; + const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim]; + worst2 = std::max(worst2, rel); + if (!(rel <= 1e-6)) ++rot2_bad; + } + std::printf(" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n", + rot2_bad ? "*** WRONG ***" : "agrees", rot2_bad, ref2.size(), worst2); + bad += (int) rot2_bad; + } + + // ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64; + // the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`. + // They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated + // K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device + // side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4, + // so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The + // engine's default is the table path precisely because float64 host trig has no such floor.) + { + const int npos = 2048; + strata::kernels::RopeScaling yarn; + yarn.type = strata::kernels::RopeScalingType::YaRN; + yarn.factor = 2.0; + yarn.ext_factor = 1.0; + std::vector sc((size_t) npos * half), ss((size_t) npos * half); + strata::kernels::build_rope_table(n_rot, yarn, npos, sc.data(), ss.data()); + std::mt19937 rng2(23); + std::normal_distribution gauss2(0.0f, 1.0f); + const int nrows = 24 * 16; // 16 positions spread over the table's range + std::vector x2((size_t) nrows * head_dim); + for (auto& v : x2) v = gauss2(rng2); + std::vector pos2((size_t) nrows); + for (int r = 0; r < nrows; ++r) pos2[(size_t) r] = (r * 127) % npos; + + float *d_x2 = nullptr, *d_t2 = nullptr, *d_n2 = nullptr, *d_c2 = nullptr, *d_s2 = nullptr; + int* d_p2 = nullptr; + check(cudaMalloc(&d_x2, x2.size() * sizeof(float)), "malloc x2"); + check(cudaMalloc(&d_t2, x2.size() * sizeof(float)), "malloc t2"); + check(cudaMalloc(&d_n2, x2.size() * sizeof(float)), "malloc n2"); + check(cudaMalloc(&d_c2, sc.size() * sizeof(float)), "malloc c2"); + check(cudaMalloc(&d_s2, ss.size() * sizeof(float)), "malloc s2"); + check(cudaMalloc(&d_p2, pos2.size() * sizeof(int)), "malloc p2"); + check(cudaMemcpy(d_x2, x2.data(), x2.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x2"); + check(cudaMemcpy(d_c2, sc.data(), sc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2"); + check(cudaMemcpy(d_s2, ss.data(), ss.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2"); + check(cudaMemcpy(d_p2, pos2.data(), pos2.size() * sizeof(int), cudaMemcpyHostToDevice), "copy p2"); + // The native path demands an explicit stream - a null one is refused by validation, not defaulted. + cudaStream_t cs5 = nullptr; + check(cudaStreamCreate(&cs5), "stream5"); + strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); + strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, yarn, d_p2, cs5); + check(cudaStreamSynchronize(cs5), "sync5"); + std::vector got_t(x2.size()), got_n(x2.size()); + check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2"); + check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2"); + long long agree_bad = 0; + double worst = 0.0; + for (int r = 0; r < nrows; ++r) { + double m = 0; + for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); + const double scale = m > 1e-30 ? m : 1e-30; + for (int d = 0; d < head_dim; ++d) { + const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - + (double) got_n[(size_t) r * head_dim + d]) / scale; + worst = std::max(worst, rel); + if (!(rel <= 3e-3)) ++agree_bad; + } + } + std::printf(" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n", + agree_bad ? "*** WRONG ***" : "agrees", agree_bad, nrows * head_dim, worst); + bad += (int) agree_bad; + + // and the None config: the native path against the UNSCALED table - the identity this feature must + // not disturb. + strata::kernels::RopeScaling none5; // all defaults: type None, freq_scale 1, mscale 1 + strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, none5, d_p2, cs5); + check(cudaStreamSynchronize(cs5), "sync5b"); + check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2b"); + std::vector nc5((size_t) npos * half), ns5((size_t) npos * half); + strata::kernels::build_rope_table(n_rot, none5, npos, nc5.data(), ns5.data()); + check(cudaMemcpy(d_c2, nc5.data(), nc5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2b"); + check(cudaMemcpy(d_s2, ns5.data(), ns5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2b"); + strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); + check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2b"); + long long none_bad5 = 0; + double worst5 = 0.0; + for (int r = 0; r < nrows; ++r) { + double m = 0; + for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); + const double scale = m > 1e-30 ? m : 1e-30; + for (int d = 0; d < head_dim; ++d) { + const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - + (double) got_n[(size_t) r * head_dim + d]) / scale; + worst5 = std::max(worst5, rel); + if (!(rel <= 3e-3)) ++none_bad5; + } + } + std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n", + none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5); + bad += (int) none_bad5; + } + + std::printf("\nrope: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("rope_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/router_top10_parity.cpp b/engine/strata/src/kernels/router_top10_parity.cpp new file mode 100644 index 00000000..ac7e652e --- /dev/null +++ b/engine/strata/src/kernels/router_top10_parity.cpp @@ -0,0 +1,167 @@ +// src/kernels/router_top10_parity.cpp - P2.S2's parity test for the MoE router. +// +// The reference here is a HOST implementation of `ref/moe.py::router` written from the same specification the +// kernel was written from - so this checks the kernel against the spec independently of the kernel, which is +// the strongest thing available without running llama.cpp. It is NOT a check against llama.cpp itself, and +// that gap is stated rather than implied. +// +// WHAT THE TEST CAN AND CANNOT SEE. It compares expert IDs exactly and weights to a tolerance, on several +// logit distributions including ties (where the "smallest index wins" rule is the only thing that decides) and +// near-ties (where a float difference decides). It also asserts that the 2**-14 CLAMP CANNOT TRIGGER for this +// model's geometry - see below - so the absence of a clamp test is a proven fact rather than an omission. +#include "strata/kernels/router_top10.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +constexpr double RENORM_CLAMP = 6.103515625e-05; // 2**-14 + +// The host reference: softmax over all experts, stable descending argsort, gather, clamp, renormalise. +void reference(const float* logits, int n_expert, int k, int* ids, float* w) { + double mx = logits[0]; + for (int e = 1; e < n_expert; ++e) mx = std::max(mx, (double) logits[e]); + double sum = 0; + std::vector p((size_t) n_expert); + for (int e = 0; e < n_expert; ++e) { + p[(size_t) e] = std::exp((double) logits[e] - mx); + sum += p[(size_t) e]; + } + for (int e = 0; e < n_expert; ++e) p[(size_t) e] /= sum; + + // stable descending: std::stable_sort with a strict greater-than keeps equal elements in index order + std::vector idx((size_t) n_expert); + std::iota(idx.begin(), idx.end(), 0); + std::stable_sort(idx.begin(), idx.end(), + [&](int a, int b) { return p[(size_t) a] > p[(size_t) b]; }); + double s = 0; + for (int i = 0; i < k; ++i) { + ids[i] = idx[(size_t) i]; + w[i] = (float) p[(size_t) idx[(size_t) i]]; + s += p[(size_t) idx[(size_t) i]]; + } + s = std::max(s, RENORM_CLAMP); + for (int i = 0; i < k; ++i) w[i] = (float) ((double) w[i] / s); +} + +int run_case(const char* name, const std::vector& logits, int n_tokens, int n_expert, int k, + double tol) { + std::vector h_ids((size_t) n_tokens * k); + std::vector h_w((size_t) n_tokens * k); + std::vector r_ids((size_t) n_tokens * k); + std::vector r_w((size_t) n_tokens * k); + for (int t = 0; t < n_tokens; ++t) { + reference(&logits[(size_t) t * n_expert], n_expert, k, &r_ids[(size_t) t * k], &r_w[(size_t) t * k]); + } + + float* d_l = nullptr; + int* d_ids = nullptr; + float* d_w = nullptr; + check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits"); + check(cudaMalloc(&d_ids, h_ids.size() * sizeof(int)), "malloc ids"); + check(cudaMalloc(&d_w, h_w.size() * sizeof(float)), "malloc w"); + check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); + strata::kernels::router_top10(d_l, n_tokens, n_expert, k, d_ids, d_w, nullptr); + check(cudaMemcpy(h_ids.data(), d_ids, h_ids.size() * sizeof(int), cudaMemcpyDeviceToHost), "back ids"); + check(cudaMemcpy(h_w.data(), d_w, h_w.size() * sizeof(float), cudaMemcpyDeviceToHost), "back w"); + + long long id_bad = 0, w_bad = 0; + double worst = 0; + for (size_t i = 0; i < h_ids.size(); ++i) { + if (h_ids[i] != r_ids[i]) ++id_bad; + const double rel = std::fabs((double) h_w[i] - (double) r_w[i]) / + (std::fabs((double) r_w[i]) > 1e-30 ? std::fabs((double) r_w[i]) : 1e-30); + worst = std::max(worst, rel); + if (!(rel <= tol)) ++w_bad; + } + // every token's weights must sum to 1 unless the clamp replaced the sum + double worst_sum = 0; + for (int t = 0; t < n_tokens; ++t) { + double s = 0; + for (int i = 0; i < k; ++i) s += (double) h_w[(size_t) t * k + i]; + double raw = 0; + for (int i = 0; i < k; ++i) raw += (double) r_w[(size_t) t * k + i]; + // both sides divide by the same clamped scale, so the ratios agree; check the kernel's own sum + worst_sum = std::max(worst_sum, std::fabs(s - 1.0)); + } + std::printf(" %-26s ids %s (%lld bad) weights worst rel %.3e (%lld over tol) |sum-1| %.1e\n", name, + id_bad ? "*** WRONG ***" : "exact", id_bad, worst, w_bad, worst_sum); + cudaFree(d_l); + cudaFree(d_ids); + cudaFree(d_w); + return (int) (id_bad + w_bad); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: router_top10_parity [--selftest]\n"); return 2; } + } + + const int NE = 512; // the real n_expert + const int K = 10; // the real top-k + const int NT = 64; + std::mt19937 rng(2024); + std::normal_distribution gauss(0.0f, 1.0f); + int bad = 0; + + // ---- random logits + std::vector a((size_t) NT * NE); + for (auto& v : a) v = gauss(rng); + bad += run_case("random normal", a, NT, NE, K, 1e-5); + + // ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding + // the ids. An unstable sort or a >= comparison in the maximum scan fails this and passes everything else. + std::vector b((size_t) NT * NE, 0.5f); + bad += run_case("all equal (ties)", b, NT, NE, K, 1e-5); + + // ---- a few exact ties among otherwise distinct values + std::vector c((size_t) NT * NE); + for (int t = 0; t < NT; ++t) { + for (int e = 0; e < NE; ++e) c[(size_t) t * NE + e] = (e < 12) ? 2.0f : gauss(rng); + } + bad += run_case("12-way exact tie", c, NT, NE, K, 1e-5); + + // ---- one dominant expert: the top-1 must be that expert and its weight must dominate + std::vector d((size_t) NT * NE, 0.0f); + for (int t = 0; t < NT; ++t) d[(size_t) t * NE + (t % NE)] = 20.0f; + bad += run_case("dominant expert", d, NT, NE, K, 1e-5); + + // ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested. + // The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform + // distribution). Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input + // whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one. + // Asserting the bound is worth more than a test that cannot reach it. + const double min_possible = (double) K / (double) NE; + std::printf(" %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx %s\n", "clamp reachability", + K, min_possible, RENORM_CLAMP, min_possible / RENORM_CLAMP, + min_possible > RENORM_CLAMP ? "(CLAMP IS UNREACHABLE, asserted)" : "*** REACHABLE ***"); + if (min_possible <= RENORM_CLAMP) { + std::fprintf(stderr, "the clamp CAN trigger, so it needs a test\n"); + ++bad; + } + + std::printf("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n", bad, NT, NE, + K); + if (bad) return 1; + if (selftest) std::printf("router_top10_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/s2_expert_grouped_parity.cpp b/engine/strata/src/kernels/s2_expert_grouped_parity.cpp new file mode 100644 index 00000000..901681f9 --- /dev/null +++ b/engine/strata/src/kernels/s2_expert_grouped_parity.cpp @@ -0,0 +1,679 @@ +// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones, +// BITWISE (GPU, synthetic, no model). +// +// build/s2_expert_grouped_parity the checks below; exit 1 on any difference +// build/s2_expert_grouped_parity --bench previous vs new kernel timings on engine-like shapes +// +// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations. Every entry +// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled +// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte: +// 1. `moe_hit_grouped_s2` per hit, host count; with fp32 activation scales and with the blocks' fp16 `d` +// 2. `moe_hit_grouped_s2_dev` device count below the capacity (the rows past it must stay untouched) +// 3. `moe_hit_grouped_s2_multi` verify window: each hit reads its own token's activation row +// 4. `moe_grouped_s2` host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe +// share), and more group capacity than groups +// 5. `moe_group_resident` + `moe_grouped_s2` the MTP layer's shape, with and without fp32 scales +// 6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels +// 7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the +// per-hit path must fall back as well (its codes are read as uint2) +// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass +// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones. +// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.) +// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names +// the projection. Bitwise equality with the previous kernels is the contract; on top of it a double-precision +// host reference of every up row and every down row checks that the fixture computes an expert at all - two +// kernels agreeing on garbage would otherwise pass. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace k = strata::kernels; + +namespace { +// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel). +constexpr int H = 2560, FF = 640, NCH_GU = H / 32, NCH_D = FF / 32; +constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64; +constexpr size_t O_D_CODES = 2ull * FF * ROW_GU; +constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D; +constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2; +constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2; +static_assert(BLOB == 1382400, "the Q2_0 expert blob is 1,382,400 bytes"); +constexpr size_t XROW = (size_t) NCH_GU * 34; // one token's activation row of block_q8_0 + +int g_fail = 0; + +void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } +} +template T* dalloc(size_t n) { + T* p = nullptr; + ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc"); + ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset"); + return p; +} +template void up(T* d, const std::vector& h) { + ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d"); +} +template std::vector down(const T* d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h"); + return h; +} + +float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); } +void put16(uint8_t* p, float f) { + const uint16_t h = k::f16_from_f32(f); + p[0] = (uint8_t) h; + p[1] = (uint8_t) (h >> 8); +} + +// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream). +void fill_blob(uint8_t* b, std::mt19937& rng) { + for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng(); + std::uniform_real_distribution mag(1e-3f, 3e-2f); + for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng)); +} + +// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes), +// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose. +void fill_x(std::vector& x, std::vector& xs, int n_tok, std::mt19937& rng) { + x.assign((size_t) n_tok * XROW, 0); + xs.assign((size_t) n_tok * NCH_GU, 0.0f); + std::uniform_real_distribution sc(2e-3f, 5e-2f); + for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) { + uint8_t* b = x.data() + c * 34; + xs[c] = sc(rng); + put16(b, xs[c]); + const int mode = (int) (rng() % 16); + for (int j = 0; j < 32; ++j) { + const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127; + b[2 + j] = (uint8_t) (int8_t) v; + } + } +} + +// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e. +// `mag` receives sum |term|, the scale the tolerance is relative to. +double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks, + double* mag) { + double acc = 0.0, a = 0.0; + for (int c = 0; c < n_chunks; ++c) { + const uint8_t* xb = xrow + (size_t) c * 34; + const double dx = xs ? (double) xs[c] : (double) f16f(xb); + const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2); + int s = 0; + for (int e = 0; e < 32; ++e) { + const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3; + s += (code - 1) * (int) (int8_t) xb[2 + e]; + } + const double t = dw * dx * (double) s; + acc += t; + a += std::fabs(t); + } + *mag = a; + return acc; +} + +bool close_to(float got, double ref, double mag) { + return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30; +} + +struct Scratch { + void* p = nullptr; + uint64_t bytes = 0; + int64_t cap = 0; + uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; } + uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; } +}; + +// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers; +// every differing float of the output and byte of the scratch is counted. `keep` receives the new run. +struct Run { + std::vector out; + std::vector scratch; +}; + +bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s, + const std::function& call, Run* keep, bool expect_new = true) { + Run r[2]; + for (int old = 1; old >= 0; --old) { + ck(cudaMemset(d_out, 0xA5, out_floats * 4), "sentinel out"); + ck(cudaMemset(s.p, 0x5A, s.bytes), "sentinel scratch"); + k::moe_grouped_select_old(old); + (void) k::moe_grouped_last_path(); // clear + call(); + const int path = k::moe_grouped_last_path(); + const int want = old ? 0 : (expect_new ? 1 : 0); + if (path != want) { + std::printf(" %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new", + path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous"); + ++g_fail; + } + ck(cudaGetLastError(), name); + ck(cudaDeviceSynchronize(), name); + Run& x = r[old ? 0 : 1]; + x.out = down(d_out, out_floats); + x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes); + } + k::moe_grouped_select_old(-1); + const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes(); + size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0; + for (size_t i = 0; i < out_floats; ++i) + diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0; + for (size_t i = 0; i < (size_t) s.bytes; ++i) { + if (r[0].scratch[i] == r[1].scratch[i]) continue; + if (i < gu) ++diff_gu; + else if (i < gu + q8) ++diff_q8; + else ++diff_hs; + } + const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0; + std::printf(" %-44s %s", name, ok ? "bitwise identical" : "DIFFERS"); + if (!ok) + std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu, + diff_q8, diff_hs); + std::printf("\n"); + if (!ok) ++g_fail; + if (keep) *keep = std::move(r[1]); + return ok; +} + +// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone) +// against the activation row it read, and every written down row against the intermediate the run produced. +struct Entry { + const uint8_t* blob; // host copy of the entry's blob + int tok; // activation row it reads + int dst; // output row it writes +}; +void reference(const char* name, const Run& r, const Scratch& s, const std::vector& ent, + const std::vector& x, const std::vector* xs) { + const float* gu = (const float*) r.scratch.data(); + const uint8_t* hq = r.scratch.data() + s.gu_bytes(); + const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes()); + long checked = 0, bad = 0; + double worst = 0.0; + for (size_t e = 0; e < ent.size(); ++e) { + const uint8_t* b = ent[e].blob; + const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW; + const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr; + for (int rr = 0; rr < FF; rr += 7) { // up row rr = row-slot 2rr + 1 + double mag; + const double ref = row_ref(b + (size_t) (2 * rr + 1) * ROW_GU, b + O_GU_SCALES + (size_t) (2 * rr + 1) * SC_GU * 2, + xrow, xsr, NCH_GU, &mag); + const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr]; + ++checked; + if (!close_to(got, ref, mag)) ++bad; + if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); + } + const uint8_t* hrow = hq + e * (size_t) NCH_D * 34; + const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr; + for (int rr = 0; rr < H; rr += 13) { + double mag; + const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2, + hrow, hsr, NCH_D, &mag); + const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr]; + ++checked; + if (!close_to(got, ref, mag)) ++bad; + if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag); + } + } + std::printf(" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked, + bad, worst); + if (bad || checked == 0) ++g_fail; +} + +struct Fixture { + int nb = 0; + std::vector h; // nb blobs + uint8_t* d = nullptr; + const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; } +}; + +Fixture make_blobs(int nb, std::mt19937& rng) { + Fixture f; + f.nb = nb; + f.h.resize((size_t) nb * BLOB); + for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng); + f.d = dalloc((size_t) nb * BLOB); + up(f.d, f.h); + return f; +} + +Scratch make_scratch(int64_t cap) { + Scratch s; + s.cap = cap; + s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF); + s.p = dalloc(s.bytes); + return s; +} + +// ---------------------------------------------------------------- the checks +void check_all() { + std::mt19937 rng(20260928); + const Fixture fx = make_blobs(12, rng); + constexpr int K = 10; + + // Activations for up to 8 tokens, device copies with and without the fp32 scales. + std::vector x; + std::vector xs; + fill_x(x, xs, 8, rng); + uint8_t* d_x = dalloc(x.size()); + float* d_xs = dalloc(xs.size()); + up(d_x, x); + up(d_xs, xs); + + // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled + { + const int n_hits = 9; + std::vector slot(n_hits), dst(K); + for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb); + std::iota(dst.begin(), dst.end(), 0); + std::shuffle(dst.begin(), dst.end(), rng); + dst.resize(n_hits); + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)"); + twice(name.c_str(), d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + scaled ? d_xs : nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + } + + // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7 + { + const int cap = 10, count = 7; + std::vector slot(cap), dst(cap); + for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb); + std::iota(dst.begin(), dst.end(), 0); + std::shuffle(dst.begin(), dst.end(), rng); + int32_t* d_slot = dalloc(cap); + int32_t* d_dst = dalloc(cap); + int32_t* d_count = dalloc(1); + up(d_slot, slot); + up(d_dst, dst); + up(d_count, std::vector{count}); + const Scratch s = make_scratch(cap); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + Run r; + twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2_dev(fx.d, d_slot, d_dst, d_count, cap, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + d_xs); + }, &r); + reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs); + // the rows of the hits past the count keep the sentinel + long touched = 0; + for (int i = count; i < cap; ++i) + for (int c = 0; c < H; ++c) { + uint32_t v; + std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4); + touched += v != 0xA5A5A5A5u; + } + std::printf(" %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched); + if (touched) ++g_fail; + } + + // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits + { + const int T = 4, n = T * K, count = 29; + std::vector ent_ids(n); + std::iota(ent_ids.begin(), ent_ids.end(), 0); + std::shuffle(ent_ids.begin(), ent_ids.end(), rng); + std::vector slot(n), dst(n); + for (int i = 0; i < n; ++i) { + dst[i] = ent_ids[i]; + slot[i] = (int32_t) (rng() % fx.nb); + } + std::sort(dst.begin(), dst.begin() + count); // hit order is routing order, as `moe_hit_select_multi` makes it + int32_t* d_slot = dalloc(n); + int32_t* d_dst = dalloc(n); + int32_t* d_count = dalloc(1); + up(d_slot, slot); + up(d_dst, dst); + up(d_count, std::vector{count}); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + std::vector ent; + for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]}); + Run r; + twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] { + k::moe_hit_grouped_s2_multi(fx.d, d_slot, d_dst, d_count, n, (int64_t) BLOB, d_x, d_xs, K, s.p, d_out, + nullptr); + }, &r); + reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs); + } + + // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob + { + const int T = 8, n = T * K; + uint8_t* h_host = nullptr; + uint8_t* d_host = nullptr; + ck(cudaHostAlloc((void**) &h_host, BLOB, cudaHostAllocMapped), "host blob"); + std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB); + ck(cudaHostGetDevicePointer((void**) &d_host, h_host, 0), "host blob ptr"); + // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries + const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5}; + std::vector order(n); // the output rows, in group order + std::iota(order.begin(), order.end(), 0); + std::shuffle(order.begin(), order.end(), rng); + std::vector gptr; + std::vector gstart{0}, edst, etok; + std::vector ent; + int at = 0, gi = 0; + while (at < n) { + const int sz = std::min(sizes[gi % 20], n - at); + const bool host = gi == 3; + const int b = gi % (fx.nb - 1); + gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB)); + for (int j = 0; j < sz; ++j, ++at) { + edst.push_back(order[at]); + etok.push_back(order[at] / K); + ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]}); + } + gstart.push_back(at); + ++gi; + } + const int n_groups = gi, cap_groups = n_groups + 3; + gstart.resize((size_t) cap_groups + 1, at); + gptr.resize((size_t) cap_groups, gptr[0]); + unsigned long long* d_gptr = dalloc(gptr.size()); + int32_t* d_gstart = dalloc(gstart.size()); + int32_t* d_ng = dalloc(1); + int32_t* d_edst = dalloc(n); + int32_t* d_etok = dalloc(n); + up(d_gptr, gptr); + up(d_gstart, gstart); + up(d_ng, std::vector{n_groups}); + up(d_edst, edst); + up(d_etok, etok); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" + + (scaled ? ", fp32 scales)" : ", fp16 d)"); + twice(name.c_str(), d_out, (size_t) n * H, s, [&] { + k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr, + s.p, d_out, nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + ck(cudaFreeHost(h_host), "free host blob"); + } + + // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB) + { + const int T = 5, n = T * K; + std::vector ids(n); + for (int t = 0; t < T; ++t) { // distinct within a token, shared across tokens + std::vector pick(fx.nb); + std::iota(pick.begin(), pick.end(), 0); + std::shuffle(pick.begin(), pick.end(), rng); + for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j]; + } + int32_t* d_ids = dalloc(n); + up(d_ids, ids); + unsigned long long* d_gptr = dalloc(n); + int32_t* d_gstart = dalloc(n + 1); + int32_t* d_counts = dalloc(2); + int32_t* d_edst = dalloc(n); + int32_t* d_etok = dalloc(n); + k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr); + ck(cudaDeviceSynchronize(), "group_resident"); + const std::vector edst = down(d_edst, n), etok = down(d_etok, n); + std::vector ent(n); // entry e: dst = routing index, blob = its expert + for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]}; + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + for (int scaled = 1; scaled >= 0; --scaled) { + Run r; + const std::string name = std::string("moe_group_resident + moe_grouped_s2") + (scaled ? " (fp32)" : " (fp16)"); + twice(name.c_str(), d_out, (size_t) n * H, s, [&] { + k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p, + d_out, nullptr); + }, &r); + reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr); + } + } + + // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run + { + uint8_t* d_x2 = dalloc(x.size() + 2); + ck(cudaMemcpy(d_x2 + 2, x.data(), XROW, cudaMemcpyHostToDevice), "x2"); + const int n_hits = 3; + std::vector slot{2, 5, 7}, dst{4, 0, 9}; + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + Run r; + twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x2 + 2, s.p, d_out, nullptr, d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs); + } + + // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback + { + constexpr size_t STRIDE = BLOB + 4; + static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads"); + const int nb = 8; + uint8_t* d_arena = dalloc((size_t) nb * STRIDE + 8); + const int n_hits = 4; + std::vector slot{6, 1, 3, 0}, dst{2, 7, 5, 8}; + int32_t* d_slot = dalloc(n_hits); + int32_t* d_dst = dalloc(n_hits); + up(d_slot, slot); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + std::vector ent; + for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]}); + // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from + // `d_arena + 4` over them. + for (int i = 0; i < nb; ++i) + ck(cudaMemcpy(d_arena + (size_t) i * STRIDE, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); + { + Run r; + twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr, + d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs); + } + for (int i = 0; i < nb; ++i) + ck(cudaMemcpy(d_arena + 4 + (size_t) i * BLOB, fx.hb(i), BLOB, cudaMemcpyHostToDevice), "arena"); + { + Run r; + twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] { + k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr, + d_xs); + }, &r, /*expect_new=*/false); + reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs); + } + } +} + +// ---------------------------------------------------------------- --bench +// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from +// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth. +void bench() { + int dev = 0; + cudaDeviceProp prop{}; + ck(cudaGetDevice(&dev), "dev"); + ck(cudaGetDeviceProperties(&prop, dev), "props"); + const int nb = std::max(48, (int) (3ull * (size_t) prop.l2CacheSize / BLOB) + 8); + std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n", prop.name, prop.l2CacheSize >> 20, nb, + nb * (double) BLOB / 1e6); + std::mt19937 rng(7); + Fixture fx; + fx.nb = nb; + fx.d = dalloc((size_t) nb * BLOB); + { + std::vector b(BLOB); + for (int i = 0; i < nb; ++i) { + fill_blob(b.data(), rng); + ck(cudaMemcpy(fx.d + (size_t) i * BLOB, b.data(), BLOB, cudaMemcpyHostToDevice), "blob"); + } + } + std::vector x; + std::vector xs; + fill_x(x, xs, 8, rng); + uint8_t* d_x = dalloc(x.size()); + float* d_xs = dalloc(xs.size()); + up(d_x, x); + up(d_xs, xs); + constexpr int K = 10, ITERS = 200, SETS = 16; + cudaEvent_t e0, e1; + ck(cudaEventCreate(&e0), "ev"); + ck(cudaEventCreate(&e1), "ev"); + auto time = [&](const std::function& call) { + call(0); + ck(cudaDeviceSynchronize(), "warm"); + ck(cudaEventRecord(e0), "rec"); + for (int i = 0; i < ITERS; ++i) call(i % SETS); + ck(cudaEventRecord(e1), "rec"); + ck(cudaEventSynchronize(e1), "sync"); + float ms = 0; + ck(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + return 1000.0 * ms / ITERS; + }; + auto ab = [&](const char* name, double blobs_per_call, const std::function& call) { + double us[2]; + for (int old = 1; old >= 0; --old) { + k::moe_grouped_select_old(old); + us[old ? 0 : 1] = time(call); + } + k::moe_grouped_select_old(-1); + const double gb = blobs_per_call * (double) BLOB / 1e3; // bytes / us = MB/s ... / 1e3 -> GB/s + std::printf(" %-40s previous %8.1f us (%6.0f GB/s) new %8.1f us (%6.0f GB/s) x%.2f\n", name, us[0], + gb / us[0], us[1], gb / us[1], us[0] / us[1]); + }; + + // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the + // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS` + for (const int n_hits : {9, 5, 3, 2, 1}) { + std::vector slots((size_t) SETS * n_hits), dst(K); + for (auto& v : slots) v = (int32_t) (rng() % nb); + std::iota(dst.begin(), dst.end(), 0); + int32_t* d_slots = dalloc(slots.size()); + int32_t* d_dst = dalloc(K); + up(d_slots, slots); + up(d_dst, dst); + const Scratch s = make_scratch(n_hits); + float* d_out = dalloc((size_t) K * H); + const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits"; + ab(name.c_str(), n_hits, [&](int set) { + k::moe_hit_grouped_s2(fx.d, d_slots + (size_t) set * n_hits, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, + d_out, nullptr, d_xs); + }); + } + // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already + // routed by an earlier token of the window + struct Shape { int T; double share; const char* what; }; + for (const Shape sh : {Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"}, + Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) { + const int n = sh.T * K; + std::vector gptr((size_t) SETS * n); + std::vector gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n); + double groups = 0; + std::uniform_real_distribution u(0, 1); + for (int set = 0; set < SETS; ++set) { + std::vector> g; // per group: routing indices + std::vector gexp; // per group: blob + for (int t = 0; t < sh.T; ++t) { + std::vector used(g.size(), 0); + for (int j = 0; j < K; ++j) { + int pick = -1; + if (t > 0 && u(rng) < sh.share) + for (size_t q = 0; q < g.size(); ++q) + if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; } + if (pick < 0) { + pick = (int) g.size(); + g.emplace_back(); + gexp.push_back((int) (rng() % nb)); + used.push_back(0); + } + used[(size_t) pick] = 1; + g[(size_t) pick].push_back(t * K + j); + } + } + int at = 0; + for (size_t q = 0; q < g.size(); ++q) { + gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB); + gstart[(size_t) set * (n + 1) + q] = at; + for (int e : g[q]) { + edst[(size_t) set * n + at] = e; + etok[(size_t) set * n + at] = e / K; + ++at; + } + } + for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at; + ng[set] = (int32_t) g.size(); + groups += (double) g.size() / SETS; + } + unsigned long long* d_gptr = dalloc(gptr.size()); + int32_t* d_gstart = dalloc(gstart.size()); + int32_t* d_ng = dalloc(SETS); + int32_t* d_edst = dalloc(edst.size()); + int32_t* d_etok = dalloc(etok.size()); + up(d_gptr, gptr); + up(d_gstart, gstart); + up(d_ng, ng); + up(d_edst, edst); + up(d_etok, etok); + const Scratch s = make_scratch(n); + float* d_out = dalloc((size_t) n * H); + char name[96]; + std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups); + ab(name, groups, [&](int set) { + k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set, + d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out, + nullptr); + }); + } +} +} // namespace + +int main(int argc, char** argv) { + bool do_bench = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--bench") == 0) do_bench = true; + else if (std::strcmp(argv[i], "--selftest") != 0) { + std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n"); + return 2; + } + } + std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n"); + check_all(); + if (do_bench) bench(); + std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS"); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/kernels/s2_gemv_parity.cpp b/engine/strata/src/kernels/s2_gemv_parity.cpp new file mode 100644 index 00000000..ab693799 --- /dev/null +++ b/engine/strata/src/kernels/s2_gemv_parity.cpp @@ -0,0 +1,173 @@ +// src/kernels/s2_gemv_parity.cpp - P2.S2's parity test for the S2 GEMV. +// +// The reference is the same CHAIN as the decode test: `strata::dequantize_q2_0` is a scalar transcription that +// `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizer, so comparing the GPU GEMV against a +// dot product built on that scalar decode compares against ggml through one proven hop. +// +// WHY A TOLERANCE AND NOT BIT EQUALITY. The decode test is bit-exact because S2's decode is exact +// integer-to-float arithmetic. A dot product is not: the compiler is free to contract `a*b + acc` into an +// FMA, which changes the result in the last bits, and nvcc does. So this asserts a RELATIVE error, measures +// what it actually is, and prints the number - the phase spec allows 1e-3 for FP16 paths, and if the measured +// error were near that the tolerance would be hiding something rather than bounding rounding. +#include "strata/artifact/dequant.hpp" +#include "strata/kernels/s2_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int QK = 64; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// FP16 patterns, and they are deliberately NOT all powers of two. +// +// The first version of this table was {1.0, 0.5, 0.25, ...} - every value a power of two. The test then +// reported a worst relative error of EXACTLY zero, which is not a property of the kernel: (code-1) is in +// {-1,0,1,2} and a power-of-two times an fp16 is exact, so every product was exact and no rounding could +// occur in either implementation. A test whose arithmetic cannot round cannot exercise its own tolerance, and +// it would have hidden an accumulation-order or contraction bug for ever. +// +// The added patterns have full 11-bit mantissas, so products round and the two implementations' +// rounding/contraction behaviour actually matters. +const uint16_t kScales[] = { + 0x3C00, 0x3800, 0x3400, 0x3000, 0x2C00, 0x2800, 0x2000, // 1, 0.5, 0.25, ... powers of two + 0xBC00, 0xB800, 0xB400, 0xB000, 0xAC00, 0x1800, 0x1400, + 0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B, // 1.75, 0.333.., 1.0009765625, ... + 0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB}; + +} // namespace + +int main(int argc, char** argv) { + long long n_in = 2560; // the real n_embd, so the row length is the engine's + long long n_out = 640; // the real expert intermediate width + double tol = 1e-5; + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--selftest") == 0) selftest = true; + else if (std::strcmp(argv[i], "--n-in") == 0 && i + 1 < argc) n_in = std::atoll(argv[++i]); + else if (std::strcmp(argv[i], "--n-out") == 0 && i + 1 < argc) n_out = std::atoll(argv[++i]); + else if (std::strcmp(argv[i], "--tol") == 0 && i + 1 < argc) tol = std::atof(argv[++i]); + else { + std::fprintf(stderr, "usage: s2_gemv_parity [--selftest] [--n-in N] [--n-out N] [--tol T]\n"); + return 2; + } + } + if (n_in % QK != 0) { std::fprintf(stderr, "--n-in must be a multiple of %d\n", QK); return 2; } + const long long nb = n_in / QK; + + std::mt19937 rng(999); + const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); + + // FP16 activations. Patterns are drawn from the same finite/exact table as the decode test, because a + // random 16-bit pattern can be NaN and a NaN makes the comparison fail for the wrong reason. + std::vector x((size_t) n_in); + for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; + + // S2 weight planes for an [n_in, n_out] matrix: row o occupies a contiguous run of nb blocks. + std::vector codes((size_t) n_out * nb * 16); + std::vector scales((size_t) n_out * nb); + for (size_t i = 0; i < codes.size(); ++i) codes[i] = (uint8_t) (rng() & 0xFF); + for (size_t i = 0; i < scales.size(); ++i) { + scales[i] = strata::fp16_to_fp32(kScales[rng() % n_scales]); + } + + // CPU reference: rebuild each row's RAW Q2_0 blocks from the planes, decode with the scalar path that + // dequant_xcheck proved equal to ggml, and accumulate in the same order the kernel does. + std::vector ref((size_t) n_out, 0.0f); + std::vector raw(18); + std::vector dec(QK); + for (long long o = 0; o < n_out; ++o) { + float acc = 0.0f; + for (long long b = 0; b < nb; ++b) { + const float d = scales[(size_t) (o * nb + b)]; + // write `d` back as the fp16 pattern the plane came from: the plane stores a WIDENED fp16, so + // re-narrowing is exact and the scalar decoder sees the same value the kernel does + const uint16_t d_bits = (uint16_t) [&] { + for (uint16_t c : kScales) { + if (strata::fp16_to_fp32(c) == d) return c; + } + return (uint16_t) 0x3C00; + }(); + raw[0] = (uint8_t) (d_bits & 0xFF); + raw[1] = (uint8_t) (d_bits >> 8); + std::memcpy(&raw[2], &codes[(size_t) ((o * nb + b) * 16)], 16); + strata::dequantize_q2_0(raw.data(), dec.data()); + for (int j = 0; j < QK; ++j) { + acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (b * QK + j)]); + } + } + ref[(size_t) o] = acc; + } + + uint16_t* d_x = nullptr; + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); + check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), + "copy scales"); + + strata::kernels::s2_gemv(d_x, d_codes, d_scales, d_y, n_in, n_out); + + std::vector got((size_t) n_out); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); + + long long bad = 0, first_bad = -1; + double worst = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref[(size_t) o], b = got[(size_t) o]; + const double denom = std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30; + const double rel = std::fabs(a - b) / denom; + if (!(rel <= worst)) worst = rel; + if (!(rel <= tol)) { + if (first_bad < 0) first_bad = o; + ++bad; + } + } + + // NON-VACUITY: a zero matrix and a zero activation vector agree at zero. The reference must actually vary + // and its magnitudes must be non-trivial, or the comparison cannot distinguish anything. + double lo = ref[0], hi = ref[0]; + for (float v : ref) { + lo = std::fmin(lo, v); + hi = std::fmax(hi, v); + } + const double spread = hi - lo; + std::printf("s2_gemv: n_in %lld, n_out %lld, %lld rows over tolerance, worst rel %.3e (tol %.1e)\n", n_in, + n_out, bad, worst, tol); + std::printf(" reference spread [%.4g, %.4g]\n", lo, hi); + if (spread <= 0.0) { + std::fprintf(stderr, "VACUOUS: the reference is constant, so agreement proves nothing\n"); + return 1; + } + if (bad) { + std::printf(" first bad row %lld: ref %.9g got %.9g\n", first_bad, (double) ref[(size_t) first_bad], + (double) got[(size_t) first_bad]); + return 1; + } + std::printf(" agrees with the scalar decode that dequant_xcheck proved equal to ggml\n"); + if (selftest) std::printf("s2_gemv_parity OK\n"); + + cudaFree(d_x); + cudaFree(d_codes); + cudaFree(d_scales); + cudaFree(d_y); + return 0; +} diff --git a/engine/strata/src/kernels/s2_gemv_q8_parity.cpp b/engine/strata/src/kernels/s2_gemv_q8_parity.cpp new file mode 100644 index 00000000..833e751a --- /dev/null +++ b/engine/strata/src/kernels/s2_gemv_q8_parity.cpp @@ -0,0 +1,181 @@ +// src/kernels/s2_gemv_q8_parity.cpp - the Q8_0-activation GEMV, and the size of the gap it closes. +// +// THREE CHECKS: +// 1. The quantized-activation GEMV matches a host reference that quantizes the activation exactly as +// `ref/quant.py::q8_0` does and then dots it against the same weights. +// 2. **The gap is REAL and MEASURABLE in this project's own kernels**: the same weights driven by an FP16 +// activation and by a Q8_0 activation must DIFFER, by roughly the activation contract's ~1%. Without this +// the first check would pass on a kernel that quietly used fp16 anyway, and the round-186 gap would look +// fixed without being fixed. +// 3. The measured size of that difference is reported, so the number in the state file is one this test +// produces rather than one quoted from elsewhere. +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/s2_gemv_q8.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: s2_gemv_q8_parity [--selftest]\n"); return 2; } + } + + const long long n_in = 2560, n_out = 64; + const int tpr = 32; + std::mt19937 rng(31); + std::normal_distribution gauss(0.0f, 1.0f); + + std::vector x((size_t) n_in); + for (auto& v : x) v = gauss(rng); + std::vector codes((size_t) n_out * n_in / 4); + for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); + std::vector scales((size_t) n_out * (n_in / 64)); + for (auto& v : scales) v = 0.001f + 0.0001f * (float) (rng() % 100); + + // ---- device buffers + float* d_x = nullptr; + uint8_t* d_act = nullptr; + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_y_fp16 = nullptr, *d_y_q8 = nullptr; + check(cudaMalloc(&d_x, (size_t) n_in * sizeof(float)), "m x"); + check(cudaMalloc(&d_act, (size_t) (n_in / 32) * 34), "m act"); + check(cudaMalloc(&d_codes, codes.size()), "m codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "m scales"); + check(cudaMalloc(&d_y_fp16, (size_t) n_out * sizeof(float)), "m y1"); + check(cudaMalloc(&d_y_q8, (size_t) n_out * sizeof(float)), "m y2"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "c x"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "c codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), "c scales"); + + strata::kernels::quantize_q8_0(d_x, d_act, n_in, nullptr); + + // ---- host reference: quantize the activation with the project's own rule, then dot + std::vector h_act((size_t) (n_in / 32) * 34); + check(cudaMemcpy(h_act.data(), d_act, h_act.size(), cudaMemcpyDeviceToHost), "c act back"); + auto act_val = [&](long long i) { + const uint8_t* blk = &h_act[(size_t) (i / 32) * 34]; + const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8)); + // fp16 -> f32 without a CUDA header: 0x3C00 = 1.0, and the block scales here are normal + float d; + const uint32_t sign = (uint32_t) (dbits & 0x8000) << 16; + uint32_t ex = (dbits >> 10) & 0x1F, man = dbits & 0x3FF; + uint32_t out; + if (ex == 0) { out = sign; } + else { out = sign | ((ex - 15 + 127) << 23) | (man << 13); } + std::memcpy(&d, &out, 4); + return (float) ((int8_t) blk[2 + (i % 32)]) * d; + }; + std::vector ref((size_t) n_out, 0.0f); + for (long long o = 0; o < n_out; ++o) { + float acc = 0.0f; + for (long long g = 0; g < n_in / 64; ++g) { + const float d = scales[(size_t) (o * (n_in / 64) + g)]; + for (int j = 0; j < 64; ++j) { + const long long i = g * 64 + j; + const uint8_t byte = codes[(size_t) (o * (n_in / 4) + i / 4)]; + const int code = (byte >> ((i % 4) * 2)) & 3; + acc += (float) (code - 1) * d * act_val(i); + } + } + ref[(size_t) o] = acc; + } + strata::kernels::s2_gemv_q8(d_act, d_codes, d_scales, d_y_q8, n_in, n_out, tpr, nullptr); + std::vector got((size_t) n_out); + check(cudaMemcpy(got.data(), d_y_q8, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y2"); + + int bad = 0; + double worst = 0.0, sum_abs = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref[(size_t) o], b = got[(size_t) o]; + sum_abs += std::fabs(a); + // relative to the row magnitude is not needed here - these rows are not cancelling - but the metric is + // stated because round 169 and round 189 both showed the wrong denominator reads as a wrong kernel + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (!(rel <= worst)) worst = rel; + // 1e-4, not 1e-5: the measured worst is 1.479e-05, which is FMA contraction over 2560 terms rather + // than a structural error, and a threshold that passes 62 of 64 by luck is not a threshold. The phase + // allows 1e-3 for FP16 paths, so this is ten times tighter than the spec and ten times looser than the + // measurement. + if (!(rel <= 1e-4)) ++bad; + } + std::printf(" %-38s %s (%d of %lld over 1e-4, worst rel %.3e, mean |ref| %.3f)\n", + "q8-activation GEMV vs host reference", bad ? "*** WRONG ***" : "matches", bad, n_out, worst, + sum_abs / (double) n_out); + + // ---- CHECK 2: the gap is real. The SAME weights driven by an fp16 activation must differ. + // The fp16 path wants fp16 activations, and `x` is f32, so it is converted exactly (the values are normal + // and small), which keeps the comparison about the ACTIVATION FORMAT and nothing else. + // A REAL fp32 -> fp16 conversion. The first version wrote `0x3C00 + (int)(x*64)`, which adds to the raw + // BITS and therefore changes the EXPONENT - x = 2.0 became 0x3C80 = 1.25 - so the two paths were driven by + // unrelated activations and the comparison reported 2770%. The number was a symptom of the fixture, and + // the fixture is what the check exists to be able to trust. + auto f32_to_f16 = [](float f) -> uint16_t { + uint32_t b; + std::memcpy(&b, &f, 4); + const uint32_t sign = (b >> 16) & 0x8000u; + int exp = (int) ((b >> 23) & 0xFF) - 127 + 15; + uint32_t man = b & 0x7FFFFFu; + if (exp >= 31) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u)); + if (exp <= 0) { + if (exp < -10) return (uint16_t) sign; + man |= 0x800000u; + const uint32_t sh = (uint32_t) (14 - exp); + uint32_t h = (man >> sh) & 0x3FFu; + const uint32_t rem = man & ((1u << sh) - 1u); + if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h; + return (uint16_t) (sign | h); + } + uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13)); + const uint32_t rem = man & 0x1FFFu; + if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h; + return h; + }; + std::vector hx((size_t) n_in); + for (long long i = 0; i < n_in; ++i) hx[(size_t) i] = f32_to_f16(x[(size_t) i]); + uint16_t* d_hx = nullptr; + check(cudaMalloc(&d_hx, hx.size() * sizeof(uint16_t)), "m hx"); + check(cudaMemcpy(d_hx, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c hx"); + strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false}; + strata::kernels::s_gemv_split(d_hx, d_codes, d_scales, nullptr, d_y_fp16, n_in, n_out, form, tpr); + std::vector y16((size_t) n_out); + check(cudaMemcpy(y16.data(), d_y_fp16, y16.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y1"); + + double diff = 0.0; + for (long long o = 0; o < n_out; ++o) { + diff += std::fabs((double) y16[(size_t) o] - (double) got[(size_t) o]); + } + const double rel_gap = diff / (sum_abs > 1e-30 ? sum_abs : 1e-30); + std::printf(" %-38s %.4f%% of the reference magnitude\n", "fp16-activation vs q8-activation", rel_gap * 100); + if (rel_gap < 1e-4) { + std::fprintf(stderr, + "the two activation paths agree to %.2e, so this test CANNOT see the difference it exists " + "to measure - either the q8 path silently used fp16, or the fixture is degenerate\n", + rel_gap); + ++bad; + } + + std::printf("\ns2_gemv_q8: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("s2_gemv_q8_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/s_gemv_parity.cpp b/engine/strata/src/kernels/s_gemv_parity.cpp new file mode 100644 index 00000000..5c0bed53 --- /dev/null +++ b/engine/strata/src/kernels/s_gemv_parity.cpp @@ -0,0 +1,634 @@ +// src/kernels/s_gemv_parity.cpp - P2.S2's parity test for the S-family GEMV. +// +// Four source types, chosen to cover every branch the kernel has: +// +// S2 Q2_0 2-bit, bias -1, group 64 affine +// S4 Q4_0 4-bit, bias -8, group 32 affine +// S4 IQ4_NL 4-bit, bias 0, group 32 CODEBOOK (non-linear, no bias can express it) +// S8 Q8_0 8-bit, bias -128, group 32 affine +// +// That is all three template instantiations, both codebooks, and four different biases. The offset branch +// (`has_offset`, only Q4_K and Q5_K) is NOT exercised here and the test prints that fact rather than leaving a +// green result to imply otherwise - Q4_K's canonicalisation needs the packed 6-bit scale/min pairs, and the +// honest move is to say so than to half-build it. +// +// THE REFERENCE IS THE CHAIN: for each type the CPU side reconstructs the RAW GGUF block from the canonical +// planes and decodes it with that type's scalar dequantizer from include/strata/artifact/dequant.hpp - the +// ones `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizers. Reconstructing raw from +// canonical is the inverse of what the packer does, and it is written here independently of the packer so the +// two are not the same code. +#include "strata/artifact/dequant.hpp" +#include "strata/kernels/s_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// Finite, exactly representable fp16 patterns WITH full mantissas. Not powers of two: with only powers of +// two every product is exact and the comparison cannot round, which is how the first version of s2_gemv's test +// managed a worst error of exactly zero without proving anything. +const uint16_t kScales[] = {0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B, 0x3800, + 0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB, 0xB800}; + +struct Case { + const char* name; + strata::kernels::SForm form; + int raw_bytes; // one block + // Reconstruct the raw GGUF block for one group from the canonical codes/scales, and return the number of + // elements the block decodes to (which may exceed group_elems: Q8_0's block IS one group, Q2_0's too). + int (*to_raw)(const uint8_t* codes, size_t code_off, const uint16_t* scale_bits, size_t scale_off, uint8_t* raw); + double (*dequant)(const uint8_t* raw, float* out); +}; + +// ---- Q2_0: raw = { fp16 d ; uint8 qs[16] }, 64 elements, code i at byte i/4 bits (i%4)*2 - identical to the +// canonical plane, so this is a straight copy plus the scale. +int q2_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { + const uint16_t d = scale_bits[so]; + raw[0] = (uint8_t) (d & 0xFF); + raw[1] = (uint8_t) (d >> 8); + // `codes` is one code PER ELEMENT (64 of them); a Q2_0 block stores them PACKED, 4 per byte, element i at + // byte i/4 bits (i%4)*2. The two coincide as a byte layout only if you confuse them, which is exactly the + // mistake the first version of this function made by copying 16 bytes verbatim. + for (int b = 0; b < 16; ++b) { + raw[2 + b] = (uint8_t) ((codes[co + 4 * b + 0] & 3) | ((codes[co + 4 * b + 1] & 3) << 2) | + ((codes[co + 4 * b + 2] & 3) << 4) | ((codes[co + 4 * b + 3] & 3) << 6)); + } + return 64; +} +double q2_0_deq(const uint8_t* raw, float* out) { + strata::dequantize_q2_0(raw, out); + return 64; +} + +// ---- Q4_0: raw = { fp16 d ; uint8 qs[16] }, 32 elements; element j is the LOW nibble of byte j and element +// j+16 the HIGH nibble. The canonical plane stores one code per element, so this re-packs them. +int q4_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { + const uint16_t d = scale_bits[so]; + raw[0] = (uint8_t) (d & 0xFF); + raw[1] = (uint8_t) (d >> 8); + for (int j = 0; j < 16; ++j) raw[2 + j] = (uint8_t) ((codes[co + j] & 0x0F) | (codes[co + 16 + j] << 4)); + return 32; +} +double q4_0_deq(const uint8_t* raw, float* out) { + strata::dequantize_q4_0(raw, out); + return 32; +} + +// ---- IQ4_NL: identical packing to Q4_0, different decode (a table, not a bias). +int iq4_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { + return q4_0_to_raw(codes, co, scale_bits, so, raw); +} +double iq4_deq(const uint8_t* raw, float* out) { + strata::dequantize_iq4_nl(raw, out); + return 32; +} + +// ---- Q8_0: raw = { fp16 d ; int8 qs[32] }, 32 elements. The canonical code plane is UNSIGNED with bias +// -128 (round 154's fix), so the raw int8 byte is exactly the canonical code reinterpreted - a straight copy, +// which is why this type is the cheapest one to check and the one whose sign bug was found by the pack. +int q8_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) { + const uint16_t d = scale_bits[so]; + raw[0] = (uint8_t) (d & 0xFF); + raw[1] = (uint8_t) (d >> 8); + // NOT a straight copy. The canonical code plane is UNSIGNED with bias -128, so canonical code c means the + // value (c - 128); the raw block stores that as an `int8_t`, whose reinterpretation as an unsigned byte is + // `c ^ 0x80` - a SIGN-BIT FLIP, not the identity. Assuming identity is the same family of mistake as the + // round-154 Q8_0 bug that the pack found, and it is why this reconstruction is written out rather than + // memcpy'd. + for (int j = 0; j < 32; ++j) raw[2 + j] = (uint8_t) (codes[co + j] ^ 0x80); + return 32; +} +double q8_0_deq(const uint8_t* raw, float* out) { + strata::dequantize_q8_0(raw, out); + return 32; +} + +// ---- S4/Q4_K: the ONLY canonical form with an offset, and the only one whose scale is an FP32 PRODUCT +// (`fl(d*sc)`) rather than a widened fp16. Both facts make it the case worth having. +// +// There is no `to_raw` for it in the table above because its canonical planes are DERIVED from the raw +// parameters, not the other way round: the packer computes `scale = d*sc` and `offset = -(dmin*m)`, so this +// generates d, dmin and the eight (sc, m) pairs, derives the planes exactly as the packer does, and writes a +// raw block from the SAME parameters. Inverting those products instead would be ambiguous. +void test_q4k(long long n_in, long long n_out, double tol, int* total_bad) { + using strata::kernels::Codebook; + using strata::kernels::SForm; + const SForm form{4, 0, 32, Codebook::Affine, true}; + + std::mt19937 rng(777); + const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); + const long long n_groups = n_in / 32; + const long long codes_per_row = n_in / 2; + + std::vector x((size_t) n_in); + for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; + + std::vector codes_el((size_t) n_out * n_in); + for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & 0x0F); + std::vector codes((size_t) n_out * codes_per_row, 0); + for (size_t i = 0; i < codes_el.size(); ++i) { + const size_t o = i / (size_t) n_in, k = i % (size_t) n_in; + codes[o * (size_t) codes_per_row + k / 2] |= (uint8_t) (codes_el[i] << ((k % 2) * 4)); + } + std::vector scales((size_t) n_out * n_groups), offsets((size_t) n_out * n_groups); + + struct Row { + uint16_t d, dmin; + uint8_t sc[8], m[8]; + }; + std::vector rows((size_t) n_out); + for (long long o = 0; o < n_out; ++o) { + Row& r = rows[(size_t) o]; + r.d = kScales[rng() % n_scales]; + r.dmin = kScales[rng() % n_scales]; + for (int g = 0; g < 8; ++g) { + r.sc[g] = (uint8_t) (rng() & 0x3F); + r.m[g] = (uint8_t) (rng() & 0x3F); + for (long long sb = 0; sb < n_in / 256; ++sb) { + scales[(size_t) (o * n_groups + sb * 8 + g)] = strata::fp16_to_fp32(r.d) * (float) r.sc[g]; + offsets[(size_t) (o * n_groups + sb * 8 + g)] = -(strata::fp16_to_fp32(r.dmin) * (float) r.m[g]); + } + } + } + + std::vector ref((size_t) n_out, 0.0f); + std::vector cond((size_t) n_out, 0.0); + double worst_plane_ref = 0.0; // max |planes - raw block| over every element, on the CPU alone + std::vector blk(144); + std::vector dec(256); + // A Q4_K raw block covers 256 elements, so a 2560-element row is TEN superblocks, each with its own + // 144-byte block. The first version of this loop ran `step < 4` - one superblock, 256 of the row's 2560 + // elements - while the kernel accumulated all of them, and the resulting 29x relative error was the + // reference being short, not the kernel being wrong. + for (long long o = 0; o < n_out; ++o) { + const Row& r = rows[(size_t) o]; + float acc = 0.0f; + double sum_abs = 0.0; // the natural scale of this row's dot product (see the metric below) + double plane_ref_diff = 0.0; // (a) vs (b): planes against the raw block, both on the CPU + for (long long sb = 0; sb < n_in / 256; ++sb) { + // ONE 144-byte block per 256-element SUPERBLOCK, with all four steps' qs bytes filled BEFORE the + // decode. The previous version decoded a fresh block per STEP and then read all 256 elements + // from each, so three quarters of every decode came from zeroed qs - four decodes of a + // quarter-filled block per superblock, which is the whole of the 1.17e4 disagreement. + // `scripts/probe_q4k_groups.cpp` builds it this way and agrees exactly, group by group. + blk.assign(144, 0); + blk[0] = (uint8_t) (r.d & 0xFF); + blk[1] = (uint8_t) (r.d >> 8); + blk[2] = (uint8_t) (r.dmin & 0xFF); + blk[3] = (uint8_t) (r.dmin >> 8); + for (int j = 0; j < 4; ++j) { // the exact inverse of get_scale_min_k4 + blk[4 + j] = (uint8_t) ((r.sc[j] & 0x3F) | ((r.sc[j + 4] >> 4) << 6)); + blk[8 + j] = (uint8_t) ((r.m[j] & 0x3F) | ((r.m[j + 4] >> 4) << 6)); + blk[12 + j] = (uint8_t) ((r.sc[j + 4] & 0x0F) | ((r.m[j + 4] & 0x0F) << 4)); + } + for (int step = 0; step < 4; ++step) { + for (int l = 0; l < 32; ++l) { // elements 0..31 LOW nibbles, 32..63 HIGH + const long long e0 = o * n_in + sb * 256 + step * 64 + l; + const long long e1 = e0 + 32; + blk[16 + step * 32 + l] = + (uint8_t) ((codes_el[(size_t) e0] & 0x0F) | (codes_el[(size_t) e1] << 4)); + } + } + strata::dequantize_q4_K(blk.data(), dec.data()); + for (int j = 0; j < 256; ++j) { + const float term = dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (sb * 256 + j)]); + acc += term; + sum_abs += std::fabs((double) term); // the CONDITION of this dot product + + // THE THIRD DECODE. (a) the raw block through the scalar dequantizer, (b) the canonical + // PLANES through `code*scale + offset`, (c) the GPU. If (a) != (b) then this test built + // planes that disagree with its own raw block and the kernel is innocent; if (a) == (b) and + // (c) differs, the kernel is wrong. Without (b) there is no way to tell which. + const long long elem = sb * 256 + j; + const long long g = elem / 32; + const int code = (int) codes_el[(size_t) (o * n_in + elem)]; + const float b_dec = (float) code * scales[(size_t) (o * n_groups + g)] + + offsets[(size_t) (o * n_groups + g)]; + if (std::fabs((double) (b_dec - dec[(size_t) j])) > plane_ref_diff) { + plane_ref_diff = std::fabs((double) (b_dec - dec[(size_t) j])); + } + } + } + ref[(size_t) o] = acc; + cond[(size_t) o] = sum_abs; + if (!(plane_ref_diff <= worst_plane_ref)) worst_plane_ref = plane_ref_diff; + } + + uint16_t* d_x = nullptr; + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_offsets = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); + check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_offsets, offsets.size() * sizeof(float)), "cudaMalloc offsets"); + check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), + "copy scales"); + check(cudaMemcpy(d_offsets, offsets.data(), offsets.size() * sizeof(float), cudaMemcpyHostToDevice), + "copy offsets"); + strata::kernels::s_gemv(d_x, d_codes, d_scales, d_offsets, d_y, n_in, n_out, form); + std::vector got((size_t) n_out); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); + + // THE ERROR IS MEASURED AGAINST sum|term|, NOT AGAINST THE RESULT. A dot product of 2560 signed terms + // cancels, so `|ref-got| / |ref|` is a statement about the condition number, not about the kernel: a row + // whose terms are ~1e7 and whose result is ~1e3 reports a relative error of 50 for an absolute error of + // 1e-6 of the terms. `sum_abs` is the natural scale of the computation, and comparing to it is what + // makes a tolerance mean "agrees to within rounding" instead of "did not cancel". + long long bad = 0; + double worst = 0.0, worst_res = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref[(size_t) o], b = got[(size_t) o]; + const double scale = cond[(size_t) o] > 1e-30 ? cond[(size_t) o] : 1e-30; + const double rel = std::fabs(a - b) / scale; + const double rel_res = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (!(rel <= worst)) worst = rel; + if (!(rel_res <= worst_res)) worst_res = rel_res; + if (!(rel <= tol)) ++bad; + } + double lo = ref[0], hi = ref[0]; + for (float v : ref) { + lo = std::fmin(lo, v); + hi = std::fmax(hi, v); + } + std::printf(" %-10s %lld rows, %lld over tol, worst rel-to-terms %.3e (rel-to-result %.3e)\n", + "S4/Q4_K", n_out, bad, worst, worst_res); + std::printf(" ref spread [%.4g, %.4g], condition (sum|term|) up to %.4g\n", lo, hi, + *std::max_element(cond.begin(), cond.end())); + std::printf(" CPU planes vs CPU raw block: max |diff| = %.3e -> %s\n", worst_plane_ref, + worst_plane_ref == 0.0 + ? "the test is SELF-CONSISTENT" + : "*** THE TEST DISAGREES WITH ITSELF - fix the reference before believing any GPU result ***"); + if (hi - lo <= 0.0) { + std::fprintf(stderr, "VACUOUS: S4/Q4_K reference is constant\n"); + std::exit(1); + } + *total_bad += (int) bad; + cudaFree(d_x); + cudaFree(d_codes); + cudaFree(d_scales); + cudaFree(d_offsets); + cudaFree(d_y); +} + +} // namespace + + +// ------------------------------------------------------------------ benchmark +// +// P2.S10 wants a first measurement and a ledger entry, and the objective is stated in tokens per second, so +// the useful output is not GiB/s but "milliseconds of expert matvec per token". Warm-up runs are discarded +// (the first launch pays module load and page faults) and the MINIMUM is reported alongside the mean, because +// the minimum is the one not polluted by another process on the machine. +void bench_s2_gemv(long long n_in, long long n_out, int iters, int* split_bad) { + using strata::kernels::Codebook; + using strata::kernels::SForm; + const SForm form{2, -1, 64, Codebook::Affine, false}; + const long long n_groups = n_in / 64; + const long long codes_per_row = n_in / 4; + + std::vector codes((size_t) n_out * codes_per_row, 0xA5); + std::vector scales((size_t) n_out * n_groups, 0.001f); + std::vector x((size_t) n_in, 0x3C00); // 1.0 in fp16 + + uint16_t* d_x = nullptr; + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "bench x"); + check(cudaMalloc(&d_codes, codes.size()), "bench codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "bench scales"); + check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "bench y"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "bench copy x"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "bench copy codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), + "bench copy scales"); + + for (int i = 0; i < 3; ++i) strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); + + std::vector ms; + for (int i = 0; i < iters; ++i) { + const auto t0 = std::chrono::steady_clock::now(); + strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); + const auto t1 = std::chrono::steady_clock::now(); + ms.push_back(std::chrono::duration(t1 - t0).count()); + } + std::sort(ms.begin(), ms.end()); + double mean = 0; + for (double v : ms) mean += v; + mean /= (double) ms.size(); + + const double weights = (double) n_in * (double) n_out; + const double bytes = (double) n_out * (double) codes_per_row + (double) n_out * n_groups * 4.0; + std::printf("s2_gemv bench [%lld x %lld] %d iters\n", n_in, n_out, iters); + std::printf(" ms per gemv: min %.4f median %.4f mean %.4f\n", ms.front(), ms[ms.size() / 2], mean); + std::printf(" min -> %.1f G weights/s, %.1f GiB/s of S2 streamed\n", weights / ms.front() / 1e6, + bytes / (1024.0 * 1024 * 1024) / (ms.front() / 1000.0)); + + // The projection the objective is stated against: 48 layers x 10 experts x 3 roles, all of one token's + // experts, at the measured per-role rate. This is the VRAM-resident path only - the CPU expert path and + // the KV/attention work are separate and are NOT included. + const double roles_per_token = 48.0 * 10.0 * 3.0; + const double tok_ms = roles_per_token * ms.front(); + std::printf(" per token: %.0f roles x %.4f ms = %.1f ms -> %.1f tok/s (expert matvec only)\n", + roles_per_token, ms.front(), tok_ms, tok_ms > 0 ? 1000.0 / tok_ms : 0.0); + std::printf(" NOTE: expert matvec ONLY. No attention, no KV, no norm, no router, no sampling, and it\n" + " assumes every expert is already resident in VRAM at zero cost.\n"); + + // The NAIVE kernel's output is the reference for the split one. `s_gemv` is checked against the scalar + // dequantizer by this file's parity cases, so its result here is a validated value, and the split kernel + // sums in a different order - so this is a relative comparison, not bit equality. + strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form); + std::vector ref_naive((size_t) n_out); + check(cudaMemcpy(ref_naive.data(), d_y, ref_naive.size() * sizeof(float), cudaMemcpyDeviceToHost), + "copy naive reference"); + + // ---- the row-split variant, same planes, same process ------------------- + // Swept rather than guessed: more threads per row buys parallelism and costs a deeper reduction. + for (int tpr : {32, 64, 128, 256}) { + if (tpr > n_in) continue; + for (int i = 0; i < 3; ++i) { + strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr); + } + std::vector sms; + for (int i = 0; i < iters; ++i) { + const auto t0 = std::chrono::steady_clock::now(); + strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr); + sms.push_back(std::chrono::duration(std::chrono::steady_clock::now() - t0) + .count()); + } + std::sort(sms.begin(), sms.end()); + + // correctness of the thing being timed + std::vector got((size_t) n_out); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), + "copy split result"); + long long bad = 0; + double worst = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref_naive[(size_t) o], b = got[(size_t) o]; + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (!(rel <= worst)) worst = rel; + if (!(rel <= 1e-4)) ++bad; + } + if (bad) { + std::printf(" split tpr=%-4d *** WRONG *** %lld of %lld rows differ, worst rel %.3e\n", tpr, + bad, n_out, worst); + *split_bad += (int) bad; + } + + // ---- the quad-amortised S2 kernel, timed AND checked against the naive reference ---- + // Only meaningful for S2: it assumes four elements share one code byte, which is true of 2-bit codes. + if (form.code_bits == 2 && (n_in % 64) == 0) { + for (int t2 : {32, 64, 128}) { + for (int i = 0; i < 3; ++i) { + strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2); + } + std::vector qms; + for (int i = 0; i < iters; ++i) { + const auto q0 = std::chrono::steady_clock::now(); + strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2); + qms.push_back(std::chrono::duration( + std::chrono::steady_clock::now() - q0).count()); + } + std::sort(qms.begin(), qms.end()); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), + "copy quads result"); + long long qbad = 0; + double qworst = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref_naive[(size_t) o], b = got[(size_t) o]; + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (rel > qworst) qworst = rel; + if (!(rel <= 1e-4)) ++qbad; + } + if (qbad) *split_bad += (int) qbad; + std::printf(" quads tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n", t2, + qms.front(), weights / qms.front() / 1e6, ms.front() / qms.front(), + qbad ? "*** WRONG ***" : "checked ok"); + } + } + + // ---- the two-lever kernel, both configurations, timed AND checked ---- + if (form.code_bits == 2 && (n_in % 64) == 0) { + for (int staged = 0; staged < 2; ++staged) { + for (int t3 : {32, 64, 128}) { + for (int i = 0; i < 3; ++i) { + strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0); + } + std::vector fms; + for (int i = 0; i < iters; ++i) { + const auto q0 = std::chrono::steady_clock::now(); + strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0); + fms.push_back(std::chrono::duration( + std::chrono::steady_clock::now() - q0).count()); + } + std::sort(fms.begin(), fms.end()); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), + "copy fast result"); + long long fbad = 0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref_naive[(size_t) o], b = got[(size_t) o]; + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (!(rel <= 1e-4)) ++fbad; + } + if (fbad) *split_bad += (int) fbad; + std::printf(" fast %s tpr=%-4d min %.4f ms -> %6.1f G weights/s vs naive %.2fx %s\n", + staged ? "staged" : "global", t3, fms.front(), + weights / fms.front() / 1e6, ms.front() / fms.front(), + fbad ? "*** WRONG ***" : "checked ok"); + } + } + } + + const double sp = ms.front() / sms.front(); + std::printf(" split tpr=%-4d min %.4f ms -> %6.1f G weights/s speedup vs naive %.2fx\n", tpr, + sms.front(), weights / sms.front() / 1e6, sp); + } + + cudaFree(d_x); + cudaFree(d_codes); + cudaFree(d_scales); + cudaFree(d_y); +} + +int main(int argc, char** argv) { + long long n_in = 2560; + long long n_out = 128; + // 1e-4, not 1e-5: the measured worst is ~1e-5 (FMA contraction of a 2560-term f32 accumulation), so a + // 1e-5 threshold would pass by 4% and fail on a different n_in. The phase spec allows 1e-3 for FP16 + // paths; this is 10x tighter than the spec and 10x looser than the measurement. + double tol = 1e-4; + bool selftest = false; + bool bench = false; + int iters = 200; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") selftest = true; + else if (a == "--bench") bench = true; + else if (a == "--iters" && i + 1 < argc) iters = std::atoi(argv[++i]); + else if (a == "--n-in" && i + 1 < argc) n_in = std::atoll(argv[++i]); + else if (a == "--n-out" && i + 1 < argc) n_out = std::atoll(argv[++i]); + else { + std::fprintf(stderr, "usage: s_gemv_parity [--selftest] [--n-in N] [--n-out N]\n"); + return 2; + } + } + + using strata::kernels::Codebook; + using strata::kernels::SForm; + std::vector cases; + cases.push_back({"S2/Q2_0", SForm{2, -1, 64, Codebook::Affine, false}, 18, q2_0_to_raw, q2_0_deq}); + cases.push_back({"S4/Q4_0", SForm{4, -8, 32, Codebook::Affine, false}, 18, q4_0_to_raw, q4_0_deq}); + cases.push_back({"S4/IQ4_NL", SForm{4, 0, 32, Codebook::Iq4Nl, false}, 18, iq4_to_raw, iq4_deq}); + cases.push_back({"S8/Q8_0", SForm{8, -128, 32, Codebook::Affine, false}, 34, q8_0_to_raw, q8_0_deq}); + + std::mt19937 rng(4242); + const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0])); + int total_bad = 0; + + for (const Case& tc : cases) { + const int bits = tc.form.code_bits; + const int per_byte = 8 / bits; + const int G = tc.form.group_elems; + const long long n_groups = n_in / G; + const long long codes_per_row = n_in / per_byte; + + // activations + std::vector x((size_t) n_in); + for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales]; + + // Codes are generated ONE PER ELEMENT and then packed into the plane the kernel reads. + // + // The first version of this test generated a random BYTE ARRAY and used it as both, which is the bug + // that made S2 pass and the other three fail by 50x-500x. The two are not the same thing: the kernel + // reads element i from byte i/per_byte at bit (i%per_byte)*bits, while the reference needs one code per + // element to rebuild a raw GGUF block. For S2 (per_byte = 4, which IS Q2_0's own raw layout) treating + // one random array as both happened to agree - and that coincidence is exactly what a test must not + // depend on. + std::vector codes_el((size_t) n_out * n_in); + for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & ((1u << bits) - 1)); + std::vector codes((size_t) n_out * codes_per_row, 0); + for (long long o = 0; o < n_out; ++o) { + for (long long i = 0; i < n_in; ++i) { + const long long byi = o * codes_per_row + i / per_byte; + codes[(size_t) byi] |= (uint8_t) (codes_el[(size_t) (o * n_in + i)] + << ((i % per_byte) * bits)); + } + } + std::vector scales((size_t) n_out * n_groups); + std::vector scale_bits((size_t) n_out * n_groups); + for (size_t i = 0; i < scales.size(); ++i) { + scale_bits[i] = kScales[rng() % n_scales]; + scales[i] = strata::fp16_to_fp32(scale_bits[i]); + } + + // CPU reference + std::vector ref((size_t) n_out, 0.0f); + std::vector raw((size_t) tc.raw_bytes); + std::vector dec((size_t) G); + for (long long o = 0; o < n_out; ++o) { + float acc = 0.0f; + for (long long g = 0; g < n_groups; ++g) { + const size_t co = (size_t) o * n_in + (size_t) g * G; // the UNPACKED code array + const size_t so = (size_t) o * n_groups + (size_t) g; + // The raw block carries the scale as fp16 and the canonical plane carries it widened, so the + // block is rebuilt from the PATTERN the plane came from. No float-to-fp16 conversion is + // needed anywhere, and the decoder therefore sees bit-identically what the kernel reads. + const int n = tc.to_raw(codes_el.data(), co, scale_bits.data(), so, raw.data()); + tc.dequant(raw.data(), dec.data()); + for (long long j = 0; j < (long long) n; ++j) { + acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (g * G + j)]); + } + } + ref[(size_t) o] = acc; + } + + // GPU + uint16_t* d_x = nullptr; + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_x, x.size() * sizeof(uint16_t)), "cudaMalloc x"); + check(cudaMalloc(&d_codes, codes.size()), "cudaMalloc codes"); + check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "cudaMalloc scales"); + check(cudaMalloc(&d_y, (size_t) n_out * sizeof(float)), "cudaMalloc y"); + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "copy codes"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), + "copy scales"); + strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, tc.form); + std::vector got((size_t) n_out); + check(cudaMemcpy(got.data(), d_y, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "copy back"); + + long long bad = 0; + double worst = 0.0; + for (long long o = 0; o < n_out; ++o) { + const double a = ref[(size_t) o], b = got[(size_t) o]; + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + if (!(rel <= worst)) worst = rel; + if (!(rel <= tol)) ++bad; + } + double lo = ref[0], hi = ref[0]; + for (float v : ref) { + lo = std::fmin(lo, v); + hi = std::fmax(hi, v); + } + std::printf(" %-10s %lld rows, %lld over tol, worst rel %.3e ref spread [%.4g, %.4g]\n", tc.name, + n_out, bad, worst, lo, hi); + if (hi - lo <= 0.0) { + std::fprintf(stderr, "VACUOUS: %s reference is constant\n", tc.name); + return 1; + } + total_bad += (int) bad; + + cudaFree(d_x); + cudaFree(d_codes); + cudaFree(d_scales); + cudaFree(d_y); + } + + std::printf("s_gemv: %zu type cases, %d rows over tolerance (tol %.1e)\n", cases.size(), total_bad, tol); + // Q4_K IS NOT PART OF THE DEFAULT RUN. It FAILS: 128 of 128 rows, worst error 0.586 of sum|term| - a + // real difference, not cancellation (the condition number is 2.8e7 and the error is 1.6e7). Either the + // kernel's offset handling or this test's reconstruction of a Q4_K block is wrong and the two have not + // been separated yet. Running it by default would turn ctest red and hide regressions in the four cases + // that ARE verified; leaving it out silently would be worse. It is one flag away, and it is recorded as + // OPEN in the project state. + // Q4_K is IN the default run as of round 171. Rounds 169-170 gated it because it FAILED, and the + // failure was this test's own reconstruction of a Q4_K block - four decodes of a quarter-filled block per + // superblock - not the kernel. It now agrees to 2.8e-07 of sum|term|, so the gate goes rather than + // staying as a habit: a gate that outlives its reason is a check that quietly stopped running. + test_q4k(n_in, n_out, tol, &total_bad); + std::printf("s_gemv total: %d rows over tolerance\n", total_bad); + if (bench) { + // the real expert shapes: gate/up are [2560 x 640], down is [640 x 2560] + int split_bad = 0; + bench_s2_gemv(2560, 640, iters, &split_bad); + bench_s2_gemv(640, 2560, iters, &split_bad); + std::printf("split kernel rows disagreeing with the naive reference: %d\n", split_bad); + // accumulated HERE, inside the block that declares it, and it makes the binary FAIL: a kernel that is + // benchmarked but never compared is an unverified kernel being quoted for performance. + total_bad += split_bad; + } + if (total_bad) return 1; + if (selftest) std::printf("s_gemv_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/s_gemv_q8k_parity.cpp b/engine/strata/src/kernels/s_gemv_q8k_parity.cpp new file mode 100644 index 00000000..5bfb475a --- /dev/null +++ b/engine/strata/src/kernels/s_gemv_q8k_parity.cpp @@ -0,0 +1,343 @@ +// src/kernels/s_gemv_q8k_parity.cpp - the Q8_K activation path of `s_gemv`. +// +// THE POINT OF THIS KERNEL IS A CONTRACT, so the test is built around the contract rather than around the +// arithmetic: +// +// 1. the kernel against a host reference that dequantizes the SAME Q8_K bytes and the SAME S-form planes, +// in double - so what is under test is the indexing, not the format; +// 2. the Q8_K activation is produced by the ACTUAL `quantize_q8_K`, which is byte-exact against ggml +// (round 198). Building the activation by hand here would make this a test of two transcriptions; +// 3. **THE Q8_K-vs-FP16 GAP IS MEASURED**, because that is the number the whole activation-contract +// decision rests on and it has only ever been measured on Q2_0 weights (0.6175%) and on BF16 ones +// (0.141-0.156%). A K-quant weight is a third case and it is the one the dense projections use. +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s_gemv.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using strata::kernels::SForm; +using strata::kernels::Codebook; + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +/// The host decode, transcribed from `docs/pack-format.md`'s rule: `value = cb[code] * scale + offset`, with +/// the integer bias applied INSIDE the integer domain before the one multiply. +const signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; + +double weight_at(const std::vector& codes, const std::vector& scales, + const std::vector& offset, const SForm& f, long long n_in, long long o, long long i) { + const int per_byte = 8 / f.code_bits; + const long long codes_per_row = n_in / per_byte; + const long long n_groups = n_in / f.group_elems; + const uint8_t* c = codes.data() + o * codes_per_row; + const int code = (c[i / per_byte] >> ((int) (i % per_byte) * f.code_bits)) & ((1 << f.code_bits) - 1); + const double v = (f.codebook == Codebook::Iq4Nl) ? (double) kIq4Nl[code & 0x0F] + : (double) (code + f.code_bias); + const long long g = i / f.group_elems; + double w = v * (double) scales[(size_t) (o * n_groups + g)]; + if (f.has_offset) w += (double) offset[(size_t) (o * n_groups + g)]; + return w; +} + +/// Dequantize a block_q8_K buffer on the host: 292 bytes per 256 elements. +double q8k_at(const std::vector& x, long long i) { + const uint8_t* blk = x.data() + (size_t) (i / 256) * 292; + float d; + std::memcpy(&d, blk, 4); + const int8_t q = ((const int8_t*) (blk + 4))[i % 256]; + return (double) d * (double) q; +} + +struct Case { + const char* what; + int bits; + int bias; + int group; + Codebook cb; + bool has_offset; +}; + +/// THE RAGGED LAST BLOCK. The split kernels give each warp one row and a block eight warps, so with +/// `n_out % 8 != 0` the last block holds warps that have no row. Those warps used to return BEFORE the +/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided. Here `n_out` is +/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard +/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write. +/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.) +int ragged_rows(const Case& cs, long long n_out) { + const long long n_in = 512; + const long long guard = 64; + std::mt19937 rng(77 + (unsigned) n_out); + std::normal_distribution g(0.0f, 1.0f); + std::vector xf((size_t) n_in); + for (auto& v : xf) v = g(rng); + SForm f; + f.code_bits = cs.bits; + f.code_bias = cs.bias; + f.group_elems = cs.group; + f.codebook = cs.cb; + f.has_offset = cs.has_offset; + const int per_byte = 8 / cs.bits; + std::vector codes((size_t) (n_out * n_in / per_byte)); + for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); + const long long n_groups = n_in / cs.group; + std::vector scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups)); + for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20); + for (auto& v : offs) v = 0.2f * g(rng); + + float* d_xf = nullptr; + uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr; + float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr; + std::vector xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34); + check(cudaMalloc(&d_xf, (size_t) n_in * 4), "rxf"); + check(cudaMalloc(&d_xk, xk.size()), "rxk"); + check(cudaMalloc(&d_x0, x0.size()), "rx0"); + check(cudaMalloc(&d_codes, codes.size()), "rcodes"); + check(cudaMalloc(&d_scales, scales.size() * 4), "rscales"); + check(cudaMalloc(&d_offs, offs.size() * 4), "roffs"); + check(cudaMalloc(&d_y, (size_t) (n_out + guard) * 4), "ry"); + check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "rcxf"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "rcc"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "rcs"); + check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "rco"); + strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr); + strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr); + check(cudaMemcpy(xk.data(), d_xk, xk.size(), cudaMemcpyDeviceToHost), "rcxk"); + check(cudaMemcpy(x0.data(), d_x0, x0.size(), cudaMemcpyDeviceToHost), "rcx0"); + + int bad = 0; + for (int kind = 0; kind < 2; ++kind) { // 0: Q8_K activation, 1: Q8_0 activation + std::vector want((size_t) n_out); + std::vector mag((size_t) n_out); // sum |w_i a_i| per row: a row whose sum cancels near 0 + for (long long o = 0; o < n_out; ++o) { // must not turn f32 rounding into a relative failure + double acc = 0, am = 0; + for (long long i = 0; i < n_in; ++i) { + double a; + if (kind == 0) { + a = q8k_at(xk, i); + } else { + const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34; + uint16_t dbits; + std::memcpy(&dbits, blk, 2); + a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32]; + } + const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a; + acc += wa; + am += std::fabs(wa); + } + want[(size_t) o] = (float) acc; + mag[(size_t) o] = am; + } + // the guard band holds a NaN pattern; any write there shows up as a changed bit + std::vector sentinel((size_t) (n_out + guard), 0x7FC0DEADu); + check(cudaMemcpy(d_y, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "rsent"); + if (kind == 0) + strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, + n_out, f, nullptr); + else + strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, + n_out, f, nullptr); + check(cudaDeviceSynchronize(), "ragged split"); + std::vector got_bits(sentinel.size()); + check(cudaMemcpy(got_bits.data(), d_y, got_bits.size() * 4, cudaMemcpyDeviceToHost), "rcy"); + double m = 0, d = 0; + for (long long o = 0; o < n_out; ++o) { + float v; + std::memcpy(&v, &got_bits[(size_t) o], 4); + m += mag[(size_t) o]; + d += std::fabs((double) want[(size_t) o] - (double) v); + } + long long touched = 0; + for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu; + const double rel = d / (m > 1e-30 ? m : 1e-30); + const bool ok = rel <= 1e-5 && touched == 0; + std::printf(" %-28s %s n_out %3lld: rel %.3e, guard words written %lld %s\n", cs.what, + kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***"); + if (!ok) ++bad; + } + cudaFree(d_xf); cudaFree(d_xk); cudaFree(d_x0); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); + cudaFree(d_y); + return bad; +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: s_gemv_q8k_parity [--selftest]\n"); return 2; } + } + int bad = 0; + + // The forms the DENSE weights actually use, taken from the manifest rather than invented: + // attn_qkv.weight IQ4_XS S4 group 32, no offset (the GDN mixer's qkv) + // attn_gate.weight Q4_K S4 group 32, offset (the GDN mixer's z) + // ssm_out.weight Q5_K S8 group 32, offset (the GDN mixer's output) + const Case cases[] = { + {"IQ4_XS S4 g32 no-offset", 4, -8, 32, Codebook::Affine, false}, + {"Q4_K S4 g32 offset", 4, 0, 32, Codebook::Affine, true}, + {"Q5_K S8 g32 offset", 8, 0, 32, Codebook::Affine, true}, + }; + + for (const Case& cs : cases) { + const long long n_in = 512, n_out = 64; // 2 Q8_K blocks wide, small enough for a host reference + std::mt19937 rng(2024); + std::normal_distribution g(0.0f, 1.0f); + std::vector xf((size_t) n_in); + for (auto& v : xf) v = g(rng); + + SForm f; + f.code_bits = cs.bits; + f.code_bias = cs.bias; + f.group_elems = cs.group; + f.codebook = cs.cb; + f.has_offset = cs.has_offset; + + const int per_byte = 8 / cs.bits; + std::vector codes((size_t) (n_out * n_in / per_byte)); + for (auto& v : codes) v = (uint8_t) (rng() & 0xFF); + const long long n_groups = n_in / cs.group; + std::vector scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups)); + for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20); + for (auto& v : offs) v = 0.2f * g(rng); + + // ---- the activation, from the REAL quantizer + std::vector xq8k((size_t) (n_in / 256) * 292); + float* d_xf = nullptr; + uint8_t* d_xq = nullptr; + check(cudaMalloc(&d_xf, (size_t) n_in * 4), "xf"); + check(cudaMalloc(&d_xq, xq8k.size()), "xq"); + check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "cxf"); + strata::kernels::quantize_q8_K(d_xf, d_xq, n_in, nullptr); + check(cudaMemcpy(xq8k.data(), d_xq, xq8k.size(), cudaMemcpyDeviceToHost), "cxq"); + + // ---- host reference in double, over the same bytes + std::vector want((size_t) n_out, 0.0f); + for (long long o = 0; o < n_out; ++o) { + double acc = 0; + for (long long i = 0; i < n_in; ++i) + acc += weight_at(codes, scales, offs, f, n_in, o, i) * q8k_at(xq8k, i); + want[(size_t) o] = (float) acc; + } + + // ---- device + uint8_t* d_codes = nullptr; + float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_codes, codes.size()), "codes"); + check(cudaMalloc(&d_scales, scales.size() * 4), "scales"); + check(cudaMalloc(&d_offs, offs.size() * 4), "offs"); + check(cudaMalloc(&d_y, (size_t) n_out * 4), "y"); + check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "cc"); + check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "cs"); + check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "co"); + + std::vector naive((size_t) n_out), warp((size_t) n_out); + strata::kernels::s_gemv_q8k(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out, + f, nullptr); + check(cudaMemcpy(naive.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy1"); + strata::kernels::s_gemv_q8k_split(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, + n_out, f, nullptr); + check(cudaMemcpy(warp.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy2"); + + double mag = 0, d1 = 0, d2 = 0; + for (long long o = 0; o < n_out; ++o) { + mag += std::fabs((double) want[(size_t) o]); + d1 += std::fabs((double) want[(size_t) o] - (double) naive[(size_t) o]); + d2 += std::fabs((double) want[(size_t) o] - (double) warp[(size_t) o]); + } + std::printf(" %-28s naive %.3e warp %.3e\n", cs.what, d1 / mag, d2 / mag); + // The kernel accumulates in f32, the reference in f64, over 512 terms with values of similar size. + // 1e-5 is the arithmetic's floor, not a structural allowance. + if (!(d1 / mag <= 1e-5 && d2 / mag <= 1e-5)) { std::printf(" *** over 1e-5 ***\n"); ++bad; } + + // ---- 2b. THE Q8_0 ACTIVATION, on the SAME weight planes. `s_gemv_q8_0_split` exists because the + // legacy block formats want Q8_0 and `ffn_down_shexp` cannot use Q8_K at all (n_in = 640 is not a + // multiple of 256). It shares every line with the Q8_K kernel except the activation loader, so what + // this checks is the LOADER - the 34-byte block, the fp16 `d`, and the element index inside it. + { + std::vector xq0((size_t) (n_in / 32) * 34); + uint8_t* d_x0 = nullptr; + check(cudaMalloc(&d_x0, xq0.size()), "x0"); + strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr); + check(cudaMemcpy(xq0.data(), d_x0, xq0.size(), cudaMemcpyDeviceToHost), "cx0"); + + // the host reference over the SAME Q8_0 bytes, with the same weight decode + std::vector want0((size_t) n_out, 0.0f); + for (long long o = 0; o < n_out; ++o) { + double acc = 0; + for (long long i = 0; i < n_in; ++i) { + const uint8_t* blk = xq0.data() + (size_t) (i / 32) * 34; + uint16_t dbits; + std::memcpy(&dbits, blk, 2); + const double d = (double) strata::kernels::f32_from_f16(dbits); + const int8_t q = ((const int8_t*) (blk + 2))[i % 32]; + acc += weight_at(codes, scales, offs, f, n_in, o, i) * d * (double) q; + } + want0[(size_t) o] = (float) acc; + } + strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, + n_in, n_out, f, nullptr); + std::vector got0((size_t) n_out); + check(cudaMemcpy(got0.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy0"); + double m0 = 0, dd0 = 0; + for (long long o = 0; o < n_out; ++o) { + m0 += std::fabs((double) want0[(size_t) o]); + dd0 += std::fabs((double) want0[(size_t) o] - (double) got0[(size_t) o]); + } + std::printf(" %-28s Q8_0 act %.3e\n", cs.what, dd0 / (m0 > 1e-30 ? m0 : 1e-30)); + if (!(dd0 / (m0 > 1e-30 ? m0 : 1e-30) <= 1e-5)) { + std::printf(" *** the Q8_0 activation loader is WRONG ***\n"); + ++bad; + } + check(cudaFree(d_x0), "fx0"); + } + + // ---- 3. THE Q8_K vs FP16 GAP, on a K-quant weight - the case the contract decision needs + { + std::vector x16((size_t) n_in); + for (long long i = 0; i < n_in; ++i) x16[(size_t) i] = strata::kernels::f16_from_f32(xf[(size_t) i]); + uint16_t* d_x16 = nullptr; + check(cudaMalloc(&d_x16, (size_t) n_in * 2), "x16"); + check(cudaMemcpy(d_x16, x16.data(), (size_t) n_in * 2, cudaMemcpyHostToDevice), "cx16"); + std::vector fp16out((size_t) n_out); + strata::kernels::s_gemv(d_x16, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out, + f); + check(cudaMemcpy(fp16out.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy3"); + double dd = 0; + for (long long o = 0; o < n_out; ++o) + dd += std::fabs((double) naive[(size_t) o] - (double) fp16out[(size_t) o]); + const double rel = dd / mag; + const bool visible = rel > 1e-3; + std::printf(" %-24s %s (%.4f%% apart, tolerance 0.1%%)\n", "Q8_K vs fp16 activation", + visible ? "yes" : "*** NO ***", rel * 100); + if (!visible) ++bad; + cudaFree(d_x16); + } + cudaFree(d_xf); cudaFree(d_xq); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); cudaFree(d_y); + } + + // ---- 4. output widths that are NOT a multiple of the eight rows per block + std::printf("\n"); + for (const Case& cs : cases) + for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out); + + std::printf("\ns_gemv_q8k: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("s_gemv_q8k_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/sampler_parity.cpp b/engine/strata/src/kernels/sampler_parity.cpp new file mode 100644 index 00000000..2351722b --- /dev/null +++ b/engine/strata/src/kernels/sampler_parity.cpp @@ -0,0 +1,1284 @@ +// src/kernels/sampler_parity.cpp - P2.S2's test for the sampler chain. +// +// THE CHECK THAT MATTERS IS THAT THE ORDER IS OBSERVABLE. A sampler in the wrong order still returns a valid +// token, so "it produced a token" proves nothing; and because temperature is MONOTONIC it does not change which +// tokens `top_k` keeps, so a top-k-only fixture cannot see the order either. What it changes is `top_p`'s CUT: +// at T < 1 the distribution sharpens, the cumulative mass reaches p sooner, and fewer tokens survive. +// +// So this builds a fixture where that happens, computes the greedy pick under BOTH orders, and requires them to +// DIFFER - then requires the kernel to agree with the specified one. Without the first half, the test would +// pass against either order. +#include "strata/kernels/sampler.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// The host reference for the specified order: top_k -> top_p -> temperature -> argmax. +// `temp_first` swaps the first and last stages, which is the intuitive-but-wrong order. +int reference_pick(const std::vector& l, const strata::kernels::SamplerParams& p, bool temp_first) { + const int nv = (int) l.size(); + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; }; + + std::vector ids; + const int k = p.top_k > 0 ? p.top_k : nv; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = -1; + float bv = 0; + for (int v = 0; v < nv; ++v) { + if (taken[(size_t) v]) continue; + if (best < 0 || val(v) > bv) { best = v; bv = val(v); } + } + taken[(size_t) best] = 1; + ids.push_back(best); + } + if (p.top_p < 1.0f) { + float mx = val(ids[0]); + for (int v : ids) mx = std::fmax(mx, val(v)); + double sum = 0; + for (int v : ids) sum += std::exp((double) val(v) - (double) mx); + double cum = 0; + int cut = (int) ids.size(); + for (size_t i = 0; i < ids.size(); ++i) { + cum += std::exp((double) val(ids[i]) - (double) mx) / sum; + if (cum >= (double) p.top_p) { cut = (int) i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size(); + ids.resize((size_t) cut); + } + return ids[0]; // greedy: the largest SURVIVING logit, and `ids` is in descending order +} + +// The number of survivors AFTER top_p, in the given order - the quantity the order actually changes. +int reference_cut(const std::vector& l, const strata::kernels::SamplerParams& p, bool temp_first) { + const int nv = (int) l.size(); + const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; + auto val = [&](int v) { return temp_first ? l[(size_t) v] * inv_t : l[(size_t) v]; }; + const int k = p.top_k > 0 ? p.top_k : nv; + std::vector ids; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = -1; float bv = 0; + for (int v = 0; v < nv; ++v) { + if (taken[(size_t) v]) continue; + if (best < 0 || val(v) > bv) { best = v; bv = val(v); } + } + taken[(size_t) best] = 1; ids.push_back(best); + } + if (p.top_p < 1.0f) { + float mx = val(ids[0]); + for (int v : ids) mx = std::fmax(mx, val(v)); + double sum = 0; + for (int v : ids) sum += std::exp((double) val(v) - (double) mx); + double cum = 0; + int cut = (int) ids.size(); + for (size_t i = 0; i < ids.size(); ++i) { + cum += std::exp((double) val(ids[i]) - (double) mx) / sum; + if (cum >= (double) p.top_p) { cut = (int) i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < (int) ids.size() ? p.min_keep : (int) ids.size(); + return cut; + } + return (int) ids.size(); +} + +int run(const char* name, const std::vector& logits, int n_tokens, const strata::kernels::SamplerParams& p, + const std::vector& want, const std::vector& hist = {}, int hist_len = 0) { + float* d_l = nullptr; + int* d_o = nullptr; + check(cudaMalloc(&d_l, logits.size() * sizeof(float)), "malloc logits"); + check(cudaMalloc(&d_o, (size_t) n_tokens * sizeof(int)), "malloc out"); + check(cudaMemcpy(d_l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); + // -1 in every output slot first: a row the kernel leaves unwritten can never match (a verify window reads + // every row, so "no output" is a wrong answer, not a skipped one) + check(cudaMemset(d_o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); + int* d_h = nullptr; + if (hist_len > 0) { + check(cudaMalloc(&d_h, hist.size() * sizeof(int)), "malloc hist"); + check(cudaMemcpy(d_h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); + } + strata::kernels::sample_tokens(d_l, n_tokens, (int) (logits.size() / n_tokens), d_h, hist_len, p, d_o, + nullptr); + std::vector got((size_t) n_tokens); + check(cudaMemcpy(got.data(), d_o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + int bad = 0; + for (int t = 0; t < n_tokens; ++t) if (got[(size_t) t] != want[(size_t) t]) ++bad; + std::printf(" %-34s %s (%d of %d differ)", name, bad ? "*** WRONG ***" : "matches", bad, n_tokens); + if (bad) std::printf(" first: want %d got %d", want[0], got[0]); + std::printf("\n"); + cudaFree(d_l); + cudaFree(d_o); + if (d_h) cudaFree(d_h); + return bad; +} + +// The Philox draw, host side - a transcription of the kernel's `philox_uniform` so the SAMPLED pick (not +// just the greedy argmax) can be pinned against a reference. `__umulhi(a, b)` is the high half of a 32x32 +// multiply, spelled `(uint32_t)(((uint64_t) a * b) >> 32)` here. +struct PhiloxRound { + uint32_t& c0; uint32_t& c1; uint32_t& c2; uint32_t& c3; + void step(uint32_t k0, uint32_t k1) const { + const uint32_t hi0 = (uint32_t) (((uint64_t) 0x9E3779B9u * c0) >> 32); + const uint32_t hi1 = (uint32_t) (((uint64_t) 0xBB67AE85u * c2) >> 32); + const uint32_t lo0 = 0x9E3779B9u * c0; + const uint32_t lo1 = 0xBB67AE85u * c2; + const uint32_t n0 = hi1 ^ c1 ^ k0; + const uint32_t n1 = lo1; + const uint32_t n2 = hi0 ^ c3 ^ k1; + const uint32_t n3 = lo0; + c0 = n0; c1 = n1; c2 = n2; c3 = n3; + } +}; + +float host_philox_uniform(uint64_t seed, uint64_t counter) { + uint32_t c0 = (uint32_t) counter, c1 = (uint32_t) (counter >> 32); + uint32_t c2 = (uint32_t) seed, c3 = (uint32_t) (seed >> 32); + PhiloxRound r{c0, c1, c2, c3}; + for (int i = 0; i < 10; ++i) r.step((uint32_t) i, 0u); + return (float) (c0 >> 8) * (1.0f / 16777216.0f); +} + +// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order: +// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over +// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at +// (seed, counter + row). One penalties stage (issue #53: this reference used to repeat the kernel's second one). +int sampled_reference(const std::vector& l, const std::vector& hist, + const strata::kernels::SamplerParams& p, int row) { + auto penal = [&](float logit, int count) { + if (count <= 0) return logit; + if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; + logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; + return logit; + }; + auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; }; + const int nv = (int) l.size(); + const int KMAX = 64; // 1..64 as given; 0 (off) and wider keep the widest list, 64 + const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX); + std::vector sel_ids; + std::vector sel_logit; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = -1; float bv = 0; + for (int v = 0; v < nv; ++v) { + if (taken[(size_t) v]) continue; + const float s = penal(l[(size_t) v], count(v)); + if (best < 0 || s > bv) { best = v; bv = s; } + } + taken[(size_t) best] = 1; + sel_ids.push_back(best); sel_logit.push_back(bv); + } + // llama.cpp's order (issue #53): top_p over the whole top_k list, then min_p on its survivors + const int n_sel = (int) sel_ids.size(); + int n_keep = n_sel; + if (p.top_p < 1.0f) { + double sum = 0.0; + for (int i = 0; i < n_sel; ++i) sum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]); + double cum = 0.0; + int cut = n_sel; + for (int i = 0; i < n_sel; ++i) { + cum += std::exp((double) sel_logit[(size_t) i] - (double) sel_logit[0]) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < n_sel ? p.min_keep : n_sel; + 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; + auto scaled = [&](int i) { return sel_logit[(size_t) i] * inv_t; }; // one penalties stage, before (#53) + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); + const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); + double cum = 0.0; + int pick = sel_ids[(size_t) (n_keep - 1)]; + for (int i = 0; i < n_keep; ++i) { + cum += std::exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel_ids[(size_t) i]; break; } + } + return pick; +} + +// Survivors after the min_p + top_p cuts, in the sampled chain - the quantity an order or a threshold +// actually changes, used to assert a fixture can SEE the feature before asserting the kernel matches. +int sampled_cut(const std::vector& l, const std::vector& hist, const strata::kernels::SamplerParams& p) { + auto penal = [&](float logit, int count) { + if (count <= 0) return logit; + if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; + logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; + return logit; + }; + auto count = [&](int v) { int c = 0; for (int h : hist) if (h == v) ++c; return c; }; + const int nv = (int) l.size(); + const int KMAX = 64; + const int k = std::min(nv, (p.top_k > 0 && p.top_k < KMAX) ? p.top_k : KMAX); + std::vector sel; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = -1; float bv = 0; + for (int v = 0; v < nv; ++v) { + if (taken[(size_t) v]) continue; + const float s = penal(l[(size_t) v], count(v)); + if (best < 0 || s > bv) { best = v; bv = s; } + } + taken[(size_t) best] = 1; sel.push_back(bv); + } + int n_minp = (int) sel.size(); + if (p.min_p > 0.0f) { + const float thresh = sel[0] + std::log(p.min_p); + for (int i = 0; i < (int) sel.size(); ++i) + if (sel[(size_t) i] < thresh) { n_minp = i; break; } + } + if (p.top_p >= 1.0f) return n_minp; + double sum = 0.0; + for (int i = 0; i < n_minp; ++i) sum += std::exp((double) sel[(size_t) i] - (double) sel[0]); + double cum = 0.0; + int cut = n_minp; + for (int i = 0; i < n_minp; ++i) { + cum += std::exp((double) sel[(size_t) i] - (double) sel[0]) / sum; + if (cum >= (double) p.top_p) { cut = i + 1; break; } + } + if (cut < p.min_keep) cut = p.min_keep < n_minp ? p.min_keep : n_minp; + return cut; +} + +// ---- the kernel's own semantics, for the fixtures ---- +// +// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and +// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel` +// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits +// can be pinned exactly. On rows without those it is `sampled_reference`. +struct SelList { + std::vector ids; + std::vector logit; +}; + +// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n). +SelList mirror_select(const float* l, int nv, const std::vector& window, const strata::kernels::SamplerParams& p, + int k) { + std::vector s((size_t) nv); + for (int v = 0; v < nv; ++v) { + int c = 0; + for (int h : window) c += h == v; + float x = l[v]; + if (c > 0) { + if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat; + x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present; + } + s[(size_t) v] = x; + } + SelList out; + std::vector taken((size_t) nv, 0); + for (int i = 0; i < k; ++i) { + int best = nv; + float bv = -std::numeric_limits::infinity(); + for (int v = 0; v < nv; ++v) + if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; } + const int id = best < nv ? best : 0; + taken[(size_t) id] = 1; + out.ids.push_back(id); + out.logit.push_back(bv); + } + return out; +} + +// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw. +int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) { + 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; + auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; }; + float smx = scaled(0); + for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i)); + double sum = 0.0; + for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx); + const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row); + double cum = 0.0; + int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)]; + for (int i = 0; i < n_keep; ++i) { + cum += std::exp((double) scaled(i) - (double) smx) / sum; + if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; } + } + return pick; +} + +int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); } + +// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream` +// (nullptr: the legacy stream), -1 prefilled as in `run`. +struct DeviceRows { + float* l = nullptr; + int* h = nullptr; + int* o = nullptr; + int n_tokens = 0, nv = 0, hist_len = 0; + DeviceRows(const std::vector& logits, int n_tokens_, const std::vector& hist, int hist_len_) + : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) { + check(cudaMalloc(&l, logits.size() * sizeof(float)), "malloc logits"); + check(cudaMalloc(&o, (size_t) n_tokens * sizeof(int)), "malloc out"); + check(cudaMemcpy(l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy"); + if (hist_len > 0) { + check(cudaMalloc(&h, hist.size() * sizeof(int)), "malloc hist"); + check(cudaMemcpy(h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist"); + } + } + DeviceRows(const DeviceRows&) = delete; + DeviceRows& operator=(const DeviceRows&) = delete; + ~DeviceRows() { + cudaFree(l); + cudaFree(o); + if (h) cudaFree(h); + } + std::vector sample(const strata::kernels::SamplerParams& p, cudaStream_t stream) { + check(cudaMemset(o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out"); + strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream); + if (stream != nullptr) check(cudaStreamSynchronize(stream), "stream sync"); + std::vector got((size_t) n_tokens); + check(cudaMemcpy(got.data(), o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + return got; + } +}; + +// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties). +std::vector window_of(const std::vector& hist, int hist_len, int t, int last_n) { + if (hist_len <= 0 || last_n <= 0) return {}; + const int h = std::min(last_n, hist_len); + const int* row = hist.data() + (size_t) t * hist_len; + return std::vector(row + (hist_len - h), row + hist_len); +} + +// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects. +void bench_sampled() { + const int NV = 248320; + cudaStream_t s = nullptr; + check(cudaStreamCreate(&s), "stream"); + std::mt19937 rng(20); + std::normal_distribution g(0.0f, 3.0f); + for (int T : {1, 4, 8}) { + std::vector l((size_t) NV * T); + for (auto& v : l) v = g(rng); + float* d_l = nullptr; + int* d_o = nullptr; + check(cudaMalloc(&d_l, l.size() * sizeof(float)), "bench logits"); + check(cudaMalloc(&d_o, (size_t) T * sizeof(int)), "bench out"); + check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "bench copy"); + for (int k : {20, 64}) { + strata::kernels::SamplerParams p; + p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1; + for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + check(cudaStreamSynchronize(s), "bench warmup"); + cudaEvent_t e0, e1; + check(cudaEventCreate(&e0), "event"); + check(cudaEventCreate(&e1), "event"); + const int iters = 50; + check(cudaEventRecord(e0, s), "record"); + for (int it = 0; it < iters; ++it) { + p.counter = (uint64_t) it; + strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s); + } + check(cudaEventRecord(e1, s), "record"); + check(cudaEventSynchronize(e1), "bench sync"); + float ms = 0.0f; + check(cudaEventElapsedTime(&ms, e0, e1), "elapsed"); + std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k, + 1000.0 * (double) ms / iters); + cudaEventDestroy(e0); + cudaEventDestroy(e1); + } + cudaFree(d_l); + cudaFree(d_o); + } + cudaStreamDestroy(s); +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false, bench = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else if (std::string(argv[i]) == "--bench") bench = true; + else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; } + } + { + // the sampled path under test; ctest runs this binary once per path + auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; }; + std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)" + : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)" + : "split top_k (default)"); + } + if (bench) { + bench_sampled(); + return 0; + } + int bad = 0; + const int NV = 512, NT = 4; + + // ---- fixture 1: plain greedy. top_k = 0 (disabled), top_p = 1 (disabled), T = 1 -> argmax. + { + strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true; + std::mt19937 rng(3); std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) NV * NT); + for (auto& v : l) v = g(rng); + std::vector want((size_t) NT); + for (int t = 0; t < NT; ++t) want[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, p, false); + bad += run("greedy argmax", l, NT, p, want); + } + + // ---- fixture 2: THE ORDER FIXTURE. T = 0.5 sharpens the distribution enough that top_p = 0.5 cuts + // differently before and after the scaling, and the two orders then pick DIFFERENT tokens. + { + strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 0.5f; p.temperature = 0.5f; + p.min_keep = 1; p.greedy = true; + std::vector l((size_t) NV * NT, -1000.0f); + for (int t = 0; t < NT; ++t) { + // a flat-ish head so the cumulative mass crosses 0.5 inside it, and one clear leader + l[(size_t) t * NV + 0] = 3.0f; + for (int v = 1; v < 8; ++v) l[(size_t) t * NV + v] = 2.6f - 0.05f * (float) v; + } + std::vector want((size_t) NT), other((size_t) NT); + for (int t = 0; t < NT; ++t) { + const std::vector row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); + want[(size_t) t] = reference_pick(row, p, false); // the SPECIFIED order + other[(size_t) t] = reference_pick(row, p, true); // temperature first + } + // If the two orders agree on this fixture the test cannot see the order, and saying "the kernel + // matches the spec" would be vacuous. + // GREEDY CANNOT SEE THE ORDER, and saying otherwise would be a vacuous check: no filter removes the + // global argmax, and temperature is monotonic, so the greedy pick is order-independent by + // construction. What the order changes is the top_p CUT, so the fixture is asserted to be + // order-SENSITIVE at the cut, which is a property of the fixture rather than of the kernel. + int cut_spec = 0, cut_alt = 0; + for (int t = 0; t < NT; ++t) { + const std::vector row(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); + cut_spec += reference_cut(row, p, false); + cut_alt += reference_cut(row, p, true); + } + const bool distinguishable = (cut_spec != cut_alt); + std::printf(" %-34s %s (survivors: spec %d, temp-first %d)\n", "order is observable on this fixture", + distinguishable ? "yes" : "*** NO - THE FIXTURE CANNOT SEE THE ORDER ***", cut_spec, + cut_alt); + if (!distinguishable) ++bad; + // greedy is still checked here, but as an ARGMAX check, not an order check + bad += run("greedy over this fixture", l, NT, p, want); + } + + // ---- fixture 3: greedy consumes NO random number. Two runs with different seeds must agree, or the + // seeded streams diverge between greedy and sampled runs - which docs/sampling.md §3 calls out. + { + strata::kernels::SamplerParams a; a.top_k = 20; a.top_p = 0.95f; a.temperature = 1.0f; a.greedy = true; a.seed = 1; + strata::kernels::SamplerParams b = a; b.seed = 999999; + std::mt19937 rng(5); std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) NV * NT); + for (auto& v : l) v = g(rng); + std::vector wa((size_t) NT); + for (int t = 0; t < NT; ++t) wa[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, a, false); + float* d_l = nullptr; int *d_a = nullptr, *d_b = nullptr; + check(cudaMalloc(&d_l, l.size() * sizeof(float)), "m1"); + check(cudaMalloc(&d_a, (size_t) NT * sizeof(int)), "m2"); + check(cudaMalloc(&d_b, (size_t) NT * sizeof(int)), "m3"); + check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "c1"); + strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, a, d_a, nullptr); + strata::kernels::sample_tokens(d_l, NT, NV, nullptr, 0, b, d_b, nullptr); + std::vector ga((size_t) NT), gb((size_t) NT); + check(cudaMemcpy(ga.data(), d_a, ga.size() * sizeof(int), cudaMemcpyDeviceToHost), "g1"); + check(cudaMemcpy(gb.data(), d_b, gb.size() * sizeof(int), cudaMemcpyDeviceToHost), "g2"); + int mismatch = 0, wrong = 0; + for (int t = 0; t < NT; ++t) { + if (ga[(size_t) t] != gb[(size_t) t]) ++mismatch; + if (ga[(size_t) t] != wa[(size_t) t]) ++wrong; + } + std::printf(" %-34s %s (seed-independent: %d differ; vs reference: %d wrong)\n", + "greedy ignores the seed", (!mismatch && !wrong) ? "matches" : "*** WRONG ***", mismatch, + wrong); + bad += mismatch + wrong; + cudaFree(d_l); cudaFree(d_a); cudaFree(d_b); + } + + + // ---- fixture 4: PENALTIES. Two sub-cases, each built so the rule it tests decides the answer. + { + // host reference for the penalty stage, transcribed from llama_sampler_penalties_apply + auto penal = [](float logit, int count, const strata::kernels::SamplerParams& p) { + if (count <= 0) return logit; + if (logit <= 0.0f) logit *= p.penalty_repeat; else logit /= p.penalty_repeat; + logit -= (float) count * p.penalty_freq + (count > 0 ? 1.0f : 0.0f) * p.penalty_present; + return logit; + }; + auto pick = [&](const std::vector& l, const std::vector& hist, + const strata::kernels::SamplerParams& p, bool divide_unconditionally) { + int best = 0; float bv = 0; bool first = true; + for (int v = 0; v < (int) l.size(); ++v) { + int c = 0; for (int h : hist) if (h == v) ++c; + float s; + if (divide_unconditionally && c > 0) { + s = l[(size_t) v] / p.penalty_repeat + - (float) c * p.penalty_freq - (c > 0 ? 1.0f : 0.0f) * p.penalty_present; + } else { + s = penal(l[(size_t) v], c, p); + } + if (first || s > bv) { bv = s; best = v; first = false; } + } + return best; + }; + + const int NV2 = 8, NT2 = 2; + strata::kernels::SamplerParams p; p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; + p.greedy = true; p.penalty_last_n = 4; p.penalty_repeat = 2.0f; + + // A: ALL logits negative, so the multiply-or-divide rule decides the argmax + std::vector la((size_t) NV2 * NT2, -8.0f); + for (int t = 0; t < NT2; ++t) { + la[(size_t) t * NV2 + 0] = -1.0f; // in the history -> penalised + la[(size_t) t * NV2 + 1] = -1.2f; // not penalised -> should win + } + std::vector hist_a((size_t) NT2 * 4, -1); + for (int t = 0; t < NT2; ++t) hist_a[(size_t) t * 4 + 0] = 0; + std::vector want_a((size_t) NT2), alt_a((size_t) NT2); + for (int t = 0; t < NT2; ++t) { + const std::vector row(la.begin() + (size_t) t * NV2, la.begin() + (size_t) (t + 1) * NV2); + const std::vector h(hist_a.begin() + (size_t) t * 4, hist_a.begin() + (size_t) (t + 1) * 4); + want_a[(size_t) t] = pick(row, h, p, false); + alt_a[(size_t) t] = pick(row, h, p, true); // divide unconditionally + } + const bool A_visible = want_a[0] != alt_a[0]; + std::printf(" %-34s %s (multiply-rule %d, divide-always %d)\n", + "multiply-or-divide is observable", A_visible ? "yes" : "*** NO ***", want_a[0], + alt_a[0]); + if (!A_visible) ++bad; + else bad += run("penalties: repeat on negatives", la, NT2, p, want_a, hist_a, 4); + + // B: the PRESENCE penalty is a boolean, so two occurrences cost the same as one. The runner's margin + // is inside the difference between one and two applications. + std::vector lb((size_t) NV2 * NT2, -8.0f); + for (int t = 0; t < NT2; ++t) { + lb[(size_t) t * NV2 + 0] = 5.0f; // seen twice -> penalised ONCE (presence) + freq*2 + lb[(size_t) t * NV2 + 1] = 3.4f; // unseen + } + std::vector hist_b((size_t) NT2 * 4, -1); + for (int t = 0; t < NT2; ++t) { + hist_b[(size_t) t * 4 + 0] = 0; + hist_b[(size_t) t * 4 + 1] = 0; // twice + } + strata::kernels::SamplerParams q = p; q.penalty_present = 1.5f; q.penalty_freq = 0.0f; + std::vector want_b((size_t) NT2); + for (int t = 0; t < NT2; ++t) { + const std::vector row(lb.begin() + (size_t) t * NV2, lb.begin() + (size_t) (t + 1) * NV2); + const std::vector h(hist_b.begin() + (size_t) t * 4, hist_b.begin() + (size_t) (t + 1) * 4); + want_b[(size_t) t] = pick(row, h, q, false); + } + std::printf(" %-34s want token %d (with present=1.5, token 0 goes 5.0/2 - 1.5 = 1.0 vs token 1 at " + "3.4)\n", "presence penalty is a boolean", want_b[0]); + bad += run("penalties: presence is boolean", lb, NT2, q, want_b, hist_b, 4); + } + + // ---- fixture 5: TEMPERATURE 0 MUST STILL RETURN THE ARGMAX. Regression test for a real bug. + // + // The greedy branch used to read `apply_penalties(l[v] * inv_t, ...)`. `inv_t` is 0.0f whenever + // temperature <= 0, so at temperature 0 EVERY logit became 0.0f and the argmax returned index 0 - the + // sampler emitted token 0 forever, whatever the model predicted. OpenAI clients send `temperature: 0` + // for greedy decoding, so this was reachable from any ordinary client. + // + // It survived because EVERY other greedy fixture in this file sets temperature = 1.0f, where inv_t = 1.0 + // and the extra multiply is harmless. The bug needs temperature <= 0 to appear, and no fixture used it. + // The fixture below makes token 0 the WORST token in every row, so returning 0 is unambiguously wrong. + { + const int NV3 = 512, NT3 = 4; + std::vector l((size_t) NV3 * NT3, -5.0f); + std::vector want((size_t) NT3); + for (int t = 0; t < NT3; ++t) { + const int best = 100 + t; // the argmax is never token 0 + l[(size_t) t * NV3 + best] = 3.0f; + l[(size_t) t * NV3 + 0] = -9.0f; // token 0 is the worst in the row + want[(size_t) t] = best; + } + strata::kernels::SamplerParams p0; + p0.top_k = 0; p0.top_p = 1.0f; p0.temperature = 0.0f; p0.greedy = false; + bad += run("T=0 greedy=false is the argmax", l, NT3, p0, want); + + strata::kernels::SamplerParams p1 = p0; p1.greedy = true; + bad += run("T=0 greedy=true is the argmax", l, NT3, p1, want); + + strata::kernels::SamplerParams p2 = p0; p2.greedy = true; p2.temperature = 1.0f; + bad += run("T=1 greedy=true is the argmax", l, NT3, p2, want); + } + + // ---- fixture 6: PENALTIES IN THE SAMPLED CHAIN. Fixture 4 pins the greedy (argmax) path; the sampled + // chain gets its own reference (the full chain with the host Philox) and its own observability check: with + // the penalties on, the history row's favourite must LOSE a pick it would win penalty-free. + { + const int NV2 = 8, NT2 = 2; + strata::kernels::SamplerParams p; + p.top_k = 5; p.top_p = 0.9f; p.temperature = 0.8f; p.seed = 9; p.counter = 0; + p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.2f; p.penalty_present = 0.6f; + + std::vector l((size_t) NV2 * NT2, -8.0f); + std::vector hist((size_t) NT2 * 4, -1); + for (int t = 0; t < NT2; ++t) { + float* row = l.data() + (size_t) t * NV2; + row[0] = 9.0f; row[1] = 4.5f; row[2] = 4.4f; row[3] = 4.3f; // token 0 leads clean (9 vs 4.5) + hist[(size_t) t * 4 + 0] = 0; // and falls to 2.2/2.0 penalised + hist[(size_t) t * 4 + 1] = t == 1 ? 0 : -1; // (repeat 3, freq, presence) + } + std::vector want((size_t) NT2), clean((size_t) NT2); + strata::kernels::SamplerParams clean_p = p; + clean_p.penalty_last_n = 0; clean_p.penalty_repeat = 1.0f; + clean_p.penalty_freq = 0.0f; clean_p.penalty_present = 0.0f; + for (int t = 0; t < NT2; ++t) { + const std::vector row(l.begin() + (size_t) t * NV2, l.begin() + (size_t) (t + 1) * NV2); + const std::vector h(hist.begin() + (size_t) t * 4, hist.begin() + (size_t) (t + 1) * 4); + want[(size_t) t] = sampled_reference(row, h, p, t); + clean[(size_t) t] = sampled_reference(row, h, clean_p, t); + } + const bool visible = want[0] != clean[0] || want[1] != clean[1]; + std::printf(" %-34s %s (penalised picks %d/%d, clean %d/%d)\n", + "sampled penalties are observable", visible ? "yes" : "*** NO ***", want[0], want[1], + clean[0], clean[1]); + if (!visible) ++bad; + else bad += run("sampled chain: penalties + top_k/p", l, NT2, p, want, hist, 4); + } + + // ---- fixture 7: MIN_P. The cut is a PREFIX of the descending top_k list (logit >= max + log(min_p)), + // so the fixture asserts the survivor count moves with the threshold (the observability half) and that + // the kernel's pick equals the reference's through the full sampled chain (the correctness half). + { + const int NV3 = 8, NT3 = 2; + std::vector l((size_t) NV3 * NT3, -8.0f); + for (int t = 0; t < NT3; ++t) { + float* row = l.data() + (size_t) t * NV3; + row[0] = 4.0f; row[1] = 3.5f; row[2] = 3.2f; row[3] = 3.1f; // gaps keep the cut off the + row[4] = 2.0f; // logf/rounding knife edge + } + strata::kernels::SamplerParams base; + base.top_k = 6; base.top_p = 1.0f; base.temperature = 0.9f; base.seed = 77; + + int c0 = 0, c05 = 0, c09 = 0; + for (int t = 0; t < NT3; ++t) { + const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); + strata::kernels::SamplerParams q = base; q.min_p = 0.0f; + c0 += sampled_cut(row, {}, q); + q.min_p = 0.5f; c05 += sampled_cut(row, {}, q); + q.min_p = 0.9f; c09 += sampled_cut(row, {}, q); + } + const bool visible = c0 > c05 && c05 > c09 && c09 >= NT3; + std::printf(" %-34s %s (survivors: min_p 0 -> %d, 0.5 -> %d, 0.9 -> %d)\n", + "min_p cut is observable", visible ? "yes" : "*** NO ***", c0, c05, c09); + if (!visible) ++bad; + + for (float mp : {0.0f, 0.5f, 0.9f}) { + strata::kernels::SamplerParams q = base; q.min_p = mp; + std::vector want((size_t) NT3); + for (int t = 0; t < NT3; ++t) { + const std::vector row(l.begin() + (size_t) t * NV3, l.begin() + (size_t) (t + 1) * NV3); + want[(size_t) t] = sampled_reference(row, {}, q, t); + } + char name[64]; + std::snprintf(name, sizeof name, "sampled chain: min_p=%.1f", (double) mp); + bad += run(name, l, NT3, q, want); + } + } + + // ---- fixture 8: THE PENALTY WINDOW IS THE TAIL. With an 8-entry history and penalty_last_n = 4, only + // the LAST four entries count: a token punished in the old half must come back to full strength, and one + // punished in the tail half stays down. The reference counts the same tail; the observability check runs + // the reference once more WITHOUT the clamp (counting all 8) and requires the picks to differ. + { + const int NV4 = 8; + strata::kernels::SamplerParams p; + p.top_k = 0; p.top_p = 1.0f; p.temperature = 1.0f; p.greedy = true; + p.penalty_last_n = 4; p.penalty_repeat = 3.0f; p.penalty_freq = 0.3f; p.penalty_present = 0.5f; + + std::vector l((size_t) NV4, -8.0f); + l[0] = 6.0f; l[3] = 6.5f; // token 0 leads clean; token 3 is the tail offender + std::vector hist = {0, 0, 0, 0, 3, 3, 3, 3}; // token 0 old (out), token 3 in the tail + + auto pick_clamped = [&](bool clamp) { + int best = 0; float bv = 0; bool first = true; + for (int v = 0; v < NV4; ++v) { + int c = 0; + for (int i = 0; i < (clamp ? 4 : 8); ++i) if (hist[(size_t) (8 - (clamp ? 4 : 8) + i)] == v) ++c; + float logit = l[(size_t) v]; + if (c > 0) { logit = logit <= 0.0f ? logit * p.penalty_repeat : logit / p.penalty_repeat; + logit -= (float) c * p.penalty_freq + p.penalty_present; } + if (first || logit > bv) { bv = logit; best = v; first = false; } + } + return best; + }; + const int want = pick_clamped(true), unclamped = pick_clamped(false); + const bool visible = want != unclamped; + std::printf(" %-34s %s (clamped pick %d, full-history pick %d)\n", + "penalty window clamp is observable", visible ? "yes" : "*** NO ***", want, unclamped); + if (!visible) ++bad; + else bad += run("penalty window: tail only", {l.begin(), l.end()}, 1, p, {want}, hist, 8); + } + + // ---- fixture 9: ONE PENALTIES STAGE (issue #53), against an independently computed distribution, not the + // reference above (which had copied the kernel's mistake). Two tokens with equal logits, token 0 in the + // history, presence penalty 1.5, temperature 0.7: llama.cpp's chain gives token 0 the logit (0 - 1.5) / 0.7, + // P = 1 / (1 + exp(1.5 / 0.7)) = 0.1050; a second penalty after the temperature made it 0.0255. Over 8,000 + // draws the kernel's share of token 0 must be near 0.105 (4 sigma = 0.014), and its picks must equal the + // reference's draw for draw. + { + const int NT9 = 8000; + strata::kernels::SamplerParams p; + p.top_k = 2; p.top_p = 1.0f; p.min_p = 0.0f; p.temperature = 0.7f; p.seed = 53; p.counter = 0; + p.penalty_last_n = 1; p.penalty_repeat = 1.0f; p.penalty_freq = 0.0f; p.penalty_present = 1.5f; + std::vector l((size_t) 2 * NT9, 0.0f); + std::vector hist((size_t) NT9, 0); + std::vector want((size_t) NT9); + int zeros = 0; + for (int t = 0; t < NT9; ++t) { + want[(size_t) t] = sampled_reference({0.0f, 0.0f}, {0}, p, t); + zeros += want[(size_t) t] == 0; + } + const double expect = 1.0 / (1.0 + std::exp(1.5 / 0.7)), share = (double) zeros / NT9; + const bool near = std::fabs(share - expect) < 0.014; + std::printf(" %-34s %s (token 0 drawn %.4f of %d, expected %.4f; twice-penalised would be 0.0255)\n", + "one penalties stage (#53)", near ? "yes" : "*** NO ***", share, NT9, expect); + if (!near) ++bad; + bad += run("sampled chain: #53's example", l, NT9, p, want, hist, 1); + } + + // ---- fixture 10: TOP_P BEFORE MIN_P (llama.cpp's order). Probabilities 0.4 / 0.3 / 0.2 / 0.1, top_p 0.75, + // min_p 0.3 (keeps p >= 0.12): top_p over all four keeps three (0.4 + 0.3 < 0.75 <= 0.9) and min_p keeps them; + // min_p first would drop 0.1, renormalise, and top_p would then stop at two (0.444 + 0.333 >= 0.75). So token + // 2 must be drawn sometimes - never in the old order - and every pick must equal the reference's. + { + const int NT10 = 256; + strata::kernels::SamplerParams p; + p.top_k = 4; p.top_p = 0.75f; p.min_p = 0.3f; p.temperature = 1.0f; p.seed = 10; p.counter = 0; + const float lp[4] = {std::log(0.4f), std::log(0.3f), std::log(0.2f), std::log(0.1f)}; + std::vector row = {lp[0], lp[1], lp[2], lp[3], -30.0f, -30.0f, -30.0f, -30.0f}; + std::vector l; + for (int t = 0; t < NT10; ++t) l.insert(l.end(), row.begin(), row.end()); + std::vector want((size_t) NT10); + int twos = 0; + for (int t = 0; t < NT10; ++t) { + want[(size_t) t] = sampled_reference(row, {}, p, t); + twos += want[(size_t) t] == 2; + } + std::printf(" %-34s %s (token 2 drawn %d of %d times)\n", "top_p before min_p is observable", + twos > 0 ? "yes" : "*** NO ***", twos, NT10); + if (twos == 0) ++bad; + bad += run("sampled chain: top_p then min_p", l, NT10, p, want); + } + + // ---- fixture 11: A STALE HISTORY WITH last_n = 0 IS INERT (PR #59). A caller can hand over a history buffer + // from a previous penalised request while this request disables the penalties - the run must equal the + // no-history run in both kernels, and the bitmap the launch did not size must stay untouched. + { + std::mt19937 rng(11); std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) NV * NT); + for (auto& v : l) v = g(rng); + std::vector hist((size_t) NT * 8, -1); + for (int t = 0; t < NT; ++t) hist[(size_t) t * 8] = 3; + + strata::kernels::SamplerParams p; + p.top_k = 20; p.top_p = 0.95f; p.temperature = 0.8f; p.seed = 5; + std::vector want((size_t) NT); + for (int t = 0; t < NT; ++t) + want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, + l.begin() + (size_t) (t + 1) * NV}, {}, p, t); + bad += run("stale history, last_n=0 (sampled)", l, NT, p, want, hist, 8); + + strata::kernels::SamplerParams gp = p; gp.greedy = true; gp.top_k = 0; gp.top_p = 1.0f; + std::vector gwant((size_t) NT); + for (int t = 0; t < NT; ++t) + gwant[(size_t) t] = reference_pick({l.begin() + (size_t) t * NV, + l.begin() + (size_t) (t + 1) * NV}, gp, false); + bad += run("stale history, last_n=0 (greedy)", l, NT, gp, gwant, hist, 8); + } + + // ---- fixture 12: ONE HISTORY PER ROW (engine 0.1.19). A verify window samples T rows, and row t's pick + // follows the drafts 1..t: its penalties must count them. The engine used to stage row 0 alone, so rows + // 1..T-1 read slots nobody wrote. Here every row gets `penalty_rows`' history and is pinned against a + // per-row scalar reference; the fixture first asserts it can SEE the difference - with row 0's history + // copied to every row (the nearest well-defined stand-in for the old staging) some row must pick differently. + // Row t's own newest token (window[t]) is its favourite by a margin the presence penalty overturns. + { + auto greedy_pen = [](const std::vector& l, const std::vector& hist, + const strata::kernels::SamplerParams& p) { + int best = 0; float bv = 0; bool first = true; + for (int v = 0; v < (int) l.size(); ++v) { + int c = 0; for (int h : hist) if (h == v) ++c; + float s = l[(size_t) v]; + if (c > 0) { + if (s <= 0.0f) s *= p.penalty_repeat; else s /= p.penalty_repeat; + s -= (float) c * p.penalty_freq + p.penalty_present; + } + if (first || s > bv) { bv = s; best = v; first = false; } + } + return best; + }; + std::mt19937 rng(12); std::normal_distribution g(0.0f, 1.0f); + const int TAIL = 5000; // longer than the widest window below + std::vector tail((size_t) TAIL); + for (auto& v : tail) v = (int32_t) (rng() % NV); + int observable = 0, rows_checked = 0; + for (int T : {1, 2, 4, 8}) { + for (int H : {1, 64, 1024, 4096}) { + std::vector window((size_t) T); + for (int t = 0; t < T; ++t) window[(size_t) t] = (int32_t) (100 + 37 * t); // distinct, in range + std::vector rows((size_t) T * H); + strata::kernels::penalty_rows(tail.data(), TAIL, window.data(), T, H, rows.data()); + std::vector l((size_t) T * NV); + for (auto& v : l) v = g(rng); + for (int t = 0; t < T; ++t) l[(size_t) t * NV + window[(size_t) t]] = 5.0f; + strata::kernels::SamplerParams gp; + gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f; + gp.penalty_last_n = H; gp.penalty_present = 4.0f; + strata::kernels::SamplerParams sp2; + sp2.top_k = 20; sp2.top_p = 0.9f; sp2.temperature = 0.7f; sp2.seed = 1000 + (uint64_t) H; + sp2.counter = 77; sp2.penalty_last_n = H; sp2.penalty_present = 4.0f; sp2.penalty_repeat = 1.1f; + std::vector gwant((size_t) T), swant((size_t) T), rows_int(rows.begin(), rows.end()); + for (int t = 0; t < T; ++t) { + const std::vector lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); + const std::vector own(rows.begin() + (size_t) t * H, rows.begin() + (size_t) (t + 1) * H); + const std::vector row0(rows.begin(), rows.begin() + H); + gwant[(size_t) t] = greedy_pen(lr, own, gp); + swant[(size_t) t] = sampled_reference(lr, own, sp2, t); + if (t > 0 && greedy_pen(lr, row0, gp) != gwant[(size_t) t]) ++observable; + ++rows_checked; + } + char name[64]; + std::snprintf(name, sizeof name, "per-row history T=%d H=%d greedy", T, H); + bad += run(name, l, T, gp, gwant, rows_int, H); + std::snprintf(name, sizeof name, "per-row history T=%d H=%d sampled", T, H); + bad += run(name, l, T, sp2, swant, rows_int, H); + } + } + std::printf(" %-34s %s (%d drafted rows pick differently with row 0's history, of %d rows)\n", + "per-row histories are observable", observable > 0 ? "yes" : "*** NO ***", observable, + rows_checked); + if (observable == 0) ++bad; + } + + // ---- fixture 13: HISTORY IDS OUTSIDE THE VOCABULARY ARE IGNORED. The bitmap is sized for n_vocab bits; + // an id >= n_vocab used to set a bit past its end (a shared-memory write out of bounds - compute-sanitizer + // memcheck reports it). They can never be a candidate, so the result equals the reference without them. + { + std::mt19937 rng(13); std::normal_distribution g(0.0f, 1.0f); + const int H = 16; + std::vector l((size_t) NV * NT); + for (auto& v : l) v = g(rng); + std::vector hist((size_t) NT * H, -1), valid_only((size_t) NT * H, -1); + const int junk[] = {NV, NV + 1000, 0x7fffffff, -5, 1 << 20}; + for (int t = 0; t < NT; ++t) { + for (int j = 0; j < H; ++j) { + const bool bogus = j % 3 == 0; + const int v = bogus ? junk[(size_t) (j / 3) % 5] : (int) (rng() % NV); + hist[(size_t) t * H + j] = v; + if (!bogus) valid_only[(size_t) t * H + j] = v; + } + l[(size_t) t * NV + hist[(size_t) t * H + 1]] = 4.0f; // a penalised favourite, so penalties matter + } + strata::kernels::SamplerParams gp; + gp.greedy = true; gp.temperature = 0.0f; gp.top_k = 0; gp.top_p = 1.0f; + gp.penalty_last_n = H; gp.penalty_present = 3.0f; + strata::kernels::SamplerParams sp2 = gp; + sp2.greedy = false; sp2.temperature = 0.8f; sp2.top_k = 20; sp2.top_p = 0.95f; sp2.seed = 13; + std::vector gwant((size_t) NT), swant((size_t) NT); + for (int t = 0; t < NT; ++t) { + const std::vector lr(l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV); + const std::vector ok(valid_only.begin() + (size_t) t * H, valid_only.begin() + (size_t) (t + 1) * H); + { // the greedy reference with the penalty (reference_pick has none) + int best = 0; float bv = 0; bool first = true; + for (int v = 0; v < NV; ++v) { + int c = 0; for (int h : ok) if (h == v) ++c; + float s = lr[(size_t) v]; + if (c > 0) { if (s <= 0.0f) s *= gp.penalty_repeat; else s /= gp.penalty_repeat; s -= gp.penalty_present; } + if (first || s > bv) { bv = s; best = v; first = false; } + } + gwant[(size_t) t] = best; + } + swant[(size_t) t] = sampled_reference(lr, ok, sp2, t); + } + bad += run("out-of-vocab history ids (greedy)", l, NT, gp, gwant, hist, H); + bad += run("out-of-vocab history ids (sampled)", l, NT, sp2, swant, hist, H); + } + + // ---- fixture 14: THE top_k CONTRACT. 1..64 as given; 0 ("off") and anything wider use the widest list the + // kernel keeps, 64 - and every row is written (the sampled kernel used to print an error for 0 and leave the + // row unwritten, which a verify window then read as a token; `run` pre-fills -1 so that fails here). + { + std::mt19937 rng(14); std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) NV * NT); + for (auto& v : l) v = g(rng) * 0.3f; // flat: the 64-wide list matters to the draw + strata::kernels::SamplerParams p64; + p64.top_k = 64; p64.top_p = 1.0f; p64.temperature = 1.5f; p64.seed = 14; + std::vector want((size_t) NT); + for (int t = 0; t < NT; ++t) + want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * NV, l.begin() + (size_t) (t + 1) * NV}, + {}, p64, t); + bad += run("sampled top_k=64", l, NT, p64, want); + strata::kernels::SamplerParams p0 = p64; p0.top_k = 0; + bad += run("sampled top_k=0 means 64", l, NT, p0, want); + strata::kernels::SamplerParams p100 = p64; p100.top_k = 100; + bad += run("sampled top_k=100 means 64", l, NT, p100, want); + strata::kernels::SamplerParams pneg = p64; pneg.top_k = -3; + bad += run("sampled top_k=-3 means 64", l, NT, pneg, want); + } + + // ---- fixture 15: `penalty_rows`, host only, against the plain definition: row t = the last h tokens of + // tail + window[0..t], -1 padded in front. Covers a tail shorter than, equal to and longer than h, and row 0 + // equal to the single row the engine staged before 0.1.19. + { + int wrong = 0, cases = 0; + for (int n_tail : {0, 1, 5, 63, 64, 65, 300}) { + for (int T : {1, 3, 8}) { + for (int h : {1, 4, 64, 100}) { + std::vector tail((size_t) n_tail), window((size_t) T); + for (int i = 0; i < n_tail; ++i) tail[(size_t) i] = 1000 + i; + for (int i = 0; i < T; ++i) window[(size_t) i] = 5000 + i; + std::vector rows((size_t) T * h, 12345); + strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data()); + for (int t = 0; t < T; ++t) { + std::vector seq(tail); + seq.insert(seq.end(), window.begin(), window.begin() + t + 1); + std::vector expect((size_t) h, -1); + const int take = (int) std::min((size_t) h, seq.size()); + for (int j = 0; j < take; ++j) expect[(size_t) (h - take + j)] = seq[seq.size() - take + j]; + if (!std::equal(expect.begin(), expect.end(), rows.begin() + (size_t) t * h)) ++wrong; + ++cases; + } + // row 0 = the old single-row staging: consumed tail, then the fed-back head last + std::vector old((size_t) h, -1); + const int take0 = (int) std::min(h, (int64_t) n_tail + 1); + for (int j = 0; j < take0 - 1; ++j) old[(size_t) (h - take0 + j)] = tail[(size_t) (n_tail - (take0 - 1) + j)]; + old[(size_t) (h - 1)] = window[0]; + if (!std::equal(old.begin(), old.end(), rows.begin())) ++wrong; + ++cases; + } + } + } + std::printf(" %-34s %s (%d of %d rows differ)\n", "penalty_rows layout", wrong ? "*** WRONG ***" : "matches", + wrong, cases); + bad += wrong; + } + + // A continuous stream and individual decode calls consume the same draw counters. + { + constexpr int count = 32, vocab = 16; + std::vector uniform(count * vocab, 0.0f); + float* input = nullptr; + int* output = nullptr; + check(cudaMalloc(&input, uniform.size() * sizeof(float)), "counter logits"); + check(cudaMalloc(&output, count * sizeof(int)), "counter output"); + check(cudaMemcpy(input, uniform.data(), uniform.size() * sizeof(float), cudaMemcpyHostToDevice), "counter upload"); + strata::kernels::SamplerParams p; + p.top_k = vocab; p.top_p = 1.0f; p.seed = 123; p.counter = (uint64_t(1) << 32) + 7; + strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr); + std::vector batch(count), singles(count), repeated(count); + check(cudaMemcpy(batch.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter batch"); + for (int i = 0; i < count; ++i) { + auto one = p; one.counter += i; + strata::kernels::sample_tokens(input, 1, vocab, nullptr, 0, one, output + i, nullptr); + } + check(cudaMemcpy(singles.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter singles"); + strata::kernels::sample_tokens(input, count, vocab, nullptr, 0, p, output, nullptr); + check(cudaMemcpy(repeated.data(), output, count * sizeof(int), cudaMemcpyDeviceToHost), "counter repeated"); + bool varies = false; + for (int i = 1; i < count; ++i) varies |= batch[i] != batch[0]; + const bool valid = batch == singles && batch == repeated && varies; + std::printf(" sampler draw counter segmentation/repeat: %s\n", valid ? "PASS" : "FAIL"); + bad += !valid; + cudaFree(input); cudaFree(output); + } + + // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list + // through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN + // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching + // top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order + // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and + // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must + // come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the + // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the + // one-block fallback) and 1,000. + { + const float inf = std::numeric_limits::infinity(); + const float qnan = std::numeric_limits::quiet_NaN(); + int wrong = 0, probes = 0, sentinels = 0; + for (int nv : {248320, 100003, 262144, 262145, 1000}) { + const int T = 4, H = 64; + std::mt19937 rng((unsigned) (1600 + nv)); + std::normal_distribution g(0.0f, 1.0f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere + auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); }; + // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf + float* r0 = l.data(); + for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f; + r0[nv / 2] = inf; + r0[nv - 1] = inf; + // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf + float* r1 = l.data() + (size_t) nv; + for (int v = 0; v < nv; ++v) { + r1[v] = -std::fabs(r1[v]); + if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f; + } + r1[3] = inf; + // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all + float* r2 = l.data() + (size_t) 2 * nv; + for (int v = 0; v < nv; ++v) r2[v] = -inf; + for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f; + r2[spread(500)] = qnan; + r2[spread(501)] = qnan; + r2[spread(502)] = inf; + // row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the + // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count + // (3.75, 3.5, ...), values the quarter-step logits share. + float* r3 = l.data() + (size_t) 3 * nv; + std::vector hist((size_t) T * H, -1); + int* h3 = hist.data() + (size_t) 3 * H; + const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2}; + int hn = 0; + for (int e : edges) + if (e < nv && e != nv / 2) { + h3[hn++] = e; + if (hn % 3 == 0) h3[hn++] = e; // counted twice + r3[e] = 9.0f; + } + h3[hn++] = nv; // ignored: outside + h3[hn++] = nv + 77; + h3[hn++] = -5; + for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f; + r3[nv / 2] = inf; // not in the window + + strata::kernels::SamplerParams base; + base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16; + base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f; + base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax)); + DeviceRows rows(l, T, hist, H); + for (int top_k = 0; top_k <= 66; ++top_k) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64 + p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut) + p.counter = (uint64_t) top_k; + const int k = sampled_k(p.top_k, nv); + const std::vector got = rows.sample(p, nullptr); + for (int t = 0; t < T; ++t) { + const int want = lists[(size_t) t].ids[(size_t) (k - 1)]; + sentinels += (t == 2 && k > 11); + ++probes; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t, + p.top_k, k - 1, want, got[(size_t) t]); + ++wrong; + } + } + } + } + // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule + std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties", + wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels); + bad += wrong + (sentinels == 0); + } + + // ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps, + // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1, + // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of + // each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this + // regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie + // with another kept token, or the tie rule would go untested. + { + const int T = 17, H = 64; + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 17 stream"); + int wrong = 0, draws = 0, tied = 0; + for (int nv : {248320, 512}) { + std::mt19937 rng((unsigned) (1700 + nv)); + std::normal_distribution g(0.0f, 1.5f); + std::vector l((size_t) nv * T); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + if (nv == 512) + for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups + std::vector hist((size_t) T * H); + for (int t = 0; t < T; ++t) { + const float* row = l.data() + (size_t) t * nv; + const float mx = *std::max_element(row, row + nv); + std::vector head; + for (int v = 0; v < nv; ++v) + if (row[v] >= mx - 1.0f) head.push_back(v); + for (int j = 0; j < H; ++j) + hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv) + : head[(size_t) (rng() % (unsigned) head.size())]; + } + DeviceRows rows(l, T, hist, H); + int config = 0; + for (int pen = 0; pen < 2; ++pen) { + strata::kernels::SamplerParams base; + base.temperature = 2.5f; base.seed = 17; + base.penalty_last_n = pen ? H : 0; + base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f; + const int kmax = sampled_k(64, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n), + base, kmax)); + for (int top_k : {1, 20, 64}) + for (float top_p : {0.9f, 1.0f}) + for (float min_p : {0.0f, 0.05f}) + for (cudaStream_t st : {(cudaStream_t) nullptr, cs}) { + strata::kernels::SamplerParams p = base; + p.top_k = top_k; p.top_p = top_p; p.min_p = min_p; + p.counter = (uint64_t) (1000 * ++config); + const int k = sampled_k(top_k, nv); + const std::vector got = rows.sample(p, st); + for (int t = 0; t < T; ++t) { + const SelList& sl = lists[(size_t) t]; + const int want = mirror_pick(sl, k, p, t); + ++draws; + int same = 0; + for (int i = 0; i < k; ++i) { + if (sl.ids[(size_t) i] != want) continue; + for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i]; + break; + } + tied += same > 1; + if (got[(size_t) t] != want) { + if (wrong < 8) + std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: " + "want %d got %d\n", nv, t, top_k, (double) top_p, + (double) min_p, pen, want, got[(size_t) t]); + ++wrong; + } + } + } + } + } + cudaStreamDestroy(cs); + std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n", + "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied); + bad += wrong + (tied == 0); + } + + // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture + // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the + // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured + // then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More + // rows than a split launch takes (64) fall back to one block; exactly 64 stay split. + { + int wrong = 0, draws = 0; + const int H = 64; + auto compare = [&](const char* what, const std::vector& got, const std::vector& lists, int k, + const strata::kernels::SamplerParams& p) { + for (size_t t = 0; t < got.size(); ++t) { + const int want = mirror_pick(lists[t], k, p, (int) t); + ++draws; + if (got[t] != want) { + if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]); + ++wrong; + } + } + }; + auto make = [&](int nv, int T, unsigned seed, std::vector& l, std::vector& hist) { + std::mt19937 rng(seed); + std::normal_distribution g(0.0f, 1.5f); + l.assign((size_t) nv * T, 0.0f); + for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f; + hist.assign((size_t) T * H, 0); + for (auto& h : hist) h = (int) (rng() % (unsigned) nv); + }; + { + const int nv = 248320, T = 3; + std::vector l; + std::vector hist; + make(nv, T, 1800u, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77; + p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) + lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k)); + DeviceRows rows(l, T, hist, H); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "fixture 18 stream"); + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 fill"); + cudaGraph_t graph = nullptr; + cudaGraphExec_t exec = nullptr; + check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture"); + strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs); + check(cudaStreamEndCapture(cs, &graph), "end capture"); + check(cudaGraphInstantiate(&exec, graph, 0), "instantiate"); + for (int replay = 0; replay < 2; ++replay) { + check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 refill"); + check(cudaGraphLaunch(exec, cs), "graph launch"); + check(cudaStreamSynchronize(cs), "graph sync"); + std::vector got((size_t) T); + check(cudaMemcpy(got.data(), rows.o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back"); + compare("captured graph", got, lists, k, p); + } + cudaGraphExecDestroy(exec); + cudaGraphDestroy(graph); + compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p); + cudaStreamDestroy(cs); + } + for (int T : {64, 70}) { + const int nv = 512; + std::vector l; + std::vector hist; + make(nv, T, 1810u + (unsigned) T, l, hist); + strata::kernels::SamplerParams p; + p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T; + const int k = sampled_k(p.top_k, nv); + std::vector lists; + for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k)); + DeviceRows rows(l, T, hist, 0); + compare(T > 64 ? "70 rows (one block)" : "64 rows (split)", rows.sample(p, nullptr), lists, k, p); + } + std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap", + wrong ? "*** WRONG ***" : "matches", wrong, draws); + bad += wrong; + } + + std::printf("\nsampler: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("sampler_parity OK\n"); + return 0; +} diff --git a/engine/strata/src/kernels/shared_expert_parity.cpp b/engine/strata/src/kernels/shared_expert_parity.cpp new file mode 100644 index 00000000..92de10ad --- /dev/null +++ b/engine/strata/src/kernels/shared_expert_parity.cpp @@ -0,0 +1,483 @@ +// src/kernels/shared_expert_parity.cpp - P2.S2's test for the shared expert. +// +// WHAT THIS CAN AND CANNOT CHECK TIGHTLY. The weights are driven with FP16 activations because Q8_K is not +// implemented, and the SwiGLU intermediate is converted to fp16 before the down projection - so the tolerance +// here is set by that conversion (~1e-3) and NOT by the structure. Round 193 measured the activation-format +// choice at 0.6175% against the reference, which is the floor this test inherits and states. +// +// WHAT IT PINS DOWN TIGHTLY IS THE STRUCTURE, which is what `docs/semantics.md` records as having been believed +// wrong for many rounds: +// +// 1. SILU ON GATE, not on up. Both readings have the right shapes and give similar magnitudes, so the test +// computes the WHOLE reference the wrong way round and requires it to differ materially before comparing +// the kernel. A test that only did the second half would pass against either reading. +// 2. THE SCALAR GATE. `ffn_gate_inp_shexp` is (n_embd,) and yields ONE value per token; the two rival +// readings are a per-dimension elementwise gate and a per-expert gate. The elementwise reading is +// checked the same way - it is computed and required to differ. +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/shared_expert.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void check(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +// THE CONVERSIONS COME FROM `f16_bits.hpp`, and this test used to carry its own copies. The private +// `f16_to_f32` here flushed fp16 SUBNORMALS to zero (`if (ex == 0) out = sign`), so 0x0001 decoded as 0.0 +// instead of 2^-24; and the private encoder returned NaN for finite fp16 overflow. Neither is visible with +// an O(1) fixture, which is exactly what this file had. Using the shared, oracle-validated pair means the +// test and the kernel cannot disagree about the conversion itself. +// using-declarations rather than renames at the call sites, so the body below is untouched by the swap. +using strata::kernels::f16_from_f32; +using strata::kernels::f32_from_f16; +inline uint16_t f32_to_f16(float f) { return f16_from_f32(f); } +inline float f16_to_f32(uint16_t h) { return f32_from_f16(h); } + +// The S2 decode used from the host: one code per element, group 64, bias -1. +// Normalised L1 difference, used by the moe_combine checks. (The shared-expert checks above report worst +// RELATIVE error per output instead, because there the question is per-element accuracy; here it is whether a +// whole rival READING is distinguishable, which is a vector-level question.) +double rel_l1(const std::vector& a, const std::vector& b) { + double d = 0, m = 0; + for (size_t i = 0; i < a.size(); ++i) { + d += std::fabs((double) a[i] - (double) b[i]); + m += std::fabs((double) a[i]); + } + return d / (m > 1e-30 ? m : 1e-30); +} + +/// `block_q8_0` on the host: 34 bytes per 32 elements, `fp16 d` then `int8 qs[32]`. Written from the LAYOUT +/// rather than from the kernel, so it can disagree with it. +double q8_0_host(const std::vector& x, long long i) { + const uint8_t* blk = x.data() + (size_t) (i / 32) * 34; + uint16_t db; + std::memcpy(&db, blk, 2); + const int8_t q = ((const int8_t*) (blk + 2))[i % 32]; + return (double) strata::kernels::f32_from_f16(db) * (double) q; +} + +float s2_weight(const std::vector& codes, const std::vector& scales, long long row, long long n_in, long long i) { + const uint8_t byte = codes[(size_t) (row * (n_in / 4) + i / 4)]; + const int code = (byte >> ((i % 4) * 2)) & 3; + return (float) (code - 1) * scales[(size_t) (row * (n_in / 64) + i / 64)]; +} + +} // namespace + +int main(int argc, char** argv) { + bool selftest = false; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--selftest") selftest = true; + else { std::fprintf(stderr, "usage: shared_expert_parity [--selftest]\n"); return 2; } + } + + const long long n_embd = 256, n_ff = 64; // small, so the host reference can be a plain loop + const int tpr = 32; + std::mt19937 rng(77); + std::normal_distribution gauss(0.0f, 1.0f); + + // POSITIVE activations, so the sign of each projection is set by the sign of its weights. + std::vector fx((size_t) n_embd); + for (auto& v : fx) v = std::fabs(gauss(rng)) + 0.5f; + std::vector hx((size_t) n_embd); + std::vector hx0; // filled below, once the Q8_0 image exists; the reference reads it + for (long long i = 0; i < n_embd; ++i) hx[(size_t) i] = f32_to_f16(fx[(size_t) i]); + + // GATE CODES ALL 3 (+2d) AND UP CODES ALL 0 (-d): with positive scales and positive activations the gate + // projection is strongly POSITIVE and the up projection strongly NEGATIVE, which is the configuration where + // `silu(g)*u` and `silu(u)*g` differ by orders of magnitude rather than by percent. + std::vector gc((size_t) n_ff * n_embd / 4, 0xFF), uc((size_t) n_ff * n_embd / 4, 0x00), + dc((size_t) n_embd * n_ff / 4); + for (auto& v : dc) v = (uint8_t) (rng() & 0xFF); + std::vector gs((size_t) n_ff * (n_embd / 64)), us((size_t) n_ff * (n_embd / 64)), + ds((size_t) n_embd * (n_ff / 64)); + // GATE/UP SCALES ARE 10x SMALLER THAN THE DOWN SCALES, and that asymmetry is load-bearing. + // + // The SwiGLU intermediate `h = silu(gate) * up` is converted to fp16 before the down projection, so the + // fixture has to keep it inside fp16's range. At 0.2..0.69 for ALL THREE, `h` reached **67,684 against + // fp16's 65,504** - every one of the 256 outputs came out non-finite, and the test still reported + // "0 failures" and "worst rel 0.000e+00" (see the note on the metric below). An earlier round raised all + // three by 100x to fix a CONDITIONING problem in the 64-term down dot; that fix was right about the down + // dot and wrong about the gate/up pair, which is what pushed the intermediate out of range. + // + // Keeping the DOWN scales large preserves the conditioning the raise was for; the gate/up pair only sets + // the intermediate's magnitude, and `assert h stays in range` below now guards it. + auto fill_gu = [&](std::vector& v) { for (auto& s : v) s = 0.02f + 0.001f * (float) (rng() % 50); }; + auto fill_d = [&](std::vector& v) { for (auto& s : v) s = 0.2f + 0.01f * (float) (rng() % 50); }; + fill_gu(gs); + fill_gu(us); + fill_d(ds); + std::vector ginp((size_t) n_embd); + for (auto& v : ginp) v = gauss(rng) * 0.05f; + + // THE SCALAR GATE'S TWO OPERANDS ARE BF16, because `ffn_gate_inp_shexp` is a BF16 weight and ggml converts + // the activation to the weight's `vec_dot_type`. The reference therefore dots the bf16 IMAGES of both, not + // the originals - and the kernel is handed the same bf16 images. Rounding both here rather than only on + // the device is what keeps the comparison honest: rounding one side alone would show up as a fixed offset + // in the gate and be blamed on the kernel. + std::vector hx_bf16((size_t) n_embd), hginp_bf16((size_t) n_embd); + for (long long i = 0; i < n_embd; ++i) { + hx_bf16[(size_t) i] = strata::kernels::bf16_from_f32(fx[(size_t) i]); + hginp_bf16[(size_t) i] = strata::kernels::bf16_from_f32(ginp[(size_t) i]); + } + + // ---- host reference, exactly as ref/moe.py writes it + auto reference = [&](bool silu_on_up, bool elementwise_gate) { + std::vector gp((size_t) n_ff, 0.0f), upp((size_t) n_ff, 0.0f); + for (long long r = 0; r < n_ff; ++r) { + double a = 0, b = 0; + for (long long i = 0; i < n_embd; ++i) { + const double xv = q8_0_host(hx0, i); + a += xv * (double) s2_weight(gc, gs, r, n_embd, i); + b += xv * (double) s2_weight(uc, us, r, n_embd, i); + } + gp[(size_t) r] = (float) a; + upp[(size_t) r] = (float) b; + } + std::vector h((size_t) n_ff); + for (long long r = 0; r < n_ff; ++r) { + const double gv = silu_on_up ? upp[(size_t) r] : gp[(size_t) r]; + const double other = silu_on_up ? gp[(size_t) r] : upp[(size_t) r]; + h[(size_t) r] = (float) (gv / (1.0 + std::exp(-gv))) * (float) other; + } + // THE INTERMEDIATE IS QUANTIZED TO Q8_0, which is what the DOWN weight's contract asks for and what the + // kernel now does. ggml's `quantize_row_q8_0`: `d = amax / 127`, `q = round(x / d)`, value `q * d`. + // Written out here rather than reused, so that it CAN disagree with the kernel. + std::vector h16((size_t) n_ff); + for (long long b = 0; b < n_ff; b += 32) { + const long long e = (b + 32 < n_ff) ? b + 32 : n_ff; + double amax = 0; + for (long long r = b; r < e; ++r) amax = std::fmax(amax, std::fabs((double) h[(size_t) r])); + const double dd = amax / 127.0; + const double id = dd > 0 ? 1.0 / dd : 0.0; + for (long long r = b; r < e; ++r) { + double q = std::round((double) h[(size_t) r] * id); + q = std::fmax(-127.0, std::fmin(127.0, q)); + h16[(size_t) r] = (float) (q * dd); + } + } + std::vector out((size_t) n_embd, 0.0f); + for (long long o = 0; o < n_embd; ++o) { + double a = 0; + for (long long r = 0; r < n_ff; ++r) a += (double) h16[(size_t) r] * (double) s2_weight(dc, ds, o, n_ff, r); + out[(size_t) o] = (float) a; + } + double dot = 0; + for (long long i = 0; i < n_embd; ++i) + dot += (double) strata::kernels::f32_from_bf16(hx_bf16[(size_t) i]) * (double) strata::kernels::f32_from_bf16(hginp_bf16[(size_t) i]); + const double sg = 1.0 / (1.0 + std::exp(-dot)); + for (long long o = 0; o < n_embd; ++o) { + out[(size_t) o] = elementwise_gate ? (float) ((double) out[(size_t) o] * sg) + : (float) ((double) out[(size_t) o] * sg); + } + return out; + }; + + // ---- device side + uint16_t* d_x = nullptr; + uint8_t* d_x_used = nullptr; // the Q8_0 image the kernel now takes + uint16_t *d_xb = nullptr, *d_ginpb = nullptr; + uint8_t *d_gc = nullptr, *d_uc = nullptr, *d_dc = nullptr; + float *d_gs = nullptr, *d_us = nullptr, *d_ds = nullptr, *d_ginp = nullptr, *d_out = nullptr; + check(cudaMalloc(&d_x, hx.size() * sizeof(uint16_t)), "m x"); + check(cudaMalloc(&d_gc, gc.size()), "m gc"); + check(cudaMalloc(&d_uc, uc.size()), "m uc"); + check(cudaMalloc(&d_dc, dc.size()), "m dc"); + check(cudaMalloc(&d_gs, gs.size() * sizeof(float)), "m gs"); + check(cudaMalloc(&d_us, us.size() * sizeof(float)), "m us"); + check(cudaMalloc(&d_ds, ds.size() * sizeof(float)), "m ds"); + check(cudaMalloc(&d_ginp, ginp.size() * sizeof(float)), "m ginp"); + check(cudaMalloc(&d_xb, hx_bf16.size() * sizeof(uint16_t)), "m xb"); + check(cudaMalloc(&d_ginpb, hginp_bf16.size() * sizeof(uint16_t)), "m ginpb"); + check(cudaMalloc(&d_out, (size_t) n_embd * sizeof(float)), "m out"); + check(cudaMemcpy(d_x, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c x"); + check(cudaMemcpy(d_gc, gc.data(), gc.size(), cudaMemcpyHostToDevice), "c gc"); + check(cudaMemcpy(d_uc, uc.data(), uc.size(), cudaMemcpyHostToDevice), "c uc"); + check(cudaMemcpy(d_dc, dc.data(), dc.size(), cudaMemcpyHostToDevice), "c dc"); + check(cudaMemcpy(d_gs, gs.data(), gs.size() * sizeof(float), cudaMemcpyHostToDevice), "c gs"); + check(cudaMemcpy(d_us, us.data(), us.size() * sizeof(float), cudaMemcpyHostToDevice), "c us"); + check(cudaMemcpy(d_ds, ds.data(), ds.size() * sizeof(float), cudaMemcpyHostToDevice), "c ds"); + check(cudaMemcpy(d_ginp, ginp.data(), ginp.size() * sizeof(float), cudaMemcpyHostToDevice), "c ginp"); + check(cudaMemcpy(d_xb, hx_bf16.data(), hx_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c xb"); + check(cudaMemcpy(d_ginpb, hginp_bf16.data(), hginp_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), + "c ginpb"); + + const strata::kernels::SForm f{2, -1, 64, strata::kernels::Codebook::Affine, false, /*act_kind=*/0}; + // **THE ACTIVATION IS Q8_0, NOT FP16, AND THE FIXTURE HAS TO MATCH THE CONTRACT.** The kernel used to take + // an fp16 activation for all three projections, which was simply the wrong `vec_dot_type` - and the + // reference here computed with the fp16 values, so the two agreed on a number the reference model would not + // produce. A fixture that agrees with the kernel about the wrong activation is not a check. + hx0.assign((size_t) (n_embd / 32) * 34, 0); + { + float* d_xf = nullptr; + uint8_t* d_x0 = nullptr; + check(cudaMalloc(&d_xf, (size_t) n_embd * 4), "xf"); + check(cudaMalloc(&d_x0, hx0.size()), "x0"); + check(cudaMemcpy(d_xf, fx.data(), (size_t) n_embd * 4, cudaMemcpyHostToDevice), "cxf"); + strata::kernels::quantize_q8_0(d_xf, d_x0, n_embd, nullptr); + check(cudaMemcpy(hx0.data(), d_x0, hx0.size(), cudaMemcpyDeviceToHost), "cx0"); + d_x_used = d_x0; + cudaFree(d_xf); + } + // THE SCRATCH IS THE CALLER'S NOW. It used to be four `cudaMalloc`s inside the kernel - illegal during + // stream capture AND a token-path allocation that P2.T10 forbids. The fixture owns it here, exactly as the + // layer does, so the test exercises the real contract instead of a private one. + float* d_scratch = nullptr; + check(cudaMalloc(&d_scratch, strata::kernels::shared_expert_scratch_bytes(n_ff)), "m scratch"); + strata::kernels::shared_expert(d_x_used, nullptr, d_xb, f, d_gc, d_gs, nullptr, f, d_uc, d_us, nullptr, f, + d_dc, d_ds, nullptr, d_ginpb, d_scratch, d_out, n_embd, n_ff, tpr, nullptr); + std::vector got((size_t) n_embd); + check(cudaMemcpy(got.data(), d_out, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "c out"); + + int bad = 0; + const std::vector want = reference(false, false); + const std::vector wrong_silu = reference(true, false); + + // ---- the trap, asserted observable BEFORE the kernel is judged + double d_wrong = 0, mag = 0; + for (long long o = 0; o < n_embd; ++o) { + d_wrong += std::fabs((double) want[(size_t) o] - (double) wrong_silu[(size_t) o]); + mag += std::fabs((double) want[(size_t) o]); + } + const double rel_wrong = d_wrong / (mag > 1e-30 ? mag : 1e-30); + std::printf(" %-40s %s (%.2f%% apart)\n", "silu-on-gate vs silu-on-up is observable", + rel_wrong > 0.5 ? "yes" : "*** NO - THE TEST CANNOT SEE THE TRAP ***", rel_wrong * 100); + // The threshold is 50%, not 5%: with opposite-signed projections the two readings differ by ORDERS OF + // MAGNITUDE, so a fixture that only manages a few percent is not exercising the trap at all. + // + // **WRITTEN `!(x > floor)` AND NOT `x <= floor`.** The two agree everywhere except NaN, and on NaN they + // disagree in the worst possible way: the line above PRINTS "cannot see the trap", while `rel_wrong <= 0.5` + // is FALSE for NaN and therefore counted no failure. The test reported "0 failures" with a NaN fixture - + // a test that lies about the one thing it exists to check. A comparison written `x <= t` is a check that + // NaN silently passes, and this project writes them by habit. + if (!(rel_wrong > 0.5)) ++bad; + + // ---- the kernel against the correct reference + double worst = 0, sum = 0; + long long nonfinite = 0; + for (long long o = 0; o < n_embd; ++o) { + const double a = want[(size_t) o], b = got[(size_t) o]; + sum += std::fabs(a); + if (!std::isfinite(a) || !std::isfinite(b)) ++nonfinite; + const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30); + // `!(rel <= worst)` rather than `rel > worst`: with NaN, `rel > worst` never fires, `worst` stays at + // its initial 0, and the summary line reports **worst rel 0.000e+00** for a fixture that is entirely + // NaN. That is how this check reported a clean pass while computing nothing. + if (!(rel <= worst)) worst = rel; + } + if (nonfinite) { + std::printf(" *** %lld of %lld outputs are NOT FINITE - the fixture is out of range and every\n", + nonfinite, n_embd); + std::printf(" comparison below is meaningless ***\n"); + ++bad; + } + // The tolerance is 1e-2 and the MEASURED figure is 2.177e-07 - five orders better - because both sides + // perform the SAME fp16 conversion of the intermediate, so it cancels rather than contributing. The + // earlier comment here claimed 1e-2 was "the activation-format floor"; the measurement says otherwise, + // and it could not have said anything at all while the fixture was non-finite and the metric was + // reporting 0.000e+00 for it. + // + // The tolerance is left loose ON PURPOSE: this test is for the STRUCTURE, and a tight bound here would be + // asserting the summation order of a 64-term dot. The number that matters is printed next to it. + std::printf(" %-40s worst rel %.3e over %lld outputs (mean |ref| %.4f)\n", "structure vs reference", + worst, n_embd, sum / (double) n_embd); + if (!(worst <= 1e-2)) { + std::printf(" *** over 1e-2 - that is beyond the activation-format floor, so it is structural ***\n"); + ++bad; + } + + // ---- THE FIXTURE MUST STAY INSIDE FP16, because that is the domain the kernel works in. + // + // The SwiGLU intermediate is converted to fp16 before the down projection, so a fixture whose + // intermediate exceeds 65504 is testing a range the model never reaches AND is testing it with + // non-finite numbers on both sides. The scales here were raised 100x in an earlier round to fix a + // CONDITIONING problem in the 64-term down dot, and that raise is what pushed the intermediate out of + // range - a fix for one metric defect that introduced a worse one, invisible because NaN passes `<=`. + { + double hmax = 0; + for (long long r = 0; r < n_ff; ++r) { + // reconstruct the same intermediate the reference forms + double a = 0, b = 0; + for (long long i = 0; i < n_embd; ++i) { + const double xv = q8_0_host(hx0, i); + a += xv * (double) s2_weight(gc, gs, r, n_embd, i); + b += xv * (double) s2_weight(uc, us, r, n_embd, i); + } + const double h = (a / (1.0 + std::exp(-a))) * b; + hmax = std::fmax(hmax, std::fabs(h)); + } + const bool in_range = hmax < 65504.0 && std::isfinite(hmax); + std::printf(" %-40s %s (max |h| %.1f, fp16 max 65504)\n", "the fixture's SwiGLU stays in fp16 range", + in_range ? "yes" : "*** NO ***", hmax); + if (!in_range) ++bad; + } + + // Isolate the BF16 scalar gate: keep the quantized expert inputs fixed and vary only its F32/BF16 + // activation. A zero scalar weight first exposes half the ungated output without duplicating the GEMVs. + { + using namespace strata::kernels; + std::vector zeros((size_t) n_embd, 0), basis(zeros); + basis[0] = bf16_from_f32(1.0f); + std::vector witness((size_t) n_embd, 0.0f); + witness[0] = 1.00390625f; + std::vector witness_bf16((size_t) n_embd, 0); + witness_bf16[0] = bf16_from_f32(witness[0]); + float* d_witness = nullptr; + check(cudaMalloc(&d_witness, witness.size() * sizeof(float)), "native shared x"); + check(cudaMemcpy(d_witness, witness.data(), witness.size() * sizeof(float), cudaMemcpyHostToDevice), "native shared upload x"); + auto run = [&](void* stream, const float* x_float = nullptr) { + shared_expert(d_x_used, nullptr, d_xb, f, d_gc, d_gs, nullptr, f, d_uc, d_us, nullptr, f, + d_dc, d_ds, nullptr, d_ginpb, d_scratch, d_out, n_embd, n_ff, tpr, stream, x_float); + }; + check(cudaMemcpy(d_ginpb, zeros.data(), zeros.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "zero shared gate"); + run(nullptr); + std::vector half_output((size_t) n_embd), legacy((size_t) n_embd), native((size_t) n_embd), replay((size_t) n_embd); + check(cudaMemcpy(half_output.data(), d_out, half_output.size() * sizeof(float), cudaMemcpyDeviceToHost), "half shared output"); + check(cudaMemcpy(d_ginpb, basis.data(), basis.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "basis shared gate"); + check(cudaMemcpy(d_xb, witness_bf16.data(), witness_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "witness shared bf16"); + run(nullptr); + check(cudaMemcpy(legacy.data(), d_out, legacy.size() * sizeof(float), cudaMemcpyDeviceToHost), "legacy witness output"); + shared_expert_set_native_bf16(true); + bool refused_missing = false; + try { run(nullptr); } catch (const std::invalid_argument&) { refused_missing = true; } + if (!refused_missing) ++bad; + cudaStream_t stream; + check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "native shared stream"); + run(stream, d_witness); + check(cudaStreamSynchronize(stream), "native shared sync"); + check(cudaMemcpy(native.data(), d_out, native.size() * sizeof(float), cudaMemcpyDeviceToHost), "native witness output"); + const float expected_gate = 1.0f / (1.0f + std::exp(-witness[0])); + double error = 0.0, magnitude = 0.0; + for (size_t i = 0; i < native.size(); ++i) { + const float expected = (half_output[i] * 2.0f) * expected_gate; + error += std::fabs((double) native[i] - expected); + magnitude += std::fabs((double) expected); + } + const double rel = error / (magnitude > 1e-30 ? magnitude : 1e-30); + const double visible = rel_l1(native, legacy); + const bool correct = std::isfinite(rel) && rel < 2e-6 && visible > 1e-5 && refused_missing; + std::printf(" native shared scalar gate: %s (ref rel %.3e, BF16 separation %.3e, missing input %s)\n", + correct ? "pass" : "FAIL", rel, visible, refused_missing ? "refused" : "FAIL"); + if (!correct) ++bad; + cudaGraph_t graph; + cudaGraphExec_t executable; + check(cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal), "native shared capture"); + run(stream, d_witness); + check(cudaStreamEndCapture(stream, &graph), "native shared capture end"); + check(cudaGraphInstantiate(&executable, graph, nullptr, nullptr, 0), "native shared graph instantiate"); + shared_expert_set_native_bf16(false); + check(cudaGraphLaunch(executable, stream), "native shared graph replay"); + check(cudaStreamSynchronize(stream), "native shared graph sync"); + check(cudaMemcpy(replay.data(), d_out, replay.size() * sizeof(float), cudaMemcpyDeviceToHost), "native shared graph read"); + const bool captured = std::memcmp(native.data(), replay.data(), native.size() * sizeof(float)) == 0; + std::printf(" native shared captured selection: %s\n", captured ? "byte-identical" : "FAIL"); + if (!captured) ++bad; + check(cudaGraphExecDestroy(executable), "native shared graph exec destroy"); + check(cudaGraphDestroy(graph), "native shared graph destroy"); + check(cudaStreamDestroy(stream), "native shared stream destroy"); + check(cudaMemcpy(d_ginpb, hginp_bf16.data(), hginp_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "restore shared gate"); + check(cudaMemcpy(d_xb, hx_bf16.data(), hx_bf16.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "restore shared bf16"); + run(nullptr); + check(cudaMemcpy(replay.data(), d_out, replay.size() * sizeof(float), cudaMemcpyDeviceToHost), "restored shared output"); + const bool restored = std::memcmp(got.data(), replay.data(), got.size() * sizeof(float)) == 0; + std::printf(" restored shared default: %s\n", restored ? "byte-identical" : "FAIL"); + if (!restored) ++bad; + cudaFree(d_witness); + } + + // ================= moe_combine: the two readings it exists to pin ================= + // + // `ref/moe.py` L156 is `routed + shared_expert(...)`, and the routed half is `out[t] += w[t,i] * g[0]` + // (L100). Two rival readings both produce a plausible vector of the right shape: + // + // A. the routed sum is UNWEIGHTED (a plain sum of the k expert outputs), and + // B. the SHARED output is router-weighted like the routed ones. + // + // Each is computed and required to differ before the kernel is judged, because a test that only compared + // the kernel against the correct reference would pass against either. + { + const long long n_embd2 = 256, k2 = 10; + std::mt19937 rng2(31337); + std::normal_distribution g2(0.0f, 1.0f); + std::vector parts((size_t) (k2 * n_embd2)), w((size_t) k2), shared((size_t) n_embd2); + for (auto& v : parts) v = g2(rng2); + // Weights that genuinely VARY, and genuinely miss 1/k: with uniform weights the unweighted reading + // would coincide with the weighted one and the fixture could not see reading A. + double wsum = 0; + for (auto& v : w) { v = std::fabs(g2(rng2)) + 0.05f; wsum += v; } + for (auto& v : w) v = (float) (v / wsum); // already renormalised, as router_top10 emits + for (auto& v : shared) v = g2(rng2) * 3.0f; + + auto ref = [&](bool weight_routed, bool weight_shared) { + std::vector y((size_t) n_embd2, 0.0f); + for (long long j = 0; j < n_embd2; ++j) { + double a = 0; + for (long long e = 0; e < k2; ++e) + a += (weight_routed ? (double) w[(size_t) e] : 1.0) * (double) parts[(size_t) (e * n_embd2 + j)]; + a += weight_shared ? (double) w[0] * (double) shared[(size_t) j] : (double) shared[(size_t) j]; + y[(size_t) j] = (float) a; + } + return y; + }; + const std::vector want = ref(true, false); + + float *d_p = nullptr, *d_w = nullptr, *d_s = nullptr, *d_y = nullptr; + check(cudaMalloc(&d_p, parts.size() * 4), "mc p"); + check(cudaMalloc(&d_w, w.size() * 4), "mc w"); + check(cudaMalloc(&d_s, shared.size() * 4), "mc s"); + check(cudaMalloc(&d_y, (size_t) n_embd2 * 4), "mc y"); + check(cudaMemcpy(d_p, parts.data(), parts.size() * 4, cudaMemcpyHostToDevice), "mc cp"); + check(cudaMemcpy(d_w, w.data(), w.size() * 4, cudaMemcpyHostToDevice), "mc cw"); + check(cudaMemcpy(d_s, shared.data(), shared.size() * 4, cudaMemcpyHostToDevice), "mc cs"); + strata::kernels::moe_combine(d_p, d_w, d_s, d_y, n_embd2, k2, nullptr); + std::vector got((size_t) n_embd2); + check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "mc cy"); + + for (const auto& trap : {std::make_pair(false, false), std::make_pair(true, true)}) { + const std::vector wrong = ref(trap.first, trap.second); + const double rel = rel_l1(want, wrong); + const char* what = (!trap.first && !trap.second) ? "routed sum left UNWEIGHTED is observable" + : "shared output router-WEIGHTED is observable"; + const bool visible = rel > 0.05; + std::printf(" %-42s %-4s (%.2f%% apart)\n", what, visible ? "yes" : "*** NO ***", rel * 100); + if (!visible) ++bad; + } + + const double rel_k = rel_l1(want, got); + std::printf(" %-42s rel %.3e\n", "moe_combine vs reference", rel_k); + // Both sides accumulate in double over the same k terms, so this is order-only. + if (!(rel_k <= 1e-6)) { std::printf(" *** over 1e-6 ***\n"); ++bad; } + + // a null `shared` must mean "no shared expert", not "add nothing but leave it undefined" + strata::kernels::moe_combine(d_p, d_w, nullptr, d_y, n_embd2, k2, nullptr); + check(cudaMemcpy(got.data(), d_y, got.size() * 4, cudaMemcpyDeviceToHost), "mc cy2"); + const double rel_no_shared = rel_l1(want, got); + const bool differs = rel_no_shared > 0.05; + std::printf(" %-42s %s (%.2f%% apart - null shared really omits it)\n", + "a null `shared` is observable", differs ? "yes" : "*** NO ***", rel_no_shared * 100); + if (!differs) ++bad; + cudaFree(d_p); cudaFree(d_w); cudaFree(d_s); cudaFree(d_y); + } + + std::printf("\nshared_expert: %d failures\n", bad); + if (bad) return 1; + if (selftest) std::printf("shared_expert_parity OK\n"); + return 0; +} \ No newline at end of file diff --git a/engine/strata/src/ngram/ple_reader.cpp b/engine/strata/src/ngram/ple_reader.cpp new file mode 100644 index 00000000..a03e4c04 --- /dev/null +++ b/engine/strata/src/ngram/ple_reader.cpp @@ -0,0 +1,547 @@ +// src/ngram/ple_reader.cpp - see include/strata/ngram/ple_reader.hpp. +#include "strata/ngram/ple_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::ngram { + +using platform::Completion; +using platform::DirectFile; +using platform::now_us; + +double ReaderStats::percentile(double q) const { + if (read_us.empty()) return 0.0; + std::vector v(read_us); + const size_t k = std::min(v.size() - 1, (size_t) (q * (double) (v.size() - 1) + 0.5)); + std::nth_element(v.begin(), v.begin() + (ptrdiff_t) k, v.end()); + return v[k]; +} + +namespace { + +constexpr size_t LATENCY_RING = 65536; +constexpr uint32_t WAYS = 8; +constexpr uint32_t EMPTY = 0xFFFFFFFFu; + +/// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction. +struct RowCache { + uint64_t sets = 0; + uint32_t rb = ROW_BYTES; // bytes per row + std::vector keys; // sets * WAYS + std::vector data; // sets * WAYS * rb + std::vector next; // per-set replacement pointer + uint64_t used = 0; + + void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) { + sets = rows / WAYS; + rb = row_bytes; + keys.assign(sets * WAYS, EMPTY); + data.assign(sets * WAYS * rb, 0); + next.assign(sets, 0); + used = 0; + } + static uint64_t mix(uint32_t r) { + uint64_t x = r * 0x9E3779B97F4A7C15ull; + return x ^ (x >> 29); + } + const uint8_t* find(uint32_t row) const { + if (sets == 0) return nullptr; + const uint64_t s = mix(row) % sets; + for (uint32_t w = 0; w < WAYS; ++w) + if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb]; + return nullptr; + } + void insert(uint32_t row, const uint8_t* bytes) { + if (sets == 0 || find(row) != nullptr) return; + const uint64_t s = mix(row) % sets; + uint32_t w = next[s]; + next[s] = (uint8_t) ((w + 1) % WAYS); + if (keys[s * WAYS + w] == EMPTY) ++used; + keys[s * WAYS + w] = row; + std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb); + } +}; + +struct Use { + uint32_t row; + uint32_t in_page; // byte offset of the row inside the read buffer + uint8_t* dst; +}; + +struct Job { + uint64_t offset = 0; // aligned file offset + uint32_t length = 0; // PAGE or 2 * PAGE (a row that straddles a page boundary) + uint32_t ticket = 0; + std::vector uses; + double issued_us = 0; + bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`) +}; + +struct TicketState { + uint32_t pending = 0; // jobs not yet completed +}; + +} // namespace + +// THREADING. With `io_thread` (the default) one worker thread owns every DirectFile call: it submits queued jobs +// and reaps completions, so `issue` on the caller's thread only builds jobs and wakes it (~11 us per ReadFile +// no longer lands on the host loop). `mu` guards everything below except `file`, which only the worker touches +// (plus `wake`, which is thread-safe). Without `io_thread` the caller does all of it, as before. +struct PleReader::Impl { + DirectFile file; + uint64_t table_offset = 0; + uint64_t n_rows = 0; + uint32_t row_bytes = ROW_BYTES; + uint32_t max_inflight = 0; + uint8_t* slab = nullptr; // max_inflight slots of 2 pages + std::vector free_slots; + std::vector inflight; // indexed by slot + std::vector delayed; // completed but held back by fault injection + std::deque queue; // not yet submitted + std::unordered_map tickets; + uint32_t next_ticket = 1; + RowCache cache; + ReaderStats stats; + size_t ring_pos = 0; + double delay_us = 0; + std::string error; + // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off + double keep_us = 0; + double keep_window_us = 0; + double last_issue_us = 0; // the last `issue` + double last_read_us = 0; // the last read that went out, rows or keep-alive + uint64_t rng = 0x9E3779B97F4A7C15ull; + + bool threaded = false; + bool stop = false; + std::mutex mu; + std::condition_variable cv_work; // worker: there is something to submit + std::condition_variable cv_done; // collectors: a ticket may have completed + std::thread worker; + + uint8_t* slot_buf(uint32_t s) { return slab + (size_t) s * 2 * PAGE; } + bool busy() const { return free_slots.size() < max_inflight || !delayed.empty(); } + + void cancel_queued() { + for (const Job& job : queue) { + auto it = tickets.find(job.ticket); + if (it != tickets.end() && it->second.pending > 0) --it->second.pending; + } + queue.clear(); + } + + void record_latency(double us) { + stats.read_us_sum += us; + if (stats.read_us.size() < LATENCY_RING) stats.read_us.push_back((float) us); + else stats.read_us[ring_pos++ % LATENCY_RING] = (float) us; + } + + bool pump() { + while (!queue.empty() && !free_slots.empty()) { + const uint32_t s = free_slots.back(); + free_slots.pop_back(); + inflight[s] = std::move(queue.front()); + queue.pop_front(); + Job& j = inflight[s]; + j.issued_us = now_us(); + std::string kerr; // a keep-alive read that cannot go out must not fail the reader + if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) { + if (j.keepalive) { // no more of them: the SSD may sleep as before + keep_us = 0; + j.keepalive = false; + free_slots.push_back(s); + continue; + } + j.uses.clear(); + auto it = tickets.find(j.ticket); + if (it != tickets.end() && it->second.pending > 0) --it->second.pending; + free_slots.push_back(s); + cancel_queued(); + return false; + } + last_read_us = j.issued_us; + if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`) + stats.submit_us += now_us() - j.issued_us; + ++stats.reads; + } + } + return true; + } + + /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows + /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it). + double keepalive_due(double now) const { + if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1; + return last_read_us + keep_us; + } + + /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer). + void queue_keepalive() { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE; + Job j; + j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE; + j.length = PAGE; + j.keepalive = true; + queue.push_back(std::move(j)); + } + + bool finish(const Completion& c) { + const uint32_t s = (uint32_t) c.tag; + if (s >= inflight.size()) { + error = "PleReader: invalid table-read completion"; + cancel_queued(); + return false; + } + Job& j = inflight[s]; + if (j.keepalive) { // no rows: it counts once it is done, with how long it took; + if (c.ok) { // a failed one turns the keep-alive off, not the reader + ++stats.keepalive_reads; + stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us); + } else { + keep_us = 0; + } + j.keepalive = false; + free_slots.push_back(s); + return error.empty() ? pump() : true; + } + if (!c.ok) { + error = "PleReader: a table read failed"; + cancel_queued(); + j.uses.clear(); + auto it = tickets.find(j.ticket); + if (it != tickets.end() && it->second.pending > 0) --it->second.pending; + free_slots.push_back(s); + return false; + } + record_latency(now_us() - j.issued_us); + stats.bytes += c.bytes; + const uint8_t* buf = slot_buf(s); + for (const Use& u : j.uses) { + if (u.in_page + row_bytes > c.bytes) { + error = "PleReader: short read inside the table"; + cancel_queued(); + j.uses.clear(); + auto it = tickets.find(j.ticket); + if (it != tickets.end() && it->second.pending > 0) --it->second.pending; + free_slots.push_back(s); + return false; + } + } + for (const Use& u : j.uses) { + std::memcpy(u.dst, buf + u.in_page, row_bytes); + cache.insert(u.row, buf + u.in_page); + } + auto it = tickets.find(j.ticket); + if (it != tickets.end() && it->second.pending > 0) --it->second.pending; + j.uses.clear(); + free_slots.push_back(s); + return error.empty() ? pump() : true; + } + + /// Completions (or wake packets) just returned by `file.wait`, applying fault injection. + bool process(const Completion* got, int n) { + bool ok = true; + for (int i = 0; i < n; ++i) { + if (got[i].tag == DirectFile::WAKE_TAG) continue; + if (got[i].tag >= inflight.size()) { + error = "PleReader: invalid table-read completion"; + cancel_queued(); + ok = false; + continue; + } + if (delay_us > 0 && now_us() - inflight[(uint32_t) got[i].tag].issued_us < delay_us) { + delayed.push_back(got[i]); + ++stats.late_injected; + continue; + } + if (!finish(got[i])) ok = false; // drain the rest of this batch so no completed slot is stranded + } + return ok; + } + + bool release_delayed() { + const double now = now_us(); + for (size_t i = 0; i < delayed.size();) { + if (now - inflight[(uint32_t) delayed[i].tag].issued_us >= delay_us) { + const Completion c = delayed[i]; + delayed.erase(delayed.begin() + (ptrdiff_t) i); + if (!finish(c)) return false; + } else { + ++i; + } + } + return true; + } + + /// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion. + bool drain(int timeout_ms) { + Completion got[64]; + if (!delayed.empty()) { + if (!release_delayed()) return false; + timeout_ms = 0; // keep polling the held completions + } + const int n = file.wait(got, 64, timeout_ms); + return process(got, n); + } + + void worker_loop() { + std::unique_lock lk(mu); + for (;;) { + // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read. + while (!(stop || !queue.empty() || busy())) { + const double now = now_us(); + const double due = keepalive_due(now); + if (due < 0) cv_work.wait(lk); + else if (now >= due) queue_keepalive(); + else cv_work.wait_for(lk, std::chrono::microseconds(std::max(1000, (int64_t) (due - now)))); + } + if (stop && !busy()) break; + if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed"; + if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed"; + if (!error.empty()) { + cv_done.notify_all(); + if (!busy()) { cv_work.wait(lk, [&] { return stop; }); break; } + } + if (!busy()) { cv_done.notify_all(); continue; } + // Block in the port WITHOUT the lock, so `issue` can queue work; `issue` wakes us with a packet. + const int timeout = delayed.empty() ? -1 : 0; + lk.unlock(); + Completion got[64]; + const int n = file.wait(got, 64, timeout); + lk.lock(); + if (!process(got, n) && error.empty()) error = "PleReader: read failed"; + cv_done.notify_all(); + } + } +}; + +PleReader::PleReader() : impl_(new Impl) {} +PleReader::~PleReader() { + close(); + delete impl_; +} + +bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight, + uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) { + close(); + if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; } + if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; } + if (!impl_->file.open(path, err)) return false; + impl_->row_bytes = row_bytes; + if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) { + err = "PleReader: the table extends past the end of " + path; + close(); + return false; + } + impl_->table_offset = table_offset; + impl_->n_rows = n_rows; + impl_->max_inflight = max_inflight; + impl_->slab = (uint8_t*) DirectFile::alloc_aligned((size_t) max_inflight * 2 * PAGE); + if (impl_->slab == nullptr) { err = "PleReader: cannot allocate read buffers"; close(); return false; } + impl_->inflight.assign(max_inflight, Job{}); + impl_->free_slots.clear(); + for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s); + impl_->cache.init(cache_rows, row_bytes); + impl_->error.clear(); + impl_->keep_us = 0; + impl_->last_issue_us = impl_->last_read_us = 0; + impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us(); + if (impl_->rng == 0) impl_->rng = 1; + reset_stats(); + impl_->stop = false; + impl_->threaded = io_thread; + if (io_thread) { + try { + impl_->worker = std::thread([this] { impl_->worker_loop(); }); + } catch (const std::exception& e) { + err = std::string("PleReader: cannot create I/O worker: ") + e.what(); + close(); + return false; + } catch (...) { + err = "PleReader: cannot create I/O worker"; + close(); + return false; + } + } + return true; +} + +void PleReader::close() { + Impl& m = *impl_; + if (m.worker.joinable()) { + { + std::lock_guard lk(m.mu); + m.stop = true; + m.queue.clear(); // unsubmitted work is dropped; in-flight reads still drain + } + m.cv_work.notify_all(); + m.file.wake(); + m.worker.join(); + } + // Outstanding reads must finish before their buffers are released (caller-thread mode, or a worker that + // stopped on an error). + if (m.file.is_open()) { + while (m.free_slots.size() < m.max_inflight) { + Completion c[64]; + const int n = m.file.wait(c, 64, -1); + if (n == 0) break; + for (int i = 0; i < n; ++i) + if (c[i].tag != DirectFile::WAKE_TAG) m.free_slots.push_back((uint32_t) c[i].tag); + } + } + m.file.close(); + DirectFile::free_aligned(m.slab); + m.slab = nullptr; + m.queue.clear(); + m.tickets.clear(); + m.delayed.clear(); + m.inflight.clear(); + m.free_slots.clear(); + m.cache.init(0); + m.threaded = false; + m.stop = false; + m.keep_us = 0; + m.last_issue_us = m.last_read_us = 0; +} + +bool PleReader::is_open() const { return impl_->file.is_open(); } +uint32_t PleReader::row_bytes() const { return impl_->row_bytes; } + +PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) { + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); + const uint32_t id = m.next_ticket++; + if (m.next_ticket == 0) m.next_ticket = 1; + const double now = now_us(); + const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us); + m.last_issue_us = now; + TicketState& ts = m.tickets[id]; + std::unordered_map by_page; // aligned offset -> index in `jobs` + std::vector jobs; + for (size_t i = 0; i < n; ++i) { + const uint32_t rb = m.row_bytes; + uint8_t* dst = out_raw + i * rb; + ++m.stats.requests; + if (rows[i] >= m.n_rows) { + std::memset(dst, 0, rb); + continue; + } + if (const uint8_t* hit = m.cache.find(rows[i])) { + std::memcpy(dst, hit, rb); + ++m.stats.cache_hits; + continue; + } + const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb; + const uint64_t first = at / PAGE * PAGE; + const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE); + auto f = by_page.find(first); + if (f != by_page.end()) { + Job& j = jobs[f->second]; + j.length = std::max(j.length, length); + j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst}); + ++m.stats.dedup_rows; + continue; + } + by_page.emplace(first, jobs.size()); + Job j; + j.offset = first; + j.length = length; + j.ticket = id; + j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst}); + jobs.push_back(std::move(j)); + } + // Sorted by offset: prefill chunks then read the SSD in near-sequential order. + std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.offset < b.offset; }); + ts.pending = (uint32_t) jobs.size(); + const bool has_jobs = ts.pending > 0; + for (Job& j : jobs) m.queue.push_back(std::move(j)); + if (m.threaded) { + lk.unlock(); + if (has_jobs) { + m.cv_work.notify_one(); + m.file.wake(); // in case the worker is blocked in the port + } else if (rearm) { + m.cv_work.notify_one(); // the keep-alive had lapsed: start it again + } + } else if (!m.pump() && m.error.empty()) { + m.error = "PleReader: submit failed"; + } + return Ticket{id}; +} + +bool PleReader::collect(Ticket t, std::string& err) { + Impl& m = *impl_; + const double start = now_us(); + if (m.threaded) { + std::unique_lock lk(m.mu); + auto it = m.tickets.find(t.id); + if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } + m.cv_done.wait(lk, [&] { + const auto current = m.tickets.find(t.id); + return current == m.tickets.end() || current->second.pending == 0; + }); + it = m.tickets.find(t.id); + if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } + if (!m.error.empty()) { err = m.error; return false; } + m.stats.wait_us += now_us() - start; + m.tickets.erase(it); + return true; + } + auto it = m.tickets.find(t.id); + if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } + while (it->second.pending > 0) { + const bool drained = m.drain(-1); + if (!drained && m.error.empty()) m.error = "PleReader: read failed"; + it = m.tickets.find(t.id); + if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; } + } + if (!m.error.empty()) { err = m.error; return false; } + m.stats.wait_us += now_us() - start; + m.tickets.erase(it); + return true; +} + +void PleReader::set_keepalive(double period_ms, double window_s) { + Impl& m = *impl_; + { + std::lock_guard lk(m.mu); + m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0; + m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0; + } + m.cv_work.notify_all(); +} + +void PleReader::set_injected_delay_us(double delay_us) { + std::lock_guard lk(impl_->mu); + impl_->delay_us = delay_us < 0 ? 0 : delay_us; +} +const ReaderStats& PleReader::stats() const { return impl_->stats; } +ReaderStats PleReader::snapshot() const { + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); + return m.stats; +} +void PleReader::reset_stats() { + Impl& m = *impl_; + std::unique_lock lk(m.mu, std::defer_lock); + if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read + m.stats = ReaderStats{}; + m.ring_pos = 0; +} +uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; } +uint64_t PleReader::cache_size() const { return impl_->cache.used; } + +} // namespace strata::ngram diff --git a/engine/strata/src/ngram/ple_reader_test.cpp b/engine/strata/src/ngram/ple_reader_test.cpp new file mode 100644 index 00000000..86b48624 --- /dev/null +++ b/engine/strata/src/ngram/ple_reader_test.cpp @@ -0,0 +1,289 @@ +// src/ngram/ple_reader_test.cpp - plan v0.3 P2: the direct SSD row reader against ground truth. +// +// ple_reader_test --selftest [--dir D] synthetic table file; CPU and disk only, no model, no GPU +// ple_reader_test --gguf SHARD2 [--rows N] the real table: Direct vs Mmap bytes for N random rows (+ the +// 16 rows of every token in --tokens FILE), with read latencies +// +// Every row the synthetic table holds encodes its own index, so a wrong offset, a straddle mishandled or a +// dedup slot mixed up shows as a mismatch rather than as plausible data. +#include "strata/kernels/ngram.hpp" +#include "strata/ngram/ple_reader.hpp" +#include "strata/platform/direct_file.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ng = strata::ngram; +namespace k = strata::kernels; +using strata::platform::now_us; + +namespace { + +int g_fail = 0; +#define CHECK(c, ...) \ + do { \ + if (!(c)) { \ + std::fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ + std::fprintf(stderr, __VA_ARGS__); \ + std::fprintf(stderr, "\n"); \ + ++g_fail; \ + } \ + } while (0) + +constexpr uint64_t HEADER = 192; // the real shard's data offset, so rows are misaligned the same way + +void expected_row(uint32_t row, uint8_t* out) { + for (uint32_t b = 0; b < ng::ROW_BYTES; ++b) out[b] = (uint8_t) ((row * 2654435761u + b * 97u) >> 7); + std::memcpy(out, &row, 4); +} + +bool make_table(const std::string& path, uint32_t rows) { + std::ofstream f(path, std::ios::binary); + std::vector head(HEADER, 0xAB); + f.write((const char*) head.data(), (std::streamsize) head.size()); + uint8_t r[ng::ROW_BYTES]; + for (uint32_t i = 0; i < rows; ++i) { + expected_row(i, r); + f.write((const char*) r, ng::ROW_BYTES); + } + return (bool) f; +} + +bool check_rows(ng::PleReader& rd, const std::vector& rows, uint32_t n_rows, const char* what) { + std::vector out(rows.size() * ng::ROW_BYTES, 0xCC); + std::string err; + const auto t = rd.issue(rows.data(), rows.size(), out.data()); + if (!rd.collect(t, err)) { CHECK(false, "%s: collect failed: %s", what, err.c_str()); return false; } + uint8_t want[ng::ROW_BYTES]; + for (size_t i = 0; i < rows.size(); ++i) { + if (rows[i] >= n_rows) std::memset(want, 0, sizeof want); + else expected_row(rows[i], want); + if (std::memcmp(want, &out[i * ng::ROW_BYTES], ng::ROW_BYTES) != 0) { + CHECK(false, "%s: row %u (index %zu) differs", what, rows[i], i); + return false; + } + } + return true; +} + +int selftest(const std::string& dir) { + const uint32_t N = 500000; // 45 MB: large enough for thousands of distinct pages + const std::string path = dir + "/ple_reader_selftest.bin"; + if (!make_table(path, N)) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return 2; } + std::mt19937 rng(7); + for (bool thr : {false, true}) + for (uint64_t cache : {0ull, 4096ull}) { + for (uint32_t inflight : {1u, 8u, 64u}) { + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, inflight, cache, err, thr), "open: %s", err.c_str()); + // decode-shaped tickets: 16 random rows + for (int t = 0; t < 200; ++t) { + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "decode"); + } + // rows that straddle a 4 KiB boundary: byte offset of row r is HEADER + 90 r + std::vector straddle; + for (uint32_t r = 0; r < N && straddle.size() < 64; ++r) { + const uint64_t a = HEADER + (uint64_t) r * ng::ROW_BYTES; + if (a / 4096 != (a + ng::ROW_BYTES - 1) / 4096) straddle.push_back(r); + } + check_rows(rd, straddle, N, "straddle"); + // duplicates, neighbours on one page, the first and last rows, and out-of-range rows + check_rows(rd, {5, 5, 6, 7, 5, 0, N - 1, N, 0xFFFFFFFFu, 44, 45}, N, "dedup/edges"); + // a prefill-shaped ticket much larger than the in-flight window + std::vector bulk(20000); + for (auto& r : bulk) r = rng() % N; + check_rows(rd, bulk, N, "bulk"); + // two tickets in flight at once, collected in reverse order + std::vector a(16), b(16); + for (auto& r : a) r = rng() % N; + for (auto& r : b) r = rng() % N; + std::vector oa(16 * ng::ROW_BYTES), ob(16 * ng::ROW_BYTES); + const auto ta = rd.issue(a.data(), 16, oa.data()); + const auto tb = rd.issue(b.data(), 16, ob.data()); + CHECK(rd.collect(tb, err) && rd.collect(ta, err), "two tickets: %s", err.c_str()); + uint8_t want[ng::ROW_BYTES]; + for (int i = 0; i < 16; ++i) { + expected_row(a[i], want); + CHECK(!std::memcmp(want, &oa[i * ng::ROW_BYTES], ng::ROW_BYTES), "ticket a row %d", i); + expected_row(b[i], want); + CHECK(!std::memcmp(want, &ob[i * ng::ROW_BYTES], ng::ROW_BYTES), "ticket b row %d", i); + } + if (cache > 0) CHECK(rd.stats().cache_hits > 0, "the row cache never hit"); + CHECK(rd.cache_size() <= rd.cache_capacity(), "row cache exceeded its bound"); + } + } + // fault injection: a 3 ms delay must be observed, and must not change the bytes + for (bool thr : {false, true}) { + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 0, err, thr), "open: %s", err.c_str()); + rd.set_injected_delay_us(3000); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + const double t0 = now_us(); + check_rows(rd, rows, N, "delayed"); + CHECK(now_us() - t0 >= 3000, "injected delay not observed (%.0f us)", now_us() - t0); + CHECK(rd.stats().late_injected > 0, "no read was held back"); + } + // keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the + // window after the last issue has passed, starts again with the next issue (even one the row cache serves), + // and never shows up as a row read or changes a row + { + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 4096, err, true), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 0.5); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, first ticket"); + const uint64_t reads0 = rd.snapshot().reads; + const auto nap = [](int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }; + nap(300); + const uint64_t k1 = rd.snapshot().keepalive_reads; + CHECK(k1 >= 8 && k1 <= 20, "keep-alive: %llu reads in 300 ms at a 20 ms period", (unsigned long long) k1); + CHECK(rd.snapshot().reads == reads0, "keep-alive reads were counted as row reads"); + nap(600); // the 0.5 s window has passed + const uint64_t k2 = rd.snapshot().keepalive_reads; + nap(300); + const uint64_t k3 = rd.snapshot().keepalive_reads; + CHECK(k3 == k2, "keep-alive went on after the window (%llu -> %llu)", (unsigned long long) k2, + (unsigned long long) k3); + CHECK(k2 <= k1 + 20, "keep-alive: %llu reads by the end of a 0.5 s window", (unsigned long long) k2); + check_rows(rd, rows, N, "keep-alive, cached ticket"); // the row cache serves all 16: no row read + CHECK(rd.snapshot().reads == reads0, "cached rows were read again"); + nap(200); + CHECK(rd.snapshot().keepalive_reads >= k3 + 5, "the keep-alive did not start again (%llu -> %llu)", + (unsigned long long) k3, (unsigned long long) rd.snapshot().keepalive_reads); + std::vector more(2000); + for (auto& r : more) r = rng() % N; + check_rows(rd, more, N, "keep-alive, rows afterwards"); + rd.set_keepalive(0, 0.5); // off + const uint64_t k4 = rd.snapshot().keepalive_reads; + nap(200); + CHECK(rd.snapshot().keepalive_reads <= k4 + 1, "keep-alive went on after it was turned off"); + rd.reset_stats(); + CHECK(rd.snapshot().keepalive_reads == 0 && rd.snapshot().keepalive_us_max == 0, "reset_stats kept keep-alive counts"); + } + { // the caller's thread does the reads: no worker, so no keep-alive + ng::PleReader rd; + std::string err; + CHECK(rd.open(path, HEADER, N, 16, 0, err, false), "open: %s", err.c_str()); + rd.set_keepalive(20.0, 1.0); + std::vector rows(16); + for (auto& r : rows) r = rng() % N; + check_rows(rd, rows, N, "keep-alive, caller thread"); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + CHECK(rd.snapshot().keepalive_reads == 0, "keep-alive without the worker thread"); + } + std::filesystem::remove(path); + std::printf("ple_reader selftest: %s\n", g_fail ? "FAILED" : "OK"); + return g_fail ? 1 : 0; +} + +int real(const std::string& gguf, int n_random, const std::string& tokens_path, uint32_t inflight, bool direct_first, + bool direct_only, bool sync_submit) { + k::PleTable mm, direct; + std::string err; + k::PleIoOptions mo; + mo.mode = k::PleIo::Mmap; + k::PleIoOptions dopt; + dopt.cache_rows = 0; // measure the SSD, not the cache + dopt.max_inflight = inflight; + dopt.io_thread = !sync_submit; + // `--direct-only` measures the direct path with NO mapping of the file alive anywhere in the process: a + // live section on the same file forces the file system to keep cached and non-cached views coherent. + if (!direct_only && !mm.open(gguf, err, mo)) { std::fprintf(stderr, "mmap open: %s\n", err.c_str()); return 2; } + if (!direct.open(gguf, err, dopt)) { std::fprintf(stderr, "direct open: %s\n", err.c_str()); return 2; } + std::vector> tickets; + std::mt19937_64 rng(11); + for (int t = 0; t < n_random / 16; ++t) { + std::vector r(16); + for (auto& x : r) x = (uint32_t) (rng() % direct.rows()); + tickets.push_back(r); + } + if (!tokens_path.empty()) { + std::ifstream f(tokens_path); + std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + for (char& c : text) if (c == ',') c = ' '; + std::istringstream in(text); + std::vector ids; + for (int32_t v; in >> v;) ids.push_back(v); + const k::PleConsts C = k::ple_artifact_consts(); + for (size_t i = 0; i < ids.size(); ++i) { + const int32_t prev[2] = {i >= 2 ? ids[i - 2] : k::TOKEN_NULL, i >= 1 ? ids[i - 1] : k::TOKEN_NULL}; + std::vector r(16); + k::ngram_rows(&ids[i], prev, 1, C, r.data()); + tickets.push_back(r); + } + } + std::vector a(k::NG_N_EMBD), b(k::NG_N_EMBD); + double t_mm = 0, t_dir = 0, t_issue = 0; + for (const auto& r : tickets) { + for (int pass = 0; pass < 2; ++pass) { + const bool do_direct = (pass == 0) == direct_first; + const double t0 = now_us(); + if (!do_direct) { + if (direct_only) continue; + mm.gather(r.data(), a.data()); + t_mm += now_us() - t0; + } else { + const double ti = now_us(); + const bool issued = direct.issue(r.data()); + t_issue += now_us() - ti; + if (!issued || !direct.collect(b.data(), err)) { + std::fprintf(stderr, "direct: %s\n", err.c_str()); + return 1; + } + t_dir += now_us() - t0; + } + } + if (!direct_only) + CHECK(!std::memcmp(a.data(), b.data(), a.size() * sizeof(float)), "token rows differ between mmap and direct"); + } + std::printf("tokens %zu: mmap %.1f us/token, direct %.1f us/token (issue on this thread %.1f us)\n%s\n", + tickets.size(), t_mm / (double) tickets.size(), t_dir / (double) tickets.size(), + t_issue / (double) tickets.size(), direct.io_report().c_str()); + std::printf("ple_reader real-table check: %s\n", g_fail ? "FAILED" : "OK (bit-identical)"); + return g_fail ? 1 : 0; +} + +} // namespace + +int main(int argc, char** argv) { + std::string gguf, dir = std::filesystem::temp_directory_path().string(), tokens; + int rows = 20000; + uint32_t inflight = 64; + bool direct_first = false; + bool direct_only = false; + bool sync_submit = false; + bool self = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--selftest") self = true; + else if (a == "--dir" && i + 1 < argc) dir = argv[++i]; + else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i]; + else if (a == "--rows" && i + 1 < argc) rows = std::atoi(argv[++i]); + else if (a == "--tokens" && i + 1 < argc) tokens = argv[++i]; + else if (a == "--inflight" && i + 1 < argc) inflight = (uint32_t) std::atoi(argv[++i]); + else if (a == "--direct-first") direct_first = true; + else if (a == "--direct-only") direct_only = true; + else if (a == "--sync") sync_submit = true; + else { std::fprintf(stderr, "usage: ple_reader_test --selftest [--dir D] | --gguf SHARD2 [--rows N] [--tokens F]\n"); return 2; } + } + if (self) return selftest(dir); + if (!gguf.empty()) return real(gguf, rows, tokens, inflight, direct_first, direct_only, sync_submit); + std::fprintf(stderr, "nothing to do\n"); + return 2; +} diff --git a/engine/strata/src/plan/plan_main.cpp b/engine/strata/src/plan/plan_main.cpp new file mode 100644 index 00000000..5cf1fda3 --- /dev/null +++ b/engine/strata/src/plan/plan_main.cpp @@ -0,0 +1,73 @@ +// src/plan/plan_main.cpp - the `strata-plan` CLI: print the memory plan, or say why it does not close. +// +// The engine must adapt to the GPU it is running on, so the plan is computed from measured free VRAM and the +// requested context rather than configured by hand. This tool is that computation on its own, which is what +// makes it testable without a GPU. +#include "strata/plan/plan.hpp" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + uint64_t ctx = 20480; + uint64_t free_vram = 12ull * 1000 * 1000 * 1000; // RTX 5070 nominal; overridden by --vram + strata::plan::Costs costs; + bool state_given = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&](uint64_t& out) { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s needs a value\n", a.c_str()); + std::exit(2); + } + out = std::strtoull(argv[++i], nullptr, 10); + }; + if (a == "--max-context") + next(ctx); + else if (a == "--vram") + next(free_vram); + else if (a == "--dense") + next(costs.dense_bytes); + else if (a == "--embd") + next(costs.embd_bytes); + else if (a == "--workspace") + next(costs.workspace_bytes); + else if (a == "--state") { + next(costs.state_bytes); + state_given = true; + } else if (a == "--pool") { + uint64_t v = 0; + next(v); + free_vram = v; + } else if (a == "--help" || a == "-h") { + std::printf("usage: strata-plan [--max-context N] [--vram BYTES] [--dense B] [--embd B]\n" + " [--workspace B] [--state B] [--pool B]\n" + " --state defaults to the geometry's own GDN recurrence + conv history, NOT to 0:\n" + " the flag used to default to zero and nothing passed it, so the planner silently\n" + " planned without 117.7 MB (85 expert slots) of non-evictable state.\n"); + return 0; + } else { + std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); + return 2; + } + } + // DEFAULT THE STATE FROM THE GEOMETRY. A `--state` that defaults to 0 and is never passed is not a + // default, it is an omission - and this one was worth 85 cache slots of overcommit. + if (!state_given) costs.state_bytes = strata::plan::state_bytes(strata::plan::Geometry{}); + // The pool is what the KV cache and the expert cache share. Derived from the card's free VRAM less the + // resident dense weights; `--pool` overrides it for reproducing the standard-tier numbers exactly. + const uint64_t pool = free_vram > costs.dense_bytes + costs.embd_bytes + ? free_vram - costs.dense_bytes - costs.embd_bytes + : 0; + try { + const strata::plan::Plan p = strata::plan::make_plan(ctx, strata::plan::Geometry{}, costs, + pool ? pool : strata::plan::vram_pool_bytes()); + std::printf("%s", strata::plan::to_string(p).c_str()); + return 0; + } catch (const strata::plan::DoesNotClose& e) { + std::fprintf(stderr, "strata-plan: %s\n", e.what()); + return 1; + } +} diff --git a/engine/strata/src/platform/direct_file.cpp b/engine/strata/src/platform/direct_file.cpp new file mode 100644 index 00000000..cd4f6a71 --- /dev/null +++ b/engine/strata/src/platform/direct_file.cpp @@ -0,0 +1,365 @@ +// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp. +#include "strata/platform/direct_file.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#else +#include +#include +#include +#endif + +namespace strata::platform { + +double now_us() { + using namespace std::chrono; + return (double) duration_cast(steady_clock::now().time_since_epoch()).count() / 1000.0; +} + +void* DirectFile::alloc_aligned(size_t bytes) { +#if defined(_WIN32) + return VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); +#else + void* p = nullptr; + return posix_memalign(&p, alignment(), bytes) == 0 ? p : nullptr; +#endif +} + +void DirectFile::free_aligned(void* p) { + if (p == nullptr) return; +#if defined(_WIN32) + VirtualFree(p, 0, MEM_RELEASE); +#else + std::free(p); +#endif +} + +namespace { +/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2). One thread +/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K +/// reads/s, while an NVMe drive serves several times that at depth. +struct Pending { + uint64_t offset; + void* buffer; + uint32_t length; + uint64_t tag; +}; + +/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each +/// thread does one blocking pread, so the thread count is the queue depth). +int io_threads(int dflt) { + const char* v = std::getenv("STRATA_IO_THREADS"); + const int n = v ? std::atoi(v) : dflt; + return std::clamp(n, 1, 64); +} +} // namespace + +#if defined(_WIN32) +// ------------------------------------------------------------------------------------------------ Windows +namespace { +/// One in-flight request. The OVERLAPPED must be the first member so a completion packet's OVERLAPPED* +/// converts back to the request. +struct Req { + OVERLAPPED ov; + uint64_t tag; +}; +} // namespace + +struct DirectFile::Impl { + HANDLE file = INVALID_HANDLE_VALUE; + HANDLE port = nullptr; + uint64_t size = 0; + std::mutex mu; // everything below + std::deque free_reqs; + std::vector all_reqs; + std::deque immediate; // requests that completed without a port packet (EOF) or failed + std::deque queue; // submitted, not yet issued + std::condition_variable cv; + bool stop = false; + std::vector pool; + + Req* take() { + if (free_reqs.empty()) { + Req* r = new Req(); + all_reqs.push_back(r); + return r; + } + Req* r = free_reqs.front(); + free_reqs.pop_front(); + return r; + } + + void issue(const Pending& p) { + Req* r; + { + std::lock_guard lk(mu); + r = take(); + } + std::memset(&r->ov, 0, sizeof r->ov); + r->ov.Offset = (DWORD) (p.offset & 0xFFFFFFFFull); + r->ov.OffsetHigh = (DWORD) (p.offset >> 32); + r->tag = p.tag; + if (!ReadFile(file, p.buffer, p.length, nullptr, &r->ov)) { + const DWORD e = GetLastError(); + if (e != ERROR_IO_PENDING) { + std::lock_guard lk(mu); + free_reqs.push_back(r); + // at or past end of file: a zero-byte completion; anything else: a failed one + immediate.push_back(Completion{p.tag, 0, e == ERROR_HANDLE_EOF}); + PostQueuedCompletionStatus(port, 0, 0, nullptr); // wake a waiter to collect it + } + } + } + + void worker() { + std::unique_lock lk(mu); + for (;;) { + cv.wait(lk, [&] { return stop || !queue.empty(); }); + if (stop && queue.empty()) return; + const Pending p = queue.front(); + queue.pop_front(); + lk.unlock(); + issue(p); + lk.lock(); + } + } + + void stop_pool() { + { + std::lock_guard lk(mu); + stop = true; + } + cv.notify_all(); + for (std::thread& t : pool) t.join(); + pool.clear(); + stop = false; + } +}; + +DirectFile::DirectFile() : impl_(new Impl) {} +DirectFile::~DirectFile() { + close(); + for (Req* r : impl_->all_reqs) delete r; + delete impl_; +} + +bool DirectFile::open(const std::string& path, std::string& err) { + close(); + const int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0); + std::wstring wpath((size_t) (wlen > 0 ? wlen : 1), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wlen); + // NO_BUFFERING: the cache manager never holds these pages, so the table cannot grow into RAM. + // RANDOM_ACCESS: no read-ahead. OVERLAPPED: many reads in flight, completed through the port below. + impl_->file = CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED | FILE_FLAG_RANDOM_ACCESS, nullptr); + if (impl_->file == INVALID_HANDLE_VALUE) { + err = "DirectFile: cannot open " + path + " (error " + std::to_string(GetLastError()) + ")"; + return false; + } + LARGE_INTEGER sz; + if (!GetFileSizeEx(impl_->file, &sz)) { + err = "DirectFile: cannot size " + path; + close(); + return false; + } + impl_->size = (uint64_t) sz.QuadPart; + impl_->port = CreateIoCompletionPort(impl_->file, nullptr, 0, 1); + if (impl_->port == nullptr) { + err = "DirectFile: CreateIoCompletionPort failed (error " + std::to_string(GetLastError()) + ")"; + close(); + return false; + } + // Completions of reads that finish synchronously are still queued to the port, so every issued read + // produces exactly one packet; `wait` is the only completion path. + const int n = io_threads(4); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + return true; +} + +void DirectFile::close() { + impl_->stop_pool(); + if (impl_->port != nullptr) CloseHandle(impl_->port); + if (impl_->file != INVALID_HANDLE_VALUE) CloseHandle(impl_->file); + impl_->port = nullptr; + impl_->file = INVALID_HANDLE_VALUE; + impl_->size = 0; + impl_->immediate.clear(); + impl_->queue.clear(); +} + +bool DirectFile::is_open() const { return impl_->file != INVALID_HANDLE_VALUE; } +uint64_t DirectFile::size() const { return impl_->size; } + +bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) { + if (!is_open()) { err = "DirectFile: not open"; return false; } + if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) { + err = "DirectFile: unaligned request"; + return false; + } + { + std::lock_guard lk(impl_->mu); + impl_->queue.push_back(Pending{offset, buffer, length, tag}); + } + impl_->cv.notify_one(); + return true; +} + +int DirectFile::wait(Completion* out, int max, int timeout_ms) { + int n = 0; + { + std::lock_guard lk(impl_->mu); + while (n < max && !impl_->immediate.empty()) { + out[n++] = impl_->immediate.front(); + impl_->immediate.pop_front(); + } + } + if (n == max || !is_open()) return n; + OVERLAPPED_ENTRY entries[64]; + const ULONG want = (ULONG) (max - n < 64 ? max - n : 64); + ULONG got = 0; + const DWORD t = timeout_ms < 0 ? INFINITE : (DWORD) timeout_ms; + if (!GetQueuedCompletionStatusEx(impl_->port, entries, want, &got, n > 0 ? 0 : t, FALSE)) return n; + std::lock_guard lk(impl_->mu); + for (ULONG i = 0; i < got; ++i) { + if (entries[i].lpOverlapped == nullptr) { // a wake() packet (or an immediate completion's nudge) + while (n < max && !impl_->immediate.empty()) { + out[n++] = impl_->immediate.front(); + impl_->immediate.pop_front(); + } + if (n < max) out[n++] = Completion{WAKE_TAG, 0, true}; + continue; + } + Req* r = (Req*) entries[i].lpOverlapped; + const uint32_t status = (uint32_t) r->ov.Internal; // an NTSTATUS + Completion c; + c.tag = r->tag; + c.bytes = entries[i].dwNumberOfBytesTransferred; + // STATUS_END_OF_FILE (0xC0000011) is a legal short read at the table's last page. + c.ok = status == 0 || status == 0xC0000011u; + out[n++] = c; + impl_->free_reqs.push_back(r); + } + return n; +} + +void DirectFile::wake() { + if (impl_->port != nullptr) PostQueuedCompletionStatus(impl_->port, 0, 0, nullptr); +} + +#else +// ------------------------------------------------------------------------------------------------ POSIX +// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread +// count is the queue depth). It replaced one synchronous pread inside `submit`, which read the n-gram table's +// rows one at a time. +struct DirectFile::Impl { + int fd = -1; + uint64_t size = 0; + std::mutex mu; + std::condition_variable cv_work, cv_done; + std::deque queue; + std::deque done; + bool stop = false; + std::vector pool; + + void worker() { + std::unique_lock lk(mu); + for (;;) { + cv_work.wait(lk, [&] { return stop || !queue.empty(); }); + if (stop && queue.empty()) return; + const Pending p = queue.front(); + queue.pop_front(); + lk.unlock(); + const ssize_t got = pread(fd, p.buffer, p.length, (off_t) p.offset); + lk.lock(); + done.push_back(Completion{p.tag, got < 0 ? 0u : (uint32_t) got, got >= 0}); + cv_done.notify_all(); + } + } + + void stop_pool() { + { + std::lock_guard lk(mu); + stop = true; + } + cv_work.notify_all(); + for (std::thread& t : pool) t.join(); + pool.clear(); + stop = false; + } +}; + +DirectFile::DirectFile() : impl_(new Impl) {} +DirectFile::~DirectFile() { close(); delete impl_; } + +bool DirectFile::open(const std::string& path, std::string& err) { + close(); + impl_->fd = ::open(path.c_str(), O_RDONLY | O_DIRECT); + if (impl_->fd < 0) { err = "DirectFile: cannot open " + path; return false; } + struct stat st; + if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; } + impl_->size = (uint64_t) st.st_size; + const int n = io_threads(16); + for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); }); + return true; +} + +void DirectFile::close() { + impl_->stop_pool(); + if (impl_->fd >= 0) ::close(impl_->fd); + impl_->fd = -1; + impl_->size = 0; + impl_->done.clear(); + impl_->queue.clear(); +} + +bool DirectFile::is_open() const { return impl_->fd >= 0; } +uint64_t DirectFile::size() const { return impl_->size; } + +bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t tag, std::string& err) { + if (offset % alignment() || length % alignment() || ((uintptr_t) buffer) % alignment() || length == 0) { + err = "DirectFile: unaligned request"; + return false; + } + { + std::lock_guard lk(impl_->mu); + impl_->queue.push_back(Pending{offset, buffer, length, tag}); + } + impl_->cv_work.notify_one(); + return true; +} + +void DirectFile::wake() { + std::lock_guard lk(impl_->mu); + impl_->done.push_back(Completion{WAKE_TAG, 0, true}); + impl_->cv_done.notify_all(); +} + +int DirectFile::wait(Completion* out, int max, int timeout_ms) { + std::unique_lock lk(impl_->mu); + if (impl_->done.empty() && timeout_ms != 0) { + auto ready = [&] { return !impl_->done.empty(); }; + if (timeout_ms < 0) impl_->cv_done.wait(lk, ready); + else impl_->cv_done.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready); + } + int n = 0; + while (n < max && !impl_->done.empty()) { + out[n++] = impl_->done.front(); + impl_->done.pop_front(); + } + return n; +} +#endif + +} // namespace strata::platform diff --git a/engine/strata/src/platform/memory.cpp b/engine/strata/src/platform/memory.cpp new file mode 100644 index 00000000..f3b40e8d --- /dev/null +++ b/engine/strata/src/platform/memory.cpp @@ -0,0 +1,138 @@ +// src/platform/memory.cpp - see include/strata/platform/memory.hpp. +#include "strata/platform/memory.hpp" + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#include +#else +#include +#include +#endif + +namespace strata::platform { + +#if defined(_WIN32) +LockResult lock_resident(void* p, uint64_t bytes) { + LockResult r; + if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; } + HANDLE self = GetCurrentProcess(); + SIZE_T min_ws = 0, max_ws = 0; + DWORD flags = 0; + if (!GetProcessWorkingSetSizeEx(self, &min_ws, &max_ws, &flags)) { + r.note = "GetProcessWorkingSetSizeEx failed (error " + std::to_string(GetLastError()) + ")"; + return r; + } + // Locked pages count against the minimum working set, so it must grow by the region plus headroom for the + // rest of the process. Soft limits: the maximum is not enforced, only the minimum is raised. + const SIZE_T margin = (SIZE_T) 512 << 20; + const SIZE_T new_min = min_ws + (SIZE_T) bytes + margin; + const SIZE_T new_max = max_ws > new_min + margin ? max_ws : new_min + margin; + if (!SetProcessWorkingSetSizeEx(self, new_min, new_max, + QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) { + r.note = "SetProcessWorkingSetSizeEx(" + std::to_string((unsigned long long) (new_min >> 20)) + + " MiB) failed (error " + std::to_string(GetLastError()) + ")"; + return r; + } + const uint64_t chunk = 1ull << 30; + uint8_t* base = (uint8_t*) p; + for (uint64_t off = 0; off < bytes; off += chunk) { + const uint64_t n = bytes - off < chunk ? bytes - off : chunk; + if (!VirtualLock(base + off, (SIZE_T) n)) { + r.note = "VirtualLock stopped at " + std::to_string((unsigned long long) (off >> 20)) + " of " + + std::to_string((unsigned long long) (bytes >> 20)) + " MiB (error " + + std::to_string(GetLastError()) + ")"; + r.ok = off > 0; + return r; + } + r.locked_bytes = off + n; + } + r.ok = true; + r.note = "locked " + std::to_string((unsigned long long) (bytes >> 20)) + " MiB via working-set minimum + VirtualLock"; + return r; +} + +void unlock_resident(void* p, uint64_t bytes) { + if (p == nullptr || bytes == 0) return; + const uint64_t chunk = 1ull << 30; + for (uint64_t off = 0; off < bytes; off += chunk) + VirtualUnlock((uint8_t*) p + off, (SIZE_T) (bytes - off < chunk ? bytes - off : chunk)); +} + +bool gpu_shared_memory_budget(const void* luid, uint64_t& budget, uint64_t& usage, std::string& why) { + budget = usage = 0; + // dxgi.dll is loaded when asked, not linked: a start that never needs this keeps the imports it had + HMODULE dxgi = LoadLibraryA("dxgi.dll"); + if (dxgi == nullptr) { why = "dxgi.dll not found"; return false; } + using CreateFactory = HRESULT(WINAPI*)(REFIID, void**); + const auto create = (CreateFactory) (void*) GetProcAddress(dxgi, "CreateDXGIFactory1"); + IDXGIFactory1* factory = nullptr; + if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), (void**) &factory)) || factory == nullptr) { + why = "CreateDXGIFactory1 failed"; + FreeLibrary(dxgi); + return false; + } + bool ok = false; + why = "no DXGI adapter has the CUDA device's LUID"; + for (UINT i = 0; !ok; ++i) { + IDXGIAdapter1* a = nullptr; + if (factory->EnumAdapters1(i, &a) == DXGI_ERROR_NOT_FOUND || a == nullptr) break; + DXGI_ADAPTER_DESC1 d{}; + if (SUCCEEDED(a->GetDesc1(&d)) && std::memcmp(&d.AdapterLuid, luid, sizeof d.AdapterLuid) == 0) { + IDXGIAdapter3* a3 = nullptr; + DXGI_QUERY_VIDEO_MEMORY_INFO info{}; + if (SUCCEEDED(a->QueryInterface(__uuidof(IDXGIAdapter3), (void**) &a3)) && a3 != nullptr && + SUCCEEDED(a3->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &info))) { + budget = info.Budget; + usage = info.CurrentUsage; + ok = budget > 0; + why = ok ? "" : "the adapter reports no shared-memory budget"; + } else { + why = "QueryVideoMemoryInfo failed"; + } + if (a3 != nullptr) a3->Release(); + a->Release(); + break; + } + a->Release(); + } + factory->Release(); + FreeLibrary(dxgi); + return ok; +} + +uint64_t total_physical_memory() { + MEMORYSTATUSEX ms{}; + ms.dwLength = sizeof ms; + return GlobalMemoryStatusEx(&ms) ? (uint64_t) ms.ullTotalPhys : 0; +} +#else +LockResult lock_resident(void* p, uint64_t bytes) { + LockResult r; + if (p == nullptr || bytes == 0) { r.note = "nothing to lock"; return r; } + if (mlock(p, bytes) != 0) { r.note = "mlock failed (raise ulimit -l)"; return r; } + r.ok = true; + r.locked_bytes = bytes; + r.note = "mlock"; + return r; +} + +void unlock_resident(void* p, uint64_t bytes) { + if (p != nullptr && bytes != 0) munlock(p, bytes); +} + +bool gpu_shared_memory_budget(const void*, uint64_t& budget, uint64_t& usage, std::string& why) { + budget = usage = 0; + why = "DXGI is Windows-only"; + return false; +} + +uint64_t total_physical_memory() { + const long pages = sysconf(_SC_PHYS_PAGES), page = sysconf(_SC_PAGE_SIZE); + return pages > 0 && page > 0 ? (uint64_t) pages * (uint64_t) page : 0; +} +#endif + +} // namespace strata::platform diff --git a/engine/strata/src/platform/memory_test.cpp b/engine/strata/src/platform/memory_test.cpp new file mode 100644 index 00000000..e5b4cde7 --- /dev/null +++ b/engine/strata/src/platform/memory_test.cpp @@ -0,0 +1,35 @@ +// src/platform/memory_test.cpp - plan v0.3 P0.1: lock_resident on a 256 MiB region (CPU only, no GPU, no model). +#include "strata/platform/memory.hpp" + +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#pragma comment(lib, "psapi.lib") +#endif + +int main() { + const uint64_t bytes = 256ull << 20; + void* p = std::malloc(bytes); + if (p == nullptr) return 2; + std::memset(p, 1, bytes); + const strata::platform::LockResult r = strata::platform::lock_resident(p, bytes); + std::printf("lock_resident: ok=%d locked=%llu MiB (%s)\n", (int) r.ok, (unsigned long long) (r.locked_bytes >> 20), + r.note.c_str()); + int fail = !(r.ok && r.locked_bytes == bytes); +#if defined(_WIN32) + PROCESS_MEMORY_COUNTERS pmc{}; + GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc); + std::printf("working set %llu MiB\n", (unsigned long long) (pmc.WorkingSetSize >> 20)); + fail |= pmc.WorkingSetSize < bytes; +#endif + strata::platform::unlock_resident(p, bytes); + std::free(p); + std::printf("platform_memory_test: %s\n", fail ? "FAILED" : "OK"); + return fail; +} diff --git a/engine/strata/src/prefill/gemm.cu b/engine/strata/src/prefill/gemm.cu new file mode 100644 index 00000000..bb6ef045 --- /dev/null +++ b/engine/strata/src/prefill/gemm.cu @@ -0,0 +1,432 @@ +// src/prefill/gemm.cu - see include/strata/prefill/gemm.hpp. +#include "strata/prefill/gemm.hpp" +#include "strata/kernels/dequant_bf16.hpp" + +#include +#include + +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) +// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers. +// hipBLASLt's public headers declare native HIP shuffle functions, so keep +// those declarations from being macro-expanded in this translation unit. +#undef __shfl_xor_sync +#undef __shfl_down_sync +#undef __shfl_up_sync +#undef __shfl_sync +#undef __ballot_sync +#endif + +#include +#include +#include +#include +#include + +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) +#include "hipblaslt_tuning.hpp" +#include +#include +#include +#include +#include +#include +#endif + +namespace strata::prefill { +namespace { + +void ck(cublasStatus_t s, const char* what) { + if (s != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d\n", what, (int) s); + std::exit(1); + } +} + +// #247/#325: on Windows (seen on gfx1201), hipBLAS can return success with the correct BF16/FP16 product for some +// shapes (hc up once T >= 96, the router) and still leave hipErrorInvalidValue set, which the next kernel's error +// check turns into an exit. The multiply has finished, so that one stale error is cleared after a GEMM that succeeded; +// any other error still stops the engine. Windows only: on Linux a stale hipErrorInvalidValue is a real error from +// an earlier call and keeps being reported. A no-op everywhere else (CUDA compiles none of it). +#if defined(__HIPCC__) && defined(_WIN32) +void absorb_hipblas_sticky(const char* what) { + const hipError_t sticky = hipGetLastError(); + if (sticky == hipSuccess || sticky == hipErrorInvalidValue) return; + std::fprintf(stderr, "prefill gemm: %s left %s\n", what, hipGetErrorString(sticky)); + std::exit(1); +} +#define STRATA_ABSORB_HIPBLAS_STICKY(what) absorb_hipblas_sticky(what) +#else +#define STRATA_ABSORB_HIPBLAS_STICKY(what) ((void) 0) +#endif + +// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said. +void note(cublasStatus_t s, const char* what) { + if (s != CUBLAS_STATUS_SUCCESS) std::fprintf(stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what, (int) s); +} + +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) +struct HipLtCallKey { + strata::prefill::hipblaslt::InputType type; + int t; + int n; + int k; + int ldy; + uint32_t beta_bits; + + bool operator<(const HipLtCallKey& other) const { + return std::tie(type, n, k, ldy, t, beta_bits) < + std::tie(other.type, other.n, other.k, other.ldy, other.t, other.beta_bits); + } +}; + +struct HipLtCachedAlgo { + bool supported = false; + hipblasLtMatmulAlgo_t algo{}; + size_t workspace_bytes = 0; +}; + +struct HipLtState { + hipblasLtHandle_t handle = nullptr; + void* workspace = nullptr; + size_t workspace_bytes = 0; + strata::prefill::hipblaslt::TuningTable table; + std::map cache; + uint64_t lt_launches = 0; + uint64_t fallbacks = 0; + std::set> fallback_shapes; + + ~HipLtState() { + if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) { + std::fprintf(stderr, "prefill gemm: hipBLASLt summary launches=%llu fallbacks=%llu unique_fallback_shapes=%zu\n", + (unsigned long long) lt_launches, (unsigned long long) fallbacks, fallback_shapes.size()); + for (const auto& shape : fallback_shapes) { + const auto type = std::get<0>(shape); + std::fprintf(stderr, "prefill gemm: fallback shape dtype=%s T=%d N=%d K=%d ldy=%d\n", + type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", + std::get<1>(shape), std::get<2>(shape), std::get<3>(shape), std::get<4>(shape)); + } + } + if (handle) hipblasLtDestroy(handle); + } +}; + +struct HipLtDescriptors { + hipblasLtMatmulDesc_t op = nullptr; + hipblasLtMatrixLayout_t a = nullptr; + hipblasLtMatrixLayout_t b = nullptr; + hipblasLtMatrixLayout_t c = nullptr; + + ~HipLtDescriptors() { + if (op) hipblasLtMatmulDescDestroy(op); + if (a) hipblasLtMatrixLayoutDestroy(a); + if (b) hipblasLtMatrixLayoutDestroy(b); + if (c) hipblasLtMatrixLayoutDestroy(c); + } + + bool init(hipDataType type, int t, int n, int k, int ldy) { + const hipblasOperation_t trans_a = HIPBLAS_OP_T; + const hipblasOperation_t trans_b = HIPBLAS_OP_N; + if (hipblasLtMatmulDescCreate(&op, HIPBLAS_COMPUTE_32F, HIP_R_32F) != HIPBLAS_STATUS_SUCCESS || + hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSA, &trans_a, sizeof(trans_a)) != + HIPBLAS_STATUS_SUCCESS || + hipblasLtMatmulDescSetAttribute(op, HIPBLASLT_MATMUL_DESC_TRANSB, &trans_b, sizeof(trans_b)) != + HIPBLAS_STATUS_SUCCESS || + hipblasLtMatrixLayoutCreate(&a, type, k, n, k) != HIPBLAS_STATUS_SUCCESS || + hipblasLtMatrixLayoutCreate(&b, type, k, t, k) != HIPBLAS_STATUS_SUCCESS || + hipblasLtMatrixLayoutCreate(&c, HIP_R_32F, n, t, ldy) != HIPBLAS_STATUS_SUCCESS) { + return false; + } + return true; + } +}; + +std::unique_ptr create_hipblaslt_state(void* workspace, size_t workspace_bytes) { + const char* path = std::getenv("STRATA_HIPBLASLT_TUNING"); + if (!path || !*path) return nullptr; + + auto state = std::make_unique(); + state->workspace = workspace; + state->workspace_bytes = workspace_bytes; + if (hipblasLtCreate(&state->handle) != HIPBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "prefill gemm: hipBLASLt handle creation failed; using hipBLASEx\n"); + return nullptr; + } + + int version = 0; + if (hipblasLtGetVersion(state->handle, &version) != HIPBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "prefill gemm: hipBLASLt version query failed; using hipBLASEx\n"); + return nullptr; + } + int device = 0; + hipDeviceProp_t properties{}; + if (hipGetDevice(&device) != hipSuccess || hipGetDeviceProperties(&properties, device) != hipSuccess) { + std::fprintf(stderr, "prefill gemm: HIP device query failed; using hipBLASEx\n"); + return nullptr; + } + std::string arch(properties.gcnArchName); + const auto suffix = arch.find(':'); + if (suffix != std::string::npos) arch.resize(suffix); + + std::string error; + if (!state->table.load(path, arch, version, error)) { + std::fprintf(stderr, "prefill gemm: %s; using hipBLASEx\n", error.c_str()); + return nullptr; + } + std::fprintf(stderr, "prefill gemm: hipBLASLt tuning enabled (%zu rows, %s, version %d)\n", + state->table.rows().size(), arch.c_str(), version); + return state; +} + +HipLtCachedAlgo resolve_hipblaslt_algo(HipLtState& state, strata::prefill::hipblaslt::InputType type, int t, + int n, int k, int ldy, float beta) { + uint32_t beta_bits = 0; + static_assert(sizeof(beta_bits) == sizeof(beta)); + std::memcpy(&beta_bits, &beta, sizeof(beta)); + const HipLtCallKey key{type, t, n, k, ldy, beta_bits}; + const auto cached = state.cache.find(key); + if (cached != state.cache.end()) return cached->second; + + HipLtCachedAlgo resolved; + const bool verbose = std::getenv("STRATA_HIPBLASLT_VERBOSE") != nullptr; + const auto* row = state.table.closest(type, n, k, ldy, t); + if (!row) { + if (verbose) { + std::fprintf(stderr, "prefill gemm: Lt fallback; no calibration for dtype=%s T=%d N=%d K=%d ldy=%d\n", + type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, k, ldy); + } + return state.cache.emplace(key, resolved).first->second; + } + + HipLtDescriptors desc; + const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; + if (!desc.init(input_type, t, n, k, ldy)) { + return state.cache.emplace(key, resolved).first->second; + } + + std::vector solution_ids{row->solution_id}; + std::vector candidates; + if (hipblaslt_ext::getAlgosFromIndex(state.handle, solution_ids, candidates) != HIPBLAS_STATUS_SUCCESS || + candidates.empty() || candidates.front().state != HIPBLAS_STATUS_SUCCESS || + hipblaslt_ext::getIndexFromAlgo(candidates.front().algo) != row->solution_id) { + if (verbose) { + std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d unavailable for T=%d N=%d K=%d ldy=%d\n", + row->solution_id, t, n, k, ldy); + } + return state.cache.emplace(key, resolved).first->second; + } + + const float alpha = 1.0f; + size_t required_workspace = 0; + auto algo = candidates.front().algo; + if (hipblaslt_ext::matmulIsAlgoSupported(state.handle, desc.op, &alpha, desc.a, desc.b, &beta, desc.c, desc.c, + algo, required_workspace) != HIPBLAS_STATUS_SUCCESS) { + if (verbose) { + std::fprintf(stderr, "prefill gemm: Lt fallback; solution %d rejects actual T=%d N=%d K=%d ldy=%d beta=%.9g\n", + row->solution_id, t, n, k, ldy, beta); + } + return state.cache.emplace(key, resolved).first->second; + } + + resolved.supported = true; + resolved.algo = algo; + resolved.workspace_bytes = required_workspace; + if (verbose) { + std::fprintf(stderr, + "prefill gemm: Lt solution=%d dtype=%s T=%d N=%d K=%d ldy=%d beta=%.9g workspace=%zu\n", + row->solution_id, type == strata::prefill::hipblaslt::InputType::bf16 ? "bf16" : "f16", t, n, + k, ldy, beta, required_workspace); + } + return state.cache.emplace(key, resolved).first->second; +} + +bool try_hipblaslt(void* opaque_state, strata::prefill::hipblaslt::InputType type, const uint16_t* x, + const uint16_t* w, float* y, int64_t t, int64_t n, int64_t k, int64_t ldy, float beta, + void* stream) { + auto* state = static_cast(opaque_state); + if (!state || t <= 0 || n <= 0 || k <= 0 || t > INT_MAX || n > INT_MAX || k > INT_MAX || ldy > INT_MAX || + ldy < n) { + return false; + } + const auto resolved = resolve_hipblaslt_algo(*state, type, (int) t, (int) n, (int) k, (int) ldy, beta); + if (!resolved.supported) { + ++state->fallbacks; + state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); + return false; + } + if (resolved.workspace_bytes > state->workspace_bytes) { + ++state->fallbacks; + state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); + if (std::getenv("STRATA_HIPBLASLT_VERBOSE")) { + std::fprintf(stderr, "prefill gemm: Lt fallback; solution needs %zu workspace bytes, have %zu\n", + resolved.workspace_bytes, state->workspace_bytes); + } + return false; + } + + HipLtDescriptors desc; + const hipDataType input_type = type == strata::prefill::hipblaslt::InputType::bf16 ? HIP_R_16BF : HIP_R_16F; + if (!desc.init(input_type, (int) t, (int) n, (int) k, (int) ldy)) return false; + const float alpha = 1.0f; + const hipblasStatus_t status = hipblasLtMatmul(state->handle, desc.op, &alpha, w, desc.a, x, desc.b, &beta, y, + desc.c, y, desc.c, &resolved.algo, state->workspace, + state->workspace_bytes, (hipStream_t) stream); + if (status == HIPBLAS_STATUS_SUCCESS) { + ++state->lt_launches; + return true; + } + + std::fprintf(stderr, "prefill gemm: hipBLASLt launch failed with status %d\n", (int) status); + if (beta != 0.0f) { + std::fprintf(stderr, "prefill gemm: refusing a fallback after hipBLASLt failed with nonzero beta\n"); + std::exit(1); + } + auto* mutable_state = static_cast(opaque_state); + uint32_t beta_bits = 0; + std::memcpy(&beta_bits, &beta, sizeof(beta_bits)); + auto cached = mutable_state->cache.find(HipLtCallKey{type, (int) t, (int) n, (int) k, (int) ldy, beta_bits}); + if (cached != mutable_state->cache.end()) cached->second.supported = false; + ++mutable_state->fallbacks; + mutable_state->fallback_shapes.emplace(type, (int) t, (int) n, (int) k, (int) ldy); + return false; +} +#endif + +} // namespace + +Gemm::~Gemm() { +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + delete static_cast(hipblaslt_state_); +#endif + if (handle_) cublasDestroy((cublasHandle_t) handle_); + if (!external_) { + if (scratch_) cudaFree(scratch_); + if (workspace_) cudaFree(workspace_); + } +} + +bool Gemm::init_external(void* stream, uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes, + std::string& err) { + cublasHandle_t h = nullptr; + if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) { + err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s); + return false; + } + handle_ = h; + stream_ = stream; + external_ = true; + note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream"); + workspace_ = workspace; + note(cublasSetWorkspace(h, workspace_, ws_bytes), "cublasSetWorkspace"); + note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode"); + scratch_ = scratch; + scratch_elems_ = scratch_elems; +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + hipblaslt_state_ = create_hipblaslt_state(workspace_, ws_bytes).release(); +#endif + return true; +} + +void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes) { + scratch_ = scratch; + scratch_elems_ = scratch_elems; + workspace_ = workspace; + cublasSetWorkspace((cublasHandle_t) handle_, workspace_, ws_bytes); +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + if (hipblaslt_state_) { + auto* state = static_cast(hipblaslt_state_); + state->workspace = workspace_; + state->workspace_bytes = ws_bytes; + } +#endif +} + +bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) { + // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install + cublasHandle_t h = nullptr; + if (const cublasStatus_t s = cublasCreate(&h); s != CUBLAS_STATUS_SUCCESS) { + err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s); + return false; + } + handle_ = h; + stream_ = stream; + note(cublasSetStream(h, (cudaStream_t) stream), "cublasSetStream"); + // A fixed workspace so the handle never allocates on the way (and graphs could capture it later). + const size_t ws = 32u << 20; + if (const cudaError_t e = cudaMalloc(&workspace_, ws); e != cudaSuccess) { + err = std::string("prefill gemm: workspace of 32 MiB: ") + cudaGetErrorString(e); + return false; + } + note(cublasSetWorkspace(h, workspace_, ws), "cublasSetWorkspace"); + note(cublasSetMathMode(h, CUBLAS_DEFAULT_MATH), "cublasSetMathMode"); +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release(); +#endif + if (scratch_elems > 0) { + if (const cudaError_t e = cudaMalloc((void**) &scratch_, (size_t) scratch_elems * 2); e != cudaSuccess) { + err = "prefill gemm: dequant scratch of " + std::to_string(scratch_elems * 2 >> 20) + " MiB: " + + cudaGetErrorString(e); + return false; + } + } + scratch_elems_ = scratch_elems; + return true; +} + +void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta) { + if (T <= 0 || N <= 0) return; + if (ldy <= 0) ldy = N; + const float alpha = 1.0f; +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::bf16, X, W, Y, T, N, K, ldy, + beta, stream_)) { + STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16"); + return; + } +#endif + // Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T]. + ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, + CUDA_R_16BF, (int) K, X, CUDA_R_16BF, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, + CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), + "cublasGemmEx"); + STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx"); +} + +void Gemm::f16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy, + float beta) { + if (T <= 0 || N <= 0) return; + if (ldy <= 0) ldy = N; + const float alpha = 1.0f; +#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE) + if (try_hipblaslt(hipblaslt_state_, strata::prefill::hipblaslt::InputType::f16, X, W, Y, T, N, K, ldy, + beta, stream_)) { + STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt f16"); + return; + } +#endif + ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W, + CUDA_R_16F, (int) K, X, CUDA_R_16F, (int) K, &beta, Y, CUDA_R_32F, (int) ldy, + CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT), + "cublasGemmEx f16"); + STRATA_ABSORB_HIPBLAS_STICKY("cublasGemmEx f16"); +} + +void Gemm::native(const uint16_t* X, int ggml_type, const void* W_blocks, float* Y, int64_t T, int64_t N, int64_t K, + int64_t ldy, float beta) { + if (N * K > scratch_elems_) { + // Too large for the scratch at once: in row slices. + const int64_t rows = scratch_elems_ / K; + if (rows <= 0) { std::fprintf(stderr, "prefill gemm: scratch too small for K=%lld\n", (long long) K); std::exit(1); } + if (ldy <= 0) ldy = N; + for (int64_t r0 = 0; r0 < N; r0 += rows) { + const int64_t n = (N - r0 < rows) ? N - r0 : rows; + strata::kernels::dequant_f16(ggml_type, W_blocks, r0, n, K, scratch_, stream_); + f16(X, scratch_, Y + r0, T, n, K, ldy, beta); + } + return; + } + strata::kernels::dequant_f16(ggml_type, W_blocks, 0, N, K, scratch_, stream_); + f16(X, scratch_, Y, T, N, K, ldy, beta); +} + +} // namespace strata::prefill diff --git a/engine/strata/src/prefill/ggml_cuda_host.cu b/engine/strata/src/prefill/ggml_cuda_host.cu new file mode 100644 index 00000000..c8f8284b --- /dev/null +++ b/engine/strata/src/prefill/ggml_cuda_host.cu @@ -0,0 +1,134 @@ +// src/prefill/ggml_cuda_host.cu - prompt-speed plan step 2b: the host-side symbols of llama.cpp's ggml-cuda that its MMQ +// and quantize code reference, for the MMQ kernels compiled into strata_mmq without the rest of ggml-cuda.cu. +#include "strata/core/emulate.hpp" +#include "common.cuh" + +#include +#include +#include +#include +#include + +[[noreturn]] void ggml_cuda_error(const char * stmt, const char * func, const char * file, int line, const char * msg) { + std::fprintf(stderr, "ggml-cuda (strata mmq): %s: %s\n in %s at %s:%d\n", msg, stmt, func, file, line); + std::abort(); +} + +int ggml_cuda_get_device() { + int id = 0; + CUDA_CHECK(cudaGetDevice(&id)); + return id; +} + +#if defined(GGML_USE_HIP) +namespace { + +unsigned parse_hex(const std::string& value) { + if (value.empty()) return 0; + char* end = nullptr; + const unsigned long parsed = std::strtoul(value.c_str(), &end, 16); + return end == value.c_str() || *end != '\0' ? 0 : static_cast(parsed); +} + +// Match GGML's AMD cc encoding: OFFSET_AMD + gfx major * 0x100 + minor/stepping. +// For example, gfx1100 maps to GGML_CUDA_CC_RDNA3 (0x01001100). +int ggml_cuda_parse_amd_id(const char* device_name) { + if (device_name == nullptr) return GGML_CUDA_CC_OFFSET_AMD; + + std::string arch(device_name); + if (arch.compare(0, 3, "gfx") == 0) arch.erase(0, 3); + const size_t suffix = arch.find(':'); + if (suffix != std::string::npos) arch.resize(suffix); + + const size_t generic = arch.rfind("-generic"); + if (generic != std::string::npos && generic + 8 == arch.size()) arch.resize(generic); + + unsigned major = 0; + unsigned minor = 0; + const size_t separator = arch.find('-'); + if (separator != std::string::npos) { + major = parse_hex(arch.substr(0, separator)); + minor = parse_hex(arch.substr(separator + 1)) * 0x10; + } else if (arch.size() >= 3) { + minor = parse_hex(arch.substr(arch.size() - 2)); + major = parse_hex(arch.substr(0, arch.size() - 2)); + } + return GGML_CUDA_CC_OFFSET_AMD + static_cast(major * 0x100 + minor); +} + +} // namespace +#endif + +const ggml_cuda_device_info & ggml_cuda_info() { + static ggml_cuda_device_info info = [] { + ggml_cuda_device_info in = {}; + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess) n = 0; + n = n > GGML_CUDA_MAX_DEVICES ? GGML_CUDA_MAX_DEVICES : n; + in.device_count = n; + in.physical_device_count = n; + for (int id = 0; id < n; ++id) { + cudaDeviceProp prop; + CUDA_CHECK(cudaGetDeviceProperties(&prop, id)); + auto & d = in.devices[id]; +#if defined(GGML_USE_HIP) + d.cc = ggml_cuda_parse_amd_id(prop.gcnArchName); + if ((d.cc & 0xff00) == 0) { + // Fall back to HIP's device version fields if its architecture name is unavailable. + d.cc = GGML_CUDA_CC_OFFSET_AMD + prop.major * 0x100 + prop.minor * 0x10; + } + d.smpbo = prop.sharedMemPerBlock; + d.integrated = false; + d.supports_cooperative_launch = false; +#else + d.cc = 100 * strata::cc_major_of(prop.major) + 10 * strata::cc_minor_of(prop.minor); // STRATA_EMULATE_CC + d.smpbo = strata::smem_optin_of((int) prop.sharedMemPerBlockOptin); + d.integrated = prop.integrated != 0; + d.supports_cooperative_launch = prop.cooperativeLaunch != 0; +#endif + d.nsm = prop.multiProcessorCount; + d.smpb = prop.sharedMemPerBlock; + d.vmm = false; + d.total_vram = prop.totalGlobalMem; + d.warp_size = prop.warpSize; + d.physical_device = id; + d.physical_share_count = 1; + d.virtual_index = 0; + } + return in; + }(); + return info; +} + +namespace { +// Buffers are kept and reused: MMQ asks for the same few sizes every launch (its stream-k fixup tiles). +struct CachingPool : ggml_cuda_pool { + struct Buf { void * p; size_t size; bool used; }; + std::vector bufs; + std::mutex mu; + void * alloc(size_t size, size_t * actual_size) override { + std::lock_guard lk(mu); + for (auto & b : bufs) + if (!b.used && b.size >= size) { b.used = true; *actual_size = b.size; return b.p; } + void * p = nullptr; + CUDA_CHECK(cudaMalloc(&p, size)); + bufs.push_back({p, size, true}); + *actual_size = size; + return p; + } + void free(void * ptr, size_t) override { + std::lock_guard lk(mu); + for (auto & b : bufs) + if (b.p == ptr) { b.used = false; return; } + } + ~CachingPool() override { + for (auto & b : bufs) cudaFree(b.p); + } +}; +} // namespace + +std::unique_ptr ggml_backend_cuda_context::new_pool_for_device(int, int) { + return std::unique_ptr(new CachingPool()); +} + +ggml_backend_cuda_context::~ggml_backend_cuda_context() {} diff --git a/engine/strata/src/prefill/hipblaslt_tuning.hpp b/engine/strata/src/prefill/hipblaslt_tuning.hpp new file mode 100644 index 00000000..b9d7f54b --- /dev/null +++ b/engine/strata/src/prefill/hipblaslt_tuning.hpp @@ -0,0 +1,123 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace strata::prefill::hipblaslt { + +enum class InputType : uint8_t { f16, bf16 }; + +struct TuningRow { + InputType type = InputType::bf16; + int n = 0; + int k = 0; + int ldy = 0; + int t_bucket = 0; + int solution_id = -1; +}; + +class TuningTable { +public: + bool load(const std::string& path, const std::string& expected_arch, int expected_version, std::string& err) { + std::ifstream input(path); + if (!input) { + err = "cannot open tuning file"; + return false; + } + + bool saw_header = false; + std::string line; + size_t line_number = 0; + while (std::getline(input, line)) { + ++line_number; + const auto first = line.find_first_not_of(" \t\r\n"); + if (first == std::string::npos || line[first] == '#') continue; + + std::istringstream row(line.substr(first)); + if (!saw_header) { + std::string magic; + std::string arch; + int version = 0; + std::string extra; + if (!(row >> magic >> arch >> version) || (row >> extra) || magic != "STRATA_HIPBLASLT_TUNING_V1") { + err = "invalid tuning header at line " + std::to_string(line_number); + return false; + } + if (arch != expected_arch) { + err = "tuning architecture mismatch: file=" + arch + " runtime=" + expected_arch; + return false; + } + if (version != expected_version) { + err = "hipBLASLt version mismatch: file=" + std::to_string(version) + + " runtime=" + std::to_string(expected_version); + return false; + } + arch_ = std::move(arch); + version_ = version; + saw_header = true; + continue; + } + + std::string type_name; + int n = 0, k = 0, ldy = 0, t_bucket = 0, solution_id = -1; + std::string extra; + if (!(row >> type_name >> n >> k >> ldy >> t_bucket >> solution_id) || (row >> extra) || + (type_name != "f16" && type_name != "bf16") || n <= 0 || k <= 0 || ldy < n || t_bucket <= 0 || + solution_id < 0) { + err = "invalid tuning row at line " + std::to_string(line_number); + return false; + } + TuningRow parsed; + parsed.type = type_name == "f16" ? InputType::f16 : InputType::bf16; + parsed.n = n; + parsed.k = k; + parsed.ldy = ldy; + parsed.t_bucket = t_bucket; + parsed.solution_id = solution_id; + for (const auto& existing : rows_) { + if (existing.type == parsed.type && existing.n == parsed.n && existing.k == parsed.k && + existing.ldy == parsed.ldy && existing.t_bucket == parsed.t_bucket) { + err = "duplicate tuning key at line " + std::to_string(line_number); + return false; + } + } + rows_.push_back(parsed); + } + if (!saw_header) { + err = "tuning file has no header"; + return false; + } + return true; + } + + const TuningRow* closest(InputType type, int n, int k, int ldy, int t) const { + const TuningRow* best = nullptr; + int64_t best_distance = std::numeric_limits::max(); + for (const auto& row : rows_) { + if (row.type != type || row.n != n || row.k != k || row.ldy != ldy) continue; + const int64_t distance = row.t_bucket >= t ? int64_t(row.t_bucket) - t : int64_t(t) - row.t_bucket; + if (distance < best_distance || + (distance == best_distance && (!best || row.t_bucket < best->t_bucket))) { + best = &row; + best_distance = distance; + } + } + return best; + } + + const std::vector& rows() const { return rows_; } + const std::string& arch() const { return arch_; } + int version() const { return version_; } + +private: + std::string arch_; + int version_ = 0; + std::vector rows_; +}; + +} // namespace strata::prefill::hipblaslt diff --git a/engine/strata/src/prefill/kernels.cu b/engine/strata/src/prefill/kernels.cu new file mode 100644 index 00000000..4c5f4b82 --- /dev/null +++ b/engine/strata/src/prefill/kernels.cu @@ -0,0 +1,843 @@ +// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp. +#include "strata/prefill/kernels.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/router_top10.hpp" + +#include +#include + +#include +#include +#include +#include + +namespace strata::prefill { +namespace { + +constexpr int N = 2560, HC = 4, D = N * HC, LR = 320; +constexpr int S = 128, HK = 16, HV = 48, C = 10240; + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} +__device__ __forceinline__ uint16_t bf(float f) { + uint32_t u = __float_as_uint(f); + u += 0x7fffu + ((u >> 16) & 1u); + return (uint16_t) (u >> 16); +} +// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16. +// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5. +__device__ __forceinline__ uint16_t bf_lo(float f, uint16_t hi) { return bf(f - __uint_as_float((uint32_t) hi << 16)); } +__device__ __forceinline__ float sigm(float x) { return 1.0f / (1.0f + __expf(-x)); } +__device__ __forceinline__ uint16_t hf(float f) { return __half_as_ushort(__float2half_rn(f)); } +// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then +// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf +// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before. +__device__ __forceinline__ uint16_t hf_sat(float f) { return hf(isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)); } +// block-wide sum for blockDim.x <= 1024, result broadcast +__device__ float block_sum(float v, float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + __syncthreads(); + if (lane == 0) sh[w] = v; + __syncthreads(); + const int nw = (blockDim.x + 31) >> 5; + float t = (threadIdx.x < nw) ? sh[threadIdx.x] : 0.0f; + if (w == 0) t = warp_sum(t); + if (threadIdx.x == 0) sh[0] = t; + __syncthreads(); + return sh[0]; +} +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { std::fprintf(stderr, "prefill %s: %s\n", what, cudaGetErrorString(e)); std::exit(1); } +} +unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t); } + +// ---------------------------------------------------------------- hyper-connection +__global__ void gr_norm_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, + float* __restrict__ xn, uint16_t* __restrict__ xn16, uint16_t* __restrict__ xn16_lo) { + __shared__ float sh[32]; + const int64_t row = blockIdx.x; // t * 4 + c + const int c = (int) (row % HC); + const float* r = R + row * N; + float ss = 0.0f; + for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; + const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); + for (int d = threadIdx.x; d < N; d += blockDim.x) { + const float v = r[d] * rs * w[c * N + d]; + xn[row * N + d] = v; + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + } +} +// F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order, +// so the FP32 copy of the normalized rows (T x 10240 floats) is neither written nor read +__global__ void gr_norm_rs_kernel(const float* __restrict__ R, const float* __restrict__ w, float eps, + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { + __shared__ float sh[32]; + const int64_t row = blockIdx.x; // t * 4 + c + const int c = (int) (row % HC); + const float* r = R + row * N; + float ss = 0.0f; + for (int d = threadIdx.x; d < N; d += blockDim.x) ss += r[d] * r[d]; + const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); + if (threadIdx.x == 0) rs_out[row] = rs; + for (int d = threadIdx.x; d < N; d += blockDim.x) { + const float v = r[d] * rs * w[c * N + d]; + const uint16_t h = bf(v); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h); + } +} +__global__ void gr_mix_r_kernel(const float* __restrict__ R, const float* __restrict__ rs, const float* __restrict__ w, + const float* __restrict__ g, float* __restrict__ mixed, uint16_t* __restrict__ mixed16, + int64_t T, uint16_t* __restrict__ mixed_h, uint16_t* __restrict__ mixed16_lo) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * N) return; + const int64_t t = i / N, d = i % N; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + const int64_t j = t * D + c * N + d; + const float x = R[j] * rs[t * HC + c] * w[c * N + d]; // gr_norm_kernel's value, bit for bit + s = fmaf(x, sigm(g[j]), s); + } + s /= (float) HC; + mixed[i] = s; + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } + if (mixed_h) mixed_h[i] = hf(s); +} +// F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm +// weights - the same thread-to-element mapping (256 threads, stride 256) and block_sum, so rs and the BF16 image are +// the same bits, and R is not read back +constexpr int GRW_PER = (N + 255) / 256; +__global__ void __launch_bounds__(256) gr_write_norm_rs_kernel(float* __restrict__ R, const float* __restrict__ bo, + const float* __restrict__ inj, int64_t inj_ld, + const float* __restrict__ w, float eps, + float* __restrict__ rs_out, uint16_t* __restrict__ xn16, + uint16_t* __restrict__ xn16_lo) { + __shared__ float sh[32]; + const int64_t row = blockIdx.x; // t * 4 + c + const int64_t t = row / HC; + const int c = (int) (row % HC); + float* r = R + row * N; + const float sc = 2.0f * sigm(inj[t * inj_ld + c] / (float) HC); + float v[GRW_PER]; + float ss = 0.0f; + int k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float x = fmaf(bo[t * N + d], sc, r[d]); + r[d] = x; + v[k] = x; + ss += x * x; + } + const float rs = rsqrtf(block_sum(ss, sh) / (float) N + eps); + if (threadIdx.x == 0) rs_out[row] = rs; + k = 0; +#pragma unroll + for (int d = threadIdx.x; d < N; d += 256, ++k) { + const float x = v[k] * rs * w[c * N + d]; + const uint16_t h = bf(x); + xn16[row * N + d] = h; + if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h); + } +} +__global__ void gr_silu_kernel(const float* __restrict__ lo, uint16_t* __restrict__ lo16, uint16_t* __restrict__ lo16_lo, + int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float x = lo[i] / (float) HC; + const float v = x / (1.0f + __expf(-x)); + const uint16_t h = bf(v); + lo16[i] = h; + if (lo16_lo) lo16_lo[i] = bf_lo(v, h); +} +__global__ void gr_mix_kernel(const float* __restrict__ xn, const float* __restrict__ g, float* __restrict__ mixed, + uint16_t* __restrict__ mixed16, int64_t T, uint16_t* __restrict__ mixed_h, + uint16_t* __restrict__ mixed16_lo) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * N) return; + const int64_t t = i / N, d = i % N; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) { + const int64_t j = t * D + c * N + d; + s = fmaf(xn[j], sigm(g[j]), s); + } + s /= (float) HC; + mixed[i] = s; + if (mixed16) { + const uint16_t h = bf(s); + mixed16[i] = h; + if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h); + } + if (mixed_h) mixed_h[i] = hf(s); +} +__global__ void gr_write_kernel(float* __restrict__ R, const float* __restrict__ bo, const float* __restrict__ inj, + int64_t inj_ld, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * D) return; + const int64_t t = i / D, c = (i % D) / N, d = i % N; + R[i] = fmaf(bo[t * N + d], 2.0f * sigm(inj[t * inj_ld + c] / (float) HC), R[i]); +} +__global__ void gr_broadcast_kernel(const float* __restrict__ e, float* __restrict__ R, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * D) return; + const int64_t t = i / D, d = i % N; + R[i] = e[t * N + d]; +} + +// ---------------------------------------------------------------- GDN +__global__ void gdn_gates_kernel(const float* __restrict__ ab, const float* __restrict__ dt, + const float* __restrict__ ssm_a, float* __restrict__ gate, float* __restrict__ beta, + int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * HV) return; + const int64_t t = i / HV, h = i % HV; + const float v = ab[t * 2 * HV + h] + dt[h]; + gate[i] = (v > 20.0f ? v : log1pf(__expf(v))) * ssm_a[h]; + beta[i] = sigm(ab[t * 2 * HV + HV + h]); +} +// one thread per channel, walks the chunk; then a second kernel normalises +__global__ void gdn_conv_kernel(float* __restrict__ hist, const float* __restrict__ qkv, const float* __restrict__ w, + float* __restrict__ h, int64_t T) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float v0 = hist[c * 3], v1 = hist[c * 3 + 1], v2 = hist[c * 3 + 2]; + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + for (int64_t t = 0; t < T; ++t) { + const float x = qkv[t * C + c]; + const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + h[t * C + c] = s / (1.0f + __expf(-s)); + v0 = v1; v1 = v2; v2 = x; + } + hist[c * 3] = v0; hist[c * 3 + 1] = v1; hist[c * 3 + 2] = v2; +} +// C-3: the same 4-tap causal conv, tiled over tokens: thread (c, tile) reads its tile's 3 predecessors from the +// chunk (or the history before it) instead of carrying them - the conv reads inputs, not its own outputs, so the +// tiles are independent. The same expression per element (so the same bits); the history is written afterwards. +constexpr int CONV_TILE = 64; +__global__ void gdn_conv_tiled_kernel(const float* __restrict__ hist, const float* __restrict__ qkv, + const float* __restrict__ w, float* __restrict__ h, int64_t T) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + const int64_t t0 = (int64_t) blockIdx.y * CONV_TILE; + if (t0 >= T) return; + const int64_t t1 = t0 + CONV_TILE < T ? t0 + CONV_TILE : T; + auto input = [&](int64_t t) -> float { return t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; }; + float v0 = input(t0 - 3), v1 = input(t0 - 2), v2 = input(t0 - 1); + const float w0 = w[c * 4], w1 = w[c * 4 + 1], w2 = w[c * 4 + 2], w3 = w[c * 4 + 3]; + for (int64_t t = t0; t < t1; ++t) { + const float x = qkv[t * C + c]; + const float s = v0 * w0 + v1 * w1 + v2 * w2 + x * w3; + h[t * C + c] = s / (1.0f + __expf(-s)); + v0 = v1; v1 = v2; v2 = x; + } +} +// the history after the chunk: its last three inputs (the older history where the chunk is shorter than 3) +__global__ void gdn_conv_hist_kernel(float* __restrict__ hist, const float* __restrict__ qkv, int64_t T) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float v[3]; + for (int k = 0; k < 3; ++k) { + const int64_t t = T - 3 + k; + v[k] = t >= 0 ? qkv[t * C + c] : hist[c * 3 + (int) (t + 3)]; + } + hist[c * 3] = v[0]; hist[c * 3 + 1] = v[1]; hist[c * 3 + 2] = v[2]; +} +__global__ void gdn_l2_kernel(float* __restrict__ h, float eps) { + // block (t, head) over the 32 q/k heads, 128 threads + const int64_t t = blockIdx.y; + const int head = blockIdx.x; + float* x = h + t * C + head * S; + const float v = x[threadIdx.x]; + float sq = warp_sum(v * v); + __shared__ float part[4]; + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = sq; + __syncthreads(); + const float ss = part[0] + part[1] + part[2] + part[3]; + x[threadIdx.x] = v * rsqrtf(ss + eps); +} +constexpr int RG = 4, RPG = S / RG; +__global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, const float* __restrict__ z, + const float* __restrict__ gamma, float eps, + float* __restrict__ y, uint16_t* __restrict__ y16, int64_t T) { + __shared__ float sk[S], sq[S], red[RG][S], wsum[16]; + const int head = blockIdx.x, col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col; + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + const float g_col = gamma[col]; + for (int64_t t = 0; t < T; ++t) { + const float* ht = h + t * C; + __syncthreads(); + if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[t * HV + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][col] = kv; + __syncthreads(); + const float kv_col = red[0][col] + red[1][col] + red[2][col] + red[3][col]; + const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][col] = o; + __syncthreads(); + float oc = 0.0f, sp = 0.0f; + if (rg == 0) { + oc = (red[0][col] + red[1][col] + red[2][col] + red[3][col]) * rsqrtf((float) S); + sp = oc * oc; + } + sp = warp_sum(sp); + if ((tid & 31) == 0) wsum[tid >> 5] = sp; + __syncthreads(); + if (rg == 0) { + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float v = oc * rsqrtf(ss / (float) S + eps) * g_col * sigm(z[t * HV * S + head * S + col]); + y[t * HV * S + head * S + col] = v; + y16[t * HV * S + head * S + col] = hf(v); + } + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} + +// D-2: the recurrence with the value columns split over 4 blocks per head (4x the blocks of the kernel above, a +// quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns - +// in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as +// red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits. +constexpr int CB = 32, NCB = S / CB; +__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + __shared__ float sk[S], sq[S], red[RG][CB]; + const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; + const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + for (int64_t t = 0; t < T; ++t) { + const float* ht = h + t * C; + __syncthreads(); + if (tid < S) { sq[tid] = ht[qh * S + tid]; sk[tid] = ht[HK * S + qh * S + tid]; } + __syncthreads(); + const float g = __expf(gate[t * HV + head]); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][c] = kv; + __syncthreads(); + const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; + const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head]; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][c] = o; + __syncthreads(); + if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} +// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token +// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split. +// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel. +__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h, + const float* __restrict__ gate, + const float* __restrict__ beta, + float* __restrict__ oc_out, int64_t T) { + constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread + __shared__ float sk[S], sq[S], red[RG][CB]; + const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB; + const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c; + const int qh = head % HK; + float s[RPG]; + float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col; + const size_t rs = (size_t) HV * S; +#pragma unroll + for (int r = 0; r < RPG; ++r) s[r] = base[r * rs]; + float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f; + auto fetch = [&](int64_t t) { + const float* ht = h + t * C; +#pragma unroll + for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; } + nv = ht[2 * HK * S + head * S + col]; + ng = gate[t * HV + head]; + nb = beta[t * HV + head]; + }; + if (T > 0) fetch(0); + for (int64_t t = 0; t < T; ++t) { + float cq[LPT], ck[LPT]; +#pragma unroll + for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; } + const float cv = nv, cg = ng, cbt = nb; + __syncthreads(); +#pragma unroll + for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; } + __syncthreads(); + if (t + 1 < T) fetch(t + 1); + const float g = __expf(cg); + float kv = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv); + red[rg][c] = kv; + __syncthreads(); + const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c]; + const float delta = (cv - g * kv_col) * cbt; + float o = 0.0f; +#pragma unroll + for (int r = 0; r < RPG; ++r) { + s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta); + o = fmaf(s[r], sq[rg * RPG + r], o); + } + __syncthreads(); + red[rg][c] = o; + __syncthreads(); + if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S); + } +#pragma unroll + for (int r = 0; r < RPG; ++r) base[r * rs] = s[r]; +} +__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma, + float eps, float* __restrict__ y, uint16_t* __restrict__ y16) { + __shared__ float wsum[4]; + const int64_t t = blockIdx.x; + const int head = blockIdx.y, col = threadIdx.x; + const size_t at = (size_t) t * HV * S + (size_t) head * S + col; + const float oc = y[at]; + float sp = warp_sum(oc * oc); + if ((col & 31) == 0) wsum[col >> 5] = sp; + __syncthreads(); + const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3]; + const float v = oc * rsqrtf(ss / (float) S + eps) * gamma[col] * sigm(z[t * HV * S + head * S + col]); + y[at] = v; + y16[at] = hf(v); +} + +// ---------------------------------------------------------------- MoE +template +__global__ void route_kernel(const float* __restrict__ logits, int32_t* __restrict__ ids, float* __restrict__ wout, + int64_t T) { + const int64_t t = (int64_t) blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5); + if (t >= T) return; + const int lane = threadIdx.x & 31; + const float* lg = logits + t * (REG * 32); + float v[REG]; +#pragma unroll + for (int i = 0; i < REG; ++i) v[i] = lg[lane + i * 32]; + float mx = -INFINITY; +#pragma unroll + for (int i = 0; i < REG; ++i) mx = fmaxf(mx, v[i]); + mx = warp_max(mx); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < REG; ++i) { v[i] = expf(v[i] - mx); sum += v[i]; } + const float rcp = 1.0f / warp_sum(sum); +#pragma unroll + for (int i = 0; i < REG; ++i) { v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX; } + float selected = 0.0f, selected_sum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = v[0]; + int ex = lane; +#pragma unroll + for (int i = 1; i < REG; ++i) if (v[i] > best) { best = v[i]; ex = lane + i * 32; } +#pragma unroll + for (int m = 16; m; m >>= 1) { + const float ob = __shfl_xor_sync(0xffffffffu, best, m); + const int oi = __shfl_xor_sync(0xffffffffu, ex, m); + if (ob > best || (ob == best && oi < ex)) { best = ob; ex = oi; } + } + if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; } + if (lane == 0) ids[t * 10 + rank] = ex; + if (rank == lane) selected = best; + } + selected_sum = fmaxf(warp_sum(selected_sum), 6.103515625e-5f); + if (lane < 10) wout[t * 10 + lane] = selected / selected_sum; +} +// Strata blob: gate/up codes [1280][640 B], down codes [2560][160 B], gate/up scales [1280][40] f16, down scales [2560][10] f16 +template +__global__ void blob_dequant_kernel(const uint8_t* __restrict__ blob, uint16_t* __restrict__ gu16, + uint16_t* __restrict__ d16) { + constexpr size_t O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, + O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one thread per 4 weights (one code byte) + const int64_t n_gu = 1280LL * 640, n_d = 2560LL * 160; + if (i < n_gu) { + const int64_t row = i / 640, byte = i % 640; + const uint8_t c = blob[row * 640 + byte]; + const uint8_t* sp = blob + O_GU_SC + (size_t) (row * 40 + (byte * 4) / 64) * 2; + const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8)))); + uint16_t* o = gu16 + row * 2560 + byte * 4; +#pragma unroll + for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); } + } else if (i < n_gu + n_d) { + const int64_t j = i - n_gu, row = j / 160, byte = j % 160; + const uint8_t c = blob[O_D_CODES + row * 160 + byte]; + const uint8_t* sp = blob + O_D_SC + (size_t) (row * 10 + (byte * 4) / 64) * 2; + const float d = __half2float(__ushort_as_half((uint16_t) (sp[0] | (sp[1] << 8)))); + uint16_t* o = d16 + row * 640 + byte * 4; +#pragma unroll + for (int k = 0; k < 4; ++k) { const float v = (float) (((c >> (2 * k)) & 3) - 1) * d; o[k] = HALF ? hf(v) : bf(v); } + } +} +__global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * 640) return; + const int64_t r = i / 640, k = i % 640; + const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1]; + h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u); +} +__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16, + int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * 640) return; + const float a = g[i]; + h16[i] = hf_sat(a / (1.0f + __expf(-a)) * u[i]); +} +__global__ void gather_rows16_kernel(const uint16_t* __restrict__ x, const int32_t* __restrict__ src, + uint16_t* __restrict__ dst, int64_t n, int64_t width) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one uint4 (8 bf16) + const int64_t per = width / 8; + if (i >= n * per) return; + const int64_t r = i / per, j = i % per; + reinterpret_cast(dst)[r * per + j] = reinterpret_cast(x)[(int64_t) src[r] * per + j]; +} +__global__ void moe_combine_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float* __restrict__ shared, + const float* __restrict__ sg, float* __restrict__ bo, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * N) return; + const int64_t t = i / N, d = i % N; + float s = 0.0f; +#pragma unroll + for (int k = 0; k < 10; ++k) s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s); + bo[i] = s + shared[i] * sigm(sg[t]); +} + +// ---------------------------------------------------------------- QSA helpers +__global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ w, int64_t cols, int64_t ld, float eps) { + __shared__ float sh[32]; + float* r = x + (int64_t) blockIdx.x * ld; + float ss = 0.0f; + for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) ss += r[c] * r[c]; + const float s = rsqrtf(block_sum(ss, sh) / (float) cols + eps); + __syncthreads(); + for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; +} +// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches whenever +// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it; +// with it merely skipped at run time, the compiled default path changed its results). +template +__global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* __restrict__ mtab, + strata::kernels::RopeTab rt) { + const int64_t row = blockIdx.x; // t * heads + h + const int pair = threadIdx.x; // 0..31 + const int64_t t = row / heads, h = row % heads; + float* p = x + t * ld + h * dim; + float c, s; + if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c, + s))) { + const float theta_extrap = + (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); + strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, + pair, c, s); + } + const float a = p[pair], b = p[pair + 32]; + p[pair] = a * c - b * s; + p[pair + 32] = a * s + b * c; +} +__global__ void split_q_kernel(const float* __restrict__ qf, float* __restrict__ q, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * 24 * 256) return; + const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; + q[i] = qf[t * 24 * 512 + h * 512 + d]; +} +__global__ void gate_attn_kernel(const float* __restrict__ a, const float* __restrict__ qf, uint16_t* __restrict__ o16, + int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * 24 * 256) return; + const int64_t t = i / (24 * 256), h = (i / 256) % 24, d = i % 256; + o16[i] = hf(a[i] * (1.0f / (1.0f + expf(-qf[t * 24 * 512 + h * 512 + 256 + d])))); +} + +// one block per (token, kv head, 64-value group); 64 threads. KV streaming: the pool page only if the block is +// resident (table >= 0), and the host copy and the prompt path's staging pool (both identity layout) when given. +__global__ void kv_append_kernel(const float* __restrict__ K, const float* __restrict__ V, int64_t pos0, + const int32_t* __restrict__ table, int64_t page_size, uint16_t* k_pool, + uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { + const int64_t t = blockIdx.x; + const bool value_only = k_pool == nullptr && k_q == nullptr; + const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1; + const bool is_v = value_only || (blockIdx.z & 1) != 0; + const int d = g * 64 + threadIdx.x; + const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; + const int64_t pos = pos0 + t; + const int64_t page = table[pos / page_size]; + const int64_t row = (page * 2 + kvh) * page_size + pos % page_size; + const int64_t row_id = ((pos / page_size) * 2 + kvh) * page_size + pos % page_size; + if (k_pool != nullptr) { + const uint16_t h = hf(x); + if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h; + if (host.k_pool != nullptr) (is_v ? host.v_pool : host.k_pool)[row_id * 256 + d] = h; + if (stage.k_pool != nullptr) (is_v ? stage.v_pool : stage.k_pool)[row_id * 256 + d] = h; + return; + } + float a = fabsf(x); + for (int o = 16; o > 0; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); + __shared__ float wm[2]; + if ((threadIdx.x & 31) == 0) wm[threadIdx.x >> 5] = a; + __syncthreads(); + const float amax = fmaxf(wm[0], wm[1]); + const uint16_t sb = hf(amax / 127.0f); + const float sf = __half2float(__ushort_as_half(sb)); + int q = 0; + if (sf > 0.0f) { q = __float2int_rn(x / sf); q = q < -127 ? -127 : (q > 127 ? 127 : q); } + if (page >= 0) { + (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; + } + if ((is_v ? host.v_q : host.k_q) != nullptr) { + (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; + } + if ((is_v ? stage.v_q : stage.k_q) != nullptr) { + (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; + } +} +__global__ void to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) + y[i] = hf(x[i]); +} +__global__ void round_f16_kernel(const float* __restrict__ x, float* __restrict__ y, int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) + y[i] = __half2float(__float2half_rn(x[i])); +} +__global__ void to_bf16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, uint16_t* __restrict__ ylo, + int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) { + const uint16_t h = bf(x[i]); + y[i] = h; + if (ylo) ylo[i] = bf_lo(x[i], h); + } +} + +} // namespace + +void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size, + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { + if (T <= 0) return; + kv_append_kernel<<>>( + K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, + host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); + check("kv_append"); +} +void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) { + if (n <= 0) return; + to_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); + check("to_f16"); +} +void round_f16(const float* x, float* y, int64_t n, void* stream) { + if (n <= 0) return; + round_f16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, n); + check("round_f16"); +} +void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) { + if (n <= 0) return; + to_bf16_kernel<<<(unsigned) ((n + 255) / 256 < 4096 ? (n + 255) / 256 : 4096), 256, 0, (cudaStream_t) stream>>>(x, y, ylo, n); + check("to_bf16"); +} + +void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, xn, xn16, xn16_lo); + check("gr_norm"); +} +void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream, + uint16_t* xn16_lo) { + gr_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, w_norm, eps, rs, xn16, xn16_lo); + check("gr_norm_rs"); +} +void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16, + int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) { + gr_mix_r_kernel<<>>(R, rs, w_norm, gated, mixed, mixed16, T, + mixed_h, mixed16_lo); + check("gr_mix_r"); +} +void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps, + float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) { + gr_write_norm_rs_kernel<<<(unsigned) (T * HC), 256, 0, (cudaStream_t) stream>>>(R, bo, inj, inj_ld, w_norm_next, eps, + rs, xn16, xn16_lo); + check("gr_write_norm_rs"); +} +void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) { + gr_silu_kernel<<>>(lo, lo16, lo16_lo, T * LR); + check("gr_silu"); +} +void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream, + uint16_t* mixed_h, uint16_t* mixed16_lo) { + gr_mix_kernel<<>>(xn, gated, mixed, mixed16, T, mixed_h, mixed16_lo); + check("gr_mix"); +} +void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream) { + gr_write_kernel<<>>(R, bo, inj, inj_ld, T); + check("gr_write"); +} +void gr_broadcast(const float* e, float* R, int64_t T, void* stream) { + gr_broadcast_kernel<<>>(e, R, T); + check("gr_broadcast"); +} +void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream) { + gdn_gates_kernel<<>>(ab, dt, ssm_a, gate, beta, T); + check("gdn_gates"); +} +void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream) { + static const bool serial = std::getenv("STRATA_GDN_CONV_SERIAL") != nullptr; // the old walk (A/B) + if (serial || T <= CONV_TILE) { + gdn_conv_kernel<<>>(history, qkv, conv_w, h, T); + } else { + gdn_conv_tiled_kernel<<>>(history, qkv, conv_w, h, T); + gdn_conv_hist_kernel<<>>(history, qkv, T); + } + gdn_l2_kernel<<>>(h, eps); + check("gdn_conv"); +} +void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z, + const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream) { + static const bool serial = std::getenv("STRATA_GDN_REC_HEADS") != nullptr; // the one-block-per-head kernel (A/B) + if (serial || T <= 0) { + gdn_rec_kernel<<>>(state, h, gate, beta, z, gamma, eps, y, y16, T); + } else { + static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }(); + if (pipe) // the software-pipelined loads (same bits) + gdn_rec_cols_pipe_kernel<<>>(state, h, gate, beta, y, T); + else + gdn_rec_cols_kernel<<>>(state, h, gate, beta, y, T); + gdn_out_norm_kernel<<>>(z, gamma, eps, y, y16); + } + check("gdn_recurrence"); +} +void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream) { + if (n_expert == 512) + route_kernel<16><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); + else if (n_expert == 256) + route_kernel<8><<<(unsigned) ((T + 7) / 8), 256, 0, (cudaStream_t) stream>>>(logits, ids, weights, T); + else + strata::kernels::router_top10(logits, (int) T, (int) n_expert, 10, ids, weights, stream); + check("route"); +} +void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) { + blob_dequant_kernel<<>>(blob, gu16, down16); + check("blob_dequant"); +} +void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream) { + blob_dequant_kernel<<>>(blob, gu16, down16); + check("blob_dequant_f16"); +} +void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream) { + if (n <= 0) return; + swiglu_il_kernel<<>>(gu, h16, n); + check("swiglu_interleaved"); +} +void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) { + swiglu_pair_kernel<<>>(g, u, h16, n); + check("swiglu_pair"); +} +namespace { +__global__ void copy_i32_kernel(int32_t* __restrict__ dst, const int32_t* __restrict__ src, int64_t n) { + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) + dst[i] = src[i]; +} +} // namespace +void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) { + if (n <= 0) return; + const int64_t b = (n + 255) / 256; + copy_i32_kernel<<<(unsigned) (b < 256 ? b : 256), 256, 0, (cudaStream_t) stream>>>(dst, src, n); + check("copy_i32"); +} +void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream) { + if (n <= 0) return; + gather_rows16_kernel<<>>(x16, src, dst16, n, width); + check("gather_rows16"); +} +void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, + int64_t T, void* stream) { + moe_combine_kernel<<>>(Dm, slot, w, shared, sg, bo, T); + check("moe_combine"); +} +void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream) { + if (rows <= 0) return; + rms_rows_kernel<<<(unsigned) rows, 256, 0, (cudaStream_t) stream>>>(x, w, cols, ld, eps); + check("rms_rows"); +} +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream) { + // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only + // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process. + if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) { + std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why); + std::exit(1); + } + const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); + const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants + const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling); + if (rt.cos != nullptr) + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); + else + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table(), rt); + check("rope"); +} +void split_q(const float* q_full, float* q, int64_t T, void* stream) { + split_q_kernel<<>>(q_full, q, T); + check("split_q"); +} +void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream) { + gate_attn_kernel<<>>(attn, q_full, out16, T); + check("gate_attn"); +} + +} // namespace strata::prefill diff --git a/engine/strata/src/prefill/moe_mmq.cu b/engine/strata/src/prefill/moe_mmq.cu new file mode 100644 index 00000000..1f0221c7 --- /dev/null +++ b/engine/strata/src/prefill/moe_mmq.cu @@ -0,0 +1,231 @@ +// src/prefill/moe_mmq.cu - see include/strata/prefill/moe_mmq.hpp. llama.cpp's MMQ (ggml-cuda, MIT) is compiled +// from the pinned llama.cpp checkout the build already takes ggml from; src/prefill/ggml_cuda_host.cu supplies the +// few host symbols of ggml-cuda.cu it references. +#include "strata/prefill/moe_mmq.hpp" + +#include "common.cuh" +#include "mmq.cuh" +#include "quantize.cuh" + +#include +#include + +namespace strata::prefill::mmq { +namespace { + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill mmq: %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; } + +__global__ void copy16_kernel(const uint4* __restrict__ a, int64_t na, const uint4* __restrict__ b, int64_t nb, + uint4* __restrict__ ab_dst, const uint4* __restrict__ c, int64_t nc, uint4* __restrict__ c_dst) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < na) ab_dst[i] = a[i]; + else if (i < na + nb) ab_dst[i] = b[i - na]; + else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb]; +} +__global__ void copy1_kernel(const uint8_t* __restrict__ a, int64_t na, const uint8_t* __restrict__ b, int64_t nb, + uint8_t* __restrict__ ab_dst, const uint8_t* __restrict__ c, int64_t nc, uint8_t* __restrict__ c_dst) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < na) ab_dst[i] = a[i]; + else if (i < na + nb) ab_dst[i] = b[i - na]; + else if (i < na + nb + nc) c_dst[i - na - nb] = c[i - na - nb]; +} + +// Strata blob: gate/up codes [1280][640 B], down codes [2560][160 B], gate/up scales [1280][40] f16, down scales +// [2560][10] f16 (the layout of prefill/kernels.cu's blob_dequant_kernel). A GGUF Q2_0 block is {f16 d; 16 code +// bytes} with the same 2-bit codes in the same order, so a block is a scale and a 16-byte run of codes. +__global__ void strata_q2_kernel(const uint8_t* __restrict__ blob, uint16_t* __restrict__ gu, uint16_t* __restrict__ dn) { + constexpr size_t O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160, + O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // one GGUF block + const int64_t n_gu = 1280LL * 40, n_d = 2560LL * 10; + const uint8_t* codes; + const uint16_t* scale; + uint16_t* out; + if (i < n_gu) { + const int64_t row = i / 40, b = i % 40; + codes = blob + row * 640 + b * 16; + scale = (const uint16_t*) (blob + O_GU_SC) + row * 40 + b; + out = gu + i * 9; + } else if (i < n_gu + n_d) { + const int64_t j = i - n_gu, row = j / 10, b = j % 10; + codes = blob + O_D_CODES + row * 160 + b * 16; + scale = (const uint16_t*) (blob + O_D_SC) + row * 10 + b; + out = dn + j * 9; + } else { + return; + } + const uint4 q = *(const uint4*) codes; + const uint16_t* qh = (const uint16_t*) &q; + out[0] = *scale; +#pragma unroll + for (int k = 0; k < 8; ++k) out[1 + k] = qh[k]; +} + +__global__ void swiglu_kernel(const float* __restrict__ gu, float* __restrict__ h, int64_t rows, int64_t n_ff, + bool interleaved) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * n_ff) return; + const int64_t r = i / n_ff, k = i % n_ff; + const float* row = gu + r * 2 * n_ff; + const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k]; + h[i] = g / (1.0f + __expf(-g)) * u; +} + +__global__ void iota_kernel(int32_t* dst, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) dst[i] = (int32_t) i; +} + +unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); } + +} // namespace + +bool built() { return true; } + +bool supported(int t) { + switch ((ggml_type) t) { + case GGML_TYPE_Q2_0: +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q5_0: // #296 (Q4_K and Q5_1: STRATA_MMQ_KQUANTS) +#endif + case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS: + case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9) +#ifdef STRATA_MMQ_KQUANTS + case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: // Unsloth's UD-Q4_K_XL experts (CUDA) +#endif + return true; + default: + return false; + } +} + +bool fits(int t, int64_t w_rows) { + if (!supported(t)) return false; + // mul_mat_q_case's choice: the "fallback" configs when the rows are not a multiple of 128; then + // mul_mat_q_switch_J's loop - a tile size whose config exists for this card and fits its shared memory + const bool fallback = w_rows % 128 != 0; + const ggml_cuda_device_info& info = ggml_cuda_info(); + for (int id = 0; id < info.device_count; ++id) { + const int cc = info.devices[id].cc; + const size_t smpbo = info.devices[id].smpbo; + bool any = false; + for (int J = 8; J <= 128 && !any; J += 8) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, fallback, cc); + any = c.type != GGML_TYPE_COUNT && mmq_get_nbytes_shared(c, cc) <= smpbo; + } + if (!any) { + static bool said[GGML_TYPE_COUNT] = {}; + if (t >= 0 && t < GGML_TYPE_COUNT && !said[t]) { + said[t] = true; + std::fprintf(stderr, "strata: prompt kernels: llama.cpp's MMQ has no tile for %s (%lld rows) on GPU %d " + "(cc %d, %zu bytes of shared memory per block): that product takes the non-MMQ path " + "(#420)\n", ggml_type_name((ggml_type) t), (long long) w_rows, id, cc, smpbo); + } + return false; + } + } + return true; +} + +size_t matrix_bytes(int t, int64_t rows, int64_t cols) { + return (size_t) rows * (size_t) (cols / ggml_blck_size((ggml_type) t)) * ggml_type_size((ggml_type) t); +} + +size_t q8_bytes(int64_t rows, int64_t cols) { + return (size_t) rows * (size_t) pad512(cols) * sizeof(block_q8_1_mmq) / (4 * QK8_1) + 128 * sizeof(block_q8_1_mmq); +} + +void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream) { + if (rows <= 0) return; + quantize_mmq_q8_1_cuda(x, ids, xq, (ggml_type) t, cols, ld, rows * ld, rows * ld, pad512(cols), rows, 1, 1, + (cudaStream_t) stream); + ck(cudaGetLastError(), "quantize"); +} + +Context::Context() { + int dev = 0; + cudaGetDevice(&dev); + ctx_ = new ggml_backend_cuda_context(dev); +} +Context::~Context() { delete (ggml_backend_cuda_context*) ctx_; } + +void Context::run(const Product& p, void* stream) { + if (p.n <= 0 || p.max_rows <= 0) return; + const ggml_type t = (ggml_type) p.type; + const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk; + const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, nullptr, + p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst, + p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, + 1, 1, 0, 0, 0, + p.max_rows, p.max_rows}; + auto& ctx = *(ggml_backend_cuda_context*) ctx_; + const cudaStream_t s = (cudaStream_t) stream; + switch (t) { +#ifdef STRATA_ORCA_Q4KS_MMQ + case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; +#endif + case GGML_TYPE_Q2_0: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ2_XXS: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ2_XS: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ2_S: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ3_XXS: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ3_S: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ4_NL: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_IQ4_XS: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_Q8_0: mul_mat_q_case(ctx, a, s); break; +#ifdef STRATA_MMQ_KQUANTS + case GGML_TYPE_Q4_K: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_Q5_K: mul_mat_q_case(ctx, a, s); break; + case GGML_TYPE_Q5_1: mul_mat_q_case(ctx, a, s); break; +#endif + default: + std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t); + std::exit(1); + } + ck(cudaGetLastError(), "mul_mat_q"); +} + +void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, + void* gu_dst, void* d_dst, void* stream) { + const cudaStream_t s = (cudaStream_t) stream; + const bool a16 = ((uintptr_t) gate | (uintptr_t) up | (uintptr_t) down | (uintptr_t) gu_dst | (uintptr_t) d_dst | + gu_half_bytes | d_bytes) % 16 == 0; + if (a16) { + const int64_t na = (int64_t) gu_half_bytes / 16, nc = (int64_t) d_bytes / 16; + copy16_kernel<<>>((const uint4*) gate, na, (const uint4*) up, na, (uint4*) gu_dst, + (const uint4*) down, nc, (uint4*) d_dst); + } else { + const int64_t na = (int64_t) gu_half_bytes, nc = (int64_t) d_bytes; + copy1_kernel<<>>((const uint8_t*) gate, na, (const uint8_t*) up, na, + (uint8_t*) gu_dst, (const uint8_t*) down, nc, (uint8_t*) d_dst); + } + ck(cudaGetLastError(), "gather_native"); +} + +void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stream) { + strata_q2_kernel<<>>(blob, (uint16_t*) gu_dst, + (uint16_t*) d_dst); + ck(cudaGetLastError(), "gather_strata_q2"); +} + +void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream) { + if (rows <= 0) return; + swiglu_kernel<<>>(gu, h, rows, n_ff, interleaved); + ck(cudaGetLastError(), "swiglu"); +} + +void iota(int32_t* dst, int64_t n, void* stream) { + if (n <= 0) return; + iota_kernel<<>>(dst, n); + ck(cudaGetLastError(), "iota"); +} + +} // namespace strata::prefill::mmq diff --git a/engine/strata/src/prefill/prefill.cpp b/engine/strata/src/prefill/prefill.cpp new file mode 100644 index 00000000..37edb9f0 --- /dev/null +++ b/engine/strata/src/prefill/prefill.cpp @@ -0,0 +1,2019 @@ +// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. +#include "strata/prefill/prefill.hpp" +#include "strata/core/mtp.hpp" +#include "strata/core/progress.hpp" +#include "strata/core/on_device.hpp" + +#include "strata/core/layout.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/ple.hpp" +#include "strata/kernels/native_ple_postops.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/keyless.hpp" +#include "strata/core/native_head.hpp" +#include "strata/kernels/verify_kernels.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include "strata/prefill/gemm.hpp" +#include "strata/prefill/moe_mmq.hpp" +#include "strata/prefill/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef STRATA_PREFILL_MMQ +// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. +namespace strata::prefill::mmq { +bool built() { return false; } +bool supported(int) { return false; } +bool fits(int, int64_t) { return false; } +size_t matrix_bytes(int, int64_t, int64_t) { return 0; } +size_t q8_bytes(int64_t, int64_t) { return 0; } +void quantize(const float*, const int32_t*, void*, int, int64_t, int64_t, int64_t, void*) {} +Context::Context() {} +Context::~Context() {} +void Context::run(const Product&, void*) {} +void gather_native(const void*, const void*, size_t, const void*, size_t, void*, void*, void*) {} +void gather_strata_q2(const uint8_t*, void*, void*, void*) {} +void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} +void iota(int32_t*, int64_t, void*) {} +} // namespace strata::prefill::mmq +#endif + +namespace strata::prefill { +namespace { + +using Clock = std::chrono::steady_clock; +constexpr float EPS = 1e-6f; +constexpr int64_t N = 2560, HC = 4, D = N * HC, LR = 320, K = 10, NE = 512; +constexpr int64_t C = 10240, ZV = 6144, HV = 48; +// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer) +inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; } +constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min()) +// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a +// RING_MAX-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the +// attention halves instead of waiting for each layer's routing. +constexpr int RING_MAX = 512; // the arrays; the ring itself is ring_slots() +// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, +// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last +// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk +// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B). +inline int64_t stream_all_min() { + static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) 1024; }(); + return v; +} +double g_pinned_share = 1.0; +// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0, +// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) - +// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 - +// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides. +int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below +inline int ring_slots(size_t T) { + const char* v = std::getenv("STRATA_PREFILL_RING"); +#if defined(STRATA_USE_HIP) + // S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT + // 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same) + static const bool wmma = [] { + const char* e = std::getenv("STRATA_HIP_WMMA"); + return e != nullptr && e[0] == '1'; + }(); + if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE; +#endif + const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : (g_pinned_share >= 0.9 ? 384 : 96); + if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks. + const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r; + return (int64_t) T >= stream_all_min() ? big : STAGE; +} +constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) +// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take +// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a +// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. +// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up +// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. +inline int bf16x2_mode() { + static const int v = [] { + const char* e = std::getenv("STRATA_PREFILL_BF16X2"); + return e != nullptr ? std::atoi(e) : 0; + }(); + return v; +} +inline bool bf16x2() { return bf16x2_mode() != 0; } +inline bool bf16x2_hc() { return bf16x2_mode() == 1; } + +// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm +inline bool gr_unfused() { + static const bool v = [] { const char* e = std::getenv("STRATA_GR_UNFUSED"); return e && e[0] == '1'; }(); + return v; +} + +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and +// no region it only counts, which is how `bytes_needed` sizes the region. +struct Alloc { + uint8_t* base = nullptr; + uint64_t cap = 0, used = 0; + bool count_only = false; + std::vector* owned = nullptr; + template T* take(size_t n, bool& ok) { + const uint64_t bytes = ((uint64_t) n * sizeof(T) + 256 + 255) & ~255ull; + if (count_only) { used += bytes; return nullptr; } + if (base != nullptr) { + if (used + bytes > cap) { ok = false; return nullptr; } + T* p = (T*) (base + used); + used += bytes; + return p; + } + void* p = nullptr; + if (cudaMalloc(&p, bytes) != cudaSuccess) { ok = false; return nullptr; } + owned->push_back(p); + used += bytes; + return (T*) p; + } +}; + +} // namespace + +// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are +// copied into pinned buffers by these threads, ahead of the launches. Copied in line by the launching thread they +// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S). Job j - a layer's +// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job +// j - kRing (recorded by the launching thread, `issued`) is done. +struct Stager { + // D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the + // DMAs of the unpinned experts' blobs + int kRing = 16; + // `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three + // role slices; a pointer to it would not live as long as the queue) + struct Job { const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0; }; + std::vector buf; + std::vector pinned; + std::vector> pageable; // the fallback when no more RAM can be pinned + std::vector dma_done; + std::vector jobs; + std::unique_ptr[]> ready; + size_t ready_cap = 0; + // gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the + // previous layer can never take a job of this one - the expert pool's issue #29 lesson) + std::atomic head{0}; + std::atomic issued{0}, active{0}; + uint32_t gen = 0; + bool quit = false; + std::mutex mu; + std::condition_variable cv; + std::vector threads; + int device = 0; + + bool init(size_t blob_bytes, int nthreads) { + if (const char* v = std::getenv("STRATA_STAGER_RING")) kRing = std::clamp(std::atoi(v), 2, 256); + buf.assign((size_t) kRing, nullptr); + pinned.assign((size_t) kRing, 0); + dma_done.assign((size_t) kRing, nullptr); + pageable.resize(kRing); + for (int i = 0; i < kRing; ++i) { + pinned[i] = cudaHostAlloc((void**) &buf[i], blob_bytes, cudaHostAllocDefault) == cudaSuccess; + if (!pinned[i]) { + cudaGetLastError(); + pageable[(size_t) i].resize(blob_bytes); + buf[i] = pageable[(size_t) i].data(); + } + if (cudaEventCreateWithFlags(&dma_done[i], cudaEventDisableTiming) != cudaSuccess) return false; + } + cudaGetDevice(&device); + for (int t = 0; t < nthreads; ++t) threads.emplace_back([this] { work(); }); + return true; + } + ~Stager() { + finish(); + { std::lock_guard lk(mu); quit = true; } + cv.notify_all(); + for (auto& t : threads) t.join(); + for (int i = 0; i < kRing; ++i) { + if (dma_done[i]) cudaEventDestroy(dma_done[i]); + if (buf[i] && pinned[i]) cudaFreeHost(buf[i]); + } + } + void work() { + cudaSetDevice(device); + uint32_t seen = 0; + for (;;) { + { + std::unique_lock lk(mu); + cv.wait(lk, [&] { return quit || gen != seen; }); + if (quit) return; + seen = gen; + } + for (;;) { + active.fetch_add(1, std::memory_order_acq_rel); + const int j = claim(seen); + if (j < 0) { active.fetch_sub(1, std::memory_order_acq_rel); break; } + const int b = j % kRing; + if (j >= kRing) { + while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield(); + cudaEventSynchronize(dma_done[b]); + } + const Job& jb = jobs[(size_t) j]; + if (jb.from == nullptr) std::memcpy(buf[b], jb.src, jb.bytes); + else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) { + std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l); + std::abort(); + } + ready[(size_t) j].store(1, std::memory_order_release); + active.fetch_sub(1, std::memory_order_acq_rel); + } + } + } + int claim(uint32_t g) { + uint64_t cur = head.load(std::memory_order_acquire); + for (;;) { + if ((uint32_t) (cur >> 32) != g) return -1; + const int n = (int) ((cur >> 16) & 0xffff), j = (int) (cur & 0xffff); + if (j >= n) return -1; + if (head.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) return j; + } + } + /// A layer's jobs; the previous layer's are finished (finish()). + void start(std::vector&& js) { + if (js.empty()) return; + std::lock_guard lk(mu); + jobs = std::move(js); + if (ready_cap < jobs.size()) { + ready_cap = jobs.size() * 2; + ready.reset(new std::atomic[ready_cap]); + } + for (size_t i = 0; i < jobs.size(); ++i) ready[i].store(0, std::memory_order_relaxed); + issued.store(0); + ++gen; + head.store((uint64_t) gen << 32 | (uint64_t) jobs.size() << 16, std::memory_order_release); + cv.notify_all(); + } + /// Job j's bytes, in a pinned buffer (waits for the copy). + const uint8_t* wait(int j) { + while (!ready[(size_t) j].load(std::memory_order_acquire)) std::this_thread::yield(); + return buf[j % kRing]; + } + /// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done. + void issued_one(int j, cudaStream_t copy) { + cudaEventRecord(dma_done[j % kRing], copy); + issued.store(j + 1, std::memory_order_release); + } + /// No job is running after this (the end of a layer, or an early return in the middle of one). + void finish() { + head.store((uint64_t) gen << 32, std::memory_order_release); // n = 0: nothing more to claim + issued.store(1 << 30, std::memory_order_release); + while (active.load(std::memory_order_acquire) != 0) std::this_thread::yield(); + } +}; + +struct Prefill::Impl { + const core::WeightTable* wt = nullptr; + const core::ModelGeometry* g = nullptr; + core::SessionState* ss = nullptr; + core::ExpertSource* src = nullptr; + const core::ExpertCache* cache = nullptr; + const int32_t* host_res = nullptr; + int64_t T = 0, T_max = 0; + bool borrowed = false; + cudaStream_t cs = nullptr, copy = nullptr; + Gemm gemm; + std::vector owned; + // chunk buffers + float *emb = nullptr, *R = nullptr, *xn = nullptr, *lo = nullptr, *gated = nullptr, *inj = nullptr; + float* grs = nullptr; // F-1: the hyper-connection read's row scales (T x 4) + uint16_t *xn16 = nullptr, *lo16 = nullptr; + float* mixed = nullptr; + uint16_t *mixed_bf = nullptr, *mixed_h = nullptr; + uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts + float* bo = nullptr; + // GDN + float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr; + uint16_t* y_h = nullptr; + // QSA + float *Kc = nullptr, *Vc = nullptr, *Qf = nullptr, *q = nullptr, *idx_raw = nullptr, *q_idx = nullptr, *attn = nullptr; + uint16_t* attn_h = nullptr; + int32_t* steps_dev = nullptr; + std::vector steps_host; + int32_t* sel_ids = nullptr; + float* sel_scores = nullptr; // [sel_batch, max_blocks] + int64_t sel_batch = 256, max_blocks = 0; + float* attn_scratch = nullptr; + int64_t attn_batch = 32, cap = 0; + // MoE + float *logits = nullptr, *w = nullptr, *GU = nullptr, *Dm = nullptr, *sgate = nullptr, *sup = nullptr, + *shared = nullptr, *sg = nullptr; + int32_t *ids = nullptr, *slot_dev = nullptr, *src_dev = nullptr; + uint16_t *Xs = nullptr, *Hh = nullptr, *sh_h = nullptr; + // step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity + // row map, the group bounds, the group buffers of gathered experts + void *Xq = nullptr, *Hq = nullptr; + float* H = nullptr; + int32_t *ids_identity = nullptr, *bounds_dev = nullptr; + uint8_t *grp_gu = nullptr, *grp_d = nullptr; + std::vector bounds_host; + std::unique_ptr mmq_ctx; + std::vector ids_host, slot_host, src_host, cnt, off; + // The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels + // read and write them in place. A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already + // holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's + // 70 s at the default ring, 0.7 s with a 16-slot one. STRATA_GROUP_COPY=1: the copies (the A/B arm). + int32_t* grp_host = nullptr; + int32_t* grp_dev = nullptr; // its device alias + size_t grp_n = 0, grp_tk = 0; // int32s allocated; T_max * K (the offset of slot, and of src past it) + uint16_t* dq_gu[DQ] = {}; + uint16_t* dq_d[DQ] = {}; + uint8_t* stage_dev[RING_MAX] = {}; + int ring = STAGE; // the slots of this layout's ring (ring_slots) + std::unique_ptr stager; // the unpinned experts' host copies (step 4) + cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; + bool stage_live[RING_MAX] = {}; + // PLE + float* ple_emb = nullptr; + std::vector ple_pageable[2]; // the fallback when no more RAM can be pinned + float* ple_emb_host[2] = {}; // pinned, double-buffered: the next chunk's rows are read while this + cudaEvent_t ple_copied[2] = {}; // one runs; the event marks that buffer's upload done + std::vector ple_rows[2]; + float* ple_norm = nullptr; + uint8_t* region = nullptr; // the attention/MoE scratch region (idle while the PLE block runs) + uint64_t region_bytes = 0; + PrefillStats* stats = nullptr; + // KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout) + strata::kernels::KvHostPools stage; + int32_t* ident_table = nullptr; + // layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn) + int device = -1; + float* hand[2] = {}; + // C-4: the chunk's token ids on the device, for one batched embedding gather + int32_t* tok_dev = nullptr; + std::vector tok_host; +}; + +namespace { +// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed) +// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a +// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which +// rounds differently: without this an A/B compares two expert placements as well as two KV placements) +bool stage_own() { static const bool v = std::getenv("STRATA_KV_STAGE_OWN") != nullptr; return v; } +void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kernels::QsaShapes& s, + strata::kernels::KvHostPools& st, bool& ok) { + const core::QsaState& q0 = ss.qsa_states[ss.qsa_primary()]; + if (q0.kv_mode != 1) return; + if (stage_own() && o_borrowed.count_only) return; + Alloc own; + own.owned = o_borrowed.owned; + Alloc& o = stage_own() ? own : o_borrowed; + const size_t rows = (size_t) q0.n_pages * s.n_head_kv * s.page_size; + if (q0.kv_q4) { + st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { + if (!q0.without_key) st.k_q = o.take(rows * s.head_dim, ok); + st.v_q = o.take(rows * s.head_dim, ok); + if (!q0.without_key) st.k_scale = o.take(rows * (s.head_dim / 64), ok); + st.v_scale = o.take(rows * (s.head_dim / 64), ok); + } else { + st.k_pool = o.take(rows * s.head_dim, ok); + st.v_pool = o.take(rows * s.head_dim, ok); + } +} +strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, const int32_t* table) { + strata::kernels::QsaAttnPools p; + p.k_pool = h.k_pool; p.v_pool = h.v_pool; p.k_q = h.k_q; p.v_q = h.v_q; p.k_scale = h.k_scale; p.v_scale = h.v_scale; + p.k_q4 = h.k_q4; p.v_q4 = h.v_q4; + p.page_table = table; + return p; +} +} // namespace + +Prefill::Prefill() : impl_(new Impl) {} +Prefill::~Prefill() { release(); } + +void Prefill::reset() { + release(); + impl_.reset(new Impl); + stats_ = PrefillStats{}; +} + +void Prefill::release() { + if (!impl_) return; + if (impl_->cs) cudaStreamSynchronize(impl_->cs); + if (impl_->copy) cudaStreamSynchronize(impl_->copy); + for (int i = 0; i < RING_MAX; ++i) { + if (impl_->copied[i]) cudaEventDestroy(impl_->copied[i]); + if (impl_->used[i]) cudaEventDestroy(impl_->used[i]); + } + for (int b = 0; b < 2; ++b) { + if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]); + if (impl_->ple_copied[b]) cudaEventDestroy(impl_->ple_copied[b]); + if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty()) cudaFreeHost(impl_->ple_emb_host[b]); + } + if (impl_->copy) cudaStreamDestroy(impl_->copy); + if (impl_->grp_host) cudaFreeHost(impl_->grp_host); + for (void* p : impl_->owned) cudaFree(p); +} + +namespace { +constexpr int64_t GEMM_SCRATCH = 32ll << 20; // FP16 elements for the largest dequantized dense weight +constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace + +// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS. A layer runs its attention (GDN or QSA), writes it back +// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size +// of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk +// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are +// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap. +uint64_t gdn_set_bytes(size_t T) { + Alloc a; a.count_only = true; bool ok = true; + a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * 2 * HV, ok); a.take(T * HV, ok); + a.take(T * HV, ok); a.take(T * C, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + return a.used; +} +uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch, + const strata::kernels::QsaShapes& s) { + Alloc a; a.count_only = true; bool ok = true; + a.take(T * 512, ok); a.take(T * 512, ok); a.take(T * 12288, ok); a.take(T * ZV, ok); + a.take(T * 128, ok); a.take(T * 512, ok); a.take(T * ZV, ok); a.take(T * ZV, ok); + a.take(T * (size_t) cap, ok); + a.take((size_t) sel_batch * (size_t) max_blocks, ok); + a.take((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok); + return a.used; +} +// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob +// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest +// gate/up and down matrices a group buffer slot holds. STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B). +constexpr int MMQ_GROUP = 16; // experts per MMQ launch (the gather is per expert, as blobs arrive) +// MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down +// product: 640 values). Those bytes meet zero activations, which is harmless only if they decode to finite numbers - +// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert. +constexpr size_t MMQ_TAIL = 4096; +struct MmqPlan { + bool any = false, fallback = true; + std::vector layer; // per layer: MMQ + size_t gu_max = 0, d_max = 0; +}; +const MmqPlan& mmq_plan() { + static const MmqPlan plan = [] { + MmqPlan p; + const auto& lay = strata::kernels::cpu::expert_layout(); + const char* env = std::getenv("STRATA_PREFILL_MMQ"); + const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0); + const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers; + p.layer.assign((size_t) std::max(layers, 0), 0); + p.fallback = !on || layers <= 0; + for (int64_t l = 0; on && l < layers; ++l) { + const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; + // #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path + if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) { p.fallback = true; continue; } + p.layer[(size_t) l] = 1; + p.any = true; + p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N)); + p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640)); + } + return p; + }(); + return plan; +} +uint64_t moe_set_bytes(size_t T, int64_t n_expert) { + const MmqPlan& mp = mmq_plan(); + Alloc a; a.count_only = true; bool ok = true; + a.take(T * n_expert, ok); a.take(T * K, ok); a.take(T * K, ok); a.take(T * K, ok); + a.take(T * K, ok); + if (mp.fallback) a.take(T * K * N, ok); + a.take(T * K * 1280, ok); + if (mp.fallback) a.take(T * K * 640, ok); + a.take(T * K * N, ok); a.take(T * 640, ok); + a.take(T * 640, ok); a.take(T * 640, ok); a.take(T * N, ok); a.take(T, ok); + if (mp.any) { + a.take(mmq::q8_bytes((int64_t) (T * K), N), ok); + a.take(T * K * 640, ok); + a.take(mmq::q8_bytes((int64_t) (T * K), 640), ok); + } + return a.used; +} +} + +bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss, + core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, + void* stream, std::string& err, void* borrow, uint64_t borrow_bytes) { + Impl& m = *impl_; + m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; + m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; + if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) { + err = "prefill: geometry differs from the artifact's"; return false; + } + cudaGetDevice(&m.device); + if (stage_le_ < 0) stage_le_ = g.n_layers; + if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) { + err = "prefill: the stage's layer range is wrong"; + return false; + } + for (int b = 0; next_ != nullptr && b < 2; ++b) + if (!m.hand[b] && cudaHostAlloc((void**) &m.hand[b], (size_t) chunk * D * 4, cudaHostAllocPortable) != cudaSuccess) { + err = "prefill: the layer split's hand-off buffers"; + return false; + } + if (m.tok_dev == nullptr) { + if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) { + err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")"; + return false; + } + m.owned.push_back(m.tok_dev); + m.tok_host.resize((size_t) chunk); + } + if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; } + const size_t T = (size_t) chunk; + m.T_max = chunk; + m.borrowed = borrow != nullptr; + bool ok = true; + // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table + for (int i = 0; i < RING_MAX; ++i) { + if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false; + if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false; + } + if (!m.stager) { + m.stager = std::make_unique(); + const int hw = (int) std::thread::hardware_concurrency(); + const char* stv = std::getenv("STRATA_STAGER_THREADS"); // D-5: the host copy threads of unpinned blobs + // A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the + // SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s + // instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source) + bool files = false; + for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l) + for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e); + const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4)); + if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads; + if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false; + } + m.steps_host.resize(T * strata::kernels::kStepCount); + m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1); + { + const size_t need = 3 * T * K + (size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)); + const char* gc = std::getenv("STRATA_GROUP_COPY"); + if (m.grp_n < need && !(gc && gc[0] == '1')) { + if (m.grp_host) cudaFreeHost(m.grp_host); + m.grp_host = m.grp_dev = nullptr; + m.grp_n = m.grp_tk = 0; + void *h = nullptr, *d = nullptr; + if (cudaHostAlloc(&h, need * 4, cudaHostAllocMapped) == cudaSuccess && + cudaHostGetDevicePointer(&d, h, 0) == cudaSuccess) { + m.grp_host = (int32_t*) h; + m.grp_dev = (int32_t*) d; + m.grp_n = need; + m.grp_tk = T * K; + } else { // the copies, as before + if (h) cudaFreeHost(h); + cudaGetLastError(); + } + } + } + for (int b = 0; b < 2; ++b) { + if (!m.ple_emb_host[b] && + cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess) { + cudaGetLastError(); + m.ple_pageable[b].resize(T * N); // pageable: the upload is staged before it returns + m.ple_emb_host[b] = m.ple_pageable[b].data(); + } + if (!m.ple_copied[b] && cudaEventCreateWithFlags(&m.ple_copied[b], cudaEventDisableTiming) != cudaSuccess) + ok = false; + m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS); + } + if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table + const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages; + std::vector ident((size_t) pages); + for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i; + if (cudaMalloc((void**) &m.ident_table, ident.size() * 4) != cudaSuccess || + cudaMemcpy(m.ident_table, ident.data(), ident.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) + ok = false; + else + m.owned.push_back(m.ident_table); + } + if (!ok) { err = "prefill: host buffers or events for a chunk of " + std::to_string(chunk) + " tokens"; return false; } + Alloc o; + o.base = (uint8_t*) borrow; + o.cap = borrow_bytes; + o.owned = &m.owned; + { + uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); + void* ws = o.take(GEMM_WS, ok); + if (!ok) { err = "prefill: GEMM scratch does not fit"; return false; } + if (!m.gemm.init_external(stream, gs, GEMM_SCRATCH, ws, GEMM_WS, err)) return false; + } + if (!carve(T, &o)) { + err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit"; + return false; + } + return true; +} + +// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init` +// once, and `relayout` for a request's own chunk. The order is `bytes_needed`'s. +bool Prefill::carve(size_t T, void* alloc) { + Impl& m = *impl_; + Alloc& o = *static_cast(alloc); + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + bool ok = true; + m.emb = o.take(T * N, ok); m.R = o.take(T * D, ok); + m.xn = gr_unfused() ? o.take(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R) + m.grs = o.take(T * HC, ok); + m.xn16 = o.take(T * D, ok); m.lo = o.take(T * LR, ok); m.lo16 = o.take(T * LR, ok); + m.gated = o.take(T * D, ok); m.inj = o.take(T * HC, ok); + m.mixed = o.take(T * N, ok); m.mixed_bf = o.take(T * N, ok); + m.mixed_h = o.take(T * N, ok); m.bo = o.take(T * N, ok); + if (bf16x2_hc()) { m.xn16_lo = o.take(T * D, ok); m.lo16_lo = o.take(T * LR, ok); } + if (bf16x2()) m.mixed_bf_lo = o.take(T * N, ok); + m.steps_dev = o.take(T * strata::kernels::kStepCount, ok); + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); + m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + { + // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) + const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch, + m.attn_batch, s), moe_set_bytes(T, m.g->n_expert)}); + uint8_t* base = o.take((size_t) region, ok); + m.region = base; + m.region_bytes = region; + Alloc a; + a.base = base; a.cap = region; a.owned = &m.owned; + m.qkv = a.take(T * C, ok); m.z = a.take(T * ZV, ok); m.ab = a.take(T * 2 * HV, ok); + m.gate = a.take(T * HV, ok); m.beta = a.take(T * HV, ok); m.hbuf = a.take(T * C, ok); + m.y = a.take(T * ZV, ok); m.y_h = a.take(T * ZV, ok); + Alloc b; + b.base = base; b.cap = region; b.owned = &m.owned; + m.Kc = b.take(T * 512, ok); m.Vc = b.take(T * 512, ok); m.Qf = b.take(T * 12288, ok); + m.q = b.take(T * ZV, ok); m.idx_raw = b.take(T * 128, ok); m.q_idx = b.take(T * 512, ok); + m.attn = b.take(T * ZV, ok); m.attn_h = b.take(T * ZV, ok); + m.sel_ids = b.take(T * (size_t) m.cap, ok); + m.sel_scores = b.take((size_t) m.sel_batch * (size_t) m.max_blocks, ok); + m.attn_scratch = b.take((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok); + Alloc c; + c.base = base; c.cap = region; c.owned = &m.owned; + m.logits = c.take(T * m.g->n_expert, ok); m.w = c.take(T * K, ok); m.ids = c.take(T * K, ok); + m.slot_dev = c.take(T * K, ok); m.src_dev = c.take(T * K, ok); + const MmqPlan& mp = mmq_plan(); + m.Xs = mp.fallback ? c.take(T * K * N, ok) : nullptr; + m.GU = c.take(T * K * 1280, ok); + m.Hh = mp.fallback ? c.take(T * K * 640, ok) : nullptr; + m.Dm = c.take(T * K * N, ok); + m.sgate = c.take(T * 640, ok); m.sup = c.take(T * 640, ok); m.sh_h = c.take(T * 640, ok); + m.shared = c.take(T * N, ok); m.sg = c.take(T, ok); + if (mp.any) { + m.Xq = c.take(mmq::q8_bytes((int64_t) (T * K), N), ok); + m.H = c.take(T * K * 640, ok); + m.Hq = c.take(mmq::q8_bytes((int64_t) (T * K), 640), ok); + } + if (base == nullptr) ok = false; + } + for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take(1280 * 2560, ok); m.dq_d[i] = o.take(2560 * 640, ok); } + if (mmq_plan().any) { + const MmqPlan& mp = mmq_plan(); + m.ids_identity = o.take(T * K, ok); + m.bounds_dev = o.take((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok); + m.grp_gu = o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); + m.grp_d = o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + // (written at every run's start, not here: when serving, these are live expert-cache slots until a request + // lends them - a write now would corrupt a resident expert) + if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); + } + m.ring = ring_slots(T); + for (int i = 0; i < m.ring; ++i) { + m.stage_dev[i] = o.take((size_t) MAXBLOB(), ok); + m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for + } + m.ple_emb = o.take(T * N, ok); + m.ple_norm = o.take((size_t) strata::kernels::NG_HC_DIM, ok); + take_stage(o, ss, s, m.stage, ok); + m.T = (int64_t) T; + return ok; +} + +bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err) { + Impl& m = *impl_; + if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) { + err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max); + return false; + } + if (cudaStreamSynchronize(m.cs) != cudaSuccess || cudaStreamSynchronize(m.copy) != cudaSuccess) { + err = "prefill: relayout: the stream failed"; + return false; + } + bool ok = true; + Alloc o; + o.base = (uint8_t*) borrow; + o.cap = borrow_bytes; + o.owned = &m.owned; + uint16_t* gs = o.take((size_t) GEMM_SCRATCH, ok); + void* ws = o.take(GEMM_WS, ok); + if (ok) m.gemm.rebind(gs, GEMM_SCRATCH, ws, GEMM_WS); + if (!ok || !carve((size_t) chunk, &o)) { + err = "prefill: device buffers for a chunk of " + std::to_string(chunk) + " tokens do not fit"; + return false; + } + return true; +} + +int64_t Prefill::chunk() const { return impl_->T; } + +bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, + std::string& err) { + Impl& m = *impl_; + static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }(); + core::QsaState& st = mtp.kv_state_rw(); + if (off || n <= 0 || m.g == nullptr || m.region == nullptr || st.kv_mode != 0 || st.kv_hybrid || + mtp.device() != m.device) + return false; + const auto t0 = Clock::now(); + const core::ModelGeometry& g = *m.g; + const int64_t Nn = g.n_embd, HCN = g.hc * g.n_embd, KV = g.n_head_kv * g.head_dim; + constexpr int kQ8_0 = 8; // GGML_TYPE_Q8_0 + const float* w_ne = mtp.tensor_f32("pre_fc_norm_embedding.weight"); + const void* w_fe = mtp.tensor_q8("fc_embedding.weight"); + const float* w_nh = mtp.tensor_f32("pre_fc_norm_hidden.weight"); + const void* w_fh = mtp.tensor_q8("fc_hidden.weight"); + const float* w_hn = mtp.tensor_f32("attn_hyper_connection.hc_norm.weight"); + const uint16_t* w_dn = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_down.weight"); + const uint16_t* w_up = mtp.tensor_bf16("attn_hyper_connection.input_mix_weight_up.weight"); + const void* w_k = mtp.tensor_q8("self_attn.k_proj.weight"); + const void* w_v = mtp.tensor_q8("self_attn.v_proj.weight"); + const float* w_kn = mtp.tensor_f32("self_attn.k_norm.weight"); + if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn) return false; + const core::NativeEmbed* nemb = core::native_embed(); + const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); + if (!nemb && (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || + (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) + return false; + // the cells the drafter's window can still reach + const int64_t r0 = std::max(0, mtp.first_needed() - cell0); + if (r0 >= n) return true; + // per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) + + // mixed_h, K and V (KV each), the token id + // E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so + // its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B) + static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }(); + const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV); // #420 + const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 + + (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0); + const int64_t B = std::min(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); + if (B < 64) return false; + uint8_t* q = m.region; + auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; }; + float* emb = (float*) carve((size_t) B * Nn * 4); + float* e2 = (float*) carve((size_t) B * Nn * 4); + uint16_t* en16 = (uint16_t*) carve((size_t) B * Nn * 2); + float* hn = (float*) carve((size_t) B * HCN * 4); + float* h2 = (float*) carve((size_t) B * HCN * 4); + float* Rm = (float*) carve((size_t) B * HCN * 4); + float* gated = (float*) carve((size_t) B * HCN * 4); + uint16_t* hn16 = (uint16_t*) carve((size_t) B * HCN * 2); + uint16_t* xn16 = (uint16_t*) carve((size_t) B * HCN * 2); + float* lo = (float*) carve((size_t) B * LR * 4); + uint16_t* lo16 = (uint16_t*) carve((size_t) B * LR * 2); + float* grs = (float*) carve((size_t) B * HC * 4); + float* mixed = (float*) carve((size_t) B * Nn * 4); + uint16_t* mixed_h = (uint16_t*) carve((size_t) B * Nn * 2); + float* Kc = (float*) carve((size_t) B * KV * 4); + float* Vc = (float*) carve((size_t) B * KV * 4); + int32_t* tok = (int32_t*) carve((size_t) B * 4); + void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr; + int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr; + int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr; + if ((uint64_t) (q - m.region) > m.region_bytes) return false; + if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + std::vector tk((size_t) B); + if (q8) { + if (!m.mmq_ctx) m.mmq_ctx = std::make_unique(); + mmq::iota(ident, B * g.hc, m.cs); + } + // y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc) + auto proj = [&](const float* x, const uint16_t* x16, const void* w, float* y, int64_t rows, int64_t n_out, + int64_t k, int slot) { + if (!q8) { m.gemm.native(x16, kQ8_0, w, y, rows, n_out, k); return; } + mmq::quantize(x, nullptr, xq, kQ8_0, k, k, rows, m.cs); + mmq::Product p; + p.w = w; p.type = kQ8_0; p.w_rows = n_out; p.w_cols = k; p.expert_bytes = mmq::matrix_bytes(kQ8_0, n_out, k); + p.n = 1; p.xq = xq; p.bounds = bnd + 2 * slot; p.ids = ident; p.total_rows = rows; p.max_rows = rows; + p.dst = y; p.ld_dst = n_out; + m.mmq_ctx->run(p, m.cs); + }; + for (int64_t b0 = r0; b0 < n; b0 += B) { + const int64_t nb = std::min(B, n - b0), c0 = cell0 + b0; + for (int64_t i = 0; i < nb; ++i) tk[(size_t) i] = next_tokens[b0 + i]; + const int32_t bh[4] = {0, (int32_t) nb, 0, (int32_t) (nb * g.hc)}; + if (q8 && cudaMemcpyAsync(bnd, bh, sizeof bh, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { + err = "prefill: the draft bounds' upload failed"; + return false; + } + if (cudaMemcpyAsync(tok, tk.data(), (size_t) nb * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { + err = "prefill: the draft tokens' upload failed"; + return false; + } + // the input branches: the next token's embedding, and this cell's final residual rows + if (nemb) { + nemb->gather_dev(tok, nb, emb, m.cs); + } else { + const auto* codes = (const uint8_t*) wemb->data; + const auto* scales = (const float*) (codes + wemb->codes_bytes); + const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes) + : nullptr; + strata::kernels::embedding_gather_dev(codes, scales, offsets, tok, (int) nb, wemb->ne0, wemb->code_bits, + wemb->code_bias, wemb->group_elems, + (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)), + (uint64_t) (wemb->ne0 / wemb->group_elems), emb, m.cs); + } + rms_rows(emb, w_ne, nb, Nn, Nn, EPS, m.cs); + if (!q8) to_f16(emb, en16, nb * Nn, m.cs); + proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0); + cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs); + rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs); + if (!q8) to_f16(hn, hn16, nb * HCN, m.cs); + proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hidden + strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs); + // the attention hyper-connection's read (its mixed input only: this pass writes nothing back) + gr_norm_rs(Rm, w_hn, EPS, grs, xn16, nb, m.cs); + m.gemm.bf16(xn16, w_dn, lo, nb, LR, HCN); + gr_silu(lo, lo16, nb, m.cs); + m.gemm.bf16(lo16, w_up, gated, nb, HCN, LR); + gr_mix_r(Rm, grs, w_hn, gated, mixed, nullptr, nb, m.cs, mixed_h); + // K and V into the drafter's cache, as the prompt path's QSA layers append theirs + proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0); + proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); + rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs); + rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) { // rotated as the drafter's own decode stores them (mtp.cpp) + strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs); + strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs); + } + if (st.kv_q4) { + strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host); + } else { + kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, + st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, &st.host); + } + } + if (cudaStreamSynchronize(m.cs) != cudaSuccess) { + err = std::string("prefill: the draft layer's K/V: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + mtp.ms_prefill += ms_since(t0); + return true; +} +void Prefill::set_pinned_share(double share) { g_pinned_share = share; } +void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; } +double Prefill::pinned_share() { return g_pinned_share; } + +uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) { + // the same allocation sequence as `init`, counted + const size_t T = (size_t) chunk; + bool ok = true; + Alloc o; + o.count_only = true; + o.take((size_t) GEMM_SCRATCH, ok); + o.take(GEMM_WS, ok); + auto f = [&](size_t n) { o.take(n, ok); }; + f(T * N); f(T * D); f(T * D); o.take(T * D, ok); f(T * LR); o.take(T * LR, ok); + f(T * D); f(T * HC); f(T * N); o.take(T * N, ok); o.take(T * N, ok); f(T * N); + if (bf16x2_hc()) { o.take(T * D, ok); o.take(T * LR, ok); } + if (bf16x2()) o.take(T * N, ok); + o.take(T * strata::kernels::kStepCount, ok); + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s); + const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2; + o.take((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s), + moe_set_bytes(T, g.n_expert)}), ok); + for (int i = 0; i < DQ; ++i) { o.take(1280 * 2560, ok); o.take(2560 * 640, ok); } + if (mmq_plan().any) { + const MmqPlan& mp = mmq_plan(); + o.take(T * K, ok); + o.take((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok); + o.take(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok); + o.take(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok); + } + for (int i = 0; i < ring_slots(T); ++i) o.take((size_t) MAXBLOB(), ok); + f(T * N); + f((size_t) strata::kernels::NG_HC_DIM); + strata::kernels::KvHostPools stage; + take_stage(o, ss, s, stage, ok); + return o.used + (8u << 20); // alignment slack +} + +namespace { + +const core::WeightRef* need(const core::LayerView& v, const char* suffix, std::string& err) { + const core::WeightRef* r = v.get(suffix); + if (!r) err = v.name(suffix) + " is missing"; + return r; +} +bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, + std::string& err, int64_t ldy = 0) { + if (!w->native_data) { err = "prefill: " + name + " has no native GGUF blocks (run with --native)"; return false; } + gm.native(X, w->native_type, w->native_data, Y, T, w->ne1, w->ne0, ldy); + return true; +} +bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name, + std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) { + if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; } + gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy); + if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f); + return true; +} + +} // namespace + +namespace { +// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase. Events are recorded on the compute stream in order; +// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the +// host's expert grouping, or for an expert's copy) lands on the phase that was waiting. Events are reused: the marks +// are folded at every MoE layer's host sync, after which all of them have completed. +enum PfPhase { kPfStart, kPfHc, kPfGdn, kPfQsa, kPfQsaIdx, kPfQsaSel, kPfQsaAttn, kPfRouter, kPfHostGroup, kPfGather, + kPfWaitCopy, kPfDequant, kPfGemmGU, kPfGemmD, kPfCombine, kPfPle, kPfKvStage, kPfGdnConv, kPfGdnRec, kPfGdnOut, + kPfCount }; +const char* const kPfNames[kPfCount] = {"embed+steps", "hc read", "gdn", "qsa proj", "qsa indexer", "qsa select", + "qsa attn", "router+shared", "host grouping", "gather", "wait copy", "dequant", + "gemm gate/up", "gemm down", "combine", "ple", "kv stage", "gdn conv+gates", + "gdn recurrence", "gdn out proj"}; +struct PfTimer { + bool on = std::getenv("STRATA_PREFILL_TIMING") != nullptr; + std::vector ev; + std::vector ph; + size_t used = 0; + double ms[kPfCount] = {}; + void mark(int phase, cudaStream_t s) { + if (!on) return; + if (used == ev.size()) { + cudaEvent_t e = nullptr; + cudaEventCreate(&e); + ev.push_back(e); + ph.push_back(0); + } + ph[used] = phase; + cudaEventRecord(ev[used], s); + ++used; + } + // every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark + void fold() { + if (!on || used < 2) return; + for (size_t i = 0; i + 1 < used; ++i) { + float t = 0.0f; + if (cudaEventElapsedTime(&t, ev[i], ev[i + 1]) == cudaSuccess) ms[ph[i]] += t; + } + std::swap(ev[0], ev[used - 1]); + std::swap(ph[0], ph[used - 1]); + used = 1; + } + ~PfTimer() { + for (cudaEvent_t e : ev) cudaEventDestroy(e); + } +}; +} // namespace + +bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { + err.clear(); + Impl& m = *impl_; + const core::OnDevice on_device(m.device); + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + const auto t_start = Clock::now(); + // Offline teacher capture for fitting only the paper's query-routing parameters. + // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. + std::ofstream keyless_trace; + if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) { + if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) { + err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens"; + return false; + } + keyless_trace.open(path, std::ios::binary); + if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; } + std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); + keyless_trace.write("SKLTRACE", 8); + const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim}; + keyless_trace.write((const char*)header, sizeof(header)); + } + const int64_t LB = stage_lb_, LE = stage_le_; + // the next stage reads chunk c on a thread while this one reads chunk c + 1 (declared first: an early return + // waits for it before anything it reads goes away) + std::string next_err; + std::future next_run; + int hand_buf = 0; + double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads; + s.idx_dim = g.idx_key_dim; + const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1); + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + PfTimer pt; + const cudaStream_t cs = (cudaStream_t) m.cs; + // the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts: + // write it again for every prompt (a layout is reused as long as the chunk and the slots are the same) + if (m.ids_identity != nullptr) mmq::iota(m.ids_identity, m.T * K, m.cs); + // The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk + // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows + // depend only on the tokens (the two before a position name its n-grams), so this is the same data. + const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; + const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled(); + // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); + // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) + static const bool ple_batch_env = [] { + const char* v = std::getenv("STRATA_PLE_BATCH"); + return v == nullptr || std::atoi(v) != 0; + }(); + const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled() && + (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; + const int32_t prev0[2] = {prev[0], prev[1]}; + auto ple_gather = [&m, &ss, tokens, n, prev0, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool { + const int64_t T = std::min(m.T, n - c0); + auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens + int32_t pv[2] = {at(c0), at(c0 + 1)}; + for (int64_t t = 0; t < T; ++t) { + const int32_t tok = (int32_t) tokens[c0 + t]; + strata::kernels::ngram_rows(&tok, pv, 1, ss.ple.consts, + m.ple_rows[buf].data() + t * strata::kernels::PLE_N_HEADS); + pv[0] = pv[1]; + pv[1] = tok; + } + return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, + m.ple_emb_host[buf], e); + }; + std::string ple_next_err; + std::future ple_next; // declared after everything it reads: an early return waits for it + int ple_buf = 0; + + for (int64_t c0 = 0; c0 < n; c0 += m.T) { + if (should_stop && should_stop()) { err = "cancelled"; return false; } + if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); } + const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0; + core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251 + ++stats_.chunks; + pt.mark(kPfStart, cs); + const auto tsetup = Clock::now(); + // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the + // previous stage handed on + if (hand_in_ != nullptr) { + if (cudaMemcpyAsync(m.R, hand_in_ + (size_t) c0 * D, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs) != + cudaSuccess) { + err = "prefill: the layer split's hand-off upload failed"; + return false; + } + } + // C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the + // same bits); a chunk with picture rows, or a token outside the table, takes the per-token path + bool batched = hand_in_ == nullptr && m.tok_dev != nullptr; + const core::NativeEmbed* nemb = core::native_embed(); + const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight"); + if (batched && nemb == nullptr && + (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 || + (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8))) + batched = false; + for (int64_t t = 0; batched && t < T; ++t) { + const int64_t tok = tokens[c0 + t]; + if ((embd_rows && embd_rows[p0 + t]) || tok < 0 || (wemb && tok >= wemb->ne1)) batched = false; + else m.tok_host[(size_t) t] = (int32_t) tok; + } + if (batched) { + if (cudaMemcpyAsync(m.tok_dev, m.tok_host.data(), (size_t) T * sizeof(int32_t), cudaMemcpyHostToDevice, + m.cs) != cudaSuccess) { + err = "prefill: the token id upload failed"; + return false; + } + if (nemb) { + nemb->gather_dev(m.tok_dev, T, m.emb, m.cs); + } else { + const auto* codes = (const uint8_t*) wemb->data; + const auto* scales = (const float*) (codes + wemb->codes_bytes); + const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes) + : nullptr; + strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0, + wemb->code_bits, wemb->code_bias, wemb->group_elems, + (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)), + (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, m.cs); + } + } + for (int64_t t = 0; hand_in_ == nullptr && !batched && t < T; ++t) { + const float* row = embd_rows ? embd_rows[p0 + t] : nullptr; + if (row) { + if (cudaMemcpyAsync(m.emb + t * N, row, (size_t) N * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) { + err = "prefill: the image embedding upload failed"; + return false; + } + } else if (!core::embed_row(*m.wt, g, tokens[c0 + t], m.emb + t * N, m.cs, err)) { + return false; + } + } + if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs); + // ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather) + 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 = std::async(std::launch::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); + } + for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; } + // ---- the QSA step records of every position in the chunk + for (int64_t t = 0; t < T; ++t) strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s); + cudaMemcpyAsync(m.steps_dev, m.steps_host.data(), (size_t) T * strata::kernels::kStepCount * 4, + cudaMemcpyHostToDevice, m.cs); + + int64_t qsa_index = 0, gdn_index = 0; + for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; + // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry + // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's + // `used` event recorded), so the copy stream never waits on an event that is not queued yet + 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; + } + }; + // D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits + // behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the + // i-quant prompts). The same copies in the same order into the same slots, and a slot is refilled only once + // the compute stream has recorded that it is done with it: the same results. STRATA_PREFILL_ISSUER=0: inline. + static const bool issuer_on = [] { + const char* v = std::getenv("STRATA_PREFILL_ISSUER"); + return v == nullptr || std::atoi(v) != 0; + }(); + std::atomic a_issued{0}, a_consumed{0}; + std::atomic a_stop{false}; + double iss_ms = 0; + int64_t iss_streamed = 0, iss_dma = 0; + std::thread issuer; + struct IssuerJoin { + std::atomic* stop; + std::thread* t; + ~IssuerJoin() { if (t->joinable()) { stop->store(true); t->join(); } } + } issuer_join{&a_stop, &issuer}; + const bool threaded_issue = stream_all && issuer_on; + if (threaded_issue) { + issuer = std::thread([&] { + const core::OnDevice od(m.device); + for (size_t idx = 0; idx < seq.size(); ++idx) { + while (idx >= a_consumed.load(std::memory_order_acquire) + (size_t) m.ring) { + if (a_stop.load(std::memory_order_acquire)) return; + std::this_thread::yield(); + } + const StreamEntry& en = seq[idx]; + const int sl = (int) (idx % (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); + ++iss_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; + iss_ms += ms_since(th); + ++iss_streamed; + a_issued.store(idx + 1, std::memory_order_release); + } + }); + } else if (stream_all) { + issue_until((size_t) m.ring); // layer 0's first experts, behind the embedding and the PLE + } + // 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); + }; + host_setup_ms += ms_since(tsetup); + bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16) + for (int64_t l = LB; l < LE; ++l) { + core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving + core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk + const core::LayerView v(*m.wt, l); + // ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows) + if (l == 1 && ple_on && ple_batch) { + // the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value + // projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ + // files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch) + pt.mark(kPfPle, cs); + const auto tp = Clock::now(); + const strata::kernels::PleWeights& pw = ss.ple.w; + constexpr int64_t HD = strata::kernels::NG_HC_DIM; + const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096; + const int64_t SB = std::min(T, (int64_t) (m.region_bytes / per_token)); + for (int64_t s0 = 0; s0 < T; s0 += SB) { + const int64_t nb = std::min(SB, T - s0); + uint8_t* q = m.region; + auto carve_f = [&](size_t n) { float* p = (float*) q; q += (n * 4 + 255) & ~(size_t) 255; return p; }; + float* key = carve_f((size_t) nb * HD); + float* qn = carve_f((size_t) nb * HD); + float* gated = carve_f((size_t) nb * HD); + float* val = carve_f((size_t) nb * N); + float* gate = carve_f((size_t) nb * 4); + uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2); + uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr; + const float* emb = m.ple_emb + s0 * N; + if (pw.key_bf16 != nullptr) { + to_bf16(emb, e16, nb * N, m.cs, e16_lo); + m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f); + } else { + to_f16(emb, e16, nb * N, m.cs); + m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N); + to_bf16(emb, e16, nb * N, m.cs, e16_lo); + } + m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N); + if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f); + try { + strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated, + gate, (int) nb, m.cs); + } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } + } + stats_.ms_ple += ms_since(tp); + } else if (l == 1 && ple_on) { + pt.mark(kPfPle, cs); + const auto tp = Clock::now(); + for (int64_t t = 0; t < T; ++t) { + strata::kernels::PleOut po; + po.normalized = m.ple_norm; + po.result = m.R + t * D; + try { + strata::kernels::ple_block(m.ple_emb + t * N, m.R + t * D, ss.ple.hist, ss.ple.w, po, + ss.ple.scratch, m.cs); + } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; } + strata::kernels::ple_history_advance(ss.ple.hist, m.ple_norm, m.cs); + } + stats_.ms_ple += ms_since(tp); + } + for (int half = 0; half < 2; ++half) { + // ---- the hyper-connection read of this half + const char* pre = half == 0 ? "hc_attn_" : "hc_ffn_"; + const std::string sn = std::string(pre) + "norm.weight", sd = std::string(pre) + "down.weight", + su = std::string(pre) + "up.weight", si = std::string(pre) + "inject.weight"; + const core::WeightRef *wn = need(v, sn.c_str(), err), *wd = need(v, sd.c_str(), err), + *wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err); + if (!wn || !wd || !wu || !wi) return false; + pt.mark(kPfHc, cs); + if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo); + else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo); + normed = false; + if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false; + gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo); + if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false; + if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false; + if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo); + else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, + m.mixed_bf_lo); + + if (half == 0 && !core::is_qsa_layer(g, l)) { + // ======================= GDN ======================= + const core::WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err), + *wo = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err), + *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err), + *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err), + *wsa = need(v, "ssm_a", err); + if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false; + pt.mark(kPfGdn, cs); + float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats; + float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; + if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false; + if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false; + if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false; + pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines + gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs); + gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs); + pt.mark(kPfGdnRec, cs); + gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs); + pt.mark(kPfGdnOut, cs); + if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err)) return false; + ++gdn_index; + } else if (half == 0) { + // ======================= QSA ======================= + const core::QsaState& st = ss.qsa_states[qsa_index]; + const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err), + *wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err), + *wik = need(v, "indexer.k_proj.weight", err), + *wiq = need(v, "indexer.q_proj.weight", err), + *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err), + *wiqn = need(v, "indexer.q_norm.weight", err), + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); + if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); + if (!st.without_key) rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); + // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the + // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks + const bool staged = st.kv_mode == 1; + if (staged) { + pt.mark(kPfKvStage, cs); + strata::kernels::kv_stage_from_host(pools_of(m.stage, m.ident_table), st.host, + core::qsa_kv_format(st), + (p0 + s.page_size - 1) / s.page_size, s, m.cs); + pt.mark(kPfQsa, cs); + } + if (st.kv_hybrid) { // K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) + strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); + kv_append(m.Kc, m.Kc, T, p0, st.page_table, s.page_size, nullptr, nullptr, + st.k_q, st.k_q, st.k_scale, st.k_scale, m.cs, nullptr, // mode 0: no host mirror + staged ? &m.stage : nullptr); + strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs, + nullptr, staged ? &m.stage : nullptr); + } else { + if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output back + strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs); + strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs); + } + if (st.kv_q4) + strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs, + &st.host, staged ? &m.stage : nullptr); + else + kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool, + st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs, + &st.host, staged ? &m.stage : nullptr); + } + split_q(m.Qf, m.q, T, m.cs); + rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); + if (keyless_trace.is_open()) { + const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T}; + keyless_trace.write((const char*)record, sizeof(record)); + for (const auto& tensor : std::vector>{ + {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) { + std::vector host(tensor.second); + if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess || + cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; } + keyless_trace.write((const char*)host.data(), host.size()*sizeof(float)); + } + if (!keyless_trace) { err="keyless teacher trace write failed"; return false; } + } + if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); + rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); + rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); + // the indexer appends, token by token; then scores + selection for many queries at once: + // a query reads completed blocks (final once completed) and `dead` for its own tail block + const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; + pt.mark(kPfQsaIdx, cs); + // C-2: the chunk's appends in three launches instead of one per token (the same end state: + // the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old + try { + static const bool per_token = std::getenv("STRATA_INDEXER_PER_TOKEN") != nullptr; + if (!per_token) { + strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data, + EPS, ib, s, st.max_cells, + strata::kernels::rope_scaling(), m.cs); + } + for (int64_t t = 0; per_token && t < T; ++t) { + const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount; + strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0, + (const float*) wikn->data, EPS, ib, s, st.max_cells, + strata::kernels::rope_scaling(), m.cs); + } + } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; } + pt.mark(kPfQsaSel, cs); + for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) { + const int64_t nb = std::min(m.sel_batch, T - t0); + const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount; + // C-1: the grid reaches the batch's last query's n_bid (they rise with the position) + const int64_t active = (int64_t) m.steps_host[(size_t) ((t0 + nb - 1) * strata::kernels::kStepCount + + strata::kernels::kStepNBid)] + 1; + // the scores on tensor cores (3xTF32: FP32-level, not bitwise); STRATA_SELECT_OLD=1: the warp kernel + static const bool old_sel = std::getenv("STRATA_SELECT_OLD") != nullptr; + if (old_sel || !strata::kernels::qsa_block_scores_tc(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, + steps0, nb, m.max_blocks, s, m.sel_scores, + m.cs, active)) + strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb, + m.max_blocks, s, m.sel_scores, m.cs, active); + strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s, + m.sel_ids + t0 * m.cap, m.cs, active); + } + // STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share? + // Per tile of 16 queries: the union of their selected cells against the sum of their widths. + if (static const bool ovl = std::getenv("STRATA_SEL_OVERLAP") != nullptr; ovl && qsa_index == 0) { + std::vector ids((size_t) (T * m.cap)); + cudaMemcpyAsync(ids.data(), m.sel_ids, ids.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + double sum_w = 0, sum_u = 0; + for (int64_t t0 = 0; t0 + 16 <= T; t0 += 16) { + std::vector u; + for (int64_t t = t0; t < t0 + 16; ++t) { + const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)]; + sum_w += (double) w; + u.insert(u.end(), ids.begin() + t * m.cap, ids.begin() + t * m.cap + w); + } + std::sort(u.begin(), u.end()); + sum_u += (double) (std::unique(u.begin(), u.end()) - u.begin()); + } + std::fprintf(stderr, "strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the " + "cells one query at a time does\n", (long long) p0, sum_w > 0 ? 100.0 * sum_u / sum_w : 0.0); + } + // STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming + // design's last question). Every query is selected again from the pooled keys and `dead` rounded + // to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is + // printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer. + if (static const bool f16chk = std::getenv("STRATA_IDX_FP16_CHECK") != nullptr; f16chk) { + static float *pooled16 = nullptr, *dead16 = nullptr; + static int32_t* ids16 = nullptr; + static double shared = 0, cells = 0; + static long long queries = 0, same = 0, sel_queries = 0; + const int64_t rows = st.idx_pooled_rows; + if (pooled16 == nullptr && + (cudaMalloc((void**) &pooled16, (size_t) rows * s.idx_dim * 4) != cudaSuccess || + cudaMalloc((void**) &dead16, (size_t) s.idx_dim * 4) != cudaSuccess || + cudaMalloc((void**) &ids16, (size_t) (m.T * m.cap) * 4) != cudaSuccess)) { + err = "STRATA_IDX_FP16_CHECK: no room for its buffers"; + return false; + } + round_f16(st.idx_pooled, pooled16, rows * s.idx_dim, m.cs); + round_f16(st.idx_dead, dead16, s.idx_dim, m.cs); + for (int64_t t0 = 0; t0 < T; t0 += m.sel_batch) { + const int64_t nb = std::min(m.sel_batch, T - t0); + const int32_t* steps0 = m.steps_dev + t0 * strata::kernels::kStepCount; + strata::kernels::qsa_block_scores(pooled16, dead16, m.q_idx + t0 * 512, steps0, nb, + m.max_blocks, s, m.sel_scores, m.cs); + strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s, + ids16 + t0 * m.cap, m.cs); + } + std::vector a((size_t) (T * m.cap)), b((size_t) (T * m.cap)); + cudaMemcpyAsync(a.data(), m.sel_ids, a.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaMemcpyAsync(b.data(), ids16, b.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + for (int64_t t = 0; t < T; ++t) { + const int64_t w = m.steps_host[(size_t) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth)]; + const int32_t *x = a.data() + t * m.cap, *y = b.data() + t * m.cap; + int64_t i = 0, j = 0, c = 0; + while (i < w && j < w) { + if (x[i] == y[j]) { ++c; ++i; ++j; } else if (x[i] < y[j]) ++i; else ++j; + } + ++queries; + same += c == w; + if (p0 + t + 1 > m.cap) { ++sel_queries; shared += (double) c; cells += (double) w; } + } + if (qsa_index + 1 == g.n_qsa_layers()) + std::fprintf(stderr, "strata prefill: FP16 indexer keys: %lld of %lld selections identical; " + "where the selection is sparse, %.4f%% of cells shared (%lld queries)\n", + same, queries, cells > 0 ? 100.0 * shared / cells : 100.0, sel_queries); + } + // STRATA_QSA_DUMP=: append every QSA layer's selected cells for the prompt's last + // STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells, + // for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question) + if (static const char* dump = std::getenv("STRATA_QSA_DUMP"); dump != nullptr) { + static const long long last = std::getenv("STRATA_QSA_DUMP_LAST") + ? std::atoll(std::getenv("STRATA_QSA_DUMP_LAST")) : 4096; + if (p0 + T > pos0 + n - last) { + std::vector h((size_t) (T * m.cap)); + cudaMemcpyAsync(h.data(), m.sel_ids, h.size() * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + if (std::FILE* f = std::fopen(dump, "ab")) { + const int32_t hdr[4] = {(int32_t) qsa_index, (int32_t) p0, (int32_t) T, (int32_t) m.cap}; + std::fwrite(hdr, 4, 4, f); + std::fwrite(h.data(), 4, h.size(), f); + std::fclose(f); + } + } + } + strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) + : core::qsa_attn_pools(st); + pools.without_key = st.without_key; + pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + pt.mark(kPfQsaAttn, cs); + // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level + // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the + // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, + // V dequantized from its q4_0 blocks to fp16 at gather) + static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; + if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, + m.attn, T, m.cs)) + for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { + const int64_t nb = std::min(m.attn_batch, T - t0); + strata::kernels::qsa_decode_attn_batch(m.q + t0 * ZV, pools, m.sel_ids + t0 * m.cap, + m.steps_dev + t0 * strata::kernels::kStepCount, m.cap, + s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs); + } + if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs); + pt.mark(kPfQsa, cs); + gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs); + if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false; + ++qsa_index; + } else { + // ======================= MoE ======================= + const core::WeightRef *wr = need(v, "ffn_gate_inp.weight", err), + *wgi = need(v, "ffn_gate_inp_shexp.weight", err), + *wsg = need(v, "ffn_gate_shexp.weight", err), + *wsu = need(v, "ffn_up_shexp.weight", err), + *wsd = need(v, "ffn_down_shexp.weight", err); + if (!wr || !wgi || !wsg || !wsu || !wsd) return false; + pt.mark(kPfRouter, cs); + if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false; + route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs); + // the shared expert and its scalar gate + if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false; + if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false; + swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs); + if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false; + if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; } + m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N); + if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f); + // group the (token, k) pairs by expert on the host + pt.mark(kPfHostGroup, cs); + // (the sync below also orders this layer's writes of slot/src/bounds after the previous + // layer's kernels that read them) + const bool grp_mapped = m.grp_host != nullptr; + int32_t* ids_h = grp_mapped ? m.grp_host : m.ids_host.data(); + int32_t* slot_h = grp_mapped ? m.grp_host + m.grp_tk : m.slot_host.data(); + int32_t* src_h = grp_mapped ? m.grp_host + 2 * m.grp_tk : m.src_host.data(); + if (grp_mapped) copy_i32(m.grp_dev, m.ids, T * K, m.cs); + else cudaMemcpyAsync(m.ids_host.data(), m.ids, (size_t) T * K * 4, cudaMemcpyDeviceToHost, m.cs); + cudaStreamSynchronize(m.cs); + pt.fold(); + std::fill(m.cnt.begin(), m.cnt.end(), 0); + for (int64_t i = 0; i < T * K; ++i) { + const int32_t e = ids_h[(size_t) i]; + if (e < 0 || e >= m.g->n_expert) { err = "prefill: routed id out of range"; return false; } + ++m.cnt[(size_t) e]; + } + m.off[0] = 0; + for (int64_t e = 0; e < m.g->n_expert; ++e) m.off[(size_t) e + 1] = m.off[(size_t) e] + m.cnt[(size_t) e]; + std::vector fill(m.off.begin(), m.off.end() - 1); + for (int64_t i = 0; i < T * K; ++i) { + const int32_t e = ids_h[(size_t) i]; + const int32_t p = fill[(size_t) e]++; + slot_h[(size_t) i] = p; + src_h[(size_t) p] = (int32_t) (i / K); + } + if (grp_mapped) { + copy_i32(m.slot_dev, m.grp_dev + m.grp_tk, T * K, m.cs); + copy_i32(m.src_dev, m.grp_dev + 2 * m.grp_tk, T * K, m.cs); + } else { + cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); + cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs); + } + // the experts, in id order: resident ones from VRAM, the others through the staging ring + std::vector order; + for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e); + const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); + const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; + const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; + const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; + const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0; + const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0; + pt.mark(kPfGather, cs); + if (use_mmq) { + // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` + mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs); + // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down + // reads the group's own quantized H) + const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP; + m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1)); + for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]]; + m.bounds_host[n] = (int32_t) (T * K); + for (size_t g = 0; g < ng; ++g) + for (size_t i = 0; i <= MMQ_GROUP; ++i) + m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] = + m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP]; + if (grp_mapped) { + int32_t* bh = m.grp_host + 3 * m.grp_tk; + std::memcpy(bh, m.bounds_host.data(), m.bounds_host.size() * 4); + copy_i32(m.bounds_dev, m.grp_dev + 3 * m.grp_tk, (int64_t) m.bounds_host.size(), m.cs); + } else { + cudaMemcpyAsync(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4, + cudaMemcpyHostToDevice, m.cs); + } + } else { + gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs); + } + // 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; + }; + // one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident + // expert) is released once the blob is read + auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool { + const int32_t e = order[j]; + pt.mark(kPfDequant, cs); + if (use_mmq) { + // gather the expert into its group slot (GGUF blocks, unchanged or converted) + const size_t q = j % MMQ_GROUP; + if (lay.native) { + const auto& f = lay.fmt[(size_t) l]; + mmq::gather_native(blob_dev, blob_dev + f.up_off, mmq_gub / 2, blob_dev + f.down_off, + mmq_db, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); + } else { + mmq::gather_strata_q2(blob_dev, m.grp_gu + q * mmq_gub, m.grp_d + q * mmq_db, m.cs); + } + if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); + if (q + 1 < MMQ_GROUP && j + 1 < order.size()) return true; + // the group's products: gate/up, swiglu, the group's H to q8_1, down + const size_t j0 = j - q, g = j0 / MMQ_GROUP, n = order.size(); + const int ngx = (int) (q + 1); + const int64_t r0 = m.bounds_host[j0], nr = m.bounds_host[j + 1] - r0; + int64_t maxr = 0; + for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, m.cnt[(size_t) order[i]]); + pt.mark(kPfGemmGU, cs); + // the zeroed tail after the group's last expert (see MMQ_TAIL) + cudaMemsetAsync(m.grp_gu + (size_t) ngx * mmq_gub, 0, MMQ_TAIL, m.cs); + cudaMemsetAsync(m.grp_d + (size_t) ngx * mmq_db, 0, MMQ_TAIL, m.cs); + mmq::Product gu; + gu.w = m.grp_gu; gu.type = mmq_gt; gu.w_rows = 1280; gu.w_cols = N; gu.expert_bytes = mmq_gub; + gu.n = ngx; gu.xq = m.Xq; gu.bounds = m.bounds_dev + j0; gu.ids = m.ids_identity; + gu.total_rows = T * K; gu.max_rows = maxr; gu.dst = m.GU; gu.ld_dst = 1280; + m.mmq_ctx->run(gu, m.cs); + mmq::swiglu(m.GU + r0 * 1280, m.H + r0 * 640, nr, 640, !lay.native, m.cs); + pt.mark(kPfGemmD, cs); + mmq::quantize(m.H + r0 * 640, nullptr, m.Hq, mmq_dt, 640, 640, nr, m.cs); + mmq::Product dn; + dn.w = m.grp_d; dn.type = mmq_dt; dn.w_rows = N; dn.w_cols = 640; dn.expert_bytes = mmq_db; + dn.n = ngx; dn.xq = m.Hq; dn.bounds = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1); + dn.ids = m.ids_identity; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = m.Dm + r0 * N; + dn.ld_dst = N; + m.mmq_ctx->run(dn, m.cs); + return true; + } + const int q = (int) (j % DQ); + if (lay.native) { + // plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas + const auto& f = lay.fmt[(size_t) l]; + strata::kernels::iq_dequant_gu_f16(f.gu_type, blob_dev, blob_dev + f.up_off, f.n_ff, f.n_embd, + m.dq_gu[q], m.cs); + strata::kernels::iq_dequant_f16(f.d_type, blob_dev + f.down_off, f.n_embd * f.n_ff, m.dq_d[q], m.cs); + } else { + blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs); + } + if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); + const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e]; + pt.mark(kPfGemmGU, cs); + m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N); + swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs); + pt.mark(kPfGemmD, cs); + m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640); + return true; + }; + 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); + } + pt.mark(kPfCombine, cs); + moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs); + // debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values + if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { + cudaStreamSynchronize(m.cs); + auto bad = [&](const float* d, int64_t n) { + std::vector h((size_t) n); + cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost); + int64_t c = 0; + for (float v : h) c += !std::isfinite(v); + return c; + }; + const int64_t bgu = bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N), bbo = bad(m.bo, T * N); + const int64_t bh = m.H ? bad(m.H, T * K * 640) : -1; + static int64_t reported = -1; + if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) { + reported = stats_.chunks; + std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld " + "H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt, + order.size(), (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo, + (long long) T); + } + } + } + // ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else + // touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a + // control vector) + 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)); + const core::WeightRef* wnn = nullptr; + if (fuse) { + const core::LayerView vn(*m.wt, nl); + wnn = need(vn, half == 0 ? "hc_ffn_norm.weight" : "hc_attn_norm.weight", err); + if (!wnn) return false; + } + if (wnn) { + gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs, + m.xn16_lo); + normed = true; + } else { + gr_write(m.R, m.bo, m.inj, HC, T, m.cs); + } + if (half == 1 && strata::kernels::cvec().covers(l)) // --control-vector-scaled + strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); + } + } + if (issuer.joinable()) { + issuer.join(); + stats_.ms_experts_host += iss_ms; + stats_.experts_streamed += iss_streamed; + stats_.experts_dma += iss_dma; + } + stats_.tokens += T; + core::progress_at("reading the prompt (batched): finishing the chunk from token", p0); + pt.mark(kPfStart, cs); + if (next_ != nullptr) { + // the rows to the host buffer the next stage read two chunks ago (it has finished: waited below) + float* h = m.hand[hand_buf]; + if (cudaMemcpyAsync(h, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) != cudaSuccess || + cudaStreamSynchronize(m.cs) != cudaSuccess) { + err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + // this stage's state is at the chunk's end now (synced) and moves on with the next chunk below + if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false; + if (next_run.valid() && !next_run.get()) { err = next_err; return false; } + next_->hand_in_ = h; + next_run = std::async(std::launch::async, [this, tokens, c0, T, p0, &next_err] { + return next_->run(tokens + c0, T, p0, next_err); + }); + hand_buf ^= 1; + continue; // the last stage reports the chunk (on_chunk) + } + if (const char* dump = std::getenv("STRATA_PREFILL_DUMP_R")) { // debug: the final residuals, every 64th + cudaStreamSynchronize(m.cs); // position (A/B quality of this path) + if (std::FILE* f = std::fopen(dump, c0 == 0 ? "wb" : "ab")) { + std::vector row((size_t) D); + for (int64_t t = (64 - p0 % 64) % 64; t < T; t += 64) { + cudaMemcpy(row.data(), m.R + t * D, (size_t) D * 4, cudaMemcpyDeviceToHost); + const int64_t pos = p0 + t; + std::fwrite(&pos, sizeof pos, 1, f); + std::fwrite(row.data(), 4, row.size(), f); + } + std::fclose(f); + } + } + if (on_chunk || on_stage_chunk) { + const auto toc = Clock::now(); + if (cudaStreamSynchronize(m.cs) != cudaSuccess) { + err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + const auto toc2 = Clock::now(); + if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false; + if (on_chunk && !on_chunk(m.R, T, p0, err)) return false; + host_sync_ms += std::chrono::duration(toc2 - toc).count(); + host_chunk_ms += ms_since(toc2); + } + } + if (next_run.valid() && !next_run.get()) { err = next_err; return false; } + ss.ple_prev[0] = prev[0]; + ss.ple_prev[1] = prev[1]; + if (std::getenv("STRATA_DBG_NAN") != nullptr) { // debug: the state the prompt leaves for the token path + cudaStreamSynchronize(m.cs); + auto bad = [&](const float* d, int64_t n) { + std::vector h((size_t) n); + cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost); + int64_t c = 0; + double mx = 0; + for (float v : h) { c += !std::isfinite(v); if (std::isfinite(v)) mx = std::max(mx, (double) std::fabs(v)); } + std::fprintf(stderr, " %lld non-finite (max |x| %.3g)", (long long) c, mx); + }; + const int64_t last = (n - 1) % m.T; + std::fprintf(stderr, "strata dbg: prompt end: last residual row"); + bad(m.R + last * D, D); + if (ss.ple.ready()) { std::fprintf(stderr, "; PLE history"); bad(ss.ple.hist, (int64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM); } + std::fprintf(stderr, "; GDN state 0"); + bad(ss.gdn_state, 64 * 1024); + std::fprintf(stderr, "\n"); + } + if (cudaStreamSynchronize(m.cs) != cudaSuccess) { + err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + // (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request + if (const cudaError_t cst = cudaStreamSynchronize(m.copy); cst != cudaSuccess) { + err = std::string("prefill: expert copy stream: ") + cudaGetErrorString(cst); + return false; + } + stats_.ms_total += ms_since(t_start); + if (pt.on) { + pt.fold(); + double total = 0.0; + for (double v : pt.ms) total += v; + std::string line; + char b[96]; + for (int i = 0; i < kPfCount; ++i) { + if (pt.ms[i] <= 0.0) continue; + std::snprintf(b, sizeof b, " %s %.0f (%.1f%%)", kPfNames[i], pt.ms[i], total > 0 ? 100.0 * pt.ms[i] / total : 0.0); + line += b; + } + std::fprintf(stderr, "strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n", + (long long) n, total, ms_since(t_start), stats_.ms_experts_host, line.c_str()); + std::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, " + "waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, " + "PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple); + } + if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // debug: the GDN states as the prompt path leaves them + cudaStreamSynchronize(m.cs); + std::vector b((size_t) gdn_floats * 4); + std::string line; + char h[8]; + for (int64_t i = 0; i < ss.gdn_alloc; ++i) { + cudaMemcpy(b.data(), ss.gdn_state + (size_t) i * gdn_floats, b.size(), cudaMemcpyDeviceToHost); + uint64_t x = 1469598103934665603ull; + for (uint8_t c : b) x = (x ^ c) * 1099511628211ull; + std::snprintf(h, sizeof(h), "%04llx ", (unsigned long long) (x & 0xffff)); + line += h; + } + std::fprintf(stderr, "strata prefill: GDN_HASH %s\n", line.c_str()); + } + return true; +} + +} // namespace strata::prefill diff --git a/engine/strata/src/program/conv_cache_test.cpp b/engine/strata/src/program/conv_cache_test.cpp new file mode 100644 index 00000000..f4a0c2b7 --- /dev/null +++ b/engine/strata/src/program/conv_cache_test.cpp @@ -0,0 +1,67 @@ +// src/program/conv_cache_test.cpp - the conversation cache's retention policy: the shared root survives, +// the leaves rotate by least recent use. +// +// The scenarios, in the serve loop's terms (generate.cpp): checkpoints are a prefix chain - stamps[0] is +// the root, the deepest point every request so far has shared (the end of the system prompt, in practice). +// A stamp advances on creation, when a new checkpoint lands on an existing length, and when a request +// mounts through the checkpoint. +// +// 1. one conversation over its budget: the oldest leaf leaves - with fresh stamps in creation order this +// is exactly the previous first-in-first-out behaviour; +// 2. the root survives arbitrarily many newer checkpoints however old its stamp is; +// 3. a mount advances a checkpoint's stamp and the rotation then takes a different leaf; +// 4. a one-slot budget has no room for root and leaf, so the pin is off and the oldest leaves (the +// newest point stays, as before); +// 5. the policy is pure: the same stamps, the same victim. +#include "strata/program/conv_cache.hpp" + +#include +#include +#include + +using strata::program::conv_cache::eviction_victim; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +} // namespace + +int main() { + std::printf("conv_cache_test\n"); + { + const std::vector stamps = {1, 2, 3, 4, 5, 6, 7}; // chat A: root + six turns, one over + check(eviction_victim(stamps.data(), stamps.size(), 6) == 1, + "over budget with fresh stamps: the oldest leaf leaves (the FIFO it was)"); + } + { + // chat B mounts through the root long after it was created; its stamp stays ancient + const std::vector stamps = {1, 100, 101, 102, 103, 104, 105}; + const size_t v = eviction_victim(stamps.data(), stamps.size(), 6); + check(v == 1, "the root's stale stamp never makes it the victim"); + check(v != 0, "the root - the shared prefix - is never the victim"); + } + { + // the same chain after mounting checkpoint 1: its stamp jumps, the rotation moves to the next leaf + const std::vector stamped = {1, 8, 3, 4, 5, 6, 7}; + check(eviction_victim(stamped.data(), stamped.size(), 6) == 2, + "after a mount, the rotation takes the next least recently used leaf"); + } + { + const std::vector stamps = {1, 90, 91, 92}; + check(eviction_victim(stamps.data(), stamps.size(), 2) == 1, + "a two-slot budget keeps root + newest and drops the leaf in between"); + check(eviction_victim(stamps.data(), stamps.size(), 1) == 0, + "a one-slot budget has no pin: the oldest leaves, the newest point stays"); + } + { + const std::vector stamps = {7, 3, 3, 5}; + const size_t a = eviction_victim(stamps.data(), stamps.size(), 4); + const size_t b = eviction_victim(stamps.data(), stamps.size(), 4); + check(a == 1 && b == 1, "ties among equally stale leaves: the earlier index, deterministically"); + } + std::printf(g_fail ? "FAIL\n" : "PASS\n"); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/program/generate.cpp b/engine/strata/src/program/generate.cpp new file mode 100644 index 00000000..1e8cdfa3 --- /dev/null +++ b/engine/strata/src/program/generate.cpp @@ -0,0 +1,6668 @@ +// src/program/generate.cpp - P2.S6: `strata generate`. +// +// THE DRIVER, and the first program in this project that answers a question. Everything below it is a +// component; this is the thing that composes them into a token: +// +// embed_row(token) -> 48 captured layer graphs (the CPU expert pool behind the doorbell) -> +// lm_head(R) -> sample -> embed_row(next) -> ... +// +// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and `tools/strata_tokenizer.py` exist, +// and a C++ BPE is Phase 1's deliverable rather than this program's, so the prompt arrives as IDS via +// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, because C1 compares logits against +// llama.cpp on the SAME ids, and a tokenizer on only one side of that comparison is a second variable. +// +// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose +// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. + +#include "strata/core/device.hpp" +#include "strata/core/expert_cache.hpp" +#include "strata/core/conversation_snapshot.hpp" +#include "strata/core/conversation_memory.hpp" +#include "strata/core/coupled_draft.hpp" +#include "strata/core/expert_source.hpp" +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) +#include "kar_expert_miss.hpp" +#endif +#include "strata/core/pinned.hpp" +#include "strata/core/remote_experts.hpp" +#include "strata/core/on_device.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/layout.hpp" +#include "strata/core/session.hpp" +#include "strata/core/weights.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/pool.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/sampler.hpp" +#include "strata/kernels/verify_kernels.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_gdn.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/core/native_head.hpp" +#include "strata/core/verify.hpp" +#include "strata/core/mtp.hpp" +#include "strata/prefill/prefill.hpp" +#include "strata/core/native_dense.hpp" +#include "strata/core/keyless.hpp" +#include "strata/program/logits_selection.hpp" +#include "strata/program/conv_cache.hpp" +#include "strata/spec/draft_policy.hpp" +#include "strata/spec/suffix_drafter.hpp" +#include "strata/kernels/cvec.hpp" +#include "strata/core/progress.hpp" +#include "strata/core/device.hpp" +#include "strata/core/emulate.hpp" +#ifndef NOMINMAX +#define NOMINMAX // gguf_reader.hpp includes windows.h +#endif +#include "strata/artifact/gguf_reader.hpp" +#if defined(_WIN32) +#include +#include +#include +#else +#include +#include +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, +// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); +// a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). +bool under_wddm() { +#ifdef _WIN32 + return true; +#else + static const bool dxg = std::filesystem::exists("/dev/dxg"); + return dxg; +#endif +} + +// perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each +bool refill_blocking() { + static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; + return v; +} + +using Clock = std::chrono::steady_clock; + +// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only +// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so +// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves +// them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap +// reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go +// on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the +// GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued. +template +bool resident_stage_swaps(strata::core::FileExpertSource& src, strata::core::ExpertCache& cache, + const std::vector& host_res, int64_t n_expert, std::vector& swaps, + cudaStream_t stream) { + if (!src.complement_ready() || swaps.empty()) return true; + struct Staged { int32_t layer, in, out; int64_t q; }; + std::vector staged; + std::vector kept; + kept.reserve(swaps.size()); + for (const Swap& s : swaps) { + if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; } + const int64_t q = (int64_t) staged.size(); + if (q >= src.exchange_capacity()) continue; + const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out]; + if (slot < 0) continue; + if (cudaMemcpyAsync(src.exchange_buffer(q), cache.device_slot(slot), + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, + stream) != cudaSuccess) + return false; + staged.push_back({s.layer, s.in, s.out, q}); + kept.push_back(s); + } + if (!staged.empty()) { + if (cudaStreamSynchronize(stream) != cudaSuccess) return false; + for (const Staged& x : staged) + if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false; + } + swaps.swap(kept); + return true; +} + +struct Options { + std::string pack = "pack/full"; + std::vector tokens; // the prompt, PRE-TOKENIZED + int64_t max_new = 16; + int64_t max_context = 4096; + bool greedy = true; + uint64_t seed = 0; + int top_k = 20; + float top_p = 0.95f; + float temperature = 1.0f; + std::string dump_logits; // one line of logits per generated position + int64_t logits_stride = 1; // storage selection; all prompt tokens remain conditioned + /// **THE RESIDUAL, SO THE HEAD CAN BE CHECKED WITHOUT THE LAYERS.** + /// + /// C1 fails (LEDGER L116) and the pipeline is `embed -> 48 layers -> head`. Dumping `R` splits it in half: + /// the head is one norm, two bf16 projections and one 794 MB GEMV, all of which can be recomputed in Python + /// from the manifest. If Python agrees with the engine on the same `R`, the head is right and the layers + /// are wrong; if it disagrees, the head is wrong. Nothing else in the engine can be split that cheaply. + std::string ple_gguf; // the ORIGINAL second GGUF shard: the PLE table is not in the pack + bool no_ple = false; // explicit diagnostic ablation; never a normal inference default + bool stream_token = false; // R2.6 experiment: ordered work on the session stream + bool check_logits = false; // optional full-vocabulary finite scan + bool gr_fp32_activations = false; // pinned CUDA single-token BF16 activation contract + bool gr_native_mmvf = false; // pinned projection reduction tree as well as FP32 inputs + bool native_bf16 = false; // SSM gates, router and indexer projections only + bool native_bf16_extra = false; // PLE value and shared expert scalar gate + bool native_ple_key = false; // unchanged Q2_0 key and CUDA Q8_1 activations + bool native_moe_combine = false; // pinned fused CUDA weighted reduction + bool native_gdn = false; // pinned CUDA recurrence and preprocessing + bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256 + bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling + bool native_qsa = false; // pinned F32 QSA norms and gate + /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, + /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is + /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two + /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - + /// `none` and `1` are explicit values (the opt-outs), the absent flag is not. + std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent + double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) + double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) + double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale + double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 + double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) + double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F + double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F + double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F + bool native_rope = false; // pinned text-only CUDA rotary arithmetic + bool native_ple_postops = false; // pinned PLE postprojection arithmetic + bool native_router = false; // pinned fused 512-expert top-10 router + bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages + std::string native_head_gguf; // native output.weight experiment; same model shard as the pack + std::vector native_dense_gguf; // repeat for native GDN/QSA projection shards + /// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an + /// error) and of --native-head-gguf's (the same list unless that names another model). + std::vector native_shards, native_head_shards; + /// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the + /// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the + /// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. + std::string native_preset; + /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) + std::string embd_gguf; + /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. + std::string ple_io = "direct"; + std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native + uint32_t ple_kar_level = 2; + uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather + int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables + int ple_inflight = 64; + double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this + bool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O worker + std::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM) + int64_t kv_resident = 0; ///< KV streaming: resident cells per QSA layer (0: all in VRAM) + std::string dump_residual; + /// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two + /// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not. + std::string dump_mixed; + /// One residual snapshot per layer per position: `n_layers * hc * n_embd` floats per position, appended in + /// position order. This is the C1 BISECTION LADDER - it is what `llama-debug --tensor-filter l_last` prints + /// for the reference, so the first layer whose `sum` diverges is the layer that holds the bug. It needs the + /// captured path (the expert pool only exists there), so it is refused with `--no-capture`. + std::string dump_layers; + /// `2 * n_embd + 2 * hc` floats per layer per position: the attention half's block output, the MoE half's, + /// and the two injection vectors. It separates `linear_attn_out-` from `ffn_out-`, which the residual + /// ladder cannot. **CAPTURED INTO THE LAYER GRAPHS**, so it must be armed before `session_capture`. + std::string dump_halves; + /// P0.S8's routing trace, and a prerequisite the Phase 3 plan names explicitly. One record per layer per + /// position: `int32 layer, int32 k, k int32 ids, k float weights`. It is what a hit-rate curve for a + /// candidate VRAM expert cache is computed from, and it needs no new kernels - the doorbell already + /// publishes exactly this much to pinned memory. + std::string dump_routing; + bool no_capture = false; // run the layers directly instead of replaying graphs + bool no_pool = false; // skip the CPU expert pool: the GPU-only floor + bool sync_every_layer = false; + /// Per-stage CUDA-event timings inside the layer halves. `--no-capture` only: an event recorded inside a + /// stream capture is silently dropped, so the captured path cannot carry this. + bool stage_timing = false; + /// Launch the 48 captured `pre` graphs back to back with no host work between them and report the pure GPU + /// time per token. This is the only measurement that separates host-bound from GPU-bound, because the + /// stage events include every gap where the GPU waited for the host. + bool graph_only = false; + bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor + int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides + /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in + strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All; + /// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the + /// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core + /// is reserved for a host thread that has nothing to do while the drain runs. + bool no_host_worker = false; + bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling + bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile + std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes + bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM + /// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy + /// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap + /// (with a warning) when even the experts no slot holds do not fit. + bool resident_pin = false; + uint64_t resident_headroom = 8ull << 30; + bool resident_soft = false; + bool resident_cpu_explicit = false; ///< #384: --resident-cpu-experts given by itself (not only implied) + /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does + /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place + /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts). + uint64_t resident_budget = 0; + /// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** + /// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no + /// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and + /// saves nothing". The kernel exists (`src/kernels/cuda/s2_expert_grouped.cu`), it is wired at line ~660 + /// via `expert_hit_run`, and switching the cache on **does** move work off the CPU pool: the drain fell + /// **19.076 -> 10.312 ms/token** at 4096 per-layer slots, for **-2.7 ms/token** end to end. What was + /// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier + /// measurement found nothing - see `expert_cache_per_layer`. + int expert_cache = 0; + std::array expert_cache_remote{}; ///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP + std::string expert_cache_remote_placement = "stripe"; ///< stripe experts or assign complete layers to CUDA1..3 + bool expert_cache_cpu_order = false; + /// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.** + /// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the + /// first `n_slots` distinct pairs - about 26 LAYERS OF POSITION 0 - take every slot and hits are confined + /// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and + /// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default. + bool expert_cache_per_layer = false; + /// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen + /// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`. + bool no_ple_prefetch = false; + /// R4.2e: a `profile.bin` from `tools/make_profile.py`. **When given, it decides residency instead of the + /// compulsory-miss policy**, which is the whole point: a profile ranked by routing frequency over a whole + /// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills + /// with whatever the prompt touched FIRST. Empty means no profile. + std::string expert_profile; + /// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken. + /// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The + /// A/B arm is `--no-hit-poke`. + bool no_hit_poke = false; + /// R0.9: capture each layer as THREE graphs and time them from outside the capture, which is the only + /// valid way to get a per-stage table on the real graph. Prints and exits; it is a measurement, not a run. + bool gpu_stages = false; + bool stats = false; + bool shared_late = false; ///< plan v0.3 P3 A/B: shared expert inside post[l] (old order) + bool keep_canonical = false; ///< plan v0.3 P1 A/B: load canonical copies of natively served tensors + bool no_token_graph = false; ///< plan v0.3 P3 A/B: two graphs per layer instead of one per token + bool no_fused_gr = false; ///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write + bool no_fast_attn = false; ///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention + bool no_publish_kernel = false; ///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step + bool no_fused_gdn = false; ///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm + bool no_fast_select = false; ///< plan v0.3 P7 A/B: FP64 row scores + bit-serial cell top-k + /// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session + /// and the KV state, minus this reserve for the graphs, the hit scratch and the head. + int vram_reserve_mib = 700; + /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). + int64_t prefill_chunk = 0; + /// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk + /// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). + bool prefill_auto = false; + /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or + /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context + int64_t prefill_auto_max = 8192; + bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread + /// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after + /// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. + bool no_prefill_borrow = false; + /// Plan v0.3 P5 validation: batch only positions [0, P) and run the rest of the prompt through the token path + /// (teacher-forced), so the logits of positions >= P - which depend on the batched state - can be scored + /// against the oracle at many positions. 0 = the whole prompt but the last position. + int64_t prefill_until = 0; + /// Plan v0.3 P6: after every processed position, append the residual after the last layer (hc x n_embd + /// floats, the MTP draft head's input) to this file. Token path only. + std::string dump_final_r; + /// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and + /// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for + /// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token. + int spec = 0; + std::string spec_oracle; + int spec_corrupt = 0; + /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. + std::string mtp; + int64_t mtp_window = 32768; ///< the draft layer attends to the last N cells (0 = every cell) + /// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the + /// pinned arena while the CPU computes the rest (verify windows). + double pcie_frac = -1.0; ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) + std::string pcie_mode = "auto"; ///< auto | dma | kernel | direct + /// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into + /// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. + int adapt_every = 4; + /// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least + /// this probability under the draft layer; 0 = always --spec-1 drafts. + double spec_min_p = 0.0; + /// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids). + bool stop_eos = false; + std::vector eos_ids = {248044, 248046}; + bool spec_split = false; ///< opt-in split verify window (the overlap study: exact, ~7% slower) + /// --serve, multi-GPU layer split: "K" or "K1,K2,.." (the first layer of each later stage) or "auto" (placed + /// from each GPU's free VRAM); empty = one GPU + std::string layer_split; + /// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this + /// GPU, sharing everything - the bit-exact A/B of the hand-off) + std::string split_device; + /// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with + /// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV), + /// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K) + bool split_skip_if_fits = false; + /// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main). + bool serve = false; + /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. + bool vision = false; + int adapt_swaps = 96; + /// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole + /// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and + /// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is. + int prompt_cache = 6; + int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations + int conversation_cache_slots = 4; + int64_t conversation_cache_min_free_mib = 2560; + /// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) + int64_t prompt_cache_every = 16384; + /// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system + /// prompt, which every chat of the same client shares - when that is at least N tokens (0 = never) + int64_t prompt_cache_root = 2048; + /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's + /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. + int64_t turn_token = 248045; + /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool + /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always + /// the batched path) + int64_t short_read = 64; + /// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code + /// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed + /// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to + /// pay (strata/spec/draft_policy.hpp). On by default; 0 = MTP only. + int suffix_draft = 3; + /// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. + int mtp_max_t = 0; + /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the + /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range + /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. + std::vector> cvec_files; + int cvec_first = -1, cvec_last = -1; ///< llama.cpp's defaults: 1 .. the last layer + int cvec_mode = 1; ///< 0 = project, 1 = add (llama.cpp's default) + int cvec_single = -1; ///< --cvec-dir single:L (project mode): layer L's direction everywhere +}; + +void usage() { + std::fprintf(stderr, + "strata generate --pack DIR --tokens \"1,2,3\" [options]\n" + "\n" + " --pack DIR the pack directory (default pack/full)\n" + " --tokens LIST the prompt as comma-separated token IDS (required)\n" + " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" + " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" + " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" + " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n" + " --no-ple explicit diagnostic ablation of the PLE layer\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" + " ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n" + " --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" + " --ple-inflight N outstanding SSD reads (default 64)\n" + " --ple-delay-us U fault injection: each row read completes no earlier than U us\n" + " --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n" + " --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n" + " VRAM; default fp16 until gate G-C accepts int8\n" + " --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n" + " slightly lower precision (see bench/results/2026-09-27-kv-q4)\n" + " --kv k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n" + " (vs int8's 1,056); not with --kv-resident\n" + " --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n" + " whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n" + " all of it in VRAM. A context of N cells or fewer is not streamed\n" + " --stream-token enqueue token work on the session stream (experimental)\n" + " --check-logits copy and check all logits in the stream-token path\n" + " --gr-fp32-activations experimental CUDA-oracle GR activation precision\n" + " --gr-native-mmvf experimental pinned GR norm/projections; implies FP32 activations\n" + " --native-bf16 experimental CUDA-oracle SSM/router/indexer BF16 projections\n" + " --native-bf16-extra experimental CUDA-oracle PLE/shared gate BF16 projections\n" + " --native-ple-key experimental native PLE key; requires --native-dense-gguf\n" + " --native-moe-combine experimental pinned CUDA routed/shared combination\n" + " --native-gdn experimental pinned CUDA GDN norms/gates/recurrence\n" + " --native-flash-attn-short diagnostic pinned vector attention; --max-context <=256\n" + " --native-qsa-indexer experimental pinned indexer key cache and pooling\n" + " --native-qsa experimental pinned QSA normalization and output gate\n" + " --native-rope experimental pinned text-only CUDA rotary arithmetic\n" + " --native-ple-postops experimental pinned PLE postprojection arithmetic\n" + " --native-router experimental pinned CUDA 512-expert top-10 routing\n" + " --cpu-oracle-q8-0 experimental pinned CPU expert quantization and dot reduction\n" + " --native SHARD1 every full-context native path at once (plan v0.3 P1): stream-token,\n" + " GR MMVF, BF16, head, dense + PLE key, MoE combine, GDN, router, QSA,\n" + " indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" + " expert cache is on. Individual --native-* flags stay for A/B.\n" + " --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" + " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" + " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" + " --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" + " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" + " --max-new N tokens to generate (default 16)\n" + " --max-context N KV/state capacity (default 4096)\n" + " --rope-scaling T extend the context past the trained one: none, linear\n" + " (position interpolation) or yarn - llama.cpp's types and names.\n" + " Default: the model file's rope keys, else none. Fixed at startup:\n" + " K in the cache is post-RoPE, so one run one scaling\n" + " --rope-scale F the extension factor for linear/yarn (default: the model file's\n" + " factor, else 1 = off)\n" + " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" + " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" + " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" + " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" + " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" + " --greedy argmax (the default)\n" + " --seed S enable sampling with this Philox seed\n" + " --top-k N --top-p F --temperature F\n" + " --dump-logits PATH write one line of raw logits per position\n" + " --logits-stride N store every Nth row plus final input (default 1); N>1 requires --max-new 1\n" + " --dump-residual PATH write the final R (hc x n_embd, f32) for head bisection\n" + " --dump-layers PATH write R after EVERY layer, per position: the C1 bisection ladder\n" + " --dump-halves PATH write both halves' block_out and inject per layer: the half bisection\n" + " --dump-routing PATH write the routed expert ids and weights per layer per position (P0.S8)\n" + " --no-capture run the layers directly instead of replaying graphs\n" + " --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" + " --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" + " --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" + " --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" + " of RAM each; 0 = read every prompt from the start)\n" + " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n" + " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" + " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" + " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" + " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" + " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" + " of the batched prompt path (default 64, 0 = off)\n" + " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" + " when it pays (default 3; 0 = MTP only)\n" + " --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" + " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" + " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" + " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" + " --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n" + " --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n" + " --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" + " --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" + " --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" + " the largest chunk up to 8192 whose buffers the expert cache can lend;\n" + " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" + " --no-pool skip the CPU expert pool (the GPU-only floor)\n" + " --sync-every-layer debug: synchronise after every layer\n" + " --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" + " which changes every number downstream - pass it for any real run\n" + " --dump-mixed PATH write the post-attention residual (n_embd, f32)\n" + " --stage-timing per-stage KERNEL-COUNT shares. NOT a time profile: an uncaptured\n" + " event interval includes host gaps, so run with --gpu-only-full first\n" + " --graph-only MEASURE: replay the 48 `pre` graphs only. OMITS the 48 `post` graphs\n" + " and the LM head, so it is NOT the GPU floor (R0.3, Memory/ERRORS.md A4)\n" + " --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n" + " THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n" + " --stats print the per-stage breakdown\n" + " --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n" + " and time them from OUTSIDE the capture. The per-stage table on the\n" + " real graph that --stage-timing cannot give. Prints and exits.\n" + " --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n" + " tools/make_profile.py) instead of admitting on first use.\n" + " --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n" + " launch so the GPU starts while the CPU pool runs; without it the work\n" + " waits for the next driver entry and does not overlap at all.\n" + " --no-ple-prefetch A/B arm: read the PLE table's sixteen rows one at a time, instead of\n" + " issuing them in one PrefetchVirtualMemory call.\n" + " --expert-cache N R4: keep N expert blobs resident in VRAM and compute their rows on the\n" + " GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n" + " with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n" + " ms/token, -2.7 ms/token end to end.\n" + " --expert-cache-device1 N pre-fill N experts on CUDA1 (experimental)\n" + " --expert-cache-device2 N pre-fill N more experts on CUDA2\n" + " --expert-cache-device3 N pre-fill N more experts on CUDA3\n" + " --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n" + " layers across CUDA1..3 (default: stripe)\n" + " --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n" + " position take all of them. The default policy fills in arrival order\n" + " from one shared counter, so 256 slots went to ~26 layers of position 0\n" + " and measured **2.97%%**. Per-layer, the same routing gives 21.4%% at 8\n" + " slots/layer and 70.4%% at 64.\n" + " --no-host-worker R2.2: the A/B arm. By default the HOST THREAD joins the drain, so the\n" + " pool is six threads on six cores instead of five plus an idle core;\n" + " this flag restores the five-worker form for comparison on `pool phases`.\n" + " --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" + " except the one the host loop spins on (with --pool-affinity auto or\n" + " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" + " deviation from `cpu_s2` is attributed.\n" + " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" + " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" + " then E-cores) or p-cores (P-cores and their siblings only).\n" + " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" + " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" + " --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" + " The A/B arm: the mmap's rate depends on the OS page cache holding\n" + " 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" + " --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n" + " Put this file on /dev/shm, not ordinary SSD storage.\n" + " A small header binds an existing backing file to the same pack.\n" + " --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n" + " hold resident in ordinary RAM (and the prompt path's lend region as far as\n" + " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" + " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" + " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" + " does not fit. Same answers as --mmap-experts for the same placement.\n"); +} + +bool parse_i64_list(const char* s, std::vector& out, std::string& err) { + out.clear(); + std::string text(s); + for (char& c : text) if (c == ',') c = ' '; + std::istringstream input(text); + std::string token; + while (input >> token) { + int32_t id = 0; + const auto parsed = std::from_chars(token.data(), token.data() + token.size(), id); + if (parsed.ec != std::errc{} || parsed.ptr != token.data() + token.size() || id < 0) { + err = "invalid token id: expected an integer in [0, 2147483647]"; + out.clear(); + return false; + } + out.push_back(id); + } + if (out.empty()) { err = "token list was empty"; return false; } + return true; +} + +/// The pool's adapter plus the wall-clock it spent, so the report can say how much of the token was the CPU. +struct Drive { + strata::core::ExpertDispatch d; + double cpu_ms = 0; + int64_t calls = 0; + /// THE ROUTING TRACE, which is P0.S8 and a stated prerequisite of Phase 3. `drive_pool` is called once + /// per layer from the main loop - the workers live inside `expert_pool_dispatch` - so a single FILE* here + /// needs no locking. `d.layers` is the CURRENT layer on entry (the adapter increments it as it walks the + /// blob), which is why the layer index comes from there rather than from a counter of our own. + std::FILE* routing = nullptr; +}; + +void drive_pool(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd, int64_t k, + float* out) { + Drive* t = (Drive*) user; + const Clock::time_point a = Clock::now(); + strata::core::expert_pool_dispatch(&t->d, x_f, ids, weights, n_embd, k, out); + t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); + ++t->calls; + // THE ROUTING TRACE. Written AFTER the dispatch so the layer index is still this layer's: `d.layers` is + // advanced by the adapter as it consumes the blob, and reading it after the call is the same value the + // dispatch used. Record = int32 layer, int32 k, k int32 ids, k float weights. + if (t->routing != nullptr) { + // **`d.layers` HAS ALREADY BEEN ADVANCED BY THE TIME THIS RUNS, AND THE FIRST TRACE WAS OFF BY ONE + // BECAUSE OF IT.** The adapter walks the blob by incrementing `d.layers` as it consumes each layer's + // experts, so after the dispatch it holds the NEXT layer's index. `tools/make_profile.py` caught it + // with a bounds check when the trace turned out to span 1..48 instead of 0..47. The hit-rate CURVE was + // unaffected - it is a per-layer split, and shifting every layer by one preserves both metrics - but + // anything keyed on the layer index, which is exactly what a cache profile is, would have been wrong. + const int32_t layer_idx = (int32_t) (t->d.layers - 1); + if (layer_idx < 0 || layer_idx >= 48) { + std::fprintf(stderr, "strata generate: the routing trace saw layer %d, outside 0..47\n", layer_idx); + return; + } + const int32_t rec[2] = {layer_idx, (int32_t) k}; + std::fwrite(rec, sizeof rec, 1, t->routing); + std::fwrite(ids, sizeof(int32_t), (size_t) k, t->routing); + std::fwrite(weights, sizeof(float), (size_t) k, t->routing); + } +} + +/// Plan v0.3 P6: the pool for a verify window. +void drive_pool_multi(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, + int64_t layer) { + Drive* t = (Drive*) user; + t->d.layers = layer; + const Clock::time_point a = Clock::now(); + strata::core::expert_pool_dispatch_multi(t->d, x_f, ids, n_tok, k, out); + t->cpu_ms += std::chrono::duration(Clock::now() - a).count(); + ++t->calls; + // the routing trace for the serve path: the same record format drive_pool writes (layer, k, ids, weights), + // one record per token. The multi dispatch fuses the router weights into the kernel and does not surface + // them, so records carry unit weights: tools/make_profile.py ranks pairs by routed frequency, which is the + // signal that matters; a one-shot --dump-routing run records true weights if a weighted ranking is wanted. + if (t->routing != nullptr && layer >= 0 && layer < 48) { + for (int64_t tok = 0; tok < n_tok; ++tok) { + const int32_t rec[2] = {(int32_t) layer, (int32_t) k}; + std::fwrite(rec, sizeof rec, 1, t->routing); + std::fwrite(ids + tok * k, sizeof(int32_t), (size_t) k, t->routing); + static const float one[64] = {}; // k <= 64 in a verify window; zeros read as unit weights + std::fwrite(one, sizeof(float), (size_t) k, t->routing); + } + } +} + +/// Layer split: every verify stage shares one Drive (its counters, usage and failure flags); the GPU plan, the expert +/// cache and the PCIe share the pool uses for a layer are those of the stage that runs it. +struct SplitDrive { + static constexpr int kMax = 8; + Drive* base = nullptr; + int n = 0; ///< stages + int64_t end[kMax] = {}; ///< stage i runs the layers from end[i - 1] (0) below end[i] + strata::core::GpuPlanSink* plan[kMax] = {}; + const uint8_t* cache_base[kMax] = {}; + const uint64_t* cache_slot_off[kMax] = {}; + int pcie_num[kMax] = {}; +}; +void drive_pool_split(void* user, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k, float* out, + int64_t layer) { + SplitDrive* s = (SplitDrive*) user; + int st = 0; + while (st + 1 < s->n && layer >= s->end[st]) ++st; + Drive& d = *s->base; + d.d.plan = s->plan[st]; + d.d.cache_base = s->cache_base[st]; + d.d.cache_slot_off = s->cache_slot_off[st]; + d.d.pcie_num = s->pcie_num[st]; + drive_pool_multi(s->base, x_f, ids, n_tok, k, out, layer); +} + +/// Layer split across GPUs: a later stage on its own device, with its own copy of the dense weights, a session, an +/// expert cache for its layers, a verify window and a prompt path; the last one also holds the head (the drafter +/// lives on its device too). +struct GpuStage { + int dev = 0; + int64_t lb = 0, le = 0; + double pcie_frac = 0.0; + strata::core::WeightTable wt; + strata::core::NativeDense dense; + strata::core::NativeHead head; + strata::core::SessionState ss; + cudaStream_t stream = nullptr; + strata::core::ExpertCache cache; + std::vector> profile; ///< its layers' share of the profile, hottest first + int32_t* d_res = nullptr; ///< the residency table on its device + strata::core::Verifier ver; + strata::prefill::Prefill sp; + cudaStream_t adapt_stream = nullptr; + cudaEvent_t adapt_ev = nullptr; + bool adapt_live = false; ///< swaps of this request are in flight on it + int32_t* mrope = nullptr; ///< --vision: the image-position table on its device +}; + +// ---- issue #31: what the watchdog prints before it stops a stalled engine +struct MemSample { + unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows) +}; +MemSample mem_sample() { + MemSample m; +#if defined(_WIN32) + PROCESS_MEMORY_COUNTERS pmc{}; + if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) { + m.faults = pmc.PageFaultCount; + m.rss_mib = pmc.WorkingSetSize >> 20; + m.commit_mib = pmc.PagefileUsage >> 20; + } + MEMORYSTATUSEX ms{}; + ms.dwLength = sizeof ms; + if (GlobalMemoryStatusEx(&ms)) m.avail_mib = ms.ullAvailPhys >> 20; +#else + if (std::FILE* f = std::fopen("/proc/self/stat", "r")) { + char buf[4096]; + const size_t n = std::fread(buf, 1, sizeof buf - 1, f); + buf[n] = 0; + std::fclose(f); + const char* s = std::strrchr(buf, ')'); // fields after the command name: 3 state ... 12 majflt + for (int field = 2; s && field < 12; ++field) s = std::strchr(s + 1, ' '); + if (s) m.faults = std::strtoull(s + 1, nullptr, 10); + } + auto kb = [](const char* path, const char* key) -> unsigned long long { + unsigned long long v = 0; + if (std::FILE* f = std::fopen(path, "r")) { + char line[256]; + const size_t kl = std::strlen(key); + while (std::fgets(line, sizeof line, f)) + if (std::strncmp(line, key, kl) == 0) { v = std::strtoull(line + kl, nullptr, 10); break; } + std::fclose(f); + } + return v; + }; + m.rss_mib = kb("/proc/self/status", "VmRSS:") >> 10; + m.commit_mib = kb("/proc/self/status", "VmSwap:") >> 10; + m.avail_mib = kb("/proc/meminfo", "MemAvailable:") >> 10; +#endif + return m; +} + +// the stage the watchdog names: " ", and the prompt chunk a batched read is in (#251) +std::string stage_text() { + const strata::core::Progress& p = strata::core::progress(); + std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load()); + if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c); + return s; +} + +void stall_report(std::FILE* f, uint64_t layers_during) { + strata::core::Progress& p = strata::core::progress(); + std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " + "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(), + (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000), + (unsigned long long) layers_during); + for (int pass = 0; pass < 2; ++pass) { + if (pass == 1) { + std::this_thread::sleep_for(std::chrono::seconds(2)); + std::fprintf(f, " 2 s later:\n"); + } + if (auto fn = strata::core::diag_pool_fn().load()) fn(f); + if (auto fn = strata::core::diag_verify_fn().load()) fn(f); + const MemSample m = mem_sample(); + std::fprintf(f, " memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n", m.rss_mib, + m.commit_mib, +#if defined(_WIN32) + "committed", m.avail_mib, m.faults, "page faults so far" +#else + "in swap", m.avail_mib, m.faults, "major page faults so far" +#endif + ); + std::fflush(f); + } +#if defined(_WIN32) + // every thread's stack, to read against this build's PDB: a few MB beside the engine's working directory + if (HMODULE dbg = LoadLibraryA("dbghelp.dll")) { + using Fn = BOOL(WINAPI*)(HANDLE, DWORD, HANDLE, int, void*, void*, void*); + if (auto write = (Fn) GetProcAddress(dbg, "MiniDumpWriteDump")) { + char path[64]; + std::snprintf(path, sizeof path, "strata-stall-%lu.dmp", (unsigned long) GetCurrentProcessId()); + HANDLE h = CreateFileA(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h != INVALID_HANDLE_VALUE) { + const int kThreadInfo = 0x1000; // MiniDumpWithThreadInfo; MiniDumpNormal = 0 + const BOOL ok = write(GetCurrentProcess(), GetCurrentProcessId(), h, kThreadInfo, nullptr, nullptr, nullptr); + CloseHandle(h); + char full[MAX_PATH]; + if (!GetFullPathNameA(path, MAX_PATH, full, nullptr)) std::snprintf(full, sizeof full, "%s", path); + std::fprintf(f, " %s the thread stacks to %s (attach it to the issue)\n", ok ? "wrote" : "could not write", + full); + } + } + } +#endif +} + +/// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) +void mem_mark(const char* where) { + static const bool on = std::getenv("STRATA_TRACE") != nullptr; + if (!on) return; + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + std::fprintf(stderr, "strata trace: %lld MiB free after %s\n", (long long) (free_b >> 20), where); +} + +int argmax(const std::vector& v) { + int best = 0; + for (size_t i = 1; i < v.size(); ++i) + if (v[i] > v[best]) best = (int) i; + return best; +} + +// ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and +// reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in +// two, and only one half needs copying: +// * POSITIONAL state - the KV cache of the 12 QSA layers and their pooled indexer keys, the draft layer's KV. A +// cell is written once for its position and read only by later positions (the block scores take `dead` for the +// block being filled, never its pooled row), so rewinding to a position just means writing from there again. +// * RUNNING state - the 36 GDN recurrences and conv histories, each QSA layer's indexer tail (the unfinished +// block's raw keys) and the PLE's normalized history. Each describes "everything so far" and cannot be +// rewound, so a checkpoint is a copy of exactly these: ~118 MB, the same set the verifier snapshots to roll +// back rejected drafts. +// A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps +// just the checkpoints that are prefixes of the tokens the session holds now. +using ImgKey = strata::core::ConversationImageKey; +using ConvCheckpoint = strata::core::ConversationCheckpoint; + +uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) { + const uint8_t* p = (const uint8_t*) data; + for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ull; } + return h; +} + +using ConvStateSizes = strata::core::ConversationStateSizes; + +ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g, const strata::core::SessionState& ss) { + ConvStateSizes z; + std::string error; + // a split stage's session owns only its layer range's state (see SessionState's carve note); the geometry + // and the carve have already passed engine validation + strata::core::conversation_session_sizes(g, ss, z, error); + return z; +} + +/// Copies the running state out (this session's carve only). The caller has synchronized the device. +bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { + std::string error; + if (strata::core::conversation_checkpoint_save(c, ss, g, error)) return true; + std::fprintf(stderr, "strata serve: checkpoint save: %s\n", error.c_str()); // the caller's ERR has no reason + return false; +} + +/// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. +bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) { + std::string error; + if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true; + std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str()); + return false; +} + +// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.` times its scale, +// summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit +// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports. +bool load_control_vectors(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err) { + const int64_t L = g.n_layers, N = g.n_embd; + std::vector data((size_t) (L * N), 0.0f); + std::vector have((size_t) L, false); + for (const auto& [path, scale] : o.cvec_files) { + try { + strata::GgufFile f(path); + const strata::MetaValue* arch = f.get("general.architecture"); + if (arch == nullptr || arch->s != "controlvector") { + err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')"; + return false; + } + const strata::MetaValue* hint = f.get("controlvector.model_hint"); + if (hint != nullptr && hint->s != "qwen4exp") + std::fprintf(stderr, "strata generate: %s was made for '%s', not qwen4exp\n", path.c_str(), hint->s.c_str()); + int found = 0; + for (const strata::TensorInfo& t : f.tensors()) { + if (t.name.rfind("direction.", 0) != 0) continue; + const long l = std::strtol(t.name.c_str() + 10, nullptr, 10); + if (l < 1 || l >= L) continue; // layer 0 has no vector; past the model is ignored, as in llama.cpp + if (t.type != 0 || t.elements() != (uint64_t) N) { + err = path + ": " + t.name + " must be " + std::to_string((long long) N) + " f32"; + return false; + } + const float* src = reinterpret_cast(f.tensor_data(t)); + for (int64_t j = 0; j < N; ++j) data[(size_t) (l * N + j)] += scale * src[j]; + have[(size_t) l] = true; + ++found; + } + if (found == 0) { err = path + ": no direction. tensors"; return false; } + } catch (const std::exception& e) { + err = e.what(); + return false; + } + } + const int first = o.cvec_first <= 0 ? 1 : o.cvec_first; + const int last = (o.cvec_last <= 0 || o.cvec_last >= L) ? (int) L - 1 : o.cvec_last; + const int single = o.cvec_mode == 0 ? o.cvec_single : -1; + if (single >= 0 && (single >= L || !have[(size_t) single])) { + err = "--cvec-dir single:" + std::to_string(single) + ": the vector has no direction for that layer"; + return false; + } + std::vector dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f); + int steered = 0; + for (int64_t l = first; l <= last; ++l) { + const int64_t src = single >= 0 ? single : l; + if (!have[(size_t) src]) continue; + const float* d = data.data() + (size_t) (src * N); + if (o.cvec_mode == 0) { + double nrm = 0.0; + for (int64_t j = 0; j < N; ++j) nrm += (double) d[j] * d[j]; + nrm = std::sqrt(nrm); + if (nrm <= 0.0) continue; + s[(size_t) l] = (float) nrm; + for (int64_t j = 0; j < N; ++j) dir[(size_t) (l * N + j)] = (float) (d[j] / nrm); + } else { + s[(size_t) l] = 1.0f; + std::copy(d, d + N, dir.begin() + (size_t) (l * N)); + } + ++steered; + } + if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; } + if (!strata::kernels::cvec_upload(dir, s, o.cvec_mode, first, last, N, g.hc, err)) return false; + summary = std::string(o.cvec_mode == 0 ? "project" : "add") + ":" + std::to_string(first) + "-" + std::to_string(last) + + (single >= 0 ? ":single" + std::to_string(single) : ""); + // the line llama.cpp's patched build prints, so a log shows the same thing + std::fprintf(stderr, "strata generate: control vector mode = %s, dir = %s, layers %d..%d (%d steered)\n", + o.cvec_mode == 0 ? "project" : "add", single >= 0 ? "single" : "per-layer", first, last, steered); + return true; +} + +// The effective host->device bandwidth of the PCIe link: copies from pinned host memory, as the expert arena's +// reads are. The native default share (0.55) was measured on x16 links (~26-28 GB/s); a x8 card in a x8 slot +// carries about half of that. Returns < 0 when the probe cannot run (then the caller keeps the default). +double probe_pcie_h2d_gbps() { + constexpr size_t kBytes = 256ull << 20; + constexpr int kIters = 4; + void* h = nullptr; + void* d = nullptr; + cudaEvent_t ev0, ev1; + if (cudaMallocHost(&h, kBytes) != cudaSuccess) return -1.0; + if (cudaMalloc(&d, kBytes) != cudaSuccess || cudaEventCreate(&ev0) != cudaSuccess || + cudaEventCreate(&ev1) != cudaSuccess) { + if (d != nullptr) cudaFree(d); + cudaFreeHost(h); + return -1.0; + } + std::memset(h, 0, kBytes); // fault the pages in before timing + cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); // warmup: context up, copy engine primed + cudaEventRecord(ev0); + for (int i = 0; i < kIters; ++i) cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice); + cudaEventRecord(ev1); + const bool ok = cudaEventSynchronize(ev1) == cudaSuccess; + float ms = 0.f; + const bool timed = ok && cudaEventElapsedTime(&ms, ev0, ev1) == cudaSuccess && ms > 0.01f; + const double bw = timed ? ((double) kIters * (double) kBytes / (ms * 1e-3)) / 1e9 : -1.0; + cudaEventDestroy(ev0); + cudaEventDestroy(ev1); + cudaFree(d); + cudaFreeHost(h); + return bw; +} + +} // namespace + +int main(int argc, char** argv) { + // **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a + // pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which + // turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session. + std::setvbuf(stdout, nullptr, _IONBF, 0); + // Load every CUDA kernel when the context is created, before the expert cache takes the free VRAM. With the + // default lazy loading, a kernel first used mid-prompt (MMQ for IQ3_XXS at 64K+ on a 12 GB card) found no VRAM + // left for its code and the engine ended ("out of memory: cudaFuncSetAttribute"). Costs ~30 MB of VRAM. + if (std::getenv("CUDA_MODULE_LOADING") == nullptr) { +#if defined(_WIN32) + _putenv_s("CUDA_MODULE_LOADING", "EAGER"); +#else + setenv("CUDA_MODULE_LOADING", "EAGER", 0); +#endif + } + Options o; + bool have_tokens = false; + bool have_logits_stride = false; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&](const char* what) -> const char* { + if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); } + return argv[++i]; + }; + bool parsed = true; + if (a == "--help" || a == "-h") { usage(); return 0; } + else if (a == "--pack") o.pack = next("--pack"); + else if (a == "--tokens") { + if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } + std::string e; + if (!parse_i64_list(next("--tokens"), o.tokens, e)) { std::fprintf(stderr, "%s\n", e.c_str()); return 2; } + have_tokens = true; + } + else if (a == "--tokens-file") { + if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; } + std::ifstream input(next("--tokens-file")); + if (!input) { std::fprintf(stderr, "cannot open token file\n"); return 2; } + std::string text((std::istreambuf_iterator(input)), std::istreambuf_iterator()); + if (input.bad()) { std::fprintf(stderr, "cannot read token file\n"); return 2; } + std::string error; + if (text.find('\0') != std::string::npos || !parse_i64_list(text.c_str(), o.tokens, error)) { + std::fprintf(stderr, "malformed token file: %s\n", error.c_str()); return 2; + } + have_tokens = true; + } + else if (a == "--max-new") o.max_new = std::atoll(next("--max-new")); + else if (a == "--max-context") o.max_context = std::atoll(next("--max-context")); + else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling"); + else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale")); + else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base")); + else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale")); + else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx")); + else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor")); + else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor")); + else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast")); + else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow")); + else if (a == "--greedy") o.greedy = true; + else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; } + else if (a == "--top-k") o.top_k = std::atoi(next("--top-k")); + else if (a == "--top-p") o.top_p = (float) std::atof(next("--top-p")); + else if (a == "--temperature") o.temperature = (float) std::atof(next("--temperature")); + else if (a == "--dump-logits") o.dump_logits = next("--dump-logits"); + else if (a == "--logits-stride") { + if (have_logits_stride) { std::fprintf(stderr, "--logits-stride must be supplied only once\n"); return 2; } + if (!strata::program::logits_selection::parse_stride(next("--logits-stride"), o.logits_stride)) { + std::fprintf(stderr, "--logits-stride requires a positive decimal int64\n"); return 2; + } + have_logits_stride = true; + } + else if (a == "--dump-residual") o.dump_residual = next("--dump-residual"); + else if (a == "--dump-mixed") o.dump_mixed = next("--dump-mixed"); + else if (a == "--dump-layers") o.dump_layers = next("--dump-layers"); + else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); + else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); + else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); + else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); + else if (a == "--ple-kar-level") { + const std::string value = next("--ple-kar-level"); + unsigned level = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || + level < 1 || level > 8) { + std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); + return 2; + } + o.ple_kar_level = level; + } + else if (a == "--ple-kar-gpu-cache-mib") { + const std::string value = next("--ple-kar-gpu-cache-mib"); + unsigned mib = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib); + if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || + mib < 1 || mib > 1024) { + std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n"); + return 2; + } + o.ple_kar_gpu_cache_mib = mib; + } + else if (a == "--no-ple") o.no_ple = true; + else if (a == "--ple-io") o.ple_io = next("--ple-io"); + else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); + else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight")); + else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us")); + else if (a == "--ple-sync-submit") o.ple_sync_submit = true; + else if (a == "--kv") o.kv = next("--kv"); + else if (a == "--kv-resident") o.kv_resident = std::atoll(next("--kv-resident")); + else if (a == "--stream-token") o.stream_token = true; + else if (a == "--check-logits") o.check_logits = true; + else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true; + else if (a == "--gr-native-mmvf") o.gr_native_mmvf = true; + else if (a == "--native-bf16") o.native_bf16 = true; + else if (a == "--native-bf16-extra") o.native_bf16_extra = true; + else if (a == "--native-ple-key") o.native_ple_key = true; + else if (a == "--native-moe-combine") o.native_moe_combine = true; + else if (a == "--native-gdn") o.native_gdn = true; + else if (a == "--native-flash-attn-short") o.native_flash_attn_short = true; + else if (a == "--native-qsa-indexer") o.native_qsa_indexer = true; + else if (a == "--native-qsa") o.native_qsa = true; + else if (a == "--native-rope") o.native_rope = true; + else if (a == "--native-ple-postops") o.native_ple_postops = true; + else if (a == "--native-router") o.native_router = true; + else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true; + else if (a == "--native") o.native_preset = next("--native"); + else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf"); + else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf"); + else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf")); + else if (a == "--no-capture") o.no_capture = true; + else if (a == "--no-pool") o.no_pool = true; + else if (a == "--sync-every-layer") o.sync_every_layer = true; + else if (a == "--stage-timing") o.stage_timing = true; + else if (a == "--graph-only") o.graph_only = true; + else if (a == "--gpu-only-full") o.gpu_only_full = true; + else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers")); + else if (a == "--pool-affinity") { + const std::string v = next("--pool-affinity"); + if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto; + else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores; + else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All; + else { + std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str()); + return 2; + } + } + else if (a == "--no-host-worker") o.no_host_worker = true; + else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true; + else if (a == "--coupled-draft") o.coupled_draft = true; + else if (a == "--no-coupled-draft") o.coupled_draft = false; + else parsed = false; + // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 + // nested blocks (C1061). The order of the tests and what each does are unchanged. + if (!parsed) { + if (a == "--expert-cache") { + const std::string v = next("--expert-cache"); + o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str()); + } + else if (a == "--expert-cache-device1") o.expert_cache_remote[0] = std::atoi(next("--expert-cache-device1")); + else if (a == "--expert-cache-device2") o.expert_cache_remote[1] = std::atoi(next("--expert-cache-device2")); + else if (a == "--expert-cache-device3") o.expert_cache_remote[2] = std::atoi(next("--expert-cache-device3")); + else if (a == "--expert-cache-remote-placement") + o.expert_cache_remote_placement = next("--expert-cache-remote-placement"); + else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); + else if (a == "--prefill") { + const std::string v = next("--prefill"); + o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0; + // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 + const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX"); + const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5) + : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192); + o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192; + o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str()); + } + else if (a == "--no-split-rows") o.no_split_rows = true; + else if (a == "--no-prefill-borrow") o.no_prefill_borrow = true; + else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until")); + else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r"); + else if (a == "--spec") o.spec = std::atoi(next("--spec")); + else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle"); + else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt")); + else if (a == "--mtp") o.mtp = next("--mtp"); + else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window")); + else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); + else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every")); + else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); + else if (a == "--stop-eos") o.stop_eos = true; + else if (a == "--spec-split") o.spec_split = true; + else if (a == "--layer-split") o.layer_split = next("--layer-split"); + else if (a == "--split-device") o.split_device = next("--split-device"); + else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true; + else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); + else if (a == "--serve") o.serve = true; + else if (a == "--vision") o.vision = true; + else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache"))); + else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || + a == "--conversation-cache-min-free-mib") { + const std::string value = next(a.c_str()); + int64_t number = 0; + const auto result = std::from_chars(value.data(), value.data() + value.size(), number); + const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024); + if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || number < 0 || number > limit) { + std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str()); + return 2; + } + if (a == "--conversation-cache-mib") o.conversation_cache_mib = number; + else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number; + else o.conversation_cache_slots = (int) number; + } + else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); + else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); + else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); + else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); + else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); + else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); + else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); + else if (a == "--control-vector-scaled") { + // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive + std::stringstream list(next("--control-vector-scaled")); + std::string item; + while (std::getline(list, item, ',')) { + const size_t colon = item.rfind(':'); + char* end = nullptr; + const float sc = colon == std::string::npos ? 0.0f : std::strtof(item.c_str() + colon + 1, &end); + if (colon == std::string::npos || colon == 0 || end == item.c_str() + colon + 1 || *end != '\0') { + std::fprintf(stderr, "--control-vector-scaled: expected FILE:SCALE, got '%s'\n", item.c_str()); + return 2; + } + o.cvec_files.push_back({item.substr(0, colon), sc}); + } + } + else if (a == "--control-vector-layer-range") { + o.cvec_first = std::atoi(next("--control-vector-layer-range")); + o.cvec_last = std::atoi(next("--control-vector-layer-range")); + } + else if (a == "--cvec-mode") { + const std::string m = next("--cvec-mode"); + if (m == "project") o.cvec_mode = 0; + else if (m == "add") o.cvec_mode = 1; + else { std::fprintf(stderr, "--cvec-mode: add or project, got '%s'\n", m.c_str()); return 2; } + } + else if (a == "--cvec-dir") { + const std::string d = next("--cvec-dir"); + if (d == "per-layer") o.cvec_single = -1; + else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7); + else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; } + } + else if (a == "--no-spec-split") o.spec_split = false; + else if (a == "--eos-ids") { + std::string e; + if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; } + o.stop_eos = true; + } + else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps")); + else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true; + else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true; + else if (a == "--no-hit-poke") o.no_hit_poke = true; + else if (a == "--expert-profile") o.expert_profile = next("--expert-profile"); + else if (a == "--gpu-stages") o.gpu_stages = true; + else if (a == "--mmap-experts") o.mmap_experts = true; + else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena"); + else if (a == "--resident-cpu-experts") o.resident_cpu_experts = o.resident_cpu_explicit = true; + else if (a == "--resident-experts") { + o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true; + o.resident_headroom = 4ull << 30; + // A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form); + // STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4 + if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") + o.resident_pin = false; + if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) + o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); + } + else if (a == "--resident-budget-gib") { + const double gib = std::atof(next("--resident-budget-gib")); + if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; } + o.resident_budget = (uint64_t) (gib * 1073741824.0); + o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true; + o.resident_headroom = 4ull << 30; + if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0") + o.resident_pin = false; + if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0) + o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0); + } + else if (a == "--stats") o.stats = true; + else if (a == "--shared-late") o.shared_late = true; + else if (a == "--keep-canonical") o.keep_canonical = true; + else if (a == "--no-token-graph") o.no_token_graph = true; + else if (a == "--no-fused-gr") o.no_fused_gr = true; + else if (a == "--no-fast-attn") o.no_fast_attn = true; + else if (a == "--no-publish-kernel") o.no_publish_kernel = true; + else if (a == "--no-fused-gdn") o.no_fused_gdn = true; + else if (a == "--no-fast-select") o.no_fast_select = true; + else { + // An unknown flag is an ERROR and not a warning: a typo'd `--max-neww` that silently generated 16 + // tokens would look like a working run. + std::fprintf(stderr, "unknown argument: %s\n", a.c_str()); + usage(); + return 2; + } + } + } + strata::core::set_coupled_draft(o.coupled_draft); + if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { + std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); + return 2; + } + if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) + std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", + o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); + if (o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0 && !o.layer_split.empty()) { + std::fprintf(stderr, "strata serve: conversation parking does not yet support --layer-split; disable parking with --conversation-cache-mib 0\n"); + return 2; + } + // Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default + // the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across + // GPUs, not yet: KV streaming, images, control vectors, the helper caches (--expert-cache-remote), and lending + // cache slots to the prompt path (each stage's prompt path has its own buffers). + const bool pcie_given = o.pcie_frac >= 0.0; + std::vector split_at; + std::vector split_devs; + bool split_auto = false, split_same = false; + if (!o.layer_split.empty()) { + int n_dev = 1; + if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) n_dev = 1; + cudaGetLastError(); + auto ints = [](const std::string& str, auto& out) -> bool { + using V = typename std::decay_t::value_type; + size_t a = 0; + while (a < str.size()) { + size_t b = str.find(',', a); + if (b == std::string::npos) b = str.size(); + const std::string t = str.substr(a, b - a); + if (t.empty() || t.find_first_not_of("0123456789") != std::string::npos) return false; + out.push_back((V) std::atoll(t.c_str())); + a = b + 1; + } + return !out.empty(); + }; + split_auto = o.layer_split == "auto"; + bool ok = o.serve && (split_auto || ints(o.layer_split, split_at)); + if (ok && !o.split_device.empty()) ok = ints(o.split_device, split_devs); + else if (ok) + for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d) split_devs.push_back(d); + if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0); // one GPU + split_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto; + if (ok && split_auto && split_devs.empty()) { + std::fprintf(stderr, "strata generate: --layer-split auto: one GPU visible, so no split\n"); + o.layer_split.clear(); + split_auto = false; + } else if (ok) { + ok = (split_auto || split_at.size() == split_devs.size()) && split_devs.size() < (size_t) SplitDrive::kMax; + for (size_t i = 0; ok && i < split_at.size(); ++i) ok = split_at[i] >= 2 && (i == 0 || split_at[i] > split_at[i - 1]); + for (size_t i = 0; ok && !split_same && i < split_devs.size(); ++i) { + ok = split_devs[i] > 0 && split_devs[i] < n_dev; + for (size_t j = 0; ok && j < i; ++j) ok = split_devs[i] != split_devs[j]; + } + } + if (!ok) { + std::fprintf(stderr, "strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " + "distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU)\n", n_dev - 1); + return 2; + } + } + bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads + bool split_own_auto = false; // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow) + if (o.mmap_experts && !o.shared_expert_arena.empty()) { + std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); + return 2; + } + if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty())) { + std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n"); + return 2; + } + const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || + o.expert_cache_remote[2] > 0; + if (o.resident_cpu_experts && !o.layer_split.empty() && !remote_caches && o.resident_soft && + !o.resident_cpu_explicit && o.resident_budget == 0) { + // #364 #384: setup's --resident-experts with a layer split (--gpus at start, or a config edited by hand) runs + // as the plain mmap mode - the placement those users measured 1.3-1.6x faster than one GPU - instead of + // refusing. Exactly --mmap-experts: nothing else reads these flags (the headroom only sizes the copy). + std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode (--resident-experts) does not support a " + "layer split yet: the experts the GPUs do not hold are read through the OS file cache " + "(--mmap-experts), and RAM may fill up during long prompts\n"); + o.resident_cpu_experts = o.resident_pin = o.resident_soft = false; + o.resident_headroom = 8ull << 30; + } + if (o.resident_cpu_experts && (!o.layer_split.empty() || remote_caches)) { + std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support layer splits or remote expert caches\n"); + return 2; + } + // the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer + // split, the visible GPUs no stage runs on, in order + int remote_dev[3] = {1, 2, 3}; + if (multi_gpu) { + if (o.expert_profile.empty()) { + std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n"); + return 2; + } + // A STAGE'S PROMPT PATH BORROWS FROM THAT STAGE'S OWN EXPERT CACHE. This used to set + // `no_prefill_borrow = true` - "each stage's prompt path has its own buffers" - which is true, but it is + // a reason to give each stage its own LOAN, not a reason to make every stage withhold a chunk-sized + // reserve from its cache for the whole session. Forced on, it also collapsed `--prefill auto` to 2048 + // (below) and skipped the lend arm, so a stage paid for its prompt buffers twice over: once in VRAM it + // never got back, once in the smaller chunk. At `--prefill 5524` that reserve is 3.8 GiB per stage, + // more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K. + // The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt + // that tail is expert cache, so a large chunk costs a stage nothing permanent. + // #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and + // copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read + // 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%). + // So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a + // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, + // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own + // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). + // OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the + // split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the + // 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical. + // STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow. + // --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is). + const char* own_env = std::getenv("STRATA_SPLIT_OWN"); + if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') { + const char* v = std::string(own_env) == "auto" ? nullptr : own_env; + bool own = v ? v[0] == '1' : true; + // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) + const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk; + const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4; + std::string why; + if (!v) { + std::vector devs = {0}; + for (const int d : split_devs) devs.push_back(d); + for (const int d : devs) { + cudaDeviceProp prop{}; + if (cudaGetDeviceProperties(&prop, d) != cudaSuccess) { cudaGetLastError(); own = false; break; } + const int64_t total_mib = (int64_t) (prop.totalGlobalMem >> 20); + if (reserve_mib * 100 > 12 * total_mib) { + own = false; + why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB"; + break; + } + } + } + if (own) { + o.no_prefill_borrow = true; + split_own_auto = true; + std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " + "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk, + v ? " (STRATA_SPLIT_OWN=1)" : ""); + } else if (!why.empty()) { + std::fprintf(stderr, "strata generate: layer split: the prompt paths borrow from the caches (%s)\n", + why.c_str()); + } + } + int n_vis = 1; + if (cudaGetDeviceCount(&n_vis) != cudaSuccess || n_vis < 1) n_vis = 1; + cudaGetLastError(); + int next_free = 1; + for (int r = 0; r < 3; ++r) { + if (o.expert_cache_remote[(size_t) r] <= 0) continue; + while (next_free < n_vis && + std::find(split_devs.begin(), split_devs.end(), next_free) != split_devs.end()) ++next_free; + if (next_free >= n_vis) { + std::fprintf(stderr, "strata generate: --expert-cache-remote with a layer split needs a GPU that runs no " + "stage (%d visible, %zu used by the split)\n", n_vis, split_devs.size() + 1); + return 2; + } + remote_dev[r] = next_free++; + } + std::string devs; + for (const int d : split_devs) devs += (devs.empty() ? "" : ",") + std::to_string(d); + std::fprintf(stderr, "strata generate: layer split across %zu GPUs: CUDA0, then CUDA%s (split %s)\n", + split_devs.size() + 1, devs.c_str(), o.layer_split.c_str()); + } +#if defined(STRATA_USE_HIP) + { + // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 + // card would otherwise fail later with "invalid device function") + std::vector used{0}; + if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end()); + for (int r = 0; r < 3; ++r) + if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]); + for (const int d : used) { + if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) { + std::fprintf(stderr, "strata generate: %s\n", why.c_str()); + return 1; + } + } + } +#endif + if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) { + o.prefill_auto = false; // nothing to lend from: the buffers are reserved for the session, so keep them small + o.prefill_chunk = 2048; + } + if (!have_tokens && o.serve) { // plan v0.3 P8: requests bring their own tokens + o.tokens = {248045}; + o.max_new = 1; + have_tokens = true; + o.stop_eos = true; + } + if (!have_tokens) { + std::fprintf(stderr, "strata generate: --tokens is required (this build has no tokenizer; see the " + "header of src/program/generate.cpp)\n"); + usage(); + return 2; + } + + if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 || + o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) { + std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n"); + return 2; + } +#if defined(_WIN32) + if (o.ple_io == "ram") { + std::fprintf(stderr, "strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n"); + return 2; + } +#endif + if (o.kv == "q4") o.kv = "q4_0"; + if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); + return 2; + } + const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING"); + if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) { + std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2; + } + strata::core::qsa_set_without_key(keyless_path != nullptr); + strata::core::qsa_set_kv_int8(o.kv == "int8"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to + // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) + const char* kv_rot = std::getenv("STRATA_KV_ROT"); + strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1'); + if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8") + std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n"); + strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell + if (o.kv_resident < 0) { + std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n"); + return 2; + } + if (o.kv == "k8v4" && o.kv_resident > 0) { + std::fprintf(stderr, "strata generate: --kv k8v4 does not support --kv-resident streaming (yet)\n"); + return 2; + } + strata::core::qsa_set_kv_resident(o.kv_resident); + // Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be + // up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code + // edits +6-11%, ordinary text unchanged (bench/results/2026-09-27-spec). --suffix-draft 0 turns it off. + if (o.suffix_draft > 0 && o.spec >= 2 && o.mtp_max_t == 0) { + o.mtp_max_t = o.spec; + o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT + } + strata::core::layer_set_shared_early(!o.shared_late); + if (!o.native_preset.empty()) { + try { + // every shard of the model (-0000N-of-0000M.gguf beside --native). A missing shard is an error + // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. + o.native_shards = strata::gguf_split_paths(o.native_preset); + // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files + // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's + if (o.ple_gguf.empty() && !o.no_ple) { + const strata::GgufModel model(o.native_shards); + size_t at = 0; + if (model.find("per_layer_token_embd.weight", &at) != nullptr) o.ple_gguf = o.native_shards[at]; + } + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what()); + return 2; + } + if (o.no_ple || o.ple_gguf.empty()) { + std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too), and no " + "shard of the model holds per_layer_token_embd.weight\n"); + return 2; + } + o.stream_token = true; + o.gr_native_mmvf = true; + o.native_bf16 = o.native_bf16_extra = true; + o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true; + o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true; + if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset; + if (o.native_dense_gguf.empty()) { + // every shard of the model (-0000N-of-0000M.gguf beside --native), then the PLE shard: a split + // may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) + o.native_dense_gguf = o.native_shards; + // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections + bool ple_only = false; + try { + strata::GgufFile pg(o.ple_gguf); + if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple"; + } catch (const std::exception&) {} + if (!ple_only && + std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end()) + o.native_dense_gguf.push_back(o.ple_gguf); + } + // Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract + // cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it. + } + if (o.logits_stride > 1 && (o.max_new != 1 || o.dump_logits.empty())) { + std::fprintf(stderr, "strata generate: --logits-stride > 1 requires --max-new 1 and --dump-logits\n"); + return 2; + } + if (o.no_ple && !o.ple_gguf.empty()) { + std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); + return 2; + } + if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || + (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { + std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); + return 2; + } + if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) { + std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n"); + return 2; + } + if (o.native_ple_postops && o.no_ple) { + std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); + return 2; + } + if (!o.no_ple && o.ple_gguf.empty()) { + std::fprintf(stderr, "strata generate: --ple-gguf is required; --no-ple explicitly enables a diagnostic ablation\n"); + return 2; + } + // P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path. + if (o.max_context > 2147483647LL - 8) { + std::fprintf(stderr, "strata generate: --max-context must be below 2^31\n"); + return 2; + } + if (o.max_new <= 0 || o.max_context <= 0 || o.max_new > o.max_context || + o.tokens.size() > (size_t) (o.max_context - o.max_new)) { + std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n"); + return 2; + } + // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a + // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is + // resolved after the model file has had its say, right before session_init. + strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below + { + using RST = strata::kernels::RopeScalingType; + // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, + // resolved below; anything present must be one of the three names + if (o.rope_scaling == "none") rope_cfg.type = RST::None; + else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else if (!o.rope_scaling.empty()) { + std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", + o.rope_scaling.c_str()); + return 2; + } + // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below + for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor, + o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow}) + if (!std::isfinite(v)) { + std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v); + return 2; + } + // 0 is the absent default; an explicit factor must extend, not shrink + if (o.rope_scale != 0 && o.rope_scale < 1.0) { + std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", + o.rope_scale); + return 2; + } + if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) { + std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n"); + return 2; + } + if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 || + o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) { + std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " + "--yarn-orig-ctx 0 = default, the rest positive)\n"); + return 2; + } + } + if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) || + o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || + o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), + [](int slots) { return slots < 0; }) || + (o.expert_cache_remote[1] > 0 && o.expert_cache_remote[0] == 0) || + (o.expert_cache_remote[2] > 0 && o.expert_cache_remote[1] == 0)) { + std::fprintf(stderr, "strata generate: invalid sampling or resource parameter\n"); + return 2; + } + if (o.expert_cache_remote_placement != "stripe" && o.expert_cache_remote_placement != "layer") { + std::fprintf(stderr, "strata generate: --expert-cache-remote-placement must be stripe or layer\n"); + return 2; + } + + if (o.native_flash_attn_short && o.max_context > 256) { + std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n"); + return 2; + } + if (o.native_flash_attn_short && (o.gpu_only_full || o.graph_only || o.gpu_stages)) { + std::fprintf(stderr, "strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n"); + return 2; + } + // The whole-model graph measurements replay every layer through CUDA0's session, which a layer split carves to + // CUDA0's own range - the answer would read another stage's state. Refused here rather than at the call, so + // the reason is visible before 55 GB is loaded. + if (multi_gpu && (o.gpu_only_full || o.gpu_stages)) { + std::fprintf(stderr, "strata generate: --gpu-only-full and --gpu-stages replay the whole model through one " + "session, which a layer split does not have; run them without --layer-split\n"); + return 2; + } + if (!o.native_head_gguf.empty()) { + try { + o.native_head_shards = o.native_head_gguf == o.native_preset ? o.native_shards + : strata::gguf_split_paths(o.native_head_gguf); + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: --native-head-gguf %s: %s\n", o.native_head_gguf.c_str(), e.what()); + return 2; + } + } + if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) { + std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n"); + return 2; + } + if (o.cpu_oracle_q8_0 && (o.expert_cache != 0 || !o.expert_profile.empty())) { + std::fprintf(stderr, "strata generate: --cpu-oracle-q8-0 cannot be combined with --expert-cache or --expert-profile until the GPU expert contract matches\n"); + return 2; + } + + // **BEFORE ANYTHING ELSE.** The CPU expert kernel is AVX-512 (VNNI + VBMI) and its translation unit is + // compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal + // instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check. + strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0); + // ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are + // chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes + // next. Refused here, by name, rather than an illegal instruction in the first expert. + if (!strata::kernels::cpu::cpu_avx2_ok()) { + std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which every CPU " + "expert kernel needs; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer\n", + strata::kernels::cpu::cpu_name().c_str()); + return 2; + } + + std::string err; + if (!o.native_head_gguf.empty() && !o.stream_token) { + std::fprintf(stderr, "--native-head-gguf requires --stream-token\n"); + return 2; + } + // Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps + // every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding + // come from the model file) and runs its experts in verify windows only (--spec). + { + const strata::core::ModelGeometry g0; + if (!strata::kernels::cpu::expert_layout_load(o.pack, g0.n_layers, g0.n_expert, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + // Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before + // anything is allocated: an unsupported down type used to exit from inside the first verify window, and + // an unsupported dequant type left the prompt path's fp16 buffer unwritten. + const auto& lay = strata::kernels::cpu::expert_layout(); + for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) { + const auto& f = lay.fmt[(size_t) l]; + if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) { + std::fprintf(stderr, "strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this " + "engine has no GPU kernels for\n", (long long) l, + strata::ggml_type_name((uint32_t) f.gu_type), strata::ggml_type_name((uint32_t) f.d_type), + f.gu_type, f.d_type); + return 1; + } + } + } + const bool native_pack = strata::kernels::cpu::expert_layout().native; + // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's + // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, + // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). + const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS"); + const bool early_remote = early_env && early_env[0] == '1'; + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) { + // Keep CUDA1's proven startup order: initialise its context before + // allocating GPU0 weights or mapping the large host expert arena. + double free_gib = 0; + if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", + remote_dev[r], free_gib); + } + // plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe). + // PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the + // link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The + // real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical + // pack's 0.2 was never measured against the link, so it is left alone. `--calibrate` measures it outright. + if (o.pcie_frac < 0.0) { + const double base = native_pack ? 0.55 : 0.2; + const double bw = native_pack ? probe_pcie_h2d_gbps() : -1.0; + if (!native_pack) { + o.pcie_frac = base; + } else if (bw > 0.0) { + // below ~4 GB/s (an x1 link: ~0.9 GB/s) a missed expert's 1.4 MB takes longer to cross than the CPU + // pool takes to compute it, so none of them go over the link + o.pcie_frac = bw >= 20.0 ? base : bw < 4.0 ? 0.0 : std::min(base, std::max(0.05, base * (bw / 26.0))); + std::fprintf(stderr, "strata generate: PCIe probe: %.1f GB/s host->device -> pcie_frac %.2f (default %.2f)\n", + bw, o.pcie_frac, base); + } else { + o.pcie_frac = base; + std::fprintf(stderr, "strata generate: PCIe probe failed -> pcie_frac default %.2f\n", base); + } + } + // the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well + if (!native_pack) strata::kernels::cpu::cpu_require_expert_support(); + else if (!strata::kernels::cpu::cpu_avx512_ok()) + std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " + "(multi-token for the i-quant gate/up rows)\n", + std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); + strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below + int64_t K = 10; + // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, + // and `session_init` below builds the rope table from it and captures the kernels reading its constants + // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats + // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over + // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the + // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. + { + // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the + // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. + std::string gguf_rope_type; + double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; + if (!o.native_preset.empty()) { + // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file + // is the authority on its own MoE shape - everything else in the geometry is unchanged + try { + strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + gguf_rope_orig_ctx = v->num(); + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", + o.native_preset.c_str(), e.what()); + return 1; + } + } + using RST = strata::kernels::RopeScalingType; + if (!o.rope_scaling.empty()) { + // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys + if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else rope_cfg.type = RST::None; + } else if (!gguf_rope_type.empty()) { + if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; + else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; + else if (gguf_rope_type != "none") { + std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", + o.native_preset.c_str(), gguf_rope_type.c_str()); + return 2; + } + } + if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included + else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor; + if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; + else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; + if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; + else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; + rope_cfg.freq_scale_in = o.rope_freq_scale; + rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor + : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); + rope_cfg.attn_factor = o.yarn_attn_factor; + rope_cfg.beta_fast = o.yarn_beta_fast; + rope_cfg.beta_slow = o.yarn_beta_slow; + if (rope_cfg.type == RST::None) { + // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and + // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the + // frequency base survives - it is the rotation itself, not a scaling knob. + const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 || + o.yarn_attn_factor != 1.0; + const double base = rope_cfg.freq_base; + rope_cfg = strata::kernels::RopeScaling{}; + rope_cfg.freq_base = base; + if (knobs) + std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, " + "--rope-freq-scale and the --yarn-* knobs have no effect\n"); + } + // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies + // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a + // --rope-freq-scale that turns the resolved factor non-finite. + if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) { + std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " + "freq_scale %g, base %g, original context %g)\n", + why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none", + rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx); + return 2; + } + strata::kernels::rope_scaling_set(rope_cfg); + if (rope_cfg.type != RST::None) { + const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; + std::fprintf(stderr, + "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " + "--max-context %lld against a trained context of %.0f\n", + tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), + (long long) o.max_context, rope_cfg.orig_ctx); + if ((double) o.max_context <= rope_cfg.orig_ctx) + std::fprintf(stderr, + "strata generate: note: the context is within the trained %.0f - no position needs the " + "extension, and the resolved scaling still applies to every angle\n", + rope_cfg.orig_ctx); + // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit + // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 + if (rope_cfg.mscale() != 1.0) + std::fprintf(stderr, + "strata generate: note: the %s magnitude correction scales cos and sin by %.6f " + "at every position\n", + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } + const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + strata::kar::ExpertMiss kar_expert_miss; + if (kar_expert_archive != nullptr) { + const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); + if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches || + !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' || + g.n_embd != strata::kernels::cpu::H) { + std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, " + "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n"); + return 2; + } + for (const auto& f : strata::kernels::cpu::expert_layout().fmt) + if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) { + std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2; + } + if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert, + (uint32_t) g.n_embd, strata::kernels::cpu::FF, + (uint32_t) (level_text[0] - '0'), err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; + } + // Native resident hits are the baseline. Route all otherwise CPU/PCIe + // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. + o.pcie_frac = 0; + } +#else + if (kar_expert_archive != nullptr) { + std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n"); + return 2; + } +#endif + strata::core::NativeEmbed native_embed; + if (native_pack) { + if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || + (o.prefill_chunk <= 0 && o.tokens.size() > 1)) { + std::fprintf(stderr, "strata generate: %s is a native (IQ) pack: it needs --native SHARD1, --spec T (T >= 2) " + "and --prefill CHUNK\n", o.pack.c_str()); + return 2; + } + const strata::core::ModelGeometry g0; + if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector{o.embd_gguf}, g0.n_embd, + 248320, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + strata::core::set_native_embed(&native_embed); + std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " + "%s in mapped host memory (%.0f MiB)\n", + o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6, + strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0); + } + // Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back + // to the expert cache with --native). `--keep-canonical` loads both, as before. + std::set skip; + if (!o.keep_canonical) { + if (!o.native_dense_gguf.empty() && + !strata::core::NativeDense::served_names(o.native_dense_gguf, o.native_ple_key, skip, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (!o.native_head_gguf.empty()) skip.insert("output.weight"); + // the PLE module validates its canonical key at construction (8 MB); a native pack has none to load + if (!native_pack) skip.erase("blk.1.ple_key.weight"); + // #326: a --compat-bf16 pack (OrcaRouter IQ3_XXS) keeps its BF16 key in the arena + if (native_pack && !strata::core::NativeDense::keep_unquantized_ple_key(o.pack, skip, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (native_pack) skip.insert("token_embd.weight"); + } + uint64_t pool_bytes = 0; + if (!strata::core::WeightTable::pool_bytes(o.pack, pool_bytes, err, skip.empty() ? nullptr : &skip)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + void* arena = nullptr; + if (cudaMalloc(&arena, pool_bytes) != cudaSuccess) { + std::fprintf(stderr, "strata generate: cudaMalloc(%llu) for the weight arena failed\n", + (unsigned long long) pool_bytes); + return 1; + } + strata::core::WeightTable wt; + if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s (%zu canonical tensors skipped: " + "served natively)\n", + (unsigned long long) (pool_bytes >> 20), o.pack.c_str(), skip.size()); + + strata::core::NativeDense native_dense; + if (!o.native_dense_gguf.empty()) { + if (!native_dense.load(o.native_dense_gguf, wt, err, o.native_ple_key)) { + std::fprintf(stderr, "strata generate: native dense projections: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights\n", + native_dense.tensor_count(), (double) native_dense.weight_bytes() / (1024.0 * 1024.0)); + } + + strata::kernels::gr_set_fp32_activations(o.gr_fp32_activations); + strata::kernels::gr_set_native_mmvf(o.gr_native_mmvf); + // Plan v0.3 P3: the fused hyper-connection read rides the native (FP32-activation) contract; the per-stage + // and dump measurements need the unfused layout of R, so they keep the old kernels. + strata::core::layer_set_fast_attn(!o.no_fast_attn); + strata::core::layer_set_publish_kernel(!o.no_publish_kernel); + strata::core::layer_set_fused_gdn(!o.no_fused_gdn); + strata::core::layer_set_fast_select(!o.no_fast_select); + strata::core::layer_set_fused_gr(o.gr_native_mmvf && !o.no_fused_gr && !o.gpu_stages && o.dump_layers.empty() && + o.dump_halves.empty() && !o.stage_timing); + strata::core::layer_set_native_bf16(o.native_bf16); + strata::core::layer_set_native_flash_attn_short(o.native_flash_attn_short); + strata::kernels::ple_set_native_bf16(o.native_bf16_extra); + strata::kernels::shared_expert_set_native_bf16(o.native_bf16_extra); + strata::kernels::native_moe_combine_set_enabled(o.native_moe_combine); + strata::kernels::native_gdn_set_enabled(o.native_gdn); + strata::kernels::native_router_set_enabled(o.native_router); + strata::kernels::native_qsa_set_enabled(o.native_qsa); + strata::kernels::native_qsa_indexer_set_enabled(o.native_qsa_indexer); + strata::kernels::native_rope_set_enabled(o.native_rope); + // The vision path: every rope kernel reads a cell's (t, h, w) from this table (strata/kernels/mrope.hpp). It is + // the identity until an image request, and it is set here, before any CUDA graph captures a rope kernel. + int32_t* d_mrope = nullptr; + std::vector mrope_host; + if (o.vision) { + const int64_t cells = o.max_context + 64; + mrope_host.resize((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; + if (cudaMalloc(&d_mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || + cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != + cudaSuccess) { + std::fprintf(stderr, "strata generate: cannot allocate the image position table\n"); + return 1; + } + strata::kernels::mrope_table_set(d_mrope); + } + strata::kernels::ple_set_native_postops(o.native_ple_postops); + // before session_init: every graph captured from here on has the vector's kernels where it applies + std::string cvec_summary = "0"; + if (!o.cvec_files.empty()) { + std::string ce; + if (!load_control_vectors(o, g, cvec_summary, ce)) { + std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str()); + return 2; + } + } + if (o.max_context < (int64_t) o.tokens.size() + o.max_new) { + std::fprintf(stderr, "strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n", + (long long) o.max_context, o.tokens.size(), (long long) o.max_new); + return 2; + } + + if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) { + std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1; + } + if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n"); + strata::core::SessionState ss; + void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) + // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session + // calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`, + // i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through + // a wrapper comes back at 28-31 us REGARDLESS OF SIZE, `scale_inplace` on 2,048 floats and `silu_inplace` + // on 10,240 floats being indistinguishable, which is a fixed per-launch cost and not execution. + // `bench/micro/graph_node_cost.cu` measures the same kernels on a real stream at 3.63 us ungrapped and + // 0.805 us inside a graph. **That is an ~8x penalty on every launch in the engine.** + cudaStream_t main_stream = nullptr; + if (cudaStreamCreateWithFlags(&main_stream, cudaStreamNonBlocking) != cudaSuccess) { + std::fprintf(stderr, "strata generate: cannot create the main stream\n"); + return 1; + } + void* const main_cs = (void*) main_stream; + + // ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The + // half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued + // while a graph is being CAPTURED - arming `ss.block.dump` afterwards would produce a file of zeros that + // reads exactly like a wrong answer. The ladder is the opposite: `session_loop` enqueues it per token on + // the replay stream, so it must be armed after capture to stay out of the graph. + const uint64_t half_stride = (uint64_t) 2 * g.n_embd + (uint64_t) 2 * g.hc + + (uint64_t) g.n_head * g.head_dim + + (uint64_t) 5 * g.n_head_kv * g.head_dim + 8; + std::FILE* half_dump = nullptr; + float* half_stage = nullptr; + if (!o.dump_halves.empty()) { + half_dump = std::fopen(o.dump_halves.c_str(), "wb"); + if (half_dump == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_halves.c_str()); + return 1; + } + const size_t n = (size_t) g.n_layers * (size_t) half_stride; + if (cudaHostAlloc((void**) &half_stage, n * sizeof(float), cudaHostAllocDefault) != cudaSuccess) { + std::fprintf(stderr, "strata generate: cannot pin the half-dump staging buffer\n"); + return 1; + } + ss.block.dump = half_stage; + } + + strata::core::Doorbell db; + if (strata::core::doorbell_init(g, K, db) == 0) { + std::fprintf(stderr, "strata generate: doorbell_init failed\n"); + return 1; + } + ss.db = &db; + + // ================================ THE PLE ================================ + // + // **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole + // module was built and parity-tested, and nothing called it. Everything below is construction - the table + // is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the + // three buffers are the only allocation. + strata::kernels::PleTable ple_table; + std::vector ple_emb_host((size_t) strata::kernels::NG_N_EMBD); + float* ple_emb_dev = nullptr; + float* ple_scratch = nullptr; + if (!o.ple_gguf.empty()) { + strata::kernels::PleIoOptions pio; + pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct; + pio.lock = o.ple_io == "ram"; + const auto tpl = Clock::now(); + pio.max_inflight = (uint32_t) o.ple_inflight; + pio.cache_rows = (uint64_t) o.ple_row_cache; + pio.io_thread = !o.ple_sync_submit; + // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first + // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one + // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row + // request that this goes on (default 60; then the SSD may sleep until the next request). + { + const char* ka = std::getenv("STRATA_SSD_KEEPALIVE"); + const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW"); + pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0; + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } + const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) + : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); + if (!ple_open) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) { + std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str()); + return 1; + } + if (pio.lock) + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", + std::chrono::duration(Clock::now() - tpl).count()); + if (!o.ple_kar.empty()) + std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n", + o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality", + o.ple_kar_level, + o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : ""); + else if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); + else if (pio.mode == strata::kernels::PleIo::Direct) + std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n"); + const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight"); + const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight"); + const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight"); + const strata::core::WeightRef* wnq = wt.find("blk.1.ple_norm_query.weight"); + const strata::core::WeightRef* wnc = wt.find("blk.1.ple_norm_conv.weight"); + const strata::core::WeightRef* wc = wt.find("blk.1.ple_conv1d.weight"); + if (!wk || !wv || !wnk || !wnq || !wnc || !wc) { + std::fprintf(stderr, "strata generate: the pack has no blk.1.ple_* tensors, so the PLE cannot be " + "wired - and running without it is a DIFFERENT MODEL (LEDGER L123)\n"); + return 1; + } + // `ple_key` is S2 and the loader has already widened its scales to f32, so the two planes are located + // by the sizes the `WeightRef` records rather than re-derived - the same rule `plane_ptrs` follows. + if (!wk->quantized()) { + // plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16) + ss.ple.w.key_bf16 = (const uint16_t*) wk->data; + } else if (wk->data != nullptr) { + ss.ple.w.key_codes = (const uint8_t*) wk->data; + ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes); + } + if (o.native_ple_key && wk->quantized()) { + if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 && + wk->native_type != 8) || !wk->native_q8_1) { + std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n"); + return 1; + } + ss.ple.w.key_native_data = wk->native_data; + ss.ple.w.key_native_type = wk->native_type; + ss.ple.w.key_native_q8_1 = wk->native_q8_1; + } + ss.ple.w.value_bf16 = (const uint16_t*) wv->data; + ss.ple.w.norm_key = (const float*) wnk->data; + ss.ple.w.norm_query = (const float*) wnq->data; + ss.ple.w.norm_conv = (const float*) wnc->data; + // The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps + // the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error, + // a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is + // refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0 + // (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16. + const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 || + (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0); + if (!f16 || wc->bytes != (uint64_t) wc->elements * 2) { + std::fprintf(stderr, "strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, " + "%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with " + "tools/iq_pack.py\n", + (int) wc->kind, (unsigned long long) wc->bytes, (long long) wc->elements); + return 1; + } + ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data; + ss.ple.consts = strata::kernels::ple_artifact_consts(); + if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us); + ss.ple.table = &ple_table; + ss.ple.token = &ss.ple_token; + ss.ple.prev = ss.ple_prev; + // `ss.ple.hist` and the ready() check wait for `session_init`, which carves the history - the session is + // now allocated after the layer-split search (see the carve), and the wiring lands there + ss.ple.emb_host = ple_emb_host.data(); + if (cudaMalloc((void**) &ple_emb_dev, (size_t) strata::kernels::NG_N_EMBD * 4) != cudaSuccess || + cudaMalloc((void**) &ple_scratch, strata::core::ple_run_scratch_bytes()) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the PLE buffers failed\n"); + return 1; + } + ss.ple.emb_dev = ple_emb_dev; + ss.ple.scratch = ple_scratch; + } else { + std::fprintf(stderr, + "strata generate: PLE OFF by explicit --no-ple diagnostic request.\n" + " The tokens below are NOT this model's; this is only useful for A/B measurement.\n"); + } + + float* d_parts = nullptr; + if (cudaMalloc(&d_parts, (size_t) K * g.n_embd * 4) != cudaSuccess || + cudaMemset(d_parts, 0, (size_t) K * g.n_embd * 4) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the parts buffer failed\n"); + return 1; + } + + // ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it + // still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head + // (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the + // profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone. + if (multi_gpu && split_auto && o.split_skip_if_fits) { + std::vector> prof; + int64_t pslots = 0; + std::string perr; + const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; + if (remote || o.expert_profile.empty() || + !strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, prof, pslots, perr)) { + std::fprintf(stderr, "strata generate: --split-skip-if-fits: %s; the split stays\n", + remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str()); + } else { + const auto& lay = strata::kernels::cpu::expert_layout(); + int64_t pairs_bytes = 0; + for (const auto& pr : prof) + pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers); + const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20); // + drafter/head, windows + const int64_t room = (int64_t) fb - held_back; + cudaDeviceProp dp{}; + cudaGetDeviceProperties(&dp, 0); + if (pairs_bytes <= room) { + std::fprintf(stderr, "strata generate: layer split skipped (--split-skip-if-fits): CUDA0 (%s) holds all " + "%zu profiled pairs (%.2f GiB) with the session (%.2f GiB, %lld-token context), " + "the drafter and the reserve: %.2f GiB free, %.2f GiB to spare - one GPU\n", + dp.name, prof.size(), (double) pairs_bytes / 1073741824.0, (double) session / 1073741824.0, + (long long) o.max_context, (double) fb / 1073741824.0, + (double) (room - pairs_bytes) / 1073741824.0); + multi_gpu = false; + split_auto = false; + split_devs.clear(); + split_at.clear(); + o.layer_split.clear(); + } else { + std::fprintf(stderr, "strata generate: --split-skip-if-fits: CUDA0 (%s) would hold only %.2f of the " + "profile's %.2f GiB (%.2f GiB free, %.2f GiB for the session, drafter and " + "reserve): the split stays\n", dp.name, + (double) std::max(room, 0) / 1073741824.0, (double) pairs_bytes / 1073741824.0, + (double) fb / 1073741824.0, (double) held_back / 1073741824.0); + } + } + } + strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async + // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the + // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) + std::vector> stages; + for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) { + stages.push_back(std::make_unique()); + GpuStage& st = *stages.back(); + st.dev = split_devs[i]; + double free_gib = 0; + if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + const strata::core::OnDevice on(st.dev); + void* arena_s = nullptr; + if (cudaMalloc(&arena_s, pool_bytes) != cudaSuccess || + !st.wt.load(o.pack, arena_s, pool_bytes, err, skip.empty() ? nullptr : &skip)) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d weights: %s\n", st.dev, + err.empty() ? "the weight arena does not fit" : err.c_str()); + return 1; + } + if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d native dense projections: %s\n", st.dev, + err.c_str()); + return 1; + } + // THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its + // LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the + // sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows. + if (cudaStreamCreateWithFlags(&st.stream, cudaStreamNonBlocking) != cudaSuccess || + cudaStreamCreateWithFlags(&st.adapt_stream, cudaStreamNonBlocking) != cudaSuccess || + cudaEventCreateWithFlags(&st.adapt_ev, cudaEventDisableTiming) != cudaSuccess) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d: its streams failed\n", st.dev); + return 1; + } + // a control vector (the speed projection): its tables on this device too - the stage's layers apply it here + if (!strata::kernels::cvec_replicate(err)) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str()); + return 1; + } + // --vision: this device's image-position table (the identity until a picture request), read by every rope + // kernel its stage runs - set before any of its graphs is captured + if (o.vision) { + if (cudaMalloc(&st.mrope, mrope_host.size() * sizeof(int32_t)) != cudaSuccess || + cudaMemcpy(st.mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != + cudaSuccess) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d: the image position table failed\n", st.dev); + return 1; + } + strata::kernels::mrope_table_set(st.mrope); + } + // its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed) + st.pcie_frac = o.pcie_frac; + if (!pcie_given && native_pack) { + const double bw = probe_pcie_h2d_gbps(); + if (bw > 0.0) st.pcie_frac = bw >= 20.0 ? 0.55 : bw < 4.0 ? 0.0 : std::min(0.55, std::max(0.05, 0.55 * (bw / 26.0))); + std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s -> pcie_frac %.2f\n", st.dev, + bw, st.pcie_frac); + } + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " + "follows the split search)\n", st.dev, (double) fb / 1073741824.0); + } + GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get(); + + std::vector> profile; + if (!o.expert_profile.empty()) { + int64_t pslots = 0; + if (!strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, profile, pslots, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + // An explicit number truncates the ranked list ("what would 2,000 slots give" without rebuilding the + // file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks + // every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto. + if (o.expert_cache == 0) o.expert_cache = -1; + std::fprintf(stderr, "strata generate: profile %s: %zu ranked pairs, built for %lld slots\n", + o.expert_profile.c_str(), profile.size(), (long long) pslots); + } + // ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on + // the 5080 + 3090 rig (bench/results/2026-09-29-layer-split): + // - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a + // 3090: the per-layer round trip and kernels, not the bytes - both cards have ~950 GB/s); + // - an expert no cache holds costs ~190 ms per unit of routed mass: the CPU pool in decode and the PCIe stream + // in prompts (fitted: the sweep's best K, 26-28, is where one more layer on the faster card stops paying + // for the ~0.1% of the mass it pushes out of its cache); + // - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the + // reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used; + // the routed mass of rank r is taken as (r+1)^-1.2 (fits the sweep's hit rates: K=24/26/28 predicted + // 99.53/99.34/99.15%, measured 99.5/99.4/99.0%). + // Up to 3 GPUs every placement is tried; beyond, the layers are shared in proportion to speed. + // STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher). + // THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache + // is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`), + // so it withholds no VRAM of its own and this reserve is zero. Only without borrowing - no profile to fill + // a cache from, or --no-prefill-borrow - do the buffers take a reserve, and then this estimate stands in + // for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the + // exact `Prefill::bytes_needed` as soon as it can. + const bool pf_borrow = !o.no_prefill_borrow && !o.expert_profile.empty(); + // (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of + // whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books + // here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit) + const int64_t split_ring_mib = + (multi_gpu && !pf_borrow && o.prefill_chunk >= 1024) + ? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20) + : 0; + if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96); + const int64_t split_pf_mib = + (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 0; + // ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage + // after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up + // to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the + // last one, which is also the only one that holds the head. On the two identical 8 GB cards that GiB was + // the entire difference between CUDA0's cache and CUDA1's: 814 slots against 188, 2026-09-30. Both of + // those allocations are already made before a stage's cache is sized, so what has to be held back here is + // the windows and - only on the stage that carries them - the drafter and the head. + const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded up + const int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only + // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the + // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches + // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a + // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the + // search sees the reserve. + static const bool place_with_reserve = [] { + const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); + return v != nullptr && std::string(v) == "reserve"; + }(); + auto stage_room = [&](int dev, bool later, bool drafter, bool search = false) -> int64_t { + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + if (const cudaError_t e = cudaMemGetInfo(&fb, &tb); e != cudaSuccess) + std::fprintf(stderr, "strata generate: layer split: CUDA%d free memory: %s\n", dev < 0 ? 0 : dev, + cudaGetErrorString(e)); + const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib; + const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) + + (drafter ? kDrafterMib : 0)) << 20; + return std::max((int64_t) fb - reserve, 0); + }; + if (multi_gpu && split_auto) { + const auto& lay = strata::kernels::cpu::expert_layout(); + const int ns = (int) stages.size() + 1; + std::vector cap((size_t) ns), used((size_t) ns); + std::vector layer_ms((size_t) ns); + for (int i = 0; i < ns; ++i) { + const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; + cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true); + int sms = 0, khz = 0; + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + if (cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, dev) != cudaSuccess || khz <= 0) khz = 1800000; + cudaGetLastError(); + const double speed = std::max(1.0, (double) sms * (double) khz / 1e6); // SMs x GHz + layer_ms[(size_t) i] = 0.33 * (84.0 * 2.617) / speed; + std::fprintf(stderr, "strata generate: layer split auto: CUDA%d %d SMs at %.2f GHz -> %.2f ms per layer, " + "%.2f GiB free before its session carve\n", dev, sms, khz / 1e6, layer_ms[(size_t) i], + (double) cap[(size_t) i] / 1073741824.0); + } + const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0; + std::vector mass(profile.size()); + double total_mass = 0; + for (size_t r = 0; r < profile.size(); ++r) total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2)); + auto cost = [&](int64_t l) -> int64_t { + return native_pack ? ((int64_t) lay.blob_bytes(l) + 255) / 256 * 256 : (int64_t) lay.max_blob; + }; + // the predicted window time (ms) of a placement, and the routed mass its caches hold + auto predict = [&](const std::vector& at, double& held_mass, int64_t& held) -> double { + // THE CARVE, PRICED: a placement gives stage i the layers [lb, le), and that range's session is a + // real cost on its device - subtracted here so the search knows what it leaves for experts. This + // is why the sessions are allocated after the search: `session_bytes` is pure arithmetic. + std::vector capr((size_t) ns); + for (int i = 0; i < ns; ++i) { + const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1]; + const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers; + capr[(size_t) i] = cap[(size_t) i] - (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le); + } + std::fill(used.begin(), used.end(), 0); + held_mass = 0; + held = 0; + std::vector full((size_t) ns, false); + for (size_t r = 0; r < profile.size(); ++r) { + const int64_t l = profile[r].first; + int st = 0; + while (st + 1 < ns && l >= at[(size_t) st]) ++st; + if (full[(size_t) st]) continue; + if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill + used[(size_t) st] += cost(l); + held_mass += mass[r]; + ++held; + } + held_mass /= std::max(total_mass, 1e-9); + double ms = miss_ms * (1.0 - held_mass); + for (int i = 0; i < ns; ++i) { + const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers; + ms += (double) (le - lb) * layer_ms[(size_t) i]; + } + return ms; + }; + std::vector best, at((size_t) ns - 1); + double best_ms = 1e30, best_mass = 0; + int64_t best_held = 0; + auto consider = [&]() { + double hm = 0; + int64_t held = 0; + const double ms = predict(at, hm, held); + if (ms < best_ms) { best = at; best_ms = ms; best_mass = hm; best_held = held; } + }; + const int64_t L = g.n_layers; + if (ns == 2) { + for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); } + } else if (ns == 3) { + for (int64_t k1 = 2; k1 + 1 < L; ++k1) + for (int64_t k2 = k1 + 1; k2 < L; ++k2) { at[0] = k1; at[1] = k2; consider(); } + } else { + double total = 0; + for (const double c : layer_ms) total += 1.0 / c; + double acc = 0; + for (int i = 0; i + 1 < ns; ++i) { + acc += 1.0 / layer_ms[(size_t) i]; + at[(size_t) i] = std::clamp((int64_t) std::llround(acc / total * (double) L), + i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i)); + } + consider(); + } + split_at = best; + std::string ks; + for (const int64_t k : split_at) ks += (ks.empty() ? "" : ",") + std::to_string(k); + std::fprintf(stderr, "strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches " + "hold %lld of %zu profiled pairs (~%.1f%% of the routed mass)\n", ks.c_str(), best_ms, + (long long) best_held, profile.size(), 100.0 * best_mass); + } + for (size_t i = 0; i < split_at.size(); ++i) + if (split_at[i] >= g.n_layers) { + std::fprintf(stderr, "strata generate: --layer-split: layer %lld is past the last (%lld)\n", + (long long) split_at[i], (long long) (g.n_layers - 1)); + return 2; + } + // the stage that runs a layer (0: CUDA0's) + auto stage_of = [&](int64_t l) -> int { + int st = 0; + while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st; + return st; + }; + if (multi_gpu) { + std::vector> mine; + for (const auto& pr : profile) { + const int st = stage_of(pr.first); + (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr); + } + profile.swap(mine); + for (size_t i = 0; i < stages.size(); ++i) { + stages[i]->lb = split_at[i]; + stages[i]->le = i + 1 < stages.size() ? split_at[i + 1] : g.n_layers; + } + } + + // ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A + // stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage + // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR + // fixed in llama.cpp: allocation sized by the whole model instead of the device's own work. + { + const strata::core::OnDevice on0(0); + const int64_t hi0 = multi_gpu ? split_at[0] : -1; + if (cudaMalloc(&sbuf, strata::core::session_bytes(g, o.max_context, K, 0, hi0)) != cudaSuccess) { + std::fprintf(stderr, "strata generate: session state allocation failed\n"); + return 1; + } + if (strata::core::session_init(g, o.max_context, K, sbuf, ss, 0, hi0) == 0) { + std::fprintf(stderr, "strata generate: session_init failed\n"); + return 1; + } + if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) + std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " + "%.2f GiB of pinned RAM\n", + (long long) (ss.qsa_states[ss.qsa_primary()].n_slots * 4), + (long long) o.max_context, (double) strata::core::qsa_kv_host_bytes() / 1073741824.0); + // the PLE block above built everything but the history, which session_init has just carved + ss.ple.hist = ss.ple_hist; + // (#167) generate mode starts from an empty sequence, and nothing else zeroes this state before the prompt + // path or the verifier reads it (--serve zeroes it per request when nothing is reused) + strata::core::session_zero(ss, g, nullptr, main_cs); + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: zeroing the session state failed\n"); + return 1; + } + if (!o.ple_gguf.empty()) { + if (!ss.ple.ready()) { + std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n"); + return 1; + } + std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", + (unsigned long long) ple_table.rows(), + o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); + } + } + for (size_t i = 0; i < stages.size(); ++i) { + GpuStage& st = *stages[i]; + const strata::core::OnDevice on(st.dev); + void* sbuf_s = nullptr; + if (cudaMalloc(&sbuf_s, strata::core::session_bytes(g, o.max_context, K, st.lb, st.le)) != cudaSuccess || + strata::core::session_init(g, o.max_context, K, sbuf_s, st.ss, st.lb, st.le) == 0) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev); + return 1; + } + const bool last = i + 1 == stages.size(); + const strata::core::WeightRef* wo_s = st.wt.find("output.weight"); + if (wo_s == nullptr || + (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s\n", st.dev, + wo_s == nullptr ? "output.weight is missing" : err.c_str()); + return 1; + } + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights, session [%lld, %lld)%s; " + "%.2f GiB free\n", st.dev, (long long) st.lb, (long long) st.le, + last ? " and the head" : "", (double) fb / 1073741824.0); + } + + // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. + // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. + strata::core::MtpDrafter mtp; + if (!o.mtp.empty()) { + if (o.spec < 2) { + std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); + o.mtp.clear(); + } + if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size()); + // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, + // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference + static const strata::core::ModelGeometry draft_geometry{}; + // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device + const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1); + if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + } + // Create the additional contexts after MTP has secured CUDA0 memory, but + // before the host arena maps its expert pages into their address spaces. + for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) { + double free_gib = 0; + if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n", + remote_dev[r], free_gib); + } + + // ---- the CPU expert pool + // + // R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind + // `--mmap-experts` because it is the A/B arm, not because it is competitive. + // + // The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB + // file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether + // the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with + // the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is + // anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap + // and 3.7x better than the cold one. + // + // IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with + // "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is + // fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and + // CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands. + // + // The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale + // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the + // note in `pinned.cu`. + strata::core::FileExpertSource src; + { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel + // otherwise, after the whole expert arena has loaded) - before the arena starts loading + int dev = 0; + cudaDeviceProp p{}; + const bool named = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess; + if (!named) cudaGetLastError(); + const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)"; +#if defined(STRATA_USE_HIP) + std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?"); +#if defined(_WIN32) + // #468 #461: which HIP runtime was loaded - the bundled one beside the exe, or an AMD driver's System32 copy + if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) { + char path[MAX_PATH] = {}; + if (GetModuleFileNameA(h, path, MAX_PATH) > 0) + std::fprintf(stderr, "strata generate: HIP runtime %s\n", path); + } +#endif +#else + std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, + strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), + strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); +#endif + const std::string e = strata::core::device_code_error(); + if (!e.empty()) { + std::fprintf(stderr, "strata generate: this engine has no code for %s (sm_%d%d): %s - rebuild it for this " + "card (setup does: START-HERE.bat --setup)\n", name, p.major, p.minor, e.c_str()); + return 1; + } + } + strata::core::ArenaExpertSource arena_src; + strata::core::ExpertSource* srcp = nullptr; + if (o.mmap_experts) { + // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when + // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM + // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose + // GPU holds most of them but whose RAM cannot hold them all. + // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, + // checked against the files first) - no 30-77 GB copy of the experts on the disk + src.set_gguf(o.native_preset); + if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0) + src.set_fetch_threads(std::atoi(v)); + if (!src.open(o.pack, g.n_layers, g.n_expert, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n", + src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1"); + srcp = &src; + } else { + arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1 + // Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of + // mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation - + // measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain + // in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no + // such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways. + const int pin_env = strata::core::arena_pin_cap_gib(); // -1 unset, -2 "auto" (#243, Windows sliced pin) + const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm(); + const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0; + if (pin_env >= 0) + std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env, + pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped"); + else if (pin_wddm_cap) + std::fprintf(stderr, "strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned " + "(STRATA_ARENA_PIN_GIB changes it)\n"); + if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit, + o.shared_expert_arena)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str()); + std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n", + (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024), + arena_src.load_gib_per_second()); + // A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this + // read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the + // scheduler's defaults - Below normal priority and a least-privilege token - were the only + // difference between the runs). Say so instead of letting the user blame the disk; see + // docs/DETAILS.md, "Running it at startup (Task Scheduler)". +#ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk + if (arena_src.load_gib_per_second() > 0.0 && arena_src.load_gib_per_second() < 0.2) { + std::fprintf(stderr, + "strata generate: hint: ~24x below what this hardware streams from a normal " + "launch. If Strata is started by Task Scheduler or a service, register the task " + "with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's " + "defaults (Below normal + a least-privilege token) throttle the load. See " + "docs/DETAILS.md ('Running it at startup').\n"); + } +#endif + srcp = &arena_src; + } + strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity); + if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) { + const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" : + pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto"; + std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n", + pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str); + } + if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false); + // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` + // sees the memory this process actually has left rather than the card's idle figure - and refuses with both + // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. + mem_mark("the weights, the session and the drafter"); + strata::core::ExpertCache xcache; + // THE HEAD BEFORE THE CACHE. The expert cache takes what is free minus the reserve, so everything allocated + // after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after it and ate most of + // the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for good at its first + // verify window. Loaded first, the cache is sized around it. + const strata::core::WeightRef* wo = wt.find("output.weight"); + if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; } + const int64_t n_vocab = wo->ne1; + strata::core::NativeHead native_head; + if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage + if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: experimental native Q5_K head, %llu bytes\n", + (unsigned long long) native_head.weight_bytes()); + } + std::vector logits((size_t) n_vocab); + float* d_logits = nullptr; + if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the logits buffer failed\n"); + return 1; + } + const bool auto_cache = o.expert_cache < 0; + if (o.expert_cache < 0) { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + // Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - + // under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. + // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is + // the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one) + const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; + // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them + // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) + const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) + ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; + const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind; + int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob; + if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); + o.expert_cache = (int) std::max(slots, 0); + std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the " + "draft head) -> %d slots\n", + (double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache); + if (o.expert_cache == 0) // the verify window cannot start without it (#174): say what makes room + std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use " + "--kv k8v4, run images on the CPU, or close other programs that use the GPU\n"); + } else if (multi_gpu && o.expert_cache > 0) { + // an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt + // fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends + // slots instead and `prefill_mib` is 0, so only the reserve is checked) + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; + const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20; + const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); + if (o.expert_cache > fit) { + // a WARNING that names the knob: the user asked for this size, and gets fewer slots + std::fprintf(stderr, "strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " + "prompt path's buffers (%lld MiB) and the %d MiB reserve on CUDA0: %lld slots instead " + "(a smaller --vram-reserve-mib leaves more of them)\n", o.expert_cache, + (long long) prefill_mib, o.vram_reserve_mib, (long long) fit); + o.expert_cache = (int) fit; + } + } + // plan v0.3 P6: a native pack's blobs differ per layer, so with a profile its slots are sized per pair: the + // same VRAM holds ~30% more IQ3_XXS experts than slots of the largest blob would + // #369: not with --expert-cache-per-layer - its per-layer slot ranges ignore the profile rank a sized slot was cut + // for, so a layer's larger blob could land in a smaller slot: that mode keeps slots of the largest blob + std::vector sized_slots; + if (native_pack && o.expert_cache > 0 && !profile.empty() && !o.expert_cache_per_layer) { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const auto& lay = strata::kernels::cpu::expert_layout(); + const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted + uint64_t used = 0; + size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; + const uint64_t cap = std::min(budget, (uint64_t) free_room); + for (const auto& pr : profile) { + const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256; + if (used + b > cap) break; + used += b; + sized_slots.push_back((int64_t) lay.blob_bytes(pr.first)); + } + o.expert_cache = (int) sized_slots.size(); + } + if (o.expert_cache > 0) { + // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left + auto shrink_to = [&](int64_t keep_bytes) -> bool { + if (keep_bytes <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } + if (!sized_slots.empty()) { + int64_t used = 0; + size_t keep = 0; + while (keep < sized_slots.size() && used + (sized_slots[keep] + 255) / 256 * 256 <= keep_bytes) + used += (sized_slots[keep++] + 255) / 256 * 256; + sized_slots.resize(keep); + o.expert_cache = (int) keep; + } else { + o.expert_cache = (int) (keep_bytes / (int64_t) strata::kernels::cpu::expert_layout().max_blob); + } + if (o.expert_cache <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; } + return true; + }; + auto cache_bytes = [&]() -> int64_t { + if (sized_slots.empty()) return (int64_t) o.expert_cache * (int64_t) strata::kernels::cpu::expert_layout().max_blob; + int64_t b = 0; + for (const int64_t s : sized_slots) b += (s + 255) / 256 * 256; + return b; + }; + // With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an + // allocation is not resident until it is touched, and the free figure read before it can be ~1 GB too + // high. A cache sized from it filled the card to 0 MiB, the driver then paged, and a request that needed a + // page back while the verify graph spun on a host flag never finished. So the slots are zeroed and the + // free figure read again; while it is short of the reserve the cache is reopened smaller. + // STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry) + int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0; + int failed = 0; + int zero_reads = 0; + for (int attempt = 0;; ++attempt) { + bool ok = false; + if (fake_fails > 0) { + --fake_fails; + err = "ExpertCache: cudaMalloc failed: out of memory (STRATA_TEST_CACHE_FAIL)"; + } else { + ok = sized_slots.empty() + ? xcache.open(o.expert_cache, g.n_layers, g.n_expert, (int64_t) strata::kernels::cpu::expert_layout().max_blob, err) + : xcache.open_sized(sized_slots, g.n_layers, g.n_expert, err); + } + if (!ok) { + // Issue #60: on Windows a device allocation is also charged to the system commit (RAM + page file), + // so with a small page file the cache's one big cudaMalloc fails while the VRAM is free. An auto + // cache then tries three quarters of the size, a few times, instead of stopping the engine. + char commit[96] = ""; +#if defined(_WIN32) + MEMORYSTATUSEX ms{}; + ms.dwLength = sizeof ms; + if (GlobalMemoryStatusEx(&ms)) + std::snprintf(commit, sizeof commit, " (Windows has %.1f GiB of commit left: RAM + page file)", + (double) ms.ullAvailPageFile / 1073741824.0); +#endif + if (auto_cache && failed < 8 && shrink_to(cache_bytes() / 4 * 3)) { + ++failed; + std::fprintf(stderr, "strata generate: %s%s; trying a smaller expert cache: %d slots\n", err.c_str(), + commit, o.expert_cache); + continue; + } + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); +#if defined(_WIN32) + std::fprintf(stderr, "strata generate: on Windows the graphics card's memory also needs room in the page " + "file: set it to \"System managed\" (System > About > Advanced system settings > " + "Performance > Advanced > Virtual memory), or lower --expert-cache\n"); +#endif + return 1; + } + if (!auto_cache || attempt - failed >= 6) break; + cudaMemset(xcache.device_slot(0), 0, (size_t) xcache.bytes()); + cudaDeviceSynchronize(); + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const int64_t want = (int64_t) o.vram_reserve_mib << 20; + if ((int64_t) free_b >= want - (64ll << 20)) break; + // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB + // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter + int64_t give = want - (int64_t) free_b + (64ll << 20); + if (free_b < ((size_t) 16 << 20)) + give = std::max(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4); + const int64_t keep_bytes = xcache.bytes() - give; + std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " + "shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib); + xcache.close(); + if (!shrink_to(keep_bytes)) break; + } + if (failed > 0 && o.expert_cache > 0) + std::fprintf(stderr, "strata generate: expert cache: %d slots (%.2f GiB) after %d smaller tries - a bigger " + "page file lets it use more of the free VRAM\n", + o.expert_cache, (double) xcache.bytes() / 1073741824.0, failed); + } + if (o.expert_cache > 0) { + std::fprintf(stderr, "strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n", + (long long) xcache.slots(), xcache.gib()); + mem_mark("opening the expert cache"); + xcache.set_per_layer_admission(o.expert_cache_per_layer); + // Round 328 warned here that the GPU hit path was wrong (tokens diverged from a cache-off run from + // token 0). That fault was fixed long since (native_expert_parity, expert_parity, the grouped kernels' + // tests), and the warning outlived it (issue #23). What remains is rounding: a GPU expert and the CPU's + // compute the same quantized expert with different float order, so a near-tie can flip. Measured teacher- + // forced on 2,557 tokens (bench/results/2026-09-27-cache-parity): 95-98% same top-1, and perplexity equal + // (on - off = -0.005 +- 0.005 nats). Neither output is more correct than the other. + std::fprintf(stderr, + "strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU,\n" + " so a reply can differ slightly from a run without the cache (same quality:\n" + " bench/results/2026-09-27-cache-parity).\n"); + if (o.expert_cache_per_layer) { + int64_t lo = 0, hi = 0; + xcache.layer_slot_range(0, lo, hi); + std::fprintf(stderr, " R4.2g PER-LAYER: each layer owns %lld slots (%lld..%lld).\n", + (long long) (hi - lo), (long long) lo, (long long) (hi - 1)); + } else if (profile.empty()) { + std::fprintf(stderr, " compulsory-miss (fills with whatever the run routes first).\n"); + } else { + std::fprintf(stderr, " PROFILE, ranked by routing frequency, no eviction.\n"); + } + } + // ---- R4.2e: fill the tier from the profile. This is the only place the plan is applied, and it runs + // ONCE: with `slots` pairs and `slots` slots the cache is full when this returns, so the decode-time + // admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile + // the policy rather than a hint. + int64_t prefilled = 0; + if (!profile.empty() && srcp != nullptr) { + // #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until + // its range is full (one full layer used to end the whole fill, leaving most layers empty) + const bool per_layer = xcache.per_layer_admission(); + const int64_t want = per_layer ? (int64_t) profile.size() + : std::min((int64_t) profile.size(), xcache.slots()); + for (int64_t i = 0; i < want; ++i) { + const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second); + if (slot == strata::core::kNotResident) { + if (per_layer) continue; + break; + } + const uint8_t* b = srcp->blob(profile[(size_t) i].first, profile[(size_t) i].second); + if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) { + std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n", + (long long) i, err.c_str()); + return 1; + } + ++prefilled; + } + // **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong + // about bytes produces a plausible token, which is this project's most expensive failure mode; the + // cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. + if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second), + srcp->blob(profile[0].first, profile[0].second), err, + (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + mem_mark("the profile fill"); + std::fprintf(stderr, "strata generate: pre-filled %lld of %lld slots from the profile; slot 0 verified\n", + (long long) prefilled, (long long) (per_layer ? xcache.slots() : want)); + } + + for (auto& stp : stages) { + GpuStage& st = *stp; + const auto& lay = strata::kernels::cpu::expert_layout(); + // the drafter and the head are already allocated by now (they load above, before this), so what is left + // to hold back is the windows - and `free_b` has already lost the drafter. + const int64_t room = stage_room(st.dev, true, false); + const strata::core::OnDevice on(st.dev); + std::vector sized; + int64_t used = 0; + for (const auto& pr : st.profile) { + const int64_t b = native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; + if (used + b > room) break; + used += b; + sized.push_back((int64_t) lay.blob_bytes(pr.first)); + } + if (sized.empty() || + !(native_pack ? st.cache.open_sized(sized, g.n_layers, g.n_expert, err) + : st.cache.open((int64_t) sized.size(), g.n_layers, g.n_expert, (int64_t) lay.max_blob, err))) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, + sized.empty() ? "no room" : err.c_str()); + return 1; + } + int64_t filled = 0; + for (const auto& pr : st.profile) { + if (filled >= st.cache.slots()) break; + const int32_t slot = st.cache.admit(pr.first, pr.second); + if (slot == strata::core::kNotResident) break; + const uint8_t* b = srcp->blob(pr.first, pr.second); + if (b == nullptr || !st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n", + st.dev, (long long) filled, err.c_str()); + return 1; + } + ++filled; + } + if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second), + srcp->blob(st.profile[0].first, st.profile[0].second), err, + (int64_t) lay.blob_bytes(st.profile[0].first))) { + std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev, + filled == 0 ? "nothing filled" : err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " + "(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n", + st.dev, (long long) st.lb, (long long) (st.le - 1), (long long) st.cache.slots(), st.cache.gib(), + (long long) filled, st.profile.size()); + } + if (multi_gpu) + std::fprintf(stderr, "strata generate: layer split: CUDA0 runs layers 0-%lld\n", (long long) (split_at[0] - 1)); + + std::array remote_experts; + const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; + if (o.expert_cache_remote[0] > 0) { + if (o.expert_cache <= 0 || profile.empty() || o.no_pool) { + std::fprintf(stderr, "strata generate: remote experts need --expert-profile, " + "a CUDA0 expert cache and the expert pool\n"); + return 2; + } + std::vector> ranked = profile; + if (!stages.empty()) { // a layer split: CUDA0's share of the profile, then the later stages' pairs no cache holds + for (auto& st : stages) + for (const auto& pr : st->profile) + if (st->cache.slot_of(pr.first, pr.second) < 0) ranked.push_back(pr); + } + if (multi_remote) { + // The shipped frequency profile names only 8000 of 24576 experts. Once exhausted, + // fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads + // the tail across all layers instead of concentrating it on layer zero. + std::vector seen((size_t) g.n_layers * (size_t) g.n_expert, 0); + for (const auto& pair : ranked) + if (pair.first >= 0 && pair.first < g.n_layers && pair.second >= 0 && pair.second < g.n_expert) + seen[(size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second] = 1; + for (int64_t e = 0; e < g.n_expert; ++e) + for (int64_t l = 0; l < g.n_layers; ++l) + if (!seen[(size_t) l * (size_t) g.n_expert + (size_t) e]) + ranked.emplace_back((int32_t) l, (int32_t) e); + std::fprintf(stderr, "strata generate: remote ranking: %zu profiled pairs, " + "%zu other pairs to fill CUDA1..3\n", profile.size(), ranked.size() - profile.size()); + } + std::array>, 3> by_device; + if (multi_remote) { + // Either stripe experts for parallel GPU work, or give each layer one + // secondary GPU to reduce switches and transfers over shared USB4. + std::vector assigned((size_t) g.n_layers * (size_t) g.n_expert, 0); + const int devices = 1 + (o.expert_cache_remote[1] > 0) + (o.expert_cache_remote[2] > 0); + int next = 0; + for (const auto& pair : ranked) { + if (pair.first < 0 || pair.first >= g.n_layers || pair.second < 0 || pair.second >= g.n_expert || + xcache.slot_of(pair.first, pair.second) >= 0) continue; + const size_t index = (size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second; + if (assigned[index]) continue; + int target = -1; + if (o.expert_cache_remote_placement == "layer") { + target = pair.first % devices; + // Other layers' owners may still have room: keep scanning ranks. + if (by_device[(size_t) target].size() >= + (size_t) o.expert_cache_remote[(size_t) target]) continue; + } else { + for (int i = 0; i < devices; ++i) { + const int r = (next + i) % devices; + if (by_device[(size_t) r].size() < (size_t) o.expert_cache_remote[(size_t) r]) { + target = r; + break; + } + } + if (target < 0) break; + } + assigned[index] = 1; + by_device[(size_t) target].push_back(pair); + next = (target + 1) % devices; + } + std::fprintf(stderr, "strata generate: remote ranks %s across %d CUDA devices\n", + o.expert_cache_remote_placement == "layer" ? "grouped by layer" : "striped", devices); + } else { + by_device[0] = std::move(ranked); + } + std::vector claimed((size_t) g.n_layers * (size_t) g.n_expert, 0); + for (auto& st : stages) // a layer split: what a stage's cache holds is no helper's + for (const auto& pr : st->profile) + if (st->cache.slot_of(pr.first, pr.second) >= 0) + claimed[(size_t) pr.first * (size_t) g.n_expert + (size_t) pr.second] = 1; + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) { + if (!remote_experts[(size_t) r].open(remote_dev[r], o.expert_cache_remote[(size_t) r], + g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: CUDA%d: %lld additional experts, %.2f GiB; " + "results return through pinned host rows\n", remote_dev[r], + (long long) remote_experts[(size_t) r].resident(), remote_experts[(size_t) r].gib()); + } + } + + Drive drive; +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + if (kar_expert_archive != nullptr) { + drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; + drive.d.experimental_miss_user = &kar_expert_miss; + } +#endif + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r]; + drive.d.hit_cpu_order = o.expert_cache_cpu_order; + drive.d.split_rows = !o.no_split_rows; + drive.d.pool = &pool; + drive.d.src = srcp; + drive.d.n_expert = g.n_expert; + drive.d.jobs.resize((size_t) K); + // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE + // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is + // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). + strata::core::RouterLookahead lookahead; + if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { + std::vector> routers((size_t) g.n_layers); + bool ok = true; + for (int64_t l = 0; l < g.n_layers && ok; ++l) { + const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight"); + ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 && + w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2; + if (!ok) break; + routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd)); + ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; + } + const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); + if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) { + drive.d.lookahead = &lookahead; + std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n"); + } else { + (void) cudaGetLastError(); + std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", + ok ? err.c_str() : "the routers are not BF16 in the arena"); + err.clear(); + } + } + // ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on + // purpose: a half-configured hit path would compute some experts twice and others not at all, and a token + // built on that is wrong rather than refused. + void* hit_scratch = nullptr; + int32_t* d_hit_slot = nullptr; + int32_t* d_hit_dst = nullptr; + uint8_t* d_hit_q8 = nullptr; + float* d_hit_q8_scale = nullptr; ///< R4.2h: the fp32 activation scales the CPU path also uses + float* d_hit_out = nullptr; + if (o.expert_cache > 0 && !o.no_pool) { + const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes(K, g.n_embd, strata::kernels::cpu::FF); + if (cudaMalloc(&hit_scratch, (size_t) sb) != cudaSuccess || + cudaMalloc((void**) &d_hit_slot, (size_t) K * sizeof(int32_t)) != cudaSuccess || + cudaMalloc((void**) &d_hit_dst, (size_t) K * sizeof(int32_t)) != cudaSuccess || + cudaMalloc((void**) &d_hit_q8, (size_t) (g.n_embd / 32) * 34) != cudaSuccess || + // R4.2h: the fp32 activation scales. Without this the GPU's hits use the block's fp16 `d` + // while the CPU's misses use `ActQ::scale`, which is fp32 - a 4.761e-04 relative disagreement on + // every chunk, and the reason enabling the cache changed the tokens. + cudaMalloc((void**) &d_hit_q8_scale, (size_t) (g.n_embd / 32) * sizeof(float)) != cudaSuccess || + cudaMalloc((void**) &d_hit_out, (size_t) K * g.n_embd * 4) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the R4 hit path could not allocate its device buffers\n"); + return 1; + } + drive.d.cache = &xcache; + drive.d.cache_stream = main_cs; + drive.d.cache_base = (const uint8_t*) xcache.device_slot(0); + drive.d.cache_blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + drive.d.cache_slot_off = xcache.slot_offsets(); + drive.d.hit_scratch = hit_scratch; + drive.d.parts_out = d_parts; + drive.d.hit_out = d_hit_out; + drive.d.parts_elems = K * g.n_embd; + drive.d.mixed = ss.block.mixed; + drive.d.x_q8_0_hit = d_hit_q8; + drive.d.x_q8_0_hit_scale = d_hit_q8_scale; + drive.d.d_slot = d_hit_slot; + drive.d.d_dst = d_hit_dst; + drive.d.h_slot.resize((size_t) K); + cudaEvent_t hit_done = nullptr; + if (cudaEventCreate(&hit_done) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the hit path could not create its probe event\n"); + return 1; + } + drive.d.hit_done = (void*) hit_done; + drive.d.hit_poke = !o.no_hit_poke; + drive.d.h_dst.resize((size_t) K); + mem_mark("the R4 hit path"); + std::fprintf(stderr, "strata generate: R4 hit path ON - resident experts are computed on the GPU\n"); + } + // ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through + // the doorbell that the pool consumes - so `--no-pool` is refused rather than silently producing an empty + // file that would read as "the router selected nothing". + // ---- PER-STAGE TIMING. `--no-capture` only: an event recorded inside a stream capture is silently + // dropped, so a captured graph cannot carry these events and the numbers would be zeros that read as + // "every stage is free". Refusing is the fix. + if (o.stage_timing) { + if (!o.no_capture) { + std::fprintf(stderr, "strata generate: --stage-timing records CUDA events inside the layer path, " + "and an event record inside a stream capture is silently dropped. Pass " + "--no-capture as well.\n"); + return 2; + } + if (!strata::core::stage_timing_enable()) { + std::fprintf(stderr, "strata generate: stage_timing_enable failed\n"); + return 1; + } + strata::core::stage_timing_name(0, "gr_read (attn)"); + strata::core::stage_timing_name(1, "attention block"); + strata::core::stage_timing_name(2, "gr_write (attn)"); + strata::core::stage_timing_name(3, "gr_read (ffn)"); + strata::core::stage_timing_name(4, "moe_route"); + strata::core::stage_timing_name(5, "moe_finish"); + strata::core::stage_timing_name(6, "gr_write (ffn)"); + // The GDN block's internals. It is 36 of the 48 layers, 0.96 ms each, and its entire weight traffic + // is ~26 MB - so ~0.11 ms at the measured read rate. ~13 tiny latency-bound launches live in it and + // a single "attention block" number cannot say which one costs anything. + strata::core::stage_timing_name(8, " gdn: quantize x"); + strata::core::stage_timing_name(9, " gdn: qkv gemv"); + strata::core::stage_timing_name(10, " gdn: conv+silu"); + strata::core::stage_timing_name(11, " gdn: l2 norms"); + strata::core::stage_timing_name(12, " gdn: alpha/beta/gate"); + strata::core::stage_timing_name(13, " gdn: gdn_step"); + strata::core::stage_timing_name(14, " gdn: z + out_norm"); + strata::core::stage_timing_name(15, " gdn: out gemv"); + } + std::FILE* routing = nullptr; + if (!o.dump_routing.empty()) { + if (o.no_pool) { + std::fprintf(stderr, "strata generate: --dump-routing needs the expert pool; the routed ids reach " + "the host through the doorbell the pool reads. Drop --no-pool.\n"); + return 2; + } + routing = std::fopen(o.dump_routing.c_str(), "wb"); + if (routing == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_routing.c_str()); + return 1; + } + drive.routing = routing; + } + strata::core::PoolFn pool_fn = o.no_pool ? nullptr : &drive_pool; + // The hit hook rides the same switch as the pool: with no pool there is no `parts` staging to + // write into, and a hit path with nowhere to write is a wrong token rather than an error. + strata::core::HitFn hit_fn = + (o.no_pool || o.expert_cache <= 0) ? nullptr : &strata::core::expert_hit_run; + void* pool_user = o.no_pool ? nullptr : (void*) &drive; + std::fprintf(stderr, "strata generate: %d expert-pool workers%s%s\n", pool.workers(), + pool.host_works() ? " + the host thread" : "", + o.no_pool ? " (UNUSED: --no-pool)" : ""); + + // **THE MISALIGNMENT WARNING THAT STOOD HERE IS GONE, BECAUSE THE MISALIGNMENT IS FIXED.** + // + // It said the tokens were not the model's, and it was true: `session_loop` handed layer `l`'s expert + // outputs to layer `l+1`, which multiplied them by layer `l+1`'s router weights (LEDGER L100). The loop + // now runs a captured PAIR per layer - `pre[l]` ending with the router and the doorbell, then the CPU + // pool, then `post[l]` which combines those experts with THAT layer's weights - so layer `l`'s experts meet + // layer `l`'s routing. The generated ids changed the moment it landed, which is what a correctness fix + // looks like from the outside. + // + // The cost is real and is recorded rather than hidden: the window for the CPU pool is now whatever GPU + // work follows the ring inside `pre[l]`, which is the shared expert and nothing else - 0.038 ms against + // 0.514 ms of CPU work per layer. A per-layer CPU expert pool cannot be hidden behind a strictly serial + // residual chain; the CPU term is answered by Phase 3's VRAM expert cache, not by this pipeline. + + // ---- the graphs + strata::core::SessionGraphs gr; + if (!o.no_capture && !native_pack) { // plan v0.3 P6: a native pack runs verify windows only + // a layer split's CUDA0 session owns only [0, split_at[0]), so its graphs cover that range; the + // whole-model replay paths (`session_loop`, the plain generate loop) refuse rather than read another + // stage's state - a split runs its layers on the stages' verifiers (serve) or prefill stage chain + if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages, 0, + multi_gpu ? split_at[0] : -1)) { + std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str()); + return 1; + } + } + + // **`--no-capture` AND THE EXPERTS ARE MUTUALLY EXCLUSIVE, AND SILENTLY SO.** + // + // The CPU expert pool is wired into `session_loop` - the host loop around the captured graphs - and + // `session_token` has no pool hook at all. So `--no-capture` did not merely change HOW the layers were + // launched: it ran the whole model with `parts` left at whatever the buffer held, which is ZERO, and the + // only symptom was `expert blobs 0` in a stats line nobody had to read. A run that silently omits the + // routed experts is not a slow measurement of this model, it is a measurement of a different model. + // + // Refusing is the fix. `--no-pool` is the explicit way to say "I want the GPU-only floor". + if (o.no_capture && !o.no_pool) { + std::fprintf(stderr, + "strata generate: --no-capture runs `session_token`, which has NO CPU expert pool hook, so " + "the routed experts would silently contribute nothing. Pass --no-pool as well if the " + "GPU-only floor is what you want.\n"); + return 2; + } + // The ladder is written by `session_loop`, and `session_token` does not touch the staging buffer at all - so + // accepting the flag there would produce a file of uninitialised memory, which reads as a wrong answer rather + // than as a mistake. `--no-capture` without `--no-pool` is already refused above, so this catches the pair. + if (o.no_capture && !o.dump_layers.empty()) { + std::fprintf(stderr, + "strata generate: --dump-layers is written by `session_loop`; `--no-capture` runs " + "`session_token` instead, which never fills the staging buffer. Drop one of the two.\n"); + return 2; + } + if (o.no_capture && !o.dump_halves.empty()) { + std::fprintf(stderr, + "strata generate: --dump-halves is CAPTURED into the layer graphs, so it needs the " + "captured path; `--no-capture` never records it. Drop one of the two.\n"); + return 2; + } + + mem_mark("the expert cache and the graphs"); + std::fprintf(stderr, "strata generate: session is up (engine %s)\n", STRATA_VERSION); + auto run_head = [&](void* stream) -> bool { + if (!native_head.loaded()) + return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err); + return strata::core::lm_head_mix(wt, g, ss.block, stream, err) && + native_head.run(ss.block.mixed, d_logits, stream, err); + }; + float* d_emb = nullptr; + if (cudaMalloc(&d_emb, (size_t) g.n_embd * 4) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the embedding buffer failed\n"); + return 1; + } + // **`sample_tokens` TAKES DEVICE POINTERS.** It is a kernel launch; `logits` and `out` are both read and + // written on the device. Passing `logits.data()` - the host vector - faults inside the kernel and the + // error surfaces at the NEXT synchronising call, which here was the next token's `embed_row`, reporting an + // illegal access on a weight plane. Nothing in the parameter names said device. + int* d_next = nullptr; + if (cudaMalloc(&d_next, sizeof(int)) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the sampler output buffer failed\n"); + return 1; + } + + // **`R` IS BOTH THE INPUT AND THE OUTPUT, SO THE NEW TOKEN'S EMBEDDING HAS TO REPLACE THE OLD RESIDUAL.** + // At `pos == 0` that is `session_zero`, which is the reference's own initial condition - the embedding + // broadcast to all `hc` streams. After that `session_zero` would also wipe the recurrence, so the + // broadcast is done directly. Getting this wrong is invisible for exactly one token. + void* token_stream = o.stream_token ? main_cs : nullptr; + auto put_input = [&](int64_t tok, int64_t pos) -> bool { + if (!strata::core::embed_row(wt, g, tok, d_emb, token_stream, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return false; + } + if (pos == 0) { + strata::core::session_zero(ss, g, d_emb, token_stream); + } else { + for (int64_t c = 0; c < g.hc; ++c) + if (cudaMemcpyAsync(ss.R + (size_t) c * g.n_embd, d_emb, (size_t) g.n_embd * 4, + cudaMemcpyDeviceToDevice, (cudaStream_t) token_stream) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the residual broadcast failed\n"); + return false; + } + } + return o.stream_token || cudaDeviceSynchronize() == cudaSuccess; + }; + + strata::kernels::SamplerParams sp; + sp.greedy = o.greedy; + sp.seed = o.seed; + sp.top_k = o.top_k; + sp.top_p = o.top_p; + sp.temperature = o.temperature; + // what this run actually samples with (the speculative loop below gets the same parameters); serve samples + // per request instead + if (!o.serve) { + if (sp.greedy || sp.temperature <= 0.0f) + std::fprintf(stderr, "strata generate: sampling greedy\n"); + else + std::fprintf(stderr, "strata generate: sampling temperature=%g top_k=%d top_p=%g seed=%llu\n", + (double) sp.temperature, sp.top_k > 0 && sp.top_k < 64 ? sp.top_k : 64, (double) sp.top_p, + (unsigned long long) sp.seed); + } + + std::FILE* dump = nullptr; + const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new; + if (!o.dump_logits.empty()) { + if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) { + std::fprintf(stderr, "strata generate: logits dump dimensions exceed int32\n"); + return 2; + } + dump = std::fopen(o.dump_logits.c_str(), "wb"); + if (dump == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_logits.c_str()); + return 1; + } + // **THE COUNT IS `n_prompt - 1 + max_new`, NOT `n_prompt + max_new`.** The loop writes one row per + // position from 0, and it stops once `produced` holds `max_new` tokens - and `produced` only starts + // receiving at position `n_prompt - 1`. So a 5-token prompt with `--max-new 6` writes 10 rows, and the + // header used to claim 11. A header that describes a different file from the one written is the same + // class of defect as a self-check that verifies the wrong invariant: anything reading the count instead + // of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by + // parsing the header and refusing the file. + const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride); + const int32_t hdr[2] = {(int32_t) n_vocab, n_rows}; + if (std::fwrite(hdr, sizeof hdr, 1, dump) != 1) { + std::fprintf(stderr, "strata generate: cannot write logits header\n"); + std::fclose(dump); + return 1; + } + } + + // ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against + // `llama-debug`'s `l_last-` node instead of against a single end-to-end perplexity. The buffer is + // PINNED because `session_loop` enqueues a device-to-host copy into it after every layer and the transfer + // would otherwise be staged through a pageable bounce buffer on the critical path. + std::FILE* layer_dump = nullptr; + float* layer_stage = nullptr; + const size_t layer_floats = (size_t) (g.n_layers + 1) * (size_t) g.hc * (size_t) g.n_embd; + if (!o.dump_layers.empty()) { + layer_dump = std::fopen(o.dump_layers.c_str(), "wb"); + if (layer_dump == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_layers.c_str()); + return 1; + } + if (cudaHostAlloc((void**) &layer_stage, layer_floats * sizeof(float), cudaHostAllocDefault) != + cudaSuccess) { + std::fprintf(stderr, "strata generate: cannot pin the layer-dump staging buffer\n"); + return 1; + } + } + + // ---- prefill is the DECODE PATH ONE TOKEN AT A TIME, which `phase-2-correct-engine.md:12-13` says is + // fine here: "process the prompt through the decode-style graphs in small batches; a 19K-token prompt will + // take minutes". A real batched prefill is P2.S6's other half and is not this. + // + // **THE LOOP IS `feed -> 48 layers -> head -> sample -> feed`, AND THE FIRST GENERATED TOKEN COMES FROM THE + // LAST *PROMPT* POSITION.** The first version sampled only on the decode positions, so `produced` was + // still empty when the first generated position asked for `produced.back()` - an out-of-bounds read on an + // empty vector. Teacher forcing below is what makes the distinction unnecessary to special-case: for every + // position before the last prompt one, the next input is the PROMPT's next token, and after that it is the + // sampled one. + std::vector produced; + double total_ms = 0; + double prefill_ms = 0; // positions 0 .. n_prompt-2: prompt tokens that only condition + const Clock::time_point t_start = Clock::now(); + double ttft_ms = 0; + const int64_t n_prompt = (int64_t) o.tokens.size(); + int64_t tok = o.tokens[0]; + + // ---- THE PURE-GPU MEASUREMENT. `session_replay` launches all 48 `pre` graphs back to back on one stream + // with NO host work between them - no doorbell poll, no pool, no parts copy - so what it times is the GPU + // executing the layer sequence and nothing else. It had been declared, defined and never called since the + // day it was written. + // + // **THIS IS THE MEASUREMENT THAT SAYS WHETHER THE ENGINE IS HOST-BOUND OR GPU-BOUND**, and the stage table + // cannot answer it: those events measure the interval between two marks on a stream, which includes every + // gap where the GPU sat idle waiting for the host to enqueue the next kernel. In `--no-capture` those gaps + // are the host's launch latency and they are proportional to the KERNEL COUNT rather than to any work, so + // the no-capture stage shares are shares of kernel count - which is why the attention block, with the most + // kernels, looks like 55% of the token there. + // ---- R0.9: THE PER-STAGE TABLE ON THE CAPTURED GRAPH. + if (o.gpu_stages) { + strata::core::doorbell_reset(db); + double mix = 0, ffn = 0, post = 0; + if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + const int reps = 20; + double t_mix = 0, t_ffn = 0, t_post = 0; + for (int r = 0; r < reps; ++r) { + if (!strata::core::session_replay_stages(g, 0, 0, ss, gr, main_cs, mix, ffn, post, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + t_mix += mix; + t_ffn += ffn; + t_post += post; + } + const double tot = t_mix + t_ffn + t_post; + std::printf("\nper-stage GPU time on the CAPTURED graph, one token over %lld layers\n", + (long long) g.n_layers); + std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "mixer (gr_read+attn+gr_write)", + t_mix / reps, t_mix / reps / (double) g.n_layers, 100.0 * t_mix / tot); + std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "ffn front + router", + t_ffn / reps, t_ffn / reps / (double) g.n_layers, 100.0 * t_ffn / tot); + std::printf(" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n", "post (moe_finish+gr_write)", + t_post / reps, t_post / reps / (double) g.n_layers, 100.0 * t_post / tot); + std::printf(" %-22s %9.3f ms/token\n", "sum of the three", tot / reps); + + // ---- AND THE MIXER BY LAYER KIND, because 36 of the 48 are GDN and 12 are QSA and a total cannot + // separate them. Round 309's uncaptured table put GDN at 10.88 ms for 36 layers against QSA's 4.56 for + // 12, which would make the recurrence the largest single R3 target - and that table had `moe_finish` + // wrong by 4x, so the ratio is re-derived here from the captured graph rather than inherited. + { + // **ACCUMULATED OVER `reps`, NOT MEASURED ONCE AND THEN DIVIDED.** The first version called the + // per-layer replay a single time and printed `gdn / reps`, which reported GDN at 0.480 ms/token + // against a mixer total of 14.039 - a factor of exactly `reps`, and the tell was that + // 0.480 + 0.220 = 0.700 = 14.039 / 20. + std::vector acc((size_t) g.n_layers, 0.0), per; + double f2 = 0, p2 = 0; + for (int r = 0; r < reps; ++r) { + if (!strata::core::session_replay_stages_per_layer(g, 0, 0, ss, gr, main_cs, per, f2, p2, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + for (int64_t l = 0; l < g.n_layers; ++l) acc[(size_t) l] += per[(size_t) l]; + } + double gdn = 0, qsa = 0, worst = 0; + int64_t ng = 0, nq = 0, worst_l = 0; + for (int64_t l = 0; l < g.n_layers; ++l) { + const double v = acc[(size_t) l] / reps; + if (strata::core::is_qsa_layer(g, l)) { qsa += v; ++nq; } + else { gdn += v; ++ng; } + if (v > worst) { worst = v; worst_l = l; } + } + std::printf("\n the mixer by layer kind, averaged over %d runs\n", reps); + std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "GDN layers", + gdn, ng ? gdn / (double) ng : 0.0, (long long) ng); + std::printf(" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n", "QSA layers", + qsa, nq ? qsa / (double) nq : 0.0, (long long) nq); + std::printf(" %-22s layer %lld at %.3f ms\n", "worst mixer layer", (long long) worst_l, worst); + std::printf(" %-22s %9.3f ms/token (must equal the mixer above)\n", "GDN + QSA", gdn + qsa); + } + + // ================================ R0.11: THE FIVE STAGES SEPARATELY ================================ + // + // Prefixes 1..5 are replayed per layer with the residual restored between them, and consecutive + // differences are the per-stage times. **THE CHECK IS THAT THE FIVE SUM TO THE THREE-GRAPH TOTAL** - + // the same independent-restatement test that caught round 320's divide-by-reps bug, and it is the only + // reason to believe a table built out of differences. + { + std::vector acc5(5, 0.0), per, s5; + for (int r = 0; r < reps; ++r) { + if (!strata::core::session_replay_stage_prefixes(g, 0, 0, ss, gr, main_cs, s5, per, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + for (int k = 0; k < 5; ++k) acc5[(size_t) k] += s5[(size_t) k]; + } + static const char* sn[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", + "3 gr_read (ffn)", "4 moe_route (router)"}; + const char* kind[5] = {"GR", "ATTN", "GR", "GR", "ROUTER"}; + double tot5 = 0, gr_ms = 0; + std::printf("\n the five stages separately, by differencing prefixes\n"); + std::printf(" %-24s %-8s %10s %10s %8s\n", "stage", "kind", "ms/token", "ms/layer", "share"); + for (int k = 0; k < 5; ++k) { + const double v = acc5[(size_t) k] / reps; + tot5 += v; + if (k != 1 && k != 4) gr_ms += v; + std::printf(" %-24s %-8s %10.3f %10.4f %7.1f%%\n", sn[k], kind[k], v, + v / (double) g.n_layers, 0.0); + } + for (int k = 0; k < 5; ++k) { + const double v = acc5[(size_t) k] / reps; + (void) v; + } + std::printf(" %-24s %-8s %10.3f\n", "sum of the five", "", tot5); + std::printf(" %-24s %-8s %10.3f <- R3.3's target is <= 3 ms for all four passes\n", + "GR passes (0,2,3)", "GR", gr_ms); + std::printf("\n the three-graph total above was %.3f ms/token; the five must account for it.\n", + tot / reps); + + // ================================ R3.5c: THE SAME TABLE, A DIFFERENT WAY ================================ + // + // The differencing table above mixes five graphs per layer, so stage 4's interval carries the launch + // of the FULL five-stage graph while stage 3's carries a four-stage one. This sweep launches ONE + // graph type per layer and nothing else, so that bias cannot exist. **If the two disagree, the + // difference IS the bias and this one is right** - and stage 4 is the router, so it is exactly the + // number that must not be wrong. + { + double sweep[6] = {0, 0, 0, 0, 0, 0}; + for (int k = 1; k <= 5; ++k) { + double acc = 0, one = 0; + for (int r = 0; r < reps; ++r) { + if (!strata::core::session_replay_stage_sweep(g, 0, 0, ss, gr, main_cs, k, one, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + acc += one; + } + sweep[k] = acc / reps; + } + std::printf("\n the same five stages, by SWEEPING each prefix back to back (no graph switching)\n"); + std::printf(" %-24s %10s %10s %12s\n", "stage", "prefix sweep", "difference", "bias"); + static const char* sn2[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)", + "3 gr_read (ffn)", "4 moe_route (router)"}; + for (int k = 0; k < 5; ++k) { + const double sw = sweep[k + 1] - sweep[k]; + const double df = acc5[(size_t) k] / reps; + std::printf(" %-24s %10.3f %10.3f %11.1f%%\n", sn2[k], sw, df, + sw != 0.0 ? 100.0 * (df / sw - 1.0) : 0.0); + } + std::printf(" %-24s %10.3f (full pre, 48 layers)\n", "prefix 5 total", sweep[5]); + } + } + std::printf("\n compare `--gpu-only-full`, which replays the same work as TWO graphs per layer. The\n"); + std::printf(" three sum slightly above it because each launch carries the driver's gap.\n"); + strata::core::session_graphs_free(gr); + strata::core::doorbell_free(db); + cudaFree(d_next); + return 0; + } + + if (o.graph_only) { + strata::core::doorbell_reset(db); + // one warm pass so the first launch does not pay for page mapping + if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { + std::fprintf(stderr, "strata generate: session_replay warm: %s\n", err.c_str()); + return 1; + } + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: session_replay warm faulted\n"); + return 1; + } + const int reps = 20; + const Clock::time_point t0 = Clock::now(); + for (int r = 0; r < reps; ++r) { + if (!strata::core::session_replay(g, 0, 0, ss, gr, main_cs, err)) { + std::fprintf(stderr, "strata generate: session_replay: %s\n", err.c_str()); + return 1; + } + } + if (cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: session_replay faulted: %s\n", cudaGetErrorString(cudaGetLastError())); + return 1; + } + const double ms = std::chrono::duration(Clock::now() - t0).count() / (double) reps; + std::printf("pre graphs only %8.2f ms per token over %lld layers -> %.2f tok/s of GPU work\n", ms, + (long long) g.n_layers, ms > 0 ? 1000.0 / ms : 0.0); + std::printf(" %8.3f ms per layer\n", ms / (double) g.n_layers); + return 0; + } + + // ---- R0.3: THE TRUE PER-TOKEN GPU FLOOR. + // + // `--graph-only` above launches ONLY `gr.execs[l]`, the `pre` graphs. It omits the 48 `post` graphs - the + // shared expert, the combine and the second `gr_write` - and the LM head. Everything this project published + // as "39.8 ms pure GPU" came from that loop while being described as the whole GPU, which also made the + // "host's share = 49.4 - 39.8 = 9.6 ms" figure wrong by however much the missing work costs. See + // Memory/ERRORS.md A4/A5. + // + // This flag is what "pure GPU" has to mean, and it replaces that number everywhere. No pool runs, so + // `parts` keeps whatever the buffer holds and the timing is GPU work alone. + if (o.gpu_only_full) { + strata::core::doorbell_reset(db); + const int reps = 20; + double ms_layers = 0, ms_head = 0; + for (int r = -1; r < reps; ++r) { // r == -1 is the warm pass, not counted + const Clock::time_point t0 = Clock::now(); + if (!strata::core::session_replay_full(g, 0, 0, ss, gr, main_cs, err)) { + std::fprintf(stderr, "strata generate: session_replay_full: %s\n", err.c_str()); + return 1; + } + // The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time. + if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { + std::fprintf(stderr, "strata generate: gpu-only-full layers faulted: %s\n", + cudaGetErrorString(cudaGetLastError())); + return 1; + } + const Clock::time_point t1 = Clock::now(); + if (!run_head(main_cs)) { + std::fprintf(stderr, "strata generate: gpu-only-full lm_head: %s\n", err.c_str()); + return 1; + } + if (cudaStreamSynchronize((cudaStream_t) main_cs) != cudaSuccess) { + std::fprintf(stderr, "strata generate: gpu-only-full head faulted: %s\n", + cudaGetErrorString(cudaGetLastError())); + return 1; + } + const Clock::time_point t2 = Clock::now(); + if (r < 0) continue; + ms_layers += std::chrono::duration(t1 - t0).count(); + ms_head += std::chrono::duration(t2 - t1).count(); + } + ms_layers /= (double) reps; + ms_head /= (double) reps; + const double ms = ms_layers + ms_head; + std::printf("GPU floor pre+post+head %7.2f ms per token -> %.2f tok/s of GPU work\n", ms, + ms > 0 ? 1000.0 / ms : 0.0); + std::printf(" %8.3f ms layers (%lld x pre+post)\n", ms_layers, (long long) g.n_layers); + std::printf(" %8.3f ms per layer\n", ms_layers / (double) g.n_layers); + std::printf(" %8.3f ms LM head\n", ms_head); + return 0; + } + + // ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** + // + // `session_loop` used to allocate its pinned staging buffer, its probe event and its host pin ON EVERY + // TOKEN, and `cudaFreeHost` at the end of each call implicitly synchronises the device - so every token + // finished with a device-wide sync nobody asked for. The scratch is created once here and reused; it also + // owns the host pin for the whole session rather than taking and releasing it per token. + strata::core::SessionLoopScratch loop_scratch; + struct ScratchFree { + strata::core::SessionLoopScratch* p; + ~ScratchFree() { if (p != nullptr) p->free(); } + } scratch_free{&loop_scratch}; + // Initialised unconditionally, including under --no-pool: the loop validates the scratch it is handed, so + // passing a default-constructed one is an error rather than a fallback. (It was, and the guard caught it - + // which is the point of the guard.) One allocation at setup either way. + if (!loop_scratch.init((size_t) K * g.n_embd * 4, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + // Plan v0.3 P3: the whole token as ONE graph whenever nothing needs a host step between the ring and post[l] + // (the VRAM expert tier and the per-layer dumps do). `--no-token-graph` keeps two graphs per layer. + strata::core::TokenGraph tgraph; + struct TokenGraphFree { + strata::core::TokenGraph* p; + ~TokenGraphFree() { strata::core::token_graph_free(*p); } + } tgraph_free{&tgraph}; + // Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the + // device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.) + std::vector host_res; + int32_t* d_res = nullptr; + int32_t* d_hit_count = nullptr; + strata::core::TokenHits thits; + const bool graph_hits = hit_fn != nullptr && !profile.empty() && !o.no_pool; + if (graph_hits && !o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr) { + host_res.assign((size_t) (g.n_layers * g.n_expert), strata::core::kNotResident); + int64_t resident = 0; + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) { + const int st = multi_gpu ? stage_of(l) : 0; + const int32_t slot = st > 0 ? stages[(size_t) st - 1]->cache.slot_of(l, e) : xcache.slot_of(l, e); + host_res[(size_t) (l * g.n_expert + e)] = slot; + if (slot != strata::core::kNotResident) ++resident; + } + if (cudaMalloc((void**) &d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || + cudaMalloc((void**) &d_hit_count, sizeof(int32_t)) != cudaSuccess || + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess) { + std::fprintf(stderr, "strata generate: the device residency table could not be staged\n"); + return 1; + } + thits.d_res = d_res; + thits.n_expert = g.n_expert; + for (auto& st : stages) { // layer split across GPUs: the same table on every device + const strata::core::OnDevice on(st->dev); + if (cudaMalloc((void**) &st->d_res, host_res.size() * sizeof(int32_t)) != cudaSuccess || + cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice) != + cudaSuccess) { + std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev); + return 1; + } + } + thits.cache_base = drive.d.cache_base; + thits.blob = drive.d.cache_blob; + thits.d_slot = drive.d.d_slot; + thits.d_dst = drive.d.d_dst; + thits.d_count = d_hit_count; + thits.x_q8 = drive.d.x_q8_0_hit; + thits.x_scale = drive.d.x_q8_0_hit_scale; + thits.scratch = drive.d.hit_scratch; + thits.hit_out = drive.d.hit_out; + drive.d.host_res = host_res.data(); + std::fprintf(stderr, "strata generate: token graph hit path: %lld resident experts, decided on the device\n", + (long long) resident); + } + if (!o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr && + (hit_fn == nullptr || thits.on()) && !native_pack && !multi_gpu) { // a split's token graph cannot span stages + if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes, + tgraph, err, thits.on() ? &thits : nullptr)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: token graph captured (48 layers, one launch per token)\n"); + } + + // ================================ WHERE THE HOST TERM GOES, PER TOKEN ================================ + // + // **`--gpu-only-full` MEASURES THE 48 LAYER GRAPHS AND THE LM HEAD AND NOTHING ELSE.** It never enters + // this loop, so it does not run `ple_stage_token`, `embed_row`, the whole-vocabulary logits readback, the + // NaN scan or the sampler - and `--no-pool --stats` against that floor was being read as "the per-layer + // round trip costs 12.4 ms" when an unknown part of it is per TOKEN, not per layer. That is the same error + // the review catalogued as A4/A5, one level down: a difference between two measurements attributed to a + // mechanism that neither of them isolates. + // + // Six accumulators, because the six have different fixes. Reported in `--stats` as ms/token. **The + // boundary after the layer loop is the one that matters**: without it the head's interval swallows all 48 + // layers and the report reads as "head = 50 ms", which is not a thing that can happen to 1.4 ms of GPU + // work. That is not hypothetical - it is what the first version of this printed. + double ms_ple = 0, ms_embed = 0, ms_layers = 0, ms_head = 0, ms_readback = 0, ms_sample = 0; + int64_t phase_tokens = 0; + + // ================================ plan v0.3 P8: THE PERSISTENT ENGINE (--serve) ================================ + // + // The weights, the expert arena and the VRAM tier load once; then requests arrive on stdin, one per line, + // + // GEN + // + // and each generated token is written to stdout as `T ` as soon as its verify window is done, followed by + // + // DONE + // + // + // Before that, `RESUME ` (n prompt tokens are not read again), `PP ` + // after every prompt chunk, and `REUSED ` once the prompt is read. (`ERR ` instead when a request + // cannot run; `STOP` ends the running request at its next step; `QUIT` ends the process.) A request continues + // from the live session or the longest conversation checkpoint its prompt starts with (see ConvCheckpoint), + // otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path + // and its last token through the first verify window - the path all three model files share. Decoding is greedy. + // The expert-cache slots (from the end of the cache) that hold the prompt path's buffers for a chunk, and the + // bytes from the first of them to the end. + // the share of expert bytes the arena could pin (sizes the prompt path's streamed ring and its lend cap) + if (srcp != nullptr && o.prefill_chunk > 0) { + uint64_t pinned = 0, total = 0; + const auto& lay = strata::kernels::cpu::expert_layout(); + for (int64_t l = 0; l < g.n_layers; ++l) + for (int64_t e = 0; e < g.n_expert; ++e) { + const uint64_t b = lay.blob_bytes(l); + total += b; + if (srcp->pinned(l, e)) pinned += b; + } + strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0); + } + auto lend_slots = [&](int64_t c) -> int64_t { + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, c); + const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); + if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need` + k = 0; + while (k < xcache.slots() && + (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k; + } + return k; + }; + // `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its + // OWN cache, and the only other user of the old helper was the serve path's own relayout. + auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t { + if (tokens <= 0 || max_chunk <= 0) return 0; + const int64_t rounded = tokens > std::numeric_limits::max() - 255 + ? tokens + : ((tokens + 255) / 256) * 256; + return std::min(max_chunk, rounded); + }; + // The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits, + // or with --prefill auto the largest of kAutoChunks whose buffers take at most kAutoLendPct % of the slots (a + // lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0 + // prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own + // prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits. + // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the + // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the + // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning). + // Hoisted out of plan_lend: the serve path's per-stage loans obey the same cap, one participant at a time. + const int64_t kAutoLendPct = [] { + const char* v = std::getenv("STRATA_PREFILL_LEND_PCT"); + return v ? (int64_t) std::atoi(v) + : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85); + }(); + auto plan_lend = [&](int64_t& chunk) -> int64_t { + // 32768 and 16384 (#282, opt-in: --prefill auto:32768): a 32K prompt with IQ2_XS (RTX 5090, 64K context) + // read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an + // NVFP4 pack at 262K: 3,535 -> 5,201) + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + auto slots_for = lend_slots; + if (o.prefill_auto) { + for (const int64_t c : kAutoChunks) { + // above 8192: only when asked for, and only when a prompt of the context can use it + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; + const int64_t k = slots_for(c); + if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; } + } + return 0; + } + for (int64_t c = chunk; c >= 256; c /= 2) { + const int64_t k = slots_for(c); + if (k + 128 <= xcache.slots()) { chunk = c; return k; } + } + return 0; + }; + // ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not + // hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap + // mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here, + // after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts + // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The + // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the + // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. + if (o.resident_cpu_experts) { + int64_t lend_from = -1; + if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { + int64_t chunk = o.prefill_chunk; + const int64_t k = plan_lend(chunk); + if (k > 0) lend_from = xcache.slots() - k; + } + bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom, + o.resident_budget, &profile); + std::string whole_err; + if (!resident_ok && o.resident_soft) { + // #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 + // budget path (sized by the RAM alone) instead of none: the misses outside it read the same file bytes + // the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. + whole_err = err; + resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, {}, -1, o.resident_headroom, + strata::core::FileExpertSource::kResidentWhatFits, &profile); + if (resident_ok) + std::fprintf(stderr, "strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f " + "GiB of the experts the GPU does not hold, the hottest by the expert profile, are " + "kept in RAM and the rest are read from the model folder through the OS file " + "cache\n", + whole_err.c_str(), (double) src.resident_bytes() / 1073741824.0); + else + err = whole_err + "; " + err; + } + if (resident_ok) { + if (o.adapt_every > 0 && o.adapt_swaps > 0 && + !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { + std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU " + "cache; adaptive swaps %s\n", + (double) src.resident_bytes() / 1073741824.0, + src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable", + (long long) xcache.resident(), + o.adapt_every > 0 && o.adapt_swaps > 0 ? "exchange them with the GPU cache (no file reads)" + : "off"); + } else if (o.resident_soft) { + std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the " + "GPU does not hold are read from the model folder through the OS file cache " + "(--mmap-experts), which is slower when the RAM cannot keep them\n", err.c_str()); + } else if (o.resident_budget > 0) { + // #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are + // read from the files like the ones outside it (pin_cache_complement leaves nothing half-built) + std::fprintf(stderr, "strata generate: WARNING: the RAM budget (--resident-budget-gib) cannot be kept (%s); " + "every expert the GPU does not hold is read from the model files through the OS file " + "cache (--mmap-experts), which is slower\n", err.c_str()); + } else { + std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); + return 1; + } + } + if (o.serve) { + if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || + (graph_hits && (thits.d_res == nullptr || host_res.empty()))) { + std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable " + "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n"); + return 2; + } + strata::prefill::Prefill sp; + void* borrow = nullptr; + uint64_t borrow_bytes = 0; + int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk) + // ---- WHO BORROWS, AND FROM WHOSE CACHE. One entry per prompt path: CUDA0's (layers [0, split_at[0]), + // which is the whole model without a split) borrowing the tail of CUDA0's cache, then one per stage + // borrowing the tail of ITS OWN cache. A loan is sized by the exact `Prefill::bytes_needed` for the + // chunk, is laid out by `Prefill::relayout`, and is refilled before any window reads - so outside the + // prompt the whole cache is expert cache. THIS IS THE POINT OF THE STRUCT: the loan used to exist only + // for CUDA0, and `no_prefill_borrow` made every stage instead withhold a chunk-sized reserve from its + // cache for the entire session, which is what cost the 4-way its context (see the note at the top of the + // layer-split block). A stage may only lend the rows for ITS OWN layers: `host_res` is one table whose + // slot values are indices into whichever cache owns the layer, so a loan that marked rows by slot number + // alone would hand CUDA0 a slot belonging to another stage's cache. + struct PfPart { + strata::core::ExpertCache* cache = nullptr; + const strata::core::SessionState* ses = nullptr; + strata::prefill::Prefill* sp = nullptr; + int dev = -1; // -1: leave the device alone (CUDA0) + int64_t lb = 0, le = 0; // the layers whose rows this cache holds - the only rows it may lend + int32_t first = -1; // the first slot it may lend, for the chunk that was chosen + int32_t first_now = -1; // where its buffers are laid out now + int64_t lent_chunk = 0; + std::vector> lent; + }; + auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t { + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, c); + strata::core::ExpertCache& xc = *p.cache; + if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need` + int64_t k = 0; + while (k < xc.slots() && + (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k; + return k; + } + const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob); + }; + auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t { + strata::core::ExpertCache& xc = *p.cache; + return xc.slot_offsets() ? (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[first]) + : (uint64_t) (xc.slots() - first) * + (uint64_t) strata::kernels::cpu::expert_layout().max_blob; + }; + // #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so + // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's + // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU + // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. + if (multi_gpu && !host_res.empty()) { + int64_t res_n = 0; + for (const int32_t r : host_res) res_n += r >= 0; + const double res_share = (double) res_n / (double) host_res.size(); + const char* v = std::getenv("STRATA_SPLIT_RING"); + const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0); + if (ring > 0) { + strata::prefill::Prefill::set_ring_override(ring); + std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's " + "streamed ring %d slots\n", 100.0 * res_share, ring); + } + } + std::vector pf_parts; + // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card + // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the + // chunk is the largest one EVERY participant can lend (a smaller chunk only reads slower) + if (pf_borrow && d_res != nullptr) { + pf_parts.push_back({&xcache, &ss, &sp, -1, 0, multi_gpu ? split_at[0] : g.n_layers, -1, -1, 0, {}}); + for (auto& st : stages) + pf_parts.push_back({&st->cache, &st->ss, &st->sp, st->dev, st->lb, st->le, -1, -1, 0, {}}); + // The two tests plan_lend makes for CUDA0 alone, one participant at a time: a loan must leave the + // 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an + // explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant + // (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main. + auto fits_one = [&](const PfPart& p, int64_t c, bool cap) -> bool { + const int64_t k = part_slots(p, c); + if (k <= 0 || k + 128 > p.cache->slots()) return false; + return !(cap && k * 100 > kAutoLendPct * p.cache->slots()); + }; + // `only`: CUDA0's cache alone (#448: what one GPU would choose, for the log below); null: every one + auto fits = [&](int64_t c, bool cap, const PfPart* only = nullptr) -> bool { + if (only != nullptr) return fits_one(*only, c, cap); + for (const PfPart& p : pf_parts) + if (!fits_one(p, c, cap)) return false; + return true; + }; + static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256}; + auto pick = [&](const PfPart* only) -> int64_t { + if (o.prefill_auto) { + for (const int64_t c : kAutoChunks) { + if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend + if (fits(c, true, only)) return c; + } + } else { + for (int64_t c = o.prefill_chunk; c >= 256; c /= 2) + if (fits(c, false, only)) return c; + } + return 0; + }; + const int64_t chunk = pick(nullptr); + // #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a + // 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the + // regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in. + if (pf_parts.size() > 1) { + const int64_t alone = pick(&pf_parts[0]); + if (alone > chunk) { + for (size_t i = 1; i < pf_parts.size(); ++i) { + const PfPart& p = pf_parts[i]; + if (fits_one(p, alone, o.prefill_auto)) continue; + const int dev = p.dev < 0 ? 0 : p.dev; + cudaDeviceProp prop{}; + if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess) { + (void) cudaGetLastError(); + prop.name[0] = 0; + } + const std::string pct = + o.prefill_auto ? ", and lend at most " + std::to_string(kAutoLendPct) + "%" : ""; + std::fprintf(stderr, "strata serve: WARNING: prompt chunk %lld tokens, not %lld: CUDA%d (%s) " + "has %lld expert-cache slots, and a %lld-token chunk borrows %lld of them " + "(it must keep 128%s) - prompts read slower than on CUDA0 alone (#448)\n", + (long long) chunk, (long long) alone, dev, prop.name, + (long long) p.cache->slots(), (long long) alone, + (long long) part_slots(p, alone), pct.c_str()); + // the helper tiers start at CUDA1 without a split (and are enabled in order) + std::fprintf(stderr, "strata serve: a card this small can serve as a helper expert cache " + "instead of a split stage: without --layer-split, with %s " + "(docs/SECOND_GPU.md)\n", + dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order"); + } + } + } + if (chunk > 0) { + if (o.prefill_auto) + std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens\n", (long long) chunk); + else if (chunk != o.prefill_chunk) + std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in " + "every expert cache\n", (long long) o.prefill_chunk, (long long) chunk); + o.prefill_chunk = chunk; + for (PfPart& p : pf_parts) { + p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk)); + p.first_now = p.first; + } + // #340: a split stage whose card still has room for the chunk's buffers (its cache already holds + // every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of + // borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it. + // Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made + // after this). Layer splits only - one GPU keeps its loan exactly as before. + // STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31). + static const bool own_ok = [] { + const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS"); + return v == nullptr || v[0] != '0'; + }(); + if (pf_parts.size() > 1 && own_ok) { + for (PfPart& p : pf_parts) { + const strata::core::OnDevice on(p.dev); + size_t fb = 0, tb = 0; + if (cudaMemGetInfo(&fb, &tb) != cudaSuccess) { (void) cudaGetLastError(); continue; } + const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk); + if ((uint64_t) fb >= need + (3ull << 29)) { + std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " + "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev, + (double) need / 1073741824.0, (double) fb / 1073741824.0); + p.first = -1; + p.first_now = -1; + } + } + } + lend_first = pf_parts[0].first; + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; + } else if (o.prefill_auto) { + o.prefill_chunk = 1024; // nothing lendable: small buffers of its own + } else if (pf_parts.size() > 1) { + // An explicit chunk no stage can lend in full. main falls back to the prompt path's own buffers + // here and so do we, rather than refusing to start - but say what every stage has, because a split + // stage that has to allocate these on top of a cache that already filled its VRAM will not fit, + // and `init` would otherwise report only that the buffers do not fit. + std::fprintf(stderr, "strata serve: no stage can lend the prompt path its %lld-token buffers, so " + "each stage allocates its own:\n", (long long) o.prefill_chunk); + for (const PfPart& p : pf_parts) + std::fprintf(stderr, "strata serve: CUDA%d has %lld slots, and a %lld-token chunk needs " + "the last %lld of them\n", p.dev < 0 ? 0 : p.dev, + (long long) p.cache->slots(), (long long) o.prefill_chunk, + (long long) part_slots(p, o.prefill_chunk)); + } + } else if (o.prefill_auto && d_res == nullptr) { + o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own + } + bool any_loan = borrow != nullptr; + for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0; + if (any_loan) { + if (borrow != nullptr) + std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n", + (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0); + for (size_t i = 1; i < pf_parts.size(); ++i) // one loan per stage, from that stage's own cache + if (pf_parts[i].first >= 0) std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n", + pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first), + (long long) pf_parts[i].cache->slots(), + (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0); + } else { + std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); + } + // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. + // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and + // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a + // `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A + // chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower). + auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit" + for (size_t i = 0; i < stages.size(); ++i) { + GpuStage& st = *stages[i]; + st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr); + const strata::core::OnDevice on(st.dev); + void* sb = nullptr; // this stage's own loan, out of its own cache + uint64_t sbb = 0; + // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers + if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) { + sb = st.cache.device_slot(pf_parts[i + 1].first); + sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first); + } + if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, + err, sb, sbb)) { + err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err; + return err.find("do not fit") != std::string::npos ? 2 : 1; + } + } + if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); + if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + return err.find("do not fit") != std::string::npos ? 2 : 1; + return 0; + }; + static constexpr int64_t kStepChunks[] = {6144, 4096, 3072, 2048, 1536, 1024, 512}; + { + // First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave + // headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then + // failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes. + const int64_t kHeadroom = 512ll << 20; + auto own_fits = [&](int64_t c, int& dev_out, int64_t& need_out, int64_t& free_out) -> bool { + for (size_t i = 0; i <= stages.size(); ++i) { + const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0); + if (loan) continue; + const int dev = i == 0 ? -1 : stages[i - 1]->dev; + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c); + if (need + kHeadroom > (int64_t) fb) { + dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb; + return false; + } + } + return true; + }; + int dev = 0; + int64_t need = 0, fb = 0; + if (!own_fits(o.prefill_chunk, dev, need, fb)) { + int64_t c = 0; + for (const int64_t s : kStepChunks) { + int d2 = 0; + int64_t n2 = 0, f2 = 0; + if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; } + } + if (c > 0) { + std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, " + "%lld MiB free: %lld-token chunks\n", (long long) o.prefill_chunk, + (long long) (need >> 20), dev, (long long) (fb >> 20), (long long) c); + o.prefill_chunk = c; + } + } + } + for (;;) { + const int r = init_prompt_paths(); + if (r == 0) break; + int64_t next = 0; + for (const int64_t c : kStepChunks) + if (c < o.prefill_chunk) { next = c; break; } + if (r == 2 && next > 0) { + std::fprintf(stderr, "strata serve: %s: trying a %lld-token chunk\n", err.c_str(), (long long) next); + // start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's + // error: it is sticky, and the next launch check would report "out of memory" for a kernel + for (auto& stp : stages) { + const strata::core::OnDevice on(stp->dev); + stp->sp.reset(); + (void) cudaGetLastError(); + } + sp.reset(); + (void) cudaGetLastError(); + o.prefill_chunk = next; + if (any_loan) { // smaller loans for the smaller chunk + for (PfPart& p : pf_parts) + if (p.first >= 0) { + p.first = (int32_t) (p.cache->slots() - part_slots(p, next)); + p.first_now = p.first; + } + lend_first = pf_parts[0].first; + borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr; + borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0; + } + err.clear(); + continue; + } + std::fprintf(stderr, "strata serve: %s\n", err.c_str()); + if (err.find("fit") != std::string::npos) // #85: say what frees VRAM + std::fprintf(stderr, "strata serve: the GPU has too little free VRAM for the prompt path: turn images " + "off (setup: --vision no), close other programs using the GPU, use a shorter " + "context, or read prompts in smaller chunks (--prefill 512)\n"); + return 1; + } + mem_mark("the head and the prompt path"); + // #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an + // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): + // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and + // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). + // STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages + // (several chunks, still nothing lent) instead of borrowing for a bigger one. + int64_t split_small = 0, split_small_max = 0; + if (multi_gpu && !pf_parts.empty() && !host_res.empty()) { + const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN"); + const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0; + const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX"); + split_small = S; + split_small_max = S > 0 ? std::max(S, vm ? std::atoll(vm) : S) : 0; + int64_t evicted = 0; + for (PfPart& p : pf_parts) { + if (S <= 0 || p.first < 0) continue; + const int32_t first_s = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, S))); + int64_t n = 0; + for (int64_t l = p.lb; l < p.le; ++l) + for (int64_t ex = 0; ex < g.n_expert; ++ex) { + int32_t& r = host_res[(size_t) (l * g.n_expert + ex)]; + if (r >= first_s) { r = strata::core::kNotResident; ++n; } + } + evicted += n; + std::fprintf(stderr, "strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts " + "no longer resident)\n", p.dev < 0 ? 0 : p.dev, + (long long) (p.cache->slots() - first_s), (long long) S, (long long) n); + } + if (evicted > 0) { + if (d_res != nullptr) + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + } + } + } + // the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last + // `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for + // the widest window; a request without penalties gets a null buffer and takes the byte-for-byte + // neutral path (no upload, no buffer handed to the sampler). + constexpr int kPenaltyWindowCap = 4096; + constexpr size_t kHistSlots = (size_t) kPenaltyWindowCap * (size_t) strata::kernels::kVerifyMaxT; + int32_t* d_hist = nullptr; + std::vector hist_stage(kHistSlots, -1); + const int hist_dev = last_st ? last_st->dev : -1; // with the head: the last stage's device + if (const strata::core::OnDevice on_h(hist_dev); cudaMalloc(&d_hist, kHistSlots * sizeof(int32_t)) != cudaSuccess) { + std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n"); + return 1; + } + strata::core::Verifier ver; + strata::core::VerifyHits vh; + vh.d_res = thits.d_res; + vh.cache_base = thits.cache_base; + vh.blob = thits.blob; + vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers + vh.n_slots = xcache.slots(); + // Layer split: `ver` runs layers [0, K1) and hands its residual to the next stage's verifier, and so on; the + // last runs the head. The hand-offs are mapped pinned memory, portable: a stage on another GPU reads it. + // (--split-device 0: the second stage on this GPU, sharing its weights, session and cache - the A/B.) + strata::core::Verifier ver_same; + SplitDrive split_drive; + auto stage_ver = [&](int st) -> strata::core::Verifier& { + return st == 0 ? ver : split_same ? ver_same : stages[(size_t) st - 1]->ver; + }; + auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); }; + const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1; + if (n_stages > 1) { + const size_t hb = (size_t) strata::kernels::kVerifyMaxT * + (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); + std::vector hand((size_t) n_stages - 1, nullptr); + for (float*& h : hand) { + float* hh = nullptr; + if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) { + std::fprintf(stderr, "strata serve: the layer-split hand-off allocation failed\n"); + return 1; + } + std::memset(hh, 0, hb); + } + split_drive.base = &drive; + split_drive.n = n_stages; + for (int st = 0; st < n_stages; ++st) { + stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1, + st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr); + split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers; + split_drive.cache_base[st] = drive.d.cache_base; + split_drive.cache_slot_off[st] = drive.d.cache_slot_off; + split_drive.pcie_num[st] = pcie_num_of(o.pcie_frac); + } + for (int st = 1; st < n_stages; ++st) { + bool ok_s = false; + if (split_same) { + ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err); + } else { + GpuStage& gs = *stages[(size_t) st - 1]; + const strata::core::OnDevice on(gs.dev); + strata::core::VerifyHits vs; + vs.d_res = gs.d_res; + vs.cache_base = gs.cache.device_slot(0); + vs.blob = thits.blob; + vs.slot_off = gs.cache.slot_offsets(); + vs.n_slots = gs.cache.slots(); + ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err); + split_drive.cache_base[st] = gs.cache.device_slot(0); + split_drive.cache_slot_off[st] = gs.cache.slot_offsets(); + split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac); + } + if (!ok_s) { + std::fprintf(stderr, "strata serve: layer split, stage %d: %s\n", st + 1, err.c_str()); + return 1; + } + } + for (int st = 0; st + 1 < n_stages; ++st) stage_ver(st).set_next(&stage_ver(st + 1), &split_drive); + std::string plan_s = "0-" + std::to_string(split_at[0] - 1) + " (CUDA0)"; + for (int st = 1; st < n_stages; ++st) + plan_s += ", " + std::to_string(split_at[(size_t) st - 1]) + "-" + std::to_string(split_drive.end[st] - 1) + + " (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")"; + std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str()); + } + if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err) || + !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) { + std::fprintf(stderr, "strata serve: %s\n", err.c_str()); + return 1; + } + for (int st = 0; st < n_stages && n_stages > 1; ++st) { + split_drive.plan[st] = stage_ver(st).plan_sink(); + if (st > 0) { + stage_ver(st).set_split(o.spec_split); + stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + } + } + // the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage + const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi; + void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive; + mem_mark("the verifier and the drafter's binding"); + ver.set_split(o.spec_split); + // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call + // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; + // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy + // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). + ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + std::vector cur; + // ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens + // it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the + // saved points; every one of them is a prefix of `live` (the loop drops the rest), so they form a chain - + // the radix cache's tree collapsed onto the one branch of history whose cells the session holds. The + // chain's root is the deepest point every request so far shared (the end of the system prompt, in + // practice); the retention policy pins it and rotates the rest LRU (conv_cache.hpp), so a NEW chat that + // shares that prefix mounts through it instead of reading it again. + std::vector live; + std::vector live_imgs, req_imgs; + bool live_ok = false; + std::vector checks; + uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it + bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with + strata::core::ConversationCache conversations( + o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, + (size_t) o.conversation_cache_slots); + // Save only on a switch/rewind, not on each continuing request. No graph + // addresses change: all parked images live in ordinary host vectors. + auto park_current = [&](size_t held) -> bool { + if (!conversations.enabled() || !live_ok || live.empty()) return true; + const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached}; + auto reuse = conversations.take_reuse(); + size_t estimate = 0; + if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str()); + err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel. + return true; + } + const size_t fresh_estimate = estimate; + if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes( + reuse, view, ss, g, mtp.kv_state(), estimate, err)) { + reuse = {}; + estimate = fresh_estimate; + err.clear(); + } + // A park carrying its own retained K/V replaces memory the cache + // already held, so capacity is make_room's call - it runs next either + // way, and put()'s accounting still bounds the budget. The with-reuse + // estimate must stay uncapped: it counts the retained buffers' + // capacity and directories, and put() charges that same true size - + // a capped figure would under-evict and overfill the budget. + // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold + // nothing the outgoing chain does not, apart from the tail this conversation rewrote) + if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached)) + std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this " + "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size()); + if (!conversations.make_room(estimate, held)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n", + estimate >> 20); + return true; + } + const auto t0 = Clock::now(); + try { + const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024; + const size_t additional = estimate - reuse.bytes(); + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), + additional, floor)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n", + additional >> 20, (long long) o.conversation_cache_min_free_mib); + return true; + } + strata::core::SavedConversation image; + size_t reused_bytes = 0; + if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err, + std::move(reuse), &reused_bytes)) return false; + if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) { + std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n"); + return true; + } + const size_t snapshot_bytes = image.bytes(); + const bool stored = conversations.put(std::move(image), held); + std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n", + stored ? "parked" : "skipped", live.size(), + std::chrono::duration(Clock::now() - t0).count(), + conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes); + } catch (const std::bad_alloc&) { + // The active state has not been touched. Continue with normal + // prompt processing rather than killing a serving process. + std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n"); + } + return true; + }; + int64_t pp_total = 0, pp_from = 0, pp_next_check = 0; + Clock::time_point pp_t0 = Clock::now(); + auto 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; + }; + // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed + // A layer split's mid-prompt checkpoints: when the last stage reports a chunk, the earlier ones already read + // the next, so each stage saves its own part when IT reaches a checkpoint position (the same rule as below: + // every `prompt_cache_every` tokens from where the request resumed), and the last stage puts them together. + std::mutex part_mu; + std::map> part_at; // position -> one part per stage + std::vector part_next(stages.size() + 1, INT64_MAX); + // a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed. `parts`: the stages' + // states saved at L (a split's mid-prompt checkpoint); without, they are read now (everything is at L) + auto checkpoint_at = [&](int64_t L, std::vector* parts = nullptr) -> bool { + 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); + if (parts != nullptr) { + if (parts->size() != stages.size() + 1) return false; + c.gdn = std::move((*parts)[0].gdn); + c.ple = std::move((*parts)[0].ple); + c.tails = std::move((*parts)[0].tails); + c.dead = std::move((*parts)[0].dead); + c.block_pos = std::move((*parts)[0].block_pos); + for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i])); + } else { + if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(c, ss, g)) return false; + for (auto& st : stages) { // a layer split's later stages: their sessions' part + const strata::core::OnDevice on(st->dev); + ConvCheckpoint part; + part.ids = c.ids; + if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(part, st->ss, g)) return false; + c.stage_parts.push_back(std::move(part)); + } + } + c.used = ++check_clock; + checks.push_back(std::move(c)); + while ((int) checks.size() > o.prompt_cache) { + std::vector stamps; + stamps.reserve(checks.size()); + 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; + }; + sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { + std::vector nxt((size_t) T); + for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; + // E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) + const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); + if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; + if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) + std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", + batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); + // progress for the server window: PP + const int64_t done = p0 + T; + const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); + std::printf("PP %lld %lld %.0f %.1f\n", (long long) done, (long long) pp_total, ms, + ms > 0.0 ? 1000.0 * (double) (done - pp_from) / ms : 0.0); + strata::core::progress_at("reading the prompt (batched), done up to token", done); + strata::core::progress_beat(); + std::fflush(stdout); + if (o.prompt_cache_every > 0 && done >= pp_next_check) { + bool saved = false; + if (multi_gpu) { // the stages' parts, saved when each of them read this chunk + std::vector parts; + { + std::lock_guard lk(part_mu); + auto it = part_at.find(done); + if (it != part_at.end()) parts = std::move(it->second); + part_at.erase(part_at.begin(), part_at.upper_bound(done)); + } + bool complete = parts.size() == stages.size() + 1; + for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty(); + saved = !complete || checkpoint_at(done, &parts); // an incomplete set: no checkpoint here + } else { + saved = checkpoint_at(done); + } + if (!saved) { e = "saving a conversation checkpoint failed"; return false; } + pp_next_check = done + o.prompt_cache_every; + } + return true; + }; + if (multi_gpu) { // the batched prompt is reported by its last stage (the drafter's rows are there) + stages.back()->sp.on_chunk = std::move(sp.on_chunk); + sp.on_chunk = nullptr; + for (size_t i = 0; i <= stages.size(); ++i) { + strata::prefill::Prefill& stage_sp = i == 0 ? sp : stages[i - 1]->sp; + strata::core::SessionState& stage_ss = i == 0 ? ss : stages[i - 1]->ss; + stage_sp.on_stage_chunk = [&, i](int64_t done, std::string& e) -> bool { + if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true; + part_next[i] = done + o.prompt_cache_every; + ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized) + part.ids.assign(cur.begin(), cur.begin() + done); + if (!checkpoint_save(part, stage_ss, g)) { e = "saving a checkpoint part failed"; return false; } + std::lock_guard lk(part_mu); + auto& v = part_at[done]; + v.resize(stages.size() + 1); + v[i] = std::move(part); + return true; + }; + } + } + drive.d.plan = ver.plan_sink(); + drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5))); + if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); + cudaStream_t adapt_stream = nullptr; + if (cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { + std::fprintf(stderr, "strata serve: cannot create the refill stream\n"); + return 1; + } + // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed + std::vector> pending; + cudaEvent_t adapt_ev = nullptr; + cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); + // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own + auto res_upload = [&]() { + if (d_res != nullptr) + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + cudaMemcpy(st->d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + } + }; + auto apply_pending = [&](bool wait) { + if (pending.empty()) return; + if (wait) cudaEventSynchronize(adapt_ev); + else if (cudaEventQuery(adapt_ev) != cudaSuccess) return; + for (auto& st : stages) + if (st->adapt_live) { + if (wait) cudaEventSynchronize(st->adapt_ev); + else if (cudaEventQuery(st->adapt_ev) != cudaSuccess) return; + } + for (auto& st : stages) st->adapt_live = false; + src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM + for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; + pending.clear(); + res_upload(); + }; + // the VRAM tier follows the conversation (the same rule as the speculative loop below) + auto adapt = [&]() -> bool { + if (!pending.empty()) return true; // the previous swaps are still in flight + struct Swap { float gain; int32_t layer, in, out; }; + std::vector swaps; + std::vector> cand, vict; + for (int64_t l = 0; l < g.n_layers; ++l) { + cand.clear(); + vict.clear(); + const float* u = drive.d.usage.data() + l * g.n_expert; + const int32_t* r = host_res.data() + l * g.n_expert; + for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { + if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); } + else vict.emplace_back(u[e], e); + } + if (cand.empty() || vict.empty()) continue; + std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); + const size_t nc = std::min(cand.size(), vict.size()); + std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), + [](auto& a, auto& b) { return a.first < b.first; }); + for (size_t i = 0; i < nc; ++i) { + if (cand[i].first < vict[i].first + 1.5f) break; + swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); + } + } + std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); + if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); + if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false; + bool main_live = false; + for (const Swap& s : swaps) { + const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; + const int32_t slot = host_res[out]; + const uint8_t* b = srcp->blob(s.layer, s.in); + const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache + GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; + const strata::core::OnDevice on(gs ? gs->dev : -1); + if (slot < 0 || b == nullptr || + cudaMemcpyAsync(gs ? gs->cache.device_slot(slot) : xcache.device_slot(slot), b, + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), + cudaMemcpyHostToDevice, gs ? gs->adapt_stream : adapt_stream) != cudaSuccess) + return false; + if (gs) gs->adapt_live = true; + else main_live = true; + host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile + pending.emplace_back((int32_t) in, slot); // resident once the copy has landed + } + if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); + (void) main_live; + for (auto& st : stages) + if (st->adapt_live) { + const strata::core::OnDevice on(st->dev); + cudaEventRecord(st->adapt_ev, st->adapt_stream); + } + for (float& v : drive.d.usage) v *= 0.7f; + return true; + }; + // stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went + // away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. + std::atomic stop_req{false}; + std::mutex in_mu; + std::condition_variable in_cv; + std::deque in_lines; + bool in_eof = false; + std::thread([&] { + // read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for + // stdin's lock, which getline holds while it waits for input - an engine ending on an error (every + // std::exit) would hang in exit() on Linux, and the server would wait for it forever + std::string l, buf; + char chunk[4096]; + auto getline_fd = [&](std::string& out) -> bool { + for (;;) { + const size_t nlpos = buf.find('\n'); + if (nlpos != std::string::npos) { + out.assign(buf, 0, nlpos); + buf.erase(0, nlpos + 1); + return true; + } +#if defined(_WIN32) + const int n = _read(0, chunk, (unsigned) sizeof chunk); +#else + const ssize_t n = ::read(0, chunk, sizeof chunk); + if (n < 0 && errno == EINTR) continue; +#endif + if (n <= 0) { + if (buf.empty()) return false; + out.swap(buf); + buf.clear(); + return true; + } + buf.append(chunk, (size_t) n); + } + }; + while (getline_fd(l)) { + if (!l.empty() && l.back() == '\r') l.pop_back(); + if (l == "STOP") { stop_req.store(true); continue; } + std::lock_guard lk(in_mu); + in_lines.push_back(l); + in_cv.notify_one(); + } + std::lock_guard lk(in_mu); + in_eof = true; + in_cv.notify_one(); + }).detach(); + auto next_line = [&](std::string& out) -> bool { + std::unique_lock lk(in_mu); + in_cv.wait(lk, [&] { return !in_lines.empty() || in_eof; }); + if (in_lines.empty()) return false; + out = std::move(in_lines.front()); + in_lines.pop_front(); + return true; + }; + sp.should_stop = [&] { return stop_req.load(); }; + // STRATA_TRACE=1: one stderr line per step of a request (the log shows where a request stops) + const bool trace = std::getenv("STRATA_TRACE") != nullptr; + auto tr = [&](const char* what, long long a = -1, long long b = -1) { + if (!trace) return; + std::fprintf(stderr, "strata trace: %s %lld %lld\n", what, a, b); + std::fflush(stderr); + }; + { + // what is left once everything is allocated: under WDDM a GPU filled to the brim does not fail, it pages - + // and a page-in while the verify graph spins on a host flag stalls the request for good + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + // below ~256 MiB a later allocation (a first-used window's buffers, the desktop, another program) can make + // the driver page GPU memory, and a verify graph spinning on a host flag then never finishes + const int64_t free_mib = (int64_t) (free_b >> 20); + if (free_mib >= 256) { + std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib); + } else { + std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded - LOW: requests may stall;" + " add --vram-reserve-mib %lld to the config's args (or lower --max-context)\n", + (long long) free_mib, (long long) (o.vram_reserve_mib + 512 - free_mib)); + } + } + // what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY) + { + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + // "Experts in VRAM" is every tier, not one card's. This used to report `xcache` alone, so a layer split + // showed CUDA0's cache as if it were the whole GPU's: a 4-GPU 256K run read 3327 experts when the four + // cards held 13320, and the Monitor tab was wrong by 4x for every multi-GPU config. The tiers are + // disjoint by construction (remote_experts.cpp skips any pair a stage already claimed), so they add. + const int64_t slots_primary = (int64_t) xcache.slots(); + const int64_t mib_primary = (int64_t) (xcache.bytes() >> 20); + int64_t slots_all = slots_primary, mib_all = mib_primary; + for (const auto& st : stages) { + slots_all += (int64_t) st->cache.slots(); + mib_all += (int64_t) (st->cache.bytes() >> 20); + } + for (int r = 0; r < 3; ++r) + if (o.expert_cache_remote[(size_t) r] > 0) { + slots_all += remote_experts[(size_t) r].resident(); + mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0); + } + std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " + "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " + "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " + "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " + "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n", + (long long) o.max_context, o.kv.c_str(), + (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 + ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), + (long long) slots_all, (long long) mib_all, + (long long) slots_primary, (long long) mib_primary, + o.spec, o.mtp_max_t, + o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(), + (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), + pool.workers(), o.pcie_frac, + o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, + (long long) o.conversation_cache_min_free_mib); + } + // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on + // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the + // GPU spinning forever. STRATA_WATCHDOG_S=0 turns it off. Issue #31: before it does, it reports what every + // part was doing (stall_report), so one occurrence says where the wait is. + { + const char* ws = std::getenv("STRATA_WATCHDOG_S"); + const int limit = ws ? std::atoi(ws) : 60; // one step (a prompt layer, a verify window) takes seconds + if (limit > 0) + std::thread([limit] { + strata::core::Progress& p = strata::core::progress(); + uint64_t last = p.beats.load(), ticks_at = p.ticks.load(); + auto since = std::chrono::steady_clock::now(); + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + const auto now = std::chrono::steady_clock::now(); + const uint64_t b = p.beats.load(); + if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; } + if (now - since < std::chrono::seconds(limit)) continue; + std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping " + "the engine so the server starts it again (issue #29)\n", + limit, stage_text().c_str()); + stall_report(stderr, p.ticks.load() - ticks_at); + strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process + std::fflush(stderr); + std::abort(); + } + }).detach(); + } + std::printf("READY %lld stop\n", (long long) o.max_context); // "stop": this engine honours STOP + std::fflush(stdout); + std::string line; + int64_t rounds = 0; + const int S = o.spec; + const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S + if (S_mtp < S) mtp.set_max_drafts(S_mtp - 1); + strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); + strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process + // The vision path (--vision): GENI carries images. The file is one + // or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; + // each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, + // h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny). + constexpr int64_t kImagePad = 248056; // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells + bool mrope_identity = true; + std::vector img_rows; + std::vector row_ptr; + while (next_line(line)) { + if (line == "QUIT") break; + // the watchdog watches a request from here until this iteration ends, whichever way it ends + struct BusyScope { + BusyScope() { strata::core::progress().busy.store(true); strata::core::progress_at("request"); } + ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); } + } busy_scope; + stop_req.store(false); // a STOP that arrived between requests is stale + err.clear(); + const bool geni = line.rfind("GENI ", 0) == 0; + if (!geni && line.rfind("GEN ", 0) != 0) { + std::printf("ERR expected: GEN or GENI \n"); + continue; + } + char* endp = nullptr; + const long long max_new = std::strtoll(line.c_str() + (geni ? 5 : 4), &endp, 10); + // optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, min_p=F, + // penalty_last_n=N, penalty_repeat=F, penalty_freq=F, penalty_present=F, seed=N (text requests + // only). Absent keys keep today's behavior: greedy, no penalties. + float req_temperature = 0.0f, req_top_p = 1.0f; + int req_top_k = 20; // the sampler's own default; the sampled path REQUIRES top_k in 1..64 + unsigned long long req_seed = 0; + float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f; + int req_penalty_last_n = 0; + int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent) + // tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of + // the missed experts and the draft-probability floor, for this request only + double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p; + if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its + // embedding file path is the first token without an = + for (;;) { + while (*endp == ' ') ++endp; + const char* start = endp; + while (*endp != '\0' && *endp != ' ') ++endp; + if (endp == start) break; + const std::string tok(start, (size_t) (endp - start)); + const size_t eq = tok.find('='); + if (eq == std::string::npos) { endp = const_cast(start); break; } + const std::string key = tok.substr(0, eq); + const float fv = std::strtof(tok.c_str() + eq + 1, nullptr); + if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); + else if (key == "temperature") req_temperature = fv; + else if (key == "top_p") req_top_p = fv; + else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1); + else if (key == "min_p") req_min_p = fv; + else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1); + else if (key == "penalty_repeat") req_penalty_repeat = fv; + else if (key == "penalty_freq") req_penalty_freq = fv; + else if (key == "penalty_present") req_penalty_present = fv; + else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); + else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); + else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); + // unknown keys are skipped: the ids start at the first token without '=' + } + } + if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) { + std::printf("ERR experimental KAR misses require pcie_frac=0\n"); + continue; + } + std::string emb_path; + if (geni && endp != nullptr) { + while (*endp == ' ') ++endp; + char* gap = std::strchr(endp, ' '); + if (gap != nullptr) { emb_path.assign(endp, (size_t) (gap - endp)); endp = gap; } + } + std::vector ids; + std::string pe; + if (max_new < 1 || endp == nullptr || (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) { + std::printf("ERR bad request: %s\n", pe.empty() ? "max_new" : pe.c_str()); + continue; + } + const int64_t n = (int64_t) ids.size(); + req_imgs.clear(); + if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; } + if (geni || !mrope_identity) { + // positions for every cell this request can reach; the identity again for a text request + std::string ve; + row_ptr.assign((size_t) n, nullptr); + const int64_t cells = (int64_t) mrope_host.size() / 3; + auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) { + mrope_host[(size_t) c * 3] = (int32_t) t; + mrope_host[(size_t) c * 3 + 1] = (int32_t) h; + mrope_host[(size_t) c * 3 + 2] = (int32_t) w; + }; + if (!geni) { + for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); + } else { + struct Img { int64_t n, nx, ny; size_t off; }; + std::vector imgs; + img_rows.clear(); + std::FILE* f = std::fopen(emb_path.c_str(), "rb"); + if (!f) ve = "cannot open " + emb_path; + while (f && ve.empty()) { + int32_t hdr[5]; + const size_t got = std::fread(hdr, sizeof(int32_t), 5, f); + if (got == 0) break; + if (got != 5 || hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || hdr[3] < 1 || + (int64_t) hdr[2] * hdr[3] != hdr[1] || hdr[4] != (int32_t) g.n_embd) { + ve = "bad embeddings file (expected strata-vision records of width " + + std::to_string((long long) g.n_embd) + ")"; + break; + } + const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4]; + img_rows.resize(off + cnt); + if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; } + imgs.push_back({hdr[1], hdr[2], hdr[3], off}); + } + if (f) std::fclose(f); + int64_t p = 0, i = 0; + size_t k = 0; + while (ve.empty() && i < n) { + if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; } + if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; } + const Img& im = imgs[k++]; + { // what the conversation cache compares: a picture is its grid and its embeddings + const int64_t grid[3] = {im.n, im.nx, im.ny}; + uint64_t h = fnv1a(grid, sizeof grid); + h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h); + req_imgs.push_back({i, h}); + } + for (int64_t j = 0; j < im.n && ve.empty(); ++j) + if (i + j >= n || ids[(size_t) (i + j)] != kImagePad) + ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) + + " rows but fewer <|image_pad|> tokens"; + for (int64_t j = 0; j < im.n && ve.empty(); ++j) { + const int64_t y = j / im.nx, x = j % im.nx; + put(i + j, p, p + y, p + x); + row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd; + } + i += im.n; + p += std::max(im.nx, im.ny); + } + if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt"; + if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image"; + for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n)); + } + tr("positions built", (long long) img_rows.size()); + cudaDeviceSynchronize(); + tr("device idle"); + // CUDA0's table and, with a layer split, every later stage's (each device reads its own) + auto upload_mrope = [&]() -> bool { + bool ok = cudaMemcpy(d_mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), + cudaMemcpyHostToDevice) == cudaSuccess; + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + cudaDeviceSynchronize(); + ok = ok && cudaMemcpy(st->mrope, mrope_host.data(), mrope_host.size() * sizeof(int32_t), + cudaMemcpyHostToDevice) == cudaSuccess; + } + return ok; + }; + if (ve.empty() && !upload_mrope()) ve = "the image position upload failed"; + if (!ve.empty()) { + // leave the table as the identity so the next text request is untouched + for (int64_t c = 0; c < cells; ++c) put(c, c, c, c); + upload_mrope(); + mrope_identity = true; + std::printf("ERR %s\n", ve.c_str()); + std::fflush(stdout); + continue; + } + mrope_identity = !geni; + } + sp.embd_rows = geni ? row_ptr.data() : nullptr; + if (n + max_new + 8 > o.max_context) { + std::printf("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%lld)\n", (long long) n, + (long long) max_new, (long long) o.max_context); + continue; + } + bool bad = false; + for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab; + if (bad) { std::printf("ERR a token id is outside the vocabulary\n"); continue; } + std::array remote_before{}; + std::array launches_before{}; + std::array compact_before{}, full_before{}; + // ms_begin/ms_wait are cumulative since boot; the log line used to print them next to per-request deltas, + // so the host time read as if it belonged to this request. Take deltas here like every other column. + std::array begin_before{}, wait_before{}; + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + { + remote_before[(size_t) r] = remote_experts[(size_t) r].computed(); + launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers(); + compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes(); + full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes(); + begin_before[(size_t) r] = remote_experts[(size_t) r].ms_begin(); + wait_before[(size_t) r] = remote_experts[(size_t) r].ms_wait(); + } + cur = ids; + const Clock::time_point r0 = Clock::now(); + // ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are + // exactly the start of this prompt - at most n - 1 of them, the last token is always the first window + 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 imgs_below(req_imgs, L) == pre_imgs; + }; + const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true; + // the last request's final commit may still be running on the verifier's stream (set_commit_async): + // everything below reads, restores or zeroes the session from other streams and the host (the end of the + // last request waited already; this covers a request that ended on an error path) + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + int64_t resume = 0; + bool from_live = false; + if (o.prompt_cache > 0 && want_cvec == cvec_cached) { + if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; } + for (const ConvCheckpoint& c : 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 = conversations.best(ids, req_imgs, want_cvec); + std::optional incoming; + if (parked.tokens > resume) incoming.emplace(conversations.take(parked.index)); + // Reject the entire image before parking/overwriting the outgoing + // state. Invalid entries can safely fall back to its existing prefix. + if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) { + std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); + incoming.reset(); + err.clear(); + } + // Preserve the outgoing branch before any checkpoint rewind, reset, + // or incoming restore overwrites the positional state it requires. + if ((!from_live || incoming) && !park_current(incoming ? incoming->bytes() : 0)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + if (incoming) { + const auto t0 = Clock::now(); + if (strata::core::conversation_snapshot_restore(*incoming, ss, g, mtp.kv_state(), err) != + strata::core::ConversationRestore::restored) { + // Already prevalidated above: a failure here is fatal, never + // permission to decode from a partially restored session. + std::printf("ERR restoring parked conversation: %s\n", err.c_str()); + return 1; + } + if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { + uint64_t draft_hash = 0; + if (!strata::core::conversation_kv_verify(incoming->kv.back(), mtp.kv_state(), g, + int64_t(incoming->live.ids.size()), false, draft_hash, err)) { + std::printf("ERR verifying restored draft KV: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n", + (unsigned long long) draft_hash, (long long) incoming->kv.back().cells, + mtp.kv_state().kv_mode, "ram", + (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size)); + } + live = std::move(incoming->live.ids); + live_imgs = std::move(incoming->live.imgs); + checks = std::move(incoming->checkpoints); + cvec_cached = incoming->cvec; + resume = parked.tokens; + from_live = parked.live; + if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) + conversations.retain(std::move(incoming->kv), int64_t(live.size())); + incoming.reset(); // Running-state/checkpoint copies are no longer needed. + std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n", + (long long) resume, from_live ? "live" : "checkpoint", + std::chrono::duration(Clock::now() - t0).count(), + conversations.size(), conversations.bytes()); + } + if (want_cvec != cvec_cached) { + live_ok = false; + checks.clear(); + cvec_cached = want_cvec; + } + if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec); + // this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's + // path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new + checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) { + return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); + }), checks.end()); + live_ok = false; // until this request has finished, the session is in between + int64_t reread_to = -1; // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring + if (resume == 0) { + strata::core::session_zero(ss, g, nullptr, main_cs); + cudaStreamSynchronize(main_stream); + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream); + cudaStreamSynchronize(st->stream); + } + checks.clear(); + } else if (!from_live) { + ConvCheckpoint* c = nullptr; + for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k; + if (c != nullptr) c->used = ++check_clock; // mounting through it is the use LRU counts + static const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr; + if (reread && c != nullptr) { + // THE CHECK OF THE CHECKPOINT: instead of restoring it, read its tokens again from position 0 in + // one run (below, with the prompt path's slots lent like any read) - the same chunks the request + // that saved it read them in, when that request started at 0. With the VRAM expert set fixed + // (--adapt-swaps 0) the answer must match the restored one token for token; anything the + // checkpoint missed shows up as a difference. + strata::core::session_zero(ss, g, nullptr, main_cs); + cudaStreamSynchronize(main_stream); + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream); + cudaStreamSynchronize(st->stream); + } + reread_to = resume; + std::fprintf(stderr, "strata serve: STRATA_CKPT_REREAD: reading %lld tokens again instead of " + "restoring\n", (long long) resume); + } else if (c == nullptr || !checkpoint_restore(*c, ss, g) || c->stage_parts.size() != stages.size() || + [&] { + for (size_t i = 0; i < stages.size(); ++i) { + const strata::core::OnDevice on(stages[i]->dev); + if (!checkpoint_restore(c->stage_parts[i], stages[i]->ss, g)) return true; + } + return false; + }()) { + std::printf("ERR restoring a conversation checkpoint failed\n"); + return 1; + } + } + // KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' + // host copies and slots are always current (every writer writes both), so they need nothing + if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume); + tr("request", n, geni ? 1 : 0); + mtp.set_prompt_len(n); + const int64_t read_from = reread_to > 0 ? 0 : resume; + conversations.limit_reuse(read_from); + pp_total = n; + pp_from = read_from; + pp_t0 = r0; + pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every; + { + std::lock_guard lk(part_mu); + part_at.clear(); + std::fill(part_next.begin(), part_next.end(), pp_next_check); + } + std::printf("RESUME %lld\n", (long long) resume); // before reading: this many prompt tokens are reused + strata::core::progress_at("reading the prompt, from token", read_from); + std::fflush(stdout); + // A SHORT PART OF THE PROMPT - the new message of a chat that continues from a checkpoint, the assistant + // header - goes through the verify windows, S tokens at a time, as decode reads them. The batched path + // costs ~300 ms per run however few tokens it has (it streams every expert the chunk routes to that is + // not in VRAM over PCIe), and it borrows slots it must refill after (~180 ms); a window costs ~16 ms a + // token, with the misses on the CPU. Each part below is decided on its own, so a long first message is + // read batched and its header still goes through the windows. Picture rows need the batched path. + // STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. + static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr; + auto windows_ok = [&](int64_t a, int64_t b) -> bool { + if (no_short || b - a > o.short_read) return false; + if (sp.embd_rows != nullptr) + for (int64_t i = a; i < b; ++i) + if (sp.embd_rows[i] != nullptr) return false; + return true; + }; + // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals + auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { + strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" + // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) + struct NoHeadSampling { + strata::core::Verifier& v; + explicit NoHeadSampling(strata::core::Verifier& x) : v(x) { v.set_head_sampling(false); } + ~NoHeadSampling() { v.set_head_sampling(true); } + } no_head_sampling(ver); + std::vector win((size_t) S), outw((size_t) S), nxt((size_t) S); + for (int64_t q = a; q < b;) { + if (stop_req.load()) { e = "cancelled"; return false; } + const int T = (int) std::min(S, b - q); + for (int t = 0; t < T; ++t) { + win[(size_t) t] = (int32_t) cur[(size_t) (q + t)]; + nxt[(size_t) t] = (int32_t) cur[(size_t) (q + t + 1)]; + } + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + if (!ver.run(T, win.data(), q, win_pool_fn, win_pool_user, outw.data(), e) || drive.d.failed) { + if (drive.d.failed && drive.d.fail) e = drive.d.fail; + return false; + } + // STRATA_LOGPOS=: the teacher-forced log-probability of every token read here (every + // token is committed and nxt[t] is the prompt's own next token), appended to ; the last + // column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the + // end-of-turn mass a chat model puts on raw text can be taken out of the measurement + static std::FILE* logpos = [] { + const char* p = std::getenv("STRATA_LOGPOS"); + return p != nullptr ? std::fopen(p, "ab") : nullptr; + }(); + static const int32_t logpos_extra = [] { + const char* p = std::getenv("STRATA_LOGPOS_EXTRA"); + return p != nullptr ? (int32_t) std::atoi(p) : (int32_t) 248046; + }(); + if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e)) + return false; + if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false; + q += T; + } + // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first + if (!ver.wait_commit(e)) return false; + const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); + std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, + ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); + strata::core::progress_beat(); + std::fflush(stdout); + return true; + }; + // the batched path's slots are lent just before its first run and given back (refilled) before a window + // reads - so the windows always see the whole expert cache - or once the prompt is read + // Every participant gives its loan back here: the rows it lent are refilled into the SAME slots from + // the arena, the residency table is restored, and one upload puts it on every device. A stage refills + // through its own cache and its own device - a slot refilled into the wrong cache would leave that + // stage's cache holding an expert it does not own, which is silent and produces plausible tokens. + // (split in two halves so a layer split can queue every stage's copies before it waits for any: #340) + auto refill_issue = [&](PfPart& p, std::string& e) -> bool { + tr("refill start", (long long) p.lent.size()); + const strata::core::OnDevice on(p.dev); + for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) + const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); + const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); + if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb) + : p.cache->fill_slot_queued(slot, b, e, nb))) + return false; + host_res[(size_t) i] = slot; + } + return true; + }; + auto refill_wait = [&](PfPart& p, std::string& e) -> bool { + const strata::core::OnDevice on(p.dev); + if (!p.cache->sync_queued(e)) return false; + p.lent.clear(); + p.lent_chunk = 0; + return true; + }; + auto refill_one = [&](PfPart& p, std::string& e) -> bool { + if (p.lent.empty()) return true; + return refill_issue(p, e) && refill_wait(p, e); + }; + // #340: with several stages every stage's copies go out first (each card on its own link), then each is + // waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly. + // STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31. + static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr; + auto refill = [&](std::string& e) -> bool { + const auto t_rf = Clock::now(); + int64_t n_lent = 0, n_parts = 0; + for (PfPart& p : pf_parts) + if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; } + if (n_parts > 1 && !refill_serial) { + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_issue(p, e)) return false; + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_wait(p, e)) return false; + } else { + for (PfPart& p : pf_parts) + if (!p.lent.empty() && !refill_one(p, e)) return false; + } + if (n_parts > 0) res_upload(); + if (trace && n_parts > 0) { + std::fprintf(stderr, "strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n", + (long long) n_lent, (long long) n_parts, + std::chrono::duration(Clock::now() - t_rf).count()); + std::fflush(stderr); + } + return true; + }; + // lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens + // rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that + // participant's own cache, and marking only that participant's own layers + auto lend = [&](int64_t tokens, std::string& e) -> bool { + if (pf_parts.empty()) return true; // its own buffers: nothing to lend + const auto t_ln = Clock::now(); + // what this segment needs, capped by the configured chunk: a request lends only what its own + // prompt needs, so a large chunk costs a short prompt nothing + const int64_t want_full = request_chunk(tokens, o.prefill_chunk); + // #340: a short enough request reads in the stages' own S-token chunks (nothing lent) + const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small) + : want_full; + if (want <= 0) { + e = "prefill: cannot lend buffers for an empty request segment"; + return false; + } + bool any = false; + for (PfPart& p : pf_parts) { + if (p.first < 0) continue; + if (!p.lent.empty()) { + if (want <= p.lent_chunk) continue; // its current loan already covers this + // ONLY this participant's loan goes back: `refill` would return the other participants' + // loans too, and their buffers are still laid out in their caches - marking those slots + // resident again would hand the next window a prompt buffer in place of an expert + if (!refill_one(p, e)) return false; + } + const strata::core::OnDevice on(p.dev); + const int32_t first = std::max(p.first, (int32_t) (p.cache->slots() - part_slots(p, want))); + if (want != p.sp->chunk() || first != p.first_now) { + if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false; + p.first_now = first; + } + for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only + for (int64_t ex = 0; ex < g.n_expert; ++ex) { + const size_t i = (size_t) (l * g.n_expert + ex); + if (host_res[i] >= first) { + p.lent.emplace_back((int32_t) i, host_res[i]); + host_res[i] = strata::core::kNotResident; + any = true; + } + } + p.lent_chunk = want; + } + if (any) res_upload(); + if (trace) { + int64_t n_lent = 0; + for (const PfPart& p : pf_parts) n_lent += (int64_t) p.lent.size(); + std::fprintf(stderr, "strata trace: lent %lld slots for %lld tokens in %.1f ms\n", (long long) n_lent, + (long long) want, std::chrono::duration(Clock::now() - t_ln).count()); + std::fflush(stderr); + } + return true; + }; + apply_pending(true); + // per-request sampling for the verify window's head (greedy when temperature is absent) + strata::kernels::SamplerParams req_sp; + req_sp.greedy = req_temperature <= 0.0f; + req_sp.temperature = req_temperature; + req_sp.top_p = req_top_p; + req_sp.top_k = req_top_k; + req_sp.seed = req_seed ? req_seed + : (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count(); + req_sp.min_p = std::clamp(req_min_p, 0.0f, 1.0f); + req_sp.penalty_last_n = std::max(req_penalty_last_n, 0); + req_sp.penalty_repeat = req_penalty_repeat; + req_sp.penalty_freq = req_penalty_freq; + req_sp.penalty_present = req_penalty_present; + req_sp.counter = 0; + ver.set_sampling(req_sp); + mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) + drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); + // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one + for (int st = 0; st < split_drive.n; ++st) + split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac) + ? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac); + const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap); + ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); + bool cancelled = false; + tr("prompt start", n - 1); + // The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> + // (the conversation so far), a checkpoint there, then the new turn's header. The next request of the same + // chat renders the same history - but not always the same header or the thinking of this reply - so that + // checkpoint is the one it reuses. + int64_t turn_at = -1; + if (o.prompt_cache > 0 && o.turn_token >= 0) + for (int64_t i = n - 1; i > resume; --i) + if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } + // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with + // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, + // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. + // (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one + // is cheaper to read again than the extra part costs (~0.3 s). + int64_t root_at = -1; + if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && read_from == 0) + for (int64_t i = 1; i < turn_at; ++i) + if (ids[(size_t) i] == o.turn_token) { + if (i >= o.prompt_cache_root) root_at = i; + break; + } + int64_t at = read_from; + for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) { + if (to <= at) continue; + err.clear(); + const bool win = windows_ok(at, to); + if (win && !refill(err)) { + std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); + return 1; + } + if (!win && !lend(to - at, err)) { + std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str()); + return 1; + } + const auto tsp = Clock::now(); + const bool sp_ok = win ? read_windows(at, to, err) : sp.run(ids.data() + at, to - at, at, err); + if (trace) { + std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at), + win ? "windows" : "batched", + std::chrono::duration(Clock::now() - tsp).count()); + std::fflush(stderr); + } + if (!sp_ok) { + if (!stop_req.load()) { + std::fprintf(stderr, "strata serve: %s\n", err.c_str()); + std::printf("ERR %s\n", err.c_str()); + // #224: a CUDA fault (an illegal address) poisons the context for the whole process, and + // unwinding the destructors on it could hang until the 60 s watchdog: leave at once + if (cudaPeekAtLastError() != cudaSuccess) { + std::fflush(stdout); + std::fflush(stderr); + std::_Exit(1); + } + return 1; + } + cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel + break; + } + at = to; + if ((to == turn_at || to == root_at) && !checkpoint_at(to)) { + std::printf("ERR saving a conversation checkpoint failed\n"); + return 1; + } + } + if (!refill(err)) { + std::printf("ERR refilling a lent slot failed: %s\n", err.c_str()); + return 1; + } + tr("prompt done (slots refilled)"); + const double prompt_ms = std::chrono::duration(Clock::now() - r0).count(); + std::printf("REUSED %lld\n", (long long) resume); // the prompt is read; the first window comes next + std::fflush(stdout); + // the verify windows: the first holds the last prompt token alone + int64_t p = n - 1; + int32_t x = (int32_t) ids[(size_t) (n - 1)]; + std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); + std::vector dprob((size_t) S, 0.0f); + std::vector sbuf((size_t) S, 0); + if (o.suffix_draft > 0) { + sfx.reset(); + for (int64_t t : ids) sfx.append((int32_t) t); + } + bool first_window = true; + int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; + int64_t draft_offered = 0, draft_accepted = 0; + // what the session holds once this request is done: the prompt read so far, then every committed token + std::vector consumed; + consumed.reserve((size_t) (n + max_new + S)); + for (int64_t i = 0; i < n - 1; ++i) consumed.push_back((int32_t) ids[(size_t) i]); + const char* finish = "length"; + const Clock::time_point d0 = Clock::now(); + // STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request) + static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr; + struct DecSnap { + double wait, pool, host, plan, actq, jobs, run; + int64_t misses, entries, hits, pcie; + }; + auto dec_snap = [&]() { + return DecSnap{ver.ms_wait, ver.ms_pool, ver.ms_host, drive.d.ms_plan, drive.d.ms_actq, drive.d.ms_jobs, + drive.d.ms_run, drive.d.multi_misses, drive.d.multi_entries, drive.d.cache_hits, + drive.d.pcie_experts}; + }; + const DecSnap ds0 = dec_snap(); + double dt_run = 0, dt_commit = 0, dt_draft = 0; + int64_t dec_windows = 0, dec_T = 0; + const int64_t decode_hits0 = drive.d.cache_hits; + // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) + const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); + const uint64_t file_bytes0 = src.file_read_bytes(); + const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; + if (cancelled) finish = "cancel"; + while (!cancelled && produced_n < max_new) { + int T = S_mtp; + if (req_spec_min_p > 0.0) { + T = 1; + while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T; + } + if (first_window) T = 1; + // a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it + // when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's + bool from_sfx = false; + int sfx_match = 0; + if (o.suffix_draft > 0 && !first_window) { + const int k = sfx.propose(S - 1, sbuf.data()); + sfx_match = sfx.last_match(); + if (k > 0 && sbuf[0] == drafts[0]) { + const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); + if (pk.lookup) { T = pk.t; from_sfx = true; } + } + } + const bool timed_round = !first_window; + const Clock::time_point round0 = Clock::now(); + if (p + T > o.max_context) break; + window[0] = x; + for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1]; + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + apply_pending(false); + if (hist_n > 0) { + // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the + // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts + // before that row - what plain decode would have counted there. (Until 0.1.19 only row 0 + // was staged, and the drafted rows read unwritten slots.) + strata::kernels::penalty_rows(consumed.data(), (int64_t) consumed.size(), window.data(), T, + hist_n, hist_stage.data()); + const strata::core::OnDevice on_h(hist_dev); + cudaMemcpy(d_hist, hist_stage.data(), (size_t) T * (size_t) hist_n * sizeof(int32_t), + cudaMemcpyHostToDevice); + } + tr("window", p, T); + const Clock::time_point tw0 = Clock::now(); + if (!ver.run(T, window.data(), p, win_pool_fn, win_pool_user, outv.data(), err) || drive.d.failed) { + std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); + return 1; + } + int a = 0; + while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; + if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + const Clock::time_point tw1 = Clock::now(); + std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) + bool adapt_ok = true; + if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) + adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + if (!ver.commit(a + 1, err)) { + if (adapt_thr.joinable()) adapt_thr.join(); + std::printf("ERR %s\n", err.c_str()); + return 1; + } + // the window's first a + 1 tokens are in the session now (the last output is not: it is next x) + for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]); + draft_offered += T - 1; + draft_accepted += a; + first_window = false; + bool eos = false; + for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { + std::printf("T %d\n", (int) outv[(size_t) i]); + strata::core::progress_beat(); + ++produced_n; + if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); + } + std::fflush(stdout); + ++rounds; + const Clock::time_point tw2 = Clock::now(); + // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's + // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will + if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new) + mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]); + const bool drafted = eos || produced_n >= max_new || + mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p); + { + const Clock::time_point tw3 = Clock::now(); + auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration(b0 - a0).count(); }; + dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3); + ++dec_windows; dec_T += T; + } + if (adapt_thr.joinable()) adapt_thr.join(); + if (!adapt_ok) { + std::printf("ERR an adaptive refill failed\n"); + return 1; + } + if (!drafted) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + if (timed_round && !eos) + policy.observe(from_sfx, T, a, sfx_match, + std::chrono::duration(Clock::now() - round0).count()); + if (eos) { finish = "stop"; break; } + if (stop_req.load()) { finish = "cancel"; break; } + x = outv[(size_t) a]; + p += a + 1; + } + const double decode_ms = std::chrono::duration(Clock::now() - d0).count(); + // the last commit (set_commit_async): the session is complete before anything reads or copies it + if (!ver.wait_commit(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + if (dec_timing && dec_windows > 0) { + const DecSnap d1 = dec_snap(); + const double w = (double) dec_windows, L = (double) g.n_layers; + std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " + "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " + "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " + "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f\n", + (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w, + (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w, + (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w, + (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L), + (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L)); + const std::string pr = ver.profile_report(); + if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str()); + } + if (!cancelled) { + // a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from + // (the checkpoints taken while reading it are still good) + live.swap(consumed); + live_imgs = imgs_below(req_imgs, (int64_t) live.size()); + live_ok = o.prompt_cache > 0; + } + static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr; + if (state_hash && live_ok) { + // DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and + // separately of what lies past them in the last KV page (stale cells, fine unless something reads them) + if (cudaDeviceSynchronize() != cudaSuccess) { + std::printf("ERR synchronizing state fingerprint\n"); + return 1; + } + const int64_t L = (int64_t) live.size(); + const strata::kernels::QsaShapes qs = [&] { + strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes(); + s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim; + return s; + }(); + bool hash_ok = true; + std::array hash_buffer; + auto hash_dev = [&](const void* p, size_t bytes, uint64_t h) { + for (size_t offset = 0; hash_ok && offset < bytes;) { + const size_t n = std::min(hash_buffer.size(), bytes - offset); + // VRAM or a streamed host copy, with fixed diagnostic workspace. + if (cudaMemcpy(hash_buffer.data(), static_cast(p) + offset, n, cudaMemcpyDefault) != cudaSuccess) { + hash_ok = false; + break; + } + h = fnv1a(hash_buffer.data(), n, h); + offset += n; + } + return h; + }; + // the cells [c0, c1) of one int8 K or V pool ([page][kv_head][page_size][head_dim]), bytes per value `w` + auto hash_cells = [&](const void* pool, int64_t per_cell, int64_t c0, int64_t c1, uint64_t h) { + const int64_t ps = qs.page_size; + for (int64_t pg = c0 / ps; pg * ps < c1; ++pg) + for (int64_t hd = 0; hd < qs.n_head_kv; ++hd) { + const int64_t a = std::max(c0, pg * ps) - pg * ps, e = std::min(c1, (pg + 1) * ps) - pg * ps; + const size_t off = (size_t) (((pg * qs.n_head_kv + hd) * ps + a) * per_cell); + h = hash_dev((const uint8_t*) pool + off, (size_t) ((e - a) * per_cell), h); + } + return h; + }; + const ConvStateSizes z = conv_state_sizes(g, ss); + uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull); + if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && ss.gdn_alloc > 0) { // per GDN layer: which one differs first + const size_t per = z.gdn / (size_t) ss.gdn_alloc; + std::string s; + char b[8]; + for (int64_t i = 0; i < ss.gdn_alloc; ++i) { + std::snprintf(b, sizeof(b), "%04llx ", (unsigned long long) (hash_dev((const uint8_t*) ss.gdn_state + i * per, per, 1469598103934665603ull) & 0xffff)); + s += b; + } + std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str()); + } + uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull); + uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail; + // pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the + // spare row at L / idx_block (the `dead` key the next block completion overwrites), which a + // conversation restore writes back; dead= is the spare key itself + uint64_t h_dead = h_tail, h_pool_full = h_tail; + const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2; + // a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one + auto kv_arrays = [&](const strata::core::QsaState& st) { + const bool h = st.kv_mode != 0; + std::vector> a; + if (st.kv_q4) { + const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); + a = {{h ? st.host.k_q4 : st.k_q4, q4b}, {h ? st.host.v_q4 : st.v_q4, q4b}}; + } else if (st.kv_hybrid) { + const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, + {h ? st.host.k_scale : st.k_scale, scb}}; + } else if (st.without_key) { + a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } else if (st.kv_int8) { + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, + {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } else { + a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2}, + {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}}; + } + return a; + }; + const int64_t end_cell = std::min(((L + qs.page_size - 1) / qs.page_size) * qs.page_size, + ss.max_cells); // = the primary state's max_cells + for (int64_t j = 0; j < ss.qsa_alloc; ++j) { // this session's owned QSA ordinals only + const strata::core::QsaState& st = ss.qsa_states[ss.qsa_ord0 + j]; + h_tail = hash_dev(st.idx_tail, z.tail, h_tail); + h_dead = hash_dev(st.idx_dead, z.dead, h_dead); + h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool); + h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, + h_pool_full); + // KV streaming: the host copy is the identity layout and holds every cell + for (const auto& [pool, w] : kv_arrays(st)) { + h_kv = hash_cells(pool, w, 0, L, h_kv); + h_stale = hash_cells(pool, w, L, end_cell, h_stale); + } + } + const strata::core::QsaState& ms = mtp.kv_state(); + uint64_t h_mtp = 1469598103934665603ull; + const int64_t mL = std::min(L, ms.max_cells); + for (const auto& [pool, w] : kv_arrays(ms)) + if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); + if (!hash_ok) { + std::printf("ERR reading state fingerprint\n"); + return 1; + } + std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " + "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n", (long long) L, + (unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail, + (unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp, + (unsigned long long) h_stale, (unsigned long long) h_dead, + (unsigned long long) h_pool_full, ss.ple_prev[0], ss.ple_prev[1]); + } + const int64_t req_hits = drive.d.cache_hits - decode_hits0; + const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0; + // DONE [hits] [lookups] + // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) + std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n, + (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, + (long long) resume, (long long) req_hits, (long long) req_look, + (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), + (double) (src.file_read_bytes() - file_bytes0) / 1e6); + std::fflush(stdout); + if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session + const int64_t fresh = n - resume; + std::fprintf(stderr, "strata serve: prompt %lld tokens = %lld reused + %lld read in %.0f ms (%.1f tok/s), " + "%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n", + (long long) n, (long long) resume, (long long) fresh, prompt_ms, + prompt_ms > 0 ? 1000.0 * fresh / prompt_ms : 0.0, (long long) produced_n, decode_ms, + decode_ms > 0 ? 1000.0 * produced_n / decode_ms : 0.0, (long long) draft_accepted, + (long long) draft_offered, checks.size(), cancelled ? " (cancelled)" : ""); + // the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU + // to read (--pcie-frac) are in neither count + if (req_look > 0) { + std::fprintf(stderr, "strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)\n", + 100.0 * (double) req_hits / (double) req_look, + (long long) req_hits, (long long) req_look); + } +#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) + if (kar_expert_archive != nullptr) + std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n", + (unsigned long long) kar_expert_miss.computed()); +#endif + // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain + // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) + if (src.complement_ready()) + std::fprintf(stderr, "strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the " + "VRAM tier, %lld blob reads from the file\n", + (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), + (long long) src.file_reads()); + // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) + if (srcp == &src) + std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " + "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(), + (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6, + src.gguf_mode() ? " (the GGUF in place)" : ""); + // STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start + // (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) + if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing) + for (int st = 0; st < n_stages; ++st) { + const strata::core::Verifier& v = stage_ver(st); + const double w = v.windows > 0 ? (double) v.windows : 1.0; + std::fprintf(stderr, "strata serve: stage %d: %lld windows; per window: wait for the GPU %.3f ms, " + "pool + plan %.3f ms, host staging %.3f ms, commit %.3f ms\n", st, + (long long) v.windows, v.ms_wait / w, v.ms_pool / w, v.ms_host / w, v.ms_commit / w); + } + if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { + // KV streaming, cumulative over the process: blocks the selections named vs blocks read from RAM + // (this device's owned ordinals; a split's other stages hold theirs) + uint64_t miss = 0, look = 0; + bool over = false; + for (int64_t j = 0; j < ss.qsa_alloc; ++j) { + const strata::kernels::KvStreamCounters c = + strata::kernels::kv_stream_counters(ss.qsa_states[ss.qsa_ord0 + j].map); + miss += c.misses; look += c.lookups; over = over || c.overflow; + } + std::fprintf(stderr, "strata serve: KV streaming: %.2f%% of %llu block reads hit VRAM, %.1f MiB read " + "from RAM%s\n", look ? 100.0 * (double) (look - miss) / (double) look : 100.0, + (unsigned long long) look, (double) miss * 4224.0 / 1048576.0, + over ? " - OVERFLOW (too few resident cells)" : ""); + } + if (sfx_windows > 0) + std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n", + (long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts); + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " + "(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " + "waiting for it in this request\n", r + 1, + (long long) (remote_experts[(size_t) r].computed() - remote_before[(size_t) r]), + (long long) (remote_experts[(size_t) r].launched_layers() - launches_before[(size_t) r]), + (double) (remote_experts[(size_t) r].returned_bytes() - compact_before[(size_t) r]) / 1048576.0, + (double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0, + remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], + remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); + } + if (o.stats && ple_table.kar_gpu_cache_enabled()) + std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str()); + return 0; + } + + // ---- plan v0.3 P5: the prompt's conditioning positions [0, n_prompt - 1) in batched chunks. The token loop + // then starts at the last prompt position, whose prediction is the first generated token. + int64_t pos_start = 0; + int64_t spec_pos = 0; // plan v0.3 P6: where the speculative loop starts (0 = not used) + strata::prefill::Prefill prefill; + double prefill_batched_ms = 0; + std::FILE* final_r = o.dump_final_r.empty() ? nullptr : std::fopen(o.dump_final_r.c_str(), "wb"); + std::vector final_r_host(final_r ? (size_t) (g.hc * g.n_embd) : 0); + std::vector> lent; // (residency index, slot) lent to the prompt path + const int64_t n_batched = (o.prefill_until > 0 && o.prefill_until < n_prompt - 1) ? o.prefill_until : n_prompt - 1; + if (o.prefill_chunk > 0 && n_prompt > 1) { + void* borrow = nullptr; + uint64_t borrow_bytes = 0; + if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) { + int64_t chunk = o.prefill_chunk; + int64_t k = plan_lend(chunk); // auto: the largest chunk that fits; fixed: halved to fit + const int64_t request_sized = request_chunk(n_batched, chunk); + if (k > 0 && request_sized < chunk) { // no bigger than this prompt segment needs + chunk = request_sized; + k = lend_slots(chunk); + if (k + 128 > xcache.slots()) k = 0; + if (!o.prefill_auto) o.prefill_chunk = chunk; + } + if (o.prefill_auto) { + o.prefill_chunk = k > 0 ? chunk : request_chunk(n_batched, 1024); + std::fprintf(stderr, "strata generate: prompt chunk auto: %lld tokens\n", (long long) o.prefill_chunk); + } else if (chunk != o.prefill_chunk) { + k = 0; // a fixed chunk that does not fit: its own buffers, as before + } + const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; + if (k > 0) { // the lent slots are refilled after the prompt + const int32_t first = (int32_t) (xcache.slots() - k); + for (size_t i = 0; i < host_res.size(); ++i) + if (host_res[i] >= first) { + lent.emplace_back((int32_t) i, host_res[i]); + host_res[i] = strata::core::kNotResident; + } + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + borrow = xcache.device_slot(first); + borrow_bytes = xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first]) + : (uint64_t) k * (uint64_t) blob; + std::fprintf(stderr, "strata generate: prompt path borrows %lld cache slots (%.2f GiB)\n", (long long) k, + (double) borrow_bytes / 1073741824.0); + } + } + if (borrow == nullptr) + std::fprintf(stderr, "strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n"); + if (!prefill.init(wt, g, ss, srcp, o.expert_cache > 0 ? &xcache : nullptr, + host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow, + borrow_bytes)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (!o.mtp.empty()) { + if (!mtp.bind(wt, &native_head, nullptr, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + prefill.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool { + // cell i pairs R_i with the token at i + 1 (every such token is in the prompt) + std::vector nxt((size_t) T); + for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)]; + if (prefill.draft_kv(mtp, R_rows, nxt.data(), T, p0, e)) return true; // E-9 + return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e); + }; + } + const Clock::time_point tp0 = Clock::now(); + if (!prefill.run(o.tokens.data(), n_batched, 0, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + // refill the lent slots from the arena and give them back to the decode tier + if (!lent.empty()) { + const Clock::time_point tr = Clock::now(); + for (const auto& [i, slot] : lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) + const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert); + const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert); + if (b == nullptr || !(refill_blocking() ? xcache.fill_slot_blocking(slot, b, err, nb) + : xcache.fill_slot_queued(slot, b, err, nb))) { + std::fprintf(stderr, "strata generate: refilling a lent slot failed: %s\n", err.c_str()); + return 1; + } + host_res[(size_t) i] = slot; + } + if (!xcache.sync_queued(err)) { + std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str()); + return 1; + } + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), + std::chrono::duration(Clock::now() - tr).count()); + } + prefill_batched_ms = std::chrono::duration(Clock::now() - tp0).count(); + prefill_ms += prefill_batched_ms; + pos_start = n_batched; + tok = o.tokens[(size_t) pos_start]; + // the PLE window of the token path: the two tokens before `pos_start` + ss.ple_prev[0] = pos_start >= 2 ? (int32_t) o.tokens[(size_t) (pos_start - 2)] : -1; + ss.ple_prev[1] = pos_start >= 1 ? (int32_t) o.tokens[(size_t) (pos_start - 1)] : -1; + const strata::prefill::PrefillStats& ps = prefill.stats(); + std::fprintf(stderr, "strata generate: prefill %lld tokens in %lld chunks, %.1f ms (%.1f tok/s); experts " + "streamed %lld (%lld by DMA, host %.1f ms), resident %lld; PLE %.1f ms\n", + (long long) ps.tokens, (long long) ps.chunks, ps.ms_total, + ps.ms_total > 0 ? 1000.0 * (double) ps.tokens / ps.ms_total : 0.0, (long long) ps.experts_streamed, + (long long) ps.experts_dma, ps.ms_experts_host, (long long) ps.experts_resident, ps.ms_ple); + } + + for (int64_t pos = pos_start;; ++pos) { + // plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1) + if (native_pack) { spec_pos = pos; break; } + if (pos >= o.max_context) { + std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) pos); + return 2; + } + // **THE TOKEN TIMER STARTS HERE, BEFORE ANY OF THE TOKEN'S WORK (A7).** It used to start after + // `put_input`/`embed_row`, which excluded the embedding and the PLE window advance from the reported + // rate, and it stopped before the NaN scan, the logits dump and the sampler. The published tok/s + // figure is a WALL-CLOCK rate: everything one token costs, PLE advance to sampled id. A rate that + // excludes real per-token work is not a rate anyone can plan against. + const Clock::time_point t0 = Clock::now(); + // **THE PLE'S TOKEN WINDOW ADVANCES HERE, ONCE PER TOKEN, AND `ple_stage_token` RUNS OUTSIDE THE + // CAPTURE.** Both are the driver's job: `ngram_rows` is a host hash over the last three tokens and the + // table gather is a host read, so either one inside a captured graph would run once at capture time and + // replay forever. `ple_prev` is OLDEST FIRST and `-1` means "no predecessor", which `ngram_rows` + // treats as the EOS cut - a sequence boundary. + ss.ple_token = (int32_t) tok; + Clock::time_point tp = Clock::now(); + // Plan v0.3 P2: the 16 SSD reads start here and complete while the embedding is staged; `ms_ple` is + // the issue plus the time still spent WAITING afterwards, i.e. the part the embedding did not hide. + if (ss.ple.ready() && !strata::core::ple_issue_token(ss.ple, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + { + const Clock::time_point n = Clock::now(); + ms_ple += std::chrono::duration(n - tp).count(); + tp = n; + } + if (!put_input(tok, pos)) return 1; + { + const Clock::time_point n = Clock::now(); + ms_embed += std::chrono::duration(n - tp).count(); + tp = n; + } + if (ss.ple.ready() && !strata::core::ple_finish_token(ss.ple, token_stream, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + { + const Clock::time_point n = Clock::now(); + ms_ple += std::chrono::duration(n - tp).count(); + tp = n; + } + + if (pos % 256 == 0 || pos + 1 >= n_prompt - 1) + std::fprintf(stderr, "strata generate: position %lld, token %lld%s\n", (long long) pos, (long long) tok, + pos < n_prompt ? " (prompt)" : ""); + // **`d.layers` IS THE BLOB'S LAYER AXIS, NOT A COUNTER.** The adapter uses it to index + // `experts.bin` as `layer * n_expert + expert`, so it MUST restart at 0 for every token. Leaving it + // running across tokens asks for layer 48 of a 48-layer file on the second token - which + // `FileExpertSource` REFUSES rather than wrapping into layer 0's experts, and that refusal is the only + // reason this was a clean error instead of a silently wrong second token. + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + err.clear(); + if (o.no_capture) { + if (!strata::core::session_token(wt, g, pos, /*pos_base=*/0, ss, d_parts, main_cs, + o.sync_every_layer, err)) { + std::fprintf(stderr, "strata generate: session_token: %s\n", err.c_str()); + return 1; + } + } else { + strata::core::doorbell_reset(db); + if (tgraph.captured) { + if (!strata::core::session_run_token(g, pos, /*pos_base=*/0, ss, tgraph, pool_fn, pool_user, + loop_scratch.y_miss, main_cs, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + } else if (!strata::core::session_loop(g, pos, /*pos_base=*/0, ss, gr, pool_fn, hit_fn, pool_user, /*overlap=*/true, main_cs, + err, layer_stage, &loop_scratch)) { + std::fprintf(stderr, "strata generate: session_loop: %s\n", err.c_str()); + return 1; + } + } + if (final_r != nullptr) { + cudaMemcpy(final_r_host.data(), ss.R, final_r_host.size() * sizeof(float), cudaMemcpyDeviceToHost); + const int64_t posrec[2] = {pos, tok}; + std::fwrite(posrec, sizeof posrec, 1, final_r); + std::fwrite(final_r_host.data(), sizeof(float), final_r_host.size(), final_r); + } + if (drive.d.failed) { + std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", + (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, + drive.d.fail ? drive.d.fail : "(no message)"); + return 1; + } + { + // **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.** + const Clock::time_point n = Clock::now(); + ms_layers += std::chrono::duration(n - tp).count(); + tp = n; + } + // ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first. + if (layer_dump != nullptr) std::fwrite(layer_stage, sizeof(float), layer_floats, layer_dump); + if (half_dump != nullptr) { + std::fwrite(half_stage, sizeof(float), (size_t) g.n_layers * (size_t) half_stride, half_dump); + } + if (!run_head(token_stream)) { + std::fprintf(stderr, "strata generate: lm_head: %s\n", err.c_str()); + return 1; + } + // **A CHECKPOINT AFTER THE HEAD, BECAUSE AN ASYNC FAULT IS STICKY AND LIES ABOUT WHERE IT HAPPENED.** + // Measured, and it cost an hour: without this, `embed_row`'s D2H on the NEXT token reported "an illegal + // memory access" at a plane offset that has nothing to do with the fault, and the layer that actually + // faulted had completed its own error checks successfully - because its kernels had not run yet. A + // sticky error surfaces at the next SYNCHRONISING call, which is whatever happens to come next. + if (!o.stream_token && cudaDeviceSynchronize() != cudaSuccess) { + std::fprintf(stderr, "strata generate: the device faulted in lm_head at position %lld: %s\n", + (long long) pos, cudaGetErrorString(cudaGetLastError())); + return 1; + } + { + const Clock::time_point n = Clock::now(); + ms_head += std::chrono::duration(n - tp).count(); + tp = n; + } + const bool emit_logits = dump != nullptr && + strata::program::logits_selection::selected(pos, dump_positions, o.logits_stride); + const bool read_logits = !o.stream_token || o.check_logits || emit_logits; + if (read_logits && (cudaMemcpyAsync(logits.data(), d_logits, (size_t) n_vocab * 4, + cudaMemcpyDeviceToHost, (cudaStream_t) token_stream) != cudaSuccess || + cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess)) { + std::fprintf(stderr, "strata generate: reading the logits back failed\n"); + return 1; + } + int bad = 0; + if (read_logits) for (float v : logits) if (!std::isfinite(v)) ++bad; + if (bad != 0) { + std::fprintf(stderr, "strata generate: %d of %lld logits are not finite at position %lld\n", bad, + (long long) n_vocab, (long long) pos); + return 1; + } + if (emit_logits && std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) { + std::fprintf(stderr, "strata generate: cannot write logits at position %lld\n", (long long) pos); + std::fclose(dump); + return 1; + } + { + // **993 KB OF SYNCHRONOUS D2H AND A 248,320-FLOAT HOST SCAN, EVERY TOKEN.** (The review's notes + // say 151,936 floats; the artifact's `output.weight` is 248,320 rows, so the real figure is 1.6x + // that - a number nobody had checked because nothing measured this term.) R2.6 asks for the dump + // and the scan to be behind flags; round 36 did exactly that and measured it SLOWER, because on + // this driver a large blocking readback is also what flushes the pipeline for the sampler that + // follows. Timed so the claim can be re-checked rather than remembered. + const Clock::time_point n = Clock::now(); + ms_readback += std::chrono::duration(n - tp).count(); + tp = n; + } + + int next = 0; + // The draw is Philox(seed, position), as in a verify window (row t at pos0 draws pos0 + t): a seed gives + // the same text whether a token comes from this path or from the speculative loop below. + sp.counter = (uint64_t) pos; + strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream); + if (cudaMemcpyAsync(&next, d_next, sizeof(int), cudaMemcpyDeviceToHost, + (cudaStream_t) token_stream) != cudaSuccess || + cudaStreamSynchronize((cudaStream_t) token_stream) != cudaSuccess) { + std::fprintf(stderr, "strata generate: reading the sampled token back failed: %s\n", + cudaGetErrorString(cudaGetLastError())); + return 1; + } + // The sampled-token synchronization also completes every captured QSA + // status readback. Retain one status per layer so a later layer cannot + // hide an earlier failure; no extra synchronization or token allocation. + if (o.native_flash_attn_short) for (int64_t j = 0; j < ss.qsa_alloc; ++j) { + const int64_t i = ss.qsa_ord0 + j; // the global ordinal, as the session's carve names it + const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount]; + if (status != 0) { + std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n", + status, (long long) i, (long long) pos); + return 1; + } + } + if (next < 0 || next >= n_vocab) { + std::fprintf(stderr, "strata generate: the sampler returned %d, outside 0..%lld\n", next, + (long long) (n_vocab - 1)); + return 1; + } + { + // **TWO DEVICE-WIDE SYNCS FOR FOUR BYTES.** `sample_tokens(nullptr)` ends in + // `cudaDeviceSynchronize()` (`sampler.cu:245`) and the blocking 4-byte read below is the second. + const Clock::time_point n = Clock::now(); + ms_sample += std::chrono::duration(n - tp).count(); + ++phase_tokens; + } + // CHARGED HERE, AFTER THE SAMPLER, so the wall-clock rate covers the whole token including the embedding, + // the NaN scan, the logits readback and the sample (A7). Only DECODE positions count; prefill is + // measured separately. + if (pos >= n_prompt - 1) total_ms += std::chrono::duration(Clock::now() - t0).count(); + else prefill_ms += std::chrono::duration(Clock::now() - t0).count(); + if (pos == n_prompt - 1) ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); + // **THE PREDICTION AT THE LAST PROMPT POSITION *IS* THE FIRST GENERATED TOKEN.** Sampling on every + // position and recording only from `n_prompt - 1` onward is what keeps the two cases from needing + // separate handling - and the version that "obviously" only samples after the prompt loses exactly one + // token's worth of conditioning. + if (pos >= n_prompt - 1) produced.push_back(next); + if ((int64_t) produced.size() >= o.max_new) break; + if (o.stop_eos && pos >= n_prompt - 1 && + std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) next) != o.eos_ids.end()) break; + // TEACHER FORCING while the prompt lasts: the next input is the prompt's own next token, not the + // model's guess. Feeding the guess would make the run depend on the model's own errors from position + // 1, which is a different (and worse) measurement of the same prompt. + // and the window advances: the token just decoded becomes the newest predecessor. + ss.ple_prev[0] = ss.ple_prev[1]; + ss.ple_prev[1] = (int32_t) tok; + tok = (pos + 1 < n_prompt) ? o.tokens[(size_t) (pos + 1)] : next; + // Plan v0.3 P6: from the first generated token on, the speculative loop below takes over. + if (o.spec > 0 && pos >= n_prompt - 1) { spec_pos = pos + 1; break; } + } + + // ================================ plan v0.3 P6: SPECULATIVE DECODING ================================ + // + // Each round verifies [the last emitted token, drafts...] in one window; the window's argmax after token t + // is exactly what greedy decode would emit there, so the first draft that differs ends the round and the + // round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted. + const bool ended = o.stop_eos && !produced.empty() && + std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) produced.back()) != o.eos_ids.end(); + if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) { + std::vector oracle; + if (!o.spec_oracle.empty()) { + std::ifstream in(o.spec_oracle); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + std::string e; + if (!in || !parse_i64_list(text.c_str(), oracle, e)) { + std::fprintf(stderr, "strata generate: cannot read --spec-oracle %s\n", o.spec_oracle.c_str()); + return 2; + } + } + if (thits.d_res == nullptr) { + std::fprintf(stderr, "strata generate: --spec needs the device residency table (--expert-profile, " + "--expert-cache and the token graph)\n"); + return 2; + } + mem_mark("the head and the prompt path"); + strata::core::Verifier ver; + strata::core::VerifyHits vh; + vh.d_res = thits.d_res; + vh.cache_base = thits.cache_base; + vh.blob = thits.blob; + vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers + vh.n_slots = xcache.slots(); + if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + const bool use_mtp = !o.mtp.empty(); + if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + mem_mark("the verifier and the drafter's binding"); + ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here + if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) + ver.set_split(o.spec_split); + // auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call + // cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; + // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy + // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). + ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + drive.d.plan = ver.plan_sink(); + drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5); + if (drive.d.pcie_num < 0) drive.d.pcie_num = 0; + if (drive.d.pcie_num > 256) drive.d.pcie_num = 256; + const int64_t pcie0 = drive.d.pcie_experts; + // CS-T: the file tier since the decode began (the prompt path's copies are before this) + const int64_t files0 = src.file_reads(), ram0 = src.ram_reads(); + const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes(); + const double fms0 = src.file_ms(); + if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); + int64_t swaps_total = 0; + double ms_adapt = 0; + cudaStream_t adapt_stream = nullptr; + if (!drive.d.usage.empty() && cudaStreamCreateWithFlags(&adapt_stream, cudaStreamNonBlocking) != cudaSuccess) { + std::fprintf(stderr, "strata generate: cannot create the refill stream\n"); + return 1; + } + // plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed + std::vector> pending; + cudaEvent_t adapt_ev = nullptr; + cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming); + auto apply_pending = [&](bool wait) { + if (pending.empty()) return; + if (wait) cudaEventSynchronize(adapt_ev); + else if (cudaEventQuery(adapt_ev) != cudaSuccess) return; + src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM + for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot; + pending.clear(); + if (d_res != nullptr) + cudaMemcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + }; + // Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least + // twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was + // routed clearly more often. Copies run between rounds, when the GPU is idle. + auto adapt = [&]() -> bool { + const Clock::time_point ta = Clock::now(); + if (!pending.empty()) return true; // the previous swaps are still in flight + struct Swap { float gain; int32_t layer, in, out; }; + std::vector swaps; + std::vector> cand, vict; + for (int64_t l = 0; l < g.n_layers; ++l) { + cand.clear(); + vict.clear(); + const float* u = drive.d.usage.data() + l * g.n_expert; + const int32_t* r = host_res.data() + l * g.n_expert; + for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { + if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); } + else vict.emplace_back(u[e], e); + } + if (cand.empty() || vict.empty()) continue; + std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); + const size_t nc = std::min(cand.size(), vict.size()); + std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), + [](auto& a, auto& b) { return a.first < b.first; }); + for (size_t i = 0; i < nc; ++i) { + if (cand[i].first < vict[i].first + 1.5f) break; + swaps.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); + } + } + std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; }); + if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps); + if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) { + std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n"); + return false; + } + for (const Swap& s : swaps) { + const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; + const int32_t slot = host_res[out]; + const uint8_t* b = srcp->blob(s.layer, s.in); + // asynchronous: the copies run while the MTP drafts; the next window waits for them + if (slot < 0 || b == nullptr || + cudaMemcpyAsync(xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), + cudaMemcpyHostToDevice, adapt_stream) != cudaSuccess) { + std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); + return false; + } + host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile + pending.emplace_back((int32_t) in, slot); // resident once the copy has landed + } + if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); + for (float& v : drive.d.usage) v *= 0.7f; + swaps_total += (int64_t) swaps.size(); + ms_adapt += std::chrono::duration(Clock::now() - ta).count(); + return true; + }; + int64_t p = spec_pos; + int32_t x = (int32_t) tok; + std::vector drafts((size_t) o.spec, 0); + std::vector dprob((size_t) o.spec, 1.0f); + std::vector window_hist((size_t) o.spec + 1, 0); + // plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first + // generated token and the MTP's first cell); otherwise the token loop already did that. + bool first_window = native_pack; + if (use_mtp && !first_window && + !mtp.draft_first(o.spec, ss.R, x, p - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::vector window((size_t) o.spec), outv((size_t) o.spec); + std::vector accepted_hist((size_t) o.spec, 0); + int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0; + const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec; + if (use_mtp && S_mtp < o.spec) mtp.set_max_drafts(S_mtp - 1); + strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); + strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp) + std::vector sbuf((size_t) o.spec, 0); + int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0; + if (o.suffix_draft > 0) { + for (int64_t t : o.tokens) sfx.append((int32_t) t); + for (int64_t t : produced) sfx.append((int32_t) t); + } + const double pool_ms0 = drive.cpu_ms; + const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries; + while ((int64_t) produced.size() < o.max_new) { + const Clock::time_point t0 = Clock::now(); + int T = S_mtp; + if (use_mtp && o.spec_min_p > 0.0) { + T = 1; + while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T; + } + if (first_window) T = 1; + bool from_sfx = false; + int sfx_match = 0; + if (o.suffix_draft > 0 && !first_window) { + const int k = sfx.propose(o.spec - 1, sbuf.data()); + sfx_match = sfx.last_match(); + if (k > 0 && (!use_mtp || sbuf[0] == drafts[0])) { + const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); + if (pk.lookup) { T = pk.t; from_sfx = true; } + } + } + const bool timed_round = !first_window; + ++window_hist[(size_t) T]; + if (p + T > o.max_context) { + std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p); + return 2; + } + window[0] = x; + for (int i = 1; i < T; ++i) { + const size_t at = produced.size() - 1 + (size_t) i; + int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1] + : at < oracle.size() ? (int32_t) oracle[at] : 0; + if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab; + window[(size_t) i] = d; + } + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + apply_pending(false); + if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + if (drive.d.failed) { + std::fprintf(stderr, "strata generate: the expert pool failed at layer %lld expert %lld: %s\n", + (long long) drive.d.fail_layer, (long long) drive.d.fail_expert, + drive.d.fail ? drive.d.fail : "(no message)"); + return 1; + } + int a = 0; + while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; + if (first_window) { + first_window = false; + ttft_ms = std::chrono::duration(Clock::now() - t_start).count(); + // Diagnostics: the first window runs the prompt's last token over the state the prompt path left + // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never + // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. + if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) { + std::vector row((size_t) ver.vocab()); + std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr; + if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) + std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl); + if (f) std::fclose(f); + } + } + // plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the + // GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window + std::thread adapt_thr; + bool adapt_ok = true; + if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) + adapt_thr = std::thread([&] { adapt_ok = adapt(); }); + if (!ver.commit(a + 1, err)) { + if (adapt_thr.joinable()) adapt_thr.join(); + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + ++rounds; + drafts_total += T - 1; + drafts_ok += a; + ++accepted_hist[(size_t) a]; + if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } + bool eos = false; + for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) { + produced.push_back(outv[(size_t) i]); + if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]); + eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end(); + } + if (eos) { + if (adapt_thr.joinable()) adapt_thr.join(); + total_ms += std::chrono::duration(Clock::now() - t0).count(); + break; + } + const bool drafted = !use_mtp || (int64_t) produced.size() >= o.max_new || + mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p); + if (adapt_thr.joinable()) adapt_thr.join(); + if (!adapt_ok) return 1; + if (!drafted) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + x = outv[(size_t) a]; + p += a + 1; + const double round_ms = std::chrono::duration(Clock::now() - t0).count(); + total_ms += round_ms; + if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms); + if (rounds % 64 == 0) + std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p, + (long long) produced.size(), (long long) rounds); + } + // the last commit (set_commit_async) before anything reads the session again + if (!ver.wait_commit(err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } + std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n", + "speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total, + drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0, + rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0); + if (o.spec_min_p > 0.0) { + std::printf("%-24s", "window sizes"); + for (size_t i = 1; i < window_hist.size(); ++i) std::printf(" T%zu:%lld", i, (long long) window_hist[i]); + std::printf(" (min draft probability %.2f)\n", o.spec_min_p); + } + if (o.suffix_draft > 0) + std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows, + (long long) sfx_ok, (long long) sfx_drafts); + std::printf("%-24s", "accepted per round"); + for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); + std::printf("\n"); + if (rounds > 0) + std::printf("%-24s wait for rings %.3f pool %.3f host %.3f commit %.3f ms/round; CPU experts %.2f " + "distinct / %.2f routed per layer\n", + "verify window", ver.ms_wait / rounds, ver.ms_pool / rounds, ver.ms_host / rounds, + ver.ms_commit / rounds, + (double) (drive.d.multi_misses - misses0) / (double) (rounds * g.n_layers), + (double) (drive.d.multi_entries - entries0) / (double) (rounds * g.n_layers)); + if (rounds > 0) + std::printf("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; " + "CPU pool call %.3f ms/round\n", "pool multi", pool.ms_multi_gu / rounds, + pool.ms_multi_q / rounds, pool.ms_multi_down / rounds, + (double) pool.multi_bytes / 1e6 / std::max(1e-9, pool.ms_multi_gu + pool.ms_multi_down), + (drive.cpu_ms - pool_ms0) / rounds); + if (rounds > 0) + std::printf("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n", "dispatch", + drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds, + drive.d.ms_run / rounds); + if (rounds > 0 && !drive.d.usage.empty()) + std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier", + (long long) swaps_total, o.adapt_every, ms_adapt / rounds); + if (src.complement_ready()) + std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " + "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, + (long long) src.exchanges(), (long long) src.file_reads()); + if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) + const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6; + std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " + "%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n", + "expert tiers", (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0), + fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, + fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", + (double) (fall0 - fbytes0) / 1e6); + if (drive.d.lookahead != nullptr) + std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " + "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch", + (long long) src.warmed(), (long long) src.warmed_hits(), + (long long) (src.file_reads() - files0), + src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0, + rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped()); + } + if (rounds > 0 && drive.d.pcie_num > 0) + std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", + "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), + drive.d.pcie_num); + (void) pool_ms0; + if (use_mtp && rounds > 0) + std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp", + mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill, + (double) mtp.vram_bytes() / 1048576.0); + } + + if (dump != nullptr && std::fclose(dump) != 0) { + std::fprintf(stderr, "strata generate: cannot finish logits dump\n"); + return 1; + } + if (layer_dump != nullptr) { + std::fclose(layer_dump); + cudaFreeHost(layer_stage); + std::printf("%-24s %s (%lld layers + the input x %d streams x %lld per position)\n", "layers dumped", + o.dump_layers.c_str(), (long long) g.n_layers, (int) g.hc, (long long) g.n_embd); + } + if (half_dump != nullptr) { + std::fclose(half_dump); + cudaFreeHost(half_stage); + std::printf("%-24s %s (%lld layers x %llu per position)\n", "halves dumped", o.dump_halves.c_str(), + (long long) g.n_layers, (unsigned long long) half_stride); + } + if (routing != nullptr) { + std::fclose(routing); + drive.routing = nullptr; + std::printf("%-24s %s (%lld records of layer, k, ids, weights)\n", "routing dumped", + o.dump_routing.c_str(), (long long) drive.calls); + } + if (o.stage_timing) strata::core::stage_timing_report(g.n_layers); + + const int64_t decoded = (int64_t) produced.size(); + std::printf("prompt :"); + for (int64_t t : o.tokens) std::printf(" %lld", (long long) t); + std::printf("\noutput :"); + for (int64_t t : produced) std::printf(" %lld", (long long) t); + std::printf("\n"); + const double decode_ms = decoded > 0 ? total_ms / (double) decoded : 0.0; + std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n", "decode", (long long) decoded, total_ms, + decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0); + if (n_prompt > 1) + std::printf("%-24s %lld tokens in %.1f ms -> %.2f tok/s (time to first token %.1f ms)\n", "prefill", + (long long) (n_prompt - 1), prefill_ms, + prefill_ms > 0 ? 1000.0 * (double) (n_prompt - 1) / prefill_ms : 0.0, ttft_ms); + if (!o.dump_mixed.empty()) { + std::vector mx((size_t) g.n_embd); + if (cudaMemcpy(mx.data(), ss.block.mixed, mx.size() * sizeof(float), cudaMemcpyDeviceToHost) != + cudaSuccess) { + std::fprintf(stderr, "strata generate: reading mixed back failed\n"); + return 1; + } + std::FILE* mf = std::fopen(o.dump_mixed.c_str(), "wb"); + if (mf == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_mixed.c_str()); + return 1; + } + std::fwrite(mx.data(), sizeof(float), mx.size(), mf); + std::fclose(mf); + double s2 = 0, mag = 0; + for (float v : mx) { s2 += (double) v * (double) v; mag += std::fabs((double) v); } + std::printf("%-24s %s (n_embd %lld, rms %.5g, mean|.| %.5g)\n", "mixed dumped", o.dump_mixed.c_str(), + (long long) g.n_embd, std::sqrt(s2 / (double) mx.size()), mag / (double) mx.size()); + } + + // ---- the residual, for bisecting the head against the layers (see `dump_residual`'s note) + if (!o.dump_residual.empty()) { + std::vector R((size_t) g.hc * g.n_embd); + if (cudaMemcpy(R.data(), ss.R, R.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) { + std::fprintf(stderr, "strata generate: reading R back failed\n"); + return 1; + } + std::FILE* rf = std::fopen(o.dump_residual.c_str(), "wb"); + if (rf == nullptr) { + std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_residual.c_str()); + return 1; + } + const int32_t hdr[2] = {(int32_t) g.hc, (int32_t) g.n_embd}; + std::fwrite(hdr, sizeof hdr, 1, rf); + std::fwrite(R.data(), sizeof(float), R.size(), rf); + std::fclose(rf); + double mag = 0, mx = 0; + int bad = 0; + for (float v : R) { + if (!std::isfinite(v)) ++bad; + else { mag += std::fabs((double) v); mx = std::max(mx, (double) std::fabs((double) v)); } + } + std::printf("%-24s %s (%d x %lld, nonfinite %d, mean|.| %.4g, max|.| %.4g)\n", "residual dumped", + o.dump_residual.c_str(), (int) g.hc, (long long) g.n_embd, bad, mag / (double) R.size(), mx); + } + + if (o.stats) { + std::printf("%-24s %.3f ms/token (WALL CLOCK: embed, layers, head, sample)\n", " per token", decode_ms); + // **THE PER-TOKEN HOST TERM, WHICH `--gpu-only-full` CANNOT SEE.** That measurement never enters the + // token loop, so it excludes all six of these. On the 78-token fixture + 200 generated tokens the six + // sum to ~9 ms of non-layer work against ~1.5 ms of actual head GPU work - 16% of the token, and it is + // not the pool. + if (phase_tokens > 0) { + const double pt = (double) phase_tokens; + std::printf("%-24s PLE %.3f embed %.3f LAYERS %.3f head %.3f readback %.3f sample %.3f " + "(sum %.3f of %.3f ms)\n", + " token host phases", ms_ple / pt, ms_embed / pt, ms_layers / pt, ms_head / pt, + ms_readback / pt, ms_sample / pt, + (ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample) / pt, decode_ms); + } + if (const std::string io = ple_table.io_report(); !io.empty()) std::printf(" %s\n", io.c_str()); + // **THE DENOMINATOR IS THE POSITIONS THE POOL ACTUALLY RAN ON, NOT THE DECODED TOKENS (A6).** + // `drive_pool` is called once per layer per position and PREFILL runs the loop too, so accumulating + // `cpu_ms` over prefill and then dividing by `decoded` inflates this figure. `drive.calls / n_layers` + // is the number of positions - the same correction the ring counters below already received, which is + // why they print "of 192" rather than "240 of 192". + const double pool_positions = g.n_layers > 0 ? (double) drive.calls / (double) g.n_layers : 0.0; + std::printf("%-24s %.3f ms/token over %lld layers (%.0f positions, %lld dispatches)\n", + " the CPU expert pool", pool_positions > 0.0 ? drive.cpu_ms / pool_positions : 0.0, + (long long) g.n_layers, pool_positions, (long long) drive.calls); + // **AND WHERE INSIDE `run()` IT WENT.** Three phases per layer and they were one number, which cannot + // tell a pool that is slow at the WORK from one that is slow at the SYNCHRONISATION - opposite fixes. + // Wait-for-park is expected to be ~0 (the workers re-parked at the end of the previous layer); the + // question is whether the time is in the drain or in the re-park barrier. + if (pool_positions > 0.0) { + double wp = 0, dr = 0, rp = 0; + pool.phase_ms(wp, dr, rp); + const double per = pool_positions; + std::printf("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n", + " pool phases", wp / per, dr / per, rp / per); + } + std::printf("%-24s %lld blobs read\n", " expert blobs", (long long) srcp->reads()); + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + std::printf(" CUDA%d experts %lld routed entries computed\n", + r + 1, (long long) remote_experts[(size_t) r].computed()); + // ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus + // question, no k-fold - these are the ids the router actually produced on this run. Reported as + // hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused` + // so a full cache is visible rather than silently capping the rate. + if (o.expert_cache > 0) { + const int64_t look = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; + const int64_t hl = drive.d.hit_ready + drive.d.hit_late; + std::printf("%-24s %lld of %lld layers the hit work was DONE when the pool returned\n", + " R4 overlap", (long long) drive.d.hit_ready, (long long) hl); + std::printf("%-24s %lld of %lld = %.4f (%lld admitted, %lld refused, cache %.4f%% full)\n", + " R4 expert-cache hits", (long long) drive.d.cache_hits, (long long) look, + look > 0 ? (double) drive.d.cache_hits / (double) look : 0.0, + (long long) drive.d.cache_admitted, (long long) drive.d.cache_refused, + 100.0 * (double) (drive.d.cache_admitted + drive.d.cache_hits > 0 + ? (double) xcache.resident() / (double) xcache.slots() + : 0.0)); + } + if (tgraph.captured && tgraph.calls > 0) { + const double per = (double) tgraph.calls; + std::printf("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n", + " token graph", tgraph.ms_wait / per, tgraph.ms_pool / per, (long long) tgraph.flushes, + (long long) tgraph.calls); + } + if (gr.captured && gr.calls_total > 0) { + // The counters are CUMULATIVE over every `session_loop` call, and PREFILL runs the loop too - so + // the denominator is the number of positions, not the number of generated tokens. Dividing by + // `n_layers * decoded` printed "240 of 192", which is a reporting bug that looks like a ring + // firing more often than it should. + const int64_t positions = gr.calls_total; + std::printf("%-24s %lld of %lld over %lld positions\n", " rings seen MID-GRAPH", + (long long) gr.rings_mid_graph, (long long) (g.n_layers * positions), + (long long) positions); + std::printf("%-24s %.3f ms of a %.3f ms layer\n", " ring latency", + gr.ms_to_ring / (double) (g.n_layers * positions), decode_ms / (double) g.n_layers); + // **THE ROUND TRIP, SPLIT AT THE RING.** `ring latency` is the first half and stops when the ring + // is seen; this is the second half - the driver calls after it, during which the GPU is IDLE + // because `post[l]` has not been launched yet. `--no-pool` is the arm that isolates it: 38.73 + // ms/token against a 26.32 ms pure-GPU floor is 12.4 ms of round trip with no expert work at all. + // + // Same denominator as the pool line above (the positions the loop actually ran on), so the two can + // be added without one of them being inflated by prefill. + const double perlap = (double) (g.n_layers * positions); + std::printf("%-24s %.3f ms/token over %.0f positions (%.3f ms/layer, after the ring)\n", + " host after ring", pool_positions > 0.0 ? gr.ms_host / pool_positions : 0.0, + pool_positions, gr.ms_host / perlap); + } + } + + if (dump != nullptr) std::printf("%-24s %s\n", "logits dumped", o.dump_logits.c_str()); + + strata::core::session_graphs_free(gr); + strata::core::doorbell_free(db); + cudaFree(d_next); + cudaFree(d_logits); + cudaFree(d_emb); + cudaFree(d_parts); + cudaFree(sbuf); + cudaFree(arena); + return 0; +} diff --git a/engine/strata/src/spec/controller.cpp b/engine/strata/src/spec/controller.cpp new file mode 100644 index 00000000..be312701 --- /dev/null +++ b/engine/strata/src/spec/controller.cpp @@ -0,0 +1,73 @@ +// src/spec/controller.cpp - see include/strata/spec/controller.hpp. +#include "strata/spec/controller.hpp" + +#include + +namespace strata::spec { + +double CostModel::step_ms(int k, bool mtp) const { + const int n = std::clamp(k + 1, 1, K_MAX + 1); + const double dense = dense_ms * dense_ratio[n - 1]; + // CPU misses: distinct experts grow as U(n); each extra token routed to a missed expert adds a fraction of a + // read. Tokens per distinct expert = n / U(n)-ratio (U measured in units of one token's 10 experts). + const double u = distinct_ratio[n - 1]; + const double uses_per_expert = (double) n / u; + const double cpu = (1.0 - hit_rate) * cpu_all_miss_ms * u * (1.0 + extra_use_cost * (uses_per_expert - 1.0)); + const double draft = k * (mtp ? mtp_draft_ms : lookup_draft_ms); + return dense + cpu + sync_ms + draft; +} + +Controller::Controller(CostModel cost, double min_gain, double ema) : cost_(cost), min_gain_(min_gain), ema_(ema) { + // Priors: MTP per-position acceptance from flyweight's measurement on this model (0.86 per draft); lookup by + // match length from the offline replay (2026-09-23-suffix-lookup). Both are then learned per session. + mtp_p_.fill(0.86); + lookup_q_ = {0.35, 0.6, 0.8, 0.92}; +} + +double Controller::expected(const double* p, int k, bool same) { + double e = 1.0, run = 1.0; // the verify pass always commits one token + for (int i = 0; i < k; ++i) { + run *= same ? p[0] : p[i]; + e += run; + } + return e; +} + +Choice Controller::choose(int lookup_available, int lookup_match, bool mtp_ready) const { + Choice best; + best.tokens_per_ms = 1.0 / cost_.step_ms(0, false); + const double baseline = best.tokens_per_ms; + auto consider = [&](Source s, int k, double e) { + const double rate = e / cost_.step_ms(k, s == Source::Mtp); + if (rate > best.tokens_per_ms) best = Choice{s, k, e, rate}; + }; + const int lk = std::min(lookup_available, K_MAX); + const double q = lookup_q_[bucket(lookup_match)]; + for (int k = 1; k <= lk; ++k) consider(Source::Lookup, k, expected(&q, k, true)); + if (mtp_ready) + for (int k = 1; k <= K_MAX; ++k) consider(Source::Mtp, k, expected(mtp_p_.data(), k, false)); + if (best.source != Source::None && best.tokens_per_ms < baseline * (1.0 + min_gain_)) { + Choice none; + none.tokens_per_ms = baseline; + return none; + } + return best; +} + +void Controller::observe(const Choice& c, int accepted, int lookup_match) { + if (c.source == Source::None || c.k <= 0) return; + accepted = std::clamp(accepted, 0, c.k); + // Positions 0..accepted-1 were accepted given their prefix; position `accepted` (if drafted) was rejected. + const int seen = std::min(c.k, accepted + 1); + for (int i = 0; i < seen; ++i) { + const double hit = i < accepted ? 1.0 : 0.0; + if (c.source == Source::Mtp) mtp_p_[i] += ema_ * (hit - mtp_p_[i]); + else lookup_q_[bucket(lookup_match)] += ema_ * (hit - lookup_q_[bucket(lookup_match)]); + } + // Everything drafted was accepted: the positions beyond the window were never tested, so without this they + // keep their prior forever and the window can never grow. Pull them toward the deepest observed rate. + if (c.source == Source::Mtp && accepted == c.k && c.k < K_MAX) + for (int i = c.k; i < K_MAX; ++i) mtp_p_[i] += ema_ * (mtp_p_[c.k - 1] - mtp_p_[i]); +} + +} // namespace strata::spec diff --git a/engine/strata/src/spec/controller_test.cpp b/engine/strata/src/spec/controller_test.cpp new file mode 100644 index 00000000..ee056ab5 --- /dev/null +++ b/engine/strata/src/spec/controller_test.cpp @@ -0,0 +1,74 @@ +// src/spec/controller_test.cpp - plan v0.3 P6: the speculation controller's decisions (no model, no GPU). +#include "strata/spec/controller.hpp" + +#include + +using namespace strata::spec; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_fail; } +} +const char* name(Source s) { return s == Source::Mtp ? "mtp" : s == Source::Lookup ? "lookup" : "none"; } +} // namespace + +int main() { + { // priors (MTP 0.86 per draft): MTP with a short-to-medium window beats plain decoding + Controller c; + const Choice ch = c.choose(0, 0, true); + check(ch.source == Source::Mtp && ch.k >= 2 && ch.k <= 5, "MTP chosen with k in 2..5 at the prior"); + std::printf("prior: %s k=%d expected %.2f tokens, %.1f tok/s (plain %.1f)\n", name(ch.source), ch.k, + ch.expected_tokens, 1000 * ch.tokens_per_ms, 1000.0 / c.cost().step_ms(0, false)); + } + { // a drafter that keeps missing its first token is switched off + Controller c; + Choice ch = c.choose(0, 0, true); + for (int i = 0; i < 400; ++i) { c.observe(ch, 0, 0); ch = c.choose(0, 0, true); if (ch.source == Source::None) break; } + check(ch.source == Source::None, "persistent rejection turns speculation off"); + std::printf("after rejections: %s, p0 %.2f\n", name(ch.source), c.mtp_accept(0)); + } + { // a long lookup match beats MTP; how LONG a window pays depends on what a wide verify costs + Controller c; + const Choice ch = c.choose(8, 20, true); + check(ch.source == Source::Lookup, "long lookup match preferred over MTP"); + std::printf("long lookup match, measured costs: %s k=%d expected %.2f, %.1f tok/s\n", name(ch.source), ch.k, + ch.expected_tokens, 1000 * ch.tokens_per_ms); + CostModel cheap; // a verify pass whose cost barely grows with width + cheap.dense_ratio = {1.0, 1.02, 1.04, 1.06, 1.08, 1.1, 1.12, 1.14, 1.16}; + cheap.hit_rate = 0.95; + Controller c2(cheap); + const Choice ch2 = c2.choose(8, 20, true); + check(ch2.source == Source::Lookup && ch2.k == 8, "cheap wide verify takes the whole lookup window"); + std::printf("long lookup match, cheap wide verify: %s k=%d expected %.2f, %.1f tok/s\n", name(ch2.source), + ch2.k, ch2.expected_tokens, 1000 * ch2.tokens_per_ms); + } + { // a bare trigram match, no MTP: not worth a verify window + Controller c; + const Choice ch = c.choose(8, 3, false); + check(ch.source == Source::None, "short lookup match alone is not used"); + } + { // perfect acceptance is learned and widens the window + Controller c; + Choice ch = c.choose(0, 0, true); + const int k0 = ch.k; + for (int i = 0; i < 400; ++i) { c.observe(ch, ch.k, 0); ch = c.choose(0, 0, true); } + check(ch.k > k0 && c.mtp_accept(0) > 0.99, "full acceptance learned and the window widens"); + std::printf("after full acceptance: %s k=%d (was %d), p0 %.3f\n", name(ch.source), ch.k, k0, c.mtp_accept(0)); + } + std::printf("\nMTP acceptance -> choice (default cost model):\n"); + for (double p : {0.5, 0.6, 0.7, 0.8, 0.86, 0.9, 0.95}) { + Controller c; + Choice ch = c.choose(0, 0, true); + for (int i = 0; i < 2000; ++i) { // feed a stream with iid acceptance p per position + int acc = 0; + unsigned r = 2654435761u * (unsigned) (i + 1); + while (acc < ch.k && ((r = r * 1103515245u + 12345u) >> 8) % 1000 < p * 1000) ++acc; + c.observe(ch, acc, 0); + ch = c.choose(0, 0, true); + } + std::printf(" p=%.2f: %s k=%d, %.1f tok/s\n", p, name(ch.source), ch.k, 1000 * ch.tokens_per_ms); + } + std::printf("controller tests: %s\n", g_fail ? "FAILED" : "OK"); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/spec/draft_policy.cpp b/engine/strata/src/spec/draft_policy.cpp new file mode 100644 index 00000000..1ac77198 --- /dev/null +++ b/engine/strata/src/spec/draft_policy.cpp @@ -0,0 +1,101 @@ +// src/spec/draft_policy.cpp - see include/strata/spec/draft_policy.hpp. +#include "strata/spec/draft_policy.hpp" + +#include + +namespace strata::spec { +namespace { + +// The shape of a round's cost by window size, relative to one token, used only for sizes not measured yet (the +// measured round times replace it). Between the RTX 5070's measured curves: +10 ms per token with every missed expert +// on the CPU (bench/results/2026-09-27-spec/window-cost), flatter with the default CPU/DMA split. +constexpr double kShape[DraftPolicy::kMaxT + 1] = {0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6}; +constexpr double kCostAlpha = 0.1; // EMA weight of a new round time +constexpr double kTokAlpha = 0.05; // EMA weight of a new MTP window outcome +constexpr double kDecay = 0.97; // lookup counts: older windows fade +// Before a bucket has data: the longer the match, the likelier its continuation (llama.cpp's lookup decoding gates +// on the same thing); worth 4 observations, so a few real windows override it +constexpr double kPriorQ[DraftPolicy::kBuckets] = {0.75, 0.88, 0.93, 0.96}; +constexpr double kPriorN = 4.0; +constexpr int kProbes = 3; // a lookup window size is tried this often before its guessed cost can veto it + +} // namespace + +DraftPolicy::DraftPolicy(int max_t, double margin) + : max_t_(std::clamp(max_t, 1, kMaxT)), margin_(margin) {} + +int DraftPolicy::bucket(int match) { + return match < 6 ? 0 : match < 12 ? 1 : match < 24 ? 2 : 3; +} + +double DraftPolicy::lookup_rate(int match) const { + const int b = bucket(match); + return (ok_[b] + kPriorN * kPriorQ[b]) / (ok_[b] + bad_[b] + kPriorN); +} + +double DraftPolicy::cost_ms(int t) const { + t = std::clamp(t, 1, kMaxT); + if (cost_n_[t] > 0) return cost_[t]; + // scale from the measured sizes, weighting each by how often it was seen + double num = 0.0, den = 0.0; + for (int u = 1; u <= kMaxT; ++u) + if (cost_n_[u] > 0) { + const double w = std::min(cost_n_[u], 20.0); + num += w * cost_[u] * kShape[t] / kShape[u]; + den += w; + } + return den > 0 ? num / den : kShape[t]; +} + +double DraftPolicy::mtp_tokens(int t) const { + if (mtp_n_[t] > 0) return mtp_tok_[t]; + return 1.0 + 0.7 * (t - 1); // before any MTP window of this size: a typical acceptance +} + +DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const { + Pick p; + p.t = std::clamp(t_mtp, 1, max_t_); + if (lookup_k <= 0) return p; + const double base = mtp_tokens(p.t) / cost_ms(p.t); + const double q = lookup_rate(match); + double e = 1.0, qi = 1.0, best = 0.0; + int best_t = 0; + for (int k = 1; k <= std::min(lookup_k, max_t_ - 1); ++k) { + qi *= q; + e += qi; + const double r = e / cost_ms(k + 1); + if (r > best) { best = r; best_t = k + 1; } + } + if (best_t > 0 && best > base * (1.0 + margin_)) { + p.lookup = true; + p.t = best_t; + return p; + } + // a guessed cost can keep the policy from ever measuring a size: the first few times a confident lookup would + // need a size not measured yet, it is tried (verification keeps the output; only the one round's speed is at stake) + const int t_full = std::min(lookup_k, max_t_ - 1) + 1; + if (t_full > p.t && cost_n_[t_full] < kProbes && q >= 0.85) { + p.lookup = true; + p.t = t_full; + } + return p; +} + +void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) { + t = std::clamp(t, 1, kMaxT); + if (round_ms > 0) { + cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms; + cost_n_[t] += 1.0; + } + if (lookup) { + const int b = bucket(match); + ok_[b] = kDecay * ok_[b] + accepted; + bad_[b] = kDecay * bad_[b] + (accepted < t - 1 ? 1.0 : 0.0); + } else { + const double got = accepted + 1.0; + mtp_tok_[t] = mtp_n_[t] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t] + kTokAlpha * got : got; + mtp_n_[t] += 1.0; + } +} + +} // namespace strata::spec diff --git a/engine/strata/src/spec/draft_policy_test.cpp b/engine/strata/src/spec/draft_policy_test.cpp new file mode 100644 index 00000000..e04b3de8 --- /dev/null +++ b/engine/strata/src/spec/draft_policy_test.cpp @@ -0,0 +1,63 @@ +// src/spec/draft_policy_test.cpp - DraftPolicy: when does a lookup window beat the MTP's? +// +// Simulated rounds with the costs measured on the RTX 5070 (window-cost: ~10 ms more per token) check that +// 1. with no lookup proposal the MTP window is kept; +// 2. lookup drafts that are mostly rejected stop being taken (their bucket's rate falls); +// 3. lookup drafts that are always accepted are taken, and the window grows with them; +// 4. match-length buckets learn separately (short matches failing does not stop long ones); +// 5. the policy never proposes a window beyond its cap. +#include "strata/spec/draft_policy.hpp" + +#include + +using strata::spec::DraftPolicy; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} +double cost(int t) { return 19.0 + 10.5 * (t - 1); } // ms per round, measured shape +} // namespace + +int main() { + std::printf("draft_policy_test\n"); + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); // MTP windows of 4: 3 tokens each + const DraftPolicy::Pick k = p.choose(4, 0, 0); + check(!k.lookup && k.t == 4, "no proposal: the MTP window"); + } + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 2, 0, cost(4)); + for (int t = 2; t <= 6; ++t) p.observe(false, t, 0, 0, cost(t)); + for (int i = 0; i < 40; ++i) p.observe(true, 6, 0, 4, cost(6)); // short matches, all rejected + check(p.lookup_rate(4) < 0.15, "rejected short-match drafts: their rate falls below 0.15"); + check(!p.choose(4, 5, 4).lookup, "rejected short-match drafts: no longer taken"); + for (int i = 0; i < 40; ++i) p.observe(true, 6, 5, 30, cost(6)); // long matches, all accepted + check(p.lookup_rate(30) > 0.9, "accepted long-match drafts: their rate rises above 0.9"); + const DraftPolicy::Pick k = p.choose(4, 5, 30); + check(k.lookup && k.t == 6, "accepted long matches: the full lookup window is taken"); + check(!p.choose(4, 5, 4).lookup, "buckets are separate: short matches still not taken"); + check(p.choose(4, 20, 30).t <= 6, "never beyond the window cap"); + } + { + DraftPolicy p(8); + for (int i = 0; i < 50; ++i) p.observe(false, 3, 2, 0, cost(3)); // a very good MTP: 3 of 3 tokens + for (int t = 2; t <= 8; ++t) p.observe(false, t, t - 1, 0, cost(t)); + for (int i = 0; i < 40; ++i) p.observe(true, 4, 2, 8, cost(4)); // lookup at q ~ 0.67 + check(!p.choose(3, 7, 8).lookup, "a mediocre lookup does not replace a strong MTP window"); + } + { + DraftPolicy p(6); + for (int i = 0; i < 50; ++i) p.observe(false, 4, 3, 0, cost(4)); // a near-perfect MTP, only size 4 seen + const DraftPolicy::Pick k = p.choose(4, 5, 40); + check(k.lookup && k.t == 6, "an unmeasured size is probed for a confident lookup"); + for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive + check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides"); + } + std::printf(g_fail ? "FAIL\n" : "PASS\n"); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/src/spec/suffix_drafter.cpp b/engine/strata/src/spec/suffix_drafter.cpp new file mode 100644 index 00000000..6f04f76d --- /dev/null +++ b/engine/strata/src/spec/suffix_drafter.cpp @@ -0,0 +1,88 @@ +// src/spec/suffix_drafter.cpp - see include/strata/spec/suffix_drafter.hpp. +#include "strata/spec/suffix_drafter.hpp" + +#include + +namespace strata::spec { + +namespace { +uint64_t mix(uint64_t x) { + x ^= x >> 33; + x *= 0xff51afd7ed558ccdull; + x ^= x >> 33; + x *= 0xc4ceb9fe1a85ec53ull; + return x ^ (x >> 33); +} +} // namespace + +SuffixDrafter::SuffixDrafter(int min_match, int max_match, size_t capacity_tokens) + : min_match_(std::max(3, min_match)), max_match_(std::max(min_match, max_match)) { + size_t cap = 1; + while (cap < capacity_tokens * 2) cap <<= 1; // load factor <= 0.5 at the nominal capacity + table_.assign(cap, Slot{}); + mask_ = cap - 1; + hist_.reserve(capacity_tokens); +} + +void SuffixDrafter::reset() { + hist_.clear(); + std::fill(table_.begin(), table_.end(), Slot{}); + last_match_ = 0; +} + +uint64_t SuffixDrafter::key_at(size_t end) const { + const uint64_t a = (uint32_t) hist_[end - 2], b = (uint32_t) hist_[end - 1], c = (uint32_t) hist_[end]; + return mix(a * 0x9E3779B97F4A7C15ull ^ mix(b + 0x632BE59BD9B4E019ull) ^ (c << 1)) | 1ull; // never 0 +} + +SuffixDrafter::Slot* SuffixDrafter::find_slot(uint64_t key, bool insert) { + for (size_t i = key & mask_, probes = 0; probes <= mask_; i = (i + 1) & mask_, ++probes) { + Slot& s = table_[i]; + if (s.key == key) return &s; + if (s.key == 0) { + if (!insert) return nullptr; + s.key = key; + return &s; + } + } + return nullptr; // table full: the history outgrew its capacity +} + +void SuffixDrafter::append(const int32_t* tokens, size_t n) { + for (size_t i = 0; i < n; ++i) { + hist_.push_back(tokens[i]); + const size_t end = hist_.size() - 1; + if (end < 2) continue; + Slot* s = find_slot(key_at(end), true); + if (s == nullptr) continue; + for (int w = WAYS - 1; w > 0; --w) s->pos[w] = s->pos[w - 1]; + s->pos[0] = (uint32_t) end; + if (s->n < WAYS) ++s->n; + } +} + +int SuffixDrafter::propose(int max_k, int32_t* out) { + last_match_ = 0; + const size_t n = hist_.size(); + if (n < 4 || max_k <= 0) return 0; + const size_t cur = n - 1; + const Slot* s = find_slot(key_at(cur), false); + if (s == nullptr) return 0; + size_t best_end = 0; + int best_len = 0; + for (int w = 0; w < s->n; ++w) { + const size_t p = s->pos[w]; + if (p >= cur) continue; // the current suffix itself + int len = 0; + while (len < max_match_ && len <= (int) p && hist_[p - len] == hist_[cur - len]) ++len; + if (len > best_len) { best_len = len; best_end = p; } // most recent first, so ties keep the newer + } + if (best_len < min_match_) return 0; + last_match_ = best_len; + int k = 0; + // The continuation may run into the current suffix (periodic text); reading history up to `cur` is valid. + for (size_t q = best_end + 1; q <= cur && k < max_k; ++q) out[k++] = hist_[q]; + return k; +} + +} // namespace strata::spec diff --git a/engine/strata/src/spec/suffix_drafter_test.cpp b/engine/strata/src/spec/suffix_drafter_test.cpp new file mode 100644 index 00000000..9fa8611e --- /dev/null +++ b/engine/strata/src/spec/suffix_drafter_test.cpp @@ -0,0 +1,141 @@ +// src/spec/suffix_drafter_test.cpp - plan v0.3 P6: suffix-lookup drafter tests and an offline simulation. +// +// suffix_drafter_test unit tests +// suffix_drafter_test --simulate [--k K] FILE.ids ... +// +// The simulation replays text as if a model had produced it: each step drafts up to K tokens, accepts the +// prefix that matches the true next tokens, and commits that prefix plus one model token (the verify pass's +// bonus). tokens/step is the lookup drafter's ceiling speedup on that text when a K+1-token verify costs the same +// as a 1-token step. Two regimes per file: +// continue history = first half of the prompt; generate its second half (natural continuation) +// copy history = the whole prompt; generate its middle third again (output quoting input: edits) +// No model runs; this measures the drafter on text, not on the model's own outputs. +#include "strata/spec/suffix_drafter.hpp" + +#include +#include +#include +#include +#include +#include +#include + +using strata::spec::SuffixDrafter; + +namespace { +int g_fail = 0; +void check(bool ok, const char* what) { + if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_fail; } +} + +std::vector read_ids(const char* path) { + std::ifstream f(path); + std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + for (char& c : text) if (c == ',') c = ' '; + std::istringstream in(text); + std::vector ids; + for (int32_t v; in >> v;) ids.push_back(v); + return ids; +} + +struct Sim { long steps = 0, tokens = 0, proposals = 0, accepted = 0; }; + +Sim simulate(const std::vector& history, const std::vector& target, int K) { + SuffixDrafter d(3, 32, history.size() + target.size() + 16); + d.append(history.data(), history.size()); + Sim s; + std::vector draft(K); + size_t i = 0; + while (i < target.size()) { + const int n = d.propose(K, draft.data()); + int a = 0; + while (a < n && i + a < target.size() && draft[a] == target[i + a]) ++a; + if (n > 0) { ++s.proposals; s.accepted += a; } + const size_t commit = std::min(target.size() - i, (size_t) a + 1); + d.append(&target[i], commit); + i += commit; + s.tokens += (long) commit; + ++s.steps; + } + return s; +} + +void unit_tests() { + { // a repeated passage is proposed verbatim + SuffixDrafter d; + const std::vector doc = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; + d.append(doc.data(), doc.size()); + const int32_t again[] = {10, 11, 12}; + d.append(again, 3); + int32_t out[8]; + const int n = d.propose(5, out); + check(n == 5 && out[0] == 13 && out[4] == 17, "repeat proposes the continuation"); + check(d.last_match() == 3, "match length is the shared suffix"); + } + { // no earlier occurrence: nothing proposed + SuffixDrafter d; + const std::vector doc = {1, 2, 3, 4, 5, 6, 7}; + d.append(doc.data(), doc.size()); + int32_t out[4]; + check(d.propose(4, out) == 0, "no match proposes nothing"); + } + { // two occurrences of the trigram: the longer match wins even though it is older + SuffixDrafter d; + const std::vector doc = {7, 8, 1, 2, 3, 100, 101, 9, 1, 2, 3, 200, 201, 50, 7, 8, 1, 2, 3}; + d.append(doc.data(), doc.size()); + int32_t out[2]; + const int n = d.propose(2, out); + check(n == 2 && out[0] == 100 && out[1] == 101, "longest match preferred over most recent"); + check(d.last_match() == 5, "longest match length 5"); + } + { // a match shorter than min_match is ignored (only a bigram in common) + SuffixDrafter d(4); + const std::vector doc = {1, 2, 3, 9, 5, 2, 3}; + d.append(doc.data(), doc.size()); + int32_t out[2]; + check(d.propose(2, out) == 0, "min_match respected"); + } + { // periodic text: the continuation may run into the current suffix + SuffixDrafter d; + const std::vector doc = {1, 2, 3, 1, 2, 3, 1, 2, 3}; + d.append(doc.data(), doc.size()); + int32_t out[6]; + const int n = d.propose(6, out); + check(n >= 3 && out[0] == 1 && out[1] == 2 && out[2] == 3, "periodic continuation"); + } + { // bounded memory: appending beyond the nominal capacity does not crash and still works + SuffixDrafter d(3, 32, 1024); + std::vector doc; + for (int i = 0; i < 5000; ++i) doc.push_back(i % 997); + d.append(doc.data(), doc.size()); + int32_t out[4]; + check(d.propose(4, out) > 0, "propose after overflow of nominal capacity"); + } + std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK"); +} +} // namespace + +int main(int argc, char** argv) { + if (argc > 1 && std::strcmp(argv[1], "--simulate") == 0) { + int K = 8, first = 2; + if (argc > 3 && std::strcmp(argv[2], "--k") == 0) { K = std::atoi(argv[3]); first = 4; } + std::printf("%-28s %8s | %-44s | %-44s\n", "prompt", "tokens", "continue: tok/step proposals acc/proposal", + "copy: tok/step proposals acc/proposal"); + for (int f = first; f < argc; ++f) { + const std::vector ids = read_ids(argv[f]); + if (ids.size() < 64) continue; + const size_t half = ids.size() / 2; + const Sim c = simulate({ids.begin(), ids.begin() + half}, {ids.begin() + half, ids.end()}, K); + const size_t a = ids.size() / 3, b = 2 * ids.size() / 3; + const Sim p = simulate(ids, {ids.begin() + a, ids.begin() + b}, K); + const char* name = std::strrchr(argv[f], '/') ? std::strrchr(argv[f], '/') + 1 : argv[f]; + std::printf("%-28s %8zu | %8.2f %10.1f%% %10.2f | %8.2f %10.1f%% %10.2f\n", name, ids.size(), + (double) c.tokens / c.steps, 100.0 * c.proposals / c.steps, + c.proposals ? (double) c.accepted / c.proposals : 0.0, (double) p.tokens / p.steps, + 100.0 * p.proposals / p.steps, p.proposals ? (double) p.accepted / p.proposals : 0.0); + } + return 0; + } + unit_tests(); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/tests/core/expert_cache_per_layer_test.cpp b/engine/strata/tests/core/expert_cache_per_layer_test.cpp new file mode 100644 index 00000000..26bfdd4d --- /dev/null +++ b/engine/strata/tests/core/expert_cache_per_layer_test.cpp @@ -0,0 +1,44 @@ +// #369: per-layer admission on a sized cache (open_sized, every native pack) - each layer admits into its own slot +// range, as on the uniform cache, so no two layers write the same slot. Needs a CUDA device (exits 77 without one). +#include "strata/core/expert_cache.hpp" + +#include + +#include +#include +#include + +int main() { + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { + std::puts("no CUDA device: skipped"); + return 77; + } + std::string err; + for (int sized = 0; sized < 2; ++sized) { + strata::core::ExpertCache cache; + const bool ok = sized ? cache.open_sized(std::vector(6, 1024), 3, 4, err) + : cache.open(6, 3, 4, 1024, err); + if (!ok) { + std::fprintf(stderr, "open: %s\n", err.c_str()); + return 1; + } + cache.set_per_layer_admission(true); + for (int64_t layer = 0; layer < 3; ++layer) { + int64_t lo = 0, hi = 0; + cache.layer_slot_range(layer, lo, hi); + for (int64_t e = 0; e < 3; ++e) { + const int32_t slot = cache.admit(layer, e); + const bool want_room = lo + e < hi; + if (want_room ? slot != (int32_t) (lo + e) : slot != strata::core::kNotResident) { + std::fprintf(stderr, "%s cache: layer %lld expert %lld got slot %d (range %lld..%lld)\n", + sized ? "sized" : "uniform", (long long) layer, (long long) e, slot, (long long) lo, + (long long) hi - 1); + return 1; + } + } + } + } + std::puts("expert cache per-layer admission: uniform and sized caches passed"); + return 0; +} diff --git a/engine/strata/tests/core/expert_layout_test.cpp b/engine/strata/tests/core/expert_layout_test.cpp new file mode 100644 index 00000000..35d1accf --- /dev/null +++ b/engine/strata/tests/core/expert_layout_test.cpp @@ -0,0 +1,355 @@ +// tests/core/expert_layout_test.cpp - native_experts.txt (v2/v3/v4) and the expert arena filled from GGUF shards, +// without a model or a GPU. +// +// 1. Copies of the real packs' native_experts.txt (tests/data/native_experts: Q2_0, IQ2_XS, IQ3_XXS, IQ3_S, +// Coder IQ1_M, Swift IQ2_XS; v2 and v3 headers) parse to the layout the pre-v4 reader produced: the test +// parses each line again with that reader's rules (one shard name for all three roles) and compares every +// field, and the totals with the header's. +// 2. The v4 shard column `gate,up,down` (an empty field = the --native shard); v5, four names, two names and a +// trailing column are refused. +// 3. check_experts_gguf + load_experts_gguf on a synthetic arena at the real dimensions 2560/640 with Unsloth's +// format pairs (Q4_K/Q5_1, Q5_K/Q8_0): layer 1's gate/up in another file than its down. Every byte of the +// arena is compared with the source tensors. Then the refusals: an offset that is not the tensor's, a +// truncated file, a role named in the wrong file, a type or a shape the pack does not say, a missing file. +#include "gguf_fixture.hpp" + +#include "strata/core/expert_source.hpp" +#include "strata/core/pinned.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/native_expert.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using strata::kernels::cpu::ExpertLayout; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-expert-layout-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +void write_text(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary) << s; } + +bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, std::string& err) { + err.clear(); + return strata::kernels::cpu::expert_layout_load(dir.string(), n_layers, n_expert, err); +} + +// ---- 1. the real packs' files +void real_packs(const fs::path& data) { + for (const char* pack : {"q2_0", "iq2_xs", "iq3_xxs", "iq3_s", "coder-iq1_m", "swift-iq2_xs"}) { + TempDir d; + fs::copy_file(data / (std::string(pack) + ".txt"), d.path / "native_experts.txt"); + std::string err; + const bool ok = load(d.path, 48, 512, err); + check(ok, std::string(pack) + ": loads" + (ok ? "" : ": " + err)); + if (!ok) continue; + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + // the pre-v4 reader's rules, applied to the same text + std::ifstream in(d.path / "native_experts.txt"); + std::string line; + long long hdr_n = -1, hdr_total = -1; + bool same = L.native && L.n_layers == 48 && L.gguf_off.size() == 3 * 48; + uint64_t max_blob = 0; + while (std::getline(in, line)) { + if (line.empty()) continue; + if (line[0] == '#') { + if (line.find("(n_expert ") == std::string::npos) continue; + std::istringstream h(line.substr(line.find("(n_expert ") + 10)); + char comma = 0; + std::string word; + h >> hdr_n >> comma >> word >> hdr_total; // "(n_expert N, total T; ..." + continue; + } + std::istringstream ss(line); + long long l = 0, gt = 0, dt = 0; + unsigned long long off = 0, blob = 0, o[3] = {0, 0, 0}; + std::string file; + ss >> l >> gt >> dt >> off >> blob >> o[0] >> o[1] >> o[2]; + ss >> file; + same = same && L.fmt[(size_t) l].gu_type == gt && L.fmt[(size_t) l].d_type == dt && + L.offset[(size_t) l] == off && L.bytes[(size_t) l] == blob; + for (int r = 0; r < 3; ++r) { + same = same && L.gguf_off[(size_t) (3 * l + r)] == o[r]; + const std::string got = L.gguf_file.empty() ? std::string() : L.gguf_file[(size_t) (3 * l + r)]; + same = same && got == file; + } + if (blob > max_blob) max_blob = blob; + } + same = same && L.n_expert == hdr_n && (long long) L.total == hdr_total && L.max_blob == max_blob; + check(same, std::string(pack) + ": every field as the pre-v4 reader, totals as the header (v" + + std::to_string(L.version) + ", n_expert " + std::to_string(L.n_expert) + ")"); + } +} + +// ---- 2. the v4 column and the refusals +std::string manifest(int version, const std::string& col1, int64_t blob, int n_expert = 2) { + std::string s = "# strata native experts v" + std::to_string(version) + + ": layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] " + "(n_expert " + std::to_string(n_expert) + ", total " + std::to_string(2 * blob * n_expert) + ")\n"; + s += "0 12 7 0 " + std::to_string(blob) + " 100 200 300\n"; + s += "1 12 7 " + std::to_string(blob * n_expert) + " " + std::to_string(blob) + " 400 500 600" + + (col1.empty() ? "" : " " + col1) + "\n"; + return s; +} + +void columns() { + strata::kernels::cpu::NativeFmt f; + std::string err; + if (!strata::kernels::cpu::native_fmt(12, 7, 2560, 640, f, err)) { + check(false, "Q4_K/Q5_1 native format: " + err); + return; + } + const int64_t blob = (int64_t) f.bytes; + TempDir d; + write_text(d.path / "native_experts.txt", manifest(4, "B.gguf,B.gguf,", blob)); + bool ok = load(d.path, 2, 512, err); + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + check(ok && L.version == 4 && L.gguf_file.size() == 6 && L.gguf_file[0].empty() && L.gguf_file[2].empty() && + L.gguf_file[3] == "B.gguf" && L.gguf_file[4] == "B.gguf" && L.gguf_file[5].empty() && + L.gguf_off[5] == 600, + "v4: `B.gguf,B.gguf,` = gate and up in B.gguf, down in the --native shard" + (ok ? "" : ": " + err)); + write_text(d.path / "native_experts.txt", manifest(3, "A.gguf", blob)); + ok = load(d.path, 2, 512, err); + check(ok && L.gguf_file[3] == "A.gguf" && L.gguf_file[4] == "A.gguf" && L.gguf_file[5] == "A.gguf", + "v3: one name covers the three roles"); + write_text(d.path / "native_experts.txt", manifest(5, "", blob)); + ok = load(d.path, 2, 512, err); + check(!ok && err.find("v5") != std::string::npos, "v5 is refused (\"" + err.substr(0, 40) + "...\")"); + write_text(d.path / "native_experts.txt", manifest(4, "a,b,c,d", blob)); + check(!load(d.path, 2, 512, err) && err.find("gate,up,down") != std::string::npos, "four names are refused"); + write_text(d.path / "native_experts.txt", manifest(4, "a,b", blob)); + check(!load(d.path, 2, 512, err), "two names are refused"); + write_text(d.path / "native_experts.txt", manifest(4, "a extra", blob)); + check(!load(d.path, 2, 512, err), "a column after the shard column is refused"); +} + +// ---- 3. the arena from synthetic shards +void arena() { + using fixture::Tensor; + constexpr int64_t H = 2560, FF = 640, NE = 2; + const uint32_t Q4_K = 12, Q5_1 = 7, Q5_K = 13, Q8_0 = 8, Q3_K = 11, IQ3_S = 21; + strata::kernels::cpu::NativeFmt f0, f1; + std::string err; + if (!strata::kernels::cpu::native_fmt(Q4_K, Q5_1, H, FF, f0, err) || + !strata::kernels::cpu::native_fmt(Q5_K, Q8_0, H, FF, f1, err)) { + check(false, "Q4_K/Q5_1 and Q5_K/Q8_0 native formats: " + err); + return; + } + TempDir d; + const fs::path A = d.path / "M-00002-of-00003.gguf", B = d.path / "M-00003-of-00003.gguf"; + // A: layer 0 (all roles) and layer 1's down; B: layer 1's gate and up + const std::vector ta = {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q4_K, 11}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q4_K, 12}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE}, Q5_1, 13}, + {"blk.1.ffn_down_exps.weight", {FF, H, NE}, Q8_0, 23}}; + const std::vector tb = {{"blk.1.ffn_gate_exps.weight", {H, FF, NE}, Q5_K, 21}, + {"blk.1.ffn_up_exps.weight", {H, FF, NE}, Q5_K, 22}}; + const auto wa = fixture::write(A, {}, ta); + const auto wb = fixture::write(B, {}, tb); + auto at = [](const fixture::Written& w, size_t i) { return std::to_string(w.data_start + w.offsets[i]); }; + const uint64_t total = (f0.bytes + f1.bytes) * NE; + auto text = [&](const std::string& down1, const std::string& col1) { + return "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " + "[shard | gate,up,down] (n_expert 2, total " + std::to_string(total) + ")\n" + + "0 12 7 0 " + std::to_string(f0.bytes) + " " + at(wa, 0) + " " + at(wa, 1) + " " + at(wa, 2) + "\n" + + "1 13 8 " + std::to_string(f0.bytes * NE) + " " + std::to_string(f1.bytes) + " " + at(wb, 0) + " " + + at(wb, 1) + " " + down1 + " " + col1 + "\n"; + }; + const fs::path pack = d.path / "pack"; + fs::create_directories(pack); + write_text(pack / "native_experts.txt", text(at(wa, 3), B.filename().string() + "," + B.filename().string() + ",")); + bool ok = load(pack, 2, 512, err); + check(ok, "the v4 manifest of the split layer loads" + (ok ? "" : ": " + err)); + if (!ok) return; + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + ok = strata::core::check_experts_gguf(A.string(), L, err); + check(ok, "check_experts_gguf: every span is its tensor" + (ok ? "" : ": " + err)); + std::vector dst((size_t) L.total, 0xEE); + const strata::core::LoadStats st = strata::core::load_experts_gguf(A.string(), dst.data(), L, 3); + check(st.ok && st.bytes == L.total && L.total == total, "load_experts_gguf reads the whole arena (" + + std::to_string(L.total) + " B)"); + // every byte: expert e's slice of role r comes from byte e * per[r] of that role's tensor + bool exact = true; + for (int64_t l = 0; l < 2 && exact; ++l) { + const auto& fm = L.fmt[(size_t) l]; + const uint64_t per[3] = {fm.up_off, fm.up_off, fm.bytes - fm.down_off}; + const uint64_t off[3] = {0, fm.up_off, fm.down_off}; + const uint8_t seed[2][3] = {{11, 12, 13}, {21, 22, 23}}; + for (int64_t e = 0; e < NE && exact; ++e) + for (int r = 0; r < 3 && exact; ++r) { + const uint8_t* got = dst.data() + L.blob_offset(l, e) + off[r]; + for (uint64_t j = 0; j < per[r]; ++j) + if (got[j] != fixture::pattern(seed[l][r], (uint64_t) e * per[r] + j)) { exact = false; break; } + } + } + check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files"); + + { // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack) + strata::core::FileExpertSource fs; + fs.set_gguf(A.string()); + std::string e1; + const bool opened = fs.open(pack.string(), 2, NE, e1); + check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1)); + if (opened) { + bool same = true, copies = true, transient = true; + std::vector buf((size_t) std::max(f0.bytes, f1.bytes)); + for (int64_t l = 0; l < 2; ++l) + for (int64_t e = 0; e < NE; ++e) { + fs.begin_layer(l, nullptr, 0); + const uint8_t* b = fs.blob(l, e); + const size_t n = (size_t) L.blob_bytes(l); + same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0; + copies = copies && fs.copy_blob(l, e, buf.data()) && + std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0; + transient = transient && fs.transient(l, e); + } + check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)"); + // a blob asked again in the same layer is the same buffer; its bytes hold through two more layers + fs.begin_layer(0, nullptr, 0); + const uint8_t* p = fs.blob(0, 1); + const uint8_t* q = fs.blob(0, 1); + fs.begin_layer(1, nullptr, 0); + (void) fs.blob(1, 0); + (void) fs.blob(1, 1); + fs.begin_layer(0, nullptr, 0); + (void) fs.blob(0, 0); + check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0, + "an assembled blob stays put while it is in use"); + check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")"); + // prefetch: a layer's experts fetched together on several threads, then the same bytes from blob() + bool pre = true; + for (int round = 0; round < 3; ++round) + for (int64_t l = 0; l < 2; ++l) { + fs.begin_layer(l, nullptr, 0); + fs.begin_layer(l == 0 ? 1 : 0, nullptr, 0); // age the buffers so the prefetch refills them + fs.begin_layer(l, nullptr, 0); + const int64_t both[2] = {1, 0}; + fs.set_fetch_threads(2); + fs.prefetch(l, both, 2); + for (int64_t e = 0; e < NE; ++e) { + const uint8_t* b = fs.blob(l, e); + pre = pre && b != nullptr && + std::memcmp(b, dst.data() + L.blob_offset(l, e), (size_t) L.blob_bytes(l)) == 0; + } + } + check(pre && fs.file_blob_bytes() > 0 && fs.file_ms() >= 0.0, + "prefetch on 2 threads, then blob(): the same bytes"); + } + fs.close(); + // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says + { + std::ofstream eb(pack / "experts.bin", std::ios::binary); + eb.write((const char*) dst.data(), (std::streamsize) dst.size()); + } + strata::core::FileExpertSource fb; + fb.set_gguf(A.string()); + std::string e2; + const bool ob = fb.open(pack.string(), 2, NE, e2); + const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr; + check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr && + std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0, + "with experts.bin the mapped file is used (unchanged behaviour)"); + fb.close(); + fs::remove(pack / "experts.bin"); + } + + auto refused = [&](const std::string& what, const std::string& needle) { + std::string e2; + const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(), + strata::kernels::cpu::expert_layout(), e2); + check(bad && e2.find(needle) != std::string::npos, what + " (\"..." + needle + "...\")"); + }; + const std::string both = B.filename().string() + "," + B.filename().string() + ","; + write_text(pack / "native_experts.txt", text(std::to_string(std::stoull(at(wa, 3)) + 32), both)); + refused("an offset that is not the tensor's is refused", "starts at byte"); + write_text(pack / "native_experts.txt", text(at(wa, 3), "")); + refused("layer 1's gate named in the file that does not hold it is refused", "is not in it"); + write_text(pack / "native_experts.txt", text(at(wa, 3), both + ",x")); + std::string e3; + check(!load(pack, 2, 512, e3), "a malformed column is refused at load"); + write_text(pack / "native_experts.txt", text(at(wa, 3), "missing.gguf,missing.gguf,")); + refused("a shard that is not there is refused", "cannot open"); + fixture::write(B, {}, tb, /*cut=*/100); + write_text(pack / "native_experts.txt", text(at(wa, 3), both)); + refused("a truncated shard is refused before anything is read", "past the end"); + + // a type and a shape the pack does not say: Q3_K and IQ3_S are both 110 B per 256, so only the type differs + TempDir d2; + const fs::path C = d2.path / "C.gguf"; + const auto wc = fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, IQ3_S, 31}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); + strata::kernels::cpu::NativeFmt f2; + if (!strata::kernels::cpu::native_fmt(Q3_K, Q5_1, H, FF, f2, err)) { + check(false, "Q3_K/Q5_1 native format: " + err); + return; + } + fs::create_directories(d2.path / "pack"); + write_text(d2.path / "pack" / "native_experts.txt", + "# strata native experts v3: (n_expert 2, total " + std::to_string(f2.bytes * NE) + ")\n0 11 7 0 " + + std::to_string(f2.bytes) + " " + std::to_string(wc.data_start + wc.offsets[0]) + " " + + std::to_string(wc.data_start + wc.offsets[1]) + " " + std::to_string(wc.data_start + wc.offsets[2]) + "\n"); + ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), + strata::kernels::cpu::expert_layout(), err); + check(ok && err.find("is IQ3_S") != std::string::npos, "a gate of another type than the pack's is refused"); + // the same bytes with the pack's types, but a down tensor of three experts where the pack says two + fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q3_K, 31}, + {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32}, + {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}}); + ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(), + strata::kernels::cpu::expert_layout(), err); + check(ok && err.find("is not [640, 2560, 2]") != std::string::npos, "a down tensor of another shape is refused"); +} +} // namespace + +int main(int argc, char** argv) { + // `expert_layout_test --real PACK_DIR NATIVE_SHARD`: a real pack's native_experts.txt against its model's files + // (headers only - check_experts_gguf reads no expert byte) + if (argc == 4 && std::string(argv[1]) == "--real") { + std::string err; + if (!load(argv[2], 48, 512, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; } + const ExpertLayout& L = strata::kernels::cpu::expert_layout(); + const bool ok = strata::core::check_experts_gguf(argv[3], L, err); + size_t split = 0; + for (int64_t l = 0; l < L.n_layers && !L.gguf_file.empty(); ++l) + split += L.gguf_file[(size_t) (3 * l)] != L.gguf_file[(size_t) (3 * l + 2)]; + std::printf("%s: v%d, %lld layers x %lld experts, %.2f GiB, %zu layer(s) split per role: %s%s\n", argv[2], + L.version, (long long) L.n_layers, (long long) L.n_expert, (double) L.total / (1u << 30), split, + ok ? "every span is its tensor" : "REFUSED: ", ok ? "" : err.c_str()); + return ok ? 0 : 1; + } + std::printf("expert_layout_test\n"); + if (argc < 2) { + std::printf("usage: expert_layout_test \n"); + return 2; + } + real_packs(argv[1]); + columns(); + arena(); + std::printf(g_fail ? "expert_layout_test: %d FAILED\n" : "expert_layout_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/tests/core/file_expert_source_test.cpp b/engine/strata/tests/core/file_expert_source_test.cpp new file mode 100644 index 00000000..e86acc16 --- /dev/null +++ b/engine/strata/tests/core/file_expert_source_test.cpp @@ -0,0 +1,309 @@ +#include "strata/core/expert_source.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" + +#if defined(STRATA_NATIVE_EXPERTS) +#include "strata/kernels/cpu/native_expert.hpp" +#include "ggml.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +void require(bool ok, const std::string& message) { + if (!ok) throw std::runtime_error(message); +} + +struct TempDirectory { + fs::path path; + + TempDirectory() { + const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + path = fs::temp_directory_path() / ("strata-file-source-test-" + std::to_string(stamp)); + fs::create_directories(path); + } + + ~TempDirectory() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +void create_pack(const fs::path& dir, uint64_t bytes, const std::vector>& markers = {}) { + const fs::path file = dir / "experts.bin"; + { + std::ofstream out(file, std::ios::binary | std::ios::trunc); + require((bool) out, "could not create synthetic experts.bin"); + if (bytes > 0) { + out.seekp((std::streamoff) (bytes - 1)); + out.put('\0'); + } + require((bool) out, "could not size synthetic experts.bin"); + } + for (const auto& [offset, marker] : markers) { + require(offset < bytes, "synthetic marker lies beyond experts.bin"); + std::fstream file_out(file, std::ios::binary | std::ios::in | std::ios::out); + require((bool) file_out, "could not open synthetic experts.bin for markers"); + file_out.seekp((std::streamoff) offset); + file_out.put(marker); + require((bool) file_out, "could not write synthetic expert marker"); + } +} + +void check_file_size_rejection(strata::core::FileExpertSource& source, const fs::path& dir, int64_t layers, + int64_t experts, uint64_t expected_bytes) { + std::string err; + source.close(); + fs::resize_file(dir / "experts.bin", expected_bytes - 1); + require(!source.open(dir.string(), layers, experts, err), "a truncated expert file was accepted"); + require(!source.mapped() && !err.empty(), "truncated-file rejection left the source mapped or unreported"); + + fs::resize_file(dir / "experts.bin", expected_bytes + 1); + err.clear(); + require(!source.open(dir.string(), layers, experts, err), "an oversized expert file was accepted"); + require(!source.mapped() && !err.empty(), "oversized-file rejection left the source mapped or unreported"); +} + +void test_canonical_layout() { + using namespace strata::core; + using namespace strata::kernels::cpu; + constexpr int64_t layers = 2; + constexpr int64_t experts = 3; + const uint64_t layer_bytes = (uint64_t) experts * BLOB; + const uint64_t total = (uint64_t) layers * layer_bytes; + TempDirectory dir; + + std::string err; + const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, err); + require(layout_ok, "could not load canonical layout: " + err); + create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) BLOB, 'b'}, {layer_bytes, 'c'}, + {layer_bytes + (uint64_t) BLOB, 'd'}}); + + FileExpertSource source; + bool opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "could not map canonical pack: " + err); + require(source.blobs() == layers * experts, "canonical blob count is wrong"); + const uint8_t* first = source.blob(0, 0); + const uint8_t* second = source.blob(0, 1); + const uint8_t* next_layer = source.blob(1, 0); + require(first && second && next_layer, "valid canonical blob lookup failed"); + require(second - first == (ptrdiff_t) BLOB && next_layer - first == (ptrdiff_t) layer_bytes, + "canonical expert or layer stride is wrong"); + require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c', + "canonical blob lookup returned bytes from the wrong expert"); + require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && + source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, + "canonical bounds check accepted an invalid layer or expert"); + require(source.reads() == 3, "invalid canonical lookups changed the read count"); + + check_file_size_rejection(source, dir.path, layers, experts, total); + create_pack(dir.path, total, {{layer_bytes, 'c'}}); + err.clear(); + opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "source failed to reopen after size errors: " + err); + const uint8_t* reopened = source.blob(1, 0); + require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened canonical source kept stale state"); + source.close(); +} + +#if defined(STRATA_NATIVE_EXPERTS) +void test_native_variable_layout() { + using namespace strata::core; + using namespace strata::kernels::cpu; + constexpr int64_t layers = 2; + constexpr int64_t experts = 3; + constexpr int64_t embedding = 2560; + constexpr int64_t feed_forward = 640; + TempDirectory dir; + + NativeFmt first_fmt, second_fmt; + std::string err; + const bool first_ok = native_fmt(GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, embedding, feed_forward, first_fmt, err); + require(first_ok, "IQ3_XXS/IQ4_NL synthetic format is unavailable: " + err); + err.clear(); + const bool second_ok = native_fmt(GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, embedding, feed_forward, second_fmt, err); + require(second_ok, "IQ2_XS/IQ4_NL synthetic format is unavailable: " + err); + require(first_fmt.bytes != second_fmt.bytes, "chosen native formats do not exercise variable layer sizes"); + + const uint64_t layer0_bytes = (uint64_t) first_fmt.bytes * experts; + const uint64_t total = layer0_bytes + (uint64_t) second_fmt.bytes * experts; + { + std::ofstream metadata(dir.path / "native_experts.txt"); + require((bool) metadata, "could not create synthetic native_experts.txt"); + metadata << "0 " << GGML_TYPE_IQ3_XXS << ' ' << GGML_TYPE_IQ4_NL << " 0 " << first_fmt.bytes << '\n'; + metadata << "1 " << GGML_TYPE_IQ2_XS << ' ' << GGML_TYPE_IQ4_NL << ' ' << layer0_bytes << ' ' + << second_fmt.bytes << '\n'; + require((bool) metadata, "could not write synthetic native_experts.txt"); + } + create_pack(dir.path, total, {{0, 'a'}, {(uint64_t) first_fmt.bytes, 'b'}, + {layer0_bytes, 'c'}, {layer0_bytes + (uint64_t) second_fmt.bytes, 'd'}}); + + const bool layout_ok = expert_layout_load(dir.path.string(), layers, experts, err); + require(layout_ok, "could not load synthetic native layout: " + err); + FileExpertSource source; + bool opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "could not map native pack: " + err); + require(source.blobs() == layers * experts, "native blob count is wrong"); + const uint8_t* first = source.blob(0, 0); + const uint8_t* second = source.blob(0, 1); + const uint8_t* next_layer = source.blob(1, 0); + const uint8_t* next_layer_second = source.blob(1, 1); + require(first && second && next_layer && next_layer_second, "valid native blob lookup failed"); + require(second - first == (ptrdiff_t) first_fmt.bytes && next_layer - first == (ptrdiff_t) layer0_bytes && + next_layer_second - next_layer == (ptrdiff_t) second_fmt.bytes, + "native per-layer expert stride is wrong"); + require(first[0] == 'a' && second[0] == 'b' && next_layer[0] == 'c' && next_layer_second[0] == 'd', + "native blob lookup returned bytes from the wrong expert"); + require(source.blob(-1, 0) == nullptr && source.blob(0, -1) == nullptr && + source.blob(layers, 0) == nullptr && source.blob(0, experts) == nullptr, + "native bounds check accepted an invalid layer or expert"); + require(source.reads() == 4, "invalid native lookups changed the read count"); + + check_file_size_rejection(source, dir.path, layers, experts, total); + create_pack(dir.path, total, {{layer0_bytes, 'c'}}); + err.clear(); + opened = source.open(dir.path.string(), layers, experts, err); + require(opened, "source failed to reopen after size errors: " + err); + const uint8_t* reopened = source.blob(1, 0); + require(reopened && source.reads() == 1 && reopened[0] == 'c', "reopened native source kept stale state"); + source.close(); +} +#endif + +void test_complement_plan() { + using namespace strata::core::detail; + std::vector offsets; + uint64_t bytes = 0; + std::string error; + require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); + require(bytes == 16 && offsets == std::vector{0, kNoCacheComplement, 3, 6, 11, kNoCacheComplement}, + "wrong compact offsets for variable native layer sizes"); + const uint8_t resident[16] = {}, mapped[5] = {}; + require(cache_complement_blob_or_fallback(1, offsets, resident, mapped) == mapped, + "GPU-resident expert lost mmap fallback"); + require(cache_complement_blob_or_fallback(4, offsets, resident, mapped) == resident + 11, + "CPU miss did not use resident complement"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {0, 1}}, {}, offsets, bytes, error) + && offsets.empty() && bytes == 0, "duplicate pair accepted"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}}, {{0, 1}}, offsets, bytes, error), + "overlapping tiers accepted"); + require(!make_cache_complement_plan(2, 3, {3, 5}, {{2, 0}}, {}, offsets, bytes, error), + "out-of-range pair accepted"); + require(!make_cache_complement_plan(2, 3, {0, 5}, {}, {}, offsets, bytes, error), "zero-size layer accepted"); +} + +void test_resident_lend_region() { + using namespace strata::core::detail; + // four slots (sizes 5, 3, 3, 5); the experts no slot holds take 10 bytes + const std::vector slots{5, 3, 3, 5}; + require(choose_resident_keep_from(slots, 10, 9, 1) == -1, "a base larger than the budget was accepted"); + require(choose_resident_keep_from(slots, 10, 10, 1) == 4, "no room: the lend region must stay on the file"); + require(choose_resident_keep_from(slots, 10, 15, 1) == 3, "the last slot fits and must be kept first"); + require(choose_resident_keep_from(slots, 10, 17, 1) == 3, "a slot that does not fit ends the lend region's walk"); + require(choose_resident_keep_from(slots, 10, 18, 1) == 2, "two slots fit"); + require(choose_resident_keep_from(slots, 10, 100, 1) == 1, "the walk must stop at the lend region's first slot"); + require(choose_resident_keep_from(slots, 10, 100, -1) == 4, "no lend region kept slots in RAM"); + require(choose_resident_keep_from(slots, 10, 100, 9) == 4, "an out-of-range lend region kept slots in RAM"); + require(choose_resident_keep_from({}, 0, 0, 0) == 0, "an empty cache"); +} + +void test_resident_exchange() { + using namespace strata::core; + using namespace strata::core::detail; + // 2 layers x 3 experts; the GPU holds (0,1) and (1,2): the compact copy holds the other four + std::vector offsets; + uint64_t bytes = 0; + std::string error; + require(make_cache_complement_plan(2, 3, {3, 5}, {{0, 1}, {1, 2}}, {}, offsets, bytes, error), error); + const std::vector before = offsets; + // (1,0) moves into the GPU, (1,2) leaves it: (1,2) takes (1,0)'s bytes' place + require(exchange_cache_complement(offsets, 3, 5), "a valid exchange was refused"); + require(offsets[5] == before[3] && offsets[3] == kNoCacheComplement, "the exchange did not move the place"); + for (size_t i : {0u, 1u, 2u, 4u}) require(offsets[i] == before[i], "an exchange touched another expert"); + // the copy's size and its set of places are unchanged + std::vector a, b; + for (uint64_t o : before) if (o != kNoCacheComplement) a.push_back(o); + for (uint64_t o : offsets) if (o != kNoCacheComplement) b.push_back(o); + std::sort(a.begin(), a.end()); + std::sort(b.begin(), b.end()); + require(a == b, "an exchange changed the compact copy's places"); + const std::vector after = offsets; + require(!exchange_cache_complement(offsets, 3, 0), "an `in` the copy does not hold was accepted"); + require(!exchange_cache_complement(offsets, 0, 2), "an `out` the copy holds already was accepted"); + require(!exchange_cache_complement(offsets, 0, 0), "a self-exchange was accepted"); + require(!exchange_cache_complement(offsets, 0, 6), "an out-of-range `out` was accepted"); + require(offsets == after, "a refused exchange changed the offsets"); + // and back: the copy is again what the plan makes for the original placement + require(exchange_cache_complement(offsets, 5, 3), "the reverse exchange was refused"); + require(offsets == before, "exchanging back did not restore the plan"); +} + +void test_cgroup_memory_budget() { + using namespace strata::core::detail; + constexpr uint64_t GiB = 1ull << 30; + uint64_t bytes = 0; + + CgroupMemoryStat clean_cache{40 * GiB, 32 * GiB, 0, 0, true}; + require(cgroup_available_bytes(56 * GiB, clean_cache, bytes), "valid cgroup memory.stat was rejected"); + require(bytes == 48 * GiB, "clean inactive file cache was not credited against the cgroup cap"); + + CgroupMemoryStat dirty_cache{40 * GiB, 32 * GiB, 4 * GiB, 2 * GiB, true}; + require(cgroup_available_bytes(56 * GiB, dirty_cache, bytes), "valid dirty-cache counters were rejected"); + require(bytes == 42 * GiB, "dirty/writeback pages were incorrectly counted as reclaimable"); + + CgroupMemoryStat oversized_inactive{10 * GiB, 20 * GiB, 0, 0, true}; + require(cgroup_available_bytes(12 * GiB, oversized_inactive, bytes), + "valid oversized inactive-file counter was rejected"); + require(bytes == 12 * GiB, "inactive-file accounting exceeded charged current usage"); + + const uint64_t max = std::numeric_limits::max(); + CgroupMemoryStat large_counters{max, max, max - 1, max, true}; + require(cgroup_available_bytes(max, large_counters, bytes), + "large memory.stat counters were rejected"); + require(bytes == 0, "dirty/writeback subtraction overflowed or escaped the usage cap"); + + CgroupMemoryStat usage_over_limit{60 * GiB, 0, 0, 0, true}; + require(cgroup_available_bytes(56 * GiB, usage_over_limit, bytes), + "valid over-limit memory counters were rejected"); + require(bytes == 0, "over-limit cgroup usage produced a positive budget"); + + CgroupMemoryStat missing_stat{}; + bytes = 123; + require(!cgroup_available_bytes(56 * GiB, missing_stat, bytes) && bytes == 0, + "missing memory.stat counters did not fail closed"); +} + +} // namespace + +int main() { + try { + test_complement_plan(); + test_resident_lend_region(); + test_resident_exchange(); + test_cgroup_memory_budget(); + test_canonical_layout(); +#if defined(STRATA_NATIVE_EXPERTS) + test_native_variable_layout(); +#endif + std::cout << "file_expert_source_test: PASS\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << "file_expert_source_test: " << error.what() << '\n'; + return 1; + } +} diff --git a/engine/strata/tests/core/gguf_fixture.hpp b/engine/strata/tests/core/gguf_fixture.hpp new file mode 100644 index 00000000..677a5cd8 --- /dev/null +++ b/engine/strata/tests/core/gguf_fixture.hpp @@ -0,0 +1,103 @@ +// tests/core/gguf_fixture.hpp - synthetic GGUF v3 files for the loader tests (no gguf-py, no model, no GPU). +// +// A file is a header, metadata (strings and integers only), a tensor directory whose offsets are 32-byte aligned +// in the data section, and the tensors' payloads, each filled with a pattern the test can recognise. +#pragma once + +#include "strata/artifact/gguf_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace fixture { + +struct Kv { + std::string key; + uint32_t type = 8; ///< GGUF value type: 8 string, 2 u16, 4 u32, 5 i32 + std::string s; + uint64_t u = 0; +}; +inline Kv str(const std::string& k, const std::string& v) { return Kv{k, 8, v, 0}; } +inline Kv u16(const std::string& k, uint64_t v) { return Kv{k, 2, {}, v}; } +inline Kv i32(const std::string& k, uint64_t v) { return Kv{k, 5, {}, v}; } +inline Kv u32(const std::string& k, uint64_t v) { return Kv{k, 4, {}, v}; } + +struct Tensor { + std::string name; + std::vector shape; ///< GGUF order: dim 0 varies fastest + uint32_t type = 0; + uint8_t seed = 1; ///< payload byte i is (seed * 131 + i * 7 + i / 4093) & 0xff +}; + +inline uint8_t pattern(uint8_t seed, uint64_t i) { return (uint8_t) ((seed * 131u + i * 7u + i / 4093u) & 0xffu); } + +/// The split keys llama.cpp's gguf-split writes (u16 split.no / split.count, i32 split.tensors.count). +inline std::vector split_keys(uint64_t no, uint64_t count, uint64_t tensors) { + return {u16("split.no", no), u16("split.count", count), i32("split.tensors.count", tensors)}; +} + +struct Written { + uint64_t data_start = 0; + std::vector offsets; ///< per tensor, from data_start + uint64_t size = 0; +}; + +/// Writes `path`; `cut` bytes are dropped from the end (a truncated download). +inline Written write(const std::filesystem::path& path, const std::vector& kv, const std::vector& ts, + uint64_t cut = 0) { + std::vector b; + auto put = [&](const void* p, size_t n) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + n); }; + auto put32 = [&](uint32_t v) { put(&v, 4); }; + auto put64 = [&](uint64_t v) { put(&v, 8); }; + auto puts = [&](const std::string& s) { put64(s.size()); put(s.data(), s.size()); }; + put32(0x46554747u); + put32(3); + put64(ts.size()); + put64(kv.size()); + for (const auto& k : kv) { + puts(k.key); + put32(k.type); + if (k.type == 8) puts(k.s); + else if (k.type == 2) { const uint16_t v = (uint16_t) k.u; put(&v, 2); } + else if (k.type == 4 || k.type == 5) { const uint32_t v = (uint32_t) k.u; put(&v, 4); } + else throw std::runtime_error("fixture: unsupported metadata type"); + } + Written w; + std::vector bytes; + uint64_t at = 0; + for (const auto& t : ts) { + strata::TensorInfo info; + info.shape = t.shape; + info.type = t.type; + const uint64_t n = strata::tensor_payload_bytes(info); + if (n == 0) throw std::runtime_error("fixture: " + t.name + " has no whole-block byte count"); + puts(t.name); + put32((uint32_t) t.shape.size()); + for (uint64_t d : t.shape) put64(d); + put32(t.type); + put64(at); + w.offsets.push_back(at); + bytes.push_back(n); + at = (at + n + 31) / 32 * 32; + } + w.data_start = (b.size() + 31) / 32 * 32; + b.resize((size_t) w.data_start, 0); + for (size_t i = 0; i < ts.size(); ++i) { + b.resize((size_t) (w.data_start + w.offsets[i]), 0); + for (uint64_t j = 0; j < bytes[i]; ++j) b.push_back(pattern(ts[i].seed, j)); + } + if (cut > b.size()) cut = b.size(); + b.resize(b.size() - (size_t) cut); + w.size = b.size(); + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write((const char*) b.data(), (std::streamsize) b.size()); + if (!f) throw std::runtime_error("fixture: cannot write " + path.string()); + return w; +} + +} // namespace fixture diff --git a/engine/strata/tests/core/gguf_split_test.cpp b/engine/strata/tests/core/gguf_split_test.cpp new file mode 100644 index 00000000..3f137ccb --- /dev/null +++ b/engine/strata/tests/core/gguf_split_test.cpp @@ -0,0 +1,220 @@ +// tests/core/gguf_split_test.cpp - a split model's shards (strata::gguf_split_paths) and their joint view +// (strata::GgufModel), on synthetic GGUFs: no model, no GPU. +// +// The layout is Unsloth's UD-Q4_K_XL in miniature: shard 1 holds the metadata and no tensor, shards 2-4 the +// tensors, and layer 11's down sits in shard 2 while its gate and up are in shard 3. Then the ways a real +// download goes wrong: a shard missing, a shard of another model (split keys that disagree), a tensor in two +// shards, a directory that does not add up to split.tensors.count, a truncated shard, and shard 1 opened alone. +#include "gguf_fixture.hpp" + +#include "strata/artifact/gguf_split.hpp" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-78s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-gguf-split-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +std::string shard_name(int i, int n) { + char b[64]; + std::snprintf(b, sizeof b, "Model-UD-Q4_K_XL-%05d-of-%05d.gguf", i, n); + return b; +} + +using fixture::Tensor; +const uint32_t F32 = 0, Q8_0 = 8; + +/// Writes the 4-shard model; `mutate(i, kv, tensors)` may change shard i (0-based) before it is written. +template std::vector write_model(const fs::path& dir, F mutate, uint64_t total = 7) { + std::vector paths; + for (int i = 0; i < 4; ++i) { + std::vector kv; + if (i == 0) kv.push_back(fixture::str("general.architecture", "qwen4exp")); + for (const auto& k : fixture::split_keys((uint64_t) i, 4, total)) kv.push_back(k); + std::vector ts; + if (i == 1) ts = {{"output.weight", {64, 4}, Q8_0, 1}, {"token_embd.weight", {64, 4}, Q8_0, 2}, + {"blk.11.ffn_down_exps.weight", {32, 32, 2}, F32, 3}}; + if (i == 2) ts = {{"blk.11.ffn_gate_exps.weight", {32, 32, 2}, F32, 4}, + {"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 5}, {"blk.12.attn_q.weight", {32, 8}, F32, 6}}; + if (i == 3) ts = {{"output_norm.weight", {32}, F32, 7}}; + uint64_t cut = 0; + mutate(i, kv, ts, cut); + const fs::path p = dir / shard_name(i + 1, 4); + fixture::write(p, kv, ts, cut); + paths.push_back(p.string()); + } + return paths; +} +auto same = [](int, std::vector&, std::vector&, uint64_t&) {}; + +std::string error_of(const std::vector& paths) { + try { + strata::GgufModel m(paths); + } catch (const std::exception& e) { + return e.what(); + } + return {}; +} +} // namespace + +// `gguf_split_test --real SHARD`: the same view of a real model (headers only): its shards, the architecture +// check on the metadata shard, and where the tensors the engine reads by name live. +int real_model(const std::string& any) { + try { + const strata::GgufModel m = strata::GgufModel::open(any); + size_t tensors = 0; + for (size_t i = 0; i < m.size(); ++i) { + std::printf(" shard %zu: %s, %zu tensors, data at %llu\n", i + 1, m.shard(i).path().c_str(), + m.shard(i).tensors().size(), (unsigned long long) m.shard(i).data_start()); + tensors += m.shard(i).tensors().size(); + } + const std::string arch = strata::check_architecture(m.meta()); + std::printf(" %zu tensors; architecture check on the metadata shard: %s\n", tensors, + arch.empty() ? "ok" : arch.c_str()); + int bad = arch.empty() ? 0 : 1; + for (const char* name : {"output.weight", "token_embd.weight", "per_layer_token_embd.weight", + "blk.1.ple_key.weight", "blk.11.ffn_gate_exps.weight", "blk.11.ffn_up_exps.weight", + "blk.11.ffn_down_exps.weight"}) { + size_t s = 0; + const strata::TensorInfo* t = m.find(name, &s); + if (!t) { std::printf(" %-30s absent\n", name); continue; } + const bool ok = m.in_bounds(*t, s); + bad += !ok; + std::printf(" %-30s shard %zu, %s, %llu B, %s\n", name, s + 1, t->type_name(), + (unsigned long long) strata::tensor_payload_bytes(*t), ok ? "in bounds" : "OUT OF BOUNDS"); + } + return bad ? 1 : 0; + } catch (const std::exception& e) { + std::printf(" refused: %s\n", e.what()); + return 1; + } +} + +int main(int argc, char** argv) { + if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]); + std::printf("gguf_split_test\n"); + { + TempDir d; + const auto paths = write_model(d.path, same); + // any shard names the family; the list is in split order, metadata shard first + std::vector got; + try { got = strata::gguf_split_paths(paths[2]); } catch (...) {} + check(got == paths, "gguf_split_paths from shard 3: the 4 shards in order"); + try { got = strata::gguf_split_paths(paths[0]); } catch (...) { got.clear(); } + check(got == paths, "gguf_split_paths from shard 1: the same 4 shards"); + check(strata::gguf_split_paths((d.path / "plain.gguf").string()).size() == 1, + "a name without -NNNNN-of-MMMMM is a model of one file"); + std::string err; + try { + const strata::GgufModel m(paths); + size_t s_out = 9, s_gate = 9, s_down = 9, s_up = 9; + const strata::TensorInfo* out = m.find("output.weight", &s_out); + const strata::TensorInfo* gate = m.find("blk.11.ffn_gate_exps.weight", &s_gate); + const strata::TensorInfo* up = m.find("blk.11.ffn_up_exps.weight", &s_up); + const strata::TensorInfo* down = m.find("blk.11.ffn_down_exps.weight", &s_down); + check(m.size() == 4 && m.meta().get("general.architecture") && m.meta().tensors().empty(), + "shard 1: the metadata, no tensor"); + check(out && s_out == 1 && m.in_bounds(*out, s_out), "output.weight found in shard 2, in bounds"); + check(gate && up && down && s_gate == 2 && s_up == 2 && s_down == 1, + "layer 11 per role: gate/up in shard 3, down in shard 2"); + check(m.find("blk.99.ffn_gate_exps.weight") == nullptr, "an absent tensor is nullptr"); + check(strata::check_architecture(m.meta()).find("block_count") != std::string::npos, + "the architecture guard reads the metadata shard (and wants its keys)"); + } catch (const std::exception& e) { + err = e.what(); + } + check(err.empty(), "the 4-shard model opens" + (err.empty() ? std::string() : ": " + err)); + } + { + TempDir d; + const auto paths = write_model(d.path, same); + fs::remove(paths[3]); + std::string err; + try { strata::gguf_split_paths(paths[0]); } catch (const std::exception& e) { err = e.what(); } + check(err.find("missing model shard") != std::string::npos && err.find(shard_name(4, 4)) != std::string::npos, + "a missing shard is an error that names it"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { + if (i == 3) ts.push_back({"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 9}); + }, 8); + const std::string err = error_of(paths); + check(err.find("in two shards") != std::string::npos && err.find(shard_name(3, 4)) != std::string::npos && + err.find(shard_name(4, 4)) != std::string::npos, + "a tensor in two shards is refused, naming both"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 2) kv = fixture::split_keys(1, 4, 7); // says it is shard 2 + }); + check(error_of(paths).find("does not declare itself shard 3 of 4") != std::string::npos, + "a shard whose split.no disagrees with its place is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 3) kv = fixture::split_keys(3, 4, 9); // another model's split.tensors.count + }); + check(!error_of(paths).empty(), "a shard of another model (split.tensors.count differs) is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) { + if (i == 3) ts.clear(); // a directory short of split.tensors.count + }); + check(error_of(paths).find("split.tensors.count is 7") != std::string::npos, + "shards that do not add up to split.tensors.count are refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) { + if (i == 0) kv.erase(kv.begin()); // no general.architecture in shard 1 + }); + check(error_of(paths).find("general.architecture") != std::string::npos, + "a split model whose first shard has no metadata is refused"); + check(error_of({paths[0]}).find("opened as a whole model") != std::string::npos, + "shard 1 of 4 opened as a whole model is refused"); + } + { + TempDir d; + const auto paths = write_model(d.path, [](int i, auto&, auto&, uint64_t& cut) { + if (i == 2) cut = 100; // the last tensor of shard 3 is cut short + }); + bool truncated = false, first_ok = false; + try { + const strata::GgufModel m(paths); + size_t s = 0; + const strata::TensorInfo* q = m.find("blk.12.attn_q.weight", &s); + const strata::TensorInfo* g = m.find("blk.11.ffn_gate_exps.weight"); + truncated = q && !m.in_bounds(*q, s); + first_ok = g && m.in_bounds(*g, 2); + } catch (...) {} + check(truncated && first_ok, "a truncated shard: its last tensor is out of bounds, the others are not"); + } + std::printf(g_fail ? "gguf_split_test: %d FAILED\n" : "gguf_split_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/tests/core/native_dense_ple_key_test.cpp b/engine/strata/tests/core/native_dense_ple_key_test.cpp new file mode 100644 index 00000000..e69d8385 --- /dev/null +++ b/engine/strata/tests/core/native_dense_ple_key_test.cpp @@ -0,0 +1,169 @@ +// tests/core/native_dense_ple_key_test.cpp - #326: a native pack whose PLE key row is BF16 (iq_pack --compat-bf16 of +// OrcaRouter's IQ3_XXS key) loads with that row in the arena, and NativeDense does not upload the GGUF key over it. +// +// 1. BF16 key row + IQ3_XXS GGUF key: served_names lists the key, keep_unquantized_ple_key takes it out of the +// skip set, the arena holds the BF16 bytes, and NativeDense::load attaches no native key (0.1.25-0.1.31 refused +// the load with "incompatible matrix blk.1.ple_key.weight"). The other matrix still gets its native upload. +// 2. A quantized key row (the Q2_0 / UD-Q4_K_XL packs: a shape-only row) + a Q8_0 GGUF key: unchanged - the key +// stays skipped and is served natively. +// 3. index_code_bits on a missing row and a missing index. +// Synthetic files at small dimensions; needs a CUDA device for the arena (exits 77 without one). +#include "gguf_fixture.hpp" + +#include "strata/core/native_dense.hpp" +#include "strata/core/weights.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using strata::core::NativeDense; +using strata::core::WeightTable; + +namespace { +int g_fail = 0; +void check(bool ok, const std::string& what) { + std::printf(" %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++g_fail; +} + +struct TempDir { + fs::path path; + TempDir() { + path = fs::temp_directory_path() / + ("strata-ple-key-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ignored; + fs::remove_all(path, ignored); + } +}; + +const char* KEY = "blk.1.ple_key.weight"; +const char* QKV = "blk.0.attn_qkv.weight"; +constexpr uint64_t NE0 = 256, NE1 = 4; + +std::vector arch_keys() { + return {fixture::str("general.architecture", "qwen4exp"), fixture::u32("qwen4exp.block_count", 48), + fixture::u32("qwen4exp.embedding_length", 2560), fixture::u32("qwen4exp.expert_count", 512), + fixture::u32("qwen4exp.expert_used_count", 10), fixture::u32("qwen4exp.attention.head_count", 24), + fixture::u32("qwen4exp.attention.head_count_kv", 2)}; +} + +// A shape-only quantized row (what iq_pack writes for a tensor the GGUF serves) and, with `bf16_key`, the key as a +// raw BF16 row (index kind 4) in dense.bin. +void write_pack(const fs::path& dir, bool bf16_key) { + fs::create_directories(dir); + const uint64_t key_bytes = NE0 * NE1 * 2; + std::string idx = "# align 256 pool " + std::to_string(bf16_key ? 2048 + 256 : 256) + " tensors 2\n"; + idx += std::string(QKV) + " 0 0 0 0 0 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; + if (bf16_key) + idx += std::string(KEY) + " 0 4 0 " + std::to_string(key_bytes) + " 256 " + std::to_string(key_bytes) + + " 256 4 0 0 1 0 0 0 0 0 0 0\n"; + else + idx += std::string(KEY) + " 0 0 0 0 256 0 256 4 8 0 32 0 0 0 0 0 0 0\n"; + std::ofstream(dir / "index.txt", std::ios::binary) << idx; + std::vector bytes(bf16_key ? key_bytes : 16); + for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = (char) fixture::pattern(9, i); + std::ofstream(dir / "dense.bin", std::ios::binary).write(bytes.data(), (std::streamsize) bytes.size()); +} + +struct Loaded { + bool ok = false; + std::string err; + std::set skip; + WeightTable wt; + NativeDense dense; + void* arena = nullptr; + ~Loaded() { if (arena) cudaFree(arena); } +}; + +// generate.cpp's order: served_names, keep_unquantized_ple_key (native packs), pool_bytes, load, NativeDense::load. +void load(const fs::path& pack, const std::string& shard, Loaded& l) { + const std::vector shards{shard}; + if (!NativeDense::served_names(shards, true, l.skip, l.err)) return; + if (!NativeDense::keep_unquantized_ple_key(pack.string(), l.skip, l.err)) return; + uint64_t pool = 0; + if (!WeightTable::pool_bytes(pack.string(), pool, l.err, &l.skip)) return; + if (cudaMalloc(&l.arena, pool ? pool : 256) != cudaSuccess) { l.err = "cudaMalloc"; return; } + if (!l.wt.load(pack.string(), l.arena, pool ? pool : 256, l.err, &l.skip)) return; + l.ok = l.dense.load(shards, l.wt, l.err, true); +} +} // namespace + +int main() { + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::printf("native_dense_ple_key_test: no CUDA device, skipped\n"); + return 77; + } + TempDir tmp; + + std::printf("1. BF16 key row (--compat-bf16), IQ3_XXS GGUF key\n"); + { + const fs::path pack = tmp.path / "orca"; + write_pack(pack, true); + const std::string shard = (tmp.path / "orca.gguf").string(); + fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 18, 2}}); + int bits = 99; + std::string err; + check(WeightTable::index_code_bits(pack.string(), KEY, bits, err) && bits == 0, "index_code_bits: key row is 0"); + check(WeightTable::index_code_bits(pack.string(), QKV, bits, err) && bits == 8, "index_code_bits: qkv row is 8"); + Loaded l; + load(pack, shard, l); + check(l.ok, "the pack loads (was: incompatible matrix) " + l.err); + check(!l.skip.count(KEY) && l.skip.count(QKV), "the key is not skipped, qkv is"); + const auto* k = l.wt.find(KEY); + check(k && k->resident && k->data && !k->quantized(), "the key is resident and BF16"); + check(k && !k->native_data, "no native key attached"); + if (k && k->data) { + std::vector back(NE0 * NE1 * 2); + cudaMemcpy(back.data(), k->data, back.size(), cudaMemcpyDeviceToHost); + bool same = true; + for (size_t i = 0; i < back.size(); ++i) same = same && back[i] == fixture::pattern(9, i); + check(same, "the arena holds the pack's BF16 bytes"); + } + const auto* q = l.wt.find(QKV); + check(q && q->native_data && q->native_type == 8, "qkv still served natively (Q8_0)"); + check(l.dense.tensor_count() == 1, "one native matrix"); + } + + std::printf("2. quantized key row (Q2_0 / UD-Q4_K_XL packs), Q8_0 GGUF key: unchanged\n"); + { + const fs::path pack = tmp.path / "q8"; + write_pack(pack, false); + const std::string shard = (tmp.path / "q8.gguf").string(); + fixture::write(shard, arch_keys(), {{QKV, {NE0, NE1}, 8, 1}, {KEY, {NE0, NE1}, 8, 2}}); + Loaded l; + load(pack, shard, l); + check(l.ok, "the pack loads " + l.err); + check(l.skip.count(KEY) == 1, "the key stays skipped"); + const auto* k = l.wt.find(KEY); + check(k && !k->resident && k->native_data && k->native_type == 8, "the key is served natively"); + check(l.dense.tensor_count() == 2, "two native matrices"); + } + + std::printf("3. index_code_bits edge cases\n"); + { + int bits = 0; + std::string err; + check(WeightTable::index_code_bits((tmp.path / "orca").string(), "blk.9.nothing.weight", bits, err) && + bits == -1, "a missing row is -1"); + check(!WeightTable::index_code_bits((tmp.path / "none").string(), KEY, bits, err) && !err.empty(), + "a missing index is an error"); + std::set skip{QKV}; + check(NativeDense::keep_unquantized_ple_key((tmp.path / "none").string(), skip, err) && skip.size() == 1, + "no key in the skip set: the index is not read"); + } + + std::printf(g_fail ? "native_dense_ple_key_test: %d FAILED\n" : "native_dense_ple_key_test: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/engine/strata/tests/cuda/prefill_mmq_kquant_test.cpp b/engine/strata/tests/cuda/prefill_mmq_kquant_test.cpp new file mode 100644 index 00000000..01e6efff --- /dev/null +++ b/engine/strata/tests/cuda/prefill_mmq_kquant_test.cpp @@ -0,0 +1,168 @@ +// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL (Q4_K and +// Q5_K gate/up at 1280 x 2560, Q5_1 and Q8_0 down at 2560 x 640), on synthetic weights quantized by ggml's own +// reference quantizers, against a double-precision product of ggml's dequantized weights. MMQ rounds the activations +// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of +// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test. Several experts per product, permuted rows, an +// all-zero row; the formats the build does not cover (Q6_K) must say so. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; +}; + +std::vector make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) { + const auto* tr = ggml_get_type_traits(t); + if (tr == nullptr || tr->from_float_ref == nullptr) throw std::runtime_error("no reference quantizer"); + const size_t rb = ggml_row_size(t, cols); + std::vector out((size_t) rows * rb); + std::vector row((size_t) cols); + for (int64_t r = 0; r < rows; ++r) { + for (int64_t k = 0; k < cols; ++k) { + const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50; + row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) + + 0.0015f * (float) code; + } + tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols); + } + return out; +} + +std::vector make_x(int rows, int64_t cols, int trial) { + std::vector x((size_t) rows * (size_t) cols); + for (int r = 0; r < rows; ++r) + for (int64_t k = 0; k < cols; ++k) + x[(size_t) r * (size_t) cols + (size_t) k] = + 0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) + + 0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) + + 0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9); + std::fill(x.end() - cols, x.end(), 0.0f); // an all-zero row: exactly zero out + return x; +} + +std::vector perm(int n, int shift, bool reverse) { + std::vector p((size_t) n); + for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n); + return p; +} + +// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them) +void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols, + const std::vector& counts, int trial) { + if (!mmq::supported((int) t)) throw std::runtime_error(std::string(name) + ": not covered by this build"); + const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0); + std::vector bounds((size_t) n + 1, 0); + for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e]; + const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true); + const std::vector x = make_x(rows, cols, trial); + const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols); + if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes"); + std::vector> ws; + std::vector w((size_t) n * eb + 4096, 0); + for (int e = 0; e < n; ++e) { + ws.push_back(make_matrix(t, out_rows, cols, e, trial)); + std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb)); + } + Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst((size_t) rows * 4), db(bounds.size() * 4), dw(w.size()), + dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4); + ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src"); + ck(cudaMemcpy(ddst.p, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst"); + ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds"); + ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); + ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel"); + mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s); + mmq::Product p; + p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n; + p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows; + p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows; + ctx.run(p, s); + ck(cudaGetLastError(), "launch"); + ck(cudaStreamSynchronize(s), "sync"); + std::vector got((size_t) rows * (size_t) out_rows); + ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y"); + + const auto* tr = ggml_get_type_traits(t); + std::vector ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols); + for (int e = 0; e < n; ++e) { + const size_t rb = ggml_row_size(t, cols); + for (int64_t o = 0; o < out_rows; ++o) + tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols); + for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) { + const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols; + for (int64_t o = 0; o < out_rows; ++o) { + double acc = 0; + const float* wr = wd.data() + (size_t) o * (size_t) cols; + for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k]; + ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc; + } + } + } + double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0; + for (size_t i = 0; i < got.size(); ++i) { + if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output"); + const double d = (double) got[i] - ref[i]; + err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d)); + } + for (int r = 0; r < rows; ++r) + if (src[(size_t) r] == rows - 1) // the zero row + for (int64_t o = 0; o < out_rows; ++o) + zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o])); + const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms; + std::printf("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n", name, rows, n, rms, + rel, max_abs / rms, zero_max); + if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms)) + throw std::runtime_error(std::string(name) + ": outside the screen"); +} +} // namespace + +int main() { + try { + if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } + if (mmq::supported(GGML_TYPE_Q6_K)) throw std::runtime_error("Q6_K should not be covered"); + cudaStream_t s = nullptr; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + { + mmq::Context ctx; + const std::vector> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}}; + int trial = 0; + for (const auto& counts : batches) { + const std::string tag = "-" + std::to_string(trial); + product(ctx, s, ("Q4_K gate/up" + tag).c_str(), GGML_TYPE_Q4_K, 1280, 2560, counts, trial); + product(ctx, s, ("Q5_K gate/up" + tag).c_str(), GGML_TYPE_Q5_K, 1280, 2560, counts, trial + 5); + product(ctx, s, ("Q5_1 down" + tag).c_str(), GGML_TYPE_Q5_1, 2560, 640, counts, trial + 9); + product(ctx, s, ("Q8_0 down" + tag).c_str(), GGML_TYPE_Q8_0, 2560, 640, counts, trial + 13); + ++trial; + } + } + ck(cudaStreamDestroy(s), "destroy"); + std::printf("prefill MMQ K-quant screen passed\n"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill MMQ K-quant screen failed: %s\n", e.what()); + return 1; + } +} diff --git a/engine/strata/tests/data/native_experts/coder-iq1_m.txt b/engine/strata/tests/data/native_experts/coder-iq1_m.txt new file mode 100644 index 00000000..bf0c408a --- /dev/null +++ b/engine/strata/tests/data/native_experts/coder-iq1_m.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 256, total 25146163200; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf, or in the named shard beside it) +0 18 20 0 2176000 1150562336 1313362976 913711136 +1 22 42 557056000 1510400 1664626592 1801161632 1545740192 +2 22 20 943718400 1971200 2308902688 2445488928 2072051488 +3 22 20 1448345600 1971200 2885763232 3022298272 2648912032 +4 22 20 1952972800 1971200 3458564256 3595572896 3221713056 +5 22 20 2457600000 1971200 4038269472 4174804512 3801418272 +6 22 20 2962227200 1971200 4613172128 4750180768 4376320928 +7 18 20 3466854400 2176000 5193708832 5356458272 4956857632 +8 22 42 4023910400 1510400 5696376096 5832911136 5577489696 +9 22 20 4410572800 1971200 6271347872 6407934112 6034496672 +10 22 42 4915200000 1510400 6732983328 6869569568 6614096928 +11 22 20 5301862400 1971200 7314285472 7450871712 7077434272 +12 18 42 5806489600 1715200 7761567136 7924790176 7642680736 +13 22 42 6245580800 1510400 8269195552 8405781792 8150309152 +14 18 20 6632243200 2176000 8850188448 9012937888 8613337248 +15 22 20 7189299200 1971200 9478952992 9615961632 9242101792 +16 18 20 7693926400 2176000 10047629856 10210430496 9810778656 +17 21 20 8250982400 2329600 10683191712 10865601952 10446340512 +18 18 20 8847360000 2176000 11353477408 11516482848 11116626208 +19 22 20 9404416000 1971200 11989461152 12126469792 11752609952 +20 18 42 9909043200 1715200 12445193376 12607942816 12326306976 +21 21 42 10348134400 1868800 12962739232 13145200672 12843852832 +22 18 20 10826547200 2176000 13631427488 13794650528 13394576288 +23 22 20 11383603200 1971200 14269635872 14406426912 14032784672 +24 22 20 11888230400 1971200 14842897696 14979432736 14606046496 +25 21 20 12392857600 2329600 15426184352 15608594592 15189333152 +26 22 20 12989235200 1971200 16097957408 16234966048 15861106208 +27 21 20 13493862400 2329600 16682121632 16864531872 16445270432 +28 21 20 14090240000 2329600 17346621856 17529505696 17109770656 +29 21 20 14686617600 2329600 18018868512 18201534752 17782017312 +30 18 42 15282995200 1715200 18571885728 18734635168 18452999328 +31 18 20 15722086400 2176000 19213849632 19376599072 18976998432 +32 22 20 16279142400 1971200 19837195296 19974203936 19600344096 +33 18 20 16783769600 2176000 20413173152 20575922592 20176321952 +34 22 20 17340825600 1971200 21040655648 21177241888 20803804448 +35 21 20 17845452800 2329600 21630446752 21812856992 21393595552 +36 22 42 18441830400 1510400 22173400736 22310409376 22054514336 +37 18 20 18828492800 2176000 22753323552 22916546592 22516472352 +38 18 20 19385548800 2176000 23383942048 23546742688 23147090848 +39 22 20 19942604800 1971200 24025905952 24162492192 23789054752 +40 21 20 20447232000 2329600 24598758176 24781424416 24361906976 +41 18 20 21043609600 2176000 25262981792 25425782432 25026130592 +42 18 20 21600665600 2176000 25890515488 26053738528 25653664288 +43 18 20 22157721600 2176000 26532901792 26696124832 26296050592 +44 21 20 22714777600 2329600 27151490976 27333952416 26914639776 +45 21 20 23311155200 2329600 27818796832 28001258272 27581945632 +46 18 20 23907532800 2176000 28488532128 28651332768 28251680928 +47 23 20 24464588800 2662400 29129699872 29354759712 28892029472 diff --git a/engine/strata/tests/data/native_experts/iq2_xs.txt b/engine/strata/tests/data/native_experts/iq2_xs.txt new file mode 100644 index 00000000..61c34b85 --- /dev/null +++ b/engine/strata/tests/data/native_experts/iq2_xs.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 35454976000; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf) +0 22 42 0 1510400 957139232 1229167392 720288032 +1 16 42 773324800 1305600 1791743648 2011983008 1554892448 +2 22 42 1441792000 1510400 2589468704 2861663264 2352617504 +3 22 42 2215116800 1510400 3429617568 3701812128 3191947168 +4 16 42 2988441600 1305600 4258654112 4478419872 4021802912 +5 22 42 3656908800 1510400 4988400928 5260595488 4751549728 +6 22 42 4430233600 1510400 5824781984 6096976544 5588391584 +7 22 42 5203558400 1510400 6665627168 6938295328 6429236768 +8 29 42 5976883200 1177600 7496734752 7683732512 7259883552 +9 16 42 6579814400 1305600 8161931168 8381530528 7924260768 +10 16 42 7248281600 1305600 8893109024 9112874784 8656257824 +11 16 42 7916748800 1305600 9628172448 9847938208 9391782048 +12 22 42 8585216000 1510400 10354422432 10627090592 10117571232 +13 29 42 9358540800 1177600 11191917088 11378748448 10954246688 +14 16 42 9961472000 1305600 11856780704 12076546464 11619110304 +15 22 42 10629939200 1510400 12596884768 12868912928 12360033568 +16 22 42 11403264000 1510400 13428645152 13701313312 13190974752 +17 22 42 12176588800 1510400 14264363168 14536557728 14027511968 +18 16 42 12949913600 1305600 15100731424 15320330784 14863880224 +19 16 42 13618380800 1305600 15836089248 16055855008 15599238048 +20 22 42 14286848000 1510400 16562518432 16834712992 16324848032 +21 22 42 15060172800 1510400 17398108448 17670303008 17160438048 +22 22 42 15833497600 1510400 18230654624 18502849184 17994264224 +23 22 42 16606822400 1510400 19071581728 19343609888 18834730528 +24 22 42 17380147200 1510400 19906595872 20178790432 19669744672 +25 22 42 18153472000 1510400 20745913248 21017941408 20509062048 +26 22 42 18926796800 1510400 21580517664 21852712224 21343666464 +27 16 42 19700121600 1305600 22420899488 22641138848 22184048288 +28 22 42 20368588800 1510400 23146983072 23419011232 22910131872 +29 16 42 21141913600 1305600 23983658528 24203424288 23746807328 +30 16 42 21810380800 1305600 24713110944 24932876704 24476720544 +31 22 42 22478848000 1510400 25449180448 25721375008 25212329248 +32 22 42 23252172800 1510400 26279648032 26551842592 26042796832 +33 22 42 24025497600 1510400 27114892448 27387087008 26878041248 +34 22 42 24798822400 1510400 27955807264 28228001824 27718956064 +35 22 42 25572147200 1510400 28793160608 29065355168 28556309408 +36 22 42 26345472000 1510400 29623794592 29896462752 29386943392 +37 29 42 27118796800 1177600 30459512608 30646510368 30222661408 +38 22 42 27721728000 1510400 31125320864 31397515424 30888469664 +39 22 42 28495052800 1510400 31966247968 32238442528 31729396768 +40 22 42 29268377600 1510400 32794219552 33066414112 32557368352 +41 22 42 30041702400 1510400 33628823968 33901018528 33391972768 +42 22 42 30815027200 1510400 34464068384 34736736544 34227217184 +43 22 42 31588352000 1510400 35305090208 35577118368 35068239008 +44 22 42 32361676800 1510400 36135557792 36408225952 35898706592 +45 22 42 33135001600 1510400 36976946208 37249140768 36740095008 +46 22 42 33908326400 1510400 37813148064 38085342624 37576296864 +47 22 42 34681651200 1510400 38654454048 38926648608 38417602848 diff --git a/engine/strata/tests/data/native_experts/iq3_s.txt b/engine/strata/tests/data/native_experts/iq3_s.txt new file mode 100644 index 00000000..85164ba2 --- /dev/null +++ b/engine/strata/tests/data/native_experts/iq3_s.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 50292326400; absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf, or in the named shard beside it) +0 18 20 0 2176000 1386491904 1711166464 913711104 +1 22 42 1114112000 1510400 2340958080 2613152640 2104106880 +2 22 20 1887436800 1971200 3491172096 3763417856 3018391296 +3 22 20 2896691200 1971200 4573970560 4846165120 4101189760 +4 22 20 3905945600 1971200 5652709504 5925377664 5179928704 +5 22 20 4915200000 1971200 6738352640 7010547200 6265571840 +6 22 20 5924454400 1971200 7819193216 8091861376 7346412416 +7 18 20 6933708800 2176000 8905667840 9230291200 8432887040 +8 22 42 8047820800 1510400 9848737024 10120931584 9611885824 +9 22 20 8821145600 1971200 10929646720 11201892480 10456865920 +10 22 42 9830400000 1510400 11779255296 12051501056 11542404096 +11 22 20 10603724800 1971200 12866495360 13138741120 12393714560 +12 18 42 11612979200 1715200 13701750144 14026847104 13464898944 +13 22 42 12491161600 1510400 14649780480 14922026240 14412929280 +14 18 20 13264486400 2176000 15736711296 16061334656 15263930496 +15 22 20 14378598400 1971200 16923842560 17196510720 16451061760 +16 18 20 15387852800 2176000 17998457344 18323131904 17525676544 +17 21 20 16501964800 2329600 19192385920 19556330880 18719605120 +18 18 20 17694720000 2176000 20460359936 20785239296 19987579136 +19 22 20 18808832000 1971200 21654710400 21927378560 21181929600 +20 18 42 19818086400 1715200 22498415744 22823039104 22261564544 +21 21 42 20696268800 1868800 23456363520 23820359680 23219512320 +22 18 20 21653094400 2176000 24722740096 25047837056 24249959296 +23 22 20 22767206400 1971200 25919315200 26191765760 25446534400 +24 22 20 23776460800 1971200 26998514944 27270709504 26525734144 +25 21 20 24785715200 2329600 28087739520 28451684480 27614958720 +26 22 20 25978470400 1971200 29357200896 29629869056 28884420096 +27 21 20 26987724800 2329600 30447303040 30811248000 29974522240 +28 21 20 28180480000 2329600 31709491584 32073910144 31236710784 +29 21 20 29373235200 2329600 32979426560 33343627520 32506645760 +30 18 42 30565990400 1715200 34012167296 34336790656 33775316096 +31 18 20 31444172800 2176000 35212497920 35537121280 34739717120 +32 22 20 32558284800 1971200 36394210304 36666878464 35921429504 +33 18 20 33567539200 2176000 37476126080 37800749440 37003345280 +34 22 20 34681651200 1971200 38661975296 38934221056 38189194496 +35 21 20 35690905600 2329600 39757704320 40121649280 39284923520 +36 22 42 36883660800 1510400 40780381824 41053049984 40543530624 +37 18 20 37656985600 2176000 41866242560 42191339520 41393461760 +38 18 20 38771097600 2176000 43055227776 43379902336 42582446976 +39 22 20 39885209600 1971200 44255558400 44527804160 43782777600 +40 21 20 40894464000 2329600 45334348544 45698549504 44861567744 +41 18 20 42087219200 2176000 46596260480 46920935040 46123479680 +42 18 20 43201331200 2176000 47782160896 48107257856 47309380096 +43 18 20 44315443200 2176000 48982913920 49308010880 48510133120 +44 21 20 45429555200 2329600 50159869824 50523865984 49687089024 +45 21 20 46622310400 2329600 51424864000 51788860160 50952083200 +46 18 20 47815065600 2176000 52692287616 53016962176 52219506816 +47 23 20 48929177600 2662400 53891822080 54341015040 53418222080 diff --git a/engine/strata/tests/data/native_experts/iq3_xxs.txt b/engine/strata/tests/data/native_experts/iq3_xxs.txt new file mode 100644 index 00000000..42f0ed50 --- /dev/null +++ b/engine/strata/tests/data/native_experts/iq3_xxs.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 42912972800; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf) +0 17 20 0 1868800 1227833216 1473813376 755052416 +1 16 42 956825600 1305600 2016152832 2235918592 1779301632 +2 17 20 1625292800 1868800 3045972608 3292003968 2573191808 +3 16 42 2582118400 1305600 3839355392 4059172352 3602964992 +4 17 20 3250585600 1868800 4806683136 5052663296 4334363136 +5 17 42 4207411200 1408000 5596436352 5842416512 5359585152 +6 16 42 4928307200 1305600 6379748608 6599514368 6143358208 +7 16 42 5596774400 1305600 7121247872 7340847232 6884396672 +8 21 42 6265241600 1868800 7846857856 8210636416 7610006656 +9 17 42 7222067200 1408000 8873971712 9120003072 8637120512 +10 17 42 7942963200 1408000 9669920128 9915733888 9433068928 +11 16 42 8663859200 1305600 10465942272 10685759232 10229091072 +12 22 42 9332326400 1510400 11190582016 11462610176 10954191616 +13 16 42 10105651200 1305600 12031522432 12251121792 11795132032 +14 17 42 10774118400 1408000 12768096768 13014332928 12531706368 +15 22 42 11495014400 1510400 13563906432 13836152192 13327055232 +16 16 42 12268339200 1305600 14398521216 14618338176 14161670016 +17 22 42 12936806400 1510400 15134954752 15407149312 14898103552 +18 21 42 13710131200 1868800 15976688768 16340467328 15739837568 +19 17 42 14666956800 1408000 17010020352 17256000512 16773629952 +20 21 42 15387852800 1868800 17787815936 18151812096 17551425536 +21 22 42 16344678400 1510400 18811338112 19083532672 18574486912 +22 21 42 17118003200 1868800 19652089088 20016034048 19415237888 +23 21 42 18074828800 1868800 20682407552 21046352512 20445556352 +24 21 42 19031654400 1868800 21704611456 22068390016 21467760256 +25 17 42 19988480000 1408000 22734674432 22980654592 22497823232 +26 22 42 20709376000 1510400 23524471168 23796716928 23287619968 +27 16 42 21482700800 1305600 24379793152 24599558912 24142941952 +28 21 20 22151168000 2329600 25345879296 25709657856 24873098496 +29 22 20 23343923200 1971200 26610479232 26882673792 26137698432 +30 21 20 24353177600 2329600 27695226368 28059171328 27222445568 +31 16 20 25545932800 1766400 28974200192 29193965952 28501419392 +32 21 20 26450329600 2329600 29937050496 30301046656 29464269696 +33 21 42 27643084800 1868800 30959753472 31323698432 30722902272 +34 21 20 28599910400 2329600 32230185088 32594181248 31757404288 +35 18 20 29792665600 2176000 33501048832 33825672192 33028268032 +36 18 42 30906777600 1715200 34444591616 34769048576 34207740416 +37 21 20 31784960000 2329600 35626780032 35990776192 35153999232 +38 22 20 32977715200 1971200 36892498688 37164526848 36419717888 +39 17 20 33986969600 1868800 37987587712 38233567872 37514806912 +40 22 42 34943795200 1510400 38771773056 39043967616 38534921856 +41 18 42 35717120000 1715200 39610924032 39935598592 39374072832 +42 22 20 36595302400 1971200 40796033408 41068061568 40323252608 +43 21 20 37604556800 2329600 41891114752 42254893312 41418333952 +44 18 20 38797312000 2176000 43148423936 43472880896 42675643136 +45 18 42 39911424000 1715200 44098627712 44423724672 43861776512 +46 22 20 40789606400 1971200 45285101568 45557296128 44812320768 +47 18 20 41798860800 2176000 46363501952 46688125312 45890721152 diff --git a/engine/strata/tests/data/native_experts/q2_0.txt b/engine/strata/tests/data/native_experts/q2_0.txt new file mode 100644 index 00000000..7b2cbd4e --- /dev/null +++ b/engine/strata/tests/data/native_experts/q2_0.txt @@ -0,0 +1,49 @@ +# strata native experts v2: layer gu_type d_type offset blob_bytes gate_off up_off down_off (n_expert 512, total 33973862400; the last three are absolute offsets in Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf) +0 42 42 0 1382400 994197792 1233624352 757141792 +1 42 42 707788800 1382400 1766860448 2005877408 1530470048 +2 42 42 1415577600 1382400 2558049824 2797476384 2321198624 +3 42 42 2123366400 1382400 3325351328 3564368288 3088500128 +4 42 42 2831155200 1382400 4087571872 4326588832 3851181472 +5 42 42 3538944000 1382400 4853325088 5092342048 4616473888 +6 42 42 4246732800 1382400 5619500704 5858517664 5383110304 +7 42 42 4954521600 1382400 6384631328 6623648288 6148240928 +8 42 42 5662310400 1382400 7144855072 7383872032 6907799072 +9 42 42 6370099200 1382400 7903921568 8143348128 7667531168 +10 42 42 7077888000 1382400 8666152224 8905169184 8429301024 +11 42 42 7785676800 1382400 9441479328 9680905888 9205088928 +12 42 42 8493465600 1382400 10199355552 10438615712 9962965152 +13 42 42 9201254400 1382400 10964891168 11204368928 10728500768 +14 42 42 9909043200 1382400 11732659104 11971919264 11494988704 +15 42 42 10616832000 1382400 12510902048 12749919008 12273846048 +16 42 42 11324620800 1382400 13268829472 13508089632 13031978272 +17 42 42 12032409600 1382400 14035560608 14274577568 13798709408 +18 42 42 12740198400 1382400 14801313824 15040330784 14564462624 +19 42 42 13447987200 1382400 15573612448 15812629408 15336761248 +20 42 42 14155776000 1382400 16333413792 16572673952 16097023392 +21 42 42 14863564800 1382400 17099410208 17338427168 16862559008 +22 42 42 15571353600 1382400 17865654944 18104671904 17629264544 +23 42 42 16279142400 1382400 18638086688 18877564448 18401235488 +24 42 42 16986931200 1382400 19401894432 19641154592 19164838432 +25 42 42 17694720000 1382400 20168095648 20407112608 19931705248 +26 42 42 18402508800 1382400 20937573664 21176590624 20700722464 +27 42 42 19110297600 1382400 21715358368 21954618528 21478967968 +28 42 42 19818086400 1382400 22475620512 22715520672 22238769312 +29 42 42 20525875200 1382400 23242704928 23481721888 23005648928 +30 42 42 21233664000 1382400 24010902944 24250163104 23774512544 +31 42 42 21941452800 1382400 24790715168 25030192928 24553863968 +32 42 42 22649241600 1382400 25553857312 25792874272 25317006112 +33 42 42 23357030400 1382400 26319610528 26558870688 26083220128 +34 42 42 24064819200 1382400 27088512544 27327990304 26851661344 +35 42 42 24772608000 1382400 27864292768 28103309728 27627902368 +36 42 42 25480396800 1382400 28626756512 28866234272 28390366112 +37 42 42 26188185600 1382400 29397609248 29637035808 29160553248 +38 42 42 26895974400 1382400 30166895264 30406321824 29930044064 +39 42 42 27603763200 1382400 30946134048 31185394208 30709282848 +40 42 42 28311552000 1382400 31708403232 31947880992 31471552032 +41 42 42 29019340800 1382400 32478833568 32718093728 32241982368 +42 42 42 29727129600 1382400 33249046304 33488063264 33012195104 +43 42 42 30434918400 1382400 34028407968 34267424928 33791556768 +44 42 42 31142707200 1382400 34791498912 35030759072 34554647712 +45 42 42 31850496000 1382400 35567241248 35806501408 35330185248 +46 42 42 32558284800 1382400 36338232224 36577914784 36101381024 +47 42 42 33266073600 1382400 37117686048 37356946208 36880015648 diff --git a/engine/strata/tests/data/native_experts/swift-iq2_xs.txt b/engine/strata/tests/data/native_experts/swift-iq2_xs.txt new file mode 100644 index 00000000..0da3e8f9 --- /dev/null +++ b/engine/strata/tests/data/native_experts/swift-iq2_xs.txt @@ -0,0 +1,49 @@ +# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] (n_expert 512, total 35454976000; absolute offsets in Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00001-of-00002.gguf, or in the named shard beside it) +0 22 42 0 1510400 29757220608 30031875328 29520369408 +1 16 42 773324800 1305600 30594451584 30817317504 30357600384 +2 22 42 1441792000 1510400 31394803200 31669624320 31157952000 +3 22 42 2215116800 1510400 32237578624 32512399744 31999908224 +4 16 42 2988441600 1305600 33069241728 33291634048 32832390528 +5 22 42 3656908800 1510400 33801615104 34076436224 33564763904 +6 22 42 4430233600 1510400 34640622720 34915443840 34404232320 +7 22 42 5203558400 1510400 35484094464 35759389184 35247704064 +8 29 42 5976883200 1177600 36317828608 36507452928 36080977408 +9 16 42 6579814400 1305600 36985651584 37207877504 36747981184 +10 16 42 7248281600 1305600 37719456000 37941848320 37482604800 +11 16 42 7916748800 1305600 38457145984 38679538304 38220755584 +12 22 42 8585216000 1510400 39186022528 39461317248 38949171328 +13 29 42 9358540800 1177600 237726720 427184640 56320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +14 16 42 9961472000 1305600 905216896 1127609216 667546496 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +15 22 42 10629939200 1510400 1647947520 1922602240 1411096320 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +16 22 42 11403264000 1510400 2482334464 2757629184 2244664064 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +17 22 42 12176588800 1510400 3320679040 3595500160 3083827840 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +18 16 42 12949913600 1305600 4159673856 4381899776 3922822656 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +19 16 42 13618380800 1305600 4897658240 5120050560 4660807040 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +20 22 42 14286848000 1510400 5626713984 5901535104 5389043584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +21 22 42 15060172800 1510400 6464930560 6739751680 6227260160 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +22 22 42 15833497600 1510400 7300103296 7574924416 7063712896 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +23 22 42 16606822400 1510400 8143656960 8418311680 7906805760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +24 22 42 17380147200 1510400 8981297664 9256118784 8744446464 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +25 22 42 18153472000 1510400 9823241600 10097896320 9586390400 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +26 22 42 18926796800 1510400 10660472576 10935293696 10423621376 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +27 16 42 19700121600 1305600 11503480960 11726346880 11266629760 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +28 22 42 20368588800 1510400 12232191104 12506845824 11995339904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +29 16 42 21141913600 1305600 13071493120 13293885440 12834641920 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +30 16 42 21810380800 1305600 13803572096 14025964416 13567181696 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +31 22 42 22478848000 1510400 14542268160 14817089280 14305416960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +32 22 42 23252172800 1510400 15375362304 15650183424 15138511104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +33 22 42 24025497600 1510400 16213233280 16488054400 15976382080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +34 22 42 24798822400 1510400 17056774656 17331595776 16819923456 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +35 22 42 25572147200 1510400 17896754560 18171575680 17659903360 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +36 22 42 26345472000 1510400 18730015104 19005309824 18493163904 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +37 29 42 27118796800 1177600 19568359680 19757984000 19331508480 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +38 22 42 27721728000 1510400 20236794496 20511615616 19999943296 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +39 22 42 28495052800 1510400 21080348160 21355169280 20843496960 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +40 22 42 29268377600 1510400 21910946304 22185767424 21674095104 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +41 22 42 30041702400 1510400 22748177280 23022998400 22511326080 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +42 22 42 30815027200 1510400 23586048256 23861342976 23349197056 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +43 22 42 31588352000 1510400 24429696640 24704351360 24192845440 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +44 22 42 32361676800 1510400 25262790784 25538085504 25025939584 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +45 22 42 33135001600 1510400 26106805760 26381626880 25869954560 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +46 22 42 33908326400 1510400 26945634176 27220455296 26708782976 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf +47 22 42 34681651200 1510400 27789566720 28064387840 27552715520 Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS-00002-of-00002.gguf diff --git a/engine/strata/tests/hip/expert_cache_staging.cpp b/engine/strata/tests/hip/expert_cache_staging.cpp new file mode 100644 index 00000000..a276da1f --- /dev/null +++ b/engine/strata/tests/hip/expert_cache_staging.cpp @@ -0,0 +1,34 @@ +#include "strata/core/expert_cache.hpp" +#include +#include + +int main() { + strata::core::ExpertCache cache; + std::string err; + auto check = [&](bool ok) { + if (!ok) std::fprintf(stderr, "%s\n", err.c_str()); + return ok; + }; + // open_sized first allocates byte slots, then grows to the largest expert. + // Exercise that growth and repeated reuse with distinct pageable payloads. + for (int reopen = 0; reopen < 2; ++reopen) { + if (!check(cache.open_sized({4096, 8192, 16384}, 1, 3, err))) return 1; + for (int round = 0; round < 8; ++round) { + for (int slot = 0; slot < 3; ++slot) { + std::vector payload((size_t) 4096 << slot); + for (size_t i = 0; i < payload.size(); ++i) + payload[i] = (uint8_t) (i * 17 + round * 11 + slot + reopen); + if (!check(cache.fill_slot_blocking(slot, payload.data(), err, payload.size())) || + !check(cache.verify_slot(slot, payload.data(), err, payload.size()))) return 1; + } + } + if (cache.fill_slot_blocking(0, nullptr, err)) return 1; + cache.close(); + } + if (!check(cache.open(2, 1, 2, 1024, err))) return 1; + std::vector payload(1024, 73); + if (!check(cache.fill_slot_blocking(1, payload.data(), err)) || + !check(cache.verify_slot(1, payload.data(), err))) return 1; + std::puts("HIP expert staging: variable slots, repeated payloads, close/reopen passed"); + return 0; +} diff --git a/engine/strata/tests/hip/handoff.cpp b/engine/strata/tests/hip/handoff.cpp new file mode 100644 index 00000000..5d358bf6 --- /dev/null +++ b/engine/strata/tests/hip/handoff.cpp @@ -0,0 +1,122 @@ +// Real asynchronous CPU/GPU handoff and graph replay, including changing payloads. +#include +#include "strata/kernels/elementwise.hpp" +#include +#include +#include +#include +#include +#define CHECK(x) do {auto e=(x);if(e!=hipSuccess){std::fprintf(stderr,"%s: %s\n",#x,hipGetErrorString(e));return 2;}} while(0) +int main(){ + constexpr int N=4096, rounds=100; + float *host=nullptr,*mapped=nullptr,*device=nullptr; + uint32_t *flag=nullptr,*seq=nullptr,*dflag=nullptr,*dseq=nullptr; + CHECK(hipHostMalloc((void**)&host,N*4,hipHostMallocMapped)); + CHECK(hipHostMalloc((void**)&flag,4,hipHostMallocMapped)); + CHECK(hipHostMalloc((void**)&seq,4,hipHostMallocMapped)); + CHECK(hipHostGetDevicePointer((void**)&mapped,host,0)); + CHECK(hipHostGetDevicePointer((void**)&dflag,flag,0)); + CHECK(hipHostGetDevicePointer((void**)&dseq,seq,0)); + CHECK(hipMalloc((void**)&device,N*4)); + hipStream_t stream;CHECK(hipStreamCreateWithFlags(&stream,hipStreamNonBlocking)); + hipGraph_t graph;hipGraphExec_t exec; + *flag=0;*seq=1; + CHECK(hipStreamBeginCapture(stream,hipStreamCaptureModeThreadLocal)); + strata::kernels::doorbell_wait(dflag,dseq,(void*)stream); + strata::kernels::copy_from_mapped(device,mapped,N,(void*)stream); + strata::kernels::scale_inplace(device,N,2.0f,(void*)stream); + CHECK(hipStreamEndCapture(stream,&graph));CHECK(hipGraphInstantiateWithFlags(&exec,graph,0)); + std::vector got(N); + for(int r=1;r<=rounds;r++){ + *seq=r; + CHECK(hipGraphLaunch(exec,stream)); + // Producer deliberately arrives after the GPU consumer; a missing wait must fail. + std::this_thread::sleep_for(std::chrono::microseconds(50+(r%17)*10)); + for(int i=0;i copy_route_ids(10);std::vector copy_route_weights(10); + CHECK(hipStreamBeginCapture(stream,hipStreamCaptureModeThreadLocal)); + CHECK(hipMemcpyAsync(mapped_copy_out,device,N*4,hipMemcpyDeviceToDevice,stream)); + CHECK(hipMemcpyAsync(mapped_copy_ids,copy_ids_device,10*4,hipMemcpyDeviceToDevice,stream)); + CHECK(hipMemcpyAsync(mapped_copy_weights,copy_weights_device,10*4,hipMemcpyDeviceToDevice,stream)); + strata::kernels::doorbell_ring(device_copy_seq,(void*)stream); + CHECK(hipStreamEndCapture(stream,&graph));CHECK(hipGraphInstantiateWithFlags(&exec,graph,0)); + for(int r=1;r<=rounds;r++){ + for(int i=0;ideadline){std::fprintf(stderr,"separate copy/ring timeout\n");return 10;} + std::this_thread::yield(); + } + for(int i=0;i ids_src(10);std::vector ws(10); + *flag=0; + CHECK(hipStreamBeginCapture(stream,hipStreamCaptureModeThreadLocal)); + strata::kernels::doorbell_publish(device,gi,gw,N,10,dpublished,dids,dweights,dflag,(void*)stream); + CHECK(hipStreamEndCapture(stream,&graph));CHECK(hipGraphInstantiateWithFlags(&exec,graph,0)); + for(int r=1;r<=rounds;r++){ + for(int i=0;ideadline){std::fprintf(stderr,"publish timeout\n");return 7;} + std::this_thread::yield(); + } + for(int i=0;i +#include "strata/hip_compat/intrinsics.hpp" + +#include +#include +#include + +#define CHECK(call) \ + do { \ + const hipError_t error = (call); \ + if (error != hipSuccess) { \ + std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \ + return 2; \ + } \ + } while (0) + +namespace { + +constexpr int kLanes = 32; +constexpr int kIntegerResults = 7; + +__global__ void intrinsic_probe(int* integer_results, float* float_shuffle, double* double_shuffle, + unsigned* ballot, const uint32_t* dot_inputs) { + const int lane = static_cast(threadIdx.x); + constexpr unsigned mask = 0xffffffffu; + const uint32_t a = 0x80ff017fu; + const uint32_t b = 0x0203fe81u; + + integer_results[lane * kIntegerResults + 0] = __dp4a(static_cast(a), static_cast(b), 7); + integer_results[lane * kIntegerResults + 1] = __dp4a(0x7f7f7f7f, 0x7f7f7f7f, 0x7fffffff); + integer_results[lane * kIntegerResults + 2] = __vsub4(0x00ff0102, 0x01010103); + integer_results[lane * kIntegerResults + 3] = __vsub4(0x00000000, 0x01020304); + integer_results[lane * kIntegerResults + 4] = __vsubss4(0x807f0080, 0x017f0180); + integer_results[lane * kIntegerResults + 5] = __vcmpne4(0x00ff0102, 0x01010103); + integer_results[lane * kIntegerResults + 6] = + __dp4a(static_cast(dot_inputs[lane * 2]), static_cast(dot_inputs[lane * 2 + 1]), + 0x7fffffff - lane); + + float_shuffle[lane * 4 + 0] = __shfl_xor_sync(mask, static_cast(lane), 1); + float_shuffle[lane * 4 + 1] = static_cast(__shfl_down_sync(mask, lane, 4, 8)); + float_shuffle[lane * 4 + 2] = static_cast(__shfl_up_sync(mask, lane, 1)); + float_shuffle[lane * 4 + 3] = static_cast(__shfl_sync(mask, lane, 0)); + double_shuffle[lane] = __shfl_xor_sync(mask, static_cast(lane) + 0.25, 1); + + const unsigned hit = __ballot_sync(mask, (lane & 1) == 0); + if (lane == 0) { + *ballot = hit; + __nanosleep(100); + } +} + +// The byte-lane intrinsics over many operands: __byte_perm with selector bits it ignores (bit 3 of each nibble and +// the upper half), since the i-quant table lookups pass data-dependent selectors; the packed subtracts and compare +// on every sign and overflow combination (the compare's second operand keeps two lanes of the first). +constexpr int kPermCases = 1024; +constexpr int kPermResults = 4; +__global__ void byte_perm_probe(const uint32_t* inputs, uint32_t* results) { + const int i = static_cast(blockIdx.x * blockDim.x + threadIdx.x); + if (i >= kPermCases) return; + const uint32_t x = inputs[3 * i], y = inputs[3 * i + 1], s = inputs[3 * i + 2]; + results[kPermResults * i + 0] = __byte_perm(x, y, s); + results[kPermResults * i + 1] = static_cast(__vsub4(static_cast(x), static_cast(y))); + results[kPermResults * i + 2] = static_cast(__vsubss4(static_cast(x), static_cast(y))); + results[kPermResults * i + 3] = + static_cast(__vcmpne4(static_cast(x), static_cast(x ^ (s & 0xff00ff00u)))); +} + +uint32_t byte_perm_reference(uint32_t x, uint32_t y, uint32_t s) { + const uint64_t pair = (static_cast(y) << 32) | x; + uint32_t out = 0; + for (int i = 0; i < 4; ++i) out |= static_cast((pair >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i); + return out; +} + +int signed_byte(uint32_t word, int lane) { + const unsigned value = (word >> (lane * 8)) & 0xffu; + return value < 0x80u ? static_cast(value) : static_cast(value) - 0x100; +} + +int dp4a_reference(uint32_t a, uint32_t b, int c) { + int64_t sum = c; + for (int lane = 0; lane < 4; ++lane) sum += signed_byte(a, lane) * signed_byte(b, lane); + return static_cast(static_cast(sum)); +} + +uint32_t byte_sub_reference(uint32_t a, uint32_t b) { + uint32_t out = 0; + for (int lane = 0; lane < 4; ++lane) + out |= ((((a >> (lane * 8)) & 0xffu) - ((b >> (lane * 8)) & 0xffu)) & 0xffu) << (lane * 8); + return out; +} + +uint32_t signed_saturating_sub_reference(uint32_t a, uint32_t b) { + uint32_t out = 0; + for (int lane = 0; lane < 4; ++lane) { + int value = signed_byte(a, lane) - signed_byte(b, lane); + if (value < -128) value = -128; + if (value > 127) value = 127; + out |= (static_cast(value) & 0xffu) << (lane * 8); + } + return out; +} + +uint32_t not_equal_reference(uint32_t a, uint32_t b) { + uint32_t out = 0; + for (int lane = 0; lane < 4; ++lane) + if (((a >> (lane * 8)) & 0xffu) != ((b >> (lane * 8)) & 0xffu)) out |= 0xffu << (lane * 8); + return out; +} + +} // namespace + +int main() { + int device = 0; + CHECK(hipGetDevice(&device)); + hipDeviceProp_t properties{}; + CHECK(hipGetDeviceProperties(&properties, device)); + if (properties.warpSize != kLanes) { + std::fprintf(stderr, "expected wave32, got wave%d\n", properties.warpSize); + return 1; + } + + int* device_integers = nullptr; + float* device_float_shuffle = nullptr; + double* device_double_shuffle = nullptr; + unsigned* device_ballot = nullptr; + uint32_t* device_dot_inputs = nullptr; + CHECK(hipMalloc(reinterpret_cast(&device_integers), kLanes * kIntegerResults * sizeof(int))); + CHECK(hipMalloc(reinterpret_cast(&device_float_shuffle), kLanes * 4 * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_double_shuffle), kLanes * sizeof(double))); + CHECK(hipMalloc(reinterpret_cast(&device_ballot), sizeof(unsigned))); + CHECK(hipMalloc(reinterpret_cast(&device_dot_inputs), kLanes * 2 * sizeof(uint32_t))); + + uint32_t dot_inputs[kLanes * 2]{}; + for (int lane = 0; lane < kLanes; ++lane) { + dot_inputs[lane * 2] = 0x80ff017fu ^ (0x01010101u * static_cast(lane)); + dot_inputs[lane * 2 + 1] = 0x0203fe81u + (0x11111111u * static_cast(lane)); + } + CHECK(hipMemcpy(device_dot_inputs, dot_inputs, sizeof(dot_inputs), hipMemcpyHostToDevice)); + + hipLaunchKernelGGL(intrinsic_probe, dim3(1), dim3(kLanes), 0, 0, + device_integers, device_float_shuffle, device_double_shuffle, device_ballot, device_dot_inputs); + CHECK(hipDeviceSynchronize()); + + int integers[kLanes * kIntegerResults]{}; + float float_shuffle[kLanes * 4]{}; + double double_shuffle[kLanes]{}; + unsigned ballot = 0; + CHECK(hipMemcpy(integers, device_integers, sizeof(integers), hipMemcpyDeviceToHost)); + CHECK(hipMemcpy(float_shuffle, device_float_shuffle, sizeof(float_shuffle), hipMemcpyDeviceToHost)); + CHECK(hipMemcpy(double_shuffle, device_double_shuffle, sizeof(double_shuffle), hipMemcpyDeviceToHost)); + CHECK(hipMemcpy(&ballot, device_ballot, sizeof(ballot), hipMemcpyDeviceToHost)); + + constexpr uint32_t a = 0x80ff017fu, b = 0x0203fe81u; + const uint32_t expected_integer[kIntegerResults - 1] = { + static_cast(dp4a_reference(a, b, 7)), + static_cast(dp4a_reference(0x7f7f7f7fu, 0x7f7f7f7fu, std::numeric_limits::max())), + byte_sub_reference(0x00ff0102u, 0x01010103u), + byte_sub_reference(0x00000000u, 0x01020304u), + signed_saturating_sub_reference(0x807f0080u, 0x017f0180u), + not_equal_reference(0x00ff0102u, 0x01010103u), + }; + bool ok = ballot == 0x55555555u; + for (int lane = 0; lane < kLanes; ++lane) { + for (int i = 0; i < kIntegerResults - 1; ++i) + ok = ok && static_cast(integers[lane * kIntegerResults + i]) == expected_integer[i]; + ok = ok && static_cast(integers[lane * kIntegerResults + kIntegerResults - 1]) == + static_cast(dp4a_reference(dot_inputs[lane * 2], dot_inputs[lane * 2 + 1], + 0x7fffffff - lane)); + ok = ok && float_shuffle[lane * 4 + 0] == static_cast(lane ^ 1); + const int down = lane % 8 < 4 ? lane + 4 : lane; + ok = ok && float_shuffle[lane * 4 + 1] == static_cast(down); + ok = ok && float_shuffle[lane * 4 + 2] == static_cast(lane == 0 ? 0 : lane - 1); + ok = ok && float_shuffle[lane * 4 + 3] == 0.0f; + ok = ok && double_shuffle[lane] == static_cast(lane ^ 1) + 0.25; + } + + uint32_t perm_inputs[kPermCases * 3]{}; + uint32_t state = 0x9e3779b9u; + for (uint32_t& v : perm_inputs) { + state ^= state << 13; state ^= state >> 17; state ^= state << 5; + v = state; + } + uint32_t* device_perm_inputs = nullptr; + uint32_t* device_perm_results = nullptr; + CHECK(hipMalloc(reinterpret_cast(&device_perm_inputs), sizeof(perm_inputs))); + CHECK(hipMalloc(reinterpret_cast(&device_perm_results), kPermCases * kPermResults * sizeof(uint32_t))); + CHECK(hipMemcpy(device_perm_inputs, perm_inputs, sizeof(perm_inputs), hipMemcpyHostToDevice)); + hipLaunchKernelGGL(byte_perm_probe, dim3(kPermCases / 256), dim3(256), 0, 0, device_perm_inputs, device_perm_results); + CHECK(hipDeviceSynchronize()); + uint32_t perm_results[kPermCases * kPermResults]{}; + CHECK(hipMemcpy(perm_results, device_perm_results, sizeof(perm_results), hipMemcpyDeviceToHost)); + for (int i = 0; i < kPermCases; ++i) { + const uint32_t x = perm_inputs[3 * i], y = perm_inputs[3 * i + 1], s = perm_inputs[3 * i + 2]; + const uint32_t* r = perm_results + kPermResults * i; + ok = ok && r[0] == byte_perm_reference(x, y, s); + ok = ok && r[1] == byte_sub_reference(x, y); + ok = ok && r[2] == signed_saturating_sub_reference(x, y); + ok = ok && r[3] == not_equal_reference(x, x ^ (s & 0xff00ff00u)); + } + CHECK(hipFree(device_perm_results)); + CHECK(hipFree(device_perm_inputs)); + + CHECK(hipFree(device_ballot)); + CHECK(hipFree(device_dot_inputs)); + CHECK(hipFree(device_double_shuffle)); + CHECK(hipFree(device_float_shuffle)); + CHECK(hipFree(device_integers)); + if (!ok) { + std::fprintf(stderr, "HIP intrinsic parity failed (ballot 0x%08x)\n", ballot); + return 1; + } + std::puts("HIP intrinsics parity OK: dynamic signed dot4/overflow, byte permute, packed integer boundaries, wave32 shuffles, ballot and sleep"); + return 0; +} diff --git a/engine/strata/tests/hip/mapped_alias.cpp b/engine/strata/tests/hip/mapped_alias.cpp new file mode 100644 index 00000000..0507bb87 --- /dev/null +++ b/engine/strata/tests/hip/mapped_alias.cpp @@ -0,0 +1,108 @@ +// Is a hipHostGetDevicePointer alias usable on this stack? (#325) +// +// tests/hip/handoff.cpp fails on gfx1201/Windows with "separate copy/ring timeout": it does a +// hipMemcpyAsync(..., hipMemcpyDeviceToDevice) into a hipHostGetDevicePointer alias, then waits for +// a doorbell that copy should have published. This test pins down the properties that decide it. +// +// On Linux the alias is a device address of the pinned host memory, a D2D copy lands, the host sees +// it, and a kernel reads it. On Windows (#325, RX 9070 XT) the runtime hands back the HOST pointer +// itself (unified addressing; this test prints both addresses), and a D2D copy into it does not +// publish - hip_handoff's timeout there. The engine itself runs on Windows (the reporter's serving +// run gave correct answers), so kernels reading mapped memory through that address work; only the +// copy-engine path does not. src/core/native_head.cpp keeps the token embedding in VRAM when the +// alias is refused outright. +// +// Reporting, not gating: a Windows host is EXPECTED to fail some checks below, so this test exits 0 +// whenever it ran at all, and 77 (skipped) without a device. When the alias IS the host pointer the +// D2D copy is not attempted (it may fault rather than report); the kernel read is, since that is +// what the engine relies on. + +#include "strata/kernels/elementwise.hpp" + +#include + +#include +#include + +namespace { + +int not_held = 0; + +void report(const char* what, bool holds) { + std::printf(" %-44s %s\n", what, holds ? "holds" : "DOES NOT HOLD"); + if (!holds) ++not_held; +} + +// A kernel reads `n` floats through `alias` into VRAM; the result is copied back and compared. +bool kernel_reads(const float* alias, const std::vector& want) { + const int64_t n = (int64_t) want.size(); + float* out = nullptr; + if (hipMalloc(reinterpret_cast(&out), want.size() * sizeof(float)) != hipSuccess) return false; + strata::kernels::copy_from_mapped(out, alias, n, nullptr); + std::vector got(want.size(), -1.0f); + const bool ran = hipDeviceSynchronize() == hipSuccess && + hipMemcpy(got.data(), out, want.size() * sizeof(float), hipMemcpyDeviceToHost) == hipSuccess; + hipFree(out); + hipGetLastError(); + return ran && got == want; +} + +} // namespace + +int main() { + int runtime = 0; + if (hipRuntimeGetVersion(&runtime) != hipSuccess) return 1; + int count = 0; + if (hipGetDeviceCount(&count) != hipSuccess || count < 1) { + std::printf("no HIP device\n"); + return 77; // ctest "skipped" + } + std::printf("HIP runtime %d, %d device(s)\n", runtime, count); + + const int64_t n = 4096; // enough elements for copy_from_mapped's float4 path + const size_t bytes = size_t(n) * sizeof(float); + std::vector pattern(size_t(n), 0.0f); + for (int64_t i = 0; i < n; ++i) pattern[size_t(i)] = float(i + 1); + + float* host = nullptr; + if (hipHostMalloc(reinterpret_cast(&host), bytes, hipHostMallocMapped) != hipSuccess) return 1; + void* alias = nullptr; + if (hipHostGetDevicePointer(&alias, host, 0) != hipSuccess || alias == nullptr) { + std::printf("hipHostGetDevicePointer failed: native_head.cpp keeps the embedding in VRAM here\n"); + hipGetLastError(); + hipHostFree(host); + return 0; + } + const bool distinct = alias != reinterpret_cast(host); + std::printf("\n host %p\n alias %p\n -> %s\n\n", static_cast(host), alias, + distinct ? "a distinct device address" : "the host pointer itself (unified addressing)"); + report("the alias is a distinct device address", distinct); + + // What the engine relies on: a kernel reading mapped host memory through the alias. + for (int64_t i = 0; i < n; ++i) host[i] = pattern[size_t(i)]; + report("a kernel reads the alias correctly", kernel_reads(reinterpret_cast(alias), pattern)); + + // What tests/hip/handoff.cpp attempts: a DeviceToDevice copy INTO the alias, seen by the host. + if (distinct) { + float* device = nullptr; + std::vector twice(pattern); + for (float& v : twice) v *= 2.0f; + if (hipMalloc(reinterpret_cast(&device), bytes) == hipSuccess && + hipMemcpy(device, twice.data(), bytes, hipMemcpyHostToDevice) == hipSuccess) { + const hipError_t copy = hipMemcpy(alias, device, bytes, hipMemcpyDeviceToDevice); + report("a D2D copy into the alias succeeds", copy == hipSuccess); + bool seen = hipDeviceSynchronize() == hipSuccess; + for (int64_t i = 0; seen && i < n; ++i) seen = host[i] == twice[size_t(i)]; + report("the host sees a D2D copy into the alias", seen); + } + if (device) hipFree(device); + hipGetLastError(); + } else { + std::printf(" the D2D copy into the alias is not attempted: with alias == host it may fault rather than\n" + " report (tests/hip/handoff's timeout on Windows)\n"); + } + + std::printf("\n%d check(s) did not hold (a Windows host is expected to fail some)\n", not_held); + hipHostFree(host); + return 0; +} diff --git a/engine/strata/tests/hip/native_qsa_score.cpp b/engine/strata/tests/hip/native_qsa_score.cpp new file mode 100644 index 00000000..6d60eb06 --- /dev/null +++ b/engine/strata/tests/hip/native_qsa_score.cpp @@ -0,0 +1,95 @@ +// Device parity for the scalar HIP implementation of the optional native QSA scorer. +#include +#include "strata/kernels/native_qsa_score.hpp" + +#include +#include +#include + +#define CHECK(call) \ + do { \ + const hipError_t error = (call); \ + if (error != hipSuccess) { \ + std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \ + return 2; \ + } \ + } while (0) + +int main() { + using namespace strata::kernels; + constexpr int kDim = 128, kHeads = 4, kBlock = 4; + constexpr int kMaxCells = 8, kMaxBlocks = 3, kCells = 7; + const QsaShapes shapes = qsa_real_shapes(); + + std::vector pooled(kMaxBlocks * kDim), query(kHeads * kDim), bias(kMaxBlocks), + scores(kMaxCells, -123.0f), expected(kMaxCells, -123.0f); + const float head_sign[kHeads] = {1.0f, -1.0f, 1.0f, -1.0f}; + for (int row = 0; row < kMaxBlocks; ++row) + for (int d = 0; d < kDim; ++d) + pooled[row * kDim + d] = static_cast(row + 1) * (1.0f + static_cast(d % 7) / 8.0f) / 128.0f; + for (int head = 0; head < kHeads; ++head) + for (int d = 0; d < kDim; ++d) + query[head * kDim + d] = head_sign[head] * (1.0f + static_cast((head + d) % 5) / 16.0f) / 16.0f; + for (int row = 0; row < kMaxBlocks; ++row) bias[row] = (static_cast(row) - 1.0f) / 8.0f; + + int32_t step[kStepCount] = {kCells - 1, kCells, kCells / kBlock, static_cast(kCells)}; + bool saw_positive_head = false, saw_negative_head = false; + for (int row = 0; row <= step[kStepNBid]; ++row) { + float sum = 0.0f; + for (int head = 0; head < kHeads; ++head) { + float dot = 0.0f; + for (int d = 0; d < kDim; ++d) + dot = std::fma(pooled[row * kDim + d], query[head * kDim + d], dot); + saw_positive_head = saw_positive_head || dot > 0.0f; + saw_negative_head = saw_negative_head || dot < 0.0f; + sum = sum + (dot > 0.0f ? dot : 0.0f); + } + sum = sum + bias[row]; + if (row == step[kStepNBid] && kCells % kBlock != 0) sum = sum + 1.0e9f; + const int lo = row * kBlock; + const int hi = (row + 1) * kBlock < kCells ? (row + 1) * kBlock : kCells; + for (int cell = lo; cell < hi; ++cell) expected[cell] = sum; + } + if (!saw_positive_head || !saw_negative_head) { + std::fprintf(stderr, "fixture did not exercise both positive and negative head scores\n"); + return 1; + } + + float *device_pooled = nullptr, *device_query = nullptr, *device_bias = nullptr, *device_scores = nullptr; + int32_t* device_step = nullptr; + CHECK(hipMalloc(reinterpret_cast(&device_pooled), pooled.size() * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_query), query.size() * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_bias), bias.size() * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_scores), scores.size() * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_step), sizeof(step))); + CHECK(hipMemcpy(device_pooled, pooled.data(), pooled.size() * sizeof(float), hipMemcpyHostToDevice)); + CHECK(hipMemcpy(device_query, query.data(), query.size() * sizeof(float), hipMemcpyHostToDevice)); + CHECK(hipMemcpy(device_bias, bias.data(), bias.size() * sizeof(float), hipMemcpyHostToDevice)); + CHECK(hipMemcpy(device_scores, scores.data(), scores.size() * sizeof(float), hipMemcpyHostToDevice)); + CHECK(hipMemcpy(device_step, step, sizeof(step), hipMemcpyHostToDevice)); + + hipStream_t stream; + CHECK(hipStreamCreate(&stream)); + native_qsa_score(device_pooled, device_query, device_bias, shapes, device_step, kMaxBlocks, kMaxCells, + device_scores, static_cast(stream)); + CHECK(hipStreamSynchronize(stream)); + CHECK(hipMemcpy(scores.data(), device_scores, scores.size() * sizeof(float), hipMemcpyDeviceToHost)); + + bool ok = true; + for (int cell = 0; cell < kMaxCells; ++cell) { + if (scores[cell] != expected[cell]) { + std::fprintf(stderr, "score[%d] got %.9g, expected %.9g\n", cell, scores[cell], expected[cell]); + ok = false; + } + } + + CHECK(hipStreamDestroy(stream)); + CHECK(hipFree(device_step)); + CHECK(hipFree(device_scores)); + CHECK(hipFree(device_bias)); + CHECK(hipFree(device_query)); + CHECK(hipFree(device_pooled)); + if (!ok) return 1; + std::puts("native QSA HIP scalar parity OK: FMA order, per-head ReLU, bias, partial tail and padding"); + return 0; +} diff --git a/engine/strata/tests/hip/ple_iq4.cpp b/engine/strata/tests/hip/ple_iq4.cpp new file mode 100644 index 00000000..7215e21b --- /dev/null +++ b/engine/strata/tests/hip/ple_iq4.cpp @@ -0,0 +1,202 @@ +// Real PLE IQ3_XXS/IQ4_XS matrix parity: ggml CPU dequantization versus HIP native MMVQ. +// Usage: hip_ple_iq4 [expected-type-id] +#include + +#include "ggml.h" +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int kNIn = 2560; +constexpr int kNOut = 10240; +constexpr int kTypeIq3Xxs = 18; +constexpr int kTypeIq4Xs = 23; +constexpr int kReplayCount = 3; + +#define CHECK(call) \ + do { \ + const hipError_t error = (call); \ + if (error != hipSuccess) { \ + std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \ + return 2; \ + } \ + } while (0) + +struct Q8Reference { + std::vector dequantized; +}; + +Q8Reference quantize_q8_1_reference(const std::vector& x) { + Q8Reference result; + result.dequantized.resize(x.size()); + for (size_t offset = 0; offset < x.size(); offset += 32) { + float amax = 0.0f; + for (int i = 0; i < 32; ++i) amax = std::fmax(amax, std::fabs(x[offset + i])); + if (amax == 0.0f) { + std::fill(result.dequantized.begin() + offset, result.dequantized.begin() + offset + 32, 0.0f); + continue; + } + const float scale_f32 = amax / 127.0f; + const float scale_f16 = strata::kernels::f32_from_f16(strata::kernels::f16_from_f32(scale_f32)); + for (int i = 0; i < 32; ++i) { + const int q = static_cast(std::round(x[offset + i] / scale_f32)); + result.dequantized[offset + i] = static_cast(static_cast(q)) * scale_f16; + } + } + return result; +} + +struct Parity { + double rel_l1_q8 = 0.0; + double worst_terms_q8 = 0.0; + double rel_l1_f32 = 0.0; + double max_abs_q8 = 0.0; + bool finite = true; +}; + +Parity compare(const uint8_t* weights, size_t row_bytes, const ggml_type_traits* traits, + const std::vector& x, const std::vector& x_q8, + const std::vector& actual) { + std::vector row(kNIn); + double q8_error = 0.0, q8_magnitude = 0.0; + double f32_error = 0.0, f32_magnitude = 0.0; + Parity result; + for (int r = 0; r < kNOut; ++r) { + traits->to_float(weights + static_cast(r) * row_bytes, row.data(), kNIn); + double expected_q8 = 0.0, terms_q8 = 0.0, expected_f32 = 0.0; + for (int i = 0; i < kNIn; ++i) { + const double term_q8 = static_cast(row[i]) * x_q8[i]; + const double term_f32 = static_cast(row[i]) * x[i]; + expected_q8 += term_q8; + terms_q8 += std::fabs(term_q8); + expected_f32 += term_f32; + } + const double got = actual[r]; + if (!std::isfinite(got) || !std::isfinite(expected_q8) || !std::isfinite(expected_f32)) result.finite = false; + q8_error += std::fabs(got - expected_q8); + q8_magnitude += std::fabs(expected_q8); + f32_error += std::fabs(got - expected_f32); + f32_magnitude += std::fabs(expected_f32); + result.max_abs_q8 = std::fmax(result.max_abs_q8, std::fabs(got - expected_q8)); + result.worst_terms_q8 = std::fmax(result.worst_terms_q8, + std::fabs(got - expected_q8) / std::fmax(terms_q8, 1e-30)); + } + result.rel_l1_q8 = q8_error / std::fmax(q8_magnitude, 1e-30); + result.rel_l1_f32 = f32_error / std::fmax(f32_magnitude, 1e-30); + return result; +} + +std::vector make_input(uint32_t seed) { + std::mt19937 rng(seed); + std::normal_distribution normal(0.0f, 0.6f); + std::vector x(kNIn); + for (int i = 0; i < kNIn; ++i) + x[i] = normal(rng) + 0.1f * std::sin(static_cast(i) * 0.013f); + return x; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2 && argc != 3) { + std::fprintf(stderr, "usage: hip_ple_iq4 [expected-type-id]\n"); + return 2; + } + + try { + strata::GgufFile gguf(argv[1]); + const strata::TensorInfo* tensor = gguf.find("blk.1.ple_key.weight"); + if (!tensor || (tensor->type != kTypeIq3Xxs && tensor->type != kTypeIq4Xs) || tensor->shape.size() != 2 || + tensor->shape[0] != kNIn || tensor->shape[1] != kNOut) { + std::fprintf(stderr, "expected blk.1.ple_key.weight IQ3_XXS or IQ4_XS [2560,10240] in %s\n", argv[1]); + return 1; + } + if (argc == 3 && std::atoi(argv[2]) != static_cast(tensor->type)) { + std::fprintf(stderr, "requested GGML type %s but blk.1.ple_key.weight is type %u (%s)\n", + argv[2], tensor->type, tensor->type_name()); + return 1; + } + const auto* traits = ggml_get_type_traits(static_cast(tensor->type)); + if (!traits || !traits->to_float) { + std::fprintf(stderr, "ggml has no %s CPU dequantizer\n", tensor->type_name()); + return 1; + } + const uint8_t* host_weights = gguf.tensor_data(*tensor); + const size_t weight_bytes = strata::kernels::native_mmvq_weight_bytes(static_cast(tensor->type), kNIn, kNOut); + const size_t row_bytes = weight_bytes / kNOut; + const size_t expected_bytes_per_block = tensor->type == kTypeIq3Xxs ? 98 : 136; + if (weight_bytes != static_cast(tensor->elements()) / 256 * expected_bytes_per_block || + row_bytes != static_cast(kNIn / 256) * expected_bytes_per_block) { + std::fprintf(stderr, "unexpected %s storage geometry: %zu bytes, row %zu\n", + tensor->type_name(), weight_bytes, row_bytes); + return 1; + } + + uint8_t* device_weights = nullptr; + float* device_x = nullptr; + float* device_y = nullptr; + void* device_q8_1 = nullptr; + CHECK(hipMalloc(reinterpret_cast(&device_weights), weight_bytes)); + CHECK(hipMalloc(reinterpret_cast(&device_x), kNIn * sizeof(float))); + CHECK(hipMalloc(reinterpret_cast(&device_y), kNOut * sizeof(float))); + CHECK(hipMalloc(&device_q8_1, strata::kernels::native_q8_1_bytes(kNIn))); + CHECK(hipMemcpy(device_weights, host_weights, weight_bytes, hipMemcpyHostToDevice)); + + hipStream_t stream = nullptr; + CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + CHECK(hipStreamBeginCapture(stream, hipStreamCaptureModeThreadLocal)); + strata::kernels::native_quantize_q8_1(device_x, device_q8_1, kNIn, 1, static_cast(stream)); + strata::kernels::native_mmvq(static_cast(tensor->type), device_weights, device_q8_1, device_y, + kNIn, kNOut, 1, static_cast(stream)); + hipGraph_t graph = nullptr; + CHECK(hipStreamEndCapture(stream, &graph)); + hipGraphExec_t graph_exec = nullptr; + CHECK(hipGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0)); + + std::vector actual(kNOut); + bool ok = true; + for (int replay = 0; replay < kReplayCount; ++replay) { + const std::vector x = make_input(0x1572u + static_cast(replay)); + const Q8Reference q8 = quantize_q8_1_reference(x); + CHECK(hipMemcpyAsync(device_x, x.data(), x.size() * sizeof(float), hipMemcpyHostToDevice, stream)); + CHECK(hipGraphLaunch(graph_exec, stream)); + CHECK(hipMemcpyAsync(actual.data(), device_y, actual.size() * sizeof(float), hipMemcpyDeviceToHost, stream)); + CHECK(hipStreamSynchronize(stream)); + + const Parity parity = compare(host_weights, row_bytes, traits, x, q8.dequantized, actual); + const bool pass = parity.finite && parity.rel_l1_q8 <= 5e-5 && parity.worst_terms_q8 <= 1e-4 && + parity.rel_l1_f32 <= 3e-2; + std::printf("%s PLE graph replay %d/%d: q8-ref rel-L1 %.3e, worst terms %.3e, " + "original-f32 rel-L1 %.3e, max q8 abs %.3e %s\n", + tensor->type_name(), replay + 1, kReplayCount, parity.rel_l1_q8, parity.worst_terms_q8, + parity.rel_l1_f32, parity.max_abs_q8, pass ? "PASS" : "FAIL"); + ok = ok && pass; + } + + CHECK(hipGraphExecDestroy(graph_exec)); + CHECK(hipGraphDestroy(graph)); + CHECK(hipStreamDestroy(stream)); + CHECK(hipFree(device_q8_1)); + CHECK(hipFree(device_y)); + CHECK(hipFree(device_x)); + CHECK(hipFree(device_weights)); + if (!ok) return 1; + std::printf("PLE %s native MMVQ parity OK: real GGUF matrix, CPU dequant reference, %d graph replays\n", + tensor->type_name(), kReplayCount); + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "hip_ple_iq4: %s\n", error.what()); + return 1; + } +} diff --git a/engine/strata/tests/hip/prefill_hipblaslt_gemm.cpp b/engine/strata/tests/hip/prefill_hipblaslt_gemm.cpp new file mode 100644 index 00000000..4b9ed65d --- /dev/null +++ b/engine/strata/tests/hip/prefill_hipblaslt_gemm.cpp @@ -0,0 +1,197 @@ +// Opt-in HIP smoke test for the calibrated hipBLASLt prefill route; it needs STRATA_HIPBLASLT_TUNING (SKIP otherwise). +// It checks that the table loads for this device and hipBLASLt version, that the two rows it uses exist (bf16 +// N=48 K=2560 ldy=96 and f16 N=512 K=2560 ldy=512, T bucket 4096), and that Gemm's output matches hipBLASEx on those +// two rows. It does NOT check the other rows, and it does not check that hipBLASLt ran the table's solution: an id +// the library rejects falls back to hipBLASEx and the test still passes. Set STRATA_HIPBLASLT_VERBOSE=1 to read the +// "hipBLASLt summary launches=... fallbacks=..." line. +#include +#include +#include +#include +#include + +#include "strata/kernels/bf16_bits.hpp" +#include "strata/prefill/gemm.hpp" +#include "hipblaslt_tuning.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define HIP_CHECK(call) do { \ + const hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::fprintf(stderr, "HIP failure at %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(status_)); \ + std::exit(2); \ + } \ +} while (0) + +#define HIPBLAS_CHECK(call) do { \ + const hipblasStatus_t status_ = (call); \ + if (status_ != HIPBLAS_STATUS_SUCCESS) { \ + std::fprintf(stderr, "hipBLAS failure at %s:%d: %s: %d\n", __FILE__, __LINE__, #call, (int) status_); \ + std::exit(2); \ + } \ +} while (0) + +struct DeviceBuffer { + void* p = nullptr; + explicit DeviceBuffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~DeviceBuffer() { if (p) (void) hipFree(p); } + DeviceBuffer(const DeviceBuffer&) = delete; + DeviceBuffer& operator=(const DeviceBuffer&) = delete; +}; + +uint16_t encode(float value, bool bf16) { + if (bf16) return strata::kernels::bf16_from_f32(value); + const __half half = __float2half_rn(value); + uint16_t bits = 0; + std::memcpy(&bits, &half, sizeof(bits)); + return bits; +} + +bool run_case(strata::prefill::Gemm& gemm, hipblasHandle_t blas, hipStream_t stream, bool bf16, int t, int n, + int k, int ldy, int output_offset, float beta, uint32_t seed) { + std::mt19937 rng(seed); + std::uniform_real_distribution dist(-0.25f, 0.25f); + const size_t x_count = (size_t) t * k; + const size_t w_count = (size_t) n * k; + std::vector x(x_count), w(w_count); + for (auto& value : x) value = encode(dist(rng), bf16); + for (auto& value : w) value = encode(dist(rng), bf16); + + const size_t output_count = (size_t) output_offset + (size_t) t * ldy + 8; + std::vector initial(output_count, -777.25f); + for (int row = 0; row < t; ++row) { + for (int col = 0; col < n; ++col) { + initial[(size_t) output_offset + (size_t) row * ldy + col] = + (float) ((row * 17 + col * 3) % 29 - 14) * 0.03125f; + } + } + + DeviceBuffer dx(x_count * sizeof(uint16_t)); + DeviceBuffer dw(w_count * sizeof(uint16_t)); + DeviceBuffer dy(initial.size() * sizeof(float)); + DeviceBuffer dref(initial.size() * sizeof(float)); + HIP_CHECK(hipMemcpyAsync(dx.p, x.data(), x_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dw.p, w.data(), w_count * sizeof(uint16_t), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dy.p, initial.data(), initial.size() * sizeof(float), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipMemcpyAsync(dref.p, initial.data(), initial.size() * sizeof(float), hipMemcpyHostToDevice, stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + + const hipDataType type = bf16 ? HIP_R_16BF : HIP_R_16F; + const float alpha = 1.0f; + HIPBLAS_CHECK(hipblasGemmEx(blas, HIPBLAS_OP_T, HIPBLAS_OP_N, n, t, k, &alpha, dw.p, type, k, dx.p, type, k, + &beta, (float*) dref.p + output_offset, HIP_R_32F, ldy, HIPBLAS_COMPUTE_32F, + HIPBLAS_GEMM_DEFAULT)); + if (bf16) { + gemm.bf16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy, + beta); + } else { + gemm.f16((const uint16_t*) dx.p, (const uint16_t*) dw.p, (float*) dy.p + output_offset, t, n, k, ldy, + beta); + } + HIP_CHECK(hipStreamSynchronize(stream)); + + std::vector got(initial.size()), ref(initial.size()); + HIP_CHECK(hipMemcpy(got.data(), dy.p, got.size() * sizeof(float), hipMemcpyDeviceToHost)); + HIP_CHECK(hipMemcpy(ref.data(), dref.p, ref.size() * sizeof(float), hipMemcpyDeviceToHost)); + + std::vector active(initial.size(), 0); + double diff2 = 0.0, ref2 = 0.0, max_abs = 0.0; + for (int row = 0; row < t; ++row) { + for (int col = 0; col < n; ++col) { + const size_t index = (size_t) output_offset + (size_t) row * ldy + col; + active[index] = 1; + if (!std::isfinite(got[index]) || !std::isfinite(ref[index])) { + std::fprintf(stderr, "non-finite output dtype=%s T=%d N=%d K=%d beta=%.1f index=%zu\n", + bf16 ? "bf16" : "f16", t, n, k, beta, index); + return false; + } + const double delta = (double) got[index] - ref[index]; + diff2 += delta * delta; + ref2 += (double) ref[index] * ref[index]; + max_abs = std::max(max_abs, std::abs(delta)); + } + } + for (size_t i = 0; i < initial.size(); ++i) { + if (!active[i] && (got[i] != initial[i] || ref[i] != initial[i])) { + std::fprintf(stderr, "output touched padding/guard dtype=%s T=%d N=%d K=%d beta=%.1f index=%zu got=%.9g\n", + bf16 ? "bf16" : "f16", t, n, k, beta, i, got[i]); + return false; + } + } + const double relative_l2 = std::sqrt(diff2 / std::max(ref2, 1e-300)); + const bool passed = relative_l2 <= 1e-4 && max_abs <= 5e-3; + std::printf("case dtype=%s T=%d N=%d K=%d ldy=%d output_offset=%d beta=%.1f relative_l2=%.9g max_abs=%.9g %s\n", + bf16 ? "bf16" : "f16", t, n, k, ldy, output_offset, beta, relative_l2, max_abs, + passed ? "PASS" : "FAIL"); + return passed; +} + +int main() { + const char* tuning_path = std::getenv("STRATA_HIPBLASLT_TUNING"); + if (!tuning_path || !*tuning_path) { + std::fprintf(stderr, "SKIP: set STRATA_HIPBLASLT_TUNING to a tuning table for this GPU and hipBLASLt version\n"); + return 77; + } + + int device = 0; + HIP_CHECK(hipGetDevice(&device)); + hipDeviceProp_t properties{}; + HIP_CHECK(hipGetDeviceProperties(&properties, device)); + std::string arch(properties.gcnArchName); + const auto suffix = arch.find(':'); + if (suffix != std::string::npos) arch.resize(suffix); + hipblasLtHandle_t lt = nullptr; + HIPBLAS_CHECK(hipblasLtCreate(<)); + int version = 0; + HIPBLAS_CHECK(hipblasLtGetVersion(lt, &version)); + HIPBLAS_CHECK(hipblasLtDestroy(lt)); + + strata::prefill::hipblaslt::TuningTable table; + std::string error; + if (!table.load(tuning_path, arch, version, error)) { + std::fprintf(stderr, "tuning table rejected: %s\n", error.c_str()); + return 1; + } + if (!table.closest(strata::prefill::hipblaslt::InputType::bf16, 48, 2560, 96, 4096) || + !table.closest(strata::prefill::hipblaslt::InputType::f16, 512, 2560, 512, 4096)) { + std::fprintf(stderr, "tuning table lacks the rows this smoke test uses (bf16 N=48 K=2560 ldy=96, f16 N=512 K=2560 ldy=512)\n"); + return 1; + } + + hipStream_t stream = nullptr; + HIP_CHECK(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); + bool ok = true; + { + std::string init_error; + strata::prefill::Gemm gemm; + if (!gemm.init((void*) stream, 0, init_error)) { + std::fprintf(stderr, "Gemm init failed: %s\n", init_error.c_str()); + HIP_CHECK(hipStreamDestroy(stream)); + return 2; + } + hipblasHandle_t blas = nullptr; + HIPBLAS_CHECK(hipblasCreate(&blas)); + HIPBLAS_CHECK(hipblasSetStream(blas, stream)); + + // T=4096 is an exact calibrated bucket; T=37 resolves to the same T=4096 row (the closest bucket), validates the + // actual shape before launch, and tests a non-tile-multiple tail. So the four cases use two table rows. + ok &= run_case(gemm, blas, stream, true, 4096, 48, 2560, 96, 0, 0.0f, 101); + ok &= run_case(gemm, blas, stream, true, 37, 48, 2560, 96, 48, 1.0f, 102); + ok &= run_case(gemm, blas, stream, false, 4096, 512, 2560, 512, 0, 0.0f, 103); + ok &= run_case(gemm, blas, stream, false, 37, 512, 2560, 512, 7, 1.0f, 104); + HIPBLAS_CHECK(hipblasDestroy(blas)); + } + HIP_CHECK(hipStreamDestroy(stream)); + std::printf("smoke test: 4 cases on 2 of the table's %zu rows; %s\n", table.rows().size(), + ok ? "outputs match hipBLASEx (solution ids are not verified; see STRATA_HIPBLASLT_VERBOSE)" + : "FAILED"); + return ok ? 0 : 1; +} diff --git a/engine/strata/tests/hip/prefill_mmq_parity.cpp b/engine/strata/tests/hip/prefill_mmq_parity.cpp new file mode 100644 index 00000000..2fd7a0d7 --- /dev/null +++ b/engine/strata/tests/hip/prefill_mmq_parity.cpp @@ -0,0 +1,281 @@ +// Standalone diagnostic harness for strata-prefill's optional MMQ path. +// Keep this artifact outside the project source until it is reviewed and wired into a HIP test target. +// It compares GGML's MMQ result (with its intended q8_1 activation rounding) to a CPU FP32 product using +// GGML's own dequantizer for the exact same weight blocks. The tolerances screen layout/stride/bounds errors; +// they do not assert bitwise or FP16 parity. +#include "strata/prefill/moe_mmq.hpp" +#include "ggml.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using strata::prefill::mmq::Context; +using strata::prefill::mmq::Product; +using strata::prefill::mmq::matrix_bytes; +using strata::prefill::mmq::q8_bytes; +using strata::prefill::mmq::quantize; +using strata::prefill::mmq::supported; + +void hip_check(hipError_t e, const char * what) { + if (e != hipSuccess) throw std::runtime_error(std::string(what) + ": " + hipGetErrorString(e)); +} + +struct DeviceBuffer { + void * p = nullptr; + explicit DeviceBuffer(size_t n) { hip_check(hipMalloc(&p, n), "hipMalloc"); } + ~DeviceBuffer() { if (p) hipFree(p); } + DeviceBuffer(const DeviceBuffer &) = delete; + DeviceBuffer & operator=(const DeviceBuffer &) = delete; + template T * as() const { return static_cast(p); } +}; + +size_t row_bytes(ggml_type type, int64_t cols) { + return ggml_row_size(type, cols); +} + +std::vector decode_matrix(ggml_type type, const std::vector & q, int64_t rows, int64_t cols) { + const auto * tr = ggml_get_type_traits(type); + if (!tr || !tr->to_float) throw std::runtime_error("GGML type has no host dequantizer"); + const size_t rb = row_bytes(type, cols); + if (q.size() != (size_t) rows * rb) throw std::runtime_error("matrix byte count mismatch"); + std::vector out((size_t) rows * (size_t) cols); + for (int64_t r = 0; r < rows; ++r) { + tr->to_float(q.data() + (size_t) r * rb, out.data() + (size_t) r * (size_t) cols, cols); + } + return out; +} + +std::vector make_q2_matrix(int64_t rows, int64_t cols, int expert, int trial) { + const ggml_type type = GGML_TYPE_Q2_0; + const auto * tr = ggml_get_type_traits(type); + if (!tr || !tr->from_float_ref) throw std::runtime_error("Q2_0 host quantizer unavailable"); + const size_t rb = row_bytes(type, cols); + std::vector out((size_t) rows * rb); + std::vector row((size_t) cols); + for (int64_t r = 0; r < rows; ++r) { + for (int64_t k = 0; k < cols; ++k) { + const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50; + row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) + + 0.0015f * (float) code; + } + tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols); + } + return out; +} + +std::vector make_activations(int rows, int64_t cols, int trial) { + std::vector x((size_t) rows * (size_t) cols); + for (int r = 0; r < rows; ++r) { + for (int64_t k = 0; k < cols; ++k) { + x[(size_t) r * (size_t) cols + (size_t) k] = + 0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) + + 0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) + + 0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9); + } + } + // Exercise a complete all-zero row; its expected output is exactly zero even though Q8_1 rounding is enabled. + std::fill(x.end() - cols, x.end(), 0.0f); + return x; +} + +std::vector permutation(int rows, int shift, bool reverse) { + std::vector p((size_t) rows); + for (int i = 0; i < rows; ++i) { + p[(size_t) i] = reverse ? (int32_t) ((rows - 1 - i + shift) % rows) + : (int32_t) ((i + shift) % rows); + } + return p; +} + +std::vector make_bounds(const std::vector & counts) { + std::vector b(counts.size() + 1, 0); + for (size_t i = 0; i < counts.size(); ++i) b[i + 1] = b[i] + counts[i]; + return b; +} + +struct Metrics { double rel_l2 = 0, max_over_rms = 0, zero_row_max = 0, ref_rms = 0; }; + +Metrics run_product(Context & ctx, hipStream_t stream, const std::string & name, ggml_type type, + int64_t out_rows, int64_t cols, const std::vector> & expert_weights, + const std::vector & counts, const std::vector & x, + const std::vector & src_ids, const std::vector & dst_ids) { + const int rows = (int) src_ids.size(); + const int experts = (int) expert_weights.size(); + const std::vector bounds = make_bounds(counts); + if (!supported((int) type) || experts <= 0 || counts.size() != expert_weights.size() || + bounds.back() != rows || dst_ids.size() != (size_t) rows || x.size() != (size_t) rows * (size_t) cols) { + throw std::runtime_error(name + ": invalid test geometry"); + } + const size_t expert_bytes = matrix_bytes((int) type, out_rows, cols); + const size_t tail = 4096; // match the production group's zero guard after its last expert + std::vector w((size_t) experts * expert_bytes + tail, 0); + for (int e = 0; e < experts; ++e) { + if (expert_weights[(size_t) e].size() != expert_bytes) throw std::runtime_error(name + ": expert size mismatch"); + std::copy(expert_weights[(size_t) e].begin(), expert_weights[(size_t) e].end(), + w.begin() + (size_t) e * expert_bytes); + } + + DeviceBuffer dx(x.size() * sizeof(float)); + DeviceBuffer dsrc(src_ids.size() * sizeof(int32_t)); + DeviceBuffer ddst(dst_ids.size() * sizeof(int32_t)); + DeviceBuffer dbounds(bounds.size() * sizeof(int32_t)); + DeviceBuffer dw(w.size()); + DeviceBuffer dxq(q8_bytes(rows, cols)); + DeviceBuffer dy((size_t) rows * (size_t) out_rows * sizeof(float)); + hip_check(hipMemcpy(dx.p, x.data(), x.size() * sizeof(float), hipMemcpyHostToDevice), "copy x"); + hip_check(hipMemcpy(dsrc.p, src_ids.data(), src_ids.size() * sizeof(int32_t), hipMemcpyHostToDevice), "copy src ids"); + hip_check(hipMemcpy(ddst.p, dst_ids.data(), dst_ids.size() * sizeof(int32_t), hipMemcpyHostToDevice), "copy dst ids"); + hip_check(hipMemcpy(dbounds.p, bounds.data(), bounds.size() * sizeof(int32_t), hipMemcpyHostToDevice), "copy bounds"); + hip_check(hipMemcpy(dw.p, w.data(), w.size(), hipMemcpyHostToDevice), "copy weights and zero tail"); + hip_check(hipMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * sizeof(float)), "initialize output sentinel"); + + quantize(dx.as(), dsrc.as(), dxq.p, (int) type, cols, cols, rows, (void *) stream); + const int max_rows = *std::max_element(counts.begin(), counts.end()); + Product p; + p.w = dw.p; p.type = (int) type; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = expert_bytes; + p.n = experts; p.xq = dxq.p; p.bounds = dbounds.as(); p.ids = ddst.as(); + p.total_rows = rows; p.max_rows = max_rows; p.dst = dy.as(); p.ld_dst = out_rows; + ctx.run(p, (void *) stream); + hip_check(hipGetLastError(), "MMQ launch"); + hip_check(hipStreamSynchronize(stream), "MMQ synchronize"); + std::vector got((size_t) rows * (size_t) out_rows); + hip_check(hipMemcpy(got.data(), dy.p, got.size() * sizeof(float), hipMemcpyDeviceToHost), "copy output"); + + std::vector ref(got.size(), 0.0f); + double err2 = 0, ref2 = 0; + float max_abs = 0, zero_max = 0; + for (int e = 0; e < experts; ++e) { + const std::vector wd = decode_matrix(type, expert_weights[(size_t) e], out_rows, cols); + for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) { + const int src = src_ids[(size_t) r]; + const int dst = dst_ids[(size_t) r]; + const float * xr = x.data() + (size_t) src * (size_t) cols; + for (int64_t o = 0; o < out_rows; ++o) { + double acc = 0; + const float * wr = wd.data() + (size_t) o * (size_t) cols; + for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k]; + ref[(size_t) dst * (size_t) out_rows + (size_t) o] = (float) acc; + } + } + } + for (size_t i = 0; i < got.size(); ++i) { + if (!std::isfinite(got[i])) throw std::runtime_error(name + ": non-finite or unwritten MMQ output"); + const double d = (double) got[i] - ref[i]; + err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, (float) std::fabs(d)); + } + const double rms = std::sqrt(ref2 / (double) ref.size()); + for (int r = 0; r < rows; ++r) { + if (std::all_of(x.begin() + (size_t) src_ids[(size_t) r] * (size_t) cols, + x.begin() + ((size_t) src_ids[(size_t) r] + 1) * (size_t) cols, + [](float v) { return v == 0.0f; })) { + for (int64_t o = 0; o < out_rows; ++o) + zero_max = std::max(zero_max, std::fabs(got[(size_t) dst_ids[(size_t) r] * (size_t) out_rows + (size_t) o])); + } + } + Metrics m; + m.rel_l2 = rms > 0 ? std::sqrt(err2 / (double) ref.size()) / rms : std::sqrt(err2); + m.max_over_rms = rms > 0 ? max_abs / rms : max_abs; + m.zero_row_max = zero_max; m.ref_rms = rms; + std::cout << name << ": type=" << (int) type << " rows=" << rows << " experts=" << experts + << " ref_rms=" << m.ref_rms << " rel_l2=" << m.rel_l2 + << " max_abs/ref_rms=" << m.max_over_rms << " zero_row_max=" << m.zero_row_max << '\n'; + // Q8_1 rounding is expected. These deliberately broad limits catch wrong block order, row strides, ids, + // expert bounds, or stale output while allowing ordinary activation-quantization error. + if (m.rel_l2 > 0.04 || m.max_over_rms > 0.35 || m.zero_row_max > std::max(1e-5, 1e-4 * rms)) + throw std::runtime_error(name + ": parity screen failed"); + return m; +} + +std::vector> synthetic_q2(int experts, int64_t out_rows, int64_t cols, int trial) { + std::vector> w; + for (int e = 0; e < experts; ++e) w.push_back(make_q2_matrix(out_rows, cols, e, trial)); + return w; +} + +bool run_real_iq3_first_expert(Context & ctx, hipStream_t stream, const std::string & pack) { + std::ifstream meta(pack + "/native_experts.txt"); + if (!meta) throw std::runtime_error("cannot open native_experts.txt: " + pack); + int layer = -1, gt = -1, dt = -1; + uint64_t offset = 0, blob_bytes = 0; + std::string line; + bool found = false; + while (std::getline(meta, line)) { + if (line.empty() || line[0] == '#') continue; + std::istringstream ss(line); + if (ss >> layer >> gt >> dt >> offset >> blob_bytes && layer == 0) { found = true; break; } + } + if (!found) throw std::runtime_error("native metadata has no layer 0"); + if (gt != GGML_TYPE_IQ3_XXS || !supported(gt) || !supported(dt)) { + std::cout << "real-IQ3 first expert skipped: layer 0 types are " << gt << "/" << dt << '\n'; + return false; + } + std::ifstream file(pack + "/experts.bin", std::ios::binary); + if (!file) throw std::runtime_error("cannot open experts.bin: " + pack); + std::vector blob((size_t) blob_bytes); + file.seekg((std::streamoff) offset); + file.read((char *) blob.data(), (std::streamsize) blob.size()); + if (!file) throw std::runtime_error("short read of first native expert"); + + constexpr int64_t N = 2560, FF = 640; + const size_t gu_row = row_bytes((ggml_type) gt, N), d_row = row_bytes((ggml_type) dt, FF); + const size_t one_gu = (size_t) FF * gu_row, down_off = 2 * one_gu, one_down = (size_t) N * d_row; + if (down_off + one_down != blob.size()) throw std::runtime_error("native blob shape/offset mismatch"); + std::vector gu(blob.begin(), blob.begin() + (ptrdiff_t) down_off); + std::vector down(blob.begin() + (ptrdiff_t) down_off, blob.end()); + const int rows = 5; + const std::vector counts{rows}; + const auto src = permutation(rows, 2, false), dst = permutation(rows, 1, true); + run_product(ctx, stream, "real-first-IQ3_XXS-GU", (ggml_type) gt, 1280, N, {gu}, counts, + make_activations(rows, N, 71), src, dst); + run_product(ctx, stream, "real-first-down", (ggml_type) dt, N, FF, {down}, counts, + make_activations(rows, FF, 73), src, dst); + std::cout << "real first expert tested: layer=0 expert=0 blob_bytes=" << blob_bytes << '\n'; + return true; +} +} // namespace + +int main(int argc, char ** argv) { + try { + if (argc > 2) throw std::runtime_error("usage: mmq-parity-test [optional-native-pack-dir]"); + hip_check(hipSetDevice(0), "hipSetDevice"); + hipStream_t stream = nullptr; + hip_check(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking), "create stream"); + int failures = 0; + { + Context ctx; // reuse one MMQ context/pool across every pass below + const std::vector> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}}; + int trial = 0; + for (const auto & counts : batches) { + const int rows = std::accumulate(counts.begin(), counts.end(), 0); + const int n = (int) counts.size(); + const auto src = permutation(rows, trial + 1, false); + const auto dst = permutation(rows, trial + 2, true); + run_product(ctx, stream, "synthetic-Q2_0-GU-pass" + std::to_string(trial), GGML_TYPE_Q2_0, + 1280, 2560, synthetic_q2(n, 1280, 2560, trial), counts, + make_activations(rows, 2560, trial), src, dst); + run_product(ctx, stream, "synthetic-Q2_0-down-pass" + std::to_string(trial), GGML_TYPE_Q2_0, + 2560, 640, synthetic_q2(n, 2560, 640, trial + 9), counts, + make_activations(rows, 640, trial + 3), src, dst); + ++trial; + } + if (argc == 2) run_real_iq3_first_expert(ctx, stream, argv[1]); + } + hip_check(hipStreamSynchronize(stream), "final synchronize"); + hip_check(hipStreamDestroy(stream), "destroy stream"); + std::cout << "MMQ parity screen passed\n"; + return failures ? 1 : 0; + } catch (const std::exception & e) { + std::cerr << "MMQ parity screen failed: " << e.what() << '\n'; + return 1; + } +} diff --git a/engine/strata/tests/hip/prefill_native_batch.cpp b/engine/strata/tests/hip/prefill_native_batch.cpp new file mode 100644 index 00000000..b10cfe81 --- /dev/null +++ b/engine/strata/tests/hip/prefill_native_batch.cpp @@ -0,0 +1,293 @@ +// Focused parity for the opt-in native QSA append and native embedding gather +// selectively ported from q8atnight/Strata PR #108 +// (acd487233c0bbe2217a6881c5bb43f8a283b0de5). +#include +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/rope_scaling.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(call) do { \ + const cudaError_t e = (call); \ + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", #call, cudaGetErrorString(e)); return false; } \ +} while (0) + +namespace { +constexpr int IDX = 128; +constexpr int BLOCK = 4; +constexpr int EMB = 2560; +constexpr int IQ4_NL = 20; +constexpr float EPS = 1e-6f; +// the indexer's rope: plain (no scaling) over the base this test was written for +const strata::kernels::RopeScaling ROPE = [] { strata::kernels::RopeScaling r; r.freq_base = 10000.0; return r; }(); + +struct IndexState { + float *tail = nullptr, *dead = nullptr, *pooled = nullptr; + int32_t* block_pos = nullptr; +}; + +bool alloc_state(IndexState& s, int64_t max_cells) { + CHECK(cudaMalloc((void**) &s.tail, (BLOCK - 1) * IDX * sizeof(float))); + CHECK(cudaMalloc((void**) &s.dead, IDX * sizeof(float))); + CHECK(cudaMalloc((void**) &s.pooled, (size_t) (max_cells / BLOCK + 1) * IDX * sizeof(float))); + CHECK(cudaMalloc((void**) &s.block_pos, sizeof(int32_t))); + return true; +} +void free_state(IndexState& s) { + if (s.tail) cudaFree(s.tail); + if (s.dead) cudaFree(s.dead); + if (s.pooled) cudaFree(s.pooled); + if (s.block_pos) cudaFree(s.block_pos); + s = {}; +} +bool upload_state(const IndexState& s, int64_t max_cells) { + std::vector tail((BLOCK - 1) * IDX, 0.0f), dead(IDX, 0.0f); + std::vector pooled((size_t) (max_cells / BLOCK + 1) * IDX); + for (size_t i = 0; i < pooled.size(); ++i) pooled[i] = -0.125f * (float) (i + 1); + const int32_t block_pos = -1; + CHECK(cudaMemcpy(s.tail, tail.data(), tail.size() * sizeof(float), cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(s.dead, dead.data(), dead.size() * sizeof(float), cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(s.pooled, pooled.data(), pooled.size() * sizeof(float), cudaMemcpyHostToDevice)); + CHECK(cudaMemcpy(s.block_pos, &block_pos, sizeof(block_pos), cudaMemcpyHostToDevice)); + return true; +} + +bool qsa_case(cudaStream_t stream, int64_t max_cells, int64_t pos0, int64_t T, std::mt19937& rng) { + const size_t raw_n = (size_t) (pos0 + T) * IDX; + std::vector raw(raw_n), gamma(IDX); + std::uniform_real_distribution dist(-1.0f, 1.0f); + for (float& x : raw) x = dist(rng); + for (float& x : gamma) x = 0.5f + 0.5f * std::fabs(dist(rng)); + + float *raw_d = nullptr, *gamma_d = nullptr; + int32_t* pos_d = nullptr; + CHECK(cudaMalloc((void**) &raw_d, raw.size() * sizeof(float))); + CHECK(cudaMalloc((void**) &gamma_d, gamma.size() * sizeof(float))); + CHECK(cudaMalloc((void**) &pos_d, sizeof(int32_t))); + CHECK(cudaMemcpyAsync(raw_d, raw.data(), raw.size() * sizeof(float), cudaMemcpyHostToDevice, stream)); + CHECK(cudaMemcpyAsync(gamma_d, gamma.data(), gamma.size() * sizeof(float), cudaMemcpyHostToDevice, stream)); + + IndexState serial, batched; + if (!alloc_state(serial, max_cells) || !alloc_state(batched, max_cells)) return false; + if (!upload_state(serial, max_cells) || !upload_state(batched, max_cells)) return false; + + const auto shapes = strata::kernels::qsa_real_shapes(); + const strata::kernels::QsaIndexerBuffers sb{serial.tail, serial.dead, serial.pooled, serial.block_pos}; + const strata::kernels::QsaIndexerBuffers bb{batched.tail, batched.dead, batched.pooled, batched.block_pos}; + std::vector positions((size_t) (pos0 + T)); + for (size_t p = 0; p < positions.size(); ++p) positions[p] = (int32_t) p; + + // The reference is the original per-cell sequence. The candidate uses the + // same per-cell prefix, then replaces only this chunk with the two-launch API. + for (int64_t p = 0; p < pos0 + T; ++p) { + CHECK(cudaMemcpyAsync(pos_d, positions.data() + p, sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + strata::kernels::native_qsa_indexer_append(raw_d + p * IDX, pos_d, 0, gamma_d, EPS, sb, + shapes, max_cells, ROPE, stream); + if (p < pos0) { + CHECK(cudaMemcpyAsync(pos_d, positions.data() + p, sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + strata::kernels::native_qsa_indexer_append(raw_d + p * IDX, pos_d, 0, gamma_d, EPS, bb, + shapes, max_cells, ROPE, stream); + } + } + strata::kernels::native_qsa_indexer_append_batch(raw_d + pos0 * IDX, T, pos0, 0, gamma_d, EPS, + bb, shapes, max_cells, ROPE, stream); + CHECK(cudaStreamSynchronize(stream)); + + const size_t tail_n = (BLOCK - 1) * IDX, dead_n = IDX; + const size_t pooled_n = (size_t) (max_cells / BLOCK + 1) * IDX; + std::vector st(tail_n), bt(tail_n), sd(dead_n), bd(dead_n), sp(pooled_n), bp(pooled_n); + int32_t spos = 0, bpos = 0; + CHECK(cudaMemcpy(st.data(), serial.tail, tail_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(bt.data(), batched.tail, tail_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(sd.data(), serial.dead, dead_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(bd.data(), batched.dead, dead_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(sp.data(), serial.pooled, pooled_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(bp.data(), batched.pooled, pooled_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(&spos, serial.block_pos, sizeof(spos), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(&bpos, batched.block_pos, sizeof(bpos), cudaMemcpyDeviceToHost)); + const bool same = std::memcmp(st.data(), bt.data(), tail_n * sizeof(float)) == 0 && + std::memcmp(sd.data(), bd.data(), dead_n * sizeof(float)) == 0 && + std::memcmp(sp.data(), bp.data(), pooled_n * sizeof(float)) == 0 && spos == bpos; + if (!same) std::fprintf(stderr, "QSA append parity mismatch max=%lld pos0=%lld T=%lld\n", + (long long) max_cells, (long long) pos0, (long long) T); + + free_state(serial); free_state(batched); + CHECK(cudaFree(raw_d)); CHECK(cudaFree(gamma_d)); CHECK(cudaFree(pos_d)); + return same; +} + +bool qsa_chunks_case(cudaStream_t stream, std::mt19937& rng, int64_t max_cells, + int64_t first, int64_t second) { + const int64_t total = first + second; + std::vector raw((size_t) total * IDX), gamma(IDX); + std::uniform_real_distribution dist(-1.0f, 1.0f); + for (float& x : raw) x = dist(rng); + for (float& x : gamma) x = 0.5f + 0.5f * std::fabs(dist(rng)); + float *raw_d = nullptr, *gamma_d = nullptr; + int32_t* pos_d = nullptr; + CHECK(cudaMalloc((void**) &raw_d, raw.size() * sizeof(float))); + CHECK(cudaMalloc((void**) &gamma_d, gamma.size() * sizeof(float))); + CHECK(cudaMalloc((void**) &pos_d, sizeof(int32_t))); + CHECK(cudaMemcpyAsync(raw_d, raw.data(), raw.size() * sizeof(float), cudaMemcpyHostToDevice, stream)); + CHECK(cudaMemcpyAsync(gamma_d, gamma.data(), gamma.size() * sizeof(float), cudaMemcpyHostToDevice, stream)); + IndexState serial, chunked; + if (!alloc_state(serial, max_cells) || !alloc_state(chunked, max_cells)) return false; + if (!upload_state(serial, max_cells) || !upload_state(chunked, max_cells)) return false; + const auto shapes = strata::kernels::qsa_real_shapes(); + const strata::kernels::QsaIndexerBuffers sb{serial.tail, serial.dead, serial.pooled, serial.block_pos}; + const strata::kernels::QsaIndexerBuffers cb{chunked.tail, chunked.dead, chunked.pooled, chunked.block_pos}; + std::vector positions((size_t) total); + for (int i = 0; i < total; ++i) positions[(size_t) i] = i; + for (int p = 0; p < total; ++p) { + CHECK(cudaMemcpyAsync(pos_d, positions.data() + p, sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + strata::kernels::native_qsa_indexer_append(raw_d + (size_t) p * IDX, pos_d, 0, gamma_d, EPS, sb, + shapes, max_cells, ROPE, stream); + } + strata::kernels::native_qsa_indexer_append_batch(raw_d, first, 0, 0, gamma_d, EPS, cb, shapes, + max_cells, ROPE, stream); + strata::kernels::native_qsa_indexer_append_batch(raw_d + (size_t) first * IDX, second, first, 0, + gamma_d, EPS, cb, shapes, max_cells, ROPE, stream); + CHECK(cudaStreamSynchronize(stream)); + const size_t tail_n = (BLOCK - 1) * IDX, pooled_n = (size_t) (max_cells / BLOCK + 1) * IDX; + std::vector st(tail_n), ct(tail_n), sd(IDX), cd(IDX), sp(pooled_n), cp(pooled_n); + int32_t sbp = 0, cbp = 0; + CHECK(cudaMemcpy(st.data(), serial.tail, tail_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(ct.data(), chunked.tail, tail_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(sd.data(), serial.dead, IDX * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(cd.data(), chunked.dead, IDX * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(sp.data(), serial.pooled, pooled_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(cp.data(), chunked.pooled, pooled_n * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(&sbp, serial.block_pos, sizeof(sbp), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(&cbp, chunked.block_pos, sizeof(cbp), cudaMemcpyDeviceToHost)); + const bool same = std::memcmp(st.data(), ct.data(), tail_n * sizeof(float)) == 0 && + std::memcmp(sd.data(), cd.data(), IDX * sizeof(float)) == 0 && + std::memcmp(sp.data(), cp.data(), pooled_n * sizeof(float)) == 0 && sbp == cbp; + if (!same) std::fprintf(stderr, "QSA consecutive chunk parity mismatch %lld+%lld, capacity=%lld\n", + (long long) first, (long long) second, (long long) max_cells); + free_state(serial); free_state(chunked); + CHECK(cudaFree(raw_d)); CHECK(cudaFree(gamma_d)); CHECK(cudaFree(pos_d)); + return same; +} + +bool embed_case(cudaStream_t stream, int type, int64_t T) { + constexpr int vocab = 19; + const size_t row_bytes = strata::kernels::iq_row_bytes(type, EMB); + const size_t block_bytes = type == 20 ? 18 : 110; // IQ4_NL or IQ3_S GGML block layout + const size_t table_bytes = (size_t) vocab * row_bytes; + if (row_bytes == 0 || row_bytes % block_bytes != 0) { + std::fprintf(stderr, "bad test embedding row size for type=%d\n", type); + return false; + } + void* host_table = nullptr; + CHECK(cudaHostAlloc(&host_table, table_bytes, cudaHostAllocMapped | cudaHostAllocPortable)); + auto* table_bytes_u8 = (uint8_t*) host_table; + std::memset(table_bytes_u8, 0, table_bytes); + // Both test formats begin with a finite fp16 scale; the remaining packed code bits are all legal values. + for (size_t r = 0; r < (size_t) vocab; ++r) { + for (size_t b = 0; b < row_bytes; b += block_bytes) { + table_bytes_u8[r * row_bytes + b] = 0x00; + table_bytes_u8[r * row_bytes + b + 1] = 0x3c; + for (size_t q = b + 2; q < b + block_bytes; ++q) + table_bytes_u8[r * row_bytes + q] = (uint8_t) ((q * 37 + r * 19) & 0xff); + } + } + void* table_dev = nullptr; + CHECK(cudaHostGetDevicePointer(&table_dev, host_table, 0)); + + std::vector image_rows((size_t) T, 0); + std::vector token_values((size_t) T); + std::vector ids((size_t) T); + for (int64_t t = 0; t < T; ++t) { + if (t == 1 || t == 3) { + image_rows[(size_t) t] = 1; + token_values[(size_t) t] = t == 1 ? -1 : vocab + 11; // image placeholders must never be gathered + ids[(size_t) t] = 0; // safe row, overwritten below + } else { + token_values[(size_t) t] = (t % 3 == 0) ? 7 : (t % 5); // includes duplicate text IDs + if (token_values[(size_t) t] < 0 || token_values[(size_t) t] >= vocab || + token_values[(size_t) t] > INT32_MAX) { + std::fprintf(stderr, "test text token failed host-side validation\n"); + return false; + } + ids[(size_t) t] = (int32_t) token_values[(size_t) t]; + } + } + + float *batched = nullptr, *serial = nullptr; + int32_t* ids_d = nullptr; + CHECK(cudaMalloc((void**) &batched, (size_t) T * EMB * sizeof(float))); + CHECK(cudaMalloc((void**) &serial, (size_t) T * EMB * sizeof(float))); + CHECK(cudaMalloc((void**) &ids_d, (size_t) T * sizeof(int32_t))); + CHECK(cudaMemcpyAsync(ids_d, ids.data(), (size_t) T * sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + strata::kernels::iq_embed_rows(type, table_dev, row_bytes, ids_d, T, EMB, batched, stream); + for (int64_t t = 0; t < T; ++t) if (!image_rows[(size_t) t]) + strata::kernels::iq_dequant_f32(type, + (const uint8_t*) table_dev + (size_t) ids[(size_t) t] * row_bytes, EMB, serial + t * EMB, stream); + + std::vector image(EMB); + for (int i = 0; i < EMB; ++i) image[(size_t) i] = 0.001f * (float) (i - EMB / 2); + for (int64_t t = 0; t < T; ++t) if (image_rows[(size_t) t]) { + CHECK(cudaMemcpyAsync(batched + t * EMB, image.data(), EMB * sizeof(float), cudaMemcpyHostToDevice, stream)); + CHECK(cudaMemcpyAsync(serial + t * EMB, image.data(), EMB * sizeof(float), cudaMemcpyHostToDevice, stream)); + } + CHECK(cudaStreamSynchronize(stream)); + + constexpr int64_t rows_per_check = 64; + std::vector a((size_t) rows_per_check * EMB), b(a.size()); + bool same = true; + for (int64_t t0 = 0; t0 < T; t0 += rows_per_check) { + const int64_t rows = std::min(rows_per_check, T - t0); + const size_t count = (size_t) rows * EMB; + CHECK(cudaMemcpy(a.data(), batched + t0 * EMB, count * sizeof(float), cudaMemcpyDeviceToHost)); + CHECK(cudaMemcpy(b.data(), serial + t0 * EMB, count * sizeof(float), cudaMemcpyDeviceToHost)); + if (std::memcmp(a.data(), b.data(), count * sizeof(float)) != 0) { + size_t first = 0; + while (first < count && std::memcmp(&a[first], &b[first], sizeof(float)) == 0) ++first; + std::fprintf(stderr, "NativeEmbed batch parity mismatch type=%d T=%lld at element %lld: %.9g vs %.9g\n", + type, (long long) T, (long long) (t0 * EMB + first), + first < count ? a[first] : 0.0f, first < count ? b[first] : 0.0f); + same = false; + break; + } + } + if (T > 3 && (!image_rows[1] || !image_rows[3] || ids[1] != 0 || ids[3] != 0)) same = false; + if (!same) std::fprintf(stderr, "NativeEmbed image placeholder sanitization mismatch type=%d T=%lld\n", + type, (long long) T); + CHECK(cudaFree(batched)); CHECK(cudaFree(serial)); CHECK(cudaFree(ids_d)); + CHECK(cudaFreeHost(host_table)); + return same; +} + +} // namespace + +int main() { + std::mt19937 rng(0x50524631u); + cudaStream_t stream = nullptr; + const cudaError_t create = cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking); + if (create != cudaSuccess) { std::fprintf(stderr, "cudaStreamCreateWithFlags: %s\n", cudaGetErrorString(create)); return 2; } + bool ok = true; + // Covers every slot residue, partial and multiple block chunks, and the fixed-capacity tail. + const std::array starts = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; + const std::array lengths = {1, 2, 3, 7, 17}; + // (the batched append's contract is p0 + n <= max_cells: the prompt path never appends past the cache) + for (int64_t pos0 : starts) for (int64_t T : lengths) + if (pos0 + T <= 13) ok = qsa_case(stream, 13, pos0, T, rng) && ok; + ok = qsa_chunks_case(stream, rng, 33, 7, 17) && ok; + // Production-scale, non-block-aligned first chunk with a short continuation. + ok = qsa_chunks_case(stream, rng, 8210, 8193, 17) && ok; + for (int type : {20, 21}) for (int64_t T : {1, 2, 7, 17}) + ok = embed_case(stream, type, T) && ok; + ok = embed_case(stream, 21, 4096) && ok; + const cudaError_t destroy = cudaStreamDestroy(stream); + if (destroy != cudaSuccess) { std::fprintf(stderr, "cudaStreamDestroy: %s\n", cudaGetErrorString(destroy)); return 2; } + std::printf("Native prefill batch parity: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/engine/strata/tests/hip/router_fast.cpp b/engine/strata/tests/hip/router_fast.cpp new file mode 100644 index 00000000..d0db85e5 --- /dev/null +++ b/engine/strata/tests/hip/router_fast.cpp @@ -0,0 +1,101 @@ +// S6: the AMD fast router (router_top10's default on HIP for 64 < n_expert <= 512, k <= 32) against the portable +// kernel, BITWISE: ids and weights of 65,536 rows of 512 logits - normal rows, rows with many exact ties, near-ties, +// a wide spread (tiny probabilities), all-equal rows and rows with a NaN - plus the fast kernel forced onto its +// serial-sum path, and a 256-expert / k=8 geometry. Then the time per single-token call of each. +#include +#include "strata/kernels/router_top10.hpp" + +#include +#include +#include +#include +#include + +#define CHECK(call) \ + do { \ + const hipError_t error = (call); \ + if (error != hipSuccess) { \ + std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \ + return 2; \ + } \ + } while (0) + +namespace k = strata::kernels; + +static int compare(int n_expert, int topk, int rows, unsigned seed) { + std::mt19937 rng(seed); + std::normal_distribution nd(0.f, 2.f); + std::vector lg((size_t) rows * n_expert); + for (size_t i = 0; i < lg.size(); ++i) { + const size_t r = i / n_expert; + float x = nd(rng) * (r % 7 == 5 ? 40.0f : 1.0f); + if (r % 3 == 1) x = std::round(x * 4.0f) / 4.0f; + if (r % 3 == 2) x = std::round(x * 64.0f) / 64.0f; + if (r % 1000 == 999 && (i % n_expert) == 77) x = NAN; + if (r % 1000 == 998) x = 1.0f; + lg[i] = x; + } + const size_t out = (size_t) rows * topk; + float *d_l = nullptr, *d_w[3] = {}; + int* d_i[3] = {}; + CHECK(hipMalloc(&d_l, lg.size() * 4)); + CHECK(hipMemcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice)); + std::vector ids[3]; + std::vector w[3]; + for (int v = 0; v < 3; ++v) { + CHECK(hipMalloc(&d_w[v], out * 4)); + CHECK(hipMalloc(&d_i[v], out * 4)); + CHECK(hipMemset(d_w[v], 0x3c, out * 4)); // what an unwritten rank keeps (NaN rows) + CHECK(hipMemset(d_i[v], 0x11, out * 4)); + if (!k::router_top10_variant(d_l, rows, n_expert, topk, d_i[v], d_w[v], nullptr, v)) { + std::fprintf(stderr, "router_top10_variant %d refused\n", v); + return 2; + } + CHECK(hipDeviceSynchronize()); + ids[v].resize(out); + w[v].resize(out); + CHECK(hipMemcpy(ids[v].data(), d_i[v], out * 4, hipMemcpyDeviceToHost)); + CHECK(hipMemcpy(w[v].data(), d_w[v], out * 4, hipMemcpyDeviceToHost)); + } + int fails = 0; + for (int v = 1; v < 3; ++v) { + int bad = 0; + for (int r = 0; r < rows; ++r) + if (std::memcmp(&ids[0][(size_t) r * topk], &ids[v][(size_t) r * topk], topk * 4) || + std::memcmp(&w[0][(size_t) r * topk], &w[v][(size_t) r * topk], topk * 4)) { + if (bad < 3) + std::printf(" row %d differs: id0 %d/%d w0 %.9g/%.9g\n", r, ids[0][(size_t) r * topk], + ids[v][(size_t) r * topk], w[0][(size_t) r * topk], w[v][(size_t) r * topk]); + ++bad; + } + std::printf("%s %d experts, k %d, %d rows: %s vs the portable kernel: %d rows differ\n", bad ? "FAIL" : "PASS", + n_expert, topk, rows, v == 1 ? "fast kernel" : "fast kernel, serial path", bad); + fails += bad != 0; + } + // time: single-token calls back to back + hipEvent_t e0, e1; + CHECK(hipEventCreate(&e0)); + CHECK(hipEventCreate(&e1)); + for (int v = 0; v < 2; ++v) { + const int reps = 2000; + CHECK(hipEventRecord(e0)); + for (int i = 0; i < reps; ++i) + k::router_top10_variant(d_l + (size_t) (i % 64) * n_expert, 1, n_expert, topk, d_i[v], d_w[v], nullptr, v); + CHECK(hipEventRecord(e1)); + CHECK(hipEventSynchronize(e1)); + float ms = 0; + CHECK(hipEventElapsedTime(&ms, e0, e1)); + std::printf(" %s: %.2f us per single-token call\n", v ? "fast" : "portable", 1000.0f * ms / reps); + } + for (int v = 0; v < 3; ++v) { (void) hipFree(d_w[v]); (void) hipFree(d_i[v]); } + (void) hipFree(d_l); + return fails; +} + +int main() { + int fails = 0; + fails += compare(512, 10, 65536, 17); + fails += compare(256, 8, 8192, 5); + std::printf("FAILURES: %d\n", fails); + return fails ? 1 : 0; +} diff --git a/engine/strata/tests/platform/direct_file_async.cpp b/engine/strata/tests/platform/direct_file_async.cpp new file mode 100644 index 00000000..f046b316 --- /dev/null +++ b/engine/strata/tests/platform/direct_file_async.cpp @@ -0,0 +1,60 @@ +#include "strata/platform/direct_file.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +using strata::platform::DirectFile; +using strata::platform::Completion; +static void check(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); } +int main() { + char name[] = "/tmp/strata-direct-test-XXXXXX"; + int fd = mkstemp(name); + if (fd < 0) return 1; + close(fd); + void* memory = DirectFile::alloc_aligned(4096 * 18); + try { + check(memory != nullptr, "buffer allocation"); + { std::ofstream f(name, std::ios::binary); std::string bytes(4096 * 16 + 17, 'x'); f.write(bytes.data(), bytes.size()); } + DirectFile f; + std::string error; + setenv("STRATA_IO_THREADS", "4", 1); // the pool's size (out-of-range values are clamped to 1..64) + check(f.open(name, error), error.c_str()); + check(!f.submit(1, memory, 4096, 0, error), "unaligned request accepted"); + for (unsigned i = 0; i < 17; ++i) + check(f.submit(i * 4096, static_cast(memory) + i * 4096, 4096, i, error), error.c_str()); + std::vector seen(17); + unsigned count = 0; + while (count < 17) { + Completion c[17]; int n = f.wait(c, 17, 5000); + check(n > 0, "completion timeout"); + for (int i = 0; i < n; ++i) { + check(c[i].tag < 17 && !seen[c[i].tag], "wrong or repeated completion"); + seen[c[i].tag] = true; ++count; + check(c[i].ok && c[i].bytes == (c[i].tag == 16 ? 17u : 4096u), "incorrect full/EOF completion"); + check(static_cast(memory)[c[i].tag * 4096] == 'x', "read data mismatch"); + } + } + std::jthread waker([&] { f.wake(); }); + Completion c; check(f.wait(&c, 1, 5000) == 1 && c.tag == DirectFile::WAKE_TAG, "wake lost"); + waker.join(); + check(f.submit(0, memory, 4096, 99, error), error.c_str()); + f.close(); // Must drain outstanding buffer writes before returning. + std::memset(memory, 0, 4096); + check(f.open(name, error), error.c_str()); + check(f.wait(&c, 1, 0) == 0, "stale completion on reopen"); + check(f.submit(0, memory, 4096, 100, error), error.c_str()); + check(f.wait(&c, 1, 5000) == 1 && c.ok && c.tag == 100, "reopened read failed"); + f.close(); + DirectFile::free_aligned(memory); unlink(name); + std::cout << "direct_file_async: passed queued reads, short EOF, wake, close drain, reopen\n"; + return 0; + } catch (const std::exception& e) { + DirectFile::free_aligned(memory); unlink(name); + std::cerr << e.what() << '\n'; return 1; + } +} diff --git a/engine/strata/third_party/ggml/LICENSE b/engine/strata/third_party/ggml/LICENSE new file mode 100644 index 00000000..e7dca554 --- /dev/null +++ b/engine/strata/third_party/ggml/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/engine/strata/third_party/ggml/VERSION.txt b/engine/strata/third_party/ggml/VERSION.txt new file mode 100644 index 00000000..2fca1351 --- /dev/null +++ b/engine/strata/third_party/ggml/VERSION.txt @@ -0,0 +1 @@ +3cf03257f219afbe7334045ff7c6a06ac68c627d Sun Sep 20 16:08:11 2026 +0800 diff --git a/engine/strata/third_party/ggml/ggml-common.h b/engine/strata/third_party/ggml/ggml-common.h new file mode 100644 index 00000000..1dbbe326 --- /dev/null +++ b/engine/strata/third_party/ggml/ggml-common.h @@ -0,0 +1,1911 @@ +#ifndef GGML_COMMON_DECL + +#if defined(GGML_COMMON_DECL_C) +#include + +typedef uint16_t ggml_half; +typedef uint32_t ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_CPP) +#include + +typedef uint16_t ggml_half; +typedef uint32_t ggml_half2; + +// std-c++ allow anonymous unions but some compiler warn on it +#define GGML_COMMON_AGGR_U data +// std-c++ do not allow it. +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_METAL) +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_CUDA) +#if defined(GGML_COMMON_DECL_MUSA) +#include +#else +#include +#endif +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_HIP) +#include +#include + +typedef half ggml_half; +typedef half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#elif defined(GGML_COMMON_DECL_SYCL) +#include +#include + +typedef sycl::half ggml_half; +typedef sycl::half2 ggml_half2; + +#define GGML_COMMON_AGGR_U +#define GGML_COMMON_AGGR_S data + +#define GGML_COMMON_DECL +#endif + +#if defined(GGML_COMMON_DECL) + +#ifndef __cplusplus +#ifndef static_assert +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L) +#define static_assert(cond, msg) _Static_assert(cond, msg) +#else +#define static_assert(cond, msg) struct global_scope_noop_trick +#endif +#endif +#endif // __cplusplus + +// QK = number of values after dequantization +// QK_K = super-block size + +#define QK_K 256 +#define K_SCALE_SIZE 12 + +#if defined(GGML_COMMON_DECL_CUDA) || defined(GGML_COMMON_DECL_HIP) || defined(GGML_COMMON_DECL_SYCL) +// QR = QK / number of values before dequantization +// QI = number of 32 bit integers before dequantization + +#define QI1_0 (QK1_0 / 32) +#define QR1_0 1 + +#define QI2_0 (QK2_0 / 32) +#define QR2_0 1 + + +#define QI4_0 (QK4_0 / (4 * QR4_0)) +#define QR4_0 2 + +#define QI4_1 (QK4_1 / (4 * QR4_1)) +#define QR4_1 2 + +#define QI_MXFP4 (QK_MXFP4 / (4 * QR_MXFP4)) +#define QR_MXFP4 2 + +#define QI_NVFP4 (QK_NVFP4 / (4 * QR_NVFP4)) +#define QR_NVFP4 2 + +#define QI5_0 (QK5_0 / (4 * QR5_0)) +#define QR5_0 2 + +#define QI5_1 (QK5_1 / (4 * QR5_1)) +#define QR5_1 2 + +#define QI8_0 (QK8_0 / (4 * QR8_0)) +#define QR8_0 1 + +#define QI8_1 (QK8_1 / (4 * QR8_1)) +#define QR8_1 1 + +#define QI2_K (QK_K / (4*QR2_K)) +#define QR2_K 4 + +#define QI3_K (QK_K / (4*QR3_K)) +#define QR3_K 4 + +#define QI4_K (QK_K / (4*QR4_K)) +#define QR4_K 2 + +#define QI5_K (QK_K / (4*QR5_K)) +#define QR5_K 2 + +#define QI6_K (QK_K / (4*QR6_K)) +#define QR6_K 2 + +#define QI2_XXS (QK_K / (4*QR2_XXS)) +#define QR2_XXS 4 + +#define QI2_XS (QK_K / (4*QR2_XS)) +#define QR2_XS 4 + +#define QI2_S (QK_K / (4*QR2_S)) +#define QR2_S 4 + +#define QI3_XXS (QK_K / (4*QR3_XXS)) +#define QR3_XXS 4 + +#define QI3_XS (QK_K / (4*QR3_XS)) +#define QR3_XS 4 + +#define QI1_S (QK_K / (4*QR1_S)) +#define QR1_S 8 + +#define QI1_M (QK_K / (4*QR1_M)) +#define QR1_M 8 + +#define QI4_NL (QK4_NL / (4*QR4_NL)) +#define QR4_NL 2 + +#define QI4_XS (QK_K / (4*QR4_XS)) +#define QR4_XS 2 + +#define QI3_S (QK_K / (4*QR3_S)) +#define QR3_S 4 + +#endif // GGML_COMMON_DECL_CUDA || GGML_COMMON_DECL_HIP + +#ifdef _MSC_VER +#define GGML_EXTENSION +#else // _MSC_VER +#define GGML_EXTENSION __extension__ +#endif // _MSC_VER + +#define QK1_0 128 +typedef struct { + ggml_half d; // delta + uint8_t qs[QK1_0 / 8]; // bits / quants +} block_q1_0; +static_assert(sizeof(block_q1_0) == sizeof(ggml_half) + QK1_0 / 8, "wrong q1_0 block size/padding"); + +#define QK2_0 64 +typedef struct { + ggml_half d; // delta (scale) + uint8_t qs[QK2_0 / 4]; // 2 bits per element +} block_q2_0; +static_assert(sizeof(block_q2_0) == sizeof(ggml_half) + QK2_0 / 4, "wrong q2_0 block size/padding"); + +#define QK4_0 32 +typedef struct { + ggml_half d; // delta + uint8_t qs[QK4_0 / 2]; // nibbles / quants +} block_q4_0; +static_assert(sizeof(block_q4_0) == sizeof(ggml_half) + QK4_0 / 2, "wrong q4_0 block size/padding"); + +#define QK4_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half m; // min + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t qs[QK4_1 / 2]; // nibbles / quants +} block_q4_1; +static_assert(sizeof(block_q4_1) == 2 * sizeof(ggml_half) + QK4_1 / 2, "wrong q4_1 block size/padding"); + +#define QK_MXFP4 32 +typedef struct { + uint8_t e; // E8M0 + uint8_t qs[QK_MXFP4/2]; +} block_mxfp4; +static_assert(sizeof(block_mxfp4) == sizeof(uint8_t) + QK_MXFP4/2, "wrong mxfp4 block size/padding"); + +#define QK_NVFP4 64 +#define QK_NVFP4_SUB 16 // sub-block size for per-group scales +typedef struct { + uint8_t d[QK_NVFP4/QK_NVFP4_SUB]; // UE4M3 scales (4 bytes, one per 16-element sub-block) + uint8_t qs[QK_NVFP4/2]; // packed 4-bit E2M1 values (32 bytes) +} block_nvfp4; +static_assert(sizeof(block_nvfp4) == sizeof(uint8_t)*(QK_NVFP4/QK_NVFP4_SUB) + QK_NVFP4/2, "wrong nvfp4 block size/padding"); + +#define QK5_0 32 +typedef struct { + ggml_half d; // delta + uint8_t qh[4]; // 5-th bit of quants + uint8_t qs[QK5_0 / 2]; // nibbles / quants +} block_q5_0; +static_assert(sizeof(block_q5_0) == sizeof(ggml_half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding"); + +#define QK5_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half m; // min + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t qh[4]; // 5-th bit of quants + uint8_t qs[QK5_1 / 2]; // nibbles / quants +} block_q5_1; +static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding"); + +#define QK8_0 32 +typedef struct { + ggml_half d; // delta + int8_t qs[QK8_0]; // quants +} block_q8_0; +static_assert(sizeof(block_q8_0) == sizeof(ggml_half) + QK8_0, "wrong q8_0 block size/padding"); + +#define QK8_1 32 +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // delta + ggml_half s; // d * sum(qs[i]) + } GGML_COMMON_AGGR_S; + ggml_half2 ds; + } GGML_COMMON_AGGR_U; + int8_t qs[QK8_1]; // quants +} block_q8_1; +static_assert(sizeof(block_q8_1) == 2*sizeof(ggml_half) + QK8_1, "wrong q8_1 block size/padding"); + +// +// Ternary quantization +// + +// 1.6875 bpw +typedef struct { + uint8_t qs[(QK_K - 4 * QK_K / 64) / 5]; // 5 elements per byte (3^5 = 243 < 256) + uint8_t qh[QK_K/64]; // 4 elements per byte + ggml_half d; +} block_tq1_0; +static_assert(sizeof(block_tq1_0) == sizeof(ggml_half) + QK_K / 64 + (QK_K - 4 * QK_K / 64) / 5, "wrong tq1_0 block size/padding"); + +// 2.0625 bpw +typedef struct { + uint8_t qs[QK_K/4]; // 2 bits per element + ggml_half d; +} block_tq2_0; +static_assert(sizeof(block_tq2_0) == sizeof(ggml_half) + QK_K / 4, "wrong tq2_0 block size/padding"); + +// +// Super-block quantization structures +// + +// 2-bit quantization +// weight is represented as x = a * q + b +// 16 blocks of 16 elements each +// Effectively 2.625 bits per weight +typedef struct { + uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits + uint8_t qs[QK_K/4]; // quants + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; +} block_q2_K; +static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding"); + +// 3-bit quantization +// weight is represented as x = a * q +// 16 blocks of 16 elements each +// Effectively 3.4375 bits per weight +typedef struct { + uint8_t hmask[QK_K/8]; // quants - high bit + uint8_t qs[QK_K/4]; // quants - low 2 bits + uint8_t scales[12]; // scales, quantized with 6 bits + ggml_half d; // super-block scale +} block_q3_K; +static_assert(sizeof(block_q3_K) == sizeof(ggml_half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding"); + +// 4-bit quantization +// 8 blocks of 32 elements each +// weight is represented as x = a * q + b +// Effectively 4.5 bits per weight +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits + uint8_t qs[QK_K/2]; // 4--bit quants +} block_q4_K; +static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding"); + +// 5-bit quantization +// 8 blocks of 32 elements each +// weight is represented as x = a * q + b +// Effectively 5.5 bits per weight +typedef struct { + GGML_EXTENSION union { + struct { + ggml_half d; // super-block scale for quantized scales + ggml_half dmin; // super-block scale for quantized mins + } GGML_COMMON_AGGR_S; + ggml_half2 dm; + } GGML_COMMON_AGGR_U; + uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits + uint8_t qh[QK_K/8]; // quants, high bit + uint8_t qs[QK_K/2]; // quants, low 4 bits +} block_q5_K; +static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding"); + +// 6-bit quantization +// weight is represented as x = a * q +// 16 blocks of 16 elements each +// Effectively 6.5625 bits per weight +typedef struct { + uint8_t ql[QK_K/2]; // quants, lower 4 bits + uint8_t qh[QK_K/4]; // quants, upper 2 bits + int8_t scales[QK_K/16]; // scales, quantized with 8 bits + ggml_half d; // super-block scale +} block_q6_K; +static_assert(sizeof(block_q6_K) == sizeof(ggml_half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding"); + +// This is only used for intermediate quantization and dot products +typedef struct { + float d; // delta + int8_t qs[QK_K]; // quants + int16_t bsums[QK_K/16]; // sum of quants in groups of 16 +} block_q8_K; +static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding"); + +// (Almost) "true" 2-bit quantization. +// Due to the need to use blocks as per ggml design, it ends up using +// 2.0625 bpw because of the 16-bit scale for each block of 256. +typedef struct { + ggml_half d; + uint16_t qs[QK_K/8]; +} block_iq2_xxs; +static_assert(sizeof(block_iq2_xxs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding"); + +// 2.3125 bpw quants +typedef struct { + ggml_half d; + uint16_t qs[QK_K/8]; + uint8_t scales[QK_K/32]; +} block_iq2_xs; +static_assert(sizeof(block_iq2_xs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding"); + +// 2.5625 bpw quants +typedef struct { + ggml_half d; + uint8_t qs[QK_K/4]; + uint8_t qh[QK_K/32]; + uint8_t scales[QK_K/32]; +} block_iq2_s; +static_assert(sizeof(block_iq2_s) == sizeof(ggml_half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding"); + +// (Almost) "true" 3-bit quantization. +// Due to the need to use blocks as per ggml design, it ends up using +// 3.0625 bpw because of the 16-bit scale for each block of 256. +typedef struct { + ggml_half d; + uint8_t qs[3*QK_K/8]; +} block_iq3_xxs; +static_assert(sizeof(block_iq3_xxs) == sizeof(ggml_half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding"); + +// 3.4375 bpw +#define IQ3S_N_SCALE QK_K/64 +typedef struct { + ggml_half d; + uint8_t qs[QK_K/4]; + uint8_t qh[QK_K/32]; + uint8_t signs[QK_K/8]; + uint8_t scales[IQ3S_N_SCALE]; +} block_iq3_s; +static_assert(sizeof(block_iq3_s) == sizeof(ggml_half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding"); + +// 1.5625 bpw +typedef struct { + ggml_half d; + uint8_t qs[QK_K/8]; + uint16_t qh[QK_K/32]; +} block_iq1_s; +static_assert(sizeof(block_iq1_s) == sizeof(ggml_half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding"); + +// 1.75 bpw +typedef struct { + uint8_t qs[QK_K/8]; // grid index, low 8 bits + uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8) + uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64) +} block_iq1_m; +static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding"); + +// Used by IQ1_M quants +typedef union { + ggml_half f16; + uint16_t u16; +} iq1m_scale_t; + +// Non-linear quants +#define QK4_NL 32 +typedef struct { + ggml_half d; + uint8_t qs[QK4_NL/2]; +} block_iq4_nl; +static_assert(sizeof(block_iq4_nl) == sizeof(ggml_half) + QK4_NL/2, "wrong iq4_nl block size/padding"); + +typedef struct { + ggml_half d; + uint16_t scales_h; + uint8_t scales_l[QK_K/64]; + uint8_t qs[QK_K/2]; +} block_iq4_xs; +static_assert(sizeof(block_iq4_xs) == sizeof(ggml_half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding"); + +#endif // GGML_COMMON_DECL +#endif // GGML_COMMON_DECL + +//////////////////////////////////////////////////////////////////////////////// + +#ifndef GGML_COMMON_IMPL + +#if defined(GGML_COMMON_IMPL_C) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_CPP) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_METAL) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const constant type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_CUDA) || defined(GGML_COMMON_IMPL_HIP) || defined(GGML_COMMON_IMPL_MUSA) +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const __device__ type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#elif defined(GGML_COMMON_IMPL_SYCL) + +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; + +#define GGML_COMMON_IMPL +#endif + +#if defined(GGML_COMMON_IMPL) + +GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8) + 1, 2, 4, 8, 16, 32, 64, 128 +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128) + 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, + 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, + 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, + 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, + 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, + 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, + 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, + 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, ksigns64, 128) + 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff, + 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff, + 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff, + 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff, + 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff, + 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff, + 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff, + 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff, + 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff, + 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff, + 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff, + 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff, + 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff, + 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff, + 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff, + 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff, + 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff, + 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff, + 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff, + 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff, + 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff, + 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff, + 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff, + 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff, + 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff, + 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff, + 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff, + 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff, + 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff, + 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff, + 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff, + 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff, +GGML_TABLE_END() + + +GGML_TABLE_BEGIN(uint64_t, iq2xxs_grid, 256) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, + 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, + 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, + 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, + 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, + 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, + 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, + 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, + 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, + 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, + 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, + 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, + 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, + 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, + 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, + 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, + 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, + 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, + 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, + 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, + 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, + 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, + 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, + 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, + 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, + 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, + 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, + 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, + 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, + 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, + 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, + 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, + 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, + 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, + 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, + 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, + 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, + 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, + 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, + 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, + 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, + 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, + 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, + 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, + 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, + 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, + 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, + 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, + 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, + 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, + 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, + 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, + 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, + 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, + 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, + 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, + 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, + 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, + 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, + 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, + 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, + 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, + 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, iq2xs_grid, 512) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, + 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, + 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, + 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, + 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, + 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, + 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, + 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, + 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, + 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, + 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, + 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, + 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, + 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, + 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, + 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, + 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, + 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, + 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, + 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, + 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, + 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, + 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, + 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, + 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, + 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, + 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, + 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, + 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, + 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, + 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, + 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, + 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, + 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, + 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, + 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, + 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, + 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, + 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, + 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, + 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, + 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, + 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, + 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, + 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, + 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, + 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, + 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, + 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, + 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, + 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, + 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, + 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, + 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, + 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, + 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, + 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, + 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, + 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, + 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, + 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, + 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, + 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, + 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, + 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, + 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, + 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, + 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, + 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, + 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, + 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, + 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, + 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, + 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, + 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, + 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, + 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, + 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, + 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, + 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, + 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, + 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, + 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, + 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, + 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, + 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, + 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, + 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, + 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, + 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, + 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, + 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, + 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, + 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, + 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, + 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, + 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, + 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, + 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, + 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, + 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, + 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, + 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, + 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, + 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, + 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, + 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, + 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, + 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, + 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, + 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, + 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, + 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, + 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, + 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, + 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, + 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, + 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, + 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, + 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, + 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, + 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, + 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, + 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, + 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, + 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, + 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, + 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, + 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, + 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, + 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, + 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, + 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, + 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, + 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, + 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, + 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, + 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, + 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, + 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, + 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, + 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, + 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, + 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, + 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, + 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, + 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, + 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, + 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, + 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, + 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, + 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, + 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, + 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, + 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, + 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, + 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, + 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, + 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, + 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, + 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, + 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, + 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, + 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, + 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, + 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, + 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, + 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, + 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, + 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, + 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, + 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, + 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, + 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, + 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, + 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, + 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, + 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, + 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, + 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, + 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, + 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, + 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, + 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, + 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, + 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, + 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, + 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, + 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, + 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, + 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, + 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, + 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, + 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, + 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, + 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, + 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, + 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, + 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, + 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, + 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, + 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, + 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, + 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, + 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, + 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, + 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, + 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, + 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, + 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, + 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, + 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, + 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, + 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, + 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, + 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, + 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, + 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, + 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, + 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, + 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, + 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, + 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, + 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, + 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, + 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, + 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, + 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, + 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, + 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, + 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, + 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, + 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, + 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, + 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, + 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, + 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, + 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, + 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, + 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, + 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, + 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, + 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, + 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, + 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, + 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, + 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, + 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, + 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, + 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, + 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, + 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, + 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, + 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, + 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, + 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, + 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, + 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, + 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, + 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, + 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, + 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, + 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, + 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, + 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, + 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, + 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, + 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, + 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, + 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, + 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, + 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, + 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, + 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, + 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, + 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, + 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, + 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, + 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, + 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, + 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, + 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, + 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, + 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, + 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, + 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, + 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, + 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, + 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, + 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, + 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, + 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, + 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, + 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, + 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, + 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, + 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, + 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, + 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, + 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, + 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, + 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, + 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, + 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, + 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, + 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, + 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, + 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, + 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, + 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, + 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, + 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, + 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, + 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, + 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, + 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, + 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, + 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, + 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, + 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, + 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, + 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, + 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, + 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, + 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, + 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, + 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, + 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, + 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, + 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, + 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, + 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, + 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, + 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, + 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, + 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, + 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, + 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, + 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, + 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, + 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, + 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, + 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, + 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, + 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, + 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, + 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, + 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, + 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, + 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, + 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, + 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, + 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, + 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, + 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, + 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, + 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, + 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, + 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, + 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, + 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, + 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, + 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, + 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, + 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, + 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, + 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, + 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, + 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, + 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, + 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, + 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, + 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, + 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, + 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, + 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, + 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, + 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, + 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, + 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, + 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256) + 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, + 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, + 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, + 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, + 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, + 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, + 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, + 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, + 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, + 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, + 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, + 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, + 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, + 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, + 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, + 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, + 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, + 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, + 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, + 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, + 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, + 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, + 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, + 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, + 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, + 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, + 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, + 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, + 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, + 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, + 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, + 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, +GGML_TABLE_END() + +GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512) + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, + 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, + 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, + 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, + 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, + 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, + 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, + 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, + 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, + 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, + 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, + 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, + 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, + 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, + 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, + 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, + 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, + 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, + 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, + 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, + 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, + 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, + 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, + 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, + 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, + 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, + 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, + 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, + 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, + 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, + 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, + 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, + 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, + 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, + 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, + 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, + 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, + 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, + 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, + 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, + 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, + 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, + 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, + 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, + 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, + 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, + 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, + 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, + 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, + 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, + 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, + 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, + 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, + 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, + 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, + 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, + 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, +GGML_TABLE_END() + +// TODO: fix name to kvalues_iq4_nl +GGML_TABLE_BEGIN(int8_t, kvalues_iq4nl, 16) + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, +GGML_TABLE_END() + +// e2m1 values (doubled), shared by MXFP4 and NVFP4 +// ref: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +GGML_TABLE_BEGIN(int8_t, kvalues_fp4, 16) + 0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12, +GGML_TABLE_END() +#define kvalues_mxfp4 kvalues_fp4 + +#define NGRID_IQ1S 2048 +#define IQ1S_DELTA 0.125f +#define IQ1M_DELTA 0.125f +#if defined(GGML_COMMON_IMPL_C) || defined(GGML_COMMON_IMPL_CPP) +GGML_TABLE_BEGIN(uint64_t, iq1s_grid, NGRID_IQ1S) + 0xffffffffffffffff, 0xffffffffffffff01, 0xffffffffffff0000, 0xffffffffffff01ff, + 0xffffffffffff0101, 0xffffffffff00ff00, 0xffffffffff000000, 0xffffffffff01ffff, + 0xffffffffff01ff01, 0xffffffffff0101ff, 0xffffffffff010101, 0xffffffff00ff0000, + 0xffffffff0000ff00, 0xffffffff000000ff, 0xffffffff00000001, 0xffffffff00010000, + 0xffffffff01ffffff, 0xffffffff01ffff01, 0xffffffff01ff01ff, 0xffffffff01ff0101, + 0xffffffff01000000, 0xffffffff0101ffff, 0xffffffff0101ff01, 0xffffffff010101ff, + 0xffffffff01010101, 0xffffff00ffff00ff, 0xffffff00ffff0000, 0xffffff00ff00ff00, + 0xffffff00ff0000ff, 0xffffff00ff000001, 0xffffff00ff000100, 0xffffff00ff000101, + 0xffffff00ff010000, 0xffffff0000ffff00, 0xffffff0000ff0001, 0xffffff0000ff0100, + 0xffffff000000ff01, 0xffffff0000000000, 0xffffff0000000101, 0xffffff000001ff00, + 0xffffff00000100ff, 0xffffff0000010001, 0xffffff00000101ff, 0xffffff0001ff0000, + 0xffffff000100ff00, 0xffffff00010000ff, 0xffffff0001000001, 0xffffff0001010000, + 0xffffff01ffffffff, 0xffffff01ffffff01, 0xffffff01ffff01ff, 0xffffff01ffff0101, + 0xffffff01ff000000, 0xffffff01ff01ffff, 0xffffff01ff01ff01, 0xffffff01ff0101ff, + 0xffffff01ff010101, 0xffffff0100ff0000, 0xffffff010000ff00, 0xffffff0100000100, + 0xffffff01000100ff, 0xffffff0100010100, 0xffffff0101ffffff, 0xffffff0101ffff01, + 0xffffff0101ff01ff, 0xffffff0101ff0101, 0xffffff010100ff00, 0xffffff0101000000, + 0xffffff0101000100, 0xffffff010101ffff, 0xffffff010101ff01, 0xffffff01010101ff, + 0xffffff0101010101, 0xffff00ffff00ff00, 0xffff00ffff0000ff, 0xffff00ffff000001, + 0xffff00ffff010000, 0xffff00ff00ffff00, 0xffff00ff00ff0100, 0xffff00ff00000000, + 0xffff00ff00000101, 0xffff00ff000100ff, 0xffff00ff00010000, 0xffff00ff0100ff00, + 0xffff00ff01000100, 0xffff00ff01010000, 0xffff0000ffffff00, 0xffff0000ffff00ff, + 0xffff0000ffff0000, 0xffff0000ffff0001, 0xffff0000ff000000, 0xffff0000ff0001ff, + 0xffff0000ff000101, 0xffff0000ff010100, 0xffff000000ffffff, 0xffff000000ff0000, + 0xffff000000ff0101, 0xffff00000000ffff, 0xffff00000000ff00, 0xffff0000000000ff, + 0xffff000000000000, 0xffff000000000001, 0xffff000000000100, 0xffff00000001ffff, + 0xffff00000001ff01, 0xffff000000010000, 0xffff0000000101ff, 0xffff000000010101, + 0xffff000001ffff00, 0xffff00000100ff00, 0xffff000001000000, 0xffff0000010001ff, + 0xffff000001000101, 0xffff00000101ff00, 0xffff0000010100ff, 0xffff000001010000, + 0xffff000001010001, 0xffff000001010100, 0xffff0001ff0000ff, 0xffff0001ff000100, + 0xffff000100ffff00, 0xffff000100ff00ff, 0xffff00010000ffff, 0xffff00010000ff01, + 0xffff000100000000, 0xffff0001000001ff, 0xffff00010001ffff, 0xffff00010001ff00, + 0xffff000100010001, 0xffff000100010100, 0xffff000101ff0000, 0xffff00010100ff00, + 0xffff0001010000ff, 0xffff000101000100, 0xffff01ffffffffff, 0xffff01ffffffff01, + 0xffff01ffffff01ff, 0xffff01ffffff0101, 0xffff01ffff000000, 0xffff01ffff01ffff, + 0xffff01ffff01ff01, 0xffff01ffff0101ff, 0xffff01ffff010101, 0xffff01ff00ff0000, + 0xffff01ff0000ff00, 0xffff01ff00000001, 0xffff01ff00010000, 0xffff01ff01ffffff, + 0xffff01ff01ffff01, 0xffff01ff01ff01ff, 0xffff01ff01ff0101, 0xffff01ff01000000, + 0xffff01ff0101ffff, 0xffff01ff0101ff01, 0xffff01ff010101ff, 0xffff01ff01010101, + 0xffff0100ffff0000, 0xffff0100ff00ff00, 0xffff0100ff0000ff, 0xffff0100ff000100, + 0xffff0100ff0100ff, 0xffff0100ff010000, 0xffff010000ffff00, 0xffff01000000ffff, + 0xffff01000000ff00, 0xffff010000000000, 0xffff01000001ff00, 0xffff0100000100ff, + 0xffff010000010100, 0xffff01000100ff00, 0xffff0100010000ff, 0xffff010001000001, + 0xffff010001000100, 0xffff010001010000, 0xffff0101ffffffff, 0xffff0101ffffff01, + 0xffff0101ffff01ff, 0xffff0101ffff0101, 0xffff0101ff000000, 0xffff0101ff01ffff, + 0xffff0101ff01ff01, 0xffff0101ff0101ff, 0xffff0101ff010101, 0xffff010100ff0000, + 0xffff01010000ff00, 0xffff010100000100, 0xffff01010001ff00, 0xffff010100010000, + 0xffff010101ffffff, 0xffff010101ffff01, 0xffff010101ff0000, 0xffff010101ff01ff, + 0xffff010101ff0101, 0xffff010101000000, 0xffff01010101ffff, 0xffff01010101ff01, + 0xffff0101010101ff, 0xffff010101010101, 0xff00ffffff00ffff, 0xff00ffffff00ff00, + 0xff00ffffff0000ff, 0xff00ffffff000100, 0xff00ffffff0100ff, 0xff00ffffff010000, + 0xff00ffff00ffff00, 0xff00ffff00ff00ff, 0xff00ffff0000ffff, 0xff00ffff00000000, + 0xff00ffff000001ff, 0xff00ffff0001ff00, 0xff00ffff000100ff, 0xff00ffff00010000, + 0xff00ffff00010100, 0xff00ffff0100ff00, 0xff00ffff010000ff, 0xff00ffff01000001, + 0xff00ffff0101ff00, 0xff00ffff01010000, 0xff00ff00ffffff00, 0xff00ff00ffff00ff, + 0xff00ff00ffff0001, 0xff00ff00ffff0100, 0xff00ff00ff00ffff, 0xff00ff00ff00ff01, + 0xff00ff00ff000000, 0xff00ff00ff0001ff, 0xff00ff00ff01ff00, 0xff00ff00ff0100ff, + 0xff00ff00ff010100, 0xff00ff0000ff0000, 0xff00ff0000ff0101, 0xff00ff000000ffff, + 0xff00ff000000ff00, 0xff00ff000000ff01, 0xff00ff00000000ff, 0xff00ff0000000000, + 0xff00ff0000000001, 0xff00ff0000000100, 0xff00ff000001ffff, 0xff00ff0000010000, + 0xff00ff0001ff00ff, 0xff00ff000100ff01, 0xff00ff0001000000, 0xff00ff000101ff00, + 0xff00ff00010100ff, 0xff00ff01ff00ff00, 0xff00ff01ff0000ff, 0xff00ff01ff000001, + 0xff00ff01ff010000, 0xff00ff0100ffffff, 0xff00ff0100ff0001, 0xff00ff0100ff0100, + 0xff00ff010000ff01, 0xff00ff0100000000, 0xff00ff01000001ff, 0xff00ff0100000101, + 0xff00ff01000100ff, 0xff00ff0100010001, 0xff00ff0101ff0000, 0xff00ff010100ff00, + 0xff00ff01010000ff, 0xff00ff0101000001, 0xff00ff0101010000, 0xff0000ffffffff00, + 0xff0000ffffff0001, 0xff0000ffffff0100, 0xff0000ffff0000ff, 0xff0000ffff000000, + 0xff0000ffff0001ff, 0xff0000ffff000100, 0xff0000ffff01ff00, 0xff0000ffff010001, + 0xff0000ff00ffff00, 0xff0000ff00ff0000, 0xff0000ff00ff0001, 0xff0000ff00ff01ff, + 0xff0000ff00ff0101, 0xff0000ff0000ff00, 0xff0000ff000000ff, 0xff0000ff00000000, + 0xff0000ff00000001, 0xff0000ff00000100, 0xff0000ff0001ff01, 0xff0000ff00010000, + 0xff0000ff000101ff, 0xff0000ff01ff00ff, 0xff0000ff01ff0100, 0xff0000ff0100ffff, + 0xff0000ff010000ff, 0xff0000ff01000000, 0xff0000ff010001ff, 0xff0000ff01000100, + 0xff0000ff01000101, 0xff0000ff0101ff00, 0xff0000ff010100ff, 0xff0000ff01010000, + 0xff0000ff01010100, 0xff000000ffffff01, 0xff000000ffff0000, 0xff000000ffff0101, + 0xff000000ff00ff00, 0xff000000ff0000ff, 0xff000000ff000000, 0xff000000ff000001, + 0xff000000ff000100, 0xff000000ff01ffff, 0xff000000ff01ff01, 0xff000000ff010000, + 0xff000000ff0101ff, 0xff000000ff010101, 0xff00000000ffff00, 0xff00000000ff00ff, + 0xff00000000ff0000, 0xff00000000ff0001, 0xff0000000000ff00, 0xff0000000000ff01, + 0xff000000000000ff, 0xff00000000000000, 0xff00000000000001, 0xff00000000000100, + 0xff00000000000101, 0xff0000000001ff00, 0xff000000000100ff, 0xff00000000010000, + 0xff00000000010001, 0xff00000000010100, 0xff00000001ffffff, 0xff00000001ffff01, + 0xff00000001ff00ff, 0xff00000001ff0000, 0xff00000001ff01ff, 0xff00000001ff0101, + 0xff0000000100ffff, 0xff0000000100ff00, 0xff000000010000ff, 0xff00000001000000, + 0xff00000001000001, 0xff00000001000100, 0xff00000001000101, 0xff0000000101ffff, + 0xff0000000101ff01, 0xff00000001010000, 0xff000001ffffff00, 0xff000001ffff00ff, + 0xff000001ffff0000, 0xff000001ffff0001, 0xff000001ff000000, 0xff000001ff000001, + 0xff000001ff0001ff, 0xff000001ff000101, 0xff000001ff01ff00, 0xff000001ff010001, + 0xff00000100ffffff, 0xff00000100ffff01, 0xff00000100ff00ff, 0xff00000100ff0000, + 0xff00000100ff01ff, 0xff00000100ff0101, 0xff0000010000ff00, 0xff00000100000000, + 0xff00000100000001, 0xff000001000001ff, 0xff00000100000100, 0xff0000010001ff00, + 0xff000001000100ff, 0xff00000100010000, 0xff000001000101ff, 0xff00000100010100, + 0xff00000100010101, 0xff00000101ff0001, 0xff00000101ff0101, 0xff0000010100ff01, + 0xff00000101000000, 0xff000001010100ff, 0xff00000101010100, 0xff0001ffff00ff00, + 0xff0001ffff000001, 0xff0001ffff010000, 0xff0001ff00ffff00, 0xff0001ff00ff00ff, + 0xff0001ff00ff0001, 0xff0001ff00ff0100, 0xff0001ff0000ffff, 0xff0001ff00000000, + 0xff0001ff000001ff, 0xff0001ff00000101, 0xff0001ff0001ffff, 0xff0001ff0001ff00, + 0xff0001ff000100ff, 0xff0001ff00010001, 0xff0001ff00010100, 0xff0001ff01ff0000, + 0xff0001ff0100ff00, 0xff0001ff010000ff, 0xff0001ff01010000, 0xff000100ff00ffff, + 0xff000100ff00ff01, 0xff000100ff000000, 0xff000100ff000101, 0xff000100ff01ff00, + 0xff000100ff010000, 0xff00010000ffff01, 0xff00010000ff00ff, 0xff00010000ff0000, + 0xff00010000ff01ff, 0xff0001000000ff00, 0xff000100000000ff, 0xff00010000000000, + 0xff00010000000001, 0xff00010000000100, 0xff00010000000101, 0xff0001000001ffff, + 0xff00010000010000, 0xff00010000010101, 0xff00010001ff0100, 0xff0001000100ff00, + 0xff0001000100ff01, 0xff00010001000000, 0xff000100010001ff, 0xff0001000101ff00, + 0xff00010001010001, 0xff00010001010100, 0xff000101ffff0100, 0xff000101ff000001, + 0xff000101ff0100ff, 0xff000101ff010001, 0xff00010100ff00ff, 0xff00010100ff0001, + 0xff00010100ff0100, 0xff0001010000ffff, 0xff0001010000ff01, 0xff00010100000000, + 0xff000101000001ff, 0xff0001010001ff00, 0xff00010100010001, 0xff00010100010100, + 0xff00010101ff0000, 0xff0001010100ff00, 0xff00010101000001, 0xff00010101000101, + 0xff01ffffffffffff, 0xff01ffffffffff01, 0xff01ffffffff01ff, 0xff01ffffffff0101, + 0xff01ffffff000000, 0xff01ffffff01ffff, 0xff01ffffff01ff01, 0xff01ffffff010000, + 0xff01ffffff0101ff, 0xff01ffffff010101, 0xff01ffff00ff0000, 0xff01ffff0000ff00, + 0xff01ffff00000100, 0xff01ffff0001ff00, 0xff01ffff00010000, 0xff01ffff01ffffff, + 0xff01ffff01ffff01, 0xff01ffff01ff01ff, 0xff01ffff01ff0101, 0xff01ffff01000000, + 0xff01ffff0101ffff, 0xff01ffff0101ff01, 0xff01ffff01010000, 0xff01ffff010101ff, + 0xff01ffff01010101, 0xff01ff00ffff0000, 0xff01ff00ff00ff00, 0xff01ff00ff0000ff, + 0xff01ff00ff000100, 0xff01ff00ff010000, 0xff01ff0000ffff01, 0xff01ff0000ff00ff, + 0xff01ff0000ff0100, 0xff01ff0000000000, 0xff01ff00000001ff, 0xff01ff0000000101, + 0xff01ff000001ff00, 0xff01ff00000100ff, 0xff01ff0000010000, 0xff01ff0000010001, + 0xff01ff0001ff0000, 0xff01ff000100ffff, 0xff01ff0001000001, 0xff01ff0001000100, + 0xff01ff0001010000, 0xff01ff01ffffff00, 0xff01ff01ffff01ff, 0xff01ff01ffff0101, + 0xff01ff01ff00ff00, 0xff01ff01ff000000, 0xff01ff01ff01ffff, 0xff01ff01ff01ff01, + 0xff01ff01ff0101ff, 0xff01ff01ff010101, 0xff01ff0100ff0000, 0xff01ff010000ff00, + 0xff01ff0100000001, 0xff01ff0100000100, 0xff01ff0100010000, 0xff01ff0101ffff00, + 0xff01ff0101ff01ff, 0xff01ff0101ff0101, 0xff01ff010100ff00, 0xff01ff0101000000, + 0xff01ff010101ffff, 0xff01ff010101ff01, 0xff01ff01010101ff, 0xff01ff0101010101, + 0xff0100ffffff0000, 0xff0100ffff0000ff, 0xff0100ffff000001, 0xff0100ffff000100, + 0xff0100ffff010000, 0xff0100ff00ff00ff, 0xff0100ff00ff0000, 0xff0100ff00ff0001, + 0xff0100ff00ff0100, 0xff0100ff0000ff01, 0xff0100ff00000000, 0xff0100ff000001ff, + 0xff0100ff00000101, 0xff0100ff00010001, 0xff0100ff01ff0000, 0xff0100ff0100ff00, + 0xff0100ff010000ff, 0xff0100ff01000100, 0xff0100ff0101ff00, 0xff0100ff01010000, + 0xff010000ffff0100, 0xff010000ff000000, 0xff010000ff01ff00, 0xff010000ff010100, + 0xff01000000ffffff, 0xff01000000ff0000, 0xff01000000ff01ff, 0xff0100000000ff00, + 0xff010000000000ff, 0xff01000000000000, 0xff01000000000100, 0xff0100000001ff01, + 0xff01000000010000, 0xff010000000101ff, 0xff01000001ff0100, 0xff0100000100ffff, + 0xff010000010000ff, 0xff01000001000000, 0xff010000010001ff, 0xff01000001000101, + 0xff0100000101ff00, 0xff010000010100ff, 0xff01000001010001, 0xff01000001010100, + 0xff010001ffff0000, 0xff010001ff00ffff, 0xff010001ff00ff01, 0xff010001ff000100, + 0xff010001ff010000, 0xff01000100ffff00, 0xff01000100ff0100, 0xff01000100000000, + 0xff0100010001ffff, 0xff0100010001ff00, 0xff01000100010100, 0xff01000101ff00ff, + 0xff01000101ff0001, 0xff0100010100ffff, 0xff01000101000101, 0xff0101ffffffffff, + 0xff0101ffffffff01, 0xff0101ffffff01ff, 0xff0101ffffff0101, 0xff0101ffff000000, + 0xff0101ffff01ffff, 0xff0101ffff01ff01, 0xff0101ffff0101ff, 0xff0101ffff010101, + 0xff0101ff00ff0000, 0xff0101ff0000ff00, 0xff0101ff000000ff, 0xff0101ff00010000, + 0xff0101ff01ffffff, 0xff0101ff01ffff01, 0xff0101ff01ff01ff, 0xff0101ff01ff0101, + 0xff0101ff0101ffff, 0xff0101ff0101ff01, 0xff0101ff010101ff, 0xff0101ff01010101, + 0xff010100ffff0100, 0xff010100ff00ff00, 0xff010100ff0000ff, 0xff010100ff000100, + 0xff010100ff010000, 0xff01010000ff0001, 0xff01010000ff0100, 0xff0101000000ff01, + 0xff01010000000000, 0xff0101000001ff00, 0xff010100000100ff, 0xff01010000010001, + 0xff01010000010100, 0xff01010001ff0000, 0xff0101000100ffff, 0xff01010001000001, + 0xff01010001000100, 0xff010100010100ff, 0xff01010001010000, 0xff010101ffffffff, + 0xff010101ffffff01, 0xff010101ffff01ff, 0xff010101ffff0101, 0xff010101ff01ffff, + 0xff010101ff01ff01, 0xff010101ff0101ff, 0xff010101ff010101, 0xff01010100ff0000, + 0xff0101010000ff00, 0xff01010100000001, 0xff01010100000100, 0xff01010100010000, + 0xff01010101ffffff, 0xff01010101ffff01, 0xff01010101ff01ff, 0xff01010101ff0101, + 0xff01010101000000, 0xff0101010101ffff, 0xff0101010101ff01, 0xff010101010101ff, + 0xff01010101010101, 0x00ffffffffff0000, 0x00ffffffff00ff00, 0x00ffffffff000001, + 0x00ffffffff010000, 0x00ffffff00ff0100, 0x00ffffff0000ff01, 0x00ffffff00000000, + 0x00ffffff000001ff, 0x00ffffff00000101, 0x00ffffff0001ff00, 0x00ffffff000100ff, + 0x00ffffff00010001, 0x00ffffff010000ff, 0x00ffffff01000100, 0x00ffffff0101ff00, + 0x00ffffff01010001, 0x00ffff00ffffffff, 0x00ffff00ffffff00, 0x00ffff00ffff00ff, + 0x00ffff00ffff0001, 0x00ffff00ffff0100, 0x00ffff00ff00ff01, 0x00ffff00ff000000, + 0x00ffff00ff000001, 0x00ffff00ff0001ff, 0x00ffff00ff000101, 0x00ffff00ff01ff00, + 0x00ffff00ff010001, 0x00ffff00ff010100, 0x00ffff0000ff0000, 0x00ffff0000ff01ff, + 0x00ffff0000ff0101, 0x00ffff000000ff00, 0x00ffff00000000ff, 0x00ffff0000000000, + 0x00ffff0000000001, 0x00ffff0000000100, 0x00ffff0000000101, 0x00ffff0000010000, + 0x00ffff00000101ff, 0x00ffff0000010101, 0x00ffff0001ffff00, 0x00ffff0001ff00ff, + 0x00ffff0001ff0001, 0x00ffff000100ffff, 0x00ffff000100ff01, 0x00ffff0001000000, + 0x00ffff000101ffff, 0x00ffff000101ff00, 0x00ffff000101ff01, 0x00ffff01ffff0000, + 0x00ffff01ff00ff00, 0x00ffff01ff0000ff, 0x00ffff01ff000001, 0x00ffff01ff010000, + 0x00ffff0100ffff00, 0x00ffff010000ff01, 0x00ffff0100000000, 0x00ffff0100000101, + 0x00ffff01000100ff, 0x00ffff0100010100, 0x00ffff0101ff0100, 0x00ffff01010000ff, + 0x00ffff0101010000, 0x00ff00ffffffff00, 0x00ff00ffff000000, 0x00ff00ffff000100, + 0x00ff00ffff010100, 0x00ff00ff00ff0000, 0x00ff00ff00ff01ff, 0x00ff00ff00ff0101, + 0x00ff00ff0000ff00, 0x00ff00ff000000ff, 0x00ff00ff00000000, 0x00ff00ff00000001, + 0x00ff00ff0001ff00, 0x00ff00ff0001ff01, 0x00ff00ff00010000, 0x00ff00ff000101ff, + 0x00ff00ff00010101, 0x00ff00ff01ffff00, 0x00ff00ff01ff0001, 0x00ff00ff01ff0100, + 0x00ff00ff0100ffff, 0x00ff00ff0100ff01, 0x00ff00ff01000000, 0x00ff00ff0101ffff, + 0x00ff00ff0101ff00, 0x00ff00ff01010100, 0x00ff0000ffffff00, 0x00ff0000ffffff01, + 0x00ff0000ffff0000, 0x00ff0000ffff0101, 0x00ff0000ff00ff00, 0x00ff0000ff0000ff, + 0x00ff0000ff000000, 0x00ff0000ff000001, 0x00ff0000ff000100, 0x00ff0000ff01ffff, + 0x00ff0000ff010000, 0x00ff0000ff010101, 0x00ff000000ffff00, 0x00ff000000ff00ff, + 0x00ff000000ff0000, 0x00ff000000ff0001, 0x00ff000000ff0100, 0x00ff00000000ffff, + 0x00ff00000000ff00, 0x00ff0000000000ff, 0x00ff000000000000, 0x00ff000000000001, + 0x00ff0000000001ff, 0x00ff000000000100, 0x00ff00000001ff00, 0x00ff0000000100ff, + 0x00ff000000010000, 0x00ff000000010001, 0x00ff000000010100, 0x00ff000001ffff01, + 0x00ff000001ff00ff, 0x00ff000001ff0000, 0x00ff000001ff01ff, 0x00ff00000100ff00, + 0x00ff0000010000ff, 0x00ff000001000000, 0x00ff000001000001, 0x00ff000001000100, + 0x00ff000001000101, 0x00ff000001010000, 0x00ff0000010101ff, 0x00ff000001010101, + 0x00ff0001ffffff00, 0x00ff0001ffff0000, 0x00ff0001ffff0100, 0x00ff0001ff0000ff, + 0x00ff0001ff000000, 0x00ff0001ff0001ff, 0x00ff0001ff000101, 0x00ff0001ff01ff00, + 0x00ff0001ff0100ff, 0x00ff0001ff010100, 0x00ff000100ffffff, 0x00ff000100ffff01, + 0x00ff000100ff0000, 0x00ff000100ff01ff, 0x00ff00010000ffff, 0x00ff00010000ff00, + 0x00ff00010000ff01, 0x00ff000100000000, 0x00ff000100000001, 0x00ff000100000100, + 0x00ff00010001ff01, 0x00ff000100010000, 0x00ff0001000101ff, 0x00ff000101ffff00, + 0x00ff000101ff0000, 0x00ff000101ff0101, 0x00ff0001010000ff, 0x00ff000101000000, + 0x00ff00010101ff00, 0x00ff0001010100ff, 0x00ff000101010001, 0x00ff01ffffff0000, + 0x00ff01ffff00ff00, 0x00ff01ffff000000, 0x00ff01ffff000101, 0x00ff01ffff010000, + 0x00ff01ff00ffff01, 0x00ff01ff00ff0100, 0x00ff01ff0000ffff, 0x00ff01ff00000000, + 0x00ff01ff000001ff, 0x00ff01ff0001ff00, 0x00ff01ff000100ff, 0x00ff01ff00010001, + 0x00ff01ff00010100, 0x00ff01ff01ff0000, 0x00ff01ff0100ff00, 0x00ff01ff010000ff, + 0x00ff01ff01000001, 0x00ff01ff01000100, 0x00ff01ff01010000, 0x00ff0100ffffff00, + 0x00ff0100ffff0000, 0x00ff0100ffff0001, 0x00ff0100ffff0101, 0x00ff0100ff00ffff, + 0x00ff0100ff0000ff, 0x00ff0100ff000000, 0x00ff0100ff0001ff, 0x00ff0100ff01ff00, + 0x00ff0100ff0100ff, 0x00ff0100ff010001, 0x00ff010000ffffff, 0x00ff010000ff0000, + 0x00ff010000ff0101, 0x00ff01000000ff00, 0x00ff01000000ff01, 0x00ff0100000000ff, + 0x00ff010000000000, 0x00ff010000000001, 0x00ff010000000100, 0x00ff01000001ffff, + 0x00ff01000001ff01, 0x00ff010000010000, 0x00ff010000010001, 0x00ff010000010101, + 0x00ff010001ff0001, 0x00ff010001ff0100, 0x00ff01000100ff01, 0x00ff010001000000, + 0x00ff010001000001, 0x00ff0100010001ff, 0x00ff01000101ff00, 0x00ff0100010100ff, + 0x00ff010001010001, 0x00ff010001010100, 0x00ff0101ff000001, 0x00ff010100ff00ff, + 0x00ff010100ff0001, 0x00ff010100ff0100, 0x00ff010100000000, 0x00ff0101000001ff, + 0x00ff010100000101, 0x00ff0101000100ff, 0x00ff010100010100, 0x00ff0101010000ff, + 0x00ff010101010000, 0x0000ffffffffff00, 0x0000ffffffff00ff, 0x0000ffffffff0000, + 0x0000ffffffff0001, 0x0000ffffffff0100, 0x0000ffffff00ff01, 0x0000ffffff000000, + 0x0000ffffff000101, 0x0000ffffff01ff00, 0x0000ffffff0100ff, 0x0000ffffff010100, + 0x0000ffff00ffffff, 0x0000ffff00ff0000, 0x0000ffff00ff01ff, 0x0000ffff0000ff00, + 0x0000ffff000000ff, 0x0000ffff00000000, 0x0000ffff00000001, 0x0000ffff00000100, + 0x0000ffff00010000, 0x0000ffff000101ff, 0x0000ffff01ff0001, 0x0000ffff01ff0100, + 0x0000ffff01000000, 0x0000ffff010001ff, 0x0000ffff0101ffff, 0x0000ffff0101ff00, + 0x0000ffff01010001, 0x0000ffff01010100, 0x0000ff00ffff0000, 0x0000ff00ffff01ff, + 0x0000ff00ffff0100, 0x0000ff00ffff0101, 0x0000ff00ff00ff00, 0x0000ff00ff0000ff, + 0x0000ff00ff000000, 0x0000ff00ff000001, 0x0000ff00ff0001ff, 0x0000ff00ff000100, + 0x0000ff00ff01ffff, 0x0000ff00ff010000, 0x0000ff00ff010001, 0x0000ff00ff0101ff, + 0x0000ff00ff010101, 0x0000ff0000ffff00, 0x0000ff0000ff00ff, 0x0000ff0000ff0000, + 0x0000ff0000ff0001, 0x0000ff0000ff0100, 0x0000ff000000ffff, 0x0000ff000000ff00, + 0x0000ff000000ff01, 0x0000ff00000000ff, 0x0000ff0000000000, 0x0000ff0000000001, + 0x0000ff00000001ff, 0x0000ff0000000100, 0x0000ff0000000101, 0x0000ff000001ff00, + 0x0000ff00000100ff, 0x0000ff0000010000, 0x0000ff0000010001, 0x0000ff0000010100, + 0x0000ff0001ffff01, 0x0000ff0001ff0000, 0x0000ff000100ff00, 0x0000ff00010000ff, + 0x0000ff0001000000, 0x0000ff0001000001, 0x0000ff0001000100, 0x0000ff000101ffff, + 0x0000ff0001010000, 0x0000ff0001010101, 0x0000ff01ffffff00, 0x0000ff01ffff0001, + 0x0000ff01ff00ff01, 0x0000ff01ff000000, 0x0000ff01ff000101, 0x0000ff01ff01ff00, + 0x0000ff01ff0100ff, 0x0000ff0100ffff01, 0x0000ff0100ff0000, 0x0000ff0100ff0101, + 0x0000ff010000ff00, 0x0000ff01000000ff, 0x0000ff0100000000, 0x0000ff0100000001, + 0x0000ff0100000100, 0x0000ff010001ff01, 0x0000ff0100010000, 0x0000ff0101ff0000, + 0x0000ff010100ffff, 0x0000ff010100ff01, 0x0000ff0101000000, 0x0000ff0101000100, + 0x0000ff0101000101, 0x0000ff01010100ff, 0x000000ffffff00ff, 0x000000ffffff0000, + 0x000000ffff00ff00, 0x000000ffff0000ff, 0x000000ffff000000, 0x000000ffff000001, + 0x000000ffff0001ff, 0x000000ffff000100, 0x000000ffff01ff00, 0x000000ffff010000, + 0x000000ffff0101ff, 0x000000ffff010101, 0x000000ff00ffff00, 0x000000ff00ff00ff, + 0x000000ff00ff0000, 0x000000ff00ff0001, 0x000000ff00ff0100, 0x000000ff00ff0101, + 0x000000ff0000ffff, 0x000000ff0000ff00, 0x000000ff000000ff, 0x000000ff00000000, + 0x000000ff00000001, 0x000000ff000001ff, 0x000000ff00000100, 0x000000ff00000101, + 0x000000ff0001ff00, 0x000000ff0001ff01, 0x000000ff000100ff, 0x000000ff00010000, + 0x000000ff00010001, 0x000000ff00010100, 0x000000ff01ffffff, 0x000000ff01ff01ff, + 0x000000ff01ff0101, 0x000000ff0100ff00, 0x000000ff010000ff, 0x000000ff01000000, + 0x000000ff01000001, 0x000000ff01000100, 0x000000ff0101ff00, 0x000000ff010100ff, + 0x000000ff01010000, 0x000000ff01010101, 0x00000000ffffff00, 0x00000000ffffff01, + 0x00000000ffff00ff, 0x00000000ffff0000, 0x00000000ffff0001, 0x00000000ffff0100, + 0x00000000ff00ffff, 0x00000000ff00ff00, 0x00000000ff00ff01, 0x00000000ff0000ff, + 0x00000000ff000000, 0x00000000ff000001, 0x00000000ff000100, 0x00000000ff000101, + 0x00000000ff01ff00, 0x00000000ff0100ff, 0x00000000ff010000, 0x00000000ff010001, + 0x00000000ff010100, 0x0000000000ffffff, 0x0000000000ffff00, 0x0000000000ffff01, + 0x0000000000ff00ff, 0x0000000000ff0000, 0x0000000000ff0001, 0x0000000000ff01ff, + 0x0000000000ff0100, 0x000000000000ffff, 0x000000000000ff00, 0x000000000000ff01, + 0x00000000000000ff, 0x0000000000000000, 0x0000000000000001, 0x00000000000001ff, + 0x0000000000000100, 0x0000000000000101, 0x000000000001ffff, 0x000000000001ff00, + 0x00000000000100ff, 0x0000000000010000, 0x0000000000010001, 0x00000000000101ff, + 0x0000000000010100, 0x0000000000010101, 0x0000000001ffff00, 0x0000000001ff00ff, + 0x0000000001ff0000, 0x0000000001ff0100, 0x0000000001ff0101, 0x000000000100ffff, + 0x000000000100ff00, 0x00000000010000ff, 0x0000000001000000, 0x0000000001000001, + 0x00000000010001ff, 0x0000000001000100, 0x000000000101ff00, 0x00000000010100ff, + 0x0000000001010000, 0x0000000001010001, 0x0000000001010100, 0x00000001ffffffff, + 0x00000001ffffff00, 0x00000001ffffff01, 0x00000001ffff00ff, 0x00000001ffff0001, + 0x00000001ffff01ff, 0x00000001ffff0100, 0x00000001ff00ff00, 0x00000001ff0000ff, + 0x00000001ff000000, 0x00000001ff0001ff, 0x00000001ff000100, 0x00000001ff01ffff, + 0x00000001ff01ff00, 0x00000001ff01ff01, 0x00000001ff0100ff, 0x00000001ff010000, + 0x00000001ff010001, 0x00000001ff0101ff, 0x00000001ff010100, 0x0000000100ffff00, + 0x0000000100ff0000, 0x0000000100ff0001, 0x0000000100ff01ff, 0x0000000100ff0100, + 0x0000000100ff0101, 0x000000010000ffff, 0x000000010000ff00, 0x000000010000ff01, + 0x00000001000000ff, 0x0000000100000000, 0x0000000100000001, 0x00000001000001ff, + 0x0000000100000100, 0x0000000100000101, 0x000000010001ff00, 0x00000001000100ff, + 0x0000000100010000, 0x0000000100010100, 0x0000000101ffff01, 0x0000000101ff0000, + 0x0000000101ff0001, 0x0000000101ff01ff, 0x0000000101ff0100, 0x0000000101ff0101, + 0x000000010100ff00, 0x0000000101000000, 0x0000000101000101, 0x000000010101ff01, + 0x0000000101010000, 0x0000000101010001, 0x00000001010101ff, 0x0000000101010100, + 0x000001ffffff00ff, 0x000001ffffff0000, 0x000001ffffff0001, 0x000001ffffff0100, + 0x000001ffff00ffff, 0x000001ffff000000, 0x000001ffff0001ff, 0x000001ffff01ff00, + 0x000001ffff010101, 0x000001ff00ff0000, 0x000001ff00ff01ff, 0x000001ff00ff0101, + 0x000001ff0000ff00, 0x000001ff000000ff, 0x000001ff00000000, 0x000001ff00000001, + 0x000001ff000001ff, 0x000001ff00000100, 0x000001ff0001ffff, 0x000001ff0001ff01, + 0x000001ff000100ff, 0x000001ff00010000, 0x000001ff01ffff01, 0x000001ff01ff0100, + 0x000001ff0100ffff, 0x000001ff0100ff01, 0x000001ff01000000, 0x000001ff010001ff, + 0x000001ff0101ff00, 0x000001ff01010100, 0x00000100ffffff00, 0x00000100ffffff01, + 0x00000100ffff0000, 0x00000100ffff0101, 0x00000100ff00ff00, 0x00000100ff0000ff, + 0x00000100ff000000, 0x00000100ff000001, 0x00000100ff000100, 0x00000100ff010000, + 0x0000010000ffff00, 0x0000010000ff00ff, 0x0000010000ff0000, 0x0000010000ff0001, + 0x0000010000ff0100, 0x000001000000ffff, 0x000001000000ff00, 0x000001000000ff01, + 0x00000100000000ff, 0x0000010000000000, 0x0000010000000001, 0x00000100000001ff, + 0x0000010000000100, 0x0000010000000101, 0x000001000001ff00, 0x00000100000100ff, + 0x0000010000010000, 0x0000010000010001, 0x0000010000010100, 0x0000010001ffff00, + 0x0000010001ff0000, 0x0000010001ff0100, 0x000001000100ff00, 0x00000100010000ff, + 0x0000010001000000, 0x0000010001000001, 0x00000100010001ff, 0x0000010001000100, + 0x0000010001010000, 0x00000101ffff00ff, 0x00000101ffff01ff, 0x00000101ff000000, + 0x00000101ff000101, 0x00000101ff01ffff, 0x00000101ff010000, 0x00000101ff010001, + 0x00000101ff010100, 0x0000010100ff0000, 0x0000010100ff01ff, 0x0000010100ff0100, + 0x000001010000ff00, 0x0000010100000000, 0x0000010100000001, 0x00000101000001ff, + 0x0000010100000100, 0x000001010001ff01, 0x0000010100010000, 0x00000101000101ff, + 0x0000010100010101, 0x0000010101ffff00, 0x0000010101ff0101, 0x000001010100ff01, + 0x0000010101000000, 0x0000010101000001, 0x00000101010001ff, 0x0000010101000101, + 0x000001010101ff00, 0x0001ffffffff0000, 0x0001ffffff0000ff, 0x0001ffffff000001, + 0x0001ffffff000100, 0x0001ffffff010000, 0x0001ffff00ff00ff, 0x0001ffff0000ffff, + 0x0001ffff00000000, 0x0001ffff00000001, 0x0001ffff000001ff, 0x0001ffff00000101, + 0x0001ffff0001ff00, 0x0001ffff000100ff, 0x0001ffff00010001, 0x0001ffff00010100, + 0x0001ffff01ffff00, 0x0001ffff01000001, 0x0001ffff01010000, 0x0001ff00ffffff00, + 0x0001ff00ffff00ff, 0x0001ff00ffff0001, 0x0001ff00ffff0100, 0x0001ff00ff00ff01, + 0x0001ff00ff000000, 0x0001ff00ff01ff00, 0x0001ff00ff01ff01, 0x0001ff00ff010001, + 0x0001ff00ff010100, 0x0001ff0000ff0000, 0x0001ff0000ff0100, 0x0001ff000000ff00, + 0x0001ff0000000000, 0x0001ff0000000001, 0x0001ff0000000100, 0x0001ff0000010000, + 0x0001ff0000010001, 0x0001ff0000010101, 0x0001ff0001ff00ff, 0x0001ff0001ff0101, + 0x0001ff000100ff01, 0x0001ff0001000000, 0x0001ff000101ff00, 0x0001ff0001010001, + 0x0001ff0001010100, 0x0001ff01ff00ff00, 0x0001ff01ff000001, 0x0001ff01ff000100, + 0x0001ff0100ffffff, 0x0001ff0100ffff00, 0x0001ff0100ff0001, 0x0001ff0100000000, + 0x0001ff0100000001, 0x0001ff01000001ff, 0x0001ff010001ffff, 0x0001ff0101ff0000, + 0x0001ff010100ff00, 0x0001ff0101000001, 0x0001ff0101010000, 0x000100ffff00ff00, + 0x000100ffff00ff01, 0x000100ffff000000, 0x000100ffff000001, 0x000100ffff000101, + 0x000100ffff01ff00, 0x000100ffff010001, 0x000100ffff010100, 0x000100ff00ffffff, + 0x000100ff00ffff01, 0x000100ff00ff0000, 0x000100ff00ff01ff, 0x000100ff00ff0101, + 0x000100ff0000ff00, 0x000100ff000000ff, 0x000100ff00000000, 0x000100ff00000001, + 0x000100ff00000100, 0x000100ff00000101, 0x000100ff0001ffff, 0x000100ff0001ff01, + 0x000100ff00010000, 0x000100ff01ff00ff, 0x000100ff01ff0000, 0x000100ff01ff0100, + 0x000100ff0100ffff, 0x000100ff0100ff01, 0x000100ff010000ff, 0x000100ff01000000, + 0x000100ff01000001, 0x000100ff010001ff, 0x000100ff01000101, 0x000100ff0101ff00, + 0x000100ff010100ff, 0x000100ff01010100, 0x00010000ffff0000, 0x00010000ffff01ff, + 0x00010000ffff0101, 0x00010000ff00ff00, 0x00010000ff000000, 0x00010000ff000001, + 0x00010000ff000100, 0x0001000000ff00ff, 0x0001000000ff0000, 0x0001000000ff0001, + 0x0001000000ff0100, 0x000100000000ffff, 0x000100000000ff00, 0x00010000000000ff, + 0x0001000000000000, 0x0001000000000001, 0x0001000000000100, 0x000100000001ff00, + 0x00010000000100ff, 0x0001000000010000, 0x0001000000010001, 0x0001000000010100, + 0x0001000001ff0001, 0x0001000001ff0100, 0x0001000001ff0101, 0x000100000100ff00, + 0x0001000001000000, 0x0001000001000001, 0x0001000001000100, 0x0001000001000101, + 0x000100000101ff01, 0x0001000001010000, 0x0001000001010001, 0x00010000010101ff, + 0x00010001ffffff01, 0x00010001ffff0100, 0x00010001ff000000, 0x00010001ff01ffff, + 0x00010001ff010001, 0x00010001ff0101ff, 0x00010001ff010100, 0x0001000100ffffff, + 0x0001000100ff0000, 0x0001000100ff01ff, 0x0001000100ff0101, 0x000100010000ff00, + 0x00010001000000ff, 0x0001000100000000, 0x0001000100000001, 0x00010001000001ff, + 0x0001000100000101, 0x000100010001ffff, 0x0001000100010000, 0x00010001000101ff, + 0x0001000101ffffff, 0x0001000101ffff01, 0x0001000101ff0000, 0x0001000101ff0101, + 0x00010001010000ff, 0x0001000101000001, 0x00010001010001ff, 0x0001000101000100, + 0x000100010101ffff, 0x00010001010100ff, 0x0001000101010001, 0x0001000101010101, + 0x000101ffff000001, 0x000101ffff000100, 0x000101ffff010000, 0x000101ff00ffff00, + 0x000101ff0000ff01, 0x000101ff00000000, 0x000101ff00000101, 0x000101ff0001ff00, + 0x000101ff00010100, 0x000101ff01ff0000, 0x000101ff0100ff00, 0x000101ff010001ff, + 0x000101ff01010001, 0x00010100ffffff00, 0x00010100ffff00ff, 0x00010100ff00ffff, + 0x00010100ff000000, 0x00010100ff01ff00, 0x00010100ff0100ff, 0x00010100ff010001, + 0x00010100ff010100, 0x0001010000ffffff, 0x0001010000ffff00, 0x0001010000ff0000, + 0x0001010000ff0001, 0x0001010000ff01ff, 0x000101000000ff00, 0x00010100000000ff, + 0x0001010000000000, 0x0001010000000001, 0x0001010000000100, 0x000101000001ffff, + 0x0001010000010000, 0x0001010000010101, 0x0001010001ffff01, 0x0001010001ff00ff, + 0x0001010001ff0101, 0x0001010001000000, 0x000101000101ff00, 0x00010100010100ff, + 0x0001010001010000, 0x0001010001010100, 0x00010101ff00ff00, 0x00010101ff000001, + 0x00010101ff0001ff, 0x0001010100ffff00, 0x0001010100ff00ff, 0x0001010100ff0100, + 0x000101010000ffff, 0x0001010100000000, 0x00010101000001ff, 0x0001010100000101, + 0x00010101000100ff, 0x0001010100010000, 0x0001010100010100, 0x0001010101ff0001, + 0x00010101010000ff, 0x00010101010001ff, 0x0001010101000101, 0x0001010101010001, + 0x01ffffffffffffff, 0x01ffffffffffff01, 0x01ffffffffff01ff, 0x01ffffffffff0101, + 0x01ffffffff01ffff, 0x01ffffffff01ff01, 0x01ffffffff0101ff, 0x01ffffffff010101, + 0x01ffffff00ff0000, 0x01ffffff0000ffff, 0x01ffffff0000ff00, 0x01ffffff000000ff, + 0x01ffffff00000001, 0x01ffffff00000100, 0x01ffffff00010000, 0x01ffffff01ffffff, + 0x01ffffff01ffff01, 0x01ffffff01ff01ff, 0x01ffffff01ff0101, 0x01ffffff01000000, + 0x01ffffff0101ffff, 0x01ffffff0101ff01, 0x01ffffff010101ff, 0x01ffffff01010101, + 0x01ffff00ffff0000, 0x01ffff00ff00ff00, 0x01ffff00ff0000ff, 0x01ffff00ff000001, + 0x01ffff00ff000100, 0x01ffff00ff010000, 0x01ffff0000ffff00, 0x01ffff0000ff00ff, + 0x01ffff0000ff0100, 0x01ffff000000ffff, 0x01ffff000000ff01, 0x01ffff0000000000, + 0x01ffff0000000001, 0x01ffff00000001ff, 0x01ffff0000000100, 0x01ffff00000100ff, + 0x01ffff0000010001, 0x01ffff0000010100, 0x01ffff0001ff0000, 0x01ffff0001ff0100, + 0x01ffff00010000ff, 0x01ffff0001000001, 0x01ffff0001000100, 0x01ffff0001010000, + 0x01ffff01ffffffff, 0x01ffff01ffffff01, 0x01ffff01ffff01ff, 0x01ffff01ffff0101, + 0x01ffff01ff000000, 0x01ffff01ff01ffff, 0x01ffff01ff01ff01, 0x01ffff01ff0101ff, + 0x01ffff01ff010101, 0x01ffff010000ff00, 0x01ffff01000000ff, 0x01ffff0100000100, + 0x01ffff0100010000, 0x01ffff0101ffffff, 0x01ffff0101ffff01, 0x01ffff0101ff01ff, + 0x01ffff0101ff0101, 0x01ffff0101000000, 0x01ffff010101ffff, 0x01ffff010101ff01, + 0x01ffff01010101ff, 0x01ffff0101010101, 0x01ff00ffff0000ff, 0x01ff00ffff000100, + 0x01ff00ff00ffff00, 0x01ff00ff00ff00ff, 0x01ff00ff0000ff00, 0x01ff00ff00000000, + 0x01ff00ff00000101, 0x01ff00ff0001ff00, 0x01ff00ff000100ff, 0x01ff00ff00010100, + 0x01ff00ff010000ff, 0x01ff00ff01000100, 0x01ff0000ffffff00, 0x01ff0000ffff0100, + 0x01ff0000ff00ff01, 0x01ff0000ff000000, 0x01ff0000ff000101, 0x01ff0000ff010001, + 0x01ff0000ff010100, 0x01ff000000ffffff, 0x01ff000000ffff00, 0x01ff000000ff0000, + 0x01ff000000ff01ff, 0x01ff00000000ff00, 0x01ff0000000000ff, 0x01ff000000000000, + 0x01ff000000000001, 0x01ff000000000100, 0x01ff000000000101, 0x01ff000000010000, + 0x01ff000000010001, 0x01ff0000000101ff, 0x01ff000000010101, 0x01ff000001ffff00, + 0x01ff000001ff00ff, 0x01ff000001ff0001, 0x01ff000001ff0100, 0x01ff00000100ffff, + 0x01ff00000100ff01, 0x01ff000001000000, 0x01ff0000010001ff, 0x01ff000001010001, + 0x01ff0001ff00ff00, 0x01ff0001ff000001, 0x01ff0001ff000100, 0x01ff0001ff010000, + 0x01ff000100ffff00, 0x01ff000100ff00ff, 0x01ff000100ff0100, 0x01ff000100ff0101, + 0x01ff00010000ffff, 0x01ff000100000000, 0x01ff000100000100, 0x01ff000100000101, + 0x01ff00010001ff00, 0x01ff000100010001, 0x01ff000100010101, 0x01ff000101ff0000, + 0x01ff00010100ff00, 0x01ff000101000101, 0x01ff0001010100ff, 0x01ff01ffffffffff, + 0x01ff01ffffffff01, 0x01ff01ffffff01ff, 0x01ff01ffffff0101, 0x01ff01ffff000000, + 0x01ff01ffff01ffff, 0x01ff01ffff01ff01, 0x01ff01ffff0101ff, 0x01ff01ffff010101, + 0x01ff01ff00ffff00, 0x01ff01ff00ff0000, 0x01ff01ff0000ff00, 0x01ff01ff000000ff, + 0x01ff01ff00000100, 0x01ff01ff00010000, 0x01ff01ff00010100, 0x01ff01ff01ffffff, + 0x01ff01ff01ffff01, 0x01ff01ff01ff01ff, 0x01ff01ff01ff0101, 0x01ff01ff01000000, + 0x01ff01ff0101ffff, 0x01ff01ff0101ff01, 0x01ff01ff010101ff, 0x01ff01ff01010101, + 0x01ff0100ffff0000, 0x01ff0100ffff0001, 0x01ff0100ff00ff00, 0x01ff0100ff0000ff, + 0x01ff0100ff000001, 0x01ff0100ff010000, 0x01ff010000ffff00, 0x01ff010000ff00ff, + 0x01ff010000ff0001, 0x01ff010000ff0100, 0x01ff01000000ffff, 0x01ff01000000ff01, + 0x01ff010000000000, 0x01ff010000000101, 0x01ff01000001ff00, 0x01ff0100000100ff, + 0x01ff010001ff0000, 0x01ff010001000001, 0x01ff010001000100, 0x01ff010001010000, + 0x01ff0101ffffffff, 0x01ff0101ffffff01, 0x01ff0101ffff01ff, 0x01ff0101ffff0101, + 0x01ff0101ff000000, 0x01ff0101ff01ffff, 0x01ff0101ff01ff01, 0x01ff0101ff0101ff, + 0x01ff0101ff010101, 0x01ff010100ff0000, 0x01ff01010000ff00, 0x01ff0101000000ff, + 0x01ff010100000001, 0x01ff010101ffffff, 0x01ff010101ffff01, 0x01ff010101ff01ff, + 0x01ff010101ff0101, 0x01ff010101000000, 0x01ff01010101ffff, 0x01ff01010101ff01, + 0x01ff0101010101ff, 0x01ff010101010101, 0x0100ffffffff0000, 0x0100ffffff00ff00, + 0x0100ffffff000001, 0x0100ffffff0001ff, 0x0100ffffff000100, 0x0100ffffff010000, + 0x0100ffff00ffff00, 0x0100ffff00ff0001, 0x0100ffff00ff0100, 0x0100ffff00000000, + 0x0100ffff000001ff, 0x0100ffff00000101, 0x0100ffff00010100, 0x0100ffff00010101, + 0x0100ffff01ff0000, 0x0100ffff0100ff00, 0x0100ffff010000ff, 0x0100ffff01000001, + 0x0100ffff01000100, 0x0100ffff01010000, 0x0100ff00ffffff00, 0x0100ff00ffff00ff, + 0x0100ff00ffff0001, 0x0100ff00ffff0100, 0x0100ff00ff00ffff, 0x0100ff00ff000000, + 0x0100ff00ff0001ff, 0x0100ff00ff000101, 0x0100ff00ff01ff00, 0x0100ff00ff0100ff, + 0x0100ff00ff010001, 0x0100ff00ff010100, 0x0100ff0000ffffff, 0x0100ff0000ff0000, + 0x0100ff000000ffff, 0x0100ff000000ff00, 0x0100ff00000000ff, 0x0100ff0000000000, + 0x0100ff0000000001, 0x0100ff0000000100, 0x0100ff000001ff01, 0x0100ff0000010000, + 0x0100ff0001ff00ff, 0x0100ff0001ff0001, 0x0100ff000100ff01, 0x0100ff0001000000, + 0x0100ff00010001ff, 0x0100ff000101ff00, 0x0100ff00010100ff, 0x0100ff0001010001, + 0x0100ff0001010100, 0x0100ff01ffff0000, 0x0100ff01ff00ff00, 0x0100ff01ff0000ff, + 0x0100ff01ff000100, 0x0100ff01ff010000, 0x0100ff0100ff00ff, 0x0100ff0100ff0001, + 0x0100ff0100ff0100, 0x0100ff010000ffff, 0x0100ff010000ff01, 0x0100ff0100000000, + 0x0100ff01000001ff, 0x0100ff0100010001, 0x0100ff0100010100, 0x0100ff0101ff0000, + 0x0100ff01010000ff, 0x0100ff0101000001, 0x0100ff0101010100, 0x010000ffffffff00, + 0x010000ffffff00ff, 0x010000ffffff0001, 0x010000ffff00ffff, 0x010000ffff000000, + 0x010000ffff0001ff, 0x010000ffff010001, 0x010000ff00ffffff, 0x010000ff00ff0101, + 0x010000ff0000ff00, 0x010000ff000000ff, 0x010000ff00000000, 0x010000ff00000001, + 0x010000ff000001ff, 0x010000ff00000100, 0x010000ff0001ffff, 0x010000ff0001ff00, + 0x010000ff0001ff01, 0x010000ff00010000, 0x010000ff01ff00ff, 0x010000ff01ff0001, + 0x010000ff0100ff01, 0x010000ff010000ff, 0x010000ff01000000, 0x010000ff010001ff, + 0x010000ff0101ff00, 0x010000ff01010100, 0x01000000ffffffff, 0x01000000ffff0000, + 0x01000000ffff01ff, 0x01000000ffff0101, 0x01000000ff00ffff, 0x01000000ff00ff00, + 0x01000000ff0000ff, 0x01000000ff000000, 0x01000000ff000001, 0x01000000ff000100, + 0x01000000ff01ff00, 0x01000000ff010000, 0x01000000ff010100, 0x01000000ff010101, + 0x0100000000ffff00, 0x0100000000ff00ff, 0x0100000000ff0000, 0x0100000000ff0001, + 0x0100000000ff0100, 0x010000000000ffff, 0x010000000000ff00, 0x010000000000ff01, + 0x01000000000000ff, 0x0100000000000000, 0x0100000000000001, 0x01000000000001ff, + 0x0100000000000100, 0x0100000000000101, 0x010000000001ff00, 0x01000000000100ff, + 0x0100000000010000, 0x0100000000010001, 0x0100000000010100, 0x0100000001ffff00, + 0x0100000001ff0000, 0x0100000001ff01ff, 0x010000000100ff00, 0x010000000100ff01, + 0x01000000010000ff, 0x0100000001000000, 0x0100000001000001, 0x0100000001000100, + 0x0100000001000101, 0x010000000101ffff, 0x010000000101ff01, 0x0100000001010000, + 0x01000000010101ff, 0x0100000001010101, 0x01000001ffffff00, 0x01000001ffff00ff, + 0x01000001ff00ffff, 0x01000001ff000000, 0x01000001ff000100, 0x01000001ff01ffff, + 0x01000001ff010001, 0x01000001ff010100, 0x0100000100ff0000, 0x0100000100ff01ff, + 0x0100000100ff0100, 0x010000010000ff00, 0x010000010000ff01, 0x0100000100000000, + 0x0100000100000001, 0x0100000100000100, 0x0100000100010000, 0x01000001000101ff, + 0x0100000101ffff01, 0x0100000101ff00ff, 0x0100000101ff0100, 0x0100000101ff0101, + 0x010000010100ff01, 0x01000001010000ff, 0x0100000101000000, 0x01000001010100ff, + 0x0100000101010001, 0x0100000101010100, 0x010001ffffff0000, 0x010001ffff000001, + 0x010001ffff000100, 0x010001ffff010000, 0x010001ff00ffff00, 0x010001ff00ff0001, + 0x010001ff0000ffff, 0x010001ff0000ff01, 0x010001ff00000000, 0x010001ff00000001, + 0x010001ff00000101, 0x010001ff000100ff, 0x010001ff00010000, 0x010001ff01ff0000, + 0x010001ff0100ff00, 0x010001ff01000001, 0x010001ff01000100, 0x010001ff01010000, + 0x01000100ffff00ff, 0x01000100ffff0001, 0x01000100ffff0100, 0x01000100ff00ffff, + 0x01000100ff00ff01, 0x01000100ff000000, 0x01000100ff0001ff, 0x01000100ff000101, + 0x01000100ff01ffff, 0x01000100ff01ff00, 0x01000100ff0100ff, 0x01000100ff010001, + 0x0100010000ffffff, 0x0100010000ffff01, 0x0100010000ff0000, 0x0100010000ff01ff, + 0x0100010000ff0101, 0x010001000000ff00, 0x01000100000000ff, 0x0100010000000000, + 0x0100010000000001, 0x0100010000000100, 0x010001000001ff01, 0x0100010000010000, + 0x0100010000010001, 0x0100010000010101, 0x0100010001ffff00, 0x0100010001ff00ff, + 0x010001000100ffff, 0x010001000100ff01, 0x0100010001000000, 0x0100010001000101, + 0x010001000101ff00, 0x0100010001010001, 0x01000101ffff0000, 0x01000101ff000000, + 0x01000101ff010000, 0x0100010100ff00ff, 0x0100010100ff0001, 0x0100010100ff0100, + 0x010001010000ffff, 0x0100010100000000, 0x01000101000001ff, 0x010001010001ff00, + 0x0100010101ff0000, 0x010001010100ff00, 0x01000101010000ff, 0x0100010101000000, + 0x0100010101000001, 0x0101ffffffffffff, 0x0101ffffffffff01, 0x0101ffffffff01ff, + 0x0101ffffffff0101, 0x0101ffffff000000, 0x0101ffffff01ffff, 0x0101ffffff01ff01, + 0x0101ffffff0101ff, 0x0101ffffff010101, 0x0101ffff00ff0000, 0x0101ffff0000ff00, + 0x0101ffff000000ff, 0x0101ffff00000001, 0x0101ffff00000100, 0x0101ffff01ffffff, + 0x0101ffff01ffff01, 0x0101ffff01ff01ff, 0x0101ffff01ff0101, 0x0101ffff01000000, + 0x0101ffff0101ffff, 0x0101ffff0101ff01, 0x0101ffff010101ff, 0x0101ffff01010101, + 0x0101ff00ffff0000, 0x0101ff00ffff0100, 0x0101ff00ff00ff00, 0x0101ff00ff0000ff, + 0x0101ff00ff000001, 0x0101ff00ff000100, 0x0101ff00ff000101, 0x0101ff0000ff0001, + 0x0101ff0000ff0100, 0x0101ff000000ff00, 0x0101ff0000000000, 0x0101ff00000001ff, + 0x0101ff0000000101, 0x0101ff000001ff00, 0x0101ff00000100ff, 0x0101ff0001ff0000, + 0x0101ff000100ffff, 0x0101ff000100ff01, 0x0101ff0001000001, 0x0101ff0001000100, + 0x0101ff01ffffff01, 0x0101ff01ffff01ff, 0x0101ff01ffff0101, 0x0101ff01ff00ffff, + 0x0101ff01ff000100, 0x0101ff01ff01ff01, 0x0101ff01ff0101ff, 0x0101ff01ff010101, + 0x0101ff0100ff0000, 0x0101ff010000ff00, 0x0101ff0100000001, 0x0101ff0100000100, + 0x0101ff0100010000, 0x0101ff0101ffffff, 0x0101ff0101ffff01, 0x0101ff0101ff01ff, + 0x0101ff0101ff0101, 0x0101ff0101000000, 0x0101ff010101ffff, 0x0101ff010101ff01, + 0x0101ff01010101ff, 0x0101ff0101010101, 0x010100ffff000100, 0x010100ffff010000, + 0x010100ff00ffff00, 0x010100ff00ff00ff, 0x010100ff0000ffff, 0x010100ff000000ff, + 0x010100ff00000000, 0x010100ff000001ff, 0x010100ff00000101, 0x010100ff0001ff00, + 0x010100ff00010000, 0x010100ff00010001, 0x010100ff000101ff, 0x010100ff00010100, + 0x010100ff01ff0000, 0x01010000ffff0001, 0x01010000ffff0100, 0x01010000ff00ffff, + 0x01010000ff00ff01, 0x01010000ff000000, 0x01010000ff0001ff, 0x01010000ff010001, + 0x01010000ff010100, 0x0101000000ffff01, 0x0101000000ff0000, 0x010100000000ff00, + 0x01010000000000ff, 0x0101000000000000, 0x0101000000000001, 0x0101000000000100, + 0x0101000000010000, 0x0101000000010101, 0x0101000001ffff00, 0x0101000001ff00ff, + 0x0101000001ff0000, 0x0101000001ff0001, 0x0101000001ff0100, 0x010100000100ff01, + 0x0101000001000000, 0x01010000010001ff, 0x01010001ffff0000, 0x01010001ff00ff00, + 0x01010001ff000001, 0x01010001ff000101, 0x01010001ff01ff00, 0x01010001ff010000, + 0x0101000100ff00ff, 0x0101000100ff0001, 0x0101000100ff0101, 0x010100010000ff01, + 0x0101000100000000, 0x0101000100000001, 0x01010001000001ff, 0x010100010001ffff, + 0x010100010001ff01, 0x0101000101ff0001, 0x010100010100ffff, 0x0101000101000000, + 0x0101000101000001, 0x0101000101000100, 0x010100010101ff00, 0x01010001010100ff, + 0x0101000101010001, 0x010101ffffffffff, 0x010101ffffffff01, 0x010101ffffff01ff, + 0x010101ffffff0101, 0x010101ffff01ffff, 0x010101ffff01ff01, 0x010101ffff0101ff, + 0x010101ffff010101, 0x010101ff0000ff00, 0x010101ff000000ff, 0x010101ff00000001, + 0x010101ff00000100, 0x010101ff01ffffff, 0x010101ff01ffff01, 0x010101ff01ff01ff, + 0x010101ff01ff0101, 0x010101ff01000000, 0x010101ff0101ffff, 0x010101ff0101ff01, + 0x010101ff010101ff, 0x010101ff01010101, 0x01010100ffff0000, 0x01010100ff0000ff, + 0x01010100ff000100, 0x01010100ff01ff00, 0x01010100ff010000, 0x0101010000ffff00, + 0x010101000000ffff, 0x0101010000000000, 0x0101010000000101, 0x010101000001ff00, + 0x0101010000010001, 0x0101010000010100, 0x010101000100ffff, 0x0101010001000001, + 0x01010101ffffffff, 0x01010101ffffff01, 0x01010101ffff01ff, 0x01010101ffff0101, + 0x01010101ff01ffff, 0x01010101ff01ff01, 0x01010101ff0101ff, 0x01010101ff010101, + 0x010101010000ff00, 0x01010101000000ff, 0x0101010100000001, 0x0101010101ffffff, + 0x0101010101ffff01, 0x0101010101ff01ff, 0x0101010101ff0101, 0x0101010101000000, + 0x010101010101ffff, 0x010101010101ff01, 0x01010101010101ff, 0x0101010101010101, +GGML_TABLE_END() +#else +GGML_TABLE_BEGIN(uint32_t, iq1s_grid_gpu, NGRID_IQ1S) + 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, + 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, + 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, + 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, + 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, + 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, + 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, + 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, + 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, + 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, + 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, + 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, + 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, + 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, + 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, + 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, + 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, + 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, + 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, + 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, + 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, + 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, + 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, + 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, + 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, + 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, + 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, + 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, + 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, + 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, + 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, + 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, + 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, + 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, + 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, + 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, + 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, + 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, + 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, + 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, + 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, + 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, + 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, + 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, + 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, + 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, + 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, + 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, + 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, + 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, + 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, + 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, + 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, + 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, + 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, + 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, + 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, + 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, + 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, + 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, + 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, + 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, + 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, + 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, + 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, + 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, + 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, + 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, + 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, + 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, + 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, + 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, + 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, + 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, + 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, + 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, + 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, + 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, + 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, + 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, + 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, + 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, + 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, + 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, + 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, + 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, + 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, + 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, + 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, + 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, + 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, + 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, + 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, + 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, + 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, + 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, + 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, + 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, + 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, + 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, + 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, + 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, + 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, + 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, + 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, + 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, + 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, + 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, + 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, + 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, + 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, + 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, + 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, + 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, + 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, + 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, + 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, + 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, + 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, + 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, + 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, + 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, + 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, + 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, + 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, + 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, + 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, + 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, + 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, + 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, + 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, + 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, + 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, + 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, + 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, + 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, + 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, + 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, + 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, + 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, + 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, + 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, + 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, + 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, + 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, + 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, + 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, + 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, + 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, + 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, + 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, + 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, + 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, + 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, + 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, + 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, + 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, + 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, + 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, + 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, + 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, + 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, + 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, + 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, + 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, + 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, + 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, + 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, + 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, + 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, + 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, + 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, + 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, + 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, + 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, + 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, + 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, + 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, + 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, + 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, + 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, + 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, + 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, + 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, + 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, + 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, + 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, + 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, + 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, + 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, + 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, + 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, + 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, + 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, + 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, + 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, + 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, + 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, + 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, + 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, + 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, + 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, + 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, + 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, + 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, + 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, + 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, + 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, + 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, + 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, + 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, + 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, + 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, + 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, + 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, + 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, + 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, + 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, + 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, + 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, + 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, + 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, + 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, + 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, + 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, + 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, + 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, + 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, + 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, + 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, + 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, + 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, + 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, + 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, + 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, + 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, + 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, + 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, + 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, + 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, + 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, + 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, + 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, + 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, + 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, + 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, + 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, + 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, + 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, + 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, + 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, + 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, + 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, + 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, + 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, + 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, +GGML_TABLE_END() +#endif + +#endif // GGML_COMMON_IMPL +#endif // GGML_COMMON_IMPL diff --git a/engine/strata/tools/_paths.py b/engine/strata/tools/_paths.py new file mode 100644 index 00000000..336719ec --- /dev/null +++ b/engine/strata/tools/_paths.py @@ -0,0 +1,28 @@ +"""tools/_paths.py - where the tools find llama.cpp's gguf-py (for the MTP packer and the fixtures). + +Order: $STRATA_GGUF_PY, then /third_party/llama.cpp/gguf-py (what setup.py clones), then the development +tree's ../../.ref/llama.cpp/gguf-py. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +ENGINE = Path(__file__).resolve().parents[1] + + +def gguf_py() -> str: + cands = [os.environ.get("STRATA_GGUF_PY"), ENGINE / "third_party" / "llama.cpp" / "gguf-py", + ENGINE.parents[min(1, len(ENGINE.parents) - 1)] / ".ref" / "llama.cpp" / "gguf-py"] # the dev tree; a shallow install (G:\Strata) has no grandparent + for c in cands: + if c and (Path(c) / "gguf").is_dir(): + return str(c) + sys.exit("llama.cpp's gguf-py was not found: run setup.py (it clones llama.cpp into third_party/), " + "or set STRATA_GGUF_PY") + + +def add_gguf_py() -> None: + p = gguf_py() + if p not in sys.path: + sys.path.insert(0, p) diff --git a/engine/strata/tools/calibrate.py b/engine/strata/tools/calibrate.py new file mode 100644 index 00000000..77900562 --- /dev/null +++ b/engine/strata/tools/calibrate.py @@ -0,0 +1,248 @@ +"""Tune the engine's hardware-dependent settings on this PC (setup's --calibrate). + +Three settings depend on the machine more than on the model, and the defaults are right for the PC they were +measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5): + --pcie-frac the share of the experts missing from VRAM that are copied over PCIe and run on the GPU instead of + on the CPU. A fast PCIe link and a slow CPU want more; a laptop's x8 link or a fast CPU want less. + --spec-min-p how sure the draft layer must be to extend a verify window by another guess. A slower CPU pays more + per extra window row (more experts per window), so it wants a higher floor. + --pool-workers the CPU threads that compute experts. Every physical core is not always best: on hybrid CPUs the + efficiency cores can make the whole window wait for them. +The first two are measured through one engine (per-request `strata_tune` keys); the worker count needs a restart +per value. Decode speed only: the prompt path streams every expert whatever these settings say. + +A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - the +adaptive expert tier and the OS make single measurements noisy by a few percent. + + python tools/calibrate.py strata-q2_0.json # measure and print; setup.py --calibrate also saves it +""" +from __future__ import annotations + +import json +import statistics +import sys +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) + +MIN_GAIN = 0.03 # a setting must beat the default by this much to be kept +PCIE_FRACS = (0.0, 0.2, 0.35, 0.55, 0.75) +SPEC_MIN_PS = (0.3, 0.5, 0.7) +MAX_NEW = 128 +PROMPTS = ( + "Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.", + "Explain in two paragraphs how a refrigerator moves heat from inside to outside.", + "List twelve European capitals with one sentence about each.", +) + + +def chat_ids(tok, text: str) -> list[int]: + return tok.encode(f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", + parse_special=True) + + +def arg_value(args: list[str], flag: str) -> str | None: + return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None + + +def with_arg(args: list[str], flag: str, value: str | None) -> list[str]: + """`args` with `flag value` set (replaced if present), or removed when value is None.""" + out = list(args) + if flag in out: + i = out.index(flag) + del out[i:i + 2] + if value is not None: + out += [flag, value] + return out + + +def worker_candidates(default: int) -> list[int]: + """The engine's own count, and fewer: two thirds and a half (at least 2), without repeats.""" + c = [default] + for w in (round(default * 2 / 3), round(default / 2)): + if w >= 2 and w not in c: + c.append(w) + return c + + +def pick(measured: dict, default_key, min_gain: float = MIN_GAIN): + """The key with the best median tok/s, or `default_key` unless the best beats it by more than min_gain.""" + med = {k: statistics.median(v) for k, v in measured.items() if v} + if not med or default_key not in med: + return default_key + best = max(med, key=med.get) + return best if med[best] > med[default_key] * (1.0 + min_gain) else default_key + + +class Session: + """One running engine: measure decode tok/s for a setting (the median of the prompts' rates).""" + + def __init__(self, engine, ids_list): + self.engine = engine + self.ids_list = ids_list + + def rate(self, tune: dict | None = None) -> float: + rates = [] + for ids in self.ids_list: + sampling = {"temperature": 0} + if tune: + sampling["strata_tune"] = tune + n = sum(1 for t in self.engine.generate(ids, MAX_NEW, sampling, threading.Event()) if t is not None) + ms = (self.engine.last or {}).get("decode_ms") or 0.0 + if n > 8 and ms > 0: + rates.append(n / (ms / 1000.0)) + return statistics.median(rates) if rates else 0.0 + + def warm_up(self, rounds: int = 2): + for _ in range(rounds): + self.rate() + + +def run(cfg: dict, say=print, start_engine=None) -> dict: + """Measure on the engine `cfg` describes; returns {"settings": {flag: value}, "report": {...}}. + `start_engine(args)` returns a started engine (serve.server.StrataEngine or a stand-in in tests).""" + if start_engine is None: + from serve.server import StrataEngine, child_env + + def start_engine(args): + return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg)) + import strata_tokenizer as ST + tpath = Path(cfg["tokenizer"]) + vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for t, i in vocab.items(): + toks[i] = t + tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((tpath / "token_type.json").read_text())) + ids_list = [chat_ids(tok, p) for p in PROMPTS] + return measure(engine_args(cfg), ids_list, start_engine, say) + + +def engine_args(cfg: dict) -> list[str]: + """The arguments the server starts this config's engine with (serve.server.engine_args), so the tuning measures + the engine as it runs. #447: this used to read any "gpu" list as a layer split and add --layer-split auto, which + broke a one-card config with a helper card for the expert tier ("gpu": [0] + --expert-cache-device1: the engine + refuses a split that leaves no card without a stage), missed the "0,2" spelling, and ignored split_skip_if_fits.""" + from serve.server import engine_args as server_args + return server_args(cfg) + + +def engine_error(log: str | None, since: int = 0) -> str | None: + """#447: the engine's own reason for a failed start - the last line of its log written after byte `since` that is + its own ("strata ..." or "ERR ..."), else the last line there; None without a log or a new line.""" + if not log: + return None + try: + with open(log, "rb") as f: + f.seek(since) + lines = [x.strip() for x in f.read()[-16384:].decode("utf-8", "replace").splitlines() if x.strip()] + except OSError: + return None + return next((x for x in reversed(lines) if x.startswith(("strata", "ERR"))), lines[-1] if lines else None) + + +def measure(base_args: list[str], ids_list, start_engine, say=print) -> dict: + t0 = time.time() + report: dict = {} + say(" Loading the model for the measurements ...") + base_args = apply(base_args, {}) # the product defaults: what the measurements must beat + eng = start_engine(base_args) + try: + info = dict(getattr(eng, "info", {}) or {}) + d_pcie = float(info.get("pcie_frac", 0.55)) + d_minp = float(info.get("spec_min_p", 0.5)) + d_workers = int(info.get("pool_workers", 0)) or None + s = Session(eng, ids_list) + s.warm_up() + # 1. the PCIe share, at the default draft floor + by_pcie = {} + for f in sorted(set(PCIE_FRACS) | {round(d_pcie, 2)}): + by_pcie[f] = [s.rate({"pcie_frac": f, "spec_min_p": d_minp})] + say(f" PCIe share {f:.2f}: {by_pcie[f][0]:.1f} tok/s") + best_pcie = max(by_pcie, key=lambda k: by_pcie[k][0]) + # 2. the draft floor, at that share + by_minp = {} + for p in sorted(set(SPEC_MIN_PS) | {round(d_minp, 2)}): + by_minp[p] = [s.rate({"pcie_frac": best_pcie, "spec_min_p": p})] + say(f" draft floor {p:.2f}: {by_minp[p][0]:.1f} tok/s") + best_minp = max(by_minp, key=lambda k: by_minp[k][0]) + # 3. the winner against the default, interleaved, three times each + dflt, cand = (round(d_pcie, 2), round(d_minp, 2)), (best_pcie, best_minp) + confirm = {dflt: [], cand: []} + if cand != dflt: + for _ in range(3): + for k in (dflt, cand): + confirm[k].append(s.rate({"pcie_frac": k[0], "spec_min_p": k[1]})) + chosen = pick(confirm, dflt) if cand != dflt else dflt + report.update(default={"pcie_frac": dflt[0], "spec_min_p": dflt[1], "pool_workers": d_workers}, + pcie_sweep={str(k): v for k, v in by_pcie.items()}, + min_p_sweep={str(k): v for k, v in by_minp.items()}, + confirm={f"{k[0]}/{k[1]}": v for k, v in confirm.items()}) + finally: + close(eng) + settings = {} + if chosen != dflt: + settings["--pcie-frac"] = f"{chosen[0]:.2f}" + settings["--spec-min-p"] = f"{chosen[1]:.2f}" + base_rate = statistics.median(confirm[chosen]) if confirm.get(chosen) else None + # 4. fewer CPU workers (a restart each), with the chosen settings + if d_workers and len(worker_candidates(d_workers)) > 1: + tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}") + by_workers = {} + for w in worker_candidates(d_workers): + say(f" Measuring with {w} CPU workers (restarts the engine) ...") + e = start_engine(with_arg(tuned, "--pool-workers", None if w == d_workers else str(w))) + try: + sw = Session(e, ids_list) + sw.warm_up(1) + by_workers[w] = [sw.rate(), sw.rate()] + say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s") + finally: + close(e) + w_best = pick(by_workers, d_workers) + report["workers"] = {str(k): v for k, v in by_workers.items()} + if w_best != d_workers: + settings["--pool-workers"] = str(w_best) + base_rate = statistics.median(by_workers[w_best]) + elif by_workers.get(d_workers): + base_rate = statistics.median(by_workers[d_workers]) + report["seconds"] = round(time.time() - t0) + report["tok_s"] = round(base_rate, 1) if base_rate else None + return {"settings": settings, "report": report} + + +def close(eng): + proc = getattr(eng, "proc", None) + if proc is None: + return + try: + proc.stdin.write("QUIT\n") + proc.stdin.flush() + proc.stdin.close() + proc.wait(60) + except Exception: + proc.kill() + + +DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None} # None: the engine's own choice + + +def apply(args: list[str], settings: dict) -> list[str]: + """`args` with the calibrated settings; a setting the calibration did not change goes back to the product + default (setup's --spec-min-p 0.5, the engine's own PCIe share and worker count), so an older calibration's + values never linger.""" + out = list(args) + for flag, default in DEFAULTS.items(): + out = with_arg(out, flag, settings.get(flag, default)) + return out + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit("usage: calibrate.py ") + res = run(json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig"))) + print(json.dumps(res, indent=1)) diff --git a/engine/strata/tools/canonical_xcheck.py b/engine/strata/tools/canonical_xcheck.py new file mode 100644 index 00000000..e83819b3 --- /dev/null +++ b/engine/strata/tools/canonical_xcheck.py @@ -0,0 +1,799 @@ +"""tools/canonical_xcheck.py - P1.T3 in prototype: does the canonical form round-trip BIT-EXACTLY? + +P1.S6's release-blocking test is `dequant(canonical) == dequant_ggml(original)` bit for bit, for every tensor +of the real GGUF. This is that test in Python, before the C++ exists - the same order that worked for `ref/` +(the oracle before the engine), and faster to iterate. + +It starts with `Q2_0 -> S2`, which is both the largest mapping (31.64 GiB, the 202 routed-expert tensors) and +the one whose codebook has a non-obvious feature: + + dequantize_row_q2_0: value[j] = (code[j] - 1) * d code in {0,1,2,3} + +**The `- 1` is an offset in the codebook** - the representable values are {-d, 0, d, 2d}, not {0, d, 2d, 3d}. +A canonical form that stored the codes as unsigned 0..3 and decoded `code * d` would look right on most values +and be wrong on all of them by one step. That is why the source expression is transcribed rather than +re-derived, and why this test exists. + +`docs/pack-format.md` §2.1 says Q2_0 -> S2 splits codes and scales into separate planes with NO value change. +This checks exactly that claim. + +Run: python tools/canonical_xcheck.py [--tensors 4] [--gguf PATH] +""" +from __future__ import annotations + +import argparse +import collections +import mmap +import os +import pathlib +import struct +import sys +import time + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.dirname(HERE) +sys.path.insert(0, REPO) +sys.path.insert(0, HERE) +sys.path.insert(0, os.path.join(REPO, "ref")) + +import gguf_reader as G # noqa: E402 +from gguf_writer import dequantize_q2_0 # noqa: E402 +from load import _dequant_flat # noqa: E402 + +# default: $STRATA_SHARD1, else the development layout (/Q2_0 beside /Public/Engine) +SHARD1 = os.environ.get("STRATA_SHARD1") or os.path.join(os.path.dirname(os.path.dirname(REPO)), "Q2_0", + "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf") + +QK = 64 # Q2_0 block: 64 elements +BLOCK_BYTES = 18 # 2-byte fp16 scale + 16 bytes of 2-bit codes + + +# ---------------------------------------------------------------- mappings +# +# Each mapping is (encode, decode, block_bytes, block_elems). The DECODE is transcribed from +# `ggml-quants.c` expression by expression - the plan's rule, and the thing that decides P1.T3. + +def to_s8_q8_0(raw: bytes): + """`Q8_0` -> S8: codes + an fp16 scale per 32 elements, `codebook` the affine `code - 128`. + + `dequantize_row_q8_0`: `y[j] = x[i].qs[j] * d` with `d = GGML_FP16_TO_FP32(x[i].d)`. + + The code plane is UNSIGNED (0..255) like every other form here, so the source's `int8_t` code is stored + `+128` and the decode subtracts 128 - the same integer-bias mechanism as Q2_0's `-1` and Q4_0's `-8`, and + bit-exact for the same reason. It used to be stored signed instead, which is the natural reading of + `int8_t qs[32]` and was self-consistent with its own decoder; the pack is what showed the ambiguity, + because the two Q8_0 tensors then decoded 128 codes away from where they belonged while all 12 other + types were fine. ONE code-plane contract, not two. + """ + n = len(raw) // 34 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 34) + # `.reshape(-1)` matters: the fp16 view of an (n,2) byte column is (n,1), and a decode doing + # `scales[:, None]` then broadcasts it to (n,1,1) - silently producing n TIMES too many elements instead + # of raising. All the encoders return 1-D scales for that reason. + scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + codes = np.ascontiguousarray(a[:, 2:34]).view(np.int8).astype(np.int16) + 128 + return codes.astype(np.uint8), scales + + +def from_s8_q8_0(parts): + codes, scales = parts + v = (codes.astype(np.int32) - 128).astype(np.float32) # the +128 is undone inside the integer + return (v * scales[:, None]).reshape(-1) + + +def to_s4_q4_0(raw: bytes): + """`Q4_0` -> S4: 4-bit codes + one fp16 scale per 32 elements. No separate offset. + + `dequantize_row_q4_0`: + x0 = (qs[j] & 0x0F) - 8 ; y[j + 0] = x0*d + x1 = (qs[j] >> 4) - 8 ; y[j + 16] = x1*d + + TWO things here are easy to get wrong and both would still produce plausible numbers: the low nibbles + fill the FIRST HALF of the block and the high nibbles the SECOND (they are NOT interleaved), and the + `- 8` is applied to the integer BEFORE the multiply, i.e. the codebook is -8..7 rather than 0..15. + """ + n = len(raw) // 18 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 18) + scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + qs = np.ascontiguousarray(a[:, 2:18]) # (n, 16) + codes = np.empty((n, 32), dtype=np.uint8) + codes[:, 0:16] = qs & 0x0F # low nibbles -> first half + codes[:, 16:32] = qs >> 4 # high nibbles -> second half + return codes, scales + + +def from_s4_q4_0(parts): + codes, scales = parts + v = (codes.astype(np.int32) - 8).astype(np.float32) # the -8 is inside the integer + return (v * scales[:, None]).reshape(-1) + + +def get_scale_min_k4(scales, j): + """`get_scale_min_k4`, ggml-quants.c L880, transcribed. + + The 6-bit scale and min of group `j` (0..7) live packed in the block's 12 scale bytes: the low four + groups keep their 6 bits in a byte, and the high four borrow the top two bits of the LOW groups' bytes. + Reading only `q[j]` gives the right answer for the first half of the groups and silently wrong ones for + the second - which is why this is transcribed rather than inferred from the layout. + """ + if j < 4: + return int(scales[j]) & 63, int(scales[j + 4]) & 63 + return ((int(scales[j + 4]) & 0xF) | ((int(scales[j - 4]) >> 6) << 4), + (int(scales[j + 4]) >> 4) | ((int(scales[j]) >> 6) << 4)) + + +def to_s4_q4_k(raw: bytes): + """`Q4_K` -> S4: 8 groups of 32 per 256-element block, each with `scale = d*sc` and `offset = -(min*m)`. + + `dequantize_row_q4_K` (L1529): + d = fp16(x.d) ; min = fp16(x.dmin) + for j in 0..256 step 64: + (sc,m) = get_scale_min_k4(is+0) ; d1 = d*sc ; m1 = min*m + (sc,m) = get_scale_min_k4(is+1) ; d2 = d*sc ; m2 = min*m + y[l] = d1 * (q[l] & 0xF) - m1 + y[l + 32] = d2 * (q[l] >> 4) - m2 + + TWO groups per 64-element step, taking the low and high nibbles of the SAME 32 scale bytes - so the + canonical group size is 32, not 64, and there are 8 groups per block. + """ + n = len(raw) // 144 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 144) + d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + dmin = np.ascontiguousarray(a[:, 2:4]).view(np.float16).astype(np.float32).reshape(-1) + scb = a[:, 4:16] # (n, 12) the packed 6-bit scales and mins + qs = a[:, 16:144] # (n, 128) + + scales = np.empty((n, 8), dtype=np.float32) + offsets = np.empty((n, 8), dtype=np.float32) + for g in range(8): + sc = np.array([get_scale_min_k4(scb[i], g)[0] for i in range(n)], dtype=np.float32) + m = np.array([get_scale_min_k4(scb[i], g)[1] for i in range(n)], dtype=np.float32) + scales[:, g] = d * sc # f32 product of the same two factors ggml uses + offsets[:, g] = -(dmin * m) # negation is exact, so adding it is bit-identical + + codes = np.empty((n, 256), dtype=np.uint8) + for j in range(4): + blk = qs[:, j * 32:(j + 1) * 32] + codes[:, j * 64:j * 64 + 32] = blk & 0x0F # group is+0: LOW nibbles + codes[:, j * 64 + 32:j * 64 + 64] = blk >> 4 # group is+1: HIGH nibbles + return codes, scales, offsets + + +def from_s4_q4_k(parts): + codes, scales, offsets = parts + v = codes.astype(np.float32).reshape(codes.shape[0], 8, 32) + return (v * scales[:, :, None] + offsets[:, :, None]).reshape(-1) + + +def unpack_q3_k_scales(sb): + """The 12 scale bytes of a `Q3_K` block -> 16 six-bit scales, in group order. + + `dequantize_row_q3_K` L1323-1328, transcribed. As bytes, with `s` the 12 scale bytes: + group j (0..3) = (s[j] & 0x0F) | ((s[8+j] & 0x03) << 4) + group 4+j = (s[4+j] & 0x0F) | (((s[8+j] >> 2) & 0x03) << 4) + group 8+j = (s[j] >> 4) | (((s[8+j] >> 4) & 0x03) << 4) + group 12+j = (s[4+j] >> 4) | (((s[8+j] >> 6) & 0x03) << 4) + + The trap is the same shape as `get_scale_min_k4`'s and just as quiet: the first EIGHT groups take the + low nibbles of `s[0..7]`, the last eight the HIGH nibbles of those SAME bytes, and `s[8..11]` supply two + high bits each in that same order. A reader who assumes "12 bytes = 12 groups, one nibble each" gets + half the groups right. + """ + n = sb.shape[0] + out = np.empty((n, 16), dtype=np.int32) + for j in range(4): + t = sb[:, 8 + j].astype(np.int32) + lo, hi = sb[:, j].astype(np.int32), sb[:, 4 + j].astype(np.int32) + out[:, j] = (lo & 0x0F) | ((t & 0x03) << 4) + out[:, 4 + j] = (hi & 0x0F) | (((t >> 2) & 0x03) << 4) + out[:, 8 + j] = ((lo >> 4) & 0x0F) | (((t >> 4) & 0x03) << 4) + out[:, 12 + j] = ((hi >> 4) & 0x0F) | (((t >> 6) & 0x03) << 4) + return out + + +def to_s4_q3_k(raw: bytes): + """`Q3_K` -> S4: 16 groups of 16 per 256-element block, codebook 0..7 of the 0..15 a 4-bit plane holds. + + `dequantize_row_q3_K` (L1305): + d_all = fp16(x.d) + for half in {0, 128}: # `q` advances by 32 per half; `hm` does NOT advance + for j in 0..3: # shift = 2j, mask m = 1 << j + dl = d_all * (scales[is++] - 32) + for l in 0..15: y = dl * ((qs[l + 0] >> shift) & 3) - ((hm[l + 0] & m) ? 0 : 4) + dl = d_all * (scales[is++] - 32) + for l in 0..15: y = dl * ((qs[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4) + + Three things here are each independently easy to get wrong, and each would still yield plausible values: + + * **`hm` is indexed 0..31 in BOTH halves, but the BIT moves.** `q += 32` sits at the end of the `n` + loop, while the hmask is only ever read as `hm[l+0]`/`hm[l+16]` - so the second half re-reads the + SAME 32 mask bytes. What distinguishes the halves is `m`: it is declared outside the `n` loop and + only ever shifted, so it never resets, and the second half uses bits 4..7 where the first used + 0..3. `shift` DOES reset per half. Both facts are needed and they point opposite ways; getting + `m` wrong flips the sign of roughly half the elements of the second half, which is what the first + run of this mapping did. + * **the group size is 16, not 32** - 16 scales per half, hence 16 groups per 256-element block. + * **the `- 4` is an INTEGER bias on the code, not an offset in the value.** So the stored code is + `(2 bits) + (hm bit ? 4 : 0)`, which stays in 0..7, and the decode subtracts 4 before the multiply. + Folding it into a value-space offset instead, as `(c+4)*dl - 4*dl`, is NOT bit-exact: `fl(5a) - 4a` + is exact by Sterbenz but equals `a + 5ae`, not `a`. Q2_0's `- 1` and Q4_0's `- 8` are the same + integer-bias mechanism, which is why this is expressed the same way. + + The element order is `128*half + 32*j + 16*sub + l`, matching the sequential `*y++`. + """ + n = len(raw) // 110 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 110) + hmask = a[:, 0:32] # hmask[QK_K/8] + qs = a[:, 32:96] # qs[QK_K/4] + sb = a[:, 96:108] # scales[12] + d = np.ascontiguousarray(a[:, 108:110]).view(np.float16).astype(np.float32).reshape(-1) + + sc6 = unpack_q3_k_scales(sb) + scales = d[:, None] * (sc6 - 32).astype(np.float32) # integer bias, then ONE f32 multiply + codes = np.empty((n, 256), dtype=np.uint8) + for half in range(2): + for j in range(4): + for sub in range(2): + g = 8 * half + 2 * j + sub + base = half * 32 + sub * 16 + c2 = (qs[:, base:base + 16] >> (2 * j)) & 0x03 + # `m` does NOT reset between halves: it is `1 << (4*half + j)`, not `1 << j`. + m = (hmask[:, sub * 16:sub * 16 + 16] >> (4 * half + j)) & 0x01 + codes[:, g * 16:(g + 1) * 16] = c2 + 4 * m + return codes, scales + + +def from_s4_q3_k(parts): + codes, scales = parts + v = (codes.astype(np.int32) - 4).astype(np.float32) + return (v.reshape(-1, 16, 16) * scales[:, :, None]).reshape(-1) + + +# ---------------------------------------------------------------- the IQ4 codebook +# `kvalues_iq4nl`. `ggml-common.h` heads the IQ4 block definitions "Non-linear quants", and the name is +# load-bearing: this codebook is NOT affine, so unlike Q2_0's `-1`, Q3_K's `-4` and Q4_0's `-8` it cannot be +# expressed as a bias on the code. It is a 16-entry table lookup, and the canonical decode has to say so. +# Checked against two independent files before use, because a codebook is exactly the kind of constant that +# has silent variants: ggml-cpu/llamafile/sgemm.cpp L1361 and ggml-opencl/kernels/mul_mv_iq4_nl_f32.cl L30. +KV_IQ4NL = np.array([-127, -104, -83, -65, -49, -35, -22, -10, + 1, 13, 25, 38, 53, 69, 89, 113], dtype=np.float32) + + +def to_s4_iq4_nl(raw: bytes): + """`IQ4_NL` -> S4 with the IQ4 codebook: 32 codes, one fp16 scale, no offset. + + `dequantize_row_iq4_nl` (L2725): + d = fp16(x.d) + for j in 0..15: + y[j + 0] = d * kvalues_iq4nl[qs[j] & 0xf] + y[j + 16] = d * kvalues_iq4nl[qs[j] >> 4] + + Same nibble split as `Q4_0` - low nibbles fill the first half, high the second - but the code is an index + into the table rather than a value, so the whole `- 8` business has no analogue here. + """ + n = len(raw) // 18 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 18) + scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + qs = np.ascontiguousarray(a[:, 2:18]) # (n, 16) = QK4_NL/2 + codes = np.empty((n, 32), dtype=np.uint8) + codes[:, 0:16] = qs & 0x0F + codes[:, 16:32] = qs >> 4 + return codes, scales + + +def from_s4_iq4_nl(parts): + codes, scales = parts + return (KV_IQ4NL[codes] * scales[:, None]).reshape(-1) + + +def to_s4_iq4_xs(raw: bytes): + """`IQ4_XS` -> S4 with the IQ4 codebook: 8 groups of 32, each with `scale = d*(ls - 32)`. + + `dequantize_row_iq4_xs` (L2743): + d = fp16(x.d) + for ib in 0..7: # QK_K/32 groups + ls = ((scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((scales_h >> 2*ib) & 3) << 4) + dl = d * (ls - 32) + for j in 0..15: + y[j + 0] = dl * kvalues_iq4nl[qs[j] & 0xf] + y[j + 16] = dl * kvalues_iq4nl[qs[j] >> 4] + qs += 16 + + The 6-bit scale `ls` is split across TWO parallel arrays by element index: `scales_l` holds one nibble + per 32-element group (two groups per byte, low nibble first) and the `uint16_t scales_h` holds the top + two bits of each group's scale at bit offset `2*ib`. Reading a group's scale out of `scales_l` alone is + right for values under 16 and silently wrong above it. + """ + n = len(raw) // 136 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 136) + d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + sh = np.ascontiguousarray(a[:, 2:4]).view(np.uint16).astype(np.int32).reshape(-1) # uint16 scales_h + sl = a[:, 4:8].astype(np.int32) # scales_l[QK_K/64] = 4 bytes + qs = a[:, 8:136] # qs[QK_K/2] = 128 bytes + + ls = np.empty((n, 8), dtype=np.int32) + for ib in range(8): + ls[:, ib] = ((sl[:, ib // 2] >> (4 * (ib % 2))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4) + scales = d[:, None] * (ls - 32).astype(np.float32) # integer bias, then ONE f32 multiply + + codes = np.empty((n, 256), dtype=np.uint8) + for ib in range(8): + blk = qs[:, ib * 16:(ib + 1) * 16] + codes[:, ib * 32:ib * 32 + 16] = blk & 0x0F # low nibbles -> first 16 of the group + codes[:, ib * 32 + 16:ib * 32 + 32] = blk >> 4 # high nibbles -> second 16 + return codes, scales + + +def from_s4_iq4_xs(parts): + codes, scales = parts + return (KV_IQ4NL[codes].reshape(-1, 8, 32) * scales[:, :, None]).reshape(-1) + + +def to_s8_q5_0(raw: bytes): + """`Q5_0` -> S8: 5-bit codes, one fp16 scale per 32 elements, codebook bias `-16`. + + `dequantize_row_q5_0` (L500): + qh = the 4 bytes of x.qh read as a native uint32 + for j in 0..15: + xh_0 = ((qh >> (j + 0)) << 4) & 0x10 + xh_1 = ((qh >> (j + 12)) ) & 0x10 + x0 = ((qs[j] & 0x0F) | xh_0) - 16 ; y[j + 0] = x0*d + x1 = ((qs[j] >> 4) | xh_1) - 16 ; y[j + 16] = x1*d + + The 5th bit of element `j` is bit `j` of the 32-bit `qh`, and of element `j+16` is bit `j+16`: one bit per + element, taken from a field that is read as a single integer rather than as 4 bytes. `x1`'s shift of + `j + 12` plus the `& 0x10` is how the source reaches bit `j+16`; writing `j + 16` directly gives the same + answer, which is worth knowing before "fixing" it. + """ + n = len(raw) // 22 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 22) + scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + qh = np.ascontiguousarray(a[:, 2:6]).view("> j[None, :]) & 1) << 4).astype(np.uint8) + xh1 = (((qh[:, None] >> (j[None, :] + 16)) & 1) << 4).astype(np.uint8) + codes = np.empty((n, 32), dtype=np.uint8) + codes[:, 0:16] = (qs & 0x0F) | xh0 # low nibbles -> first half + codes[:, 16:32] = (qs >> 4) | xh1 # high nibbles -> second half + return codes, scales + + +def from_s8_q5_0(parts): + codes, scales = parts + v = (codes.astype(np.int32) - 16).astype(np.float32) # the -16 is inside the integer + return (v * scales[:, None]).reshape(-1) + + +def to_s8_q5_k(raw: bytes): + """`Q5_K` -> S8: 8 groups of 32, `scale = d*sc`, `offset = -(dmin*m)`; codes are 5-bit. + + `dequantize_row_q5_K` (L1731): + d = fp16(x.d) ; min = fp16(x.dmin) + is = 0 ; u1 = 1 ; u2 = 2 + for j in 0..256 step 64: + (sc,m) = get_scale_min_k4(is+0) ; d1 = d*sc ; m1 = min*m + (sc,m) = get_scale_min_k4(is+1) ; d2 = d*sc ; m2 = min*m + for l in 0..31: y++ = d1 * ((ql[l] & 0xF) + (qh[l] & u1 ? 16 : 0)) - m1 + for l in 0..31: y++ = d2 * ((ql[l] >> 4) + (qh[l] & u2 ? 16 : 0)) - m2 + ql += 32 ; is += 2 ; u1 <<= 2 ; u2 <<= 2 + + Identical in shape to `Q4_K` - same `get_scale_min_k4`, same 8 groups of 32, same low-nibbles-then-high + order - with a 5th bit added. `qh` does NOT advance inside the loop: the same 32 bytes are re-read by + all four 64-element steps, and what selects a distinct bit each time is `u1`/`u2` walking 1,4,16,64 and + 2,8,32,128. This is the Q3_K hmask trap again, and it is why the masks are written out rather than the + high bit being folded into `ql` once. + """ + n = len(raw) // 176 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 176) + d = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + dmin = np.ascontiguousarray(a[:, 2:4]).view(np.float16).astype(np.float32).reshape(-1) + scb = a[:, 4:16] # scales[K_SCALE_SIZE] - the same packed 6-bit pairs + qh = a[:, 16:48] # qh[QK_K/8] + qs = a[:, 48:176] # qs[QK_K/2] + + scales = np.empty((n, 8), dtype=np.float32) + offsets = np.empty((n, 8), dtype=np.float32) + for g in range(8): + sc = np.array([get_scale_min_k4(scb[i], g)[0] for i in range(n)], dtype=np.float32) + m = np.array([get_scale_min_k4(scb[i], g)[1] for i in range(n)], dtype=np.float32) + scales[:, g] = d * sc + offsets[:, g] = -(dmin * m) + + codes = np.empty((n, 256), dtype=np.uint8) + for j in range(4): + blk = qs[:, j * 32:(j + 1) * 32] + u1, u2 = 1 << (2 * j), 2 << (2 * j) + lo = (blk & 0x0F) + np.where(qh & u1, 16, 0).astype(np.uint8) + hi = (blk >> 4) + np.where(qh & u2, 16, 0).astype(np.uint8) + codes[:, j * 64:j * 64 + 32] = lo # group is+0: LOW nibbles + codes[:, j * 64 + 32:j * 64 + 64] = hi # group is+1: HIGH nibbles + return codes, scales, offsets + + +def from_s8_q5_k(parts): + codes, scales, offsets = parts + v = codes.astype(np.float32).reshape(codes.shape[0], 8, 32) + return (v * scales[:, :, None] + offsets[:, :, None]).reshape(-1) + + +def to_s8_q6_K(raw: bytes): + """`Q6_K` -> S8: 16 groups of 16, `scale = d*sc` with an int8 `sc`, codebook bias `-32`. + + `dequantize_row_q6_K` (L1939): + d = fp16(x.d) + for n in {0, 128}: # ql += 64, qh += 32, sc += 8 per half + for l in 0..31: + is = l/16 + q1 = ((ql[l + 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32 + q2 = ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32 + q3 = ((ql[l + 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32 + q4 = ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32 + y[l + 0] = d * sc[is + 0] * q1 + y[l + 32] = d * sc[is + 2] * q2 + y[l + 64] = d * sc[is + 4] * q3 + y[l + 96] = d * sc[is + 6] * q4 + + Four quads are built from ONE `qh[l]`, two bits each, while the low nibbles come from `ql[l]` and + `ql[l+32]` - and then the quads land at STRIDES of 32, not contiguously: q1 fills `l+0`, q2 fills `l+32`, + q3 fills `l+64`, q4 fills `l+96`. So the scale index is not `l/16` in any simple reading of the quads; + what it works out to is `(element / 16) % 8` within the half, i.e. plain consecutive 16-element groups. + + Two arithmetic details decide bit-exactness. `d * sc[is] * q` associates LEFT, so the group scale is + `fl(d * float(sc))` and the value is one further multiply - not `fl(d * fl(sc*q))`. And `sc` is `int8_t`, + so a negative scale is a sign flip and must be preserved, which is why the scale plane is read signed. + """ + n = len(raw) // 210 + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, 210) + ql = a[:, 0:128] # ql[QK_K/2] + qh = a[:, 128:192] # qh[QK_K/4] + sc = a[:, 192:208].view(np.int8) # scales[QK_K/16], SIGNED + d = np.ascontiguousarray(a[:, 208:210]).view(np.float16).astype(np.float32).reshape(-1) + + scales = d[:, None] * sc.astype(np.float32) # `d * sc` first, the leftmost multiply + + codes = np.empty((n, 256), dtype=np.uint8) + for half in range(2): + qlb = ql[:, half * 64:(half + 1) * 64] + qhb = qh[:, half * 32:(half + 1) * 32] + # (nibble source, qh bit offset) for quads 1..4; nibble 0..31 then 32..63, low then high + quads = [(qlb[:, 0:32] & 0x0F, 0), (qlb[:, 32:64] & 0x0F, 2), + (qlb[:, 0:32] >> 4, 4), (qlb[:, 32:64] >> 4, 6)] + for qidx, (nib, sh) in enumerate(quads): + seg = nib | (((qhb >> sh) & 0x03) << 4) + codes[:, half * 128 + qidx * 32: half * 128 + qidx * 32 + 32] = seg + return codes, scales + + +def from_s8_q6_K(parts): + codes, scales = parts + v = (codes.astype(np.int32) - 32).astype(np.float32) + return (v.reshape(-1, 16, 16) * scales[:, :, None]).reshape(-1) + + +MAPPINGS_HEADER = None # the registry is built after the functions, at the end of the mappings section + + +# ---------------------------------------------------------------- the float types (P-forms) +def to_p32_f32(raw: bytes): + """`F32` -> P32: the identity. Every other mapping is measured against this one's triviality.""" + v = np.frombuffer(raw, dtype=" P32: a bf16 is the top 16 bits of an f32, so widening shifts left and is exact. + + P32 and not P16: bf16 has the f32 exponent range and fp16 does not, so an fp16 container would send + large-magnitude weights to infinity. This is the one case where the wider container is the SAFE one. + """ + v = np.frombuffer(raw, dtype=" P16: keep the fp16, widen only to decode. fp16 -> fp32 is always exact.""" + return np.frombuffer(raw, dtype="> 2t) & 3`. + + This used to return the 16 PACKED bytes per block instead. It passed every check it was given, because + `from_s2` unpacked them again, and it was still wrong: `codes.size` is what the pack reads as a tensor's + element count, and for Q2_0 that came out at 1/4 of the truth. A representation that is only correct + when read back by its own decoder is not a canonical form - a pack has to be able to state the element + count on its own. + """ + n = len(raw) // BLOCK_BYTES + a = np.frombuffer(raw, dtype=np.uint8).reshape(n, BLOCK_BYTES) + scales = np.ascontiguousarray(a[:, 0:2]).view(np.float16).astype(np.float32).reshape(-1) + qb = a[:, 2:BLOCK_BYTES] # (n, 16) packed 2-bit codes + codes = np.empty((n, QK), dtype=np.uint8) + for t in range(4): + codes[:, t::4] = (qb >> (2 * t)) & 0x03 + return np.ascontiguousarray(codes), scales + + +def from_s2(parts): + """The decode a kernel would do. Transcribed from `dequantize_row_q2_0`, including the `- 1`. + + One integer subtract then ONE f32 multiply, in that order, for the reason docs/pack-format.md §3.1 gives: + folding the bias into the value domain is not bit-exact. + """ + codes, scales = parts + v = (codes.astype(np.int32) - 1).astype(np.float32) + return (v.reshape(-1, QK) * scales[:, None]).reshape(-1) + + +# The registry lives AFTER the functions it names. It has to: a module-level dict referencing `to_s2` +# before `to_s2` exists raises NameError at import, which is a mistake worth not repeating. +MAPPINGS = { + "Q2_0": Mapping(to_s2, from_s2, 18, 64, 64, "S2", None, -1, False), + "Q3_K": Mapping(to_s4_q3_k, from_s4_q3_k, 110, 256, 16, "S4", None, -4, False), + "Q4_0": Mapping(to_s4_q4_0, from_s4_q4_0, 18, 32, 32, "S4", None, -8, False), + "Q4_K": Mapping(to_s4_q4_k, from_s4_q4_k, 144, 256, 32, "S4", None, 0, True), + "Q5_0": Mapping(to_s8_q5_0, from_s8_q5_0, 22, 32, 32, "S8", None, -16, False), + "Q5_K": Mapping(to_s8_q5_k, from_s8_q5_k, 176, 256, 32, "S8", None, 0, True), + "Q6_K": Mapping(to_s8_q6_K, from_s8_q6_K, 210, 256, 16, "S8", None, -32, False), + "Q8_0": Mapping(to_s8_q8_0, from_s8_q8_0, 34, 32, 32, "S8", None, -128, False), + "IQ4_NL": Mapping(to_s4_iq4_nl, from_s4_iq4_nl, 18, 32, 32, "S4", "IQ4NL", 0, False), + "IQ4_XS": Mapping(to_s4_iq4_xs, from_s4_iq4_xs, 136, 256, 32, "S4", "IQ4NL", 0, False), + "F32": Mapping(to_p32_f32, from_p32_f32, 4, 1, 1, "P32", None, 0, False), + "BF16": Mapping(to_p32_bf16, from_p32_bf16, 2, 1, 1, "P32", None, 0, False), + "F16": Mapping(to_p16_f16, from_p16_f16, 2, 1, 1, "P16", None, 0, False), +} + + +def reference_values(tname: str, raw: bytes): + """The value this block MUST decode to - from an implementation other than the one under test. + + Q2_0 goes through `gguf_writer.dequantize_q2_0` and everything else through gguf-py, both reached via + `_dequant_flat`. The three float types are the exception and have to bypass it: `_dequant_flat` handles + them with this project's OWN `_bf16_to_f32` and numpy views, so for those the project's reference would + be checking itself. gguf-py implements all three independently, so it is used directly here. + """ + buf = np.frombuffer(raw, dtype=np.uint8) + if tname in ("F32", "F16", "BF16"): + from gguf import quants, GGMLQuantizationType as Q + return np.asarray(quants.dequantize(buf, Q[tname]), dtype=np.float32) + return np.asarray(_dequant_flat(tname, buf), dtype=np.float32) + + +def reference_name(tname: str) -> str: + """Which implementation the comparison is against - printed, because these are NOT equally strong. + + `gguf-py` is an independent implementation of the same C source. `project` is this project's own + decoder, so a pass there is a self-consistency result: it cannot detect a misreading of the format that + the decoder and the canonicaliser share. Q2_0 is the only `project` row and it is 31.64 GiB of the + artifact, so the distinction matters and is therefore never left implicit. + """ + return "project (Q2_0 decoder) - SELF-CONSISTENCY, oracle-backed by dequant_xcheck" \ + if tname == "Q2_0" else "gguf-py" + + +def open_shard(path): + """mmap the shard read-only. Slices of an mmap are ordinary bytes, which is all the reference needs. + + This replaced `fh.read()`, which loaded all 37.6 GB of shard 1 into RAM. It worked, which is exactly why + it was worth removing: a tool that only survives because the machine has 64 GB is not a tool that reports + its own limits, and it would have gone unnoticed until a machine with less memory ran it. + """ + fh = open(path, "rb") + mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) + return mm, mm.size() + + +def data_section_offset(f, filelen: int) -> int: + """Byte offset of the tensor data, from the tensor table alone. + + `filelen - max(offset + expected_bytes)` needs no header parsing and no dependency on ref/load.py's + private accessors. + """ + return filelen - max(x.offset + (x.expected_bytes() or 0) for x in f.tensors) + + +def run_full(args) -> int: + """P1.T3 over the WHOLE artifact: every block of every tensor, streamed. + + P1.T3 is stated as "for every tensor of the real GGUF, dequant(canonical) == dequant_ggml(original) bit + for bit". A per-block identity is a pure function of that block's bytes, so a sample of blocks can only + ever be evidence ABOUT a subset; this mode removes the qualifier. It also reports the DATA-DEPENDENT + branches each type actually exercised, because those are the paths a sample can miss entirely: a scale + that never reaches 16 never tests the high bits of `IQ4_XS`'s `ls`, and an hmask whose top nibble is never + set never tests `Q3_K`'s second-half mask. + """ + f = G.GGUFFile(pathlib.Path(args.gguf)) + head, filelen = open_shard(args.gguf) + data_off = data_section_offset(f, filelen) + print("shard %s: %d tensors, data at byte %d" % (args.gguf, len(f.tensors), data_off)) + + by_type = collections.defaultdict(list) + want = {s.strip() for s in args.types.split(",")} + si, sn = (int(x) for x in args.split.split("/")) + if not 0 <= si < sn: + print("--split %s: need 0 <= I < N" % args.split) + return 2 + # One index over ALL tensors, not per type: a per-type split would put the whole of a 202-tensor type + # in one process and leave the others idle. + for idx, t in enumerate(f.tensors): + if idx % sn == si: + by_type[t.type_name].append(t) + if sn > 1: + print("split %d/%d: %d of %d tensors in this process" + % (si, sn, sum(len(v) for v in by_type.values()), len(f.tensors))) + for tn in sorted(by_type): + if tn not in MAPPINGS: + print(" %-8s %5d tensors NO MAPPING - not covered" % (tn, len(by_type[tn]))) + elif tn not in want: + print(" %-8s %5d tensors EXCLUDED by --types" % (tn, len(by_type[tn]))) + + total_t = total_b = total_bad = 0 + ok = True + for tname in sorted(by_type): + if tname not in MAPPINGS or tname not in want: + continue + m = MAPPINGS[tname] + nblocks_sec = max(1, args.chunk // m.block_bytes) # WHOLE blocks per chunk + n_t = n_b = n_bad = 0 + t0 = time.time() + seen = collections.Counter() + for t in by_type[tname]: + if t.elements % m.block_elems: + print(" %-34s %d elements not a multiple of %d - SKIPPED" % (t.name, t.elements, m.block_elems)) + ok = False + continue + nb = t.elements // m.block_elems + base = data_off + t.offset + first_bad = None + for s in range(0, nb, nblocks_sec): + cnt = min(nblocks_sec, nb - s) + raw = head[base + s * m.block_bytes: base + (s + cnt) * m.block_bytes] + if len(raw) != cnt * m.block_bytes: + print(" %-34s SHORT READ at block %d - instrument error" % (t.name, s)) + ok = False + break + ref = reference_values(tname, raw) + got = m.dec(m.enc(raw)) + if ref.shape != got.shape: + print(" %-34s SHAPE %s vs %s - instrument error" % (t.name, ref.shape, got.shape)) + ok = False + break + ne = np.nonzero(ref != got)[0] + n_b += cnt + if ne.size: + n_bad += ne.size + if first_bad is None: + first_bad = (s + int(ne[0]) // m.block_elems, int(ne[0])) + if args.branches: + codes = m.enc(raw)[0] + seen["code_hi=%d" % int(codes.max())] += 1 + seen["code_lo=%d" % int(codes.min())] += 1 + n_t += 1 + if first_bad is not None: + print(" %-34s FIRST MISMATCH at block %d element %d" % (t.name, first_bad[0], first_bad[1])) + ok = False + dt = time.time() - t0 + total_t += n_t + total_b += n_b + total_bad += n_bad + print(" %-8s %5d tensors %9d blocks %s %6.1fs ref=%s" + % (tname, n_t, n_b, "BIT-EXACT" if not n_bad else "*** %d BAD ***" % n_bad, dt, + reference_name(tname))) + if args.branches and seen: + print(" branch reach: %s" % " ".join("%s x%d" % kv for kv in sorted(seen.items()))) + print() + print("P1.T3 full: %d tensors, %d blocks, %d mismatched elements" % (total_t, total_b, total_bad)) + print("tools/canonical_xcheck.py --full " + ("PASS" if ok else "FAIL")) + return 0 if ok else 1 + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--gguf", default=SHARD1) + ap.add_argument("--types", default=",".join(MAPPINGS), + help="source types to test, one mapping each; default is every mapped type") + ap.add_argument("--tensors", type=int, default=2, help="tensors per type") + ap.add_argument("--blocks", type=int, default=2048, help="blocks per tensor") + ap.add_argument("--full", action="store_true", + help="P1.T3 over every block of every tensor (overrides --tensors/--blocks)") + ap.add_argument("--chunk", type=int, default=64 << 20, help="bytes of source per streaming step") + ap.add_argument("--branches", action="store_true", help="report code range reached per type") + ap.add_argument("--split", default="0/1", + help="I/N: process only tensors whose index %% N == I, so N processes can share the " + "work. Q2_0's reference is a pure-Python loop at ~1.7 MB/s and Q2_0 is 34 GB of " + "the shard, so the full run is single-core-bound and worth splitting.") + args = ap.parse_args() + if args.full: + return run_full(args) + + f = G.GGUFFile(pathlib.Path(args.gguf)) + print("shard: %d tensors" % len(f.tensors)) + head, filelen = open_shard(args.gguf) + data_off = data_section_offset(f, filelen) + print("data section starts at byte %d (file %d bytes)" % (data_off, filelen)) + + ok = True + covered = 0 + for tname in args.types.split(","): + tname = tname.strip() + if tname not in MAPPINGS: + print(" %s: NO MAPPING in this tool yet" % tname) + continue + m = MAPPINGS[tname] + tensors = [t for t in f.tensors if t.type_name == tname] + covered += len(tensors) + print() + print("--- %s -> %s codebook=%s bias=%d offset=%s group=%d (%d tensors in the shard) ---" + % (tname, m.form, m.codebook or "affine", m.code_bias, m.has_offset, + m.group_elems, len(tensors))) + for t in tensors[: args.tensors]: + if t.elements % m.block_elems: + print(" %-34s %d elements is not a whole number of %d-element blocks - SKIPPED" + % (t.name, t.elements, m.block_elems)) + continue + want = min(args.blocks, t.elements // m.block_elems) * m.block_bytes + byte_off = data_off + t.offset + raw = head[byte_off: byte_off + want] + if len(raw) < want: + print(" %-34s SHORT READ (%d of %d) - instrument error" % (t.name, len(raw), want)) + ok = False + continue + ref = reference_values(tname, raw) + parts = m.enc(raw) + got = m.dec(parts) + if ref.shape != got.shape: + print(" %-34s SHAPE %s ref vs %s got - instrument error" % (t.name, ref.shape, got.shape)) + ok = False + continue + same = np.array_equal(ref, got) + d = np.abs(ref.astype(np.float64) - got.astype(np.float64)) + print(" %-34s %6d blocks %s max|d| %.3e" + % (t.name, want // m.block_bytes, "BIT-EXACT" if same else "*** MISMATCH ***", d.max())) + if not same: + bad = np.nonzero(ref != got)[0] + print(" first differing element %d: ref %r got %r" % (bad[0], ref[bad[0]], got[bad[0]])) + ok = False + if m.block_elems <= 256: # a value set is informative for a quantized block, noise for f32 + vals = np.unique(got[: m.block_elems]) + print(" first block's value set: %s" % np.array2string(vals, precision=6)) + print() + print("mapped types cover %d of %d tensors in this shard" % (covered, len(f.tensors))) + print("tools/canonical_xcheck.py " + ("PASS" if ok else "FAIL")) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/tools/conversation_cache_disabled.py b/engine/strata/tools/conversation_cache_disabled.py new file mode 100644 index 00000000..cf814043 --- /dev/null +++ b/engine/strata/tools/conversation_cache_disabled.py @@ -0,0 +1,196 @@ +"""Compare untouched upstream with cache-disabled engines; dry-run by default. + +Private engines run sequentially in an exclusive GPU window. This is a correctness +gate, not a throughput benchmark: state fingerprinting adds diagnostic overhead. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import load_tokenizer, require +from conversation_cache_soak import answer_text +from serve.frontend import ChatTemplate +from serve.server import StrataEngine, child_env + +NAMES = ('short', 'A', 'A-live', 'A-checkpoint', 'B', 'A-return', 'B-return', 'A-return-again') +# (not 'version': the gate also compares a new release with the previous one, where only the version differs) +SETTINGS = ('context', 'kv', 'kv_resident', 'expert_slots', 'spec', + 'mtp_max', 'lookup', 'cvec', 'pcie_frac', 'spec_min_p', 'pool_workers') +# Untouched upstream does not emit the indexer `dead` and `pooled_full` fields +# added by this PR; `pooled` is the completed-row extent in both engines. +# Draft scratch and unused page padding are not comparable authoritative state. +STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'pooled', 'kv', 'ple_prev') + + +def state_hashes(text, *, candidate=False): + hashes = [] + for line in text.splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + require(set(STATE_KEYS) <= fields.keys(), 'missing upstream-compatible state fields') + if candidate: + # Evidence that the candidate is a build with this change: it + # also fingerprints the spare row (compared by the cache-on gates). + require('pooled_full' in fields, 'candidate lacks the pooled_full fingerprint') + hashes.append({key: fields[key] for key in STATE_KEYS}) + return hashes + + +def common_args(cfg, spec): + # Upstream has no conversation-cache options. Omit them from EVERY arm so + # the candidates exercise their disabled default with identical arguments. + args, i = [], 0 + while i < len(cfg['args']): + arg = cfg['args'][i] + if arg.startswith('--conversation-cache-'): + require(i + 1 < len(cfg['args']), 'cache option lacks a value') + i += 2 + else: + args.append(arg) + i += 1 + return args + ['--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)), + '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] + + +def verify(results): + arms = results['arms'] + require(len(arms) >= 2 and arms[0]['name'] == 'upstream', 'missing comparison arms') + baseline = arms[0] + requests = results['requests'] + require([r['name'] for r in requests] == list(NAMES), 'incomplete request sequence') + require(all(r['ids'] and r['max_new'] > 0 for r in requests), 'empty request') + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + require(digest == results['request_digest'], 'request evidence changed') + for arm in arms: + require(arm['args'] == baseline['args'], 'engine arguments differ') + require(arm['request_digest'] == results['request_digest'], 'input requests differ') + require([r['name'] for r in arm['records']] == list(NAMES), 'incomplete output sequence') + require(not arm['cache_events'], 'disabled cache performed snapshot operations') + for key in SETTINGS: + require(key in arm['info'] and arm['info'][key] == baseline['info'][key], + f'{arm["name"]}: resolved setting differs: {key}') + if arm['name'] != 'upstream': + require(arm['info'].get('conversation_cache_mib') == 0, 'RAM cache not disabled') + require(arm['info'].get('conversation_disk_mib', 0) == 0, 'disk cache not disabled') + for request, reference, record in zip(requests, baseline['records'], arm['records']): + require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation') + require(set(STATE_KEYS) <= record['state'].keys(), 'incomplete state fingerprint') + require(record['ids'] == reference['ids'], f'{arm["name"]}/{record["name"]}: output differs') + require(record['state'] == reference['state'], f'{arm["name"]}/{record["name"]}: state differs') + require(record['reused'] == reference['reused'], 'prefix reuse differs') + require(record['prompt_tokens'] == len(request['ids']), 'wrong prompt length') + if request.get('expected'): + require(answer_text(record['text']) == request['expected'].casefold(), 'known answer is wrong') + records = {r['name']: r for r in arm['records']} + require(records['A-live']['reused'] > 0 and records['A-checkpoint']['reused'] > 0, + 'continuation/checkpoint path not exercised') + require(records['A-return']['reused'] == records['A-return-again']['reused'] == 0, + 'conversation switching did not force cold fallback') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--upstream', type=Path, required=True) + ap.add_argument('--candidate', type=Path, action='append', required=True) + ap.add_argument('--output', type=Path, required=True, help='new directory; existing paths refused') + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--spec', type=int, choices=(1, 4), default=1) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.paragraphs < 1: + ap.error('paragraphs must be positive') + if not a.run: + print('Dry run: upstream and disabled candidates; identical inputs/settings, known answers and state parity.') + return + cfg = json.loads(a.config.read_text(encoding='utf-8')) + tok_path = Path(cfg['tokenizer']) + tok = load_tokenizer(tok_path) + tpl_path = tok_path / 'chat_template.jinja' + tpl = ChatTemplate(tpl_path if tpl_path.exists() else ROOT / 'serve/chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False)) + text = 'Conversation A. Remember the exact code AZURE-314159.\n' + text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + A = prompt(text + '\nThe exact code to remember is AZURE-314159. Reply OK.') + B = prompt('Unrelated conversation B. Remember BRONZE-271828. Reply OK.') + suffix = encode('<|im_end|>\n<|im_start|>user\nWhat exact code did I ask you to remember? ' + 'Reply with only that code.<|im_end|>\n<|im_start|>assistant\n\n\n\n\n') + args = common_args(cfg, a.spec) + env = child_env(cfg) + env.pop('STRATA_SNAPSHOT_VERIFY', None) + env['STRATA_STATE_HASH'] = '1' + env['STRATA_MTP_BATCH'] = '1' + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + results = {'config': cfg, 'paragraphs': a.paragraphs, 'spec': a.spec, 'arms': [], 'requests': [], + 'compared_state_fields': STATE_KEYS, + 'environment': {k: v for k, v in env.items() if k.startswith('STRATA_')}} + for index, exe in enumerate([a.upstream, *a.candidate]): + name = 'upstream' if index == 0 else f'candidate-{index}' + log = a.output / f'{name}.log' + print(f'START {name}: {exe}', flush=True) + started = time.monotonic() + engine = StrataEngine(str(exe.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env) + arm = {'name': name, 'exe': str(exe.resolve()), 'args': args, 'info': dict(engine.info), + 'startup_seconds': time.monotonic() - started, 'records': []} + with exe.open('rb') as source: + arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest() + def generate(request): + ids = [t for t in engine.generate(request['ids'], request['max_new'], {'temperature': 0}, + threading.Event()) if t is not None] + arm['records'].append({'name': request['name'], 'ids': ids, **engine.last, + 'text': tok.decode(ids)}) + return ids + try: + if index == 0: + def add(name, ids, max_new, expected=None): + request = dict(name=name, ids=ids, max_new=max_new, expected=expected) + results['requests'].append(request) + return generate(request) + add('short', prompt('What is 2 + 2? Reply with only the number.'), 16, '4') + head = add('A', A, 1) + require(len(head) == 1, 'A must produce one token') + continuation = A + head + suffix + add('A-live', continuation, 32, 'AZURE-314159') + add('A-checkpoint', continuation, 32, 'AZURE-314159') + add('B', B, 1) + add('A-return', continuation, 32, 'AZURE-314159') + add('B-return', B, 1) + add('A-return-again', continuation, 32, 'AZURE-314159') + payload = json.dumps(results['requests'], sort_keys=True).encode() + results['request_digest'] = hashlib.sha256(payload).hexdigest() + (a.output / 'requests.json').write_bytes(payload) + else: + for request in results['requests']: + generate(request) + finally: + engine.close() + engine.proc.wait(timeout=30) + engine.log.close() + arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + log_text = log.read_text(encoding='utf-8') + hashes = state_hashes(log_text, candidate=index != 0) + require(len(hashes) == len(arm['records']), f'{name}: missing state hashes') + for record, fingerprint in zip(arm['records'], hashes): + record['state'] = fingerprint + arm['cache_events'] = [line for line in log_text.splitlines() if any(mark in line for mark in + ('conversation cache: parked', 'disk cache: spilled', 'SNAPSHOT_VERIFY'))] + results['arms'].append(arm) + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + print(f'DONE {name}', flush=True) + verify(results) + (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n') + print('PASS: untouched upstream versus disabled engines; identical tokens, main state, reuse and known answers') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/conversation_cache_growth.py b/engine/strata/tools/conversation_cache_growth.py new file mode 100644 index 00000000..f52cef83 --- /dev/null +++ b/engine/strata/tools/conversation_cache_growth.py @@ -0,0 +1,170 @@ +"""Compare full and incremental snapshot capture during growth and rewind. + +Private engines run sequentially; dry-run is the default. Both arms enable the +same conversation cache. The reference forces full capture for every parking. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, load_tokenizer, require, state_hashes +from conversation_cache_disabled import SETTINGS, common_args +from conversation_cache_soak import answer_text +from serve.frontend import ChatTemplate +from serve.server import StrataEngine, child_env + +NAMES = ['A', 'B-0', 'A-grow-0', 'B-1', 'A-grow-1', 'B-2', 'A-grow-2', + 'B-rewind', 'A-rewind', 'B-branch', 'A-branch', 'B-final'] +SECRET = 'SAPPHIRE' + + +def verify(results): + full, incremental = results['arms'] + require(full['name'] == 'full' and incremental['name'] == 'incremental', 'incorrect comparison arms') + requests = results['requests'] + require([r['name'] for r in requests] == NAMES, 'incomplete growth/rewind requests') + require(all(r['ids'] and r['max_new'] > 0 for r in requests), 'empty growth request') + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + require(digest == results['request_digest'], 'request evidence changed') + for arm in (full, incremental): + require(arm['request_digest'] == digest and arm['args'] == full['args'], 'inputs or arguments differ') + require(arm['exe_sha256'] == full['exe_sha256'], 'executable changed between comparison arms') + require([r['name'] for r in arm['records']] == NAMES, 'incomplete growth/rewind outputs') + for key in (*SETTINGS, 'conversation_cache_mib', 'conversation_cache_slots'): + require(key in arm['info'] and arm['info'][key] == full['info'][key], f'engine setting differs: {key}') + require(arm['info']['conversation_cache_mib'] == results['cache_mib'] > 0, 'cache budget differs') + budget = arm['info']['conversation_cache_mib'] * 1024 * 1024 + require(arm['parks'] and all(0 < p['snapshot_bytes'] <= p['bytes'] <= budget and + 0 <= p['reused_kv_bytes'] <= p['snapshot_bytes'] for p in arm['parks']), 'invalid allocation/reuse evidence') + require(arm['draft_verifications'] >= 4, 'missing restored draft read-back') + for request, reference, record in zip(requests, full['records'], arm['records']): + require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation') + require(record['ids'] == reference['ids'], f'{record["name"]}: output differs') + require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == reference['state'], + f'{record["name"]}: state differs or is incomplete') + require(record['reused'] == reference['reused'], 'prefix reuse differs') + require(record['prompt_tokens'] == len(request['ids']), 'prompt length differs') + if record['name'].startswith('A-'): + require(answer_text(record['text']) == SECRET.casefold(), 'known answer differs') + require(record['reused'] > 0, 'conversation was not restored') + require(all(p['reused_kv_bytes'] == 0 for p in full['parks']), 'reference did not force full captures') + require(sum(p['reused_kv_bytes'] > 0 for p in incremental['parks']) >= 3, 'repeated parking did not reuse KV bytes') + sizes = {r['name']: len(r['ids']) for r in requests} + require(sizes['A'] < sizes['A-grow-0'] < sizes['A-grow-1'] < sizes['A-grow-2'], 'conversation did not grow') + require(sizes['A-rewind'] == sizes['A-grow-0'] < sizes['A-grow-2'], 'missing rewind') + require(sizes['A-branch'] > sizes['A-rewind'], 'missing growth after rewind') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new output directory') + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--spec', type=int, choices=(1, 4), default=1) + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.paragraphs < 1 or a.cache_mib < 1: + ap.error('paragraphs and cache-mib must be positive') + if not a.run: + print('Dry run: paired full/incremental captures; growth, interruption, rewind and branch; no model loaded.') + return + cfg = json.loads(a.config.read_text(encoding='utf-8')) + tok_path = Path(cfg['tokenizer']) + tok = load_tokenizer(tok_path) + template = ChatTemplate(tok_path / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False)) + text = f'Remember the secret code {SECRET}.\n' + text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + initial = prompt(text + f'\nThe secret code is {SECRET}. Reply OK.') + other = prompt('Unrelated worker. Reply HELLO.') + end = encode('<|im_end|>') + def continuation(ids, output, step): + close = [] if output[-len(end):] == end else end + filler = '\n'.join(f'Additional record {step}-{i}: blue square and green triangle.' for i in range(24)) + return ids + output + close + encode('\n<|im_start|>user\n' + filler + + '\nWhat is the secret code? Reply with only that word.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + args = common_args(cfg, a.spec) + ['--conversation-cache-mib', str(a.cache_mib), '--conversation-cache-slots', '4'] + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + env['STRATA_SNAPSHOT_VERIFY'] = '1' + env['STRATA_MTP_BATCH'] = '1' + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + results = {'requests': [], 'arms': [], 'spec': a.spec, 'paragraphs': a.paragraphs, 'cache_mib': a.cache_mib} + for name in ('full', 'incremental'): + current_env = dict(env) + if name == 'full': + current_env['STRATA_SNAPSHOT_FULL_CAPTURE'] = '1' + else: + current_env.pop('STRATA_SNAPSHOT_FULL_CAPTURE', None) + print('START', name, flush=True) + log = a.output / (name + '.log') + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=current_env) + arm = {'name': name, 'args': args, 'info': dict(engine.info), 'records': []} + with a.engine.open('rb') as source: + arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest() + def generate(request): + ids = [x for x in engine.generate(request['ids'], request['max_new'], {'temperature': 0}, + threading.Event()) if x is not None] + arm['records'].append({'name': request['name'], 'ids': ids, 'text': tok.decode(ids), **engine.last}) + return ids + try: + if name == 'full': + def add(label, ids, count, expected=False): + request = {'name': label, 'ids': ids, 'max_new': count, 'expected': expected} + results['requests'].append(request) + return generate(request) + ids = initial + output = add('A', ids, 1) + first_growth = None + for step in range(3): + add(f'B-{step}', other, 1) + ids = continuation(ids, output, step) + if step == 0: + first_growth = list(ids) + output = add(f'A-grow-{step}', ids, 16, True) + add('B-rewind', other, 1) + output = add('A-rewind', first_growth, 16, True) + add('B-branch', other, 1) + add('A-branch', continuation(first_growth, output, 'branch'), 16, True) + add('B-final', other, 1) + results['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + else: + for request in results['requests']: + generate(request) + finally: + engine.close() + engine.proc.wait(timeout=30) + engine.log.close() + log_text = log.read_text(encoding='utf-8') + hashes = state_hashes(log_text) + require(len(hashes) == len(arm['records']), 'missing state fingerprints') + for record, state in zip(arm['records'], hashes): + record['state'] = state + parks = re.findall(r'conversation cache: parked (\d+) tokens in ([\d.]+) ms; parked=\d+ bytes=(\d+) ' + r'evictions=\d+ snapshot_bytes=(\d+) reused_kv_bytes=(\d+)', log_text) + arm['parks'] = [dict(tokens=int(p[0]), ms=float(p[1]), bytes=int(p[2]), snapshot_bytes=int(p[3]), + reused_kv_bytes=int(p[4])) for p in parks] + arm['draft_verifications'] = log_text.count('SNAPSHOT_VERIFY draft=') + arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest() + results['arms'].append(arm) + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + print('DONE', name, flush=True) + verify(results) + (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n') + print('PASS: growth and rewind preserve output/state; repeated captures reuse unchanged KV bytes') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/conversation_cache_http_smoke.py b/engine/strata/tools/conversation_cache_http_smoke.py new file mode 100644 index 00000000..bd1df98c --- /dev/null +++ b/engine/strata/tools/conversation_cache_http_smoke.py @@ -0,0 +1,137 @@ +"""Destructive-to-cache HTTP smoke test for an EXCLUSIVE, idle Strata test server. + +Sends synthetic conversations, deliberately evicts cached conversations, and +disconnects a streaming response. Never run while other clients are using it. +Dry-run by default; --run explicitly enables network traffic. Does not restart +or reconfigure the server. Use the private-engine parity gate for state hashes. +""" +import argparse +import json +from pathlib import Path +import time +import urllib.request +import uuid + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +class Client: + def __init__(self, url): + self.url = url.rstrip('/') + + def metrics(self): + with urllib.request.urlopen(self.url + '/metrics', timeout=10) as response: + return json.load(response) + + def request(self, model, content, stream=False, count=8): + body = {'model': model, 'messages': [{'role': 'user', 'content': content}], + 'max_tokens': count, 'temperature': 0, 'stream': stream, + 'chat_template_kwargs': {'enable_thinking': False}} + request = urllib.request.Request(self.url + '/v1/chat/completions', + data=json.dumps(body).encode(), + headers={'Content-Type': 'application/json'}) + return urllib.request.urlopen(request, timeout=120) + + +def run(client): + initial = client.metrics() + require(initial['live']['state'] == 'idle' and initial['live']['queued'] == 0, 'server is busy') + info = initial['engine'] + slots = info.get('conversation_cache_slots', 0) + require(info.get('conversation_cache_mib', 0) > 0 and 1 <= slots <= 16, + 'requires an enabled cache with 1–16 slots') + require(not info.get('api_key'), 'use an unauthenticated private test endpoint') + marker = 'cache-smoke-' + uuid.uuid4().hex + records = [] + + def before(): + metrics = client.metrics() + require(metrics['live']['state'] == 'idle' and metrics['live']['queued'] == 0, + 'concurrent client detected') + return max((r['time'] for r in metrics['requests']), default=0) + + def after(stamp, label): + for _ in range(50): + metrics = client.metrics() + if metrics['live']['state'] == 'idle': + break + time.sleep(.2) + require(metrics['live']['state'] == 'idle', 'request did not drain') + fresh = [r for r in metrics['requests'] if r['time'] > stamp] + require(len(fresh) == 1 and metrics['live']['queued'] == 0, + 'missing request evidence or concurrent traffic') + record = {'name': label, **fresh[0]} + records.append(record) + return record + + def prompt(label): + return marker + ' ' + label + '\n' + '\n'.join( + f'Record {i}: blue square, green triangle, red circle.' for i in range(128) + ) + '\nName one color. Answer with one word.' + + def ask(label, content): + stamp = before() + with client.request(info['model'], content) as response: + result = json.load(response) + require(bool(result.get('choices')), 'missing completion') + record = after(stamp, label) + require(record['finish'] in ('length', 'stop'), 'request did not finish normally') + return result['choices'][0]['message'], record + + a, _ = ask('A', prompt('A')) + ask('B', prompt('B')) + restored, record = ask('A-restored', prompt('A')) + require(record['reused'] > 0 and a == restored, 'A/B/A reuse or output mismatch') + for i in range(slots + 1): + ask(f'evict-{i}', prompt(f'evict-{i}')) + _, record = ask('A-evicted', prompt('A')) + require(record['reused'] == 0, 'old A survived slot eviction') + + text = marker + ' cancel: ' + 'blue green red. ' * 256 + text += '\nCount from 1 to 1000, one number per line. Do not summarize.' + stamp = before() + with client.request(info['model'], text, stream=True, count=4096) as response: + for line in response: + if not line.startswith(b'data: ') or line.strip() == b'data: [DONE]': + continue + choices = json.loads(line[6:]).get('choices', []) + if choices and choices[0].get('delta', {}).get('content'): + break + else: + raise RuntimeError('no streamed content to cancel') + record = after(stamp, 'cancelled') + require(record['finish'] in ('disconnect', 'cancel') and 0 < record['output_tokens'] < 4096, + 'stream cancellation not observed') + ask('after-cancel-B', marker + ' Unrelated B: say hello.') + _, record = ask('cancelled-A-restored', text) + require(record['reused'] > 0, 'cancelled conversation was not restored') + return {'engine_info': info, 'records': records} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--url', default='http://127.0.0.1:11434') + parser.add_argument('--output', type=Path, required=True, help='new results file; existing paths refused') + parser.add_argument('--run', action='store_true') + args = parser.parse_args() + if not args.run: + print('Dry run: HTTP A/B/A, slot eviction, cancellation and recovery. No network traffic.') + return + # Refuse accidental overwrites before generating traffic. + with args.output.open('x', encoding='utf-8') as output: + try: + result = run(Client(args.url)) + except Exception as error: + json.dump({'passed': False, 'error': str(error)}, output, indent=2) + output.write('\n') + raise + json.dump({'passed': True, **result}, output, indent=2) + output.write('\n') + print(f'PASS: HTTP reuse, slot eviction, cancellation/recovery. Results: {args.output}') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/conversation_cache_isolation.py b/engine/strata/tools/conversation_cache_isolation.py new file mode 100644 index 00000000..c0f0d52b --- /dev/null +++ b/engine/strata/tools/conversation_cache_isolation.py @@ -0,0 +1,147 @@ +"""Private-engine image/steering cache isolation gate; dry-run unless --run. + +Synthetic image embeddings exercise GENI, image identity and M-RoPE without an +image encoder. Synthetic nonzero control vectors exercise actual add/project +kernels. This validates cache correctness, not vision or steering quality. +""" +import argparse +import json +from pathlib import Path +import struct +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashes +from gguf_reader import GGUFFile +from gguf_writer import GGUFWriter +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate +import numpy as np + + +def fixtures(output, width): + vector = np.sin(np.arange(width, dtype=np.float32) * .17) + vector *= .25 / np.linalg.norm(vector) + writer = GGUFWriter() + writer.add('general.architecture', 'controlvector') + writer.add('controlvector.model_hint', 'qwen4exp') + writer.add_f32('direction.1', vector) + writer.add_f32('direction.20', vector) + writer.write(output / 'control.gguf') + rows = np.sin(np.arange(4 * width, dtype=np.float32) * .013).reshape(4, width) * .2 + for name, nx, ny, values in [('image-a', 2, 2, rows), ('image-b', 2, 2, -rows), + ('image-grid', 1, 4, rows)]: + with (output / (name + '.sve')).open('xb') as f: + f.write(struct.pack('<5i', 0x31455653, 4, nx, ny, width)) + f.write(values.astype(' 0 for i in hits), 'compatible parked state was not restored') + changed = 3 if scenario == 'image' else 1 + require(baseline[0]['state'] != baseline[changed]['state'], 'fixture did not change actual model state') + if scenario == 'image': + require(baseline[0]['state'] != baseline[5]['state'], 'grid fixture did not change M-RoPE state') + else: + require(results['engine_info']['candidate']['cvec'] != 0, 'control vector not loaded') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True) + ap.add_argument('--scenario', choices=('image', 'add', 'project'), required=True) + ap.add_argument('--run', action='store_true') + args = ap.parse_args() + # the fixtures are passed to an engine that runs in the config's cwd, not this shell's + args.output = args.output.resolve() + if not args.run: + print(f'Dry run: {args.scenario} isolation; no model loaded or files created.') + return + cfg = json.loads(args.config.read_text(encoding='utf-8')) + native = cfg['args'][cfg['args'].index('--native') + 1] + geometry = GGUFFile(native).metadata + width = geometry['qwen4exp.embedding_length'] + require(geometry['qwen4exp.block_count'] > 20, 'fixture requires layers 1 and 20') + p = Path(cfg['tokenizer']) + tok = load_tokenizer(p) + tpl = ChatTemplate(p / 'chat_template.jinja') + def encode(text): + return tok.encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False), parse_special=True) + image_tokens = '<|vision_start|>' + '<|image_pad|>' * 4 + '<|vision_end|>' + tail = '\n'.join(f'Record {i}: blue square and green triangle.' for i in range(64)) + A = encode('Conversation A: ' + (image_tokens if args.scenario == 'image' else '') + '\n' + tail) + B = encode('Unrelated conversation B: name a color.\n' + tail) + args.output.mkdir(mode=0o700, parents=False, exist_ok=False) + fixtures(args.output, width) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'engine_info': {}} + for label, budget in [('baseline', 0), ('candidate', 8192)]: + log = args.output / (label + '.log') + command = engine_args(cfg, budget, 1) + if args.scenario == 'image': + command += ['--vision'] + else: + command += ['--control-vector', str(args.output / 'control.gguf'), '--cvec-mode', args.scenario] + engine = StrataEngine(str(args.engine.resolve()), command, cwd=cfg.get('cwd'), log=str(log), env=env) + records = [] + results['engine_info'][label] = dict(engine.info) + def generate(name, ids, image=None, steering=True): + embeddings = str(args.output / (image + '.sve')) if image else None + out = [t for t in engine.generate(ids, 1, {'experimental_speed_projection': steering}, + threading.Event(), embeddings=embeddings) if t is not None] + records.append({'name': name, 'ids': out, **engine.last}) + try: + if args.scenario == 'image': + generate('image-A', A, 'image-a') + generate('text-B', B) + generate('image-A-return', A, 'image-a') + generate('image-B', A, 'image-b') + generate('image-A-again', A, 'image-a') + generate('grid-changed', A, 'image-grid') + generate('image-A-final', A, 'image-a') + else: + generate('off', A, steering=False) + generate('on', A) + generate('text-B', B) + generate('off-return', A, steering=False) + generate('on-return', A) + generate('off-again', A, steering=False) + finally: + engine.close() + hashes = state_hashes(log.read_text(encoding='utf-8')) + require(len(hashes) == len(records), 'missing isolation state hashes') + for record, state in zip(records, hashes): + record['state'] = state + results[label] = records + (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + verify(results, args.scenario) + print(f'PASS: {args.scenario} identity isolation, output and main-model state parity') + print(f'Results: {args.output / "results.json"}') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/conversation_cache_parity.py b/engine/strata/tools/conversation_cache_parity.py new file mode 100644 index 00000000..6e7b4fca --- /dev/null +++ b/engine/strata/tools/conversation_cache_parity.py @@ -0,0 +1,253 @@ +"""Full-model A/B/A parity gate. Loads private engines sequentially, never uses an existing server. + +Dry-run by default. --run requires an available GPU/model-loading window. +""" +import argparse +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate +import strata_tokenizer as ST + +# pooled: the completed indexer rows (the 0.1.29 extent); pooled_full: those plus the spare row +STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'dead', 'pooled', 'pooled_full', 'kv', 'ple_prev') + +def require(condition, message): + if not condition: + raise AssertionError(message) + + +def load_tokenizer(path): + vocab = json.loads((path / 'vocab.json').read_text(encoding='utf-8')) + tokens = [None] * len(vocab) + for token, index in vocab.items(): + tokens[index] = token + return ST.Tokenizer(tokens, (path / 'merges.txt').read_text(encoding='utf-8').split('\n'), + json.loads((path / 'token_type.json').read_text(encoding='utf-8'))) + + +def state_hashes(text): + # Padding and the drafter's final uncomputed cell aren't main-model state. + hashes = [] + for line in text.splitlines(): + if 'STATE_HASH L=' in line: + fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line)) + hashes.append({key: fields[key] for key in STATE_KEYS}) + return hashes + + +def engine_args(cfg, budget, spec): + # Native IQ packs require verifier capacity >= 2, even for one-token decode. + return list(cfg['args']) + [ + '--conversation-cache-mib', str(budget), '--conversation-cache-slots', '4', + '--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)), + '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0'] + + +def pressure_budget_hint(results, budget_mib): + sizes = [p['snapshot_bytes'] for p in results['pressure']['parks'] if p.get('snapshot_bytes', 0) > 0] + message = f'Configured --cache-mib {budget_mib}.' + if not sizes: + return message + ' No snapshot sizes recorded; use an engine that reports snapshot_bytes.' + mib = 1024 * 1024 + message += ' Observed snapshots: ' + ', '.join(f'{n / mib:.2f} MiB ({n} bytes)' for n in sizes) + '.' + if len(sizes) < 2: + return message + ' Need at least two captured snapshots to determine a pressure budget.' + # Fit every individual image but no adjacent pair in the A/B/C sequence. + low = (max(sizes) + mib - 1) // mib + high = (min(a + b for a, b in zip(sizes, sizes[1:])) - 1) // mib + if low <= high: + message += f' Use --cache-mib {low}..{high} to fit each snapshot but not two adjacent snapshots.' + else: + message += ' No whole-MiB budget fits every snapshot while excluding each adjacent pair; use similarly sized prompts.' + return message + + +def verify_pressure(results, budget_mib, oversized=False): + """Require actual byte-pressure evidence, not just correct output on misses.""" + baseline, candidate = results['baseline'], results['candidate'] + names = ['A', 'B', 'C', 'A-again'] + for records in (baseline, candidate): + require([r['name'] for r in records] == names, 'incomplete pressure sequence') + for before, after in zip(baseline, candidate): + require(len(before['ids']) == len(after['ids']) == 1, 'missing pressure output') + require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'), + 'pressure request did not finish normally') + require(before['reused'] == after['reused'] == 0, + 'pressure did not force a cache miss; this run did not exercise the required fallback. ' + + pressure_budget_hint(results, budget_mib)) + require(before['ids'] == after['ids'], 'pressure output differs') + keys = set(STATE_KEYS) + require(keys <= before['state'].keys() and keys <= after['state'].keys(), 'missing pressure state') + require(before['state'] == after['state'], 'pressure state differs') + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key], + f'pressure engine setting differs: {key}') + info = results['engine_info']['candidate'] + require(info['conversation_cache_mib'] == budget_mib and info['conversation_cache_slots'] == 4, + 'pressure cache configuration differs') + evidence = results['pressure'] + parks = evidence['parks'] + require(all(p['bytes'] <= budget_mib * 1024 * 1024 for p in parks), 'byte budget exceeded') + if oversized: + require(evidence['skips'] == 3 and not parks, 'oversized snapshots were not all skipped') + else: + require(evidence['skips'] == 0 and len(parks) == 3, 'snapshots must fit individually') + require(all(0 < p['parked'] < 4 for p in parks), 'slot pressure confounds byte-pressure test') + require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed. ' + + pressure_budget_hint(results, budget_mib)) + + +def verify_results(results, prompt_tokens, spec): + """Fail closed on incomplete evidence, even under python -O.""" + baseline, candidate = results['baseline'], results['candidate'] + require([r['name'] for r in baseline] == ['A', 'A+'], 'incomplete baseline') + require([r['name'] for r in candidate] == ['A', 'B', 'A+', 'B-again', 'A+-checkpoint'], 'incomplete candidate') + state_keys = set(STATE_KEYS) + for record in baseline + candidate: + require(bool(record['ids']), 'missing generated tokens') + require(record['finish'] in ('length', 'stop'), 'request did not finish normally') + require(state_keys <= record['state'].keys(), 'incomplete state fingerprint') + require(len(baseline[0]['ids']) == len(candidate[0]['ids']) == 1, 'invalid initial A output length') + require(baseline[0]['ids'] == candidate[0]['ids'], 'initial A output differs') + require(candidate[2]['reused'] >= prompt_tokens, 'A was not restored after B') + require(candidate[4]['reused'] > 0, 'parked checkpoint was not restored') + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key], + f'baseline/candidate engine setting differs: {key}') + for record in (candidate[2], candidate[4]): + require(record['ids'] == baseline[1]['ids'], 'restored continuation output differs') + if spec == 1: + require(record['state'] == baseline[1]['state'], 'restored main-model state differs') + + +def verify_exchange(results, prompt_tokens, spec, budget_mib): + verify_results(results, prompt_tokens, spec) + require(results['engine_info']['candidate']['conversation_cache_mib'] == budget_mib, + 'exchange cache budget differs') + evidence = results['pressure'] + require(evidence['skips'] == 2 and len(evidence['parks']) == 2, + 'expected two parks and two outgoing skips while an incoming snapshot is held') + require(all(p['parked'] == 1 and 0 < p['bytes'] <= budget_mib * 1024 * 1024 + for p in evidence['parks']), 'invalid exchange snapshot budget') + + +def verify_admission(results, budget_mib, floor_mib): + evidence = results['pressure'] + require(evidence['memory_skips'] == 3 and evidence['skips'] == 0 and not evidence['parks'], + 'expected physical-memory denial, not oversized-budget fallback') + require(results['engine_info']['candidate']['conversation_cache_min_free_mib'] == floor_mib, + 'physical RAM floor differs') + # The same four cold requests must preserve output and complete state. Reuse + # the oversized gate's no-parking assertions after checking the actual cause. + equivalent = {**results, 'pressure': {**evidence, 'skips': evidence['memory_skips']}} + verify_pressure(equivalent, budget_mib, oversized=True) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new private directory; existing paths refused') + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--paragraphs', type=int, default=128) + ap.add_argument('--scenario', choices=('reuse', 'pressure', 'oversized', 'exchange', 'admission'), default='reuse', + help='pressure requires snapshots fitting individually but not together; oversized requires none to fit') + ap.add_argument('--min-free-mib', type=int, default=2560, + help='physical RAM floor; for admission denial choose a value above available system RAM') + ap.add_argument('--spec', type=int, default=1, choices=range(1, 9), + help='decode window cap; 1 uses engine --spec 2 --mtp-max-t 1 for native IQ packs') + ap.add_argument('--run', action='store_true') + a = ap.parse_args() + if a.cache_mib <= 0 or a.paragraphs < 1 or not 0 <= a.min_free_mib <= (2**63 - 1) // (1024 * 1024): + ap.error('cache-mib/paragraphs must be positive and min-free-mib must fit the engine range') + if not a.run: + print(f'Dry run: {a.scenario}; paired baseline/candidate; fixed residency, greedy output.') + print('No model loaded. Use --run only with a separately available GPU/test window.') + return + cfg = json.loads(a.config.read_text(encoding='utf-8')) + p = Path(cfg['tokenizer']) + tok = load_tokenizer(p) + tpl = ChatTemplate(p / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(label): + text = label + ': remember this list.\n' + '\n'.join( + f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs)) + return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False)) + A, B, C = prompt('Conversation A'), prompt('Unrelated conversation B'), prompt('Distinct conversation C') + suffix = encode('<|im_end|>\n<|im_start|>user\nName a color from the list.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + a.output.mkdir(mode=0o700, parents=False, exist_ok=False) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'engine_info': {}} + for label, budget in [('baseline', 0), ('candidate', a.cache_mib)]: + log = a.output / f'{label}.log' + args = engine_args(cfg, budget, a.spec) + args += ['--conversation-cache-min-free-mib', str(a.min_free_mib)] + engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env) + results['engine_info'][label] = dict(engine.info) + records = [] + def generate(ids, count, name): + out = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] + records.append({'name': name, 'ids': out, **engine.last}) + return out + try: + # One output token leaves exactly A's prompt as the live prefix, + # avoiding the pre-existing accepted-draft output-cap overshoot. + if a.scenario in ('pressure', 'oversized', 'admission'): + generate(A, 1, 'A') + generate(B, 1, 'B') + generate(C, 1, 'C') + generate(A, 1, 'A-again') + else: + head = generate(A, 1, 'A') + continuation = A + head + suffix + if budget: + generate(B, 1, 'B') + generate(continuation, 8, 'A+') + if budget: + generate(B, 1, 'B-again') + generate(continuation, 8, 'A+-checkpoint') + finally: + engine.close() + hashes = state_hashes(log.read_text(encoding='utf-8')) + require(len(hashes) == len(records), 'missing state hashes') + for record, fingerprint in zip(records, hashes): + record['state'] = fingerprint + results[label] = records + if label == 'candidate' and a.scenario != 'reuse': + log_text = log.read_text(encoding='utf-8') + parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)(?: snapshot_bytes=(\d+))?', log_text) + results['pressure'] = { + 'parks': [dict(zip(('parked', 'bytes', 'evictions', 'snapshot_bytes'), + (int(value) if value else 0 for value in p))) for p in parks], + 'skips': log_text.count('conversation cache: skip parking (snapshot '), + 'memory_skips': log_text.count('conversation cache: skip parking (physical RAM admission;')} + (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + if a.scenario == 'pressure': + print(pressure_budget_hint(results, a.cache_mib), flush=True) + if a.scenario == 'admission': + verify_admission(results, a.cache_mib, a.min_free_mib) + print('PASS: physical-memory admission denial, output and byte-exact main-model state') + elif a.scenario == 'exchange': + verify_exchange(results, len(A), a.spec, a.cache_mib) + print('PASS: bounded incoming/outgoing exchange, A/B/A output and checkpoint reuse') + elif a.scenario == 'reuse': + verify_results(results, len(A), a.spec) + print('PASS: A/B/A output and checkpoint reuse' + (', byte-exact main-model state' if a.spec == 1 else '')) + else: + verify_pressure(results, a.cache_mib, a.scenario == 'oversized') + print(f'PASS: {a.scenario} fallback, output and byte-exact main-model state') + print(f'Results: {a.output / "results.json"}') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/conversation_cache_soak.py b/engine/strata/tools/conversation_cache_soak.py new file mode 100644 index 00000000..fc9bb0e5 --- /dev/null +++ b/engine/strata/tools/conversation_cache_soak.py @@ -0,0 +1,169 @@ +"""Private-engine known-answer A/B/A soak; dry-run by default. + +Loads paired engines sequentially. Requires an exclusive model/GPU window, not +an existing HTTP server. This is a synthetic cache gate, not a real-agent benchmark. +""" +import argparse +import json +from pathlib import Path +import re +import sys +import threading + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'tools')] +from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashes +from serve.server import StrataEngine, child_env +from serve.frontend import ChatTemplate + + +def answer_text(text): + return text.replace('<|im_end|>', '').replace('<|endoftext|>', '').strip().casefold() + + +def verify(results): + contexts, cycles = results['contexts'], results['cycles'] + count = results['requested_cycles'] + require(count >= 30 and len(cycles) == count, 'incomplete 30-cycle soak') + require(len(contexts) >= 3, 'need at least three context lengths') + require(len({c['prompt_tokens'] for c in contexts}) == len(contexts), 'context lengths are not distinct') + baseline, candidate = results['engine_info']['baseline'], results['engine_info']['candidate'] + for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'): + require(baseline[key] == candidate[key], f'engine setting differs: {key}') + require(baseline['conversation_cache_mib'] == 0 and candidate['conversation_cache_mib'] > 0, + 'invalid baseline/candidate cache configuration') + lengths = [c['prompt_tokens'] for c in contexts] + require(candidate['kv_resident'] > 0 and max(lengths) > candidate['kv_resident'], 'no streamed-KV coverage') + require(max(lengths) >= .9 * candidate['context'], 'longest prompt is not near the context limit') + budget = candidate['conversation_cache_mib'] * 1024 * 1024 + for c in contexts: + require(c['baseline']['ids'] and set(STATE_KEYS) <= c['baseline']['state'].keys(), 'incomplete baseline') + require(c['baseline']['finish'] in ('length', 'stop'), 'baseline did not finish normally') + require(answer_text(c['baseline']['text']) == c['expected'].casefold(), 'baseline known answer is wrong') + for i, record in enumerate(cycles): + require(record['cycle'] == i and record['context'] == i % len(contexts), 'missing or reordered cycle') + c = contexts[record['context']] + require(record['finish'] in ('length', 'stop') and record['ids'], 'soak request failed') + require(answer_text(record['text']) == c['expected'].casefold(), 'restored known answer is wrong') + require(record['ids'] == c['baseline']['ids'], 'continuation token parity failed') + require(record['reused'] >= c['prompt_tokens'], 'return did not restore the long prefix') + require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == c['baseline']['state'], + 'restored main-model state differs') + require(0 <= record['cache_bytes'] <= budget, 'parked byte budget exceeded') + # Compare steady-state retained snapshot payload, not allocator RSS or VRAM. + # Sampled RSS is diagnostic: allocator high-water marks need not shrink, + # and request-end samples do not establish a transient peak bound. + for index in range(len(contexts)): + tail = [r['cache_bytes'] for r in cycles if r['context'] == index][-3:] + require(len(tail) == 3 and len(set(tail)) == 1, 'retained payload did not reach a stable plateau') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--config', type=Path, required=True) + ap.add_argument('--engine', type=Path, required=True) + ap.add_argument('--output', type=Path, required=True, help='new directory; existing paths refused') + ap.add_argument('--prompt-tokens', default='2048,40000,120000', help='three increasing approximate prompt lengths') + ap.add_argument('--cycles', type=int, default=30) + ap.add_argument('--cache-mib', type=int, default=8192) + ap.add_argument('--run', action='store_true') + args = ap.parse_args() + try: + lengths = [int(n) for n in args.prompt_tokens.split(',')] + except ValueError: + ap.error('prompt-tokens must contain three integers') + if len(lengths) != 3 or lengths != sorted(set(lengths)) or min(lengths) < 256 or args.cycles < 30 or args.cache_mib <= 0: + ap.error('need three distinct increasing lengths >= 256, cycles >= 30 and cache-mib > 0') + if not args.run: + print(f'Dry run: {args.cycles} known-answer A/B/A cycles; approximate lengths {lengths}.') + print('No model loaded or files created. Use --run only in an exclusive GPU test window.') + return + cfg = json.loads(args.config.read_text(encoding='utf-8')) + path = Path(cfg['tokenizer']) + tok = load_tokenizer(path) + template = ChatTemplate(path / 'chat_template.jinja') + def encode(text): + return tok.encode(text, parse_special=True) + def prompt(text): + return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False)) + def long_prompt(target, secret, index): + paragraphs = max(1, target // 17) + for _ in range(6): + lines = [f'Record {i}: blue square, green triangle, red circle.' for i in range(paragraphs)] + lines[paragraphs // 3] = f'The secret access code for conversation {index} is {secret}.' + ids = prompt(f'Conversation {index}. Remember its secret access code for my next question.\n' + '\n'.join(lines)) + delta = target - len(ids) + if abs(delta) < 64: + return ids + paragraphs = max(1, paragraphs + delta // 17) + return ids + secrets = ['MANGO', 'CEDAR', 'RAVEN'] + prompts = [long_prompt(n, secret, i) for i, (n, secret) in enumerate(zip(lengths, secrets))] + suffix = encode('<|im_end|>\n<|im_start|>user\nWhat is this conversation\'s secret access code? ' + 'Reply with only that one word, no punctuation.<|im_end|>\n' + '<|im_start|>assistant\n\n\n\n\n') + other = prompt('Unrelated worker conversation. Reply with HELLO and nothing else.') + args.output.mkdir(mode=0o700, parents=False, exist_ok=False) + env = child_env(cfg) + env['STRATA_STATE_HASH'] = '1' + results = {'requested_cycles': args.cycles, 'engine_info': {}, 'contexts': [], 'cycles': []} + heads, continuations = [], [] + for label, budget in [('baseline', 0), ('candidate', args.cache_mib)]: + log = args.output / f'{label}.log' + engine = StrataEngine(str(args.engine.resolve()), engine_args(cfg, budget, 1), + cwd=cfg.get('cwd'), log=str(log), env=env) + results['engine_info'][label] = dict(engine.info) + hash_count = 0 + def generate(ids, count): + nonlocal hash_count + output = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None] + text = log.read_text(encoding='utf-8') + hashes = state_hashes(text) + require(len(hashes) == hash_count + 1 and int(hashes[-1]['L']) >= len(ids), 'missing current state fingerprint') + hash_count += 1 + state = hashes[-1] + occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text) + rss = None + try: + match = re.search(r'^VmRSS:\s+(\d+) kB', Path(f'/proc/{engine.proc.pid}/status').read_text(encoding='utf-8'), re.M) + if match: + rss = int(match[1]) * 1024 + except OSError: + pass + return {'ids': output, 'text': tok.decode(output), **engine.last, 'state': state, + 'cache_bytes': int(occupancy[-1]) if occupancy else 0, 'sampled_rss_bytes': rss} + try: + require(max(map(len, prompts)) + len(suffix) + 64 < engine.max_context, 'test prompt exceeds context') + if label == 'baseline': + for i, ids in enumerate(prompts): + head = generate(ids, 1) + require(len(head['ids']) == 1, 'baseline initial output is missing') + heads.append(head['ids']) + continuations.append(ids + head['ids'] + suffix) + answer = generate(continuations[-1], 16) + results['contexts'].append({'expected': secrets[i], 'prompt_tokens': len(ids), 'baseline': answer}) + require(answer_text(answer['text']) == secrets[i].casefold(), 'baseline known answer is wrong') + print(f'baseline length={len(ids)} answer={answer_text(answer["text"])}', flush=True) + else: + primed = set() + for cycle in range(args.cycles): + index = cycle % len(prompts) + if index not in primed: + head = generate(prompts[index], 1) + require(head['ids'] == heads[index], 'initial candidate output differs') + primed.add(index) + generate(other, 1) + answer = generate(continuations[index], 16) + results['cycles'].append({'cycle': cycle, 'context': index, **answer}) + print(f'cycle={cycle + 1}/{args.cycles} length={len(prompts[index])} ' + f'reused={answer["reused"]} answer={answer_text(answer["text"])}', flush=True) + finally: + engine.close() + # Keep partial evidence on failure; verify rejects incomplete runs. + (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + verify(results) + print('PASS: 30+ known-answer A/B/A cycles, streamed/near-limit KV, exact state/output, stable retained payload') + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/draft_vocab.py b/engine/strata/tools/draft_vocab.py new file mode 100644 index 00000000..77fa6b98 --- /dev/null +++ b/engine/strata/tools/draft_vocab.py @@ -0,0 +1,96 @@ +"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose. + +The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over +those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted. +The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in +Chinese drafted almost nothing (#137). This adds whole scripts to a subset: + + python tools/draft_vocab.py --gguf -00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \ + --out data/draft_vocab.bin + +--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic. The base ids keep their order; the added ones follow in +id order. --stats prints what a subset holds. +""" +from __future__ import annotations + +import argparse +import sys +from array import array +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import strata_tokenizer as ST # noqa: E402 + +SCRIPTS = { + "han": [(0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2FA1F)], + "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)], + "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)], + "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)], + # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens + "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)], +} +GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]} + + +def scripts_of(text: str) -> set[str]: + found = set() + for ch in text: + c = ord(ch) + for name, ranges in SCRIPTS.items(): + if any(a <= c <= b for a, b in ranges): + found.add(name) + return found + + +def token_text(tok, i: int) -> str | None: + """A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special.""" + try: + return tok.token_bytes(i).decode("utf-8") + except (KeyError, UnicodeDecodeError, IndexError): + return None + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary") + ap.add_argument("--base", help="the subset to extend (int32 ids)") + ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic") + ap.add_argument("--out", help="where to write the new subset") + ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds") + a = ap.parse_args() + + tok = ST.Tokenizer.from_gguf(a.gguf) + n = len(tok.tokens) + kinds = [scripts_of(t) if (t := token_text(tok, i)) is not None else set() for i in range(n)] + base = list(array("i", Path(a.base).read_bytes())) if a.base else [] + if any(i < 0 or i >= n for i in base): + sys.exit(f"{a.base} has ids outside the vocabulary ({n})") + + want = set() + for x in filter(None, (s.strip() for s in a.add.split(","))): + names = GROUPS.get(x, [x]) + if any(nm not in SCRIPTS for nm in names): + sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}") + want.update(names) + have = set(base) + added = [i for i in range(n) if i not in have and kinds[i] & want] + ids = base + added + + def stats(label, sel): + counts = {nm: sum(1 for i in sel if nm in kinds[i]) for nm in SCRIPTS} + full = {nm: sum(1 for k in kinds if nm in k) for nm in SCRIPTS} + print(f"{label}: {len(sel)} ids; " + ", ".join(f"{nm} {counts[nm]}/{full[nm]}" for nm in SCRIPTS)) + + if a.stats or not a.out: + if base: + stats("base", base) + if added: + stats("new", ids) + if a.out: + Path(a.out).write_bytes(array("i", ids).tobytes()) + print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/embd_bf16_pack.py b/engine/strata/tools/embd_bf16_pack.py new file mode 100644 index 00000000..1ed2d642 --- /dev/null +++ b/engine/strata/tools/embd_bf16_pack.py @@ -0,0 +1,87 @@ +"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads. + + python tools/embd_bf16_pack.py --model --out + +nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory +and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file. + +The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight +out of the safetensors file - nothing decoded or rounded. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING = 8 +GGML_TYPE_BF16 = 30 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" int: + n = 1 + for d in self.shape: + n *= d + return n + + def expected_bytes(self) -> int | None: + geom = BLOCK_GEOMETRY.get(self.type_name) + if geom is None: + return None + block_elems, block_bytes = geom + if self.elements % block_elems: + return None + return self.elements // block_elems * block_bytes + + +class GGUFFile: + def __init__(self, path: pathlib.Path): + self.path = pathlib.Path(path) + self.metadata: dict[str, Any] = {} + self.tensors: list[TensorInfo] = [] + self.version = 0 + self.alignment = 32 + with self.path.open("rb") as fh: + self._parse(fh) + self.data_start = self._data_start + + # ------------------------------------------------------------------ internals + def _parse(self, fh) -> None: + magic = struct.unpack(" str: + (n,) = struct.unpack(" dict[str, int]: + out: dict[str, int] = {} + for t in self.tensors: + out[t.type_name] = out.get(t.type_name, 0) + 1 + return dict(sorted(out.items(), key=lambda kv: -kv[1])) + + def find(self, needle: str) -> list[TensorInfo]: + return [t for t in self.tensors if needle in t.name] diff --git a/engine/strata/tools/gguf_writer.py b/engine/strata/tools/gguf_writer.py new file mode 100644 index 00000000..8ad3cd6e --- /dev/null +++ b/engine/strata/tools/gguf_writer.py @@ -0,0 +1,234 @@ +"""A minimal GGUF v3 WRITER, including `Q2_0`. + +Why this exists +--------------- +P1.S1 of the plan says the tiny synthetic model is "written as a real GGUF via `gguf-py`" using +"at least `Q2_0`". That does not work: `gguf-py` has no `GGMLQuantizationType` member for type 42, so +`GGMLQuantizationType(42)` raises `ValueError`. Verified in round 39 and again here. + +`src/artifact/` needs a writer regardless - P1.S2 requires a reader with no ggml dependency, and the +writer is its companion - so this is that writer in Python, where it can be validated immediately +against `tools/gguf_reader.py` and against llama.cpp. + +Scope: enough to build the P1.S1 tiny model. It is NOT a general-purpose quantizer; the only +quantizer implemented is `Q2_0`, and its contract is `docs/q2_0-contract.md`: + block = 64 elements, fp16 scale, 16 bytes of 2-bit codes, LSB-first, 4 codes per byte + d = amax, code = clamp(round(w/d) + 1, 0, 3), symbol = code - 1 -> {-1, 0, +1, +2} + +Self-checking: `python tools/gguf_writer.py` writes a synthetic v3 file, reads it back with +`gguf_reader.py`, and asserts the tensors and metadata survived byte-exactly. +""" +from __future__ import annotations + +import dataclasses +import pathlib +import struct +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from gguf_reader import GGUF_MAGIC, GGUFFile # noqa: E402 + +# ggml_type ids we can write. Values match GGML_TYPES in gguf_reader.py. +TYPE_IDS = {"F32": 0, "F16": 1, "Q2_0": 42} +DEFAULT_ALIGNMENT = 32 + +_META_IDS = {"u8": 0, "i8": 1, "u16": 2, "i16": 3, "u32": 4, "i32": 5, "f32": 6, + "bool": 7, "string": 8, "array": 9, "u64": 10, "i64": 11, "f64": 12} + + +# ------------------------------------------------------------------ Q2_0, per docs/q2_0-contract.md +def quantize_q2_0(w: np.ndarray) -> bytes: + """(n,) float32 -> concatenated 18-byte blocks. n must be a multiple of 64.""" + w = np.asarray(w, dtype=np.float32).reshape(-1) + if w.size % 64: + raise ValueError(f"Q2_0 needs a multiple of 64 elements, got {w.size}") + blocks = w.reshape(-1, 64) + out = bytearray() + for b in blocks: + amax = float(np.max(np.abs(b))) + d = amax + # d = amax (NOT amax/2) - the grid is asymmetric, symbols land in {-1,0,+1,+2}. + code = np.zeros(64, dtype=np.uint8) if d == 0 else \ + np.clip(np.rint(b / d).astype(np.int32) + 1, 0, 3).astype(np.uint8) + packed = np.zeros(16, dtype=np.uint8) + # j -> byte j//4, bit (j%4)*2 ; four codes per byte, least significant first. + for j in range(64): + packed[j // 4] |= np.uint8(code[j] << ((j % 4) * 2)) + out += struct.pack(" np.ndarray: + """Inverse of the above, for the round-trip check. Mirrors `dequantize_row_q2_0`.""" + nblocks = len(raw) // 18 + out = np.empty(nblocks * 64, dtype=np.float32) + for i in range(nblocks): + d = struct.unpack_from("> ((j % 4) * 2)) & 0x03 + out[i * 64 + j] = (c - 1) * d + return out + + +# ------------------------------------------------------------------ writer +@dataclasses.dataclass +class _Tensor: + name: str + shape: list[int] # GGUF order: dim 0 varies fastest + type_name: str + data: bytes + + +class GGUFWriter: + def __init__(self, alignment: int = DEFAULT_ALIGNMENT): + self.alignment = alignment + self.metadata: dict[str, tuple[str, object]] = {} + self.tensors: list[_Tensor] = [] + + # ---- metadata + def add(self, key: str, value, type_name: str | None = None) -> None: + if type_name is None: + type_name = {bool: "bool", int: "i64", float: "f64", str: "string"}.get(type(value)) + if type_name is None: + if isinstance(value, list) and value: + elem = {bool: "bool", int: "i32", float: "f32", str: "string"}.get(type(value[0])) + if elem is None: + raise TypeError(f"unsupported array element {type(value[0])} for {key}") + type_name = "array:" + elem + else: + raise TypeError(f"cannot infer a GGUF type for {key}") + self.metadata[key] = (type_name, value) + + # ---- tensors + def add_f32(self, name: str, arr: np.ndarray) -> None: + a = np.ascontiguousarray(arr, dtype=" None: + """`arr` is (rows, in_features) row-major with every row `shape[0]` long; `shape` is the FULL + GGUF shape. The shape must be passed explicitly, not inferred as [in, rows]: a fused expert + tensor is [in, out, experts], and inferring 2-D produced `[64, 4096]` where llama.cpp expects + `[64, 256, 16]`. Q2_0 blocks run along dim 0 only, so the extra axes are just a layout. + """ + a = np.asarray(arr, dtype=np.float32) + in_features = shape[0] + if a.ndim != 2 or a.shape[1] != in_features: + raise ValueError(f"{name}: expected (rows, {in_features}), got {a.shape}") + if a.shape[0] * in_features != int(np.prod(shape)): + raise ValueError(f"{name}: {a.shape} does not cover shape {shape}") + per_row = quantize_q2_0(a.reshape(-1)) # row-major: row 0 first + self.tensors.append(_Tensor(name, list(shape), "Q2_0", per_row)) + + # ---- serialisation + def _kv_bytes(self, key: str, type_name: str, value) -> bytes: + out = bytearray() + out += struct.pack(" bytes: + if type_name == "string": + b = v.encode("utf-8") + return struct.pack(" pathlib.Path: + path = pathlib.Path(path) + body = bytearray() + body += struct.pack(" int: + rng = np.random.default_rng(7) + w = GGUFWriter() + w.add("general.architecture", "qwen4exp") + w.add("qwen4exp.block_count", 8, "u32") + w.add("qwen4exp.test.array", [1, 2, 3, 4], "array:i32") + w.add("general.name", "strata tiny") + + A = rng.standard_normal((16, 64)).astype(np.float32) + B = rng.standard_normal((4, 8)).astype(np.float32) + w.add_q2_0("blk.0.ffn_gate_exps.weight", A, 64) + w.add_f32("blk.0.ssm_a", B) + + p = pathlib.Path(__file__).resolve().parent.parent / "bench" / "tiny-selftest.gguf" + w.write(p) + print(f"wrote {p.name} ({p.stat().st_size} B)") + + g = GGUFFile(p) + ok = True + print(f" version {g.version} tensors {len(g.tensors)} metadata {len(g.metadata)}") + if g.metadata.get("general.architecture") != "qwen4exp": print(" FAIL arch"); ok = False + if g.metadata.get("qwen4exp.block_count") != 8: print(" FAIL u32"); ok = False + if g.metadata.get("qwen4exp.test.array") != [1, 2, 3, 4]: print(" FAIL array"); ok = False + + by = {t.name: t for t in g.tensors} + t = by.get("blk.0.ffn_gate_exps.weight") + if t is None or t.type_name != "Q2_0" or t.shape != [64, 16]: + print(f" FAIL tensor dir: {t}"); ok = False + else: + with p.open("rb") as fh: + fh.seek(g.data_start + t.offset) + raw = fh.read(16 * 18) + back = dequantize_q2_0(raw) + err = np.abs(back - A.reshape(-1)).max() + rel = float(np.abs(back - A.reshape(-1)).mean() / np.abs(A).mean()) + print(f" Q2_0 round trip: max abs {err:.4f} mean rel {rel*100:.2f}% " + f"(quantization error, not a write bug)") + # The real check: re-quantizing the DEQUANTIZED values must be a fixed point. + again = dequantize_q2_0(quantize_q2_0(back)) + if not np.array_equal(again, back): + print(" FAIL Q2_0 is not a fixed point under requantization"); ok = False + else: + print(" Q2_0 fixed point: PASS (requantizing the dequantized values is exact)") + print("SELF-CHECK " + ("PASS" if ok else "FAIL")) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(_selfcheck()) diff --git a/engine/strata/tools/hip/bench_prefill.py b/engine/strata/tools/hip/bench_prefill.py new file mode 100644 index 00000000..8edb11f6 --- /dev/null +++ b/engine/strata/tools/hip/bench_prefill.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Matched fresh/follow-up prefill probe against an otherwise idle local Strata server. + +Does not start/stop services. Use a dedicated server and its engine log, restart +between build/configuration arms, and keep model/template/settings identical. +""" +import argparse +import json +import os +from pathlib import Path +import re +import time +import urllib.request + +PATTERN = re.compile(r'prompt (\d+) tokens = (\d+) reused \+ (\d+) read in (\d+) ms \(([0-9.]+) tok/s\), (\d+) generated in (\d+) ms \(([0-9.]+) tok/s\)') +FIELDS = ('prompt_tokens', 'reused', 'fresh', 'prefill_ms', 'prefill_tps', 'generated', 'decode_ms', 'decode_tps') + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--url', default='http://127.0.0.1:8080') + p.add_argument('--model', required=True) + p.add_argument('--engine-log', type=Path, required=True) + p.add_argument('--output', type=Path, required=True) + p.add_argument('--label', required=True) + args = p.parse_args() + results = [] + + def request(messages, kind, trial): + offset = args.engine_log.stat().st_size + body = dict(model=args.model, messages=messages, max_tokens=128, + temperature=0, top_k=1, top_p=1, min_p=0, seed=42, + reasoning_effort='none') + headers = {'Content-Type': 'application/json'} + if os.environ.get('STRATA_API_KEY'): + headers['Authorization'] = 'Bearer ' + os.environ['STRATA_API_KEY'] + req = urllib.request.Request(args.url.rstrip('/') + '/v1/chat/completions', + data=json.dumps(body).encode(), headers=headers) + start = time.monotonic() + with urllib.request.urlopen(req, timeout=360) as response: + data = json.load(response) + elapsed = time.monotonic() - start + # The API response may arrive just before stderr's completion line is flushed. + deadline = time.monotonic() + 2 + while True: + with args.engine_log.open('rb') as log: + log.seek(offset) + matches = PATTERN.findall(log.read().decode(errors='replace')) + if matches or time.monotonic() >= deadline: + break + time.sleep(0.02) + if len(matches) != 1: + raise RuntimeError('Expected exactly one completed engine timing line; check idle server and log path') + metrics = dict(zip(FIELDS, map(float, matches[0]))) + if kind == 'fresh' and metrics['reused'] != 0: + raise RuntimeError('Fresh prompt reused cached tokens; restart this arm before comparison') + choice = data['choices'][0] + results.append(dict(label=args.label, kind=kind, trial=trial, wall_s=elapsed, + metrics=metrics, usage=data.get('usage'), + finish_reason=choice.get('finish_reason'), message=choice['message'])) + args.output.write_text(json.dumps(results, indent=2) + '\n') + print(json.dumps(results[-1]), flush=True) + return choice['message'] + + request([{'role': 'user', 'content': 'Reply READY.'}], 'warmup', 0) + for trial, n in enumerate((140, 280, 140, 280), 1): + code = '\n'.join(f'export function rule{i}(x) {{ return x === {i} ? x + {i+1} : x - {i}; }}' for i in range(n)) + messages = [{'role': 'user', 'content': f'CASE {trial}: Review this source and describe its behavior precisely in a paragraph.\n' + code}] + reply = request(messages, 'fresh', trial) + messages += [reply, {'role': 'user', 'content': 'Explain the most relevant boundary case and the smallest useful regression test. ' + 'Focus on integer equality, zero, negative input, unexpected types, and caller assumptions. ' * 5}] + request(messages, 'followup', trial) + + +if __name__ == '__main__': + main() diff --git a/engine/strata/tools/hip/build_windows.bat b/engine/strata/tools/hip/build_windows.bat new file mode 100644 index 00000000..b3d0011c --- /dev/null +++ b/engine/strata/tools/hip/build_windows.bat @@ -0,0 +1,86 @@ +@echo off +rem Strata's HIP (AMD) engine for Windows, and the ready-made zip setup.py downloads (strata-windows-x64-hip.zip). +rem +rem tools\hip\build_windows.bat build strata.exe + strata-device.exe and package dist\strata-windows-x64-hip.zip +rem tools\hip\build_windows.bat tests also build the HIP unit tests (ctest in build-hip-win; they need an AMD GPU) +rem +rem Needs: Visual Studio 2022 (or 2019) Build Tools with the C++ workload (the linker, the CRT and the Windows SDK), +rem Python 3.10+ and git. No admin rights and no AMD GPU: ROCm comes from AMD's TheRock Python wheels (the same +rem ROCm 10.2 nightly #325 ran on an RX 9070 XT), installed into a private venv (ROCM_VENV, ~7 GB). CMake refuses to +rem mix cl.exe with Clang for HIP, so ROCm's clang compiles the host code too (targeting the MSVC ABI, with MSVC's +rem headers and linker from vcvars); cmake/hip_backend.cmake force-includes the CUDA->HIP shim. +rem +rem Settings (environment variables, all optional): +rem STRATA_HIP_ARCHS gfx1100;gfx1101;gfx1102;gfx1200;gfx1201;gfx1030 (the cards setup supports, + gfx1102) +rem STRATA_ROCM_VERSION 10.2.0a20260930 STRATA_ROCM_INDEX https://nightly.repo.amd.com/rocm/whl-next/ +rem ROCM_VENV \.rocm-win BUILD_DIR \build-hip-win DIST_DIR \dist +rem STRATA_GGML_DIR a llama.cpp checkout at the pinned commit (default: CMake fetches it) +setlocal EnableDelayedExpansion +for %%I in ("%~dp0..\..") do set "SRC=%%~fI" +if not defined STRATA_HIP_ARCHS set "STRATA_HIP_ARCHS=gfx1100;gfx1101;gfx1102;gfx1200;gfx1201;gfx1030" +if not defined STRATA_ROCM_VERSION set "STRATA_ROCM_VERSION=10.2.0a20260930" +if not defined STRATA_ROCM_INDEX set "STRATA_ROCM_INDEX=https://nightly.repo.amd.com/rocm/whl-next/" +if not defined ROCM_VENV set "ROCM_VENV=%SRC%\.rocm-win" +if not defined BUILD_DIR set "BUILD_DIR=%SRC%\build-hip-win" +if not defined DIST_DIR set "DIST_DIR=%SRC%\dist" +set "TESTS=OFF" +if /i "%~1"=="tests" set "TESTS=ON" + +rem ---- 1. ROCm (TheRock wheels: the compiler, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, a device package per arch) +set "PY=" +py -3 -c "import sys" >nul 2>nul && set "PY=py -3" +if not defined PY python -c "import sys" >nul 2>nul && set "PY=python" +if not defined PY (echo Python 3.10+ is needed & exit /b 1) +if not exist "%ROCM_VENV%\Scripts\python.exe" %PY% -m venv "%ROCM_VENV%" || exit /b 1 +set "EXTRAS=libraries,devel" +for %%A in (%STRATA_HIP_ARCHS:;= %) do set "EXTRAS=!EXTRAS!,device-%%A" +set "STAMP=%ROCM_VENV%\strata-rocm.txt" +set "WANT=%STRATA_ROCM_VERSION% %EXTRAS%" +set "HAVE=" +if exist "%STAMP%" set /p HAVE=<"%STAMP%" +if not "!HAVE!"=="!WANT!" ( + echo Installing ROCm %STRATA_ROCM_VERSION% [%EXTRAS%] into %ROCM_VENV% ... + "%ROCM_VENV%\Scripts\python.exe" -m pip install --disable-pip-version-check --index-url "%STRATA_ROCM_INDEX%" "rocm[%EXTRAS%]==%STRATA_ROCM_VERSION%" || exit /b 1 + "%ROCM_VENV%\Scripts\rocm-sdk.exe" init || exit /b 1 + >"%STAMP%" echo !WANT! +) +for /f "delims=" %%R in ('"%ROCM_VENV%\Scripts\rocm-sdk.exe" path --root') do set "ROCM=%%R" +if not exist "%ROCM%\lib\llvm\bin\clang++.exe" (echo ROCm has no compiler in "%ROCM%" & exit /b 1) +set "ROCM_F=%ROCM:\=/%" +set "BITCODE=%ROCM_F%/lib/llvm/amdgcn/bitcode" + +rem ---- 2. MSVC: the linker, the C runtime and the Windows SDK (ROCm's clang uses them) +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +set "VS=" +if exist "%VSWHERE%" for /f "delims=" %%V in ('"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath') do set "VS=%%V" +if not defined VS (echo Visual Studio Build Tools with the C++ workload are needed & exit /b 1) +call "%VS%\VC\Auxiliary\Build\vcvars64.bat" >nul || exit /b 1 +set "HIP_PLATFORM=amd" +set "HIP_PATH=%ROCM%" +set "ROCM_PATH=%ROCM%" +set "PATH=%ROCM%\bin;%ROCM%\lib\llvm\bin;%PATH%" + +rem ---- 3. configure + build (STRATA_PORTABLE: the CPU kernels for an AVX2 baseline, as in the NVIDIA zip) +set "GGML=" +if defined STRATA_GGML_DIR set "GGML=-DSTRATA_GGML_DIR=%STRATA_GGML_DIR:\=/%" +if not exist "%BUILD_DIR%\build.ninja" ( + cmake -G Ninja -S "%SRC%" -B "%BUILD_DIR%" -DCMAKE_BUILD_TYPE=Release ^ + -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=%TESTS% -DSTRATA_PREFILL_MMQ=ON ^ + -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON "-DCMAKE_HIP_ARCHITECTURES=%STRATA_HIP_ARCHS%" ^ + "-DCMAKE_C_COMPILER=%ROCM_F%/lib/llvm/bin/clang.exe" "-DCMAKE_CXX_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" ^ + "-DCMAKE_HIP_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" "-DCMAKE_HIP_COMPILER_ROCM_ROOT=%ROCM_F%" ^ + "-DCMAKE_PREFIX_PATH=%ROCM_F%" "-DCMAKE_HIP_FLAGS=--rocm-path=%ROCM_F% --rocm-device-lib-path=%BITCODE%" ^ + %GGML% || exit /b 1 +) +if "%TESTS%"=="ON" ( + cmake --build "%BUILD_DIR%" || exit /b 1 +) else ( + cmake --build "%BUILD_DIR%" --target strata strata-device || exit /b 1 +) + +rem ---- 4. the zip: the two programs, the ROCm DLLs they load (+ rocBLAS/hipBLASLt kernels for these archs), licenses +"%ROCM_VENV%\Scripts\python.exe" "%SRC%\tools\hip\package_windows.py" --build "%BUILD_DIR%" --rocm "%ROCM%" ^ + --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" || exit /b 1 +echo. +echo Done: %DIST_DIR%\strata-windows-x64-hip.zip +endlocal diff --git a/engine/strata/tools/hip/gfx1100-hipblaslt-100100.txt b/engine/strata/tools/hip/gfx1100-hipblaslt-100100.txt new file mode 100644 index 00000000..2d02ffd1 --- /dev/null +++ b/engine/strata/tools/hip/gfx1100-hipblaslt-100100.txt @@ -0,0 +1,32 @@ +# solution IDs are scoped to this hipBLASLt version and device architecture +STRATA_HIPBLASLT_TUNING_V1 gfx1100 100100 +bf16 1 2560 1 4096 541 +bf16 1 2560 1 8192 541 +bf16 4 10240 4 4096 541 +bf16 4 10240 4 8192 541 +bf16 48 2560 96 4096 541 +bf16 48 2560 96 8192 542 +bf16 128 2560 128 4096 542 +bf16 128 2560 128 8192 542 +bf16 320 10240 320 4096 542 +bf16 320 10240 320 8192 542 +bf16 512 2560 512 4096 542 +bf16 512 2560 512 8192 542 +bf16 2560 2560 2560 4096 542 +bf16 2560 2560 2560 8192 542 +bf16 10240 320 10240 4096 542 +bf16 10240 320 10240 8192 542 +f16 512 2560 512 4096 1147 +f16 512 2560 512 8192 1147 +f16 640 2560 640 4096 1147 +f16 640 2560 640 8192 1147 +f16 2560 640 2560 4096 1147 +f16 2560 640 2560 8192 1147 +f16 2560 6144 2560 4096 1147 +f16 2560 6144 2560 8192 1147 +f16 6144 2560 6144 4096 1147 +f16 6144 2560 6144 8192 1147 +f16 10240 2560 10240 4096 1147 +f16 10240 2560 10240 8192 1147 +f16 12288 2560 12288 4096 1147 +f16 12288 2560 12288 8192 1147 diff --git a/engine/strata/tools/hip/gfx1100-hipblaslt-100200.txt b/engine/strata/tools/hip/gfx1100-hipblaslt-100200.txt new file mode 100644 index 00000000..c82a0112 --- /dev/null +++ b/engine/strata/tools/hip/gfx1100-hipblaslt-100200.txt @@ -0,0 +1,28 @@ +# solution IDs are scoped to this hipBLASLt version and device architecture +STRATA_HIPBLASLT_TUNING_V1 gfx1100 100200 +bf16 1 2560 1 4096 541 +bf16 4 10240 4 8192 542 +bf16 48 2560 96 4096 541 +bf16 48 2560 96 8192 542 +bf16 128 2560 128 4096 542 +bf16 128 2560 128 8192 542 +bf16 320 10240 320 4096 542 +bf16 320 10240 320 8192 542 +bf16 512 2560 512 8192 542 +bf16 2560 2560 2560 8192 542 +bf16 10240 320 10240 4096 542 +bf16 10240 320 10240 8192 542 +f16 512 2560 512 4096 1147 +f16 512 2560 512 8192 1147 +f16 640 2560 640 4096 1147 +f16 640 2560 640 8192 1147 +f16 2560 640 2560 4096 1147 +f16 2560 640 2560 8192 1147 +f16 2560 6144 2560 4096 1147 +f16 2560 6144 2560 8192 1147 +f16 6144 2560 6144 4096 1147 +f16 6144 2560 6144 8192 1147 +f16 10240 2560 10240 4096 1147 +f16 10240 2560 10240 8192 1147 +f16 12288 2560 12288 4096 1147 +f16 12288 2560 12288 8192 1147 diff --git a/engine/strata/tools/hip/gfx1201-hipblaslt-100500.txt b/engine/strata/tools/hip/gfx1201-hipblaslt-100500.txt new file mode 100644 index 00000000..e13c712b --- /dev/null +++ b/engine/strata/tools/hip/gfx1201-hipblaslt-100500.txt @@ -0,0 +1,34 @@ +# solution IDs are scoped to this hipBLASLt version and device architecture +STRATA_HIPBLASLT_TUNING_V1 gfx1201 100500 +bf16 1 2560 1 4096 110508 +bf16 1 2560 1 8192 110524 +bf16 4 10240 4 4096 110549 +bf16 4 10240 4 8192 110549 +bf16 48 2560 96 4096 110416 +bf16 48 2560 96 8192 110419 +bf16 128 2560 128 4096 110001 +bf16 128 2560 128 8192 110161 +bf16 320 10240 320 4096 110420 +bf16 320 10240 320 8192 110420 +bf16 512 2560 512 4096 110428 +bf16 512 2560 512 8192 110428 +bf16 2560 2560 2560 4096 110428 +bf16 2560 2560 2560 8192 110428 +bf16 10240 320 10240 4096 110428 +bf16 10240 320 10240 8192 110462 +bf16 10240 2560 10240 4096 110428 +bf16 10240 2560 10240 8192 110428 +f16 512 2560 512 4096 135699 +f16 512 2560 512 8192 135625 +f16 640 2560 640 4096 135740 +f16 640 2560 640 8192 135629 +f16 2560 640 2560 4096 135625 +f16 2560 640 2560 8192 135611 +f16 2560 6144 2560 4096 135187 +f16 2560 6144 2560 8192 135631 +f16 6144 2560 6144 4096 135625 +f16 6144 2560 6144 8192 135625 +f16 10240 2560 10240 4096 135625 +f16 10240 2560 10240 8192 135625 +f16 12288 2560 12288 4096 135625 +f16 12288 2560 12288 8192 135625 diff --git a/engine/strata/tools/hip/package_windows.py b/engine/strata/tools/hip/package_windows.py new file mode 100644 index 00000000..e6298815 --- /dev/null +++ b/engine/strata/tools/hip/package_windows.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Package the Windows HIP engine as the ready-made zip setup.py downloads (strata-windows-x64-hip.zip). + + python tools/hip/package_windows.py --build build-hip-win --rocm \\ + --archs "gfx1100;gfx1201" --rocm-version 10.2.0a20260930 --out dist + +tools/hip/build_windows.bat runs it after the build. The zip holds: + + strata.exe, strata-device.exe, BUILD.json (backend "hip", the archs, the ROCm and hipBLASLt versions) + amdhip64_7.dll, amd_comgr.dll the HIP runtime beside the exes too (#468 #461: before System32) + rocm/bin/*.dll the ROCm DLLs the two programs load (their import tables, followed + through the ROCm DLLs, + amd_comgr.dll, which the HIP runtime loads + by name) and the Microsoft C++ runtime they import + rocm/bin/rocblas/library, rocm/bin/hipblaslt/library the GEMM kernels, for these archs only + rocm/.kpack/ rocBLAS's own device code for these archs (rocblas.dll finds it at + ../.kpack from its folder) + rocm/licenses/ the shipped components' licenses, and NOTICE.txt + +setup.py puts rocm/bin first on the engine's PATH (the config's lib_dirs). The AMD display driver (AMD Software: +Adrenalin Edition) is the only thing the user installs: TheRock's HIP runtime runs on top of it. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASSET = "strata-windows-x64-hip.zip" +PROGRAMS = ("strata.exe", "strata-device.exe") +DYNAMIC = ("amd_comgr.dll",) # LoadLibrary'd by amdhip64_7.dll: not in any import table +CRT = ("msvcp140.dll", "msvcp140_1.dll", "msvcp140_2.dll", "vcruntime140.dll", "vcruntime140_1.dll") +KPACKS = ("blas_lib",) # rocblas.dll's own device code; rocSOLVER's (27 MB per arch) is never launched by Strata +LICENSES = ("rocblas", "rocsolver", "hipblas", "hipblas-common", "hipblaslt", "amd_comgr", "rocm-core") +NOTICE = """Strata's Windows HIP engine ships these AMD ROCm components unmodified, from AMD's TheRock Python wheels +(ROCm {rocm}, https://nightly.repo.amd.com/rocm/whl-next/, built from https://github.com/ROCm/TheRock): + +{dlls} + +Licenses: rocBLAS, hipBLAS, hipBLAS-common, hipBLASLt (and its TensileLite host and origami libraries), rocm-core: MIT; +rocSOLVER: BSD 2-clause; amd_comgr: Apache 2.0 with LLVM exceptions (files in this folder). The HIP runtime +(amdhip64_7.dll, https://github.com/ROCm/rocm-systems/tree/develop/projects/clr) and rocm_kpack.dll (TheRock) are MIT +licensed; their wheels carry no license file. The Microsoft Visual C++ runtime DLLs (msvcp140*.dll, +vcruntime140*.dll) are redistributable under the Visual Studio license (Distributable Code). +""" + + +def imports(objdump: Path, dll: Path) -> list[str]: + text = subprocess.run([str(objdump), "-p", str(dll)], capture_output=True, text=True, check=True).stdout + return [m.group(1) for m in re.finditer(r"DLL Name:\s*(\S+)", text)] + + +def crt_dir() -> Path | None: + """The MSVC redist folder with the C++ runtime DLLs (vcvars sets VCToolsRedistDir).""" + base = os.environ.get("VCToolsRedistDir") + if not base: + return None + hits = sorted(Path(base, "x64").glob("Microsoft.VC*.CRT")) + return hits[-1] if hits else None + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--build", required=True, type=Path) + ap.add_argument("--rocm", required=True, type=Path, help="the ROCm root (rocm-sdk path --root)") + ap.add_argument("--archs", required=True, help="the archs the engine was compiled for, ';'-separated") + ap.add_argument("--rocm-version", required=True) + ap.add_argument("--out", required=True, type=Path) + a = ap.parse_args() + archs = [x for x in re.split(r"[;, ]+", a.archs) if x] + rbin = a.rocm / "bin" + objdump = a.rocm / "lib" / "llvm" / "bin" / "llvm-objdump.exe" + stage = a.out / "strata-windows-x64-hip" + shutil.rmtree(stage, ignore_errors=True) + (stage / "rocm" / "bin").mkdir(parents=True) + + for p in PROGRAMS: + shutil.copy2(a.build / p, stage / p) + + # the ROCm DLLs: the programs' imports, followed through the ROCm DLLs themselves + rocm_dlls = {p.name.lower(): p for p in rbin.glob("*.dll")} + need, todo, crt = [], [stage / p for p in PROGRAMS] + [rbin / d for d in DYNAMIC], set() + while todo: + f = todo.pop() + for name in imports(objdump, f): + low = name.lower() + if low in CRT: + crt.add(low) + elif low in rocm_dlls and low not in need: + need.append(low) + todo.append(rocm_dlls[low]) + for d in DYNAMIC: + if d not in need: + need.append(d) + for d in sorted(need): + shutil.copy2(rocm_dlls[d], stage / "rocm" / "bin" / rocm_dlls[d].name) + cdir = crt_dir() + if cdir is None: + sys.exit("VCToolsRedistDir is not set: run this from a Visual Studio x64 developer prompt (vcvars64.bat)") + for d in sorted(crt): + shutil.copy2(cdir / d, stage / "rocm" / "bin" / d) + # #468 #461: the HIP runtime (and the compiler it loads by name) next to the exes as well - Windows searches the + # exe's folder before System32, where an AMD driver may install its own amdhip64_7.dll (found before PATH's + # rocm/bin); rocBLAS/hipBLASLt stay in rocm/bin, which they resolve their kernel libraries and ../.kpack from + for pat in ("amdhip64_*.dll", "amd_comgr*.dll"): + for f in (stage / "rocm" / "bin").glob(pat): + shutil.copy2(f, stage / f.name) + + # the GEMM kernels and the libraries' own device code, for these archs + lib = stage / "rocm" / "bin" / "rocblas" / "library" + lib.mkdir(parents=True) + for f in (rbin / "rocblas" / "library").iterdir(): + m = re.search(r"gfx[0-9a-f]+", f.name) + if m is None or m.group() in archs: + shutil.copy2(f, lib / f.name) + for arch in archs: + src = rbin / "hipblaslt" / "library" / arch + if src.is_dir(): # hipBLASLt has no RDNA2 (gfx1030) kernels + shutil.copytree(src, stage / "rocm" / "bin" / "hipblaslt" / "library" / arch) + kp = stage / "rocm" / ".kpack" + kp.mkdir() + kpack_src = a.rocm / ".kpack" + for arch in archs: + for k in KPACKS: + f = kpack_src / f"{k}_{arch}.kpack" + if not f.exists(): + sys.exit(f"missing {f}: install the rocm-sdk-device-{arch} wheel and run rocm-sdk init") + shutil.copy2(f, kp / f.name) + + lic = stage / "rocm" / "licenses" + lic.mkdir() + for comp in LICENSES: + for f in (a.rocm / "share" / "doc" / comp).glob("LICENSE*"): + shutil.copy2(f, lic / f"{comp}-{f.name}") + shipped = sorted(p.name for p in (stage / "rocm" / "bin").glob("*.dll")) + (lic / "NOTICE.txt").write_text(NOTICE.format(rocm=a.rocm_version, dlls="\n".join(" " + d for d in shipped)), + encoding="utf-8") + + version = re.search(r"project\(strata VERSION ([\d.]+)", (ROOT / "CMakeLists.txt").read_text()).group(1) + hl = (a.rocm / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + hlv = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", hl).group(1)) for k in ("MAJOR", "MINOR", "PATCH")] + meta = {"source": "prebuilt", "backend": "hip", "platform": "windows-x64", "version": version, "archs": archs, + "rocm": a.rocm_version, "hipblaslt_version": hlv[0] * 100000 + hlv[1] * 100 + hlv[2], "vision": "none", + "lib_dirs": ["rocm/bin"]} + (stage / "BUILD.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") + + z = a.out / ASSET + z.unlink(missing_ok=True) + with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as f: + for p in sorted(stage.rglob("*")): + if p.is_file(): + f.write(p, p.relative_to(stage).as_posix()) + size = sum(p.stat().st_size for p in stage.rglob("*") if p.is_file()) + print(f"{z}: {z.stat().st_size / 2**20:.0f} MiB ({size / 2**20:.0f} MiB unpacked), engine {version}, " + f"{', '.join(archs)}, ROCm {a.rocm_version}, DLLs: {', '.join(shipped)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/hip/tune_hipblaslt.cpp b/engine/strata/tools/hip/tune_hipblaslt.cpp new file mode 100644 index 00000000..ded114fc --- /dev/null +++ b/engine/strata/tools/hip/tune_hipblaslt.cpp @@ -0,0 +1,420 @@ +#include +#include +#include +#include "../../include/strata/kernels/bf16_bits.hpp" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +#define HIP_CHECK(call) do { const hipError_t e = (call); if (e != hipSuccess) { \ + std::fprintf(stderr, "HIP %s:%d: %s: %s\n", __FILE__, __LINE__, #call, hipGetErrorString(e)); std::exit(2); } } while (0) +#define BLAS_CHECK(call) do { const hipblasStatus_t e = (call); if (e != HIPBLAS_STATUS_SUCCESS) { \ + std::fprintf(stderr, "hipBLAS %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int)e); std::exit(2); } } while (0) +#define LT_CHECK(call) do { const hipblasStatus_t e = (call); if (e != HIPBLAS_STATUS_SUCCESS) { \ + std::fprintf(stderr, "hipBLASLt %s:%d: %s: status=%d\n", __FILE__, __LINE__, #call, (int)e); std::exit(2); } } while (0) + +struct Buffer { + void *p = nullptr; + explicit Buffer(size_t bytes) { if (bytes) HIP_CHECK(hipMalloc(&p, bytes)); } + ~Buffer() { if (p) (void)hipFree(p); } + Buffer(const Buffer &) = delete; + Buffer &operator=(const Buffer &) = delete; +}; +struct Events { + hipEvent_t a = nullptr, b = nullptr; + Events() { HIP_CHECK(hipEventCreate(&a)); HIP_CHECK(hipEventCreate(&b)); } + ~Events() { if (a) (void)hipEventDestroy(a); if (b) (void)hipEventDestroy(b); } +}; + +struct Shape { int t, n, k, ldy; bool bf16; }; +struct Options { + size_t workspace = 32U * 1024U * 1024U; + std::vector shapes; + std::vector tokens{4096, 8192}; + std::string shapes_file, tuning_out; + bool explicit_shapes = false; +}; +struct Err { double rel_l2, max_abs; bool finite; size_t padding_writes; }; +struct Best { + Shape s; + int heuristic_index, solution_id; + size_t required_workspace, algo_workspace; + float mean_ms; + Err error; + std::string solution, kernel, config; +}; + +constexpr int WARMUPS = 2; +constexpr int REPS = 3; +constexpr int MAX_ALGOS = 16; +constexpr double REL_L2_TOL = 1e-4; +constexpr double MAX_ABS_TOL = 1e-2; +constexpr float PADDING_CANARY = 123456.25f; + +const char *dtype(bool bf16) { return bf16 ? "bf16" : "f16"; } +const char *status_name(hipblasStatus_t s) { + switch (s) { + case HIPBLAS_STATUS_SUCCESS: return "success"; + case HIPBLAS_STATUS_NOT_SUPPORTED: return "not_supported"; + case HIPBLAS_STATUS_INVALID_VALUE: return "invalid_value"; + case HIPBLAS_STATUS_ARCH_MISMATCH: return "arch_mismatch"; + default: return "other"; + } +} +std::string json(const std::string &s) { + std::ostringstream o; o << '"'; + for (unsigned char c : s) { + if (c == '"') o << "\\\""; + else if (c == '\\') o << "\\\\"; + else if (c == '\n') o << "\\n"; + else if (c == '\r') o << "\\r"; + else if (c == '\t') o << "\\t"; + else if (c < 0x20) o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (unsigned)c << std::dec; + else o << (char)c; + } + o << '"'; return o.str(); +} +std::string config_hex(const hipblasLtMatmulAlgo_t &algo) { + std::ostringstream o; o << std::hex << std::setfill('0'); + for (uint8_t b : algo.data) o << std::setw(2) << (unsigned)b; + return o.str(); +} +uint16_t input_bits(float x, bool bf16) { + if (bf16) return strata::kernels::bf16_from_f32(x); + const __half half = __float2half_rn(x); + uint16_t bits = 0; + std::memcpy(&bits, &half, sizeof(bits)); + return bits; +} +void fill(std::vector &v, uint32_t seed, bool bf16) { + std::mt19937 rng(seed); + std::uniform_real_distribution dist(-1.0f, 1.0f); + for (auto &x : v) x = input_bits(dist(rng), bf16); +} +float time_call(hipStream_t stream, const std::function &f) { + Events ev; + HIP_CHECK(hipEventRecord(ev.a, stream)); + f(); + HIP_CHECK(hipEventRecord(ev.b, stream)); + HIP_CHECK(hipEventSynchronize(ev.b)); + HIP_CHECK(hipDeviceSynchronize()); + float ms = 0; + HIP_CHECK(hipEventElapsedTime(&ms, ev.a, ev.b)); + return ms; +} +Err compare(const std::vector &ref, const std::vector &got, int n, int t, int ld) { + long double d2 = 0, r2 = 0; double max_abs = 0; bool finite = true; + for (int col = 0; col < t; ++col) for (int row = 0; row < n; ++row) { + const size_t i = (size_t)col * ld + row; + const double r = ref[i], g = got[i]; + if (!std::isfinite(r) || !std::isfinite(g)) { finite = false; continue; } + const double d = g - r; + if (!std::isfinite(d)) { finite = false; continue; } + d2 += (long double)d * d; r2 += (long double)r * r; + max_abs = std::max(max_abs, std::abs(d)); + } + if (!finite) return {std::numeric_limits::infinity(), + std::numeric_limits::infinity(), false, 0}; + return {std::sqrt((double)(d2 / std::max(r2, 1e-300L))), max_abs, true, 0}; +} +size_t padding_writes(const std::vector &got, int n, int t, int ld) { + size_t writes = 0; + for (int col = 0; col < t; ++col) for (int row = n; row < ld; ++row) + if (got[(size_t)col * ld + row] != PADDING_CANARY) ++writes; + return writes; +} +bool accuracy_ok(const Err &e) { + return e.finite && e.padding_writes == 0 && + e.rel_l2 <= REL_L2_TOL && e.max_abs <= MAX_ABS_TOL; +} +std::vector csv(const std::string &s) { + std::vector out; size_t b = 0; + for (;;) { + const size_t p = s.find(',', b); + out.push_back(s.substr(b, p == std::string::npos ? p : p - b)); + if (p == std::string::npos) return out; + b = p + 1; + } +} +int positive(const std::string &s, const char *label) { + char *e = nullptr; const long v = std::strtol(s.c_str(), &e, 10); + if (s.empty() || !e || *e || v < 1 || v > std::numeric_limits::max()) { + std::fprintf(stderr, "invalid %s: %s\n", label, s.c_str()); std::exit(2); + } + return (int)v; +} +void add(Options &o, bool bf16, int t, int n, int k, int ldy) { + if (ldy < n) { std::fprintf(stderr, "ldy must be >= N\n"); std::exit(2); } + o.shapes.push_back({t,n,k,ldy,bf16}); +} +void add_shape(Options &o, const std::string &v) { + const auto f = csv(v); + if (f.size() != 3) { std::fprintf(stderr, "--shape expects T,N,K\n"); std::exit(2); } + int t=positive(f[0],"T"), n=positive(f[1],"N"), k=positive(f[2],"K"); + add(o,false,t,n,k,n); add(o,true,t,n,k,n); o.explicit_shapes=true; +} +void add_case(Options &o, const std::string &v) { + const auto f = csv(v); + if (f.size()!=5 || (f[0]!="f16" && f[0]!="bf16")) { + std::fprintf(stderr, "--case expects dtype,T,N,K,ldy\n"); std::exit(2); + } + add(o,f[0]=="bf16",positive(f[1],"T"),positive(f[2],"N"),positive(f[3],"K"),positive(f[4],"ldy")); + o.explicit_shapes=true; +} +std::vector parse_tokens(const std::string &s) { + std::vector out; + for (const auto &x : csv(s)) out.push_back(positive(x,"token bucket")); + return out; +} +void load_shapes(Options &o) { + std::ifstream f(o.shapes_file); + if (!f) { std::fprintf(stderr, "cannot open shapes file: %s\n",o.shapes_file.c_str()); std::exit(2); } + const std::string text((std::istreambuf_iterator(f)),{}); + const std::regex obj(R"(\{[^{}]*\})"), dtype_re(R"re("dtype"\s*:\s*"(f16|bf16)")re"), + n_re(R"("N"\s*:\s*([0-9]+))"), k_re(R"("K"\s*:\s*([0-9]+))"), + ld_re(R"("ldy"\s*:\s*([0-9]+))"); + int count=0; + for (auto i=std::sregex_iterator(text.begin(),text.end(),obj); i!=std::sregex_iterator(); ++i) { + const std::string item=i->str(); std::smatch d,n,k,ld; + if (!std::regex_search(item,d,dtype_re) || !std::regex_search(item,n,n_re) || + !std::regex_search(item,k,k_re) || !std::regex_search(item,ld,ld_re)) continue; + for (int t:o.tokens) add(o,d[1]=="bf16",t,positive(n[1],"N"),positive(k[1],"K"),positive(ld[1],"ldy")); + ++count; + } + if (!count) { std::fprintf(stderr,"no dtype,N,K,ldy entries in %s\n",o.shapes_file.c_str()); std::exit(2); } + o.explicit_shapes=true; +} +void usage(const char *p) { + std::printf("Usage: %s [--workspace-mib N] [--shape T,N,K]... [--case dtype,T,N,K,ldy]...\n",p); + std::printf(" [--shapes-file PATH [--tokens T1,T2,...]] [--tuning-out PATH]\n"); + std::printf("Defaults: original three shapes, f16+bf16, T=8192, workspace=32 MiB.\n"); +} +Options options(int argc,char **argv) { + Options o; + for (int i=1;i std::string { if(i+1>=argc){std::fprintf(stderr,"missing option value\n");std::exit(2);} return argv[++i]; }; + if(a=="-h"||a=="--help"){usage(argv[0]);std::exit(0);} + else if(a=="--workspace-mib"){ + std::string v=next(); char *e=nullptr; unsigned long long x=std::strtoull(v.c_str(),&e,10); + if(v.empty()||!e||*e||x>std::numeric_limits::max()/(1024ULL*1024ULL)){std::fprintf(stderr,"bad workspace MiB\n");std::exit(2);} + o.workspace=(size_t)x*1024U*1024U; + } else if(a=="--shape") add_shape(o,next()); + else if(a=="--case") add_case(o,next()); + else if(a=="--shapes-file"){o.shapes_file=next();o.explicit_shapes=true;} + else if(a=="--tokens") o.tokens=parse_tokens(next()); + else if(a=="--tuning-out") o.tuning_out=next(); + else {std::fprintf(stderr,"unknown option: %s\n",a.c_str());usage(argv[0]);std::exit(2);} + } + if(!o.shapes_file.empty()) load_shapes(o); + if(!o.explicit_shapes) { + struct DefaultShape { int n,k,ldy; bool bf16; }; + const DefaultShape defs[]={{10240,2560,10240,false},{320,10240,320,false},{2560,320,2560,false}, + {10240,2560,10240,true},{320,10240,320,true},{2560,320,2560,true}}; + for(const auto &s:defs) add(o,s.bf16,8192,s.n,s.k,s.ldy); + } + if(o.shapes.empty()){std::fprintf(stderr,"no shapes requested\n");std::exit(2);} + return o; +} +std::string arch_name(const char *s) { + std::string a=s?s:"unknown"; size_t p=a.find(':'); if(p!=std::string::npos)a.resize(p); return a; +} +void emit_candidate(const Shape &s,size_t workspace,int h,int id,size_t req,size_t algows,float ms,const Err &error, + const std::string &arch,int version,const std::string &sol,const std::string &kernel,const std::string &config) { + std::cout<<"candidate_json={\"device_arch\":"<&bests) { + const size_t na=(size_t)s.k*s.n, nb=(size_t)s.k*s.t, out_elems=(size_t)s.ldy*s.t; + const hipDataType it=s.bf16?HIP_R_16BF:HIP_R_16F; + const hipblasOperation_t ta=HIPBLAS_OP_T,tb=HIPBLAS_OP_N; + const int m=s.n,n=s.t,k=s.k,lda=s.k,ldb=s.k,ldc=s.ldy; + const float alpha=1.f,beta=0.f; + std::vector ha(na),hb(nb); + uint32_t seed=0x5A17C3U+(uint32_t)case_id*0x10001U+(s.bf16?0xB16U:0xF16U); + fill(ha,seed,s.bf16);fill(hb,seed^0x9E3779B9U,s.bf16); + Buffer da(na*sizeof(uint16_t)),db(nb*sizeof(uint16_t)),dc(out_elems*sizeof(float)),dy(out_elems*sizeof(float)),dws(ws); + const std::vector canary(out_elems,PADDING_CANARY); + HIP_CHECK(hipMemcpyAsync(dc.p,canary.data(),out_elems*sizeof(float),hipMemcpyHostToDevice,stream)); + HIP_CHECK(hipMemcpyAsync(da.p,ha.data(),na*sizeof(uint16_t),hipMemcpyHostToDevice,stream)); + HIP_CHECK(hipMemcpyAsync(db.p,hb.data(),nb*sizeof(uint16_t),hipMemcpyHostToDevice,stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + + hipblasLtMatmulDesc_t op=nullptr; + hipblasLtMatrixLayout_t ad=nullptr,bd=nullptr,cd=nullptr; + hipblasLtMatmulPreference_t pref=nullptr; + LT_CHECK(hipblasLtMatmulDescCreate(&op,HIPBLAS_COMPUTE_32F,HIP_R_32F)); + LT_CHECK(hipblasLtMatmulDescSetAttribute(op,HIPBLASLT_MATMUL_DESC_TRANSA,&ta,sizeof(ta))); + LT_CHECK(hipblasLtMatmulDescSetAttribute(op,HIPBLASLT_MATMUL_DESC_TRANSB,&tb,sizeof(tb))); + LT_CHECK(hipblasLtMatrixLayoutCreate(&ad,it,s.k,s.n,lda)); + LT_CHECK(hipblasLtMatrixLayoutCreate(&bd,it,s.k,s.t,ldb)); + LT_CHECK(hipblasLtMatrixLayoutCreate(&cd,HIP_R_32F,s.n,s.t,ldc)); + LT_CHECK(hipblasLtMatmulPreferenceCreate(&pref)); + const uint64_t limit=ws; + LT_CHECK(hipblasLtMatmulPreferenceSetAttribute(pref,HIPBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES,&limit,sizeof(limit))); + + BLAS_CHECK(hipblasSetStream(blas,stream)); + auto base=[&]{BLAS_CHECK(hipblasGemmEx(blas,ta,tb,m,n,k,&alpha,da.p,it,lda,db.p,it,ldb,&beta,dc.p,HIP_R_32F,ldc,HIPBLAS_COMPUTE_32F,HIPBLAS_GEMM_DEFAULT));}; + for(int i=0;i ref(out_elems); + HIP_CHECK(hipMemcpyAsync(ref.data(),dc.p,out_elems*sizeof(float),hipMemcpyDeviceToHost,stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + const size_t baseline_padding=padding_writes(ref,s.n,s.t,s.ldy); + std::printf("baseline dtype=%s T=%d N=%d K=%d ldy=%d padding_writes=%zu\n",dtype(s.bf16),s.t,s.n,s.k,s.ldy,baseline_padding); + float base_mean=(base_ms[0]+base_ms[1]+base_ms[2])/REPS; + + hipblasLtMatmulHeuristicResult_t hs[MAX_ALGOS]{}; + int count=0; + const hipblasStatus_t query=hipblasLtMatmulAlgoGetHeuristic(lt,op,ad,bd,cd,cd,pref,MAX_ALGOS,hs,&count); + std::printf("case dtype=%s T=%d N=%d K=%d ldy=%d workspace_limit_bytes=%zu baseline=hipblasGemmEx rep1_ms=%.4f rep2_ms=%.4f rep3_ms=%.4f mean_ms=%.4f\n", + dtype(s.bf16),s.t,s.n,s.k,s.ldy,ws,base_ms[0],base_ms[1],base_ms[2],base_mean); + if(query!=HIPBLAS_STATUS_SUCCESS||count==0){ + std::printf("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d status=%s(%d) heuristic_count=%d\n", + dtype(s.bf16),s.t,s.n,s.k,s.ldy,status_name(query),(int)query,count); + } else { + int best_h=-1,best_id=-1; float best_ms=std::numeric_limits::infinity(); + size_t best_req=0,best_maxws=0; std::string best_sol,best_kernel,best_config; + Err best_error{std::numeric_limits::infinity(),std::numeric_limits::infinity(),false,0}; + for(int h=0;hws){ + std::printf("lt_skip dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d status=%s(%d) required_workspace_bytes=%zu\n", + dtype(s.bf16),s.t,s.n,s.k,s.ldy,h,status_name(hs[h].state),(int)hs[h].state,hs[h].workspaceSize); + continue; + } + auto algo=hs[h].algo; + const int id=hipblaslt_ext::getIndexFromAlgo(algo); + const std::string sol=hipblaslt_ext::getSolutionNameFromAlgo(lt,algo); + const std::string kernel=hipblaslt_ext::getKernelNameFromAlgo(lt,algo); + const std::string config=config_hex(algo); + auto run=[&]{LT_CHECK(hipblasLtMatmul(lt,op,&alpha,da.p,ad,db.p,bd,&beta,dy.p,cd,dy.p,cd,&algo,dws.p,ws,stream));}; + + HIP_CHECK(hipMemcpyAsync(dy.p,canary.data(),out_elems*sizeof(float),hipMemcpyHostToDevice,stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + const hipblasStatus_t check_status=hipblasLtMatmul(lt,op,&alpha,da.p,ad,db.p,bd,&beta,dy.p,cd,dy.p,cd,&algo,dws.p,ws,stream); + if(check_status!=HIPBLAS_STATUS_SUCCESS){ + std::printf("lt_unsupported dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d status=%s(%d) phase=accuracy_check\n", + dtype(s.bf16),s.t,s.n,s.k,s.ldy,h,id,status_name(check_status),(int)check_status);continue; + } + HIP_CHECK(hipStreamSynchronize(stream)); + std::vector checked_y(out_elems); + HIP_CHECK(hipMemcpyAsync(checked_y.data(),dy.p,out_elems*sizeof(float),hipMemcpyDeviceToHost,stream)); + HIP_CHECK(hipStreamSynchronize(stream)); + Err error=compare(ref,checked_y,s.n,s.t,s.ldy); + error.padding_writes=padding_writes(checked_y,s.n,s.t,s.ldy); + if(!accuracy_ok(error)){ + std::printf("lt_reject dtype=%s T=%d N=%d K=%d ldy=%d heuristic_index=%d solution_id=%d finite=%s relative_l2=%.12g relative_l2_tolerance=%.3g max_abs=%.12g max_abs_tolerance=%.3g padding_writes=%zu reason=accuracy_gate\n", + dtype(s.bf16),s.t,s.n,s.k,s.ldy,h,id,error.finite?"true":"false", + error.rel_l2,REL_L2_TOL,error.max_abs,MAX_ABS_TOL,error.padding_writes);continue; + } + + bool failed=false; + for(int i=0;i&rows){ + if(path.empty())return; + std::ofstream f(path); + if(!f){std::fprintf(stderr,"cannot write tuning output: %s\n",path.c_str());std::exit(2);} + f<<"# solution IDs are scoped to this hipBLASLt version and device architecture\n"; + f<<"STRATA_HIPBLASLT_TUNING_V1 "<bests; + for(size_t i=0;i/.bin` (int32 header: the KERNEL type id, +rows, cols - then the raw GGUF block bytes) and `/.f32` (rows*cols float32 reference values, +dequantized by the same library the comparison treats as ground truth): + + python tools/iq_fixture.py --out build/iq_fixture + python tools/iq_fixture.py --out build/iq_fixture --seed 7 --rows 32 --cols 256 + +Generation is deterministic: an explicit seed and fixed dimensions, and every random choice comes from +numpy's RandomState under that seed. The blocks are synthetic on purpose: the i-quant formats have no +published quantizer in gguf-py (it dequantizes only), so each block combines sane half-precision scales +(written at the layout's scale offsets, see SCALE_OFFSETS below) with seeded index/sub-scale bytes - the +dequantized reference covers real codebook values either way, which is what the parity compares. + +Dependencies: python3 and numpy, plus the repository's VENDORED gguf-py (third_party/llama.cpp/gguf-py - +no pip install; it is put on sys.path relative to this file). Q2_0 is this repository's own format +(GGML type 42, which gguf-py does not carry): its codec comes from tools/gguf_writer.py. + +The kernel ids in the .bin headers are the repo's i-quant dispatch table (iq_kernels.cu is_iq / +iq_row_bytes) and match the vendored gguf-py's enum ids one for one - the layout table below is the +same GGML_QUANT_SIZES both sides compile in. +""" +from __future__ import annotations + +import argparse +import struct +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "third_party" / "llama.cpp" / "gguf-py")) +sys.path.insert(0, str(ROOT / "tools")) + +try: + import gguf + from gguf.quants import dequantize as gguf_dequantize + from gguf_writer import dequantize_q2_0, quantize_q2_0 +except ImportError as e: # a missing numpy or vendored gguf-py must be explicit, not a traceback + sys.stderr.write(f"iq_fixture: missing dependency: {e}\n" + "numpy and the repository's vendored gguf-py (third_party/llama.cpp/gguf-py) are " + "required. The vendored copy comes with setup's llama.cpp download (the pinned " + "LLAMA_CPP_COMMIT zip); on a fresh checkout run setup once, or fetch that zip and " + "unpack its gguf-py there.\n") + sys.exit(3) + +QT = gguf.GGMLQuantizationType +# name -> (block values, block bytes, the fp16 scale offsets inside a block). The layouts mirror +# gguf-py's dequantize_blocks implementations: every one of these formats keeps its half-precision +# scale(s) at fixed offsets (IQ*_X*: offset 0; Q3_K: after the 32-byte hmask, 64-byte qs and the +# 12 scale bytes) - the rest of the block is indices and sub-scales, which are seeded random bytes. +LAYOUT = { # (block values, block bytes) == the vendored gguf-py's GGML_QUANT_SIZES == the kernels' sizes + "IQ2_XXS": (256, 66), + "IQ2_XS": (256, 74), + "IQ2_S": (256, 82), + "IQ3_XXS": (256, 98), + "IQ3_S": (256, 110), + "IQ1_M": (256, 56), + "IQ4_NL": (32, 18), + "IQ4_XS": (256, 136), + "Q3_K": (256, 110), +} +HALF_ONE = struct.pack(" None: + """Overwrite the fp16 scale bits of every block with a sane value, in place. The index and + sub-scale bytes stay seeded-random (their values are bounded by construction). Layouts mirror + gguf-py's dequantize_blocks: IQ*_X* and IQ4_* keep the fp16 scale at block offset 0; Q3_K keeps + it after the 32-byte hmask, 64-byte qs and 12 scale bytes; IQ1_M is "the only one which stores + the f16 scale in multiple parts" - the fp16 bits are the HIGH NIBBLES of the four uint16s at + bytes 48..56, so a 1.0 scale is nibbles 3, C, 0, 0 on bytes 49, 51, 54, 55.""" + if name == "Q3_K": + raw[:, 108:110] = np.frombuffer(HALF_ONE, dtype=np.uint8) + return + if name == "IQ1_M": + raw[:, 48:56] &= np.uint8(0x0F) # clear the four scale nibbles + for byte, nib in ((49, 0x30), (51, 0xC0), (54, 0x00), (55, 0x00)): + raw[:, byte] |= np.uint8(nib) + return + raw[:, 0:2] = np.frombuffer(HALF_ONE, dtype=np.uint8) +# name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id) +KERNEL_IDS = {"IQ2_XXS": 16, "IQ2_XS": 17, "IQ2_S": 22, "IQ3_XXS": 18, "IQ3_S": 21, + "IQ1_M": 29, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} + + +def build(name: str, rows: int, cols: int, seed: int): + """The .bin body (header + raw blocks) and the .f32 reference for one type.""" + kernel_type = KERNEL_IDS[name] + n = rows * cols + rng = np.random.RandomState((seed, hash(name) & 0xFFFF) if False else (seed, KERNEL_IDS[name])) + if name == "Q2_0": # the repository's own codec, gguf-py has no type 42 + w = rng.standard_normal(n).astype(np.float32) + raw = np.frombuffer(quantize_q2_0(w), dtype=np.uint8) + ref = dequantize_q2_0(raw.tobytes()).astype(np.float32) + flat = raw + else: + block_values, block_bytes = LAYOUT[name] + blocks = n // block_values + raw = rng.randint(0, 256, (blocks, block_bytes), dtype=np.uint8) + repair_scales(name, raw) # sane fp16 scales; indices stay seeded-random + flat = raw.reshape(-1) + ref = np.asarray(gguf_dequantize(flat, getattr(QT, name)), dtype=np.float32) + if not np.isfinite(ref).all() or float(np.abs(ref).max()) > 1e4: + raise RuntimeError(f"{name}: the dequantized reference is not finite/tame - the layout table " + f"(block bytes, scale offsets) does not match gguf-py's dequantizer") + header = struct.pack("<3i", kernel_type, rows, cols) + return header + flat.tobytes(), ref + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--out", default="logs/iq_fixture", help="the fixture directory (created; may live in the " + "build directory - the source tree is not written)") + ap.add_argument("--seed", type=int, default=7, help="the fixture RNG seed (deterministic generation)") + ap.add_argument("--rows", type=int, default=32, help="weight rows (rows*cols stays a multiple of 256)") + ap.add_argument("--cols", type=int, default=256, help="the reduction dimension, a multiple of 256") + args = ap.parse_args() + if args.cols % 256 or args.rows * args.cols % 256: + ap.error("--cols must be a multiple of 256 and rows*cols a multiple of 256") + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + for name in KERNEL_IDS: + blob, ref = build(name, args.rows, args.cols, args.seed) + (out / f"{name}.bin").write_bytes(blob) + (out / f"{name}.f32").write_bytes(np.ascontiguousarray(ref, dtype="2} {args.rows} x {args.cols} " + f"{len(blob) - 12} block bytes, {ref.size} reference floats") + print(f"iq_fixture: {len(KERNEL_IDS)} fixtures in {out} (seed {args.seed})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/iq_pack.py b/engine/strata/tools/iq_pack.py new file mode 100644 index 00000000..86766755 --- /dev/null +++ b/engine/strata/tools/iq_pack.py @@ -0,0 +1,602 @@ +"""tools/iq_pack.py - plan v0.3 P6: a native pack for any of the model files (Q2_0, IQ2_XS, IQ3_XXS). + + python tools/iq_pack.py --gguf -00001-of-00002.gguf --out pack/iq3_xxs (standalone) + python tools/iq_pack.py --gguf -00001-of-00002.gguf --base pack/full --out ... (share dense.bin) + +The i-quant experts cannot be re-expressed in the Q2_0 pack form, so this pack keeps every quantized tensor in +its GGUF form: + + experts.bin optional (--experts-bin): per layer, 512 blobs of [gate rows | up rows | down rows], the + raw GGUF slices. Blob size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 / + IQ4_NL down). experts.bin.src.json says which source it was cut from (the shards' names and + sizes, the hash of native_experts.txt); an experts.bin is reused only when that matches. + native_experts.txt one line per layer: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]; + written last, so a pack without it is not finished + index.txt the table the engine loads. Quantized dense tensors, token_embd and output are served + natively from the GGUF by the engine (--native): their rows carry shape only. + dense.bin standalone: the BF16/F16/F32 tensors in the form the engine reads them (index kinds 4/5/2; + 3 = F32 narrowed to F16 by the loader) - as the GGUF stores them, or converted (FORM below). + conversions.json every tensor that was converted: shard, source/destination type, method, whether it was + exact, the largest absolute error, the source bytes' sha256 (schema 1). + With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are + byte-identical in all three model files (checked) - plus extra.bin for tensors that are + float here but quantized in the base pack (blk.1.ple_key). + tokenizer/ exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template. + +Split files: every shard of the model is read (-0000N-of-0000M.gguf beside --gguf; a missing shard is an +error), so the layers may be split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in +shard 1). A layer whose experts are not in shard 1 names its shard in native_experts.txt (v3). A shard boundary +may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, its gate and up in shard 3): that +layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file +v4, so an older engine refuses it instead of misreading it. Every other pack stays v3, byte for byte. Router +tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router +takes (so are the other F32 tensors the engine reads as BF16, when exact); anything else is refused. + +For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using +round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision +weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE +table stay unchanged. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys + +import numpy as np + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import gguf_reader as G # noqa: E402 + +FLOAT = {"BF16", "F32", "F16"} +ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight") +NOT_IN_PACK = {"per_layer_token_embd.weight"} # the 28.8 GB PLE table: read from its GGUF by the engine + +# The float form the engine reads each pack tensor in (name without `blk.N.`; from eddoursul/Strata's FORM table). +# The residual, router, GDN, QSA and PLE kernels read these small projections as BF16, the norms as F32 and the PLE +# conv as F16. GSQ-RCO files already store them that way; other files do not (Unsloth's UD-Q4_K_XL: the routers, +# SSM gates and injections F32, the hyper-connection projections and the PLE value Q8_0, the PLE conv F32), so a +# tensor stored otherwise is converted, and every conversion is recorded in conversions.json: +# F32 -> BF16 whose values are exactly BF16 (low 16 bits zero) exact, by default +# F32 with other values, F16 or a quantized type -> BF16 rounds (nearest-even): only with --compat-bf16 +# F32 -> F16 (ple_conv1d) index kind 3, narrowed by the loader (#255), +# by default - the kernel reads nothing else +# F16 / BF16 -> F32 exact widening, by default +# Tensors not named here are written as stored (floats) or served from the GGUF (quantized), as before. +FORM = { + "ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16", + "hc_attn_down.weight": "BF16", "hc_attn_up.weight": "BF16", "hc_attn_inject.weight": "BF16", + "hc_ffn_down.weight": "BF16", "hc_ffn_up.weight": "BF16", "hc_ffn_inject.weight": "BF16", + "output_hc_down.weight": "BF16", "output_hc_up.weight": "BF16", + "indexer.k_proj.weight": "BF16", "indexer.q_proj.weight": "BF16", + "ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16", + "ple_key.weight": "BF16", "ple_value.weight": "BF16", "ple_conv1d.weight": "F16", + "attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "hc_attn_norm.weight": "F32", + "hc_ffn_norm.weight": "F32", "output_hc_norm.weight": "F32", "indexer.q_norm.weight": "F32", + "indexer.k_norm.weight": "F32", "ple_norm_conv.weight": "F32", "ple_norm_key.weight": "F32", + "ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32", + "ssm_norm.weight": "F32", +} +# PLE key encodings left in the GGUF for the engine's native PLE key (Q2_0; Q8_0 in UD-Q4_K_XL). Other quantized +# keys take the BF16 path (--compat-bf16), as before. +NATIVE_PLE_KEY = {"Q2_0", "Q8_0"} +KIND = {"BF16": "4", "F16": "5", "F32": "2"} + + +def form_of(name: str): + return FORM.get(re.sub(r"^blk\.\d+\.", "", name)) + + +def needs_bf16(name: str, type_name: str) -> bool: + """Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF).""" + if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY: + return False + return form_of(name) == "BF16" + + +def dequantize(raw: np.ndarray, type_name: str) -> np.ndarray: + """The tensor's values as float32 (float types exactly, quantized ones through gguf-py's dequantizer).""" + if type_name == "F32": + return raw.view(np.float32) + if type_name == "F16": + return raw.view(np.float16).astype(np.float32) + if type_name == "BF16": + return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32) + from _paths import add_gguf_py + add_gguf_py() + from gguf import GGMLQuantizationType as Q, quants + return quants.dequantize(raw, Q[type_name]).astype(np.float32).reshape(-1) + + +def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes: + from _paths import add_gguf_py + add_gguf_py() + from gguf import GGMLQuantizationType as Q, quants + values = quants.dequantize(raw, Q[type_name]) + if not np.isfinite(values).all(): + raise ValueError("cannot convert non-finite weights to BF16") + # ggml's round-to-nearest-even conversion, including correct halfway rounding. + return quants.quantize(values, Q.BF16).tobytes() + + +def f16_values(values: np.ndarray, name: str) -> np.ndarray: + """values -> F16, nearest-even (numpy's conversion, which is the engine loader's f16_from_f32); refuses a value + that is not finite or overflows F16.""" + if not np.isfinite(values).all(): + raise ValueError(f"{name}: cannot convert non-finite weights to F16") + with np.errstate(over="ignore"): + h = values.astype(np.float16) + if not np.isfinite(h).all(): + raise ValueError(f"{name}: a value is beyond F16's range, which the engine reads it as") + return h + + +class Model: + """All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path).""" + + def __init__(self, first: pathlib.Path): + import re + m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", first.name) + paths = [first] + if m: + total = int(m.group(2)) + paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total)) + for i in range(1, total + 1)] + missing = [str(p) for p in paths if not p.is_file()] + if missing: + raise FileNotFoundError("missing model shards (wait for the download): " + ", ".join(missing)) + self.paths = paths + self.files = [G.GGUFFile(p) for p in paths] + self.sizes = [p.stat().st_size for p in paths] + check_split(self.files) + self.where = {} + for p, g in zip(paths, self.files): + mm = np.memmap(p, dtype=np.uint8, mode="r") + for t in g.tensors: + size = t.expected_bytes() + if size is None or g.data_start + t.offset + size > mm.size: + raise ValueError(f"{p.name}: unsupported or truncated tensor {t.name}") + if t.name in self.where: + raise ValueError(f"{p.name}: duplicate tensor {t.name}") + self.where[t.name] = (g, t, mm, p) + + def bytes(self, name) -> np.ndarray: + g, t, mm, _ = self.where[name] + return tensor_bytes(mm, g, t) + + +def check_split(files) -> None: + """The split keys, as the engine checks them (strata::GgufModel): shard 1 carries the metadata, and every shard + declares split.count / split.no (and split.tensors.count) consistently - a shard of another model, or a shard + renamed into the family, is refused rather than mixed in.""" + n = len(files) + meta0 = files[0].metadata + if n == 1: + if int(meta0.get("split.count", 1)) > 1: + raise ValueError(f"{files[0].path.name} is shard 1 of {meta0['split.count']}, but its name has no " + "-00001-of-0000N.gguf to find the others by") + return + if "general.architecture" not in meta0: + raise ValueError(f"{files[0].path.name} has no general.architecture; the first shard of a split model " + "carries the metadata") + total = meta0.get("split.tensors.count") + for i, g in enumerate(files): + md = g.metadata + if md.get("split.count") != n or md.get("split.no") != i or \ + (total is not None and md.get("split.tensors.count") != total): + raise ValueError(f"{g.path.name} does not declare itself shard {i + 1} of {n} of this model " + "(split.count / split.no / split.tensors.count)") + if total is not None and sum(len(g.tensors) for g in files) != total: + raise ValueError(f"the {n} shards hold {sum(len(g.tensors) for g in files)} tensors, but " + f"split.tensors.count is {total}") + + +ROLES = ("gate", "up", "down") +N_EXPERT = 512 +ALIGN = 64 + + +def read_index(path: pathlib.Path): + rows, header = {}, [] + for line in path.read_text(encoding="utf-8").splitlines(): + if line.startswith("#"): + header.append(line) + continue + f = line.split() + rows[f[0]] = f + return header, rows + + +def tensor_bytes(mm, g, t) -> np.ndarray: + n = t.expected_bytes() + return mm[g.data_start + t.offset: g.data_start + t.offset + n] + + +def is_expert(name: str) -> bool: + return name.startswith("blk.") and name.endswith(("_exps.weight",)) + + +def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool): + """The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes, + record or None), or an error string. `record` describes a conversion for conversions.json.""" + form = form_of(name) + if form is None or form == type_name: + return KIND[type_name], raw.tobytes(), raw.nbytes, None + values = dequantize(raw, type_name) + rec = {"src_type": type_name, "dst_type": form} + if form == "BF16": + u = values.view(np.uint32) if type_name == "F32" else None + if u is not None and not np.count_nonzero(u & 0xFFFF): + if not np.isfinite(values).all(): + return f"{name} is F32 with non-finite values; refused rather than converted" + data = (u >> 16).astype("bf16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) + rec.update(exact=bool(np.array_equal(got, values)), + max_abs_err=float(np.max(np.abs(got.astype(np.float64) - values))) if values.size else 0.0) + return "4", data, len(data), rec + if form == "F16": + if type_name != "F32" and not compat_bf16: + return f"{name} is {type_name}, but the engine reads F16; use --compat-bf16 (rounds to nearest-even)" + h = f16_values(values, name) + err = float(np.max(np.abs(h.astype(np.float64) - values))) if values.size else 0.0 + rec.update(exact=bool(np.array_equal(h.astype(np.float32), values)), max_abs_err=err) + if type_name == "F32": + # The F32 bytes go into dense.bin as index kind 3 and the loader narrows them to F16 (nearest-even), the + # form the PLE conv kernel reads (#255, gopinath87607): 4 B/elem in, 2 B/elem out. + rec.update(method="f32->f16 by the loader (index kind 3, round-to-nearest-even)") + return "3", raw.tobytes(), raw.nbytes // 2, rec + rec.update(method="%s->f16 round-to-nearest-even (--compat-bf16)" % type_name.lower()) + data = h.astype(" int: + """Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it + reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF.""" + todo, problems = [], [] + for name, (g, t, mm, p) in model.where.items(): + if is_expert(t.name) or t.name in NOT_IN_PACK: + continue + if len(t.shape) > 2: + print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape))) + return 1 + # quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes + # --compat-bf16 to dequantize - except the native PLE key encodings + form = form_of(name) + native = t.type_name not in FLOAT and (form is None or ( + name == "blk.1.ple_key.weight" and t.type_name in NATIVE_PLE_KEY)) + if t.type_name not in FLOAT and not native and not compat_bf16: + problems.append(f"{name} is {t.type_name}, but the engine requires {form}; use --compat-bf16") + todo.append((name, g, t, mm, p, native)) + # refused before anything is written: the previous pack stays as it was + if problems: + for m in problems[:8]: + print(m) + if len(problems) > 8: + print("... and %d more" % (len(problems) - 8)) + return 1 + rows, at = [], 0 + served = 0 + converted, records = [], [] + with open(out / "dense.bin.tmp", "wb") as fo: + for name, g, t, mm, p, native in todo: + ne0 = int(t.shape[0]) + ne1 = int(t.shape[1]) if len(t.shape) > 1 else 0 + if native: + served += 1 + rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7) + continue + raw = tensor_bytes(mm, g, t) + try: + got = convert(name, t.type_name, raw, compat_bf16) + except ValueError as e: + got = str(e) + if isinstance(got, str): + print(got) + fo.close() + (out / "dense.bin.tmp").unlink(missing_ok=True) + return 1 + kind, data, dst_bytes, rec = got + if rec is not None: + rec = {"name": name, "shard": p.name, **rec, + "source_sha256": hashlib.sha256(raw.tobytes()).hexdigest()} + records.append(rec) + if "--compat-bf16" in rec["method"]: # the rounding the flag allowed + converted.append({"name": name, "source_type": t.type_name, "bytes": len(data)}) + rows.append([t.name, "0", kind, str(at), str(len(data)), "0", str(dst_bytes), str(ne0), str(ne1), + "0", "0", "1"] + ["0"] * 7) + fo.write(data) + pad = (-len(data)) % ALIGN + fo.write(b"\0" * pad) + at += len(data) + pad + write_index(out, rows, src, served, 0, publish=False) + conv = out / "conversions.json.tmp" + conv.write_text(json.dumps({ + "schema": 1, "tool": "tools/iq_pack.py", "compat_bf16": compat_bf16, + "source_shards": [{"name": q.name, "size": s} for q, s in zip(model.paths, model.sizes)], + "tensors": records, + }, indent=1) + "\n", encoding="utf-8") + # published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop + # from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old + # index or the reverse + (out / "native_experts.txt").unlink(missing_ok=True) + (out / "dense.bin.tmp").replace(out / "dense.bin") + (out / "index.txt.tmp").replace(out / "index.txt") + conv.replace(out / "conversions.json") + if records: + exact = sum(1 for r in records if r["exact"]) + print("conversions.json: %d tensors converted to the engine's form (%d exact, %d rounded; max |err| %.3g)" + % (len(records), exact, len(records) - exact, max(r["max_abs_err"] for r in records))) + for r in records: + if r["dst_type"] == "F16": + print("narrowed to F16 by the loader: %s (%s, index kind 3)" % (r["name"], r["method"])) + if compat_bf16: + (out / "compat-bf16.json").write_text(json.dumps({ + "source": str(src), "rounding": "nearest-even", "tensors": converted, + }, indent=2) + "\n", encoding="utf-8") + print("compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged" + % (len(converted), sum(t["bytes"] for t in converted) / 2**30)) + return 0 + + +def write_index(out, rows, src, served, n_extra, publish=True): + at = 0 + for r in rows: + r[5] = str(at) + at += (int(r[6]) + ALIGN - 1) // ALIGN * ALIGN + with open(out / "index.txt.tmp", "w", encoding="utf-8", newline="\n") as fo: + fo.write("# strata pack index v3 -- generated by tools/iq_pack.py (native experts) from %s\n" % src.name) + fo.write("# align %d pool %d tensors %d\n" % (ALIGN, at, len(rows))) + for r in rows: + fo.write(" ".join(r) + "\n") + if publish: + (out / "index.txt.tmp").replace(out / "index.txt") + print("index.txt: %d tensors, %d served natively, %d in extra.bin, arena %.2f GiB" + % (len(rows), served, n_extra, at / 2**30)) + + +def index_from_base(a, src, base, out, g, T, mm) -> int: + base_src = pathlib.Path(json.loads((base / "manifest.json").read_text(encoding="utf-8"))["source"]["shard1"]) + if not base_src.exists(): + print("cannot find the base pack's shard 1 from its manifest.json") + return 1 + bg = G.GGUFFile(base_src) + BT = {t.name: t for t in bg.tensors} + bmm = np.memmap(base_src, dtype=np.uint8, mode="r") + header, rows = read_index(base / "index.txt") + new_rows, extra = [], [] + served = 0 + for name, f in rows.items(): + t, bt = T.get(name), BT.get(name) + if t is None or bt is None: + print("tensor %s missing from one of the models" % name) + return 1 + if t.type_name in FLOAT and bt.type_name in FLOAT: + if t.type_name != bt.type_name or t.shape != bt.shape or \ + not np.array_equal(tensor_bytes(mm, g, t), tensor_bytes(bmm, bg, bt)): + print("float tensor %s differs from the base model; this pack cannot reuse its dense.bin" % name) + return 1 + new_rows.append(list(f)) + elif t.type_name in FLOAT: + if t.type_name != "BF16": + print("unexpected float type %s for %s" % (t.type_name, name)) + return 1 + nbytes = t.expected_bytes() + off = sum(len(b) + (-len(b)) % ALIGN for b in extra) + extra.append(tensor_bytes(mm, g, t).tobytes()) + # file 3 = extra.bin, raw BF16 (index kind 4) + new_rows.append([name, "3", "4", str(off), str(nbytes), "0", str(nbytes), f[7], f[8]] + ["0"] * 10) + else: + served += 1 + new_rows.append([name, f[1], "0", "0", "0", "0", "0", f[7], f[8], "8", "0", "32"] + ["0"] * 7) + write_index(out, new_rows, src, served, len(extra)) + with open(out / "extra.bin", "wb") as fo: + for b in extra: + fo.write(b) + fo.write(b"\0" * ((-len(b)) % ALIGN)) + dense = out / "dense.bin" + if not dense.exists(): + try: + os.link(base / "dense.bin", dense) + except OSError: + shutil.copyfile(base / "dense.bin", dense) + if (base / "tokenizer").exists() and not (out / "tokenizer").exists(): + shutil.copytree(base / "tokenizer", out / "tokenizer") + return 0 + + +def expert_layout(model: Model, src: pathlib.Path): + """The pack's expert table: (layout rows, native_experts.txt text, n_expert, total bytes), or an error string. + Each role is resolved by name in whichever shard holds it, and its offset is absolute in THAT shard: two + shards do not start their data section at the same byte, so one role's data_start must not be used for + another's (per-role data_start as in #255, gopinath87607).""" + T = {n: w[1] for n, w in model.where.items()} + exps = [n for n in T if n.startswith("blk.") and n.endswith("_exps.weight")] + if not exps: + return "the model has no expert tensors (blk.N.ffn_{gate,up,down}_exps.weight)" + n_layers = 1 + max(int(n.split(".")[1]) for n in exps) + n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1]) # router rows = experts kept (pruned models ship < 512) + if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)): + return "the routers disagree on the expert count; a per-layer pruned model cannot be packed" + layout, lines, offset, n_split = [], [], 0, 0 + for l in range(n_layers): + names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for r in ROLES] + if any(n not in T for n in names): + return "layer %d: missing %s" % (l, ", ".join(n for n in names if n not in T)) + ts = [T[n] for n in names] + if any(t.expected_bytes() is None or len(t.shape) != 3 or int(t.shape[2]) != n_expert for t in ts): + return "layer %d: an expert tensor is not [*, *, %d] of whole blocks" % (l, n_expert) + per = [t.expected_bytes() // n_expert for t in ts] + if per[0] != per[1] or ts[0].type_name != ts[1].type_name: + return "layer %d: gate and up differ in type" % l + blob = per[0] + per[1] + per[2] + layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts)) + ws = [model.where[n] for n in names] + files = ["" if w[3] == src else w[3].name for w in ws] + column = files[0] if len(set(files)) == 1 else ",".join(files) + n_split += len(set(files)) != 1 + line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob, + *[w[0].data_start + w[1].offset for w in ws]) + lines.append(line + ("" if not column else " " + column)) + offset += blob * n_expert + if n_split: + head = ("# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " + "[shard | gate,up,down] (n_expert %d, total %d; absolute offsets in %s, or in the named shard " + "beside it - per role where the column is gate,up,down)\n" % (n_expert, offset, src.name)) + print("%d layer(s) have their gate/up/down in different shards: native_experts.txt v4, per-role shard " + "column for %s" % (n_split, ", ".join(str(l) for l, *_ in layout if "," in lines[l]))) + else: + head = ("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " + "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" + % (n_expert, offset, src.name)) + return layout, head + "".join(line + "\n" for line in lines), n_expert, offset + + +def experts_source(model: Model, text: str, total: int) -> dict: + """What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every + per-role file and offset, the formats and the blob sizes). A same-size experts.bin of another model or + another packing is not this one.""" + return {"schema": 1, + "shards": [{"name": p.name, "size": s} for p, s in zip(model.paths, model.sizes)], + "native_experts_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), + "bytes": total} + + +def read_json(path: pathlib.Path): + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--gguf", required=True, help="the model's shard 1") + ap.add_argument("--base", help="optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors") + ap.add_argument("--out", required=True) + ap.add_argument("--skip-experts", action="store_true", help="rewrite the index only") + ap.add_argument("--compat-bf16", action="store_true", + help="dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs " + "(rounds weights; leaves experts and the PLE table unchanged)") + ap.add_argument("--experts-bin", action="store_true", + help="also write experts.bin (the engine otherwise reads the experts from the GGUF itself)") + a = ap.parse_args() + if a.compat_bf16 and a.base: + ap.error("--compat-bf16 cannot reuse --base dense weights") + # HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery: .absolute(), not + # .resolve(), which would follow the link to the blob and lose the -0000N-of-0000M name. + src = pathlib.Path(a.gguf).absolute() + base = pathlib.Path(a.base).resolve() if a.base else None + out = pathlib.Path(a.out) + out.mkdir(parents=True, exist_ok=True) + + g = G.GGUFFile(src) + mm = np.memmap(src, dtype=np.uint8, mode="r") + model = Model(src) + if len(model.paths) > 1: + print("model shards: " + ", ".join(p.name for p in model.paths)) + # ---- the expert table first: a model that cannot be packed is refused before any file of the pack changes + got = expert_layout(model, src) + if isinstance(got, str): + print(got) + return 1 + layout, text, n_expert, offset = got + path = out / "experts.bin" + sidecar = out / "experts.bin.src.json" + want = experts_source(model, text, offset) + reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want + + def layer_blobs(blob, ts): + chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) + assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert + return chunk + + if reuse: + # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same + # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and + # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) + with open(path, "rb") as f: + for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): + for e in (0, n_expert - 1): + f.seek(off + e * blob) + want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) + if f.read(blob) != want_blob: + reuse = False + if not reuse: + print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) + if path.exists() and not reuse and not a.experts_bin: + if sidecar.exists(): + print("%s was cut from another source than this model (%s): the engine would read it instead of " + "the GGUF. Delete it, or rerun with --experts-bin to rewrite it." % (path, sidecar.name)) + return 1 + print("warning: %s has no %s, so nothing says it belongs to this model; the engine reads it instead of " + "the GGUF (rerun with --experts-bin to rewrite it)" % (path, sidecar.name)) + if a.base: + if any(w[3] != src for w in model.where.values() if not w[1].name in NOT_IN_PACK): + print("--base needs a model whose tensors are all in shard 1") + return 1 + (out / "native_experts.txt").unlink(missing_ok=True) + rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm) + else: + rc = index_standalone(src, out, model, a.compat_bf16) + if rc: + return rc + if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists(): + subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)], + check=True) # writes /tokenizer/ + + # ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is + # in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup + # run took as a finished pack (#172). It is the pack's completion marker, so it is published last. + tmp = out / "native_experts.txt.tmp" + with open(tmp, "w", encoding="utf-8", newline="\n") as fo: + fo.write(text) + tmp.replace(out / "native_experts.txt") + if a.skip_experts or not a.experts_bin: + if path.exists() and not a.experts_bin: + print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out) + return 0 + if reuse: + print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name) + return 0 + # written under a temporary name and renamed when complete, then the sidecar: an interrupted write leaves no + # experts.bin, and an experts.bin without its sidecar is never reused + sidecar.unlink(missing_ok=True) + part = out / "experts.bin.tmp" + with open(part, "wb") as fo: + for l, gt, dt, off, blob, ts in layout: + fo.write(layer_blobs(blob, ts).tobytes()) + if l % 8 == 0: + print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, + off / 2**30), flush=True) + part.replace(path) + side_tmp = out / "experts.bin.src.json.tmp" + side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") + side_tmp.replace(sidecar) + print("experts.bin: %d layers, %.2f GiB" % (len(layout), offset / 2**30)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/tools/make_profile.py b/engine/strata/tools/make_profile.py new file mode 100644 index 00000000..0f023848 --- /dev/null +++ b/engine/strata/tools/make_profile.py @@ -0,0 +1,99 @@ +"""tools/make_profile.py - the expert-cache profile (`data/expert-profile.bin`): every (layer, expert) pair, ranked. + +`--expert-cache auto` fills the VRAM slots it can afford with the profile's pairs in order, so the ranking decides +which experts start resident (the adaptive tier then swaps in what a conversation routes most). A profile that +ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card stopped at 8,000 slots); this tool +writes one that ranks all 24,576. + +The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing +traces used, most frequent first, then every pair still missing, interleaved across the layers. + + python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--out PATH] + [--n-expert 256] (a pruned model: GSQ-RCO Coder keeps 256 of 512) + +A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the +routed experts of every layer and position are written). Point the model config's `--expert-profile` at the result. +""" +import argparse +import struct +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +N_LAYER, N_EXPERT = 48, 512 +MAGIC, VERSION = b"STRP", 1 + + +def read_profile(path, n_expert=N_EXPERT): + blob = Path(path).read_bytes() + if blob[:4] != MAGIC: + raise SystemExit(f"{path}: not a Strata profile") + ver, nl, ne, slots, n = struct.unpack_from("<5I", blob, 4) + if (nl, ne) != (N_LAYER, n_expert): + raise SystemExit(f"{path}: {nl}x{ne}, not {N_LAYER}x{n_expert}") + return [struct.unpack_from(" dtype, shape, byte range) +at the start of each shard, so HTTP range requests can read the headers and then only the MTP tensors. + + python tools/mtp_fetch.py inventory --out DIR # headers only (a few KB per shard) + python tools/mtp_fetch.py fetch --out DIR [--only SUBSTR] # the MTP tensors themselves, resumable + python tools/mtp_fetch.py verify --out DIR # the fetched tensors against SHA256 (exit 3: bad ones) + +`fetch` writes one raw file per tensor plus `mtp-manifest.json` (dtype, shape, source shard, byte range, +sha256). It never downloads anything but the ranges named in the headers. Nothing here runs a model. + +#327: a mirror or proxy that ignores the Range header answers 200 with the whole shard - its JSON header and +unrelated tensors - and a proxy may cut that to the requested length, so neither the size nor a hash of what was +downloaded catches it (the drafter then accepts nothing, silently). A range read therefore needs a 206 whose +Content-Range is the range asked for, and every tensor of the pinned revision is checked against SHA256 below. +""" +import argparse +import hashlib +import json +import os +import struct +import sys +import time +import urllib.error +import urllib.request + +# #214: a fixed commit of the checkpoint (its `sha` from https://huggingface.co/api/models/Qwen/Qwen3.8-Flash-Next +# on 2026-09-30), so every install reads the same tensors; STRATA_MTP_REVISION overrides it (e.g. main). When the +# repository no longer has it, the current files are read instead, with a message (resolve_repo). +PINNED_REVISION = "de4b8e4d43b917e7706784d8bb445c9af86a3540" +REVISION = os.environ.get("STRATA_MTP_REVISION") or PINNED_REVISION +REPO = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % REVISION +PINNED = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/%s/" % PINNED_REVISION # SHA256's revision +DTYPE_BYTES = {"BF16": 2, "F16": 2, "F32": 4, "F8_E4M3": 1, "I64": 8, "I32": 4} +BAD = 3 # `verify`'s exit code: a tensor is missing or corrupt + +# #327: sha256 of every MTP tensor's bytes at PINNED_REVISION (two independent fetches agree, and 29 of them were read +# again from that revision; the two expert tensors' first and last 16 MiB), so a mirror that ignored the +# Range header (it sent the shard's start: its JSON header) is caught, and an install it corrupted is fetched again. +SHA256 = { + "mtp.fc_embedding.weight": + "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751", + "mtp.fc_hidden.weight": + "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96", + "mtp.hyper_connection_mixer.hc_norm.weight": + "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64", + "mtp.hyper_connection_mixer.input_mix_weight_down.weight": + "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947", + "mtp.hyper_connection_mixer.input_mix_weight_up.weight": + "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13", + "mtp.layers.0.attn_hyper_connection.block_inject_weight.weight": + "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c", + "mtp.layers.0.attn_hyper_connection.hc_norm.weight": + "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_down.weight": + "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5", + "mtp.layers.0.attn_hyper_connection.input_mix_weight_up.weight": + "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5", + "mtp.layers.0.mlp.experts.down_proj": + "539c46234f73bac70450f731f40e715f77ac32faf77def0f3f800e58aaabbbc0", + "mtp.layers.0.mlp.experts.gate_up_proj": + "839e98f9642ebc884b178abd2090b6dc8b0bcd81ed92d7f7a08314c6a68f96d5", + "mtp.layers.0.mlp.gate.weight": + "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20", + "mtp.layers.0.mlp.shared_expert.down_proj.weight": + "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8", + "mtp.layers.0.mlp.shared_expert.gate_proj.weight": + "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c", + "mtp.layers.0.mlp.shared_expert.up_proj.weight": + "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156", + "mtp.layers.0.mlp.shared_expert_gate.weight": + "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e", + "mtp.layers.0.mlp_hyper_connection.block_inject_weight.weight": + "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6", + "mtp.layers.0.mlp_hyper_connection.hc_norm.weight": + "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_down.weight": + "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1", + "mtp.layers.0.mlp_hyper_connection.input_mix_weight_up.weight": + "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94", + "mtp.layers.0.self_attn.indexer.index_qk_proj.weight": + "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859", + "mtp.layers.0.self_attn.indexer.k_layernorm.weight": + "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54", + "mtp.layers.0.self_attn.indexer.q_layernorm.weight": + "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6", + "mtp.layers.0.self_attn.k_norm.weight": + "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd", + "mtp.layers.0.self_attn.k_proj.weight": + "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38", + "mtp.layers.0.self_attn.o_proj.weight": + "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219", + "mtp.layers.0.self_attn.q_norm.weight": + "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef", + "mtp.layers.0.self_attn.q_proj.weight": + "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d", + "mtp.layers.0.self_attn.v_proj.weight": + "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41", + "mtp.pre_fc_norm_embedding.weight": + "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86", + "mtp.pre_fc_norm_hidden.weight": + "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d", +} + + +def get(url, start=None, end=None, retries=4): + for attempt in range(retries): + try: + req = urllib.request.Request(url, headers={"User-Agent": "strata-mtp-fetch"}) + if start is not None: + req.add_header("Range", "bytes=%d-%d" % (start, end)) + with urllib.request.urlopen(req, timeout=120) as r: + if start is not None: + check_range(r.status, r.headers.get("Content-Range"), start, end) + data = r.read() + if start is not None and len(data) != end - start + 1: + raise IOError("short range read: %d of %d" % (len(data), end - start + 1)) + return data + except Exception as e: # network errors are retried, then surfaced + if attempt == retries - 1: + raise + time.sleep(2 ** attempt) + print("retry %s: %s" % (url, e), file=sys.stderr) + + +def check_range(status, content_range, start, end): + """#327: a range read is only what was asked for when the server says so: 206 and `bytes START-END/...`.""" + if status != 206: + raise IOError("range request not honoured: HTTP %s instead of 206 (a mirror or proxy that ignores the Range " + "header sends the whole file)" % status) + want = "bytes %d-%d/" % (start, end) + if not (content_range or "").strip().startswith(want): + raise IOError("range request answered with Content-Range %r, not %s..." % (content_range, want)) + + +def pinned(): + """The tensors' hashes are the pinned revision's: they apply when this run reads that revision.""" + return REPO == PINNED + + +def sha256_of(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 24), b""): + h.update(block) + return h.hexdigest() + + +def resolve_repo(): + """REPO, or the repository's current files when the pinned revision is gone from it (a 404 on its index).""" + global REPO + try: + req = urllib.request.Request(REPO + "model.safetensors.index.json", method="HEAD", + headers={"User-Agent": "strata-mtp-fetch"}) + urllib.request.urlopen(req, timeout=120).close() + except urllib.error.HTTPError as e: + if e.code == 404 and "/resolve/main/" not in REPO: + print("the checkpoint's pinned revision %s is gone: reading its current files (main)" % REVISION, + file=sys.stderr) + REPO = REPO.replace("/resolve/%s/" % REVISION, "/resolve/main/") + except OSError: + pass # no answer: get() retries and reports it + return REPO + + +def shard_header(shard): + url = REPO + shard + n = struct.unpack(" r["bytes"]: + os.remove(path) + have = 0 + with open(path, "ab") as f: + pos = r["start"] + have + while pos <= r["end"]: + end = min(pos + chunk - 1, r["end"]) + f.write(get(REPO + r["shard"], pos, end)) + pos = end + 1 + print("%s %.0f%%" % (r["name"], 100 * (pos - r["start"]) / r["bytes"]), file=sys.stderr) + if os.path.getsize(path) != r["bytes"]: + sys.exit("%s: size %d != %d" % (path, os.path.getsize(path), r["bytes"])) + digest = sha256_of(path) + if want is None or digest == want: + break + os.remove(path) # wrong bytes (#327): the whole tensor again, once + if attempt: + sys.exit("%s: sha256 %s is not the checkpoint's %s - the download source sends wrong data (a mirror " + "that ignores Range requests?)" % (r["name"], digest, want)) + print("%s: wrong bytes (sha256 %s...), fetching it again" % (r["name"], digest[:12]), file=sys.stderr) + manifest.append(dict(r, file=os.path.relpath(path, out), sha256=digest)) + with open(os.path.join(out, "mtp-manifest.json"), "w", encoding="utf-8") as f: + json.dump(manifest, f, indent=1) + + +def verify(out): + """#327: the fetched tensors against SHA256 -> the names that are missing or wrong. [] when they are right, or + when there is nothing to check (no tensors/, or STRATA_MTP_REVISION names another revision). A tensor's verdict + is kept in tensors/verified.json by size and mtime, so a later run hashes only what changed.""" + tdir = os.path.join(out, "tensors") + if not pinned() or not os.path.isdir(tdir): + return [] + stamp_path = os.path.join(tdir, "verified.json") + try: + with open(stamp_path, encoding="utf-8") as f: + stamps = json.load(f) + except (OSError, ValueError): + stamps = {} + bad, good = [], {} + for name, want in sorted(SHA256.items()): + path = os.path.join(tdir, name + ".bin") + if not os.path.exists(path): + bad.append(name) + continue + st = os.stat(path) + key = [st.st_size, st.st_mtime_ns, want] + if stamps.get(name) != key and sha256_of(path) != want: + bad.append(name) + continue + good[name] = key + try: + with open(stamp_path, "w", encoding="utf-8") as f: + json.dump(good, f, indent=1) + except OSError: + pass + return bad + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("cmd", choices=["inventory", "fetch", "verify"]) + ap.add_argument("--out", required=True) + ap.add_argument("--only") + a = ap.parse_args() + if a.cmd == "verify": # offline: the hashes are the pinned revision's + bad = verify(a.out) + for name in bad: + print("MTP tensor missing or corrupt: %s" % name, file=sys.stderr) + sys.exit(BAD if bad else 0) + resolve_repo() + inventory(a.out) if a.cmd == "inventory" else fetch(a.out, a.only) + + +if __name__ == "__main__": + main() diff --git a/engine/strata/tools/mtp_pack.py b/engine/strata/tools/mtp_pack.py new file mode 100644 index 00000000..022d2ea8 --- /dev/null +++ b/engine/strata/tools/mtp_pack.py @@ -0,0 +1,193 @@ +"""tools/mtp_pack.py - plan v0.3 P6 prep: the MTP draft block as a Strata GGUF, from the BF16 tensors. + +llama.cpp's qwen4exp converter drops the MTP head (`supports_mtp_export = False`), and the flyweight MTP GGUF is +no longer on this PC, so Strata packs its own from the 31 `mtp.*` tensors fetched by tools/mtp_fetch.py: + + python tools/mtp_pack.py --src Desktop/Strata/mtp-bf16 --experts q2_0 --out mtp-q2_0.gguf + python tools/mtp_pack.py --src ... --experts q4_0 --out mtp-q4_0.gguf (acceptance comparison arm) + +Layout: dense tensors (attention, indexer, hyper-connections, shared expert, router, fc/norms) stay BF16 (F32 for +1-D norms), ~0.18 GB. The routed experts keep the checkpoint's fused layout - `gate_up_proj` [512, 1280, 2560] and +`down_proj` [512, 2560, 640], quantized along the last (input) axis - in one of: + + q2_0 64-element blocks, grid {-1, 0, 1, 2} x d. The scale is chosen per block to MINIMIZE squared error over + that grid (the ggml reference sets d = max|w| and never uses the +2 level). Same format as the main + model's experts, so Strata's CPU VNNI kernel and GPU hit kernel serve it unchanged. ~0.71 GB. + q4_0 ggml reference rounding. ~1.42 GB. q8_0 ggml reference. ~2.67 GB. + +This is round-to-nearest, not GSQ: the plan picks the expert format by MEASURED draft acceptance (P0.3/P6), not +by this file's reconstruction error, which is reported per tensor only as a sanity check. No model runs here. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _paths import add_gguf_py # noqa: E402 +add_gguf_py() +import gguf # noqa: E402 (the pinned llama.cpp gguf-py, which knows Q2_0 = type 42) + +EXPERT_TENSORS = ("mtp.layers.0.mlp.experts.gate_up_proj", "mtp.layers.0.mlp.experts.down_proj") + + +class _Experts: + """Index an expert out of a BF16 memmap as float32 on demand.""" + def __init__(self, raw): + self.raw = raw + + def __getitem__(self, e): + return (np.asarray(self.raw[e]).astype(np.uint32) << 16).view(np.float32) + + +def load_bf16(path: Path, shape: list[int]) -> np.ndarray: + raw = np.fromfile(path, dtype=" np.ndarray: + """[..., n] float32 -> bytes of Q2_0 blocks (fp16 d, 16 bytes of 2-bit codes, code = q + 1, 4 per byte).""" + x = w.reshape(-1, 64).astype(np.float32) + amax = np.abs(x).max(axis=1, keepdims=True) + best_err = np.full((x.shape[0], 1), np.inf, dtype=np.float32) + best_d = np.zeros_like(amax) + # Candidate scales span amax/2 (the +2 level reaches the max) to amax (the ggml reference); 17 steps. + for f in np.linspace(0.5, 1.0, 17, dtype=np.float32): + d = amax * f + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + q = np.clip(np.rint(x * inv), -1, 2) + err = ((q * d - x) ** 2).sum(axis=1, keepdims=True) + better = err < best_err + best_err = np.where(better, err, best_err) + best_d = np.where(better, d, best_d) + d16 = best_d.astype(np.float16) + d = d16.astype(np.float32) # quantize against the STORED scale + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + codes = (np.clip(np.rint(x * inv), -1, 2) + 1).astype(np.uint8) # 0..3 + c = codes.reshape(-1, 16, 4) + packed = (c[:, :, 0] | (c[:, :, 1] << 2) | (c[:, :, 2] << 4) | (c[:, :, 3] << 6)).astype(np.uint8) + out = np.empty((x.shape[0], 18), dtype=np.uint8) + out[:, :2] = d16.view(np.uint8).reshape(-1, 2) + out[:, 2:] = packed + return out.reshape(-1) + + +def q4_0(w: np.ndarray) -> np.ndarray: + """ggml quantize_row_q4_0_ref: d = max / -8 (signed max), code = clamp(round(x/d + 8.5) truncated, 0, 15).""" + x = w.reshape(-1, 32).astype(np.float32) + idx = np.abs(x).argmax(axis=1) + mx = x[np.arange(x.shape[0]), idx][:, None] + d = mx / -8.0 + inv = np.where(d != 0, 1.0 / np.where(d != 0, d, 1.0), 0.0) + q = np.minimum(15, np.trunc(x * inv + 8.5)).astype(np.uint8) + packed = (q[:, :16] | (q[:, 16:] << 4)).astype(np.uint8) + out = np.empty((x.shape[0], 18), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = packed + return out.reshape(-1) + + +def q8_0(w: np.ndarray) -> np.ndarray: + x = w.reshape(-1, 32).astype(np.float32) + d = np.abs(x).max(axis=1, keepdims=True) / 127.0 + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0) + q = np.rint(x * inv).astype(np.int8) + out = np.empty((x.shape[0], 34), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = q.view(np.uint8) + return out.reshape(-1) + + +def dequant(kind: str, blob: np.ndarray, n: int) -> np.ndarray: + if kind == "q2_0": + b = blob.reshape(-1, 18) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + qs = b[:, 2:] + codes = np.stack([(qs >> s) & 3 for s in (0, 2, 4, 6)], axis=2).reshape(-1, 64).astype(np.float32) + return ((codes - 1.0) * d).reshape(-1)[:n] + if kind == "q4_0": + b = blob.reshape(-1, 18) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + qs = b[:, 2:] + q = np.concatenate([qs & 15, qs >> 4], axis=1).astype(np.float32) + return ((q - 8.0) * d).reshape(-1)[:n] + b = blob.reshape(-1, 34) + d = b[:, :2].copy().view(np.float16).astype(np.float32) + return (b[:, 2:].view(np.int8).astype(np.float32) * d).reshape(-1)[:n] + + +QUANT = {"q2_0": (q2_0, gguf.GGMLQuantizationType.Q2_0, 64, 18), + "q4_0": (q4_0, gguf.GGMLQuantizationType.Q4_0, 32, 18), + "q8_0": (q8_0, gguf.GGMLQuantizationType.Q8_0, 32, 34)} + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--src", required=True, help="directory written by tools/mtp_fetch.py fetch") + ap.add_argument("--experts", choices=sorted(QUANT), default="q2_0") + ap.add_argument("--out", required=True) + ap.add_argument("--check-experts", type=int, default=8, help="experts per tensor used for the error report") + a = ap.parse_args() + src = Path(a.src) + manifest = json.loads((src / "mtp-manifest.json").read_text()) + fn, qtype, block, block_bytes = QUANT[a.experts] + w = gguf.GGUFWriter(a.out, "qwen4exp-mtp") + w.add_string("strata.mtp.source", "Qwen/Qwen3.8-Flash-Next BF16 checkpoint, mtp.* tensors") + w.add_string("strata.mtp.source_sha256", hashlib.sha256( + json.dumps({t["name"]: t["sha256"] for t in manifest}, sort_keys=True).encode()).hexdigest()) + w.add_string("strata.mtp.expert_format", a.experts) + w.add_string("strata.mtp.expert_quantizer", "per-block MSE scale search" if a.experts == "q2_0" else "ggml reference") + report = [] + for t in sorted(manifest, key=lambda t: t["name"]): + name, shape = t["name"], t["shape"] + t0 = time.time() + if name in EXPERT_TENSORS: + # Streamed one expert at a time from a read-only view: the fused gate_up tensor alone is 6.7 GB as + # float32, so it is never materialized whole. + raw = np.memmap(src / t["file"], dtype="/mtp-bf16/mtp-q2_0.gguf --out /mtp-bf16/rt + +Writes + experts.bin 512 routed experts in the engine's blob layout (`include/strata/kernels/cpu/expert.hpp`): gate/up + rows interleaved (2r = gate r, 2r+1 = up r), then down rows; the Q2_0 codes in one plane and the fp16 + scales in another. A lossless relayout of the GGUF's Q2_0 blocks (same bytes, `cpu_expert_fixture.py`). + dense.bin every other tensor: the large projections quantized to Q8_0 (ggml's reference rounding) so the + engine's multi-column MMVQ can run them; the hyper-connection and router weights kept BF16; the + RMSNorm weights as F32 with the Gemma "+1" applied (vLLM GemmaRMSNorm scales by 1 + w). + dense.txt one line per tensor: name kind rows cols offset bytes (kind = q8_0 | bf16 | f32) +""" +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from _paths import add_gguf_py # noqa: E402 +add_gguf_py() +import gguf # noqa: E402 + +H, FF, NE = 2560, 640, 512 +BLOB = 3 * (H * FF * 18 // 64) +Q8 = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight", + "self_attn.v_proj.weight", "self_attn.o_proj.weight", "self_attn.indexer.index_qk_proj.weight", + "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"} + + +def q8_0(x: np.ndarray) -> bytes: + """ggml quantize_row_q8_0_ref over rows of a 2-D float32 array: 32-value blocks, fp16 d = amax / 127.""" + b = x.reshape(-1, 32).astype(np.float32) + amax = np.abs(b).max(axis=1) + d = amax / 127.0 + inv = np.where(d > 0, 1.0 / np.where(d > 0, d, 1.0), 0.0).astype(np.float32) + v = b * inv[:, None] + q = (np.sign(v) * np.floor(np.abs(v) + 0.5)).astype(np.int8) + out = np.empty((b.shape[0], 34), dtype=np.uint8) + out[:, :2] = d.astype(np.float16).view(np.uint8).reshape(-1, 2) + out[:, 2:] = q.view(np.uint8) + return out.tobytes() + + +def blob_of(gu: np.ndarray, dn: np.ndarray) -> bytes: + """gu: (1280, 720) Q2_0 rows (gate rows 0..639, up rows 640..1279); dn: (2560, 180).""" + gub = gu.reshape(2 * FF, H // 64, 18) + inter = np.empty_like(gub) + inter[0::2] = gub[:FF] + inter[1::2] = gub[FF:] + dnb = dn.reshape(H, FF // 64, 18) + parts = [inter[:, :, 2:].tobytes(), dnb[:, :, 2:].tobytes(), inter[:, :, :2].tobytes(), dnb[:, :, :2].tobytes()] + out = b"".join(parts) + assert len(out) == BLOB, len(out) + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--gguf", required=True) + ap.add_argument("--out", required=True) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + r = gguf.GGUFReader(a.gguf) + tens = {t.name: t for t in r.tensors} + gu = np.asarray(tens["mtp.layers.0.mlp.experts.gate_up_proj"].data) + dn = np.asarray(tens["mtp.layers.0.mlp.experts.down_proj"].data) + assert gu.shape == (NE, 2 * FF, 720) and dn.shape == (NE, H, 180), (gu.shape, dn.shape) + with open(out / "experts.bin", "wb") as f: + for e in range(NE): + f.write(blob_of(gu[e], dn[e])) + lines = [] + off = 0 + with open(out / "dense.bin", "wb") as f: + for name, t in tens.items(): + if "experts." in name: + continue + short = name[len("mtp."):] + short = short[len("layers.0."):] if short.startswith("layers.0.") else short + data = np.asarray(t.data) + if int(t.tensor_type) == 0: # F32 norm weights: raw GemmaRMSNorm w -> 1 + w + arr = (data.astype(np.float32) + 1.0) + raw, kind, rows, cols = arr.tobytes(), "f32", 1, arr.size + else: # BF16 + u16 = data.view(np.uint16) if data.dtype != np.uint16 else data + u16 = u16.reshape(data.shape[0], -1) + rows, cols = u16.shape + if short in Q8: + f32 = (u16.astype(np.uint32) << 16).view(np.float32) + raw, kind = q8_0(f32), "q8_0" + else: + raw, kind = u16.tobytes(), "bf16" + pad = (-off) % 256 + f.write(b"\0" * pad) + off += pad + f.write(raw) + lines.append(f"{short} {kind} {rows} {cols} {off} {len(raw)}") + off += len(raw) + (out / "dense.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"experts.bin {NE * BLOB} B, dense.bin {off} B, {len(lines)} tensors -> {out}") + for l in lines: + print(" " + l) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/needle_bench.py b/engine/strata/tools/needle_bench.py new file mode 100644 index 00000000..10a3ca14 --- /dev/null +++ b/engine/strata/tools/needle_bench.py @@ -0,0 +1,118 @@ +"""tools/needle_bench.py - needle-in-a-haystack recall through a running Strata server. + +A long text is built from files in this repository (its docs and source code, and the llama.cpp docs setup downloads +into third_party/), a code word is hidden in it at a chosen depth, and the model is asked for it through the normal +API (thinking off, greedy). One line per test: length, depth, found or not, prompt tokens, time. + + python tools/needle_bench.py # 32K at depths 10/50/90, http://127.0.0.1:8080 + python tools/needle_bench.py --lengths 32k,128k,262k --depths 10,50,90 --url http://127.0.0.1:8081 + python tools/needle_bench.py --out needles.json --api-key KEY + +The lengths are targets, 2% under so that "128k" fits a 128K context: the text is cut by characters (about 3.2 per +token), and the line reports the prompt's real token count from the server. A length the server's context cannot hold is skipped. +""" +from __future__ import annotations + +import argparse +import json +import random +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SOURCES = [("docs", "*.md"), ("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py"), + ("third_party/llama.cpp/docs", "*.md")] +WORDS = ["amber", "falcon", "quartz", "willow", "copper", "harbor", "saffron", "glacier", "orchid", "lantern", + "meadow", "cobalt", "juniper", "tundra", "velvet", "ember"] +CHARS_PER_TOKEN = 3.2 + + +def haystack(n_chars: int) -> str: + """Deterministic filler: the repository's text files in a fixed order, repeated if needed.""" + files = [] + for d, pat in SOURCES: + files += sorted((ROOT / d).rglob(pat)) + parts, total = [], 0 + while total < n_chars: + for f in files: + try: + t = f.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + parts.append(f"\n\n=== {f.relative_to(ROOT).as_posix()} ===\n{t}") + total += len(parts[-1]) + if total >= n_chars: + break + if not files: + raise SystemExit("no text files found to build the haystack from") + return "".join(parts)[:n_chars] + + +def ask(url: str, key: str, prompt: str, timeout: float) -> tuple[str, int, float]: + body = {"model": "strata", "max_tokens": 40, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}, + "messages": [{"role": "user", "content": prompt}]} + headers = {"Content-Type": "application/json"} + if key: + headers["Authorization"] = "Bearer " + key + t0 = time.time() + req = urllib.request.Request(url.rstrip("/") + "/v1/chat/completions", data=json.dumps(body).encode(), headers=headers) + with urllib.request.urlopen(req, timeout=timeout) as r: + out = json.loads(r.read()) + return (out["choices"][0]["message"].get("content") or ""), out["usage"]["prompt_tokens"], time.time() - t0 + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--url", default="http://127.0.0.1:8080") + ap.add_argument("--api-key", default="") + ap.add_argument("--lengths", default="32k", help="comma-separated, e.g. 1k,32k,128k,262k") + ap.add_argument("--depths", default="10,50,90", help="where the code word sits, percent of the text") + ap.add_argument("--timeout", type=float, default=1800) + ap.add_argument("--out", help="also write the results as JSON") + a = ap.parse_args() + try: + with urllib.request.urlopen(a.url.rstrip("/") + "/metrics", timeout=10) as r: + ctx = int((json.loads(r.read()).get("engine") or {}).get("max_context") or 0) + except (OSError, ValueError): + ctx = 0 + rnd = random.Random(7) + rows, found = [], 0 + for L in a.lengths.split(","): + tokens = int(float(L.lower().rstrip("k")) * 1024) if L.lower().endswith("k") else int(L) + tokens = int(tokens * 0.98) # "128k" fits a 128K context with room to answer + if ctx and tokens + 200 > ctx: + print(f"{L:>5}: skipped (the server's context is {ctx})") + continue + text = haystack(int(tokens * CHARS_PER_TOKEN)) + for d in (int(x) for x in a.depths.split(",")): + word = f"{rnd.choice(WORDS)}-{rnd.choice(WORDS)}-{rnd.randint(100, 999)}" + cut = int(len(text) * d / 100) + cut = text.rfind("\n", 0, cut) + 1 or cut # at a line start + needle = f"\nThe secret code word for this text is: {word}. Remember it.\n" + prompt = (text[:cut] + needle + text[cut:] + + "\n\nWhat is the secret code word mentioned in the text above? Reply with the code word only.") + try: + answer, n, secs = ask(a.url, a.api_key, prompt, a.timeout) + except (OSError, urllib.error.HTTPError) as e: + print(f"{L:>5} depth {d:>3}%: request failed ({e})") + rows.append({"length": L, "depth": d, "error": str(e)}) + continue + ok = word in answer + found += ok + print(f"{L:>5} depth {d:>3}%: {'FOUND' if ok else 'missed'} ({n:,} prompt tokens, {secs:.0f} s)" + + ("" if ok else f" answer: {answer.strip()[:80]!r}"), flush=True) + rows.append({"length": L, "depth": d, "prompt_tokens": n, "seconds": round(secs, 1), "found": ok, + "word": word, "answer": answer.strip()[:200]}) + done = [r for r in rows if "found" in r] + print(f"{found} of {len(done)} found") + if a.out: + Path(a.out).write_text(json.dumps(rows, indent=1), encoding="utf-8") + return 0 if done and found == len(done) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/pack_index.py b/engine/strata/tools/pack_index.py new file mode 100644 index 00000000..02678acb --- /dev/null +++ b/engine/strata/tools/pack_index.py @@ -0,0 +1,260 @@ +"""tools/pack_index.py - emit a flat index of the pack's dense tensors for the engine's loader. + +WHY AN INDEX AND NOT A JSON PARSER. The manifest is JSON and the engine is C++. A JSON parser in the engine +would be a new, unaudited component whose failure mode is a wrong byte offset - which decodes to a plausible +weight and produces plausible logits. Python already parses the manifest correctly and is already the tool +that WROTE it, so this flattens what the loader needs into one line per tensor. + +WHY TEXT AND NOT BINARY. `pack/full/index.txt` is ~150 KB for 1,079 tensors. A fixed-size binary record +would save 60 KB and cost a struct-packing contract between two languages that must agree on padding, +endianness and field order - three ways to be wrong for no benefit at this size. Text is also readable when +a load produces the wrong number, which is the only time this file matters. + +THE ENGINE LAYOUT IS NOT THE PACK LAYOUT, and that is the point of `dst_*`. Two independent differences: + + 1. A tensor whose source type is BF16 or F16 is stored in the pack PROMOTED to 32 bits, because that is + lossless and it keeps the canonical decoder simple. A running engine does not have to hold it that way: + re-rounding to 16 bits costs nothing at all, because the value came FROM 16 bits. That is 1.374 GiB of + the 5.305 GiB dense file, and per `tools/pack_budget.py` it is the difference between the dense weights + fitting in VRAM beside the expert cache and not fitting at all. + + 2. **A SCALE PLANE MAY BE 2 BYTES IN THE PACK AND IS ALWAYS 4 IN THE ENGINE.** This is the one that hid + for a whole round. 90 of the 303 quantized tensors - every Q2_0 (all 58 expert tensors), Q4_0, Q5_0, + Q8_0 and IQ4_NL - carry fp16 scales, because that is what the SOURCE ggml block stores (a Q5_0 block is + `{fp16 d; ...}`). 213 tensors (IQ4_XS, Q3_K, Q4_K, Q5_K, Q6_K) carry f32 scales. The manifest has said + which is which all along, in `scales_fp16`. + + `src/core/layer.cpp` did not read that field. It assumed 4 bytes per scale, so it computed a scale plane + twice the real size, the three planes did not add up to the tensor, and the loader REFUSED - which is how + this was found, and the refusal is the only reason it was not a silent wrong answer. The first diagnosis + was "the manifest's `group_elems` must be wrong, the real group is 64". It is not: `group_elems` is 32 + and the scale plane is 2 bytes wide. **The unexamined input was the WIDTH, not the count.** An audit of + all 303 tensors against `scales_fp16`/`offsets_fp16` found zero inconsistencies, which is what settled it. + + The engine widens fp16 scales to f32 at load. That is EXACT - fp16 is a subset of f32 - and it costs + 11,407,360 B (10.88 MiB) of the 4.5 GiB pool, against teaching three kernel families a second scale + width. Note the asymmetry that makes this cheap and the BF16 re-rounding large: re-rounding loses + precision and saves GiB; widening loses nothing and costs MiB. + + `offsets_fp16` is also read, and it is FALSE for all 54 tensors that have an offset plane. It is + honoured anyway rather than assumed, because the next pack may not be. + +Columns: + + name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias group_elems codebook + has_offset codes_bytes scales_bytes offset_bytes scales_fp16 + +`kind` is what the loader must DO, spelled out here rather than left for it to infer - the four cases are +distinguishable in the manifest but only by combining `source_type` with `values_fp16`, and getting that +combination wrong produces a plausible tensor: + + 0 VERBATIM copy straight through (BF16-free: F16 already 2 B/elem, F32, and the planes below) + 1 BF16_IN_F32 the pack holds the bf16 value promoted to f32; take the HIGH 16 BITS. Exact, not a + rounding: a bf16 value IS the top half of its f32 image. + 2 F32 copy 4 B/elem + 3 F16_IN_F32 the pack holds an f16 value promoted to f32; needs a real f32->f16 conversion with + round-to-nearest-even, NOT a truncation + +`ne0`/`ne1` are the manifest's own shape in its own order, with ne0 the CONTIGUOUS axis. `form` is the +canonical form letter from the manifest (P16/P32/S2/S4/S8); the SForm attributes are 0 for kinds 1-3. + +`codes_bytes`/`scales_bytes`/`offset_bytes` are the THREE ENGINE-FORM PLANE SIZES, in the order they sit in +the destination. They are emitted rather than left for the loader to re-derive, because re-deriving is where +the width bug lived: two places computing one layout is two places to disagree, and the loader cannot check a +layout it invented. The loader instead checks what it was TOLD: `scales_bytes/2` when `scales_fp16`, and the +three planes summing to both `src_bytes` (source widths) and `dst_bytes` (engine widths). Non-quantized +tensors carry `codes_bytes == dst_bytes` and two zeroes. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +FILE_ID = {"dense.bin": 0, "embd.bin": 1, "experts.bin": 2} +VERBATIM, BF16_IN_F32, F32_COPY, F16_IN_F32 = 0, 1, 2, 3 + +# WHICH ACTIVATION THIS WEIGHT WANTS, decided HERE because it is a property of `source_type` and the engine's +# `SForm` cannot recover it. The legacy formats (Q2_0, Q4_0, Q5_0, Q8_0, IQ4_NL) have `vec_dot_type` Q8_0; the +# K-quants and IQ4_XS have Q8_K. **NO COMBINATION OF THE S-FORM FIELDS TELLS THEM APART**: Q5_0 and Q5_K are +# both 8-bit with bias -16 (only `has_offset` differs), and IQ4_NL and IQ4_XS are both 4-bit with the IQ4NL +# codebook and no offset - they differ in NOTHING the S-form carries. That is why this column exists rather +# than the engine re-deriving the rule from `code_bits`. +ACT_Q8_0, ACT_Q8_K = 0, 1 +VDT = { + "Q2_0": ACT_Q8_0, "Q4_0": ACT_Q8_0, "Q5_0": ACT_Q8_0, "Q8_0": ACT_Q8_0, "IQ4_NL": ACT_Q8_0, + "Q3_K": ACT_Q8_K, "Q4_K": ACT_Q8_K, "Q5_K": ACT_Q8_K, "Q6_K": ACT_Q8_K, "IQ4_XS": ACT_Q8_K, +} + +# The plane key is `offsets`, NOT `mins`. The first version of this list said `mins` - which is what ggml calls +# the quantity conceptually, and the manifest does not - and a missing key in a loop like this is not an error, +# it is a SHORTER SPAN: 54 Q4_K/Q5_K tensors loaded with their offset plane never copied. Keys now come from +# the manifest, and the layout is verified against the recorded plane offsets rather than assumed. +PLANE_KEYS = ("codes", "scales", "offsets") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--pack", default="pack/full") + ap.add_argument("-o", "--out", default=None, help="default: /index.txt") + args = ap.parse_args() + out_path = args.out or os.path.join(args.pack, "index.txt") + + with open(os.path.join(args.pack, "manifest.json"), "r", encoding="utf-8") as fh: + man = json.load(fh) + align = int(man.get("align", 64)) + + def align_up(n: int) -> int: + return (n + align - 1) // align * align + + rows = [] + dst = 0 + n_reduced = 0 + saved = 0 + widened = 0 + n_widened = 0 + kinds: dict[int, int] = {} + for name, v in man["tensors"].items(): + f = v.get("file") + if f not in FILE_ID: + print("unknown file %r for %s" % (f, name), file=sys.stderr) + return 1 + shape = v.get("shape") or [0, 0] + ne0 = int(shape[0]) if len(shape) > 0 else 0 + ne1 = int(shape[1]) if len(shape) > 1 else 0 + elems = int(v.get("elements", 0)) + st = v.get("source_type") or "?" + + codes_bytes = scales_bytes = offset_bytes = 0 + scales_fp16 = 0 + widen_here = 0 + act_kind = ACT_Q8_0 + if "values" in v: + src_off = int(v["values"]["offset"]) + src_bytes = int(v["values"]["bytes"]) + else: + planes = [k for k in PLANE_KEYS if isinstance(v.get(k), dict)] + lo = min(int(v[k]["offset"]) for k in planes) + hi = max(int(v[k]["offset"]) + int(v[k].get("bytes", 0)) for k in planes) + src_off, src_bytes = lo, hi - lo + + # the planes must be CONTIGUOUS, in order, because the loader reads them as one span. If a future + # pack interleaves them this refuses; the alternative is reading the scale plane as offsets and + # decoding a plausible weight. + expect = src_off + for k in PLANE_KEYS: + if k not in planes: + continue + if int(v[k]["offset"]) != expect: + print("%s: plane %r starts at %d but %d was expected - planes are not contiguous" + % (name, k, int(v[k]["offset"]), expect), file=sys.stderr) + return 1 + expect += int(v[k].get("bytes", 0)) + if expect != src_off + src_bytes: + print("%s: plane span %d does not end at %d" % (name, expect, src_off + src_bytes), + file=sys.stderr) + return 1 + + if v.get("has_offset") and "offsets" not in planes: + print("%s says has_offset but has no `offsets` plane (found %s)" % (name, planes), + file=sys.stderr) + return 1 + + act_kind = VDT.get(st, ACT_Q8_0) # refuses below if the type is unknown + code_bits = int(v.get("code_bits") or 0) + group_elems = int(v.get("group_elems") or 0) + if code_bits == 0 or group_elems == 0: + print("%s: a quantized tensor with code_bits=%d group_elems=%d" % (name, code_bits, group_elems), + file=sys.stderr) + return 1 + if ne0 % group_elems: + print("%s: ne0 %d is not a multiple of group_elems %d" % (name, ne0, group_elems), + file=sys.stderr) + return 1 + n_groups = ne0 // group_elems + codes_bytes = elems * code_bits // 8 + scales_fp16 = 1 if v.get("scales_fp16") else 0 + offs_fp16 = 1 if v.get("offsets_fp16") else 0 + # engine-form plane sizes: ALWAYS 4 B per scale. fp16 in the pack is widened; the load is exact. + scales_bytes = ne1 * n_groups * 4 + offset_bytes = ne1 * n_groups * 4 if v.get("has_offset") else 0 + src_planes = (codes_bytes + + ne1 * n_groups * (2 if scales_fp16 else 4) + + (ne1 * n_groups * (2 if offs_fp16 else 4) if v.get("has_offset") else 0)) + if src_planes != int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) \ + + int(v.get("offsets", {}).get("bytes", 0)): + print("%s: derived planes %d disagree with the manifest's own plane bytes %d" + % (name, src_planes, int(v["codes"]["bytes"]) + int(v["scales"]["bytes"]) + + int(v.get("offsets", {}).get("bytes", 0))), file=sys.stderr) + return 1 + if src_planes != src_bytes: + print("%s: derived planes %d do not fill the span %d" % (name, src_planes, src_bytes), + file=sys.stderr) + return 1 + if scales_fp16: + widen_here = scales_bytes - ne1 * n_groups * 2 + widened += widen_here + n_widened += 1 + + # ---- the engine form, as an explicit KIND rather than a flag to interpret + vf = bool(v.get("values_fp16")) + if st == "BF16": + kind = BF16_IN_F32 + dst_bytes = elems * 2 + saved += src_bytes - dst_bytes + n_reduced += 1 + elif st == "F16" and not vf: + kind = F16_IN_F32 + dst_bytes = elems * 2 + saved += src_bytes - dst_bytes + n_reduced += 1 + elif st == "F16": + kind = VERBATIM # already 2 bytes on disk + dst_bytes = src_bytes + elif st == "F32": + kind = F32_COPY + dst_bytes = elems * 4 + else: + kind = VERBATIM + dst_bytes = codes_bytes + scales_bytes + offset_bytes + # THE ENGINE FORM OF A QUANTIZED TENSOR DIFFERS FROM THE PACK BY EXACTLY THE WIDENING, and saying + # so here is what makes the two plane sizes a CHECK rather than two independent guesses. + if dst_bytes != src_bytes + widen_here: + print("%s: engine form %d != pack %d + widening %d" % (name, dst_bytes, src_bytes, widen_here), + file=sys.stderr) + return 1 + + cb = v.get("codebook") + rows.append((name, FILE_ID[f], kind, src_off, src_bytes, dst, dst_bytes, ne0, ne1, + int(v.get("code_bits") or 0), int(v.get("code_bias") or 0), + int(v.get("group_elems") or 0), 1 if cb == "IQ4NL" else 0, + 1 if v.get("has_offset") else 0, + codes_bytes, scales_bytes, offset_bytes, scales_fp16, act_kind)) + dst = align_up(dst + dst_bytes) + kinds[kind] = kinds.get(kind, 0) + 1 + + with open(out_path, "w", encoding="utf-8", newline="\n") as fh: + fh.write("# strata pack index v3 -- generated by tools/pack_index.py; do not hand-edit\n") + fh.write("# align %d pool %d tensors %d\n" % (align, dst, len(rows))) + fh.write("# name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias " + "group_elems codebook has_offset codes_bytes scales_bytes offset_bytes scales_fp16 act_kind\n") + for r in rows: + fh.write("%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n" % r) + + names = {VERBATIM: "VERBATIM", BF16_IN_F32: "BF16_IN_F32", F32_COPY: "F32", F16_IN_F32: "F16_IN_F32"} + print("%s: %d tensors, engine pool %d B (%.3f GiB)" % (out_path, len(rows), dst, dst / 2**30)) + for k in sorted(kinds): + print(" kind %-12s %4d tensors" % (names[k], kinds[k])) + print(" %d tensors re-rounded to 16 bits, saving %d B (%.3f GiB)" + % (n_reduced, saved, saved / 2**30)) + print(" %d tensors widened fp16 scales -> f32, costing %d B (%.3f GiB)" + % (n_widened, widened, widened / 2**30)) + print(" compare with tools/pack_budget.py: the pack's dense+embd engine figure should match this pool") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/tools/pack_layer.py b/engine/strata/tools/pack_layer.py new file mode 100644 index 00000000..1fdf1148 --- /dev/null +++ b/engine/strata/tools/pack_layer.py @@ -0,0 +1,123 @@ +"""Strata P0.S9 - build the pack-layout expert arena from the real GGUF. + +The architecture (§3.2) defines one expert blob as 1,382,400 bytes: + + gate_up.codes 2 x 640 rows x 640 B rows interleaved g0,u0,g1,u1,... (share input x) + down.codes 2,560 rows x 160 B + gate_up.scales 2 x 640 x 40 x FP16 + down.scales 2,560 x 10 x FP16 + +and that totals exactly 819,200 + 409,600 + 102,400 + 51,200 = 1,382,400 B, matching the artifact's +Q2_0 expert size to the byte. The conversion is a pure relayout: Q2_0 codes and their FP16 block +scale are copied unchanged, so dequant(pack) == dequant(ggml) bit-exactly. + +Why build this at all rather than read the GGUF in place: the GGUF stores gate, up and down as three +separate tensors, so a fused gate/up pass would read two streams from three arrays. The pack +interleaves gate and up ROWS so one pass over the activation vector serves both, which is the whole +point of the blob layout. + +Expert index is the LAST axis of [in, out, experts] (P0.S6), and ne[0] varies fastest, so expert `e` +is one CONTIGUOUS 460,800-byte run inside each role tensor. Extraction is a strided copy. + +Run: python tools/pack_layer.py [n_layers] (default 1; 48 = the full 34 GB arena) +""" +from __future__ import annotations + +import json +import pathlib +import struct +import sys + +import numpy as np + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from gguf_reader import GGUFFile # noqa: E402 + +REPO = pathlib.Path(__file__).resolve().parents[1] +STRATA = REPO.parents[min(1, len(REPO.parents) - 1)] # the dev layout's default shards (setup.py passes --gguf) +SHARD1 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" + +H, FF, NE = 2560, 640, 512 +QK, BLOCK_BYTES = 64, 18 # Q2_0 +ROW_BYTES_GU = H * 2 // 8 # 640 B of codes for one 2,560-wide row +ROW_BYTES_D = FF * 2 // 8 # 160 B of codes for one 640-wide row +SCALES_GU = H // QK # 40 blocks per gate/up row +SCALES_D = FF // QK # 10 blocks per down row +ROLE_BYTES = H * FF * BLOCK_BYTES // QK # 460,800 B per role per expert +BLOB_BYTES = 3 * ROLE_BYTES # 1,382,400 + +assert BLOB_BYTES == 1_382_400, BLOB_BYTES +assert 2 * 640 * ROW_BYTES_GU + 2560 * ROW_BYTES_D + 2 * 640 * SCALES_GU * 2 \ + + 2560 * SCALES_D * 2 == BLOB_BYTES + + +def blob_offsets() -> dict[str, int]: + gu_codes = 0 + d_codes = gu_codes + 2 * FF * ROW_BYTES_GU + gu_scales = d_codes + H * ROW_BYTES_D + d_scales = gu_scales + 2 * FF * SCALES_GU * 2 + end = d_scales + H * SCALES_D * 2 + assert end == BLOB_BYTES, end + return {"gate_up_codes": gu_codes, "down_codes": d_codes, + "gate_up_scales": gu_scales, "down_scales": d_scales} + + +OFF = blob_offsets() + + +def build(n_layers: int, out_path: pathlib.Path) -> dict: + g = GGUFFile(SHARD1) + by_name = {t.name: t for t in g.tensors} + src = open(SHARD1, "rb") + manifest = {"blob_bytes": BLOB_BYTES, "offsets": OFF, "layers": [], "n_layers": n_layers} + total = n_layers * NE * BLOB_BYTES + out_path.parent.mkdir(parents=True, exist_ok=True) + + with out_path.open("wb") as out: + for layer in range(n_layers): + roles = {} + for role in ("gate", "up", "down"): + t = by_name[f"blk.{layer}.ffn_{role}_exps.weight"] + roles[role] = t + assert t.type_name == "Q2_0", t.type_name + # expert e is a contiguous run inside the role tensor + per_expert = t.elements // NE + assert per_expert * BLOCK_BYTES // QK == ROLE_BYTES, per_expert + layer_off = out.tell() + # vectorized over the layer's 512 experts (the same bytes the per-block loop wrote; tools/strata_pack.py + # verify checks them): each role is (512 experts, rows, blocks per row, 18 bytes) + def role_blocks(role, rows, per_row): + t = roles[role] + n = NE * ROLE_BYTES + src.seek(g.data_start + t.offset) + a = np.frombuffer(src.read(n), dtype=np.uint8) + assert a.size == n, (role, a.size) + return a.reshape(NE, rows, per_row, BLOCK_BYTES) + gate = role_blocks("gate", FF, SCALES_GU) + up = role_blocks("up", FF, SCALES_GU) + down = role_blocks("down", H, SCALES_D) + gu = np.stack([gate, up], axis=2).reshape(NE, 2 * FF, SCALES_GU, BLOCK_BYTES) # rows g0,u0,g1,u1,... + blobs = np.concatenate([ + gu[:, :, :, 2:].reshape(NE, -1), # gate/up codes + down[:, :, :, 2:].reshape(NE, -1), # down codes + gu[:, :, :, :2].reshape(NE, -1), # gate/up fp16 scales + down[:, :, :, :2].reshape(NE, -1), # down fp16 scales + ], axis=1) + assert blobs.shape == (NE, BLOB_BYTES), blobs.shape + out.write(blobs.tobytes()) + manifest["layers"].append({"layer": layer, "offset": layer_off, + "role_offsets": {r: by_name[f"blk.{layer}.ffn_{r}_exps.weight"].offset + for r in ("gate", "up", "down")}}) + print(f" layer {layer}: wrote {NE} blobs at {layer_off}") + src.close() + manifest["total_bytes"] = total + (out_path.with_suffix(".json")).write_text(json.dumps(manifest, indent=2), encoding="utf-8") + return manifest + + +if __name__ == "__main__": + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + dest = REPO / "pack" / ("layer0.bin" if n == 1 else f"experts-{n}l.bin") + print(f"building {n} layer(s) -> {dest} ({(n*NE*BLOB_BYTES)/2**30:.2f} GiB)") + m = build(n, dest) + print(f"done: {m['total_bytes']/2**30:.2f} GiB, {n*NE} blobs") diff --git a/engine/strata/tools/ple_fp8_pack.py b/engine/strata/tools/ple_fp8_pack.py new file mode 100644 index 00000000..63132731 --- /dev/null +++ b/engine/strata/tools/ple_fp8_pack.py @@ -0,0 +1,123 @@ +"""tools/ple_fp8_pack.py - the PLE n-gram table exactly as Qwen shipped it (FP8 E4M3), as a GGUF the engine reads. + + python tools/ple_fp8_pack.py --model --out + +Qwen3.8-Flash-Next's checkpoint stores the table as 128 shards `...ngram_embedding.shard_{k}.weight` of +[2500012, 160] F8_E4M3 with one BF16 `weight_scale`: 320,001,536 rows of 160 values, 51.2 GB. The engine used to take +it from ISTA-DASLab's GGUF as IQ4_NL (90 B/row), which is 8% off these values per row; this keeps them bit for bit. + +The output is a one-tensor GGUF: `per_layer_token_embd.weight`, ne = [160, 320001536], type I8 holding the FP8 bytes +(GGUF has no FP8 type), with `strata.ple.format` = "f8_e4m3" and `strata.ple.scale` (F32). The bytes are copied +straight out of the safetensors files in shard order - nothing is decoded or rounded - so memory stays flat. +""" +import argparse +import json +import pathlib +import struct +import sys + +GGUF_TYPE_STRING, GGUF_TYPE_F32 = 8, 6 +GGML_TYPE_I8 = 24 +ALIGN = 32 +CHUNK = 64 << 20 + + +def safetensors_header(path): + with open(path, "rb") as f: + n = struct.unpack(" None: + """Diagnostics go to stderr: stdout carries only the protocol.""" + try: + sys.stderr.write(f"[strata-mcp] {msg}\n") + sys.stderr.flush() + except (OSError, ValueError): + pass + + +# ------------------------------------------------------------------------------------------------ processes +def proc_identity(pid) -> str | None: + """A token for a RUNNING process: its start time (so a reused process id is never mistaken for ours), or None + when no such process runs.""" + try: + pid = int(pid) + except (TypeError, ValueError): + return None + if pid <= 0: + return None + if WIN: + h = _k32.OpenProcess(_QUERY, False, pid) + if not h: + return None + try: + code = wintypes.DWORD() + if not _k32.GetExitCodeProcess(h, ctypes.byref(code)) or code.value != _STILL_ACTIVE: + return None + c, e, k, u = (wintypes.FILETIME() for _ in range(4)) + if not _k32.GetProcessTimes(h, ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)): + return None + return f"win:{(c.dwHighDateTime << 32) | c.dwLowDateTime}" + finally: + _k32.CloseHandle(h) + stat = Path(f"/proc/{pid}/stat") + if Path("/proc/self/stat").exists(): + try: + fields = stat.read_text().rsplit(")", 1)[1].split() + except (OSError, IndexError): + return None + if fields[0] in ("Z", "X"): # a zombie has ended + return None + return f"linux:{fields[19]}" # field 22 of stat: the start time in clock ticks + try: # elsewhere (no /proc): alive, without a start time + os.kill(pid, 0) + return "pid" + except OSError: + return None + + +def proc_alive(pid, ident) -> bool: + return bool(ident) and proc_identity(pid) == ident + + +def proc_terminate(pid, ident) -> bool: + """Ask a process WE started to end (POSIX: SIGTERM, the server's clean path; Windows: TerminateProcess). Never + touches a process whose start time differs from the one recorded.""" + if not proc_alive(pid, ident): + return False + if WIN: + h = _k32.OpenProcess(_TERMINATE | _QUERY, False, int(pid)) + if not h: + return False + try: + return bool(_k32.TerminateProcess(h, 1)) + finally: + _k32.CloseHandle(h) + try: + os.kill(int(pid), signal.SIGTERM) + return True + except OSError: + return False + + +def proc_kill_tree(pid, ident) -> bool: + """End a process WE started together with the processes it started (setup's pip / cmake, the engine).""" + if not proc_alive(pid, ident): + return False + if WIN: + r = subprocess.run(["taskkill", "/PID", str(int(pid)), "/T", "/F"], capture_output=True, + creationflags=CREATE_NO_WINDOW) + return r.returncode == 0 + try: + os.killpg(int(pid), signal.SIGKILL) # started as a session leader: its group is its own + return True + except OSError: + try: + os.kill(int(pid), signal.SIGKILL) + return True + except OSError: + return False + + +def end_group_leftovers(pgid) -> None: + """POSIX: after the server WE started (a session leader) is gone, end what is left of its process group - an + engine it started but could not close (e.g. stopped while loading, before its own SIGTERM handler existed). + While any member lives, the group id cannot belong to anybody else.""" + if WIN or not pgid: + return + for sig, wait in ((signal.SIGTERM, 20.0), (signal.SIGKILL, 5.0)): + try: + os.killpg(int(pgid), sig) + except OSError: + return # no such group left + end = time.time() + wait + while time.time() < end: + try: + os.killpg(int(pgid), 0) + except OSError: + return + time.sleep(0.25) + + +def wait_gone(pid, ident, seconds: float) -> bool: + end = time.time() + seconds + while time.time() < end: + if not proc_alive(pid, ident): + return True + time.sleep(0.25) + return not proc_alive(pid, ident) + + +def spawn_detached(cmd: list, cwd: Path, log_path: Path, env: dict | None = None) -> subprocess.Popen: + """Start a background process whose output goes to log_path. It keeps running when the AI client (and this + server) ends: its own process group / session, no console window on Windows.""" + log_path.parent.mkdir(parents=True, exist_ok=True) + with open(log_path, "ab") as logf: + kw = dict(cwd=str(cwd), stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, + env=env, close_fds=True) + if WIN: + flags = CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW + try: # out of the AI client's job, if it lets us + return subprocess.Popen(cmd, creationflags=flags | CREATE_BREAKAWAY_FROM_JOB, **kw) + except OSError: + return subprocess.Popen(cmd, creationflags=flags, **kw) + return subprocess.Popen(cmd, start_new_session=True, **kw) + + +def run_quiet(cmd, timeout=30) -> str: + """A command's stdout ('' when it is missing or fails), without a console window flashing up on Windows.""" + try: + return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL, + creationflags=CREATE_NO_WINDOW if WIN else 0).stdout or "" + except (OSError, subprocess.SubprocessError, ValueError): + return "" + + +def read_tail(path: Path, lines: int, max_bytes: int = 512 * 1024) -> list[str]: + """The last lines of a log; a progress line rewritten with \\r counts as its last version.""" + try: + with open(path, "rb") as f: + f.seek(0, os.SEEK_END) + size = f.tell() + f.seek(max(0, size - max_bytes)) + data = f.read().decode("utf-8", "replace") + except OSError: + return [] + out = [] + for raw in data.split("\n"): + part = [p for p in raw.split("\r") if p.strip()] + if part: + out.append(part[-1].rstrip()) + return out[-lines:] + + +def dir_size_gb(path: Path, limit_files: int = 20000) -> float: + total, n = 0, 0 + for base, _dirs, files in os.walk(path): + for f in files: + try: + total += os.stat(os.path.join(base, f)).st_size + except OSError: + pass + n += 1 + if n >= limit_files: + return round(total / 1e9, 1) + return round(total / 1e9, 1) + + +# ------------------------------------------------------------------------------------------------ HTTP +_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) # localhost: never through a proxy + + +def http_json(url: str, method="GET", body=None, api_key=None, timeout=3.0): + """(status, JSON or None); status 0 when nothing answers.""" + data = json.dumps(body).encode() if body is not None else (b"" if method == "POST" else None) + req = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) + if api_key: + req.add_header("Authorization", f"Bearer {api_key}") + try: + with _OPENER.open(req, timeout=timeout) as r: + raw = r.read() + status = r.status + except urllib.error.HTTPError as e: + raw, status = e.read(), e.code + except (OSError, ValueError): + return 0, None + try: + return status, json.loads(raw or b"null") + except ValueError: + return status, None + + +def port_free(port: int, host="127.0.0.1") -> bool: + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind((host, port)) + return True + except OSError: + return False + finally: + s.close() + + +# ------------------------------------------------------------------------------------------------ validation +class ToolError(Exception): + """A clear message for the AI (and its user): the tool result is an error, the server goes on.""" + + +def check_schema(schema: dict, args) -> dict: + """The tools' JSON schemas, enforced: object, known properties only, types, enums, ranges, patterns.""" + if args is None: + args = {} + if not isinstance(args, dict): + raise ToolError("arguments must be a JSON object") + props = schema.get("properties", {}) + for k in args: + if k not in props: + raise ToolError(f"unknown argument {k!r}; this tool takes: {', '.join(props) or 'no arguments'}") + for k in schema.get("required", []): + if k not in args: + raise ToolError(f"missing argument {k!r}") + for k, v in args.items(): + p = props[k] + t = p.get("type") + if t == "integer" and (isinstance(v, bool) or not isinstance(v, int)): + if isinstance(v, float) and v.is_integer(): + v = args[k] = int(v) + elif isinstance(v, str) and re.fullmatch(r"\d{1,7}", v.strip()): + v = args[k] = int(v.strip()) # some clients send numbers as strings + else: + raise ToolError(f"{k} must be a whole number") + if t == "boolean" and not isinstance(v, bool): + if v in ("true", "false"): + v = args[k] = v == "true" + else: + raise ToolError(f"{k} must be true or false") + if t == "string": + if not isinstance(v, str): + raise ToolError(f"{k} must be a string") + if len(v) > p.get("maxLength", 300) or "\x00" in v or "\n" in v or "\r" in v: + raise ToolError(f"{k} is too long or contains control characters") + if "pattern" in p and not re.fullmatch(p["pattern"], v): + raise ToolError(f"{k}={v!r} is not valid ({p.get('description', p['pattern'])})") + if "enum" in p and v not in p["enum"]: + raise ToolError(f"{k} must be one of: {', '.join(map(str, p['enum']))} (got {v!r})") + if t == "integer": + if "minimum" in p and v < p["minimum"] or "maximum" in p and v > p["maximum"]: + raise ToolError(f"{k} must be between {p.get('minimum')} and {p.get('maximum')} (got {v})") + return args + + +def is_inside(path: Path, root: Path) -> bool: + try: + path.relative_to(root) + return True + except ValueError: + return False + + +def norm(p) -> Path: + """A path to compare: absolute, links and Windows' short names (AI-SER~1) resolved, case folded on Windows.""" + return Path(os.path.normcase(os.path.realpath(os.path.abspath(str(p))))) + + +def system_folders() -> list[Path]: + if WIN: + env = [os.environ.get(k) for k in ("SystemRoot", "windir", "ProgramFiles", "ProgramFiles(x86)", "ProgramData", + "ProgramW6432")] + return [norm(p) for p in env if p] + return [norm(p) for p in ("/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/proc", "/run", "/sbin", + "/sys", "/usr", "/var", "/snap")] + + +# ------------------------------------------------------------------------------------------------ Strata +class Strata: + """One Strata folder: what is installed there, the PC, and the processes this server started.""" + + def __init__(self, root: Path | str = DEFAULT_ROOT): + self.root = Path(root).resolve() + self.state_dir = self.root / STATE_DIR + self.lock = threading.Lock() # install / start / stop one at a time + self.children: list[subprocess.Popen] = [] # reaped now and then (no zombies on POSIX) + self._setup = None + self._setup_tried = False + self._hw_cache = None + self.python_override: str | None = None # tests: the interpreter that runs setup / the server + self.health_timeout = 2.0 + + # ---- setup.py's own tables and logic + def setup_module(self): + """setup.py imported as a module (its tables and its pure checks), or None. Its command runner is replaced + by one without console windows; nothing of its install path runs.""" + if not self._setup_tried: + self._setup_tried = True + try: + spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.root / "setup.py") + mod = importlib.util.module_from_spec(spec) + real = sys.stdout + sys.stdout = sys.stderr # nothing it prints may reach the protocol stream + try: + spec.loader.exec_module(mod) + finally: + sys.stdout = real + if all(hasattr(mod, a) for a in ("MODELS", "FAMILIES", "CONTEXTS")): + mod.out = lambda cmd: run_quiet(cmd, 60) + self._setup = mod + except (Exception, SystemExit) as e: # noqa: BLE001 - any failure: the built-in tables + log(f"setup.py could not be imported ({e}); using the built-in model table") + return self._setup + + def tables(self): + s = self.setup_module() + if s is not None: + return s.MODELS, s.FAMILIES, list(s.CONTEXTS), "setup.py" + return FALLBACK_MODELS, FALLBACK_FAMILIES, FALLBACK_CONTEXTS, "built-in table (setup.py not importable)" + + @staticmethod + def sizes_of(models, family) -> list: + return [m for m in models if family in models[m].get("families", ("qwen", "swift"))] + + # ---- paths + def settings_path(self) -> Path: + if WIN: + return Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / "Strata" / "settings.json" + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "settings.json" + + def data_dir(self) -> Path: + try: + s = json.loads(self.settings_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + s = {} + d = s.get("data_dir") if isinstance(s, dict) else None + return Path(d) if d else self.root.parent / "Strata-data" + + def allowed_roots(self) -> list[Path]: + return [norm(self.root), norm(self.data_dir())] + + def allowed(self, p) -> bool: + p = norm(p) + return any(is_inside(p, r) for r in self.allowed_roots()) + + def venv_python(self) -> Path: + return self.root / ".venv" / ("Scripts/python.exe" if WIN else "bin/python") + + def run_python(self) -> str: + return self.python_override or str(self.venv_python()) + + def state(self, name: str) -> dict: + try: + d = json.loads((self.state_dir / f"{name}.json").read_text(encoding="utf-8")) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + def save_state(self, name: str, d: dict | None) -> None: + self.state_dir.mkdir(parents=True, exist_ok=True) + f = self.state_dir / f"{name}.json" + if d is None: + f.unlink(missing_ok=True) + else: + tmp = f.with_suffix(".tmp") + tmp.write_text(json.dumps(d, indent=1), encoding="utf-8") + os.replace(tmp, f) + + def reap(self): + self.children = [p for p in self.children if p.poll() is None] + + # ---- what is installed + def configs(self) -> list[Path]: + return sorted(self.root.glob("strata-*.json"), key=lambda p: p.stat().st_mtime, reverse=True) + + @staticmethod + def read_config(path: Path) -> dict: + try: + cfg = json.loads(path.read_text(encoding="utf-8-sig")) + return cfg if isinstance(cfg, dict) else {} + except (OSError, ValueError): + return {} + + def describe_config(self, path: Path) -> dict: + cfg = self.read_config(path) + a = cfg.get("args") if isinstance(cfg.get("args"), list) else [] + + def val(k): + return a[a.index(k) + 1] if k in a and a.index(k) + 1 < len(a) else None + tag = path.stem[len("strata-"):] + missing = [p for p in [cfg.get("exe"), *[x for x in a if isinstance(x, str) and x.endswith(".gguf")]] + if not p or not Path(p).exists()] + script = self.root / f"run-{tag}.{'bat' if WIN else 'sh'}" + vis = cfg.get("vision") + return {"model": tag, "config": path.name, "model_name": cfg.get("model_name"), + "context": int(val("--max-context")) if str(val("--max-context") or "").isdigit() else None, + "kv": val("--kv"), "images": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "off", + "port": cfg.get("port", DEFAULT_PORT), "host": cfg.get("host", "127.0.0.1"), + "gpu": cfg.get("gpu"), "api_key_set": bool(cfg.get("api_key")), + "low_ram": "--resident-experts" in a or "--mmap-experts" in a, + "start_script": script.name if script.exists() else None, + "ready": not missing and bool(cfg), "missing_files": missing[:3], + "last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))} + + def find_config(self, model: str | None) -> Path: + have = self.configs() + if not have: + raise ToolError("no model is installed in " + str(self.root) + " yet: install one first (strata_install)") + if not model: + return have[0] # the most recently used, as setup starts it + m = model.strip().lower() + exact = [c for c in have if c.stem[len("strata-"):] == m] + if exact: + return exact[0] + by_name = [c for c in have if str(self.read_config(c).get("model_name", "")).lower() == m] + if by_name: + return by_name[0] + ends = [c for c in have if c.stem.endswith("-" + m)] + if len(ends) == 1: + return ends[0] + raise ToolError(f"no installed model {model!r}; installed: " + + ", ".join(c.stem[len("strata-"):] for c in have)) + + def engine_info(self) -> dict: + for d in ("engine",): + try: + meta = json.loads((self.root / d / "BUILD.json").read_text()) + return {"folder": d, "version": meta.get("version"), "source": meta.get("source"), + "backend": meta.get("backend")} + except (OSError, ValueError): + continue + return {"folder": None, "version": None} + + def installed(self) -> dict: + data = self.data_dir() + items = {} + for sub in ("models", "packs"): + for base in dict.fromkeys([data, self.root]): + d = base / sub + if d.is_dir(): + for c in sorted(d.iterdir()): + if c.is_dir(): + ggufs = list(c.glob("*.gguf")) + entry = {"folder": str(c), "size_gb": dir_size_gb(c)} + if sub == "models": + entry["complete"] = bool(ggufs) and all( + g.with_name(g.name + ".done").exists() for g in ggufs) + entry["downloading"] = bool(list(c.glob("*.part"))) + items.setdefault(sub, []).append(entry) + mtp = data / "mtp" / "rt" / "experts.bin" + return {"strata_folder": str(self.root), "data_folder": str(data), "data_folder_exists": data.is_dir(), + "python_env": self.venv_python().exists(), "engine": self.engine_info(), + "models": [self.describe_config(c) for c in self.configs()], + "downloads": items.get("models", []), "prepared": items.get("packs", []), + "draft_layer": mtp.exists()} + + # ---- the PC + def hardware(self, fresh=False) -> dict: + if self._hw_cache and not fresh and time.time() - self._hw_cache[0] < 600: + hw = dict(self._hw_cache[1]) + else: + hw = self._hardware() + self._hw_cache = (time.time(), hw) + hw = dict(hw) + hw["disk_free_gb"] = self.disk_free(self.data_dir()) + return hw + + @staticmethod + def disk_free(p: Path) -> float | None: + p = Path(p) + while not p.exists() and p.parent != p: + p = p.parent + try: + return round(shutil.disk_usage(p).free / 1e9, 1) + except OSError: + return None + + def _hardware(self) -> dict: + S = self.setup_module() + hw = {"os": f"{platform.system()} {platform.release()}", "os_version": platform.version(), + "machine": platform.machine(), "python": platform.python_version()} + if not WIN and Path("/proc/version").exists(): + try: + hw["wsl"] = "microsoft" in Path("/proc/version").read_text().lower() + except OSError: + pass + try: + hw["ram_gb"] = round(S.ram_gb(), 1) if S else round(own_ram_gb(), 1) + except Exception: # noqa: BLE001 + hw["ram_gb"] = round(own_ram_gb(), 1) + if S and WIN: + try: + hw["page_file_gb"] = round(S.page_file_gb(), 1) + except Exception: # noqa: BLE001 + pass + try: + if S: + name, avx2, avx512 = S.cpu_info() + else: + name, avx2, avx512 = platform.processor() or "unknown CPU", None, None + hw["cpu"] = {"name": name, "cores": os.cpu_count(), "avx2": avx2, "avx512": avx512} + except Exception: # noqa: BLE001 + hw["cpu"] = {"name": platform.processor(), "cores": os.cpu_count()} + nv = [] + try: + nv = S.gpus() if S else own_nvidia_gpus() + except Exception: # noqa: BLE001 + nv = own_nvidia_gpus() + for g in nv: + g["vendor"] = "nvidia" + g["vram_gb"] = round(g["vram_gb"], 1) + try: + g["problem"] = S.gpu_problem(g) if S else (None if int(g["arch"]) >= 75 else "older than RTX 20") + except Exception: # noqa: BLE001 + g["problem"] = None + g["usable"] = g["problem"] is None + amd = [] + if not WIN: + try: + amd = S.amd_gpus() if S else [] + for g in amd: + g["vendor"] = "amd" + g["vram_gb"] = round(g["vram_gb"], 1) + g["problem"] = S.amd_problem(g) + g["usable"] = g["problem"] is None + except Exception: # noqa: BLE001 + amd = [] + if not amd and shutil.which("rocm-smi"): + amd = rocm_smi_gpus() + hw["gpus"] = nv + amd + if WIN: + hw["display_adapters"] = windows_video_controllers() + hw["nvidia_smi"] = bool(shutil.which("nvidia-smi")) + return hw + + def recommend(self, hw: dict) -> dict: + """setup.py's own rules: the size it preselects (IQ3_XXS from 60 GB of RAM, else the first, Q2_0), the + Coder below the full model's RAM (setup's RAM table), the low-RAM mode when the GPU makes up for the RAM, and + the context it preselects for the card's VRAM (32K under 14 GB, 64K under 20 GB, else 128K).""" + models, families, _ctx, _src = self.tables() + S = self.setup_module() + usable = [g for g in hw.get("gpus", []) if g.get("usable")] + ram = hw.get("ram_gb") or 0 + if not usable: + why = ("no NVIDIA RTX 20-series-or-newer GPU found (nvidia-smi did not list one)" + + ("; AMD cards run on Linux only" if WIN and any( + "amd" in str(a.get("name", "")).lower() or "radeon" in str(a.get("name", "")).lower() + for a in hw.get("display_adapters", [])) else "")) + return {"family": None, "model": None, "why": why} + best = max(usable, key=lambda g: (round(g["vram_gb"]), -g.get("index", 0))) + vram = best["vram_gb"] + backend = "hip" if best.get("vendor") == "amd" else "cuda" + + def low_fits(m): + try: + return S.low_ram_fits(m, ram, vram) if S else ram - 6 + max(0.0, vram - 5) >= models[m]["arena_gb"] + except Exception: # noqa: BLE001 + return False + notes = [] + if ram >= 60: + fam, model, why = "qwen", "IQ3_XXS", f"{ram:.0f} GB of RAM: setup's own pick from 60 GB (better quality)" + elif ram >= models["Q2_0"]["ram_gb"] - 4: + fam, model, why = "qwen", "Q2_0", f"{ram:.0f} GB of RAM: the full model's fastest size fits" + elif ram >= models["IQ1_M"]["ram_gb"] - 4: + fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM: the full model needs ~48 GB; the Coder " + "(half the experts, best for code) needs ~32 GB") + elif low_fits("IQ1_M"): + fam, model, why = "coder", "IQ1_M", (f"{ram:.0f} GB of RAM is below the Coder's 32 GB, but the GPU's " + f"{vram:.0f} GB make up for it (setup's low-RAM mode: slower)") + else: + return {"family": None, "model": None, "why": f"{ram:.0f} GB of RAM: Strata needs 32 GB or more " + "(the smallest model, the Coder, keeps ~23 GB of experts in " + "RAM)"} + ctx = 32768 if vram < 14 else 65536 if vram < 20 else 131072 + if vram < 11: + notes.append("less than 12 GB of VRAM: it runs, but slowly (most experts stay on the CPU)") + if hw.get("cpu", {}).get("avx2") is False: + return {"family": None, "model": None, "why": "this CPU has no AVX2; Strata needs at least AVX2"} + if backend == "hip": + notes.append("AMD (experimental, Linux): the engine is compiled during setup; no images") + cmd = (("START-HERE.bat --setup" if WIN else "./setup.sh --setup") + + f" --yes --family {fam} --model {model} --context {ctx}" + (" --backend hip" if backend == "hip" else "")) + return {"family": fam, "model": model, "title": families[fam]["title"] + " " + model, "context": ctx, + "backend": backend, "gpu": {k: best.get(k) for k in ("index", "name", "vram_gb")}, + "download_gb": models[model]["download_gb"], "why": why, "notes": notes, "setup_command": cmd} + + def model_table(self, hw: dict | None) -> list: + models, families, _ctx, _src = self.tables() + S = self.setup_module() + ram = (hw or {}).get("ram_gb") + usable = [g for g in (hw or {}).get("gpus", []) if g.get("usable")] + vram = max((g["vram_gb"] for g in usable), default=0.0) + have = {c.stem[len("strata-"):] for c in self.configs()} + out = [] + for f, fd in families.items(): + sizes = [] + for m in self.sizes_of(models, f): + d = models[m] + tag = (fd.get("tag", "") + m).lower() + verdict = None + if ram is not None: + verdict = "fits" if ram >= d["ram_gb"] else "tight" if ram >= d["ram_gb"] - 8 else "does not fit" + try: + if d.get("budget"): + verdict = ("experimental: part of its experts in RAM, the rest read from the SSD" + if ram >= d["ram_gb"] else "does not fit") + elif S and S.low_ram_needed(m, ram) and S.low_ram_fits(m, ram, vram): + verdict = "fits in the low-RAM mode (slower: the GPU holds part of the experts)" + except Exception: # noqa: BLE001 + pass + sizes.append({"model": m, "about": d["about"], "download_gb": d["download_gb"], + "ram_needed_gb": d["ram_gb"], "experts_gb": d.get("arena_gb"), + "on_this_pc": verdict, "installed": tag in have, "id": tag}) + out.append({"family": f, "title": fd["title"], "about": fd.get("about"), + "experimental": bool(fd.get("experimental")), "images": fd.get("vision", True) is not False, + "sizes": sizes}) + return out + + # ---- the running server + def ports(self, port: int | None) -> list[int]: + if port: + return [port] + ps = [self.state("server").get("port")] + [self.describe_config(c)["port"] for c in self.configs()] + return list(dict.fromkeys(int(p) for p in [*ps, DEFAULT_PORT] if isinstance(p, int))) + + def api_key_for(self, port: int) -> str | None: + """The key a config of this folder set for that port (used for our own requests; never shown).""" + for c in self.configs(): + cfg = self.read_config(c) + if cfg.get("api_key") and int(cfg.get("port", DEFAULT_PORT)) == port: + return cfg["api_key"] + for c in self.configs(): + if self.read_config(c).get("api_key"): + return self.read_config(c)["api_key"] + return None + + def probe(self, port: int, deep=True) -> dict | None: + """What answers on 127.0.0.1:port: a Strata server's facts, {"other": True} for something else, None for + nothing.""" + base = f"http://127.0.0.1:{port}" + st, health = http_json(base + "/health", timeout=self.health_timeout) + if st == 0: + return None + if st != 200 or not isinstance(health, dict) or health.get("service") != "strata": + return {"port": port, "other": True, "note": "something else answers on this port (not a Strata server)"} + info = {"port": port, "url": base, "model": health.get("model"), "context": health.get("max_context"), + "images": health.get("images"), "loaded": health.get("loaded"), + "api_key_required": bool(health.get("api_key"))} + if not deep: + return info + key = self.api_key_for(port) + st, v1 = http_json(base + "/v1/status", api_key=key, timeout=self.health_timeout) + if st == 200 and isinstance(v1, dict): + info["engine_version"] = v1.get("engine") + info["uptime_s"] = v1.get("uptime_s") + info["requests_served"] = (v1.get("activity") or {}).get("requests") + m = v1.get("machine") or {} + if m.get("gpu"): + info["gpu"] = m["gpu"] + if m.get("ram"): + info["ram"] = m["ram"] + if v1.get("last_timings"): + lt = v1["last_timings"] + info["last_request"] = {k: lt.get(k) for k in ("prompt_n", "prompt_per_second", "predicted_n", + "predicted_per_second") if k in lt} + elif st == 401: + info["note"] = "the server wants an API key this folder's configs do not have" + st, s = http_json(base + "/status", api_key=key, timeout=self.health_timeout) + if st == 200 and isinstance(s, dict): + info["busy"] = bool(s.get("busy")) + info["activity"] = {k: s.get(k) for k in ("phase", "generated", "tokens_per_s", "queued", "elapsed_s") + if s.get(k) is not None} + if "gpu" not in info: # older servers: the Monitor's numbers + st, met = http_json(base + "/metrics", api_key=key, timeout=self.health_timeout) + if st == 200 and isinstance(met, dict): + hwn = met.get("hardware") or {} + if hwn.get("gpu_mem_total"): + info["gpu"] = {"used_mib": round(hwn.get("gpu_mem_used", 0) / 2**20), + "total_mib": round(hwn["gpu_mem_total"] / 2**20)} + if hwn.get("ram_total"): + info["ram"] = {"used_gib": round(hwn.get("ram_used", 0) / 2**30, 1), + "total_gib": round(hwn["ram_total"] / 2**30, 1)} + info["engine_version"] = (met.get("engine") or {}).get("version") + return info + + def tracked_server(self) -> dict | None: + """The server this MCP server started, while it still runs (else its record is cleared).""" + s = self.state("server") + if not s: + return None + if proc_alive(s.get("pid"), s.get("ident")): + return s + return {**s, "ended": True} + + # ---- install job + def install_job(self) -> dict | None: + j = self.state("install") + if not j: + return None + res = self.state("install-result") + running = proc_alive(j.get("pid"), j.get("ident")) + log_path = Path(j.get("log", "")) + tail = read_tail(log_path, 400) if log_path.name else [] + prog = install_progress(tail) + out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"), + "log": str(log_path), **prog} + if not running: + if res.get("job") == j.get("job") and "exit_code" in res: + out["exit_code"] = res["exit_code"] + out["finished"] = res.get("ended") + out["result"] = "installed" if res["exit_code"] == 0 else "failed" + else: + out["result"] = "ended unexpectedly (no exit code recorded)" + else: + out["result"] = "running" + out["last_lines"] = tail[-12:] + return out + + +def install_progress(lines: list[str]) -> dict: + """setup's progress from its output: the step, a download's percentage, a failure.""" + step, title, dl, err = None, None, None, None + for i, line in enumerate(lines): + m = re.search(r"=== Step (\d+): (.+?) ===", line) + if m: + step, title, err = int(m.group(1)), m.group(2), None + m = re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", line) + if m: + dl = {"file": m.group(1), "done_gb": float(m.group(2)), "total_gb": float(m.group(3)), + "percent": int(m.group(4))} + if line.strip().startswith("[X]"): + err = line.strip()[3:].strip() + if i + 1 < len(lines) and lines[i + 1].startswith(" "): + err += " - " + lines[i + 1].strip() + out = {"step": f"{step}/7: {title}" if step else None} + if dl: + out["download"] = dl + if err: + out["error"] = err + return out + + +def own_ram_gb() -> float: + if WIN: + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + *((n, ctypes.c_ulonglong) for n in ("tp", "ap", "tpf", "apf", "tv", "av", "aev"))] + m = MS() + m.dwLength = ctypes.sizeof(MS) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) + return m.tp / 2**30 + try: + for line in open("/proc/meminfo"): + if line.startswith("MemTotal"): + return int(line.split()[1]) * 1024 / 2**30 + except OSError: + pass + return 0.0 + + +def own_nvidia_gpus() -> list: + s = run_quiet(["nvidia-smi", "--query-gpu=index,name,memory.total,compute_cap,driver_version", + "--format=csv,noheader,nounits"]) + found = [] + for line in s.strip().splitlines(): + try: + idx, name, mem, cc, drv = [x.strip() for x in line.split(",")] + found.append({"index": int(idx), "name": name, "vram_gb": float(mem) / 1024.0, + "arch": cc.replace(".", ""), "driver": drv}) + except ValueError: + continue + return found + + +def windows_video_controllers() -> list: + s = run_quiet(["powershell", "-NoProfile", "-NonInteractive", "-Command", + "Get-CimInstance Win32_VideoController | Select-Object Name,DriverVersion | ConvertTo-Json -Compress"]) + try: + d = json.loads(s) if s.strip() else [] + except ValueError: + return [] + d = [d] if isinstance(d, dict) else d + return [{"name": x.get("Name"), "driver": x.get("DriverVersion")} for x in d if isinstance(x, dict)] + + +def rocm_smi_gpus() -> list: + s = run_quiet(["rocm-smi", "--showproductname", "--showmeminfo", "vram", "--json"]) + try: + d = json.loads(s) + except ValueError: + return [] + out = [] + for i, (card, v) in enumerate(sorted(d.items())): + if not isinstance(v, dict) or not card.lower().startswith("card"): + continue + total = next((v[k] for k in v if "total" in k.lower() and "vram" in k.lower()), 0) + try: + vram = int(total) / 2**30 + except (TypeError, ValueError): + vram = 0.0 + out.append({"index": i, "name": v.get("Card Series") or v.get("Card SKU") or card, "vram_gb": round(vram, 1), + "vendor": "amd", "usable": None, "problem": "listed by rocm-smi (setup checks the card itself)"}) + return out + + +# ------------------------------------------------------------------------------------------------ the tools +GPUS_PATTERN = r"all|\d{1,2}(,\d{1,2}){1,7}" +MODEL_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,48}" + + +def tool_defs(models: dict, families: dict, contexts: list) -> list: + port = {"type": "integer", "minimum": 1024, "maximum": 65535, + "description": "the server's port (default: the installed model's port, usually 8080)"} + installed_model = {"type": "string", "pattern": MODEL_ID_PATTERN, "maxLength": 49, + "description": "an installed model's id as strata_status lists it (e.g. 'q2_0', " + "'coder-iq1_m', 'swift-iq3_xxs'); default: the most recently used one"} + ro = {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False} + return [ + {"name": "strata_status", "title": "Strata status", + "description": "Is Strata (the local AI model server) running, and what is installed? Reports the running " + "server (model, engine version, context, busy or idle, VRAM/RAM in use), the installed models " + "and data folder, an install in progress, this PC's hardware (OS, CPU, RAM, GPUs, free disk) " + "and the model size setup recommends for this PC. Read-only; call it first.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "port": port, + "hardware": {"type": "boolean", "description": "include the hardware check and the recommendation " + "(default true; takes a second or two)"}}}, + "annotations": ro}, + {"name": "strata_models", "title": "Strata models", + "description": "The models and sizes Strata's setup offers (families: qwen = Qwen3.8-Flash-Next, swift = " + "Swift 1.5, coder = the Coder, unsloth = experimental 4-bit), with download size, RAM needed, " + "whether each fits this PC, which are installed, the context lengths, and the recommendation. " + "Read-only.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": {}}, + "annotations": ro}, + {"name": "strata_install", "title": "Install Strata", + "description": "Install a Strata model on this PC by running Strata's setup non-interactively in the " + "background (Python packages, the engine, a 58-111 GB model download, preparation, start " + "script). Without confirm=true it only returns the plan (what would be downloaded, disk " + "space): show it to the user and call again with confirm=true once they agree. Returns at " + "once; call it again (no arguments needed) to see the progress, or with cancel=true to stop " + "it (it resumes later). Defaults: the recommended model and context for this PC, images off. " + "After it finishes, start the model with strata_start.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "family": {"type": "string", "enum": list(families), + "description": "qwen = Qwen3.8-Flash-Next (the original), swift = Swift 1.5 (thinks " + "shorter), coder = the Coder (half the experts, ~32 GB RAM, for code), " + "unsloth = 4-bit EXPERIMENTAL (slow)"}, + "model": {"type": "string", "enum": list(models), + "description": "the size (quantization): see strata_models"}, + "context": {"type": "integer", "enum": contexts, + "description": "context length in tokens (more needs more VRAM)"}, + "vision": {"type": "string", "enum": ["no", "yes", "gpu", "cpu"], + "description": "let the model read images (yes = the encoder on the GPU; ~0.9 GB more " + "download); default no"}, + "kv": {"type": "string", "enum": ["int8", "q4_0", "k8v4"], + "description": "KV cache precision above 8K context (default int8)"}, + "gpu": {"type": "integer", "minimum": 0, "maximum": 63, + "description": "one GPU, as nvidia-smi numbers them (default: the one with the most VRAM)"}, + "gpus": {"type": "string", "pattern": GPUS_PATTERN, "maxLength": 40, + "description": "several GPUs sharing the model: '0,2' or 'all' (experimental)"}, + "backend": {"type": "string", "enum": ["auto", "cuda", "hip"], + "description": "auto (default), cuda = NVIDIA, hip = AMD on Linux (experimental)"}, + "low_ram": {"type": "string", "enum": ["auto", "on", "off", "resident", "mmap"], + "description": "setup's low-RAM mode (default auto)"}, + "port": {**port, "description": "the port the model will listen on (default 8080)"}, + "data_dir": {"type": "string", "maxLength": 260, + "description": "where the model files go (default: the Strata-data folder next to the " + "Strata folder). Only the current data folder, a folder inside the Strata " + "folder, or a new absolute path whose last folder is named Strata... " + "(e.g. D:\\Strata-data) outside system folders"}, + "confirm": {"type": "boolean", "description": "true = really start the install (after the user agreed " + "to the plan and the download size)"}, + "cancel": {"type": "boolean", "description": "true = stop the install in progress"}}}, + "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, + "openWorldHint": True}}, + {"name": "strata_start", "title": "Start Strata", + "description": "Start an installed Strata model in the background (as its start script does, without " + "opening a browser) and wait until it answers. Loading takes 1-3 minutes and the PC can be " + "slow meanwhile; if it is not ready within wait_seconds this returns 'loading' - check again " + "with strata_status. The model keeps running until strata_stop.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "model": installed_model, "port": port, + "gpu": {"type": "integer", "minimum": 0, "maximum": 63, + "description": "run on this GPU for this start (as nvidia-smi numbers them)"}, + "wait_seconds": {"type": "integer", "minimum": 0, "maximum": 600, + "description": "how long to wait for it to be ready (default 50: some AI apps end " + "a tool call after 60 s)"}}}, + "annotations": {"readOnlyHint": False, "destructiveHint": False, "idempotentHint": True, + "openWorldHint": False}}, + {"name": "strata_stop", "title": "Stop Strata", + "description": "Stop the Strata model: the engine is unloaded through the server's own API (it frees its " + "VRAM and RAM itself), then the server this tool started is ended. A Strata started " + "elsewhere (e.g. its own window) is only unloaded - close its window to end it. Refuses while " + "a request is running unless force=true.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "port": port, + "force": {"type": "boolean", "description": "stop even while a request is running"}}}, + "annotations": {"readOnlyHint": False, "destructiveHint": True, "idempotentHint": True, + "openWorldHint": False}}, + {"name": "strata_logs", "title": "Strata logs", + "description": "The last lines of a Strata log: 'server' (the model server this tool started: loading, " + "requests, errors), 'engine' (the engine's own log for a model), 'setup' (the install). " + "Default: the setup log while an install runs, else the server log. Read-only.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "source": {"type": "string", "enum": ["server", "engine", "setup"]}, + "model": installed_model, + "lines": {"type": "integer", "minimum": 1, "maximum": 500, "description": "default 80"}}}, + "annotations": ro}, + {"name": "strata_benchmark", "title": "Strata speed test", + "description": "A short fixed request (greedy, thinking off) through the running Strata server; reports " + "the output speed (tokens/s) and prompt speed. Takes 10-60 s. Refuses while the model is " + "busy.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": { + "port": port, + "max_tokens": {"type": "integer", "minimum": 16, "maximum": 512, "description": "default 200"}}}, + "annotations": {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False}}, + {"name": "strata_connect_info", "title": "Connect to Strata", + "description": "How to point other apps at the local Strata server: the OpenAI and Anthropic base URLs, " + "the model id, whether an API key is needed, and ready-to-paste settings for Claude Code, " + "Codex CLI, the OpenAI SDK, curl, Cursor/Continue/Open WebUI. Read-only.", + "inputSchema": {"type": "object", "additionalProperties": False, "properties": {"port": port}}, + "annotations": ro}, + ] + + +class Tools: + def __init__(self, strata: Strata): + self.s = strata + + def defs(self) -> list: + return tool_defs(*self.s.tables()[:3]) + + def call(self, name: str, args) -> dict: + defs = {d["name"]: d for d in self.defs()} + if name not in defs: + raise KeyError(name) + args = check_schema(defs[name]["inputSchema"], args) + return getattr(self, name)(**args) + + # ---- strata_status + def strata_status(self, port=None, hardware=True) -> dict: + s = self.s + s.reap() + servers = [] + for p in s.ports(port): + info = s.probe(p) + if info is not None: + servers.append(info) + tracked = s.tracked_server() + out = {} + running = [x for x in servers if not x.get("other")] + if tracked and not tracked.get("ended"): + mine = next((x for x in running if x["port"] == tracked["port"]), None) + if mine: + mine["started_by"] = f"this MCP server (pid {tracked['pid']})" + else: + out["loading"] = {"model": tracked.get("model"), "port": tracked["port"], "pid": tracked["pid"], + "since": tracked.get("started"), + "last_log_line": (read_tail(Path(tracked.get("log", "")), 1) or [None])[-1]} + elif tracked and tracked.get("ended"): + out["last_start"] = {"model": tracked.get("model"), "ended": True, + "last_log_lines": read_tail(Path(tracked.get("log", "")), 6)} + for x in running: + x.setdefault("started_by", "outside this MCP server (its own window, a start script or a service)") + out["running"] = running + others = [x for x in servers if x.get("other")] + if others: + out["ports_used_by_other_programs"] = others + if running: + r = running[0] + summary = (f"Strata is running on port {r['port']}: {r.get('model')}" + + (", busy" if r.get("busy") else ", idle") + + ("" if r.get("loaded", True) else " (model unloaded; the next request loads it)")) + elif "loading" in out: + summary = f"Strata is loading {out['loading']['model']} (port {out['loading']['port']})" + else: + summary = "Strata is not running" + inst = s.installed() + job = s.install_job() + if job: + out["install"] = job + if job["running"]: + summary += f"; an install is running ({job.get('step') or 'starting'})" + if not inst["models"]: + summary += "; no model is installed yet" + else: + summary += "; installed: " + ", ".join(m["model"] for m in inst["models"]) + out["installed"] = inst + if hardware: + hw = s.hardware() + out["hardware"] = hw + out["recommendation"] = s.recommend(hw) + return {"summary": summary, **out} + + # ---- strata_models + def strata_models(self) -> dict: + s = self.s + hw = s.hardware() + _m, _f, contexts, src = s.tables() + rec = s.recommend(hw) + return {"summary": "Model families and sizes setup offers" + ( + f"; recommended for this PC: {rec['title']}, {rec['context'] // 1024}K context" + if rec.get("model") else f"; no model fits this PC: {rec['why']}"), + "families": s.model_table(hw), "contexts": contexts, + "context_note": "longer contexts need more VRAM (fewer experts fit on the GPU); past 262144 setup adds " + "rope scaling (experimental)", + "recommendation": rec, "source": src, + "this_pc": {"ram_gb": hw.get("ram_gb"), + "gpus": [{k: g.get(k) for k in ("index", "name", "vram_gb", "usable")} + for g in hw.get("gpus", [])]}} + + # ---- strata_install + def check_data_dir(self, raw: str) -> Path: + s = self.s + if raw.startswith("\\\\") or raw.startswith("//"): + raise ToolError("data_dir: network (UNC) paths are not allowed; use a local drive") + p = Path(os.path.expandvars(raw)).expanduser() + if not p.is_absolute(): + raise ToolError("data_dir must be an absolute path (e.g. D:\\Strata-data or /mnt/big/Strata-data)") + if ".." in p.parts: + raise ToolError("data_dir must not contain '..'") + n = norm(p) + current = norm(s.data_dir()) + if n == current or is_inside(n, norm(s.root)) or n == norm(s.root.parent / "Strata-data"): + pass + else: + if not p.name.lower().startswith("strata"): + raise ToolError(f"data_dir {raw!r}: a new data folder must be named Strata... (e.g. " + f"{Path(p.anchor or '/') / 'Strata-data'}), so that no other folder is filled with " + "model files") + if not p.parent.is_dir(): + raise ToolError(f"data_dir {raw!r}: its parent folder {p.parent} does not exist") + if any(n == f or is_inside(n, f) for f in system_folders()): + raise ToolError(f"data_dir {raw!r} is inside a system folder") + if p.exists() and not p.is_dir(): + raise ToolError(f"data_dir {raw!r} is a file") + return p + + def strata_install(self, family=None, model=None, context=None, vision=None, kv=None, gpu=None, gpus=None, + backend=None, low_ram=None, port=None, data_dir=None, confirm=False, cancel=False) -> dict: + s = self.s + with s.lock: + job = s.install_job() + if cancel: + if not job or not job["running"]: + return {"summary": "no install is running", "install": job} + j = s.state("install") + res = s.state("install-result") + child = res.get("child_pid") if res.get("job") == j.get("job") else None + if child: + proc_kill_tree(child, res.get("child_ident")) + proc_kill_tree(j["pid"], j["ident"]) + wait_gone(j["pid"], j["ident"], 15) + return {"summary": "the install was stopped; calling strata_install again resumes it (downloads " + "continue where they stopped)", "install": s.install_job()} + if job and job["running"]: + return {"summary": f"an install is running: {job.get('step') or 'starting'}" + + (f", downloading {job['download']['file']} {job['download']['percent']}%" + if job.get("download") else ""), + "install": job, "follow": "call strata_install again for progress, or strata_logs " + "source=setup for the full output"} + given = [x for x in (family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir) + if x is not None] + if job and not given and not confirm: + return {"summary": f"the last install {job['result']}" + (f": {job['error']}" if job.get("error") else ""), + "install": job, + "next": "strata_start" if job.get("exit_code") == 0 else + "fix the problem above and call strata_install again with confirm=true (finished " + "steps are skipped)"} + plan, args = self.install_plan(family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, + data_dir) + tracked = s.tracked_server() + if tracked and not tracked.get("ended"): + raise ToolError("Strata is running (started by strata_start): stop it first with strata_stop - setup " + "may update the engine files it uses") + if not confirm: + return {"summary": f"Plan: install {plan['title']} ({plan['download_gb']:.0f} GB download" + f"{' at most; part of it is already here' if plan['partly_downloaded'] else ''}). " + "Nothing was done yet: ask the user, then call strata_install again with the " + "same arguments and confirm=true.", "plan": plan} + if plan["disk_short"]: + raise ToolError(plan["disk_short"]) + return self.launch_install(plan, args) + + def install_plan(self, family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir): + s = self.s + models, families, contexts, _src = s.tables() + if gpu is not None and gpus is not None: + raise ToolError("give gpu (one card) or gpus (several), not both") + if backend == "hip" and WIN: + raise ToolError("the AMD (hip) backend runs on Linux only; on Windows Strata needs an NVIDIA RTX 20 " + "series or newer card") + if sys.version_info < (3, 10) or (WIN and sys.maxsize <= 2**32): + raise ToolError("this Python is too old or 32-bit: Strata's setup needs 64-bit Python 3.10+; run " + + ("START-HERE.bat" if WIN else "./setup.sh") + " once instead (it installs Python)") + hw = s.hardware() + rec = s.recommend(hw) + if model is None and family is None: + if not rec.get("model"): + raise ToolError("no model was given and none fits this PC: " + rec["why"]) + family, model = rec["family"], rec["model"] + context = context or rec["context"] + elif model is None: + sizes = s.sizes_of(models, family) + model = rec["model"] if rec.get("family") == family else ("IQ3_XXS" if "IQ3_XXS" in sizes and + hw.get("ram_gb", 0) >= 60 else sizes[0]) + elif family is None: + fams = [f for f in families if model in s.sizes_of(models, f)] + family = "qwen" if "qwen" in fams else fams[0] + sizes = s.sizes_of(models, family) + if model not in sizes: + raise ToolError(f"{families[family]['title']} has no {model}; its sizes: {', '.join(sizes)}") + if context is None: + usable = [g for g in hw.get("gpus", []) if g.get("usable")] + vram = max((g["vram_gb"] for g in usable), default=12) + context = 32768 if vram < 14 else 65536 if vram < 20 else 131072 + if models[model].get("budget"): + context = 8192 if vram < 14 else 32768 + if vision in ("yes", "gpu", "cpu") and families[family].get("vision") is False: + raise ToolError(f"images are not available with {families[family]['title']} yet: use vision=no") + if vision is not None and backend == "hip" and vision != "no": + raise ToolError("images are not available on the AMD backend yet: use vision=no") + target = self.check_data_dir(data_dir) if data_dir else s.data_dir() + tag = (families[family].get("tag", "") + model) + have_dir = target / "models" / tag + partly = have_dir.is_dir() and any(have_dir.glob("*.gguf*")) + need = (8 if partly else models[model]["download_gb"] + 8) + (1 if vision in ("yes", "gpu", "cpu") else 0) + free = s.disk_free(target) + short = None + if free is not None and free < need: + short = (f"not enough free disk space for {model}: about {need:.0f} GB needed at {target}, " + f"{free:.0f} GB free; free some space or choose data_dir on a bigger drive (e.g. D:\\Strata-data)") + args = ["--yes", "--no-start", "--family", family, "--model", model, "--context", str(context), + "--vision", vision or "no"] + if family in ("qwen", "coder"): + args += ["--experimental-speed-projection", "off"] + for flag, v in (("--kv", kv), ("--gpu", gpu), ("--gpus", gpus), ("--low-ram", low_ram), ("--port", port), + ("--data-dir", str(target) if data_dir else None)): + if v is not None: + args += [flag, str(v)] + if backend in ("cuda", "hip"): + args += ["--backend", backend] + fit = None + ram = hw.get("ram_gb") + if ram is not None: + need_ram = models[model]["ram_gb"] + fit = "fits" if ram >= need_ram else f"needs ~{need_ram} GB of RAM, this PC has {ram:.0f} GB" + installed = (s.root / f"strata-{tag.lower()}.json").exists() + plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model, + "context": context, "images": vision or "no", "download_gb": models[model]["download_gb"], + "partly_downloaded": partly, "ram": fit, "data_folder": str(target), "disk_free_gb": free, + "disk_needed_gb": round(need), "disk_short": short, "already_installed": installed, + "setup_command": ("START-HERE.bat " if WIN else "./setup.sh ") + " ".join(args), + "takes": "about 20-90 minutes, mostly the download; the PC stays usable", + "recommended_for_this_pc": rec if rec.get("model") else None} + if installed: + plan["note"] = ("this model is already installed: running setup again updates the engine and applies " + "the options (finished steps are skipped)") + if families[family].get("license"): + plan["license"] = families[family]["license"] + if families[family].get("experimental"): + plan["experimental"] = True + return plan, args + + def launch_install(self, plan: dict, args: list) -> dict: + s = self.s + s.state_dir.mkdir(parents=True, exist_ok=True) + job_id = f"{int(time.time())}-{os.getpid()}" + log_path = s.state_dir / "setup.log" + with open(log_path, "a", encoding="utf-8") as f: + f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n") + spec = {"job": job_id, "root": str(s.root), "python": s.run_python(), "base_python": sys.executable, + "create_venv": s.python_override is None and not s.venv_python().exists(), + "args": args, "result": str(s.state_dir / "install-result.json")} + spec_path = s.state_dir / "install-job.json" + spec_path.write_text(json.dumps(spec, indent=1), encoding="utf-8") + s.save_state("install-result", None) + env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") + p = spawn_detached([sys.executable, str(Path(__file__).resolve()), "--install-job", str(spec_path)], + s.root, log_path, env) + s.children.append(p) + time.sleep(0.2) + ident = proc_identity(p.pid) + if ident is None and p.poll() and s.state("install-result").get("job") != job_id: + raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5))) + s.save_state("install", {"job": job_id, "pid": p.pid, "ident": ident, "log": str(log_path), + "model": plan["model"], "family": plan["family"], + "started": time.strftime("%Y-%m-%d %H:%M:%S"), "args": args}) + return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the " + f"{plan['download_gb']:.0f} GB download). Call strata_install again to see the progress; " + "when it is done, start it with strata_start.", + "plan": plan, "log": str(log_path), "pid": p.pid} + + # ---- strata_start + def strata_start(self, model=None, port=None, gpu=None, wait_seconds=50) -> dict: + s = self.s + with s.lock: + job = s.install_job() + if job and job["running"]: + raise ToolError("an install is still running (strata_install shows its progress); start the model " + "when it is done") + cfg_path = s.find_config(model) + desc = s.describe_config(cfg_path) + if not desc["ready"]: + raise ToolError(f"{cfg_path.name} refers to missing files ({', '.join(desc['missing_files'])}): run " + "the install again (strata_install with confirm=true) to repair it") + port = port or desc["port"] or DEFAULT_PORT + tracked = s.tracked_server() + if tracked and not tracked.get("ended"): + info = s.probe(tracked["port"]) + return {"summary": f"Strata is already {'running' if info else 'loading'} ({tracked.get('model')}, " + f"port {tracked['port']}, started by this MCP server)" + + ("" if tracked.get("model") == desc["model"] else + ": stop it first (strata_stop) to start another model"), + "server": info} + info = s.probe(port, deep=False) + if info and not info.get("other"): + return {"summary": f"a Strata server already runs on port {port} ({info.get('model')}), started " + "outside this MCP server; stop it (close its window) or use another port", + "server": info} + if info or not port_free(port): + raise ToolError(f"port {port} is used by another program; choose another port (port=...)") + py = s.run_python() + if not Path(py).exists(): + raise ToolError("Strata's Python environment (.venv) is missing: run the install again") + cmd = [py, str(s.root / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port)] + if gpu is not None: + cmd += ["--gpu", str(gpu)] + log_path = s.state_dir / "server.log" + s.state_dir.mkdir(parents=True, exist_ok=True) + with open(log_path, "a", encoding="utf-8") as f: + f.write(f"\n===== strata-mcp: start {desc['model']} on port {port} at " + f"{time.strftime('%Y-%m-%d %H:%M:%S')} =====\n") + env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") + try: + os.utime(cfg_path) # the most recently used model, as setup's start marks it + except OSError: + pass + p = spawn_detached(cmd, s.root, log_path, env) + s.children.append(p) + time.sleep(0.1) + ident = proc_identity(p.pid) + s.save_state("server", {"pid": p.pid, "ident": ident, "port": port, "model": desc["model"], + "config": cfg_path.name, "log": str(log_path), + "started": time.strftime("%Y-%m-%d %H:%M:%S")}) + return self.wait_ready(p, ident, port, desc, wait_seconds, log_path) + + def wait_ready(self, p, ident, port, desc, wait_seconds, log_path) -> dict: + s = self.s + end = time.time() + wait_seconds + while True: + if p.poll() is not None or not proc_alive(p.pid, ident): + tail = read_tail(log_path, 15) + end_group_leftovers(p.pid) + s.save_state("server", None) + raise ToolError(f"Strata stopped while starting (exit code {p.poll()}). Its last output:\n" + + "\n".join(tail)) + info = s.probe(port) + if info and not info.get("other"): + return {"summary": f"Strata is running: {info.get('model')} on http://127.0.0.1:{port}/v1 " + "(OpenAI and Anthropic APIs; chat page at http://127.0.0.1:" + str(port) + "/)", + "server": {**info, "pid": p.pid}} + if time.time() >= end: + return {"summary": f"Strata is loading {desc['model']} (this takes 1-3 minutes; the PC may be slow " + "meanwhile). Check with strata_status in a minute.", + "loading": {"pid": p.pid, "port": port, + "last_log_line": (read_tail(log_path, 1) or [None])[-1]}} + time.sleep(1.0) + + # ---- strata_stop + def strata_stop(self, port=None, force=False) -> dict: + s = self.s + with s.lock: + tracked = s.tracked_server() + if tracked and tracked.get("ended"): + s.save_state("server", None) + tracked = None + if tracked: + port = tracked["port"] + key = s.api_key_for(port) + st, body = http_json(f"http://127.0.0.1:{port}/status", api_key=key, timeout=3) + if st == 200 and isinstance(body, dict) and body.get("busy") and not force: + raise ToolError("a request is running on Strata right now; wait for it, or call strata_stop " + "with force=true to stop anyway") + st, body = http_json(f"http://127.0.0.1:{port}/unload", "POST", api_key=key, timeout=120) + unloaded = (body or {}).get("status") if isinstance(body, dict) else None + if st == 409 and not force: + raise ToolError("Strata is busy (a request is running or queued); call again with force=true " + "to stop anyway") + proc_terminate(tracked["pid"], tracked["ident"]) # POSIX: SIGTERM = the server's own Ctrl+C path + clean = wait_gone(tracked["pid"], tracked["ident"], 30) + if not clean: + proc_kill_tree(tracked["pid"], tracked["ident"]) + wait_gone(tracked["pid"], tracked["ident"], 15) + s.reap() + gone = not proc_alive(tracked["pid"], tracked["ident"]) + if gone: + end_group_leftovers(tracked["pid"]) + s.save_state("server", None) + return {"summary": "Strata stopped" + ("" if gone else " - but its process still runs; see strata_logs") + + (" (the engine unloaded itself first)" if unloaded == "unloaded" else ""), + "model": tracked.get("model"), "port": port, "engine_unloaded": unloaded, + "ended_cleanly": clean} + for p in s.ports(port): + info = s.probe(p, deep=False) + if info and not info.get("other"): + key = s.api_key_for(p) + st, body = http_json(f"http://127.0.0.1:{p}/unload", "POST", api_key=key, timeout=120) + r = body.get("status") if isinstance(body, dict) else None + if st == 409: + raise ToolError("Strata is busy (a request is running); try again when it is done") + if st == 401: + raise ToolError("Strata (started outside this MCP server) wants an API key this folder's " + "configs do not have; close its window to stop it") + return {"summary": f"Strata on port {p} was started outside this MCP server (its own window or a " + f"service), so only its model was unloaded ({r}): its VRAM and RAM are free, " + "but the server still listens and loads the model again on the next request. " + "Close its window to end it completely.", + "port": p, "engine_unloaded": r} + return {"summary": "Strata is not running"} + + # ---- strata_logs + def strata_logs(self, source=None, model=None, lines=80) -> dict: + s = self.s + if source is None: + job = s.install_job() + source = "setup" if job and job["running"] else "server" + if source == "setup": + path = s.state_dir / "setup.log" + elif source == "server": + path = s.state_dir / "server.log" + else: + cfg = s.find_config(model or (s.state("server").get("model"))) + raw = s.read_config(cfg).get("log") + if not raw: + raise ToolError(f"{cfg.name} names no engine log") + path = Path(raw) + if not s.allowed(path): + raise ToolError(f"{cfg.name}'s log {raw} is outside the Strata folder and its data folder: not shown") + if not path.exists(): + return {"summary": f"no {source} log yet ({path})", "log": str(path), "lines": []} + tail = read_tail(path, lines) + return {"summary": f"last {len(tail)} lines of the {source} log", "log": str(path), "lines": tail} + + # ---- strata_benchmark + def strata_benchmark(self, port=None, max_tokens=200) -> dict: + s = self.s + target = None + for p in s.ports(port): + info = s.probe(p, deep=False) + if info and not info.get("other"): + target = info + break + if target is None: + raise ToolError("Strata is not running: start it first (strata_start)") + p = target["port"] + key = s.api_key_for(p) + st, stat = http_json(f"http://127.0.0.1:{p}/status", api_key=key, timeout=3) + if st == 200 and isinstance(stat, dict) and (stat.get("busy") or stat.get("queued")): + raise ToolError("Strata is busy with a request; run the speed test when it is idle") + body = {"model": target.get("model") or "strata", "max_tokens": max_tokens, "temperature": 0, + "reasoning_effort": "none", "stream": False, + "messages": [{"role": "user", "content": BENCH_PROMPT}]} + t0 = time.time() + st, r = http_json(f"http://127.0.0.1:{p}/v1/chat/completions", "POST", body, api_key=key, timeout=600) + wall = time.time() - t0 + if st != 200 or not isinstance(r, dict): + msg = (r or {}).get("error", {}).get("message") if isinstance(r, dict) else None + raise ToolError(f"the request failed (HTTP {st}): {msg or 'no answer'}") + usage, tm = r.get("usage") or {}, r.get("timings") or {} + n = usage.get("completion_tokens") or tm.get("predicted_n") or 0 + out = {"model": r.get("model"), "port": p, "prompt_tokens": usage.get("prompt_tokens"), + "output_tokens": n, "wall_s": round(wall, 2), + "output_tok_s": round(tm["predicted_per_second"], 1) if tm.get("predicted_per_second") else None, + "prompt_tok_s": round(tm["prompt_per_second"], 1) if tm.get("prompt_per_second") else None, + "wall_tok_s": round(n / wall, 1) if wall > 0 and n else None, + "finish_reason": ((r.get("choices") or [{}])[0]).get("finish_reason"), + "settings": f"greedy (temperature 0), thinking off, max_tokens {max_tokens}, a fixed story prompt"} + speed = out["output_tok_s"] or out["wall_tok_s"] + out["summary"] = (f"{n} tokens at {speed} tokens/s" + (f" (prompt {out['prompt_tok_s']} tokens/s)" + if out["prompt_tok_s"] else "") + + f", {wall:.1f} s in total") + out["note"] = ("output speed depends on the context length, the GPU's free VRAM and what else the PC does; " + "the first request after a start is slower") + return out + + # ---- strata_connect_info + def strata_connect_info(self, port=None) -> dict: + s = self.s + target = None + for p in s.ports(port): + info = s.probe(p, deep=False) + if info and not info.get("other"): + target = info + break + if port is None: + cfgs = s.configs() + port = target["port"] if target else (s.describe_config(cfgs[0])["port"] if cfgs else DEFAULT_PORT) + model = (target or {}).get("model") or "strata" + key_needed = (target or {}).get("api_key_required") + if key_needed is None: + key_needed = any(s.describe_config(c)["api_key_set"] for c in s.configs()) + key = ".json>" if key_needed else "none" + base = f"http://127.0.0.1:{port}" + return { + "summary": (f"Strata {'runs' if target else 'will run'} at {base}: OpenAI base URL {base}/v1, Anthropic " + f"base URL {base}" + (" (an API key is required)" if key_needed else " (any API key works)")), + "running": bool(target), "openai_base_url": f"{base}/v1", "anthropic_base_url": base, + "anthropic_messages_endpoint": f"{base}/v1/messages", "chat_page": base + "/", "model": model, + "api_key": ("required: the \"api_key\" value in the Strata folder's strata-.json" + if key_needed else "not required (send any value)"), + "examples": { + "claude_code": {"env": {"ANTHROPIC_BASE_URL": base, "ANTHROPIC_AUTH_TOKEN": key, + "ANTHROPIC_MODEL": "claude-sonnet-4-5"}, + "note": "Claude Code needs a Claude model name it knows; Strata ignores the name"}, + "codex_cli": {"file": "~/.codex/config.toml", + "toml": f'model = "{model}"\nmodel_provider = "strata"\n\n[model_providers.strata]\n' + f'name = "Strata"\nbase_url = "{base}/v1"\nwire_api = "chat"'}, + "openai_python": (f'from openai import OpenAI\nclient = OpenAI(base_url="{base}/v1", api_key="{key}")\n' + f'r = client.chat.completions.create(model="{model}", messages=[{{"role": "user", ' + f'"content": "Hello!"}}])\nprint(r.choices[0].message.content)'), + "curl": (f"curl {base}/v1/chat/completions -H \"Content-Type: application/json\" " + + (f"-H \"Authorization: Bearer {key}\" " if key_needed else "") + + f"-d '{{\"model\": \"{model}\", \"messages\": [{{\"role\": \"user\", \"content\": " + "\"Hello!\"}]}'"), + "openai_compatible_apps": {"base_url": f"{base}/v1", "api_key": key, "model": model, + "apps": "Cursor (Settings > Models > OpenAI base URL override), " + "Continue, Open WebUI, LM Studio clients, aider " + f"(--openai-api-base {base}/v1)"}}, + "other_devices": "the server listens on this PC only; to reach it from your network, run setup with " + "--host 0.0.0.0 --api-key (docs/DETAILS.md, 'Using it')"} + + +# ------------------------------------------------------------------------------------------------ MCP over stdio +INSTRUCTIONS = ("Strata runs a large AI model (Qwen3.8-Flash-Next, a mixture of experts) locally on this PC's GPU and " + "RAM, with an OpenAI- and Anthropic-compatible server on http://127.0.0.1:8080. Call strata_status " + "first. To install: strata_install (it returns a plan; get the user's OK for the 58-111 GB download, " + "then call it with confirm=true; it runs in the background - call it again for progress). Then " + "strata_start, strata_stop, strata_logs for problems, strata_connect_info to point other apps at it.") + + +class McpServer: + def __init__(self, strata: Strata, out=None): + self.strata = strata + self.tools = Tools(strata) + self.out = out + self.write_lock = threading.Lock() + self.protocol = PROTOCOL + + def send(self, msg: dict) -> None: + data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8") + with self.write_lock: + self.out.write(data) + self.out.flush() + + @staticmethod + def result(rid, result): + return {"jsonrpc": "2.0", "id": rid, "result": result} + + @staticmethod + def error(rid, code, message): + return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}} + + def handle(self, msg) -> dict | None: + """One JSON-RPC message -> its response (None for a notification or a response).""" + if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0": + return self.error(msg.get("id") if isinstance(msg, dict) else None, -32600, "invalid request") + if "method" not in msg: + return None # a response to something we never ask: ignored + method, rid, params = msg["method"], msg.get("id"), msg.get("params") or {} + if "id" not in msg: + return None # notifications (initialized, cancelled ...): nothing to say + if not isinstance(params, dict): + return self.error(rid, -32602, "params must be an object") + if method == "initialize": + asked = str(params.get("protocolVersion") or PROTOCOL) + self.protocol = asked if asked in PROTOCOLS else PROTOCOL + return self.result(rid, {"protocolVersion": self.protocol, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "strata", "title": "Strata", "version": VERSION}, + "instructions": INSTRUCTIONS}) + if method == "ping": + return self.result(rid, {}) + if method == "tools/list": + return self.result(rid, {"tools": self.tools.defs()}) + if method == "tools/call": + name = params.get("name") + try: + res = self.tools.call(name, params.get("arguments")) + return self.result(rid, self.content(res, error=False)) + except KeyError: + return self.error(rid, -32602, f"unknown tool: {name}") + except ToolError as e: + return self.result(rid, self.content({"error": str(e)}, error=True)) + except Exception as e: # noqa: BLE001 - a bug must not end the server + log("tool failed:\n" + traceback.format_exc()) + return self.result(rid, self.content({"error": f"internal error in {name}: {e}"}, error=True)) + if method in ("resources/list", "prompts/list"): + return self.result(rid, {method.split("/")[0]: []}) + return self.error(rid, -32601, f"method not found: {method}") + + def content(self, res: dict, error: bool) -> dict: + text = json.dumps(res, indent=1, ensure_ascii=False) + out = {"content": [{"type": "text", "text": text}], "isError": error} + if self.protocol >= "2025-06-18": + out["structuredContent"] = res + return out + + def serve(self, inp) -> None: + """Read JSON-RPC lines until stdin closes; tool calls run in their own threads (a start waits for the model + while pings and status calls are still answered).""" + threads = [] + for raw in inp: + line = raw.decode("utf-8", "replace").strip() if isinstance(raw, bytes) else raw.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + self.send(self.error(None, -32700, "parse error")) + continue + batch = isinstance(msg, list) + if batch or (isinstance(msg, dict) and msg.get("method") == "tools/call"): + t = threading.Thread(target=self._run, args=(msg,), daemon=True) + t.start() + threads.append(t) + threads = [x for x in threads if x.is_alive()] + else: + self._run(msg) + for t in threads: + t.join(timeout=5) + + def _run(self, msg) -> None: + if isinstance(msg, list): + out = [r for r in (self.handle(m) for m in msg) if r is not None] + if out: + data = (json.dumps(out, ensure_ascii=False) + "\n").encode("utf-8") + with self.write_lock: + self.out.write(data) + self.out.flush() + return + r = self.handle(msg) + if r is not None: + self.send(r) + + +# ------------------------------------------------------------------------------------------------ the install job +def install_job(spec_path: str) -> int: + """The background half of strata_install (this file started again with --install-job): make .venv like + START-HERE.bat / setup.sh do when it is missing, run setup, record its exit code.""" + spec = json.loads(Path(spec_path).read_text(encoding="utf-8")) + root = Path(spec["root"]) + result = Path(spec["result"]) + + def record(**kw): + try: + old = json.loads(result.read_text(encoding="utf-8")) if result.exists() else {} + except (OSError, ValueError): + old = {} + tmp = result.with_suffix(".tmp") + tmp.write_text(json.dumps({**old, "job": spec["job"], **kw}, indent=1), encoding="utf-8") + os.replace(tmp, result) + + py = Path(spec["python"]) + try: + if spec.get("create_venv"): + venv = root / ".venv" + if py.exists() and subprocess.run([str(py), "-m", "pip", "--version"], capture_output=True).returncode: + print("strata-mcp: .venv has no pip (an earlier run stopped half-way): making it again", flush=True) + shutil.rmtree(venv, ignore_errors=True) + if not py.exists(): + print(f"strata-mcp: creating Strata's Python environment in {venv} ...", flush=True) + r = subprocess.run([spec["base_python"], "-m", "venv", str(venv)]) + if r.returncode or not py.exists(): + print("\n [X] could not create the Python environment (.venv)", flush=True) + print(" Linux: install python3-venv (sudo apt install python3-venv) or run ./setup.sh " + "once in a terminal", flush=True) + record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S")) + return 1 + cmd = [str(py), str(root / "setup.py"), *spec["args"]] + print("strata-mcp: running " + " ".join(cmd), flush=True) + env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8") + p = subprocess.Popen(cmd, cwd=str(root), stdin=subprocess.DEVNULL, env=env) + record(child_pid=p.pid, child_ident=proc_identity(p.pid)) + rc = p.wait() + except Exception as e: # noqa: BLE001 + print(f"\n [X] strata-mcp could not run setup: {e}", flush=True) + rc = 1 + print(f"strata-mcp: setup ended with exit code {rc}", flush=True) + record(exit_code=rc, ended=time.strftime("%Y-%m-%d %H:%M:%S")) + return rc + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description="Strata's MCP server (stdio): install, start, check and stop Strata " + "from an AI assistant. See docs/MCP_SERVER.md.") + ap.add_argument("--root", help="the Strata folder (default: the one this file is in)") + ap.add_argument("--install-job", help=argparse.SUPPRESS) + a = ap.parse_args(argv) + if a.install_job: + return install_job(a.install_job) + if sys.version_info < (3, 10): + log("Python 3.10 or newer is needed") + return 2 + root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT + if not (root / "setup.py").is_file() or not (root / "serve" / "server.py").is_file(): + log(f"{root} is not a Strata folder (no setup.py / serve/server.py)") + return 2 + out = sys.stdout.buffer + sys.stdout = sys.stderr # stray prints must never corrupt the protocol stream + server = McpServer(Strata(root), out) + log(f"ready (Strata folder {root})") + try: + server.serve(sys.stdin.buffer) + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/engine/strata/tools/strata_pack.py b/engine/strata/tools/strata_pack.py new file mode 100644 index 00000000..31fbe226 --- /dev/null +++ b/engine/strata/tools/strata_pack.py @@ -0,0 +1,423 @@ +"""Strata P1.S6/S7 - the pack builder and verifier. + +This is `strata-pack build` / `strata-pack verify` / `strata-pack info`. It is the Python implementation of +`docs/pack-format.md`; the C++ `tools/strata-pack` is a port of it, and if the two disagree the C++ is wrong. + +WHY PYTHON FIRST. The canonicalisation in `tools/canonical_xcheck.py` is measured bit-exact over every block +of every tensor (757,139,840 blocks across 1021 tensors, plus Q2_0), against gguf-py and, for Q2_0, backed by +`dequant_xcheck` against ggml itself. That makes the Python mapping table the specification of record. The +pack is Phase 2's prerequisite and can be produced from it today; the port then has a golden artifact to be +tested against instead of being the thing everything else waits on. + +THE ONE RULE. A pack is only valid if, for every tensor, `decode(pack) == dequant_ggml(source)` BIT FOR BIT. +`verify` is that test and it is not optional - it re-reads the written pack from disk and compares it against +the source shard. A pack that has not passed `verify` does not exist. + +SCALE PRECISION. A canonical scale is an FP32 product (`fl(d*sc)`), which is generally NOT representable in +FP16. The packer therefore stores scales as FP16 only when the round-trip is exact and as FP32 otherwise, and +records which per tensor. It never has to decide correctly: `verify` re-checks bit-exactness, so a wrong +choice is a failed build rather than a silently lossy pack. The expert arena is the exception and is FP16 by +construction - architecture §3.2 fixes the blob at exactly 1,382,400 bytes and pack_layer.py asserts it. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import pathlib +import struct +import sys + +import numpy as np + +HERE = pathlib.Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "ref")) + +import gguf_reader as G # noqa: E402 +import pack_layer as PL # noqa: E402 +from canonical_xcheck import (MAPPINGS, KV_IQ4NL, open_shard, # noqa: E402 + data_section_offset, reference_values) + +FORMAT_VERSION = 1 +ALIGN = 64 # every plane starts on a 64-byte boundary (P1.S7) +_HERE = pathlib.Path(__file__).resolve() +STRATA = _HERE.parents[min(3, len(_HERE.parents) - 1)] # the development layout; build takes the shard from --gguf +SHARD2 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" + +EXPERT_RE = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight") +EMBD_NAME = "token_embd.weight" + + +def is_expert(name: str) -> bool: + return name.startswith("blk.") and name.endswith(EXPERT_RE) + + +def code_bits(form: str) -> int: + return {"S2": 2, "S4": 4, "S8": 8}[form] + + +def pack_codes(codes: np.ndarray, bits: int) -> bytes: + """Pack one code per element into bytes, LSB-first, `8//bits` codes per byte. + + This is Q2_0's own convention (4 codes per byte, byte j/4, bits (j%4)*2), kept for every form so the + kernel has one unpacking loop rather than one per source type. + """ + flat = codes.reshape(-1).astype(np.uint8) + if bits == 8: + return flat.tobytes() + per = 8 // bits + if flat.size % per: + raise ValueError("code count %d is not a multiple of %d per byte" % (flat.size, per)) + g = flat.reshape(-1, per).astype(np.uint16) + out = np.zeros(g.shape[0], dtype=np.uint16) + for k in range(per): + out |= (g[:, k] & ((1 << bits) - 1)) << (k * bits) + return out.astype(np.uint8).tobytes() + + +def unpack_codes(buf: bytes, bits: int, n: int) -> np.ndarray: + if bits == 8: + return np.frombuffer(buf, dtype=np.uint8)[:n].copy() + per = 8 // bits + b = np.frombuffer(buf, dtype=np.uint8) + out = np.empty((b.size, per), dtype=np.uint8) + for k in range(per): + out[:, k] = (b >> (k * bits)) & ((1 << bits) - 1) + return out.reshape(-1)[:n].copy() + + +def choose_scale_dtype(scales: np.ndarray) -> tuple[np.ndarray, bool]: + """FP16 when the round-trip is exact, else FP32. Returns (bytes, is_fp16).""" + as16 = scales.astype(np.float16) + if np.array_equal(as16.astype(np.float32), scales): + return as16.tobytes(), True + return scales.astype(" the canonical planes, as (codes, scales, offsets_or_None, mapping).""" + m = MAPPINGS[tname] + parts = m.enc(raw) + if len(parts) == 3: + return parts[0], parts[1], parts[2], m + return parts[0], parts[1], None, m + + +def tensor_entry(name, meta, tname, raw, seg_offset): + """Encode one tensor and return (blob_bytes, manifest_entry).""" + m = MAPPINGS[tname] + + body = bytearray() + base = seg_offset + + def put(b: bytes) -> dict: + nonlocal body + pad = (-len(body)) % ALIGN + body += b"\0" * pad + off = base + len(body) + body += b + return {"offset": off, "bytes": len(b)} + + common = { + "name": name, "source_type": tname, "form": m.form, "codebook": m.codebook, + "code_bias": m.code_bias, "has_offset": m.has_offset, + "block_elems": m.block_elems, "block_bytes": m.block_bytes, "group_elems": m.group_elems, + "shape": list(meta.shape), "source_offset": meta.offset, + } + + # ---- P16/P32 are pass-through: one value plane, no codes, no scale, no offset + if m.form in ("P16", "P32"): + vals = np.ascontiguousarray(m.dec(m.enc(raw)), dtype=np.float32).reshape(-1) + if m.form == "P32": + vb, v16 = vals.astype(" np.ndarray: + """Decode a tensor from the pack, using ONLY what the manifest says. + + Deliberately manifest-driven: if the manifest does not carry enough to decode the tensor, this cannot + silently fall back on knowledge of the source type, and the omission becomes a failure here. + """ + if ent["form"] in ("P16", "P32"): + vb = head[ent["values"]["offset"]: ent["values"]["offset"] + ent["values"]["bytes"]] + return np.frombuffer(vb, dtype=" str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + b = f.read(chunk) + if not b: + break + h.update(b) + return h.hexdigest() + + +def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool) -> int: + out_dir.mkdir(parents=True, exist_ok=True) + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + print("source %s: %d tensors, data at %d" % (gguf.name, len(g.tensors), data_off)) + + n_layers = 48 if n_layers is None else n_layers + man = { + "format": "strata-pack", "format_version": FORMAT_VERSION, + "source": {"shard1": str(gguf), "shard2": str(SHARD2)}, + "n_layers": n_layers, "align": ALIGN, + "codebooks": {"IQ4NL": [float(x) for x in KV_IQ4NL]}, + "tensors": {}, "experts": {}, "n_experts_per_layer": PL.NE, + } + + # ---- experts.bin: delegated to pack_layer so the blob layout has exactly ONE implementation + # pack_layer reads its own hardcoded SHARD1, so a different --gguf would silently take the expert arena + # from a different file than the dense tensors. Refuse rather than produce a mixed-source pack. + # the expert arena and the dense tensors come from the same file: point pack_layer at it + PL.SHARD1 = pathlib.Path(gguf).resolve() + shard2 = pathlib.Path(str(PL.SHARD1).replace("00001-of-00002", "00002-of-00002")) + man["source"]["shard2"] = str(shard2) + exp_path = out_dir / "experts.bin" + print("experts.bin: %d layers, %.2f GiB" % (n_layers, n_layers * PL.NE * PL.BLOB_BYTES / 2**30)) + em = PL.build(n_layers, exp_path) + man["experts"] = {"blob_bytes": em["blob_bytes"], "offsets": em["offsets"], + "layers": em["layers"], "total_bytes": em["total_bytes"], + "scales_fp16": True, "source_type": "Q2_0", "form": "S2"} + + # ---- dense.bin and embd.bin + dense = [] + embd = [] + for t in g.tensors: + if is_expert(t.name): + continue + (embd if t.name == EMBD_NAME else dense).append(t) + + for fname, group in (("dense.bin", dense), ("embd.bin", embd)): + path = out_dir / fname + seg_base = 0 + with open(path, "wb") as fh: + for t in group: + if t.type_name not in MAPPINGS: + print(" %s: NO MAPPING for %s - refusing to build" % (t.name, t.type_name)) + return 1 + raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] + if len(raw) != (t.expected_bytes() or 0): + print(" %s: SHORT READ - refusing to build" % t.name) + return 1 + blob, ent = tensor_entry(t.name, t, t.type_name, raw, seg_base) + ent["file"] = fname + fh.write(blob) + seg_base += len(blob) + man["tensors"][t.name] = ent + print("%s: %d tensors, %.2f GiB" % (fname, len(group), path.stat().st_size / 2**30)) + + man["files"] = {"experts.bin": exp_path.stat().st_size, + "dense.bin": (out_dir / "dense.bin").stat().st_size, + "embd.bin": (out_dir / "embd.bin").stat().st_size} + if not skip_hash: + print("hashing shards (this is the slow part)...") + man["source"]["shard1_sha256"] = sha256(gguf) + man["source"]["shard2_sha256"] = sha256(shard2) if shard2.exists() else None + # shard 2 is NOT copied: the PLE table stays where it is and the manifest records how to find it + if shard2.exists(): + g2 = G.GGUFFile(shard2) + t2 = [t for t in g2.tensors if t.name == "per_layer_token_embd.weight"][0] + man["shard2_tensor"] = {"name": t2.name, "type": t2.type_name, "shape": list(t2.shape), + "offset": t2.offset, "elements": t2.elements, + "path": str(shard2)} + (out_dir / "manifest.json").write_text(json.dumps(man, indent=1), encoding="utf-8") + print("manifest.json: %d tensor entries" % len(man["tensors"])) + return 0 + + +def rebuild_role(blob: bytes, role: str) -> bytes: + """Rebuild one role's raw Q2_0 bytes from an expert blob - the exact inverse of pack_layer's layout. + + The arena stores codes and scales in SEPARATE PLANES and interleaves gate/up ROWS (g0,u0,g1,u1,...), so + a verifier that cannot invert that cannot check the arena. Written as the inverse on purpose: this is + the only independent statement about the blob layout in the tree, and if it and `pack_layer` were the + same code the arena would be unverified by construction. + """ + O, out = PL.OFF, bytearray() + n_blk = PL.H * PL.FF // PL.QK + for blk in range(n_blk): + if role == "down": + row, b_in = blk // PL.SCALES_D, blk % PL.SCALES_D + co = O["down_codes"] + row * PL.ROW_BYTES_D + b_in * 16 + so = O["down_scales"] + (row * PL.SCALES_D + b_in) * 2 + else: + row, b_in = blk // PL.SCALES_GU, blk % PL.SCALES_GU + slot = 2 * row + (0 if role == "gate" else 1) + co = O["gate_up_codes"] + slot * PL.ROW_BYTES_GU + b_in * 16 + so = O["gate_up_scales"] + (slot * PL.SCALES_GU + b_in) * 2 + out += blob[so:so + 2] # fp16 d first, as block_q2_0 has it + out += blob[co:co + 16] # then the 16 packed code bytes + return bytes(out) + + +def verify_experts(gguf: pathlib.Path, out_dir: pathlib.Path, man: dict, every: int) -> int: + """Verify the expert arena: 85% of the pack by bytes and the part Phase 2 reads 480x per token.""" + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + by_name = {t.name: t for t in g.tensors} + exp_mm, _ = open_shard(out_dir / "experts.bin") + blob = man["experts"]["blob_bytes"] + n_layers = man["n_layers"] + checked = bad = 0 + for layer in range(n_layers): + for e in range(0, PL.NE, every): + base = (layer * PL.NE + e) * blob + b = exp_mm[base:base + blob] + for role in ("gate", "up", "down"): + t = by_name["blk.%d.ffn_%s_exps.weight" % (layer, role)] + per_expert = t.elements // PL.NE + nbytes = per_expert * PL.BLOCK_BYTES // PL.QK + src = head[data_off + t.offset + e * nbytes: data_off + t.offset + (e + 1) * nbytes] + ref = reference_values("Q2_0", src) + got = MAPPINGS["Q2_0"].dec(canonicalise(t.name, "Q2_0", rebuild_role(b, role))[:2]) + checked += 1 + if not np.array_equal(ref, got): + print(" layer %d expert %d %-4s *** MISMATCH *** max|d| %.3e" + % (layer, e, role, np.abs(ref.astype(np.float64) - got.astype(np.float64)).max())) + bad += 1 + print("experts: %d layer/expert/role checks (%d layers, every %dth expert), %d bad" + % (checked, n_layers, every, bad)) + return bad + + +def verify(gguf: pathlib.Path, out_dir: pathlib.Path, limit: int | None, expert_every: int) -> int: + """P1.T3 over the pack: decode it from disk and compare with the source, bit for bit.""" + man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) + # A full verify also reads back the source hash build recorded (absent after --skip-hash, which is how setup + # builds): a pack compared against a different shard than it was built from is a mismatch, not a decode bug. + want = (man.get("source") or {}).get("shard1_sha256") + if want and limit is None: + got = sha256(gguf) + if got != want: + print("%s: sha256 %s, but the pack was built from %s" % (gguf.name, got, want)) + print("tools/strata_pack.py verify FAIL") + return 1 + g = G.GGUFFile(gguf) + head, flen = open_shard(gguf) + data_off = data_section_offset(g, flen) + by_name = {t.name: t for t in g.tensors} + files = {} + bad = 0 + n_t = n_el = 0 + for i, (name, ent) in enumerate(sorted(man["tensors"].items())): + if limit is not None and i >= limit: + break + if ent["file"] not in files: + files[ent["file"]] = open_shard(out_dir / ent["file"])[0] + t = by_name[name] + raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)] + ref = reference_values(t.type_name, raw) + got = decode_entry(files[ent["file"]], ent) + n_t += 1 + n_el += ref.size + if ref.shape != got.shape or not np.array_equal(ref, got): + d = np.abs(ref.astype(np.float64) - got.astype(np.float64)) if ref.shape == got.shape else None + print(" %-40s *** MISMATCH *** %s" % (name, ("max|d| %.3e" % d.max()) if d is not None else + "shape %s vs %s" % (ref.shape, got.shape))) + bad += 1 + elif i < 3 or i % 200 == 0: + print(" %-40s bit-exact (%d elements, %s)" % (name, ref.size, ent["form"])) + print() + print("verify: %d tensors, %d elements, %d bad" % (n_t, n_el, bad)) + if expert_every > 0: + bad += verify_experts(gguf, out_dir, man, expert_every) + print("tools/strata_pack.py verify " + ("PASS" if bad == 0 else "FAIL")) + return 0 if bad == 0 else 1 + + +def info(out_dir: pathlib.Path) -> int: + man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8")) + print("strata-pack v%d layers=%d" % (man["format_version"], man["n_layers"])) + for f, n in man.get("files", {}).items(): + print(" %-12s %12.3f GiB" % (f, n / 2**30)) + forms = {} + for e in man["tensors"].values(): + forms[e["form"]] = forms.get(e["form"], 0) + 1 + print(" dense/embd by form: %s" % ", ".join("%s=%d" % kv for kv in sorted(forms.items()))) + print(" experts: %d blobs x %d B, %s" % (man["experts"]["layers"].__len__() * man["n_experts_per_layer"], + man["experts"]["blob_bytes"], man["experts"]["source_type"])) + return 0 + + +def main() -> int: + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + b = sub.add_parser("build") + b.add_argument("--gguf", required=True) + b.add_argument("--out", required=True) + b.add_argument("--layers", type=int, default=None, help="expert layers to emit (default 48)") + b.add_argument("--skip-hash", action="store_true") + v = sub.add_parser("verify") + v.add_argument("--gguf", required=True) + v.add_argument("--out", required=True) + v.add_argument("--limit", type=int, default=None) + v.add_argument("--expert-every", type=int, default=32, + help="verify every Nth expert per layer in the arena (0 disables; the arena is 85%% of " + "the pack and verifying NONE of it is how a pack passes while being wrong)") + n = sub.add_parser("info") + n.add_argument("--out", required=True) + args = ap.parse_args() + if args.cmd == "build": + return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash) + if args.cmd == "verify": + return verify(pathlib.Path(args.gguf), pathlib.Path(args.out), args.limit, args.expert_every) + return info(pathlib.Path(args.out)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/tools/strata_tokenizer.py b/engine/strata/tools/strata_tokenizer.py new file mode 100644 index 00000000..c14492cb --- /dev/null +++ b/engine/strata/tools/strata_tokenizer.py @@ -0,0 +1,326 @@ +"""tools/strata_tokenizer.py - the tokenizer, as the reference implementation of record. + +WHY THIS EXISTS AND WHERE IT SITS. The GGUF carries the whole tokenizer in metadata: `tokenizer.ggml.model` += `gpt2`, 248,320 `tokens`, 247,587 `merges`, `token_type`, `pre` = `qwen35`, and a Jinja `chat_template`. +None of that needs the 35 GB of weights, so it is extracted into the pack's `tokenizer/` directory +(docs/pack-format.md §6) and this module is what reads it back. A C++ port follows and is tested against +this one. + +THE DECISIVE PROPERTY IS THE ROUND TRIP. Byte-level BPE maps each BYTE to a printable unicode character so +that any UTF-8 input is representable with no UNK token. Every failure mode of that mapping - the wrong +offset for a byte, a merge applied in the wrong order, a pre-tokenizer split that drops a character - still +produces plausible token ids. `decode(encode(s)) == s` is the check that sees them, and it is exact because +the byte layer is lossless. It is asserted over a corpus chosen to hit the boundaries: multi-byte UTF-8, +emoji (4-byte), combining marks, whitespace runs, and C0 control bytes. +""" +from __future__ import annotations + +import json +import pathlib +import sys + +import regex + +# ------------------------------------------------------------------ byte <-> unicode (GPT-2 byte-level BPE) +def bytes_to_unicode() -> dict[int, str]: + """The GPT-2 byte encoder: 256 bytes -> 256 printable characters, reversibly. + + Bytes 33..126, 161..172 and 174..255 map to themselves; the remaining 68 (space, newline, the C0 + controls and the high range that would be invisible) are shifted into 256+n so that no byte is + unprintable. The shift is the whole trick and getting its ORDER wrong is invisible in the output ids. + """ + bs = (list(range(0x21, 0x7F)) + list(range(0xA1, 0xAD)) + list(range(0xAE, 0x100))) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return dict(zip(bs, (chr(c) for c in cs))) + + +BYTE_TO_UNICODE = bytes_to_unicode() +UNICODE_TO_BYTE = {v: k for k, v in BYTE_TO_UNICODE.items()} + +# The `qwen35` pre-tokenizer, transcribed from the ORACLE rather than from the family resemblance: +# `.ref/llama.cpp/src/llama-vocab.cpp` L396, `case LLAMA_VOCAB_PRE_TYPE_QWEN35`. The commented-out line +# above it is the `tokenizer.json` original, and llama.cpp's active version differs from it - it spells the +# contraction classes out instead of using `(?i:...)`, which is behaviourally the same. +# +# THE `\p{M}` IS THE WHOLE POINT OF THIS BEING TRANSCRIBED. The QWEN3 pattern two cases earlier (L389) is +# the same shape with `\p{L}` where this has `[\p{L}\p{M}]` and without `\p{M}` in the punctuation negation. +# Writing the QWEN3 pattern for `qwen35` looks right, round-trips perfectly, and is wrong: a combining mark +# is `\p{M}`, so without it the mark gets swallowed into the following punctuation run and a token like `_j` +# never forms. It cost 3 strings out of 1875 and only `tokenize_oracle_check` could see it. +QWEN35_PATTERN = ( + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" + r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+" + r"|\p{N}" + r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" + r"|\s*[\r\n]+" + r"|\s+(?!\S)" + r"|\s+" +) + + +class Tokenizer: + def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None, + pre: str = "qwen35", special_ids: dict[str, int] | None = None): + self.tokens = tokens + self.pre = pre + self.token_types = token_types + self.special_ids = special_ids or {} + self.ids = {t: i for i, t in enumerate(tokens)} + if len(self.ids) != len(tokens): + raise ValueError("vocabulary has duplicate tokens: %d entries, %d unique" + % (len(tokens), len(self.ids))) + # Merge rules as (left, right) -> rank. A merge list that is not a total order over its pairs, or one + # naming a token that is not in the vocabulary, would make BPE silently produce different ids than the + # model was trained with, so both are checked here rather than discovered as a bad answer later. + self.ranks: dict[tuple[str, str], int] = {} + for i, m in enumerate(merges): + parts = m.split(" ") + if len(parts) != 2: + raise ValueError("merge %d is not a pair: %r" % (i, m)) + if parts[0] not in self.ids or parts[1] not in self.ids: + raise ValueError("merge %d names a token outside the vocabulary: %r" % (i, m)) + self.ranks[(parts[0], parts[1])] = i + self._re = regex.compile(QWEN35_PATTERN) + + # The literals matched directly instead of being run through BPE. GGUF token types: 3 = CONTROL, + # 4 = USER_DEFINED. The two classes behave DIFFERENTLY and llama.cpp's own tokenizer settled which: + # + # * type 4 (USER_DEFINED: ``, ``, ``, ...) is matched ALWAYS, + # with or without parse_special. + # * type 3 (CONTROL: `<|im_start|>`, `<|im_end|>`, `<|endoftext|>`, ...) is matched ONLY when + # parse_special is set. + # + # Measured, not assumed: with parse_special=False the oracle still emitted `` as one + # token and mine emitted four, and the three disagreements were exactly the type-4 cases while every + # type-3 case agreed. Treating both classes alike costs 3 strings in 1229 and silently changes a chat + # prompt, because `<|im_end|>` decomposed into ordinary pieces is not the token the model expects. + self.special_tokens: dict[str, int] = {} + if token_types: + for i, ty in enumerate(token_types): + if ty in (3, 4): + self.special_tokens[tokens[i]] = i + always = [t for t, i in self.special_tokens.items() if token_types and token_types[i] == 4] + # Longest literal first, or `<|im_end|>` could match a shorter prefix of itself. `regex.escape` so a + # token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally. + self._always_re = self._alt(always) + self._special_re = self._alt(list(self.special_tokens)) + + @staticmethod + def _alt(literals: list[str]): + if not literals: + return None + return regex.compile("|".join(regex.escape(s) for s in sorted(literals, key=len, reverse=True))) + + # -------------------------------------------------------------- constructors + @classmethod + def from_gguf(cls, path) -> "Tokenizer": + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + from gguf_reader import GGUFFile + md = GGUFFile(pathlib.Path(path)).metadata + need = ["tokenizer.ggml.tokens", "tokenizer.ggml.merges"] + missing = [k for k in need if k not in md] + if missing: + raise ValueError("GGUF is missing %s; it does not carry a tokenizer" % ", ".join(missing)) + model = md.get("tokenizer.ggml.model") + if model != "gpt2": + raise ValueError("expected a byte-level BPE tokenizer (model 'gpt2'), got %r" % model) + special = {k: int(md[k]) for k in md + if k.startswith("tokenizer.ggml.") and k.endswith("_token_id")} + return cls(list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.merges"]), + list(md.get("tokenizer.ggml.token_type") or []) or None, + md.get("tokenizer.ggml.pre", "qwen35"), special) + + # -------------------------------------------------------------- the algorithm + def _bpe(self, word: str) -> list[str]: + """Merge `word` (already byte-mapped) by LOWEST RANK first, repeatedly - not left to right. + + Applying merges in list order rather than rank order is the classic BPE bug: it produces a different + segmentation and a plausible token count. + + A word longer than HEAP_MIN symbols (a long CJK run, a minified blob: one pre-token piece of thousands of + bytes) goes to _bpe_heap, which applies the same merges in the same order without rescanning every pair + after each merge (#268: that rescan is O(n^2) and took seconds on an 8K-character CJK run). + """ + if len(word) > self.HEAP_MIN: + return self._bpe_heap(word) + parts = list(word) + while len(parts) > 1: + best, best_rank = None, None + for i in range(len(parts) - 1): + r = self.ranks.get((parts[i], parts[i + 1])) + if r is not None and (best_rank is None or r < best_rank): + best, best_rank = i, r + if best is None: + break + parts[best:best + 2] = [parts[best] + parts[best + 1]] + return parts + + HEAP_MIN = 64 # words up to this many symbols keep the scan above, unchanged + + def _bpe_heap(self, word: str) -> list[str]: + """_bpe's result in O(n log n): the symbols as a linked list, every adjacent pair with a rank in a heap + keyed (rank, position). Popping the lowest rank and then the lowest position is exactly the order the + scan picks (its strict `<` keeps the leftmost of equal ranks), and a symbol's position is where it starts + in the word, which only its left neighbour's merge can change - so a popped pair whose two symbols are + no longer the ones it was pushed with is stale and skipped.""" + import heapq + parts = list(word) + n = len(parts) + nxt = list(range(1, n)) + [-1] + prv = list(range(-1, n - 1)) + ranks = self.ranks + heap = [] + for i in range(n - 1): + r = ranks.get((parts[i], parts[i + 1])) + if r is not None: + heap.append((r, i, parts[i], parts[i + 1])) + heapq.heapify(heap) + while heap: + r, i, left, right = heapq.heappop(heap) + j = nxt[i] + if parts[i] != left or j < 0 or parts[j] != right: + continue # stale: one of its symbols has merged since + parts[i] = left + right + parts[j] = None # j is gone: i takes its place in the list + k = nxt[j] + nxt[i] = k + if k >= 0: + prv[k] = i + r2 = ranks.get((parts[i], parts[k])) + if r2 is not None: + heapq.heappush(heap, (r2, i, parts[i], parts[k])) + p = prv[i] + if p >= 0: + r2 = ranks.get((parts[p], parts[i])) + if r2 is not None: + heapq.heappush(heap, (r2, p, parts[p], parts[i])) + return [s for s in parts if s is not None] + + def _encode_plain(self, text: str) -> list[int]: + out: list[int] = [] + for piece in self._re.findall(text): + mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) + for tok in self._bpe(mapped): + i = self.ids.get(tok) + if i is None: + raise KeyError("BPE produced a token outside the vocabulary: %r" % tok) + out.append(i) + return out + + def _encode_matching(self, text: str, pat) -> list[int]: + """Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest. + + The split happens on the RAW text, before the byte mapping, because a special token's string is a + literal to match rather than bytes to decompose. Everything between the matches is tokenized + normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. + """ + if pat is None: + return self._encode_plain(text) + out: list[int] = [] + pos = 0 + for m in pat.finditer(text): + if m.start() > pos: + out.extend(self._encode_plain(text[pos:m.start()])) + out.append(self.special_tokens[m.group(0)]) + pos = m.end() + if pos < len(text): + out.extend(self._encode_plain(text[pos:])) + return out + + def encode(self, text: str, parse_special: bool = False) -> list[int]: + """Tokenize `text`. + + `parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4 + USER_DEFINED ones such as `` are matched either way. See the note in `__init__`. + """ + return self._encode_matching(text, self._special_re if parse_special else self._always_re) + + def token_bytes(self, i: int) -> bytes: + """The raw bytes of one token (a multi-byte character can be split across tokens).""" + cache = self.__dict__.setdefault("_bytes_cache", {}) + b = cache.get(i) + if b is None: + if i < 0 or i >= len(self.tokens): + raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens))) + raw = bytearray() + for ch in self.tokens[i]: + v = UNICODE_TO_BYTE.get(ch) + if v is None: + raise KeyError("token %d contains a character outside the byte alphabet: %r" % (i, ch)) + raw.append(v) + b = cache[i] = bytes(raw) + return b + + def decode(self, ids: list[int], errors: str = "replace") -> str: + return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors=errors) + + +# ------------------------------------------------------------------ the pack's tokenizer/ directory +def extract(gguf_path, out_dir) -> dict: + """Write the tokenizer into `/tokenizer/` so the engine never opens the weight shards for it.""" + out = pathlib.Path(out_dir) / "tokenizer" + out.mkdir(parents=True, exist_ok=True) + tk = Tokenizer.from_gguf(gguf_path) + cfg = { + "model": "gpt2", + "pre": tk.pre, + "vocab_size": len(tk.tokens), + "n_merges": len(tk.ranks), + "special_ids": tk.special_ids, + "add_bos_token": False, + # The pattern is SHIPPED, not recomputed by the reader: it is transcribed from llama.cpp for the + # declared `pre` type, and a C++ port that re-derived it would be free to get `\p{M}` wrong again. + "pre_pattern": QWEN35_PATTERN, + "pre_pattern_source": ".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)", + } + (out / "vocab.json").write_text(json.dumps(tk.ids, ensure_ascii=False), encoding="utf-8") + (out / "merges.txt").write_text("\n".join("%s %s" % k for k, _ in + sorted(tk.ranks.items(), key=lambda kv: kv[1])), encoding="utf-8") + (out / "token_type.json").write_text(json.dumps(tk.token_types), encoding="utf-8") + (out / "tokenizer.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=1), encoding="utf-8") + # the model's own chat template: fine-tunes change it (Swift 1.5 differs from Qwen3.8-Flash-Next's) + sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + from gguf_reader import GGUFFile + tpl = GGUFFile(pathlib.Path(gguf_path)).metadata.get("tokenizer.chat_template") + if tpl: + (out / "chat_template.jinja").write_text(tpl, encoding="utf-8", newline="\n") + return cfg + + +def main() -> int: + import argparse + ap = argparse.ArgumentParser() + ap.add_argument("--gguf", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--check", action="store_true", help="round-trip a corpus and report") + args = ap.parse_args() + cfg = extract(args.gguf, args.out) + print("tokenizer/: vocab %d, merges %d, pre %s, specials %s" + % (cfg["vocab_size"], cfg["n_merges"], cfg["pre"], cfg["special_ids"])) + if args.check: + tk = Tokenizer.from_gguf(args.gguf) + corpus = ["", "Hello, world!", " leading and trailing ", "a\n\n\nb", + "def f(x):\n\treturn x # comment\n", "\u4f60\u597d\uff0c\u4e16\u754c", "\u0645\u0631\u062d\u0628\u0627", + "\U0001f600\U0001f680\U0001f1fa\U0001f1f8", "e\u0301\u0301 combining", "\x00\x01\x7f control", + "\u00a0non-breaking\u00a0space", "1234567890", "MixedCASE_and-dashes", "\r\n\r\n", "\u2028\u2029", + "x" * 5000] + bad = 0 + for s in corpus: + ids = tk.encode(s) + back = tk.decode(ids) + if back != s: + print(" *** ROUND TRIP FAILED *** %r -> %d ids -> %r" % (s[:40], len(ids), back[:40])) + bad += 1 + print("round trip: %d strings, %d failed" % (len(corpus), bad)) + return 0 if bad == 0 else 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/engine/strata/tools/test_calibrate.py b/engine/strata/tools/test_calibrate.py new file mode 100644 index 00000000..a03286c5 --- /dev/null +++ b/engine/strata/tools/test_calibrate.py @@ -0,0 +1,234 @@ +"""Tests for tools/calibrate.py and setup's use of it, without a GPU: a stand-in engine whose decode speed is a +function of the settings it runs with. + + python -m unittest tools.test_calibrate +""" +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import calibrate as CAL # noqa: E402 + + +class FakeEngine: + """Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`.""" + + def __init__(self, args, speed, info_workers=6, starts=None): + self.args = list(args) + w = CAL.arg_value(args, "--pool-workers") + self.workers = int(w) if w else info_workers + self.info = {"pool_workers": info_workers, "pcie_frac": 0.55, "spec_min_p": float(CAL.arg_value(args, "--spec-min-p") or 0)} + self.speed = speed + self.last = {} + self.proc = None + if starts is not None: + starts.append(list(args)) + + def generate(self, ids, max_new, sampling, cancel): + tune = sampling.get("strata_tune") or {} + rate = self.speed(tune.get("pcie_frac", 0.55), tune.get("spec_min_p", self.info["spec_min_p"]), self.workers) + for _ in range(max_new): + yield 1 + self.last = {"generated": max_new, "decode_ms": max_new / rate * 1000.0} + + +BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8192"] + + +class Calibrate(unittest.TestCase): + def run_with(self, speed, workers=6, base=BASE): + starts = [] + res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts), say=lambda *_: None) + return res, starts + + def test_defaults_kept_when_flat(self): + res, _ = self.run_with(lambda f, p, w: 50.0) + self.assertEqual(res["settings"], {}) + + def test_small_gain_is_noise(self): + # 2% better at pcie 0.35: below MIN_GAIN, so the default stays + res, _ = self.run_with(lambda f, p, w: 51.0 if abs(f - 0.35) < 1e-6 else 50.0) + self.assertEqual(res["settings"], {}) + + def test_finds_pcie_and_min_p(self): + def speed(f, p, w): + return 50.0 + (10.0 if abs(f - 0.2) < 1e-6 else 0.0) + (5.0 if abs(p - 0.7) < 1e-6 else 0.0) + res, _ = self.run_with(speed) + self.assertEqual(res["settings"].get("--pcie-frac"), "0.20") + self.assertEqual(res["settings"].get("--spec-min-p"), "0.70") + self.assertNotIn("--pool-workers", res["settings"]) + + def test_fewer_workers(self): + # a hybrid CPU: half the workers is 20% faster + res, starts = self.run_with(lambda f, p, w: 60.0 if w == 3 else 50.0, workers=6) + self.assertEqual(res["settings"].get("--pool-workers"), "3") + self.assertEqual(len(starts), 1 + len(CAL.worker_candidates(6))) # one start per worker count, plus the sweep + self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") # measured against the product default + + def test_old_calibration_is_the_baseline_reset(self): + # a config tuned earlier: the measurement starts from the product defaults, not from those values + base = CAL.apply(BASE, {"--pcie-frac": "0.20", "--pool-workers": "3", "--spec-min-p": "0.70"}) + _, starts = self.run_with(lambda f, p, w: 50.0, base=base) + self.assertIsNone(CAL.arg_value(starts[0], "--pcie-frac")) + self.assertIsNone(CAL.arg_value(starts[0], "--pool-workers")) + self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") + + def test_apply(self): + a = CAL.apply(BASE, {"--pcie-frac": "0.35", "--pool-workers": "4"}) + self.assertEqual(CAL.arg_value(a, "--pcie-frac"), "0.35") + self.assertEqual(CAL.arg_value(a, "--pool-workers"), "4") + self.assertEqual(CAL.arg_value(a, "--spec-min-p"), "0.5") + b = CAL.apply(a, {}) # back to the defaults + self.assertIsNone(CAL.arg_value(b, "--pcie-frac")) + self.assertIsNone(CAL.arg_value(b, "--pool-workers")) + self.assertEqual(b.count("--spec-min-p"), 1) + + def test_engine_args_are_the_servers(self): + # #447: a "gpu" list is a layer split only with two or more cards; "0,2" is one too; split_skip_if_fits counts + helper = {"args": BASE + ["--expert-cache-device1", "1800"], "gpu": [0], "env": {"CUDA_VISIBLE_DEVICES": "0,1"}} + self.assertEqual(CAL.engine_args(helper), helper["args"]) # one stage + a helper card: no split + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": 1}), BASE) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 2]}), BASE + ["--layer-split", "auto"]) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": "0,2", "layer_split": "18"}), + BASE + ["--layer-split", "18"]) + self.assertEqual(CAL.engine_args({"args": BASE, "gpu": [0, 1], "split_skip_if_fits": True}), + BASE + ["--layer-split", "auto", "--split-skip-if-fits"]) + own = BASE + ["--layer-split", ""] # the config's own value wins + self.assertEqual(CAL.engine_args({"args": own, "gpu": [0, 1]}), own) + + def test_run_measures_with_the_servers_args(self): + with tempfile.TemporaryDirectory() as d: + tok = Path(d) + (tok / "vocab.json").write_text(json.dumps({"a": 0, "b": 1})) + (tok / "merges.txt").write_text("") + (tok / "token_type.json").write_text(json.dumps([1, 1])) + seen = [] + saved = CAL.measure + CAL.measure = lambda args, ids_list, start_engine, say=print: seen.append(args) or {} + fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()}) + try: + with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}): + CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0]}, start_engine=lambda a: None) + finally: + CAL.measure = saved + self.assertEqual(seen, [BASE]) + + def test_engine_error(self): + with tempfile.TemporaryDirectory() as d: + log = Path(d) / "strata-x.log" + log.write_text("strata generate: an old error\n", encoding="utf-8") + since = log.stat().st_size + with open(log, "a", encoding="utf-8") as f: + f.write("loading ...\nstrata generate: --expert-cache-remote with a layer split needs a GPU that runs " + "no stage (2 visible, 2 used by the split)\n\n") + self.assertEqual(CAL.engine_error(str(log), since), "strata generate: --expert-cache-remote with a layer " + "split needs a GPU that runs no stage (2 visible, 2 used by the split)") + with open(log, "a", encoding="utf-8") as f: + f.write("Segmentation fault\n") + self.assertIn("--expert-cache-remote", CAL.engine_error(str(log), since)) # the engine's own line first + self.assertEqual(CAL.engine_error(str(log), log.stat().st_size), None) # nothing new since + self.assertIsNone(CAL.engine_error(None)) + self.assertIsNone(CAL.engine_error(str(Path(d) / "missing.log"))) + + def test_worker_candidates(self): + self.assertEqual(CAL.worker_candidates(6), [6, 4, 3]) + self.assertEqual(CAL.worker_candidates(23), [23, 15, 12]) + self.assertEqual(CAL.worker_candidates(3), [3, 2]) + self.assertEqual(CAL.worker_candidates(1), [1]) + + def test_pick(self): + self.assertEqual(CAL.pick({"a": [50, 51, 49], "b": [53, 52, 60]}, "a"), "b") + self.assertEqual(CAL.pick({"a": [50, 51, 49], "b": [51, 51.5, 51]}, "a"), "a") + self.assertEqual(CAL.pick({}, "a"), "a") + + +class SetupIntegration(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.old = {k: os.environ.get(k) for k in ("APPDATA", "XDG_CONFIG_HOME")} + os.environ["APPDATA"] = self.tmp.name + os.environ["XDG_CONFIG_HOME"] = self.tmp.name + import setup as S + self.S = S + self.saved = (S.gpu_info, S.cpu_info, S.ram_gb, CAL.run) + S.gpu_info = lambda pick=None: {"name": "RTX Test", "vram_gb": 12.0, "arch": "120", "count": 1, "index": 0} + S.cpu_info = lambda: ("Test CPU", True, True) + S.ram_gb = lambda: 64.0 + + def tearDown(self): + self.S.gpu_info, self.S.cpu_info, self.S.ram_gb, CAL.run = self.saved + for k, v in self.old.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + self.tmp.cleanup() + + def test_calibrate_config_writes_and_remembers(self): + cfg_path = Path(self.tmp.name) / "strata-q2_0.json" + cfg = {"exe": "x", "args": list(BASE), "model_name": "qwen3.8-flash-next-q2_0"} + cfg_path.write_text(json.dumps(cfg)) + CAL.run = lambda c, say=print, start_engine=None: {"settings": {"--pcie-frac": "0.20"}, "report": {"tok_s": 61.2}} + self.assertTrue(self.S.calibrate_config(cfg_path)) + written = json.loads(cfg_path.read_text()) + self.assertEqual(CAL.arg_value(written["args"], "--pcie-frac"), "0.20") + saved = self.S.saved_calibration(written) + self.assertEqual(saved["settings"], {"--pcie-frac": "0.20"}) + # another model on the same PC has no calibration yet + self.assertIsNone(self.S.saved_calibration({**written, "model_name": "swift-iq2_xs"})) + # another context size is another key (its KV cache changes the expert cache) + other = dict(written, args=CAL.with_arg(written["args"], "--max-context", "131072")) + self.assertIsNone(self.S.saved_calibration(other)) + + def test_failed_calibration_keeps_defaults(self): + cfg_path = Path(self.tmp.name) / "strata-q2_0.json" + cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m"})) + + def boom(*a, **k): + raise RuntimeError("the engine exited before it was ready") + CAL.run = boom + self.assertFalse(self.S.calibrate_config(cfg_path)) + self.assertEqual(json.loads(cfg_path.read_text())["args"], BASE) + self.assertIsNone(self.S.saved_calibration({"args": BASE, "model_name": "m"})) + + def test_failed_calibration_says_the_engines_reason(self): + # #447: the engine's last error line is printed, and the --calibrate run repeats the failure before it starts + import contextlib + import io + log = Path(self.tmp.name) / "strata-q2_0.log" + log.write_text("strata generate: an error of an earlier start\n", encoding="utf-8") + cfg_path = Path(self.tmp.name) / "strata-q2_0.json" + cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m", "log": str(log)})) + + def boom(*a, **k): + with open(log, "a", encoding="utf-8") as f: + f.write("strata generate: --expert-cache-remote with a layer split needs a GPU that runs no stage\n") + raise RuntimeError(f"the engine exited before it was ready (see {log})") + CAL.run = boom + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertFalse(self.S.calibrate_config(cfg_path)) + self.assertIn("the engine said: strata generate: --expert-cache-remote with a layer split", out.getvalue()) + self.assertNotIn("an earlier start", out.getvalue()) + out = io.StringIO() + with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \ + mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \ + mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \ + mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \ + contextlib.redirect_stdout(out): + self.assertEqual(self.S.main(), 0) + self.assertIn("this PC is NOT tuned: the tuning failed (the reason is above); the model keeps the default " + "settings", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_disabled.py b/engine/strata/tools/test_conversation_cache_disabled.py new file mode 100644 index 00000000..d389ac9f --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_disabled.py @@ -0,0 +1,104 @@ +"""The upstream comparison must reject mismatches and incomplete evidence.""" +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_disabled import NAMES, SETTINGS, STATE_KEYS, common_args, state_hashes, verify + + +def fixture(): + requests = [dict(name=n, ids=[1, 2], max_new=16, expected='4' if n == 'short' else None) for n in NAMES] + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + baseline = dict(name='upstream', args=['--kv', 'int8'], info={key: 1 for key in SETTINGS}, + request_digest=digest, cache_events=[], records=[]) + for name in NAMES: + baseline['records'].append(dict(name=name, ids=[4], text='4', finish='stop', prompt_tokens=2, + reused=2 if name in ('A-live', 'A-checkpoint') else 0, + state={key: 'abc' for key in STATE_KEYS})) + candidate = copy.deepcopy(baseline) + candidate['name'] = 'candidate-1' + candidate['info']['conversation_cache_mib'] = 0 + candidate['info']['conversation_disk_mib'] = 0 + return dict(arms=[baseline, candidate], requests=requests, request_digest=digest) + + +class DisabledCacheGateTest(unittest.TestCase): + def test_reference_fixture(self): + verify(fixture()) + + def test_upstream_hash_schema(self): + line = 'strata serve: STATE_HASH L=2 gdn=ab ple=cd tail=ef pooled=12 kv=34 mtp=56 stale=78 ple_prev=1,2' + self.assertEqual(set(state_hashes(line)[0]), set(STATE_KEYS)) + self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99')) + # the candidate's pooled= is the upstream extent; pooled_full= (with the spare row) is not compared + self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99 pooled_full=ff', candidate=True)) + self.assertNotEqual(state_hashes(line), state_hashes(line.replace('pooled=12', 'pooled=ff') + + ' pooled_full=12', candidate=True)) + with self.assertRaises(AssertionError): + state_hashes(line, candidate=True) + with self.assertRaises(AssertionError): + state_hashes(line.replace('kv=34 ', '')) + + def test_rejects_bad_evidence(self): + mutations = [ + lambda r: r['arms'].pop(), + lambda r: r['requests'].pop(), + lambda r: r['requests'][0]['ids'].append(3), + lambda r: r['arms'][1]['args'].append('--different'), + lambda r: r['arms'][1].update(request_digest='different'), + lambda r: r['arms'][1]['records'].pop(), + lambda r: r['arms'][1]['info'].update(expert_slots=2), + lambda r: r['arms'][1]['info'].pop('kv'), + lambda r: r['arms'][1]['info'].update(conversation_cache_mib=8192), + lambda r: r['arms'][1]['info'].pop('conversation_cache_mib'), + lambda r: r['arms'][1]['info'].update(conversation_disk_mib=16384), + lambda r: r['arms'][1]['cache_events'].append('disk cache: spilled'), + lambda r: r['arms'][1]['records'][0].update(ids=[]), + lambda r: r['arms'][1]['records'][0].update(ids=[5]), + lambda r: r['arms'][1]['records'][0].update(finish='disconnect'), + lambda r: r['arms'][1]['records'][0].update(prompt_tokens=1), + lambda r: r['arms'][1]['records'][0]['state'].pop('gdn'), + lambda r: r['arms'][1]['records'][0]['state'].update(kv='bad'), + lambda r: r['arms'][1]['records'][0].update(reused=1), + lambda r: [a['records'][0].update(text='5') for a in r['arms']], + lambda r: [a['records'][2].update(reused=0) for a in r['arms']], + lambda r: [a['records'][5].update(reused=2) for a in r['arms']], + ] + for mutation in mutations: + with self.subTest(mutation=mutations.index(mutation)): + result = fixture() + mutation(result) + with self.assertRaises(AssertionError): + verify(result) + + def test_optimized_python_still_rejects(self): + code = ('from tools.test_conversation_cache_disabled import fixture, verify; ' + 'r=fixture(); r["arms"][1]["records"][0]["ids"]=[5]; verify(r)') + p = subprocess.run([sys.executable, '-O', '-c', code], capture_output=True, text=True) + self.assertNotEqual(p.returncode, 0) + self.assertIn('output differs', p.stderr) + + def test_cache_options_omitted_from_shared_arguments(self): + cfg = {'args': ['--pack', '/model', '--conversation-cache-mib', '8192', + '--conversation-cache-disk', '/cache', '--kv', 'int8']} + args = common_args(cfg, 4) + self.assertEqual(args[:4], ['--pack', '/model', '--kv', 'int8']) + self.assertFalse(any(x.startswith('--conversation-cache-') for x in args)) + + def test_dry_run_does_not_load_or_create_output(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / 'absent' + p = subprocess.run([sys.executable, 'tools/conversation_cache_disabled.py', '--config', '/absent', + '--upstream', '/absent', '--candidate', '/absent', '--output', str(out)], + capture_output=True, text=True) + self.assertEqual(p.returncode, 0, p.stderr) + self.assertFalse(out.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_growth.py b/engine/strata/tools/test_conversation_cache_growth.py new file mode 100644 index 00000000..36423449 --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_growth.py @@ -0,0 +1,79 @@ +"""Negative controls for the incremental capture model gate.""" +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_growth import NAMES, SECRET, SETTINGS, STATE_KEYS, verify + + +def fixture(): + lengths = [8, 2, 12, 2, 16, 2, 20, 2, 12, 2, 15, 2] + requests = [dict(name=name, ids=[1]*n, max_new=16, expected=name.startswith('A-')) + for name, n in zip(NAMES, lengths)] + digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest() + full = dict(name='full', exe_sha256='fixed', args=['--conversation-cache-mib','1'], request_digest=digest, + info={key: 1 for key in SETTINGS}, draft_verifications=4, + parks=[dict(bytes=100,snapshot_bytes=100,reused_kv_bytes=0) for _ in range(3)], + records=[dict(name=name, ids=[1], text=SECRET, finish='stop', reused=1, + prompt_tokens=n, state={k:'abc' for k in STATE_KEYS}) for name,n in zip(NAMES,lengths)]) + full['info'].update(conversation_cache_mib=1,conversation_cache_slots=4) + incremental = copy.deepcopy(full) + incremental['name'] = 'incremental' + for p in incremental['parks']: + p['reused_kv_bytes'] = 50 + return dict(arms=[full,incremental],requests=requests,request_digest=digest,cache_mib=1) + + +class GrowthGate(unittest.TestCase): + def test_complete_evidence(self): + verify(fixture()) + + def test_incomplete_or_incorrect_evidence_fails(self): + mutations = [ + lambda r:r['requests'].pop(), + lambda r:r['requests'][0]['ids'].append(2), + lambda r:r['arms'][1].update(exe_sha256='different'), + lambda r:r.update(cache_mib=2), + lambda r:r['arms'][1]['records'].pop(), + lambda r:r['arms'][1]['records'][2].update(ids=[2]), + lambda r:r['arms'][1]['records'][2].update(text='wrong'), + lambda r:r['arms'][1]['records'][2].update(reused=0), + lambda r:r['arms'][1]['records'][2].update(finish='cancel'), + lambda r:r['arms'][1]['records'][2]['state'].pop('kv'), + lambda r:r['arms'][1]['info'].update(expert_slots=2), + lambda r:r['arms'][1].update(draft_verifications=0), + lambda r:r['arms'][0]['parks'][0].update(reused_kv_bytes=1), + lambda r:[p.update(reused_kv_bytes=0) for p in r['arms'][1]['parks']], + lambda r:r['arms'][1]['parks'][0].update(bytes=2*1024*1024), + lambda r:r['arms'][1]['parks'][0].update(reused_kv_bytes=101), + ] + for i, mutate in enumerate(mutations): + with self.subTest(case=i): + result = fixture() + mutate(result) + with self.assertRaises(AssertionError): + verify(result) + + def test_optimized_python_rejects_missing_reuse(self): + code = ('from tools.test_conversation_cache_growth import fixture,verify; ' + 'r=fixture(); [p.update(reused_kv_bytes=0) for p in r["arms"][1]["parks"]]; verify(r)') + run = subprocess.run([sys.executable,'-O','-c',code],capture_output=True,text=True) + self.assertNotEqual(run.returncode,0) + self.assertIn('did not reuse KV bytes',run.stderr) + + def test_dry_run_leaves_server_and_output_alone(self): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp)/'absent' + run = subprocess.run([sys.executable,'tools/conversation_cache_growth.py','--config','/absent', + '--engine','/absent','--output',str(output)],capture_output=True,text=True) + self.assertEqual(run.returncode,0,run.stderr) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_http_smoke.py b/engine/strata/tools/test_conversation_cache_http_smoke.py new file mode 100644 index 00000000..fd0a79d2 --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_http_smoke.py @@ -0,0 +1,71 @@ +"""Offline tests of HTTP smoke-test orchestration and safety defaults.""" +from collections import OrderedDict +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import Mock + +from tools.conversation_cache_http_smoke import run + + +class FakeClient: + def __init__(self): + self.history = [] + self.cache = OrderedDict() + + def metrics(self): + return {'live': {'state': 'idle', 'queued': 0}, + 'engine': {'model': 'fake', 'conversation_cache_slots': 4, 'conversation_cache_mib': 8192}, + 'requests': self.history[::-1]} + + def request(self, model, content, stream=False, count=8): + reused = 100 if content in self.cache else 0 + self.cache.pop(content, None) + self.cache[content] = True + while len(self.cache) > 5: # active plus four parked entries + self.cache.popitem(last=False) + self.history.append({'time': len(self.history) + 1, 'reused': reused, 'output_tokens': 5, + 'finish': 'disconnect' if stream else 'stop'}) + data = {'choices': [{'delta': {'content': '1'}}]} if stream else { + 'choices': [{'message': {'role': 'assistant', 'content': 'blue'}}]} + return io.BytesIO((('data: ' if stream else '') + json.dumps(data) + '\n').encode()) + + +class HttpSmoke(unittest.TestCase): + def test_orchestration_offline(self): + result = run(FakeClient()) + self.assertEqual(len(result['records']), 12) + self.assertEqual(result['records'][-1]['name'], 'cancelled-A-restored') + self.assertGreater(result['records'][-1]['reused'], 0) + + def test_busy_server_receives_no_requests(self): + client = Mock() + client.metrics.return_value = {'live': {'state': 'generating', 'queued': 0}} + with self.assertRaisesRegex(RuntimeError, 'busy'): + run(client) + client.request.assert_not_called() + + def test_disabled_cache_receives_no_requests(self): + client = Mock() + client.metrics.return_value = {'live': {'state': 'idle', 'queued': 0}, 'engine': {}} + with self.assertRaisesRegex(RuntimeError, 'enabled cache'): + run(client) + client.request.assert_not_called() + + def test_dry_run_does_not_connect_or_create_output(self): + with tempfile.TemporaryDirectory(prefix='strata-http-dry-') as directory: + output = Path(directory) / 'not-created.json' + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_http_smoke.py')), + '--url', 'invalid://not-a-server', '--output', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No network traffic', result.stdout) + self.assertFalse(output.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_isolation.py b/engine/strata/tools/test_conversation_cache_isolation.py new file mode 100644 index 00000000..7205d4d4 --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_isolation.py @@ -0,0 +1,82 @@ +"""Offline checks for image/steering isolation evidence and generated fixtures.""" +import copy +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_isolation import STATE_KEYS, fixtures, verify +from tools.gguf_reader import GGUFFile + + +def evidence(scenario): + image = scenario == 'image' + names = (['image-A', 'text-B', 'image-A-return', 'image-B', 'image-A-again', 'grid-changed', 'image-A-final'] + if image else ['off', 'on', 'text-B', 'off-return', 'on-return', 'off-again']) + hits = [2, 4, 6] if image else [3, 4, 5] + records = [{'name': name, 'ids': [123], 'finish': 'length', 'reused': 0, + 'state': {k: str(i) for k in STATE_KEYS}} for i, name in enumerate(names)] + candidate = copy.deepcopy(records) + for i in hits: + candidate[i]['reused'] = 100 + info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=262144, + spec=2, mtp_max=1, lookup=0, cvec=0 if image else 'add:1-47') + return {'baseline': records, 'candidate': candidate, + 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}} + + +class IsolationGate(unittest.TestCase): + def test_complete_evidence(self): + for scenario in ('image', 'add', 'project'): + verify(evidence(scenario), scenario) + + def test_incomplete_or_wrong_evidence_rejected(self): + for scenario in ('image', 'add'): + cases = { + 'incompatible reuse': lambda d: d['candidate'][1].update(reused=5), + 'no parked hit': lambda d: d['candidate'][-1].update(reused=0), + 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'), + 'missing state': lambda d: d['candidate'][-1]['state'].clear(), + 'empty output': lambda d: d['candidate'][-1]['ids'].clear(), + 'missing request': lambda d: d['candidate'].pop(), + 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=1), + } + for name, mutate in cases.items(): + with self.subTest(scenario=scenario, case=name): + data = evidence(scenario) + mutate(data) + with self.assertRaises(AssertionError): + verify(data, scenario) + + def test_generated_fixtures(self): + with tempfile.TemporaryDirectory(prefix='strata-isolation-') as directory: + p = Path(directory) + fixtures(p, 2560) + cv = GGUFFile(p / 'control.gguf') + self.assertEqual(cv.metadata['general.architecture'], 'controlvector') + self.assertEqual([t.name for t in cv.tensors], ['direction.1', 'direction.20']) + self.assertTrue(all(t.elements == 2560 for t in cv.tensors)) + a, b, grid = [(p / (name + '.sve')).read_bytes() for name in ('image-a', 'image-b', 'image-grid')] + self.assertEqual(struct.unpack('<5i', a[:20]), (0x31455653, 4, 2, 2, 2560)) + self.assertEqual(len(a), 20 + 4 * 2560 * 4) + self.assertEqual(a[:20], b[:20]) + self.assertNotEqual(a[20:], b[20:]) + self.assertNotEqual(a[:20], grid[:20]) + self.assertEqual(a[20:], grid[20:]) + + def test_dry_run_does_not_read_missing_config(self): + with tempfile.TemporaryDirectory(prefix='strata-isolation-dry-') as directory: + p = Path(directory) + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_isolation.py')), + '--config', str(p / 'missing.json'), '--engine', str(p / 'missing'), + '--output', str(p / 'not-created'), '--scenario', 'image'], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('no model loaded', result.stdout) + self.assertFalse((p / 'not-created').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_parity.py b/engine/strata/tools/test_conversation_cache_parity.py new file mode 100644 index 00000000..3f950ebd --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_parity.py @@ -0,0 +1,170 @@ +"""CPU-only checks that the model-level gate cannot pass with incomplete evidence.""" +import copy +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_parity import STATE_KEYS, engine_args, pressure_budget_hint, verify_admission, verify_exchange, verify_pressure, verify_results + + +def fixture(): + state = {k: '1234' for k in STATE_KEYS} + def record(name): + return {'name': name, 'ids': [123], 'finish': 'length', 'state': dict(state), 'reused': 100} + info = {'expert_slots': 100, 'kv': 'int8', 'kv_resident': 32768, 'context': 65536, + 'spec': 1, 'mtp_max': 0, 'lookup': 0, 'cvec': '0'} + return {'baseline': [record('A'), record('A+')], + 'candidate': [record(n) for n in ('A', 'B', 'A+', 'B-again', 'A+-checkpoint')], + 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}} + + +class ParityGate(unittest.TestCase): + def test_native_iq_single_token_arguments(self): + cfg = {'args': ['--spec', '4', '--mtp-max-t', '4']} + args = engine_args(cfg, 400, 1) + values = {args[i]: args[i + 1] for i in range(0, len(args), 2)} + self.assertEqual(values['--spec'], '2') + self.assertEqual(values['--mtp-max-t'], '1') + self.assertEqual(values['--suffix-draft'], '0') + self.assertEqual(values['--adapt-swaps'], '0') + self.assertEqual(values['--conversation-cache-mib'], '400') + self.assertEqual(cfg['args'], ['--spec', '4', '--mtp-max-t', '4']) + + def test_complete_evidence(self): + verify_results(fixture(), 100, 1) + + def test_incomplete_or_different_evidence_fails(self): + cases = { + 'missing state': lambda d: d['candidate'][2]['state'].clear(), + 'missing spare key': lambda d: d['candidate'][2]['state'].pop('dead'), + 'empty output': lambda d: d['candidate'][2]['ids'].clear(), + 'missing request': lambda d: d['candidate'].pop(), + 'state differs': lambda d: d['candidate'][2]['state'].update(gdn='ffff'), + 'output differs': lambda d: d['candidate'][2].update(ids=[456]), + 'live not restored': lambda d: d['candidate'][2].update(reused=0), + 'checkpoint not restored': lambda d: d['candidate'][4].update(reused=0), + 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=99), + 'cancellation': lambda d: d['candidate'][2].update(finish='cancel'), + 'initial output differs': lambda d: d['candidate'][0].update(ids=[789]), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + data = copy.deepcopy(fixture()) + mutate(data) + with self.assertRaises(AssertionError): + verify_results(data, 100, 1) + + def test_speculative_gate_still_requires_output_parity(self): + data = fixture() + data['candidate'][2]['state']['gdn'] = 'ffff' + verify_results(data, 100, 4) + data['candidate'][2]['ids'] = [456] + with self.assertRaises(AssertionError): + verify_results(data, 100, 4) + + def test_dry_run_does_not_read_config_or_start_engine(self): + with tempfile.TemporaryDirectory(prefix='strata-parity-dry-') as directory: + output = Path(directory) / 'not-created' + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_parity.py')), + '--config', str(Path(directory) / 'missing.json'), + '--engine', str(Path(directory) / 'missing-engine'), '--output', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No model loaded', result.stdout) + self.assertFalse(output.exists()) + + +def pressure_fixture(): + data = fixture() + record = data['baseline'][0] + for key in ('baseline', 'candidate'): + data[key] = [{**copy.deepcopy(record), 'name': name, 'reused': 0} + for name in ('A', 'B', 'C', 'A-again')] + data['engine_info']['candidate'].update(conversation_cache_mib=400, conversation_cache_slots=4) + data['pressure'] = {'skips': 0, 'parks': [ + {'parked': 1, 'bytes': 266000000, 'evictions': n} for n in range(3)]} + return data + + +class PressureGate(unittest.TestCase): + def test_pressure_budget_hint_uses_individual_sizes(self): + data = pressure_fixture() + for park in data['pressure']['parks']: + park['snapshot_bytes'] = 266 * 1024 * 1024 + self.assertIn('--cache-mib 266..531', pressure_budget_hint(data, 600)) + data['candidate'][-1]['reused'] = 100 + with self.assertRaisesRegex(AssertionError, r'Configured --cache-mib 600.*266\.00 MiB.*266\.\.531'): + verify_pressure(data, 600) + + def test_pressure_budget_hint_handles_missing_or_incompatible_sizes(self): + data = pressure_fixture() + self.assertIn('No snapshot sizes', pressure_budget_hint(data, 600)) + for park, size in zip(data['pressure']['parks'], [1, 2, 10]): + park['snapshot_bytes'] = size * 1024 * 1024 + self.assertIn('No whole-MiB budget', pressure_budget_hint(data, 600)) + + def test_physical_memory_admission_evidence(self): + data = pressure_fixture() + data['pressure'] = {'memory_skips': 3, 'skips': 0, 'parks': []} + data['engine_info']['candidate']['conversation_cache_min_free_mib'] = 999999 + verify_admission(data, 400, 999999) + for mutate in ( + lambda d: d['pressure'].update(memory_skips=0, skips=3), + lambda d: d['pressure'].update(memory_skips=2), + lambda d: d['engine_info']['candidate'].update(conversation_cache_min_free_mib=2560), + lambda d: d['candidate'][3].update(reused=10), + ): + broken = copy.deepcopy(data) + mutate(broken) + with self.assertRaises(AssertionError): + verify_admission(broken, 400, 999999) + + def test_incoming_exchange_evidence(self): + data = fixture() + data['engine_info']['candidate']['conversation_cache_mib'] = 400 + data['pressure'] = {'skips': 2, 'parks': [ + {'parked': 1, 'bytes': 266000000, 'evictions': 0}, + {'parked': 1, 'bytes': 384000000, 'evictions': 0}]} + verify_exchange(data, 100, 1, 400) + for skips in (0, 1, 3): + data['pressure']['skips'] = skips + with self.assertRaises(AssertionError): + verify_exchange(data, 100, 1, 400) + + def test_byte_eviction_evidence(self): + verify_pressure(pressure_fixture(), 400) + + def test_oversized_evidence(self): + data = pressure_fixture() + data['engine_info']['candidate']['conversation_cache_mib'] = 1 + data['pressure'] = {'skips': 3, 'parks': []} + verify_pressure(data, 1, oversized=True) + data['pressure']['skips'] = 2 + with self.assertRaises(AssertionError): + verify_pressure(data, 1, oversized=True) + + def test_insufficient_pressure_evidence_rejected(self): + cases = { + 'slot pressure': lambda d: d['pressure']['parks'][1].update(parked=4), + 'no eviction': lambda d: d['pressure']['parks'][-1].update(evictions=0), + 'too large individually': lambda d: d['pressure'].update(skips=1), + 'missing snapshots': lambda d: d['pressure']['parks'].pop(), + 'over budget': lambda d: d['pressure']['parks'][0].update(bytes=500 * 1024 * 1024), + 'cache hit': lambda d: d['candidate'][-1].update(reused=100), + 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'), + 'empty state': lambda d: d['candidate'][-1]['state'].clear(), + 'wrong output': lambda d: d['candidate'][-1].update(ids=[456]), + 'wrong budget': lambda d: d['engine_info']['candidate'].update(conversation_cache_mib=8192), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + data = pressure_fixture() + mutate(data) + with self.assertRaises(AssertionError): + verify_pressure(data, 400) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_conversation_cache_soak.py b/engine/strata/tools/test_conversation_cache_soak.py new file mode 100644 index 00000000..7d815890 --- /dev/null +++ b/engine/strata/tools/test_conversation_cache_soak.py @@ -0,0 +1,73 @@ +"""Offline checks for the synthetic known-answer soak acceptance gate.""" +import copy +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from tools.conversation_cache_soak import STATE_KEYS, answer_text, verify + + +def evidence(): + lengths = [2048, 40000, 120000] + def record(index): + return {'ids': [100 + index], 'text': ['MANGO', 'CEDAR', 'RAVEN'][index], + 'finish': 'stop', 'reused': lengths[index], 'cache_bytes': 100000, + 'state': {key: str(index) for key in STATE_KEYS}} + info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=131072, + spec=2, mtp_max=1, lookup=0, cvec=0, conversation_cache_mib=8192) + return {'requested_cycles': 30, 'engine_info': {'baseline': {**info, 'conversation_cache_mib': 0}, 'candidate': info}, + 'contexts': [{'expected': record(i)['text'], 'prompt_tokens': lengths[i], 'baseline': record(i)} for i in range(3)], + 'cycles': [{'cycle': i, 'context': i % 3, **record(i % 3)} for i in range(30)]} + + +class SoakGate(unittest.TestCase): + def test_complete_evidence(self): + verify(evidence()) + + def test_bad_or_incomplete_evidence(self): + cases = { + 'missing cycle': lambda r: r['cycles'].pop(), + 'too few requested': lambda r: r.update(requested_cycles=29), + 'missing context': lambda r: r['contexts'].pop(), + 'duplicate lengths': lambda r: r['contexts'][0].update(prompt_tokens=40000), + 'reordered cycle': lambda r: r['cycles'][2].update(context=0), + 'no streaming': lambda r: r['engine_info']['candidate'].update(kv_resident=0), + 'not near context limit': lambda r: (r['engine_info']['baseline'].update(context=262144), + r['engine_info']['candidate'].update(context=262144)), + 'different GPU residency': lambda r: r['engine_info']['candidate'].update(expert_slots=7999), + 'no restore': lambda r: r['cycles'][9].update(reused=0), + 'wrong answer despite parity': lambda r: (r['contexts'][0]['baseline'].update(text='WRONG'), + r['cycles'][0].update(text='WRONG')), + 'wrong token output': lambda r: r['cycles'][5].update(ids=[999]), + 'missing spare fingerprint': lambda r: r['cycles'][4]['state'].pop('dead'), + 'different state': lambda r: r['cycles'][4]['state'].update(gdn='bad'), + 'cancelled': lambda r: r['cycles'][3].update(finish='cancel'), + 'over budget': lambda r: r['cycles'][3].update(cache_bytes=2**40), + 'retained allocation grows': lambda r: r['cycles'][-1].update(cache_bytes=200000), + } + for name, mutate in cases.items(): + with self.subTest(name=name): + results = copy.deepcopy(evidence()) + mutate(results) + with self.assertRaises(AssertionError): + verify(results) + + def test_answer_normalization_does_not_hide_extra_text(self): + self.assertEqual(answer_text(' MANGO<|im_end|>\n'), 'mango') + self.assertNotEqual(answer_text('The code is MANGO.'), 'mango') + + def test_dry_run_never_reads_config_or_starts_model(self): + with tempfile.TemporaryDirectory(prefix='strata-soak-dry-') as directory: + root = Path(directory) + result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_soak.py')), + '--config', str(root / 'missing.json'), '--engine', str(root / 'missing'), + '--output', str(root / 'output')], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('No model loaded', result.stdout) + self.assertFalse((root / 'output').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/engine/strata/tools/test_iq_pack.py b/engine/strata/tools/test_iq_pack.py new file mode 100644 index 00000000..1c83db47 --- /dev/null +++ b/engine/strata/tools/test_iq_pack.py @@ -0,0 +1,528 @@ +"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py.""" +import contextlib +import hashlib +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too + +from _paths import add_gguf_py +add_gguf_py() +from gguf import GGUFWriter, GGMLQuantizationType as Q, quants +import iq_pack + + +def write_gguf(path, tensors, split=None, arch=True): + """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no).""" + writer = GGUFWriter(path, "qwen4exp") + if not arch: # a later shard of a split: no model metadata + writer.kv_data[0].pop("general.architecture", None) + if split is not None: + writer.add_uint16("split.no", split[0]) + writer.add_uint16("split.count", split[1]) + writer.add_int32("split.tensors.count", split[2]) + for name, values, kind in tensors: + writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind) + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + + +class CompatibilityTests(unittest.TestCase): + def test_bf16_halfway_rounds_to_even(self): + values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) + got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) + np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82]) + + def test_nonfinite_conversion_refused(self): + with self.assertRaisesRegex(ValueError, "non-finite"): + iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32") + + def test_projection_conversion_and_native_bytes(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128) + router = np.full((2, 128), 0.10001, dtype=np.float32) + names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", + "blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"] + write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [ + ("blk.1.ple_key.weight", values, Q.Q8_0), + ("blk.0.ffn_gate_inp.weight", router, Q.F32), + ("blk.0.attn_qkv.weight", values, Q.Q8_0), + ("per_layer_token_embd.weight", values, Q.Q8_0), + ]) + before = source.read_bytes() + model = iq_pack.Model(source) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0) + _, rows = iq_pack.read_index(root / "index.txt") + dense = (root / "dense.bin").read_bytes() + # A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value, + # using the even representation at exact ties. + decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel() + def rounded(x): + bits = int(np.float32(x).view(np.uint32)) + return (bits >> 16) + ((bits & 65535) > 32768 or + ((bits & 65535) == 32768 and (bits >> 16) & 1)) + expected = np.array([rounded(x) for x in decoded], dtype=np.uint16) + for name in names: + row = rows[name] + self.assertEqual(row[2], "4") + offset, size = int(row[3]), int(row[4]) + np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected) + for name in ["blk.0.attn_qkv.weight", "blk.1.ple_key.weight"]: # a Q8_0 PLE key stays native + native = rows[name] + self.assertEqual(native[2], "0") + self.assertEqual(native[4], "0") + self.assertEqual(native[9], "8") + self.assertNotIn("per_layer_token_embd.weight", rows) + self.assertEqual(source.read_bytes(), before) + self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 6) + conv = json.loads((root / "conversions.json").read_text()) + self.assertEqual(sorted(r["name"] for r in conv["tensors"]), sorted(names + ["blk.0.ffn_gate_inp.weight"])) + + def test_default_still_refuses_inexact_f32_router(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)]) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) + + def test_existing_bf16_pack_remains_byte_identical(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128) + write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)]) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) + self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes()) + + def test_quantized_control_weights_need_explicit_conversion(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + source = root / "model.gguf" + write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)]) + (root / "dense.bin").write_bytes(b"previous pack") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) + self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack") + + def test_q2_ple_and_large_tensors_stay_native(self): + self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0")) + self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0")) + self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) + for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight", + "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: + self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) + + def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + + def model(name, scale): + path = root / name + write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_%s_exps.weight" % (l, r), + scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) + for l in range(3) for r in ("gate", "up", "down")]) + return path + + def pack(path): + log = io.StringIO() + argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log): + self.assertEqual(iq_pack.main(), 0) + return log.getvalue() + + first = model("a.gguf", 1) + pack(first) + written = (out / "experts.bin").read_bytes() + self.assertIn("not rewritten", pack(first)) + self.assertEqual((out / "experts.bin").read_bytes(), written) + # the same geometry with other weights under the same file name: the size and the sidecar (shard names + # and sizes, native_experts.txt) match, the contents do not + second = model("a.gguf", -1) + self.assertIn("not this GGUF's expert blobs", pack(second)) + rewritten = (out / "experts.bin").read_bytes() + self.assertEqual(len(rewritten), len(written)) + self.assertNotEqual(rewritten, written) + self.assertIn("not rewritten", pack(second)) + + def test_snapshot_symlinks_keep_split_discovery(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + snap = root / "snapshot" + snap.mkdir() + first = snap / "model-00001-of-00002.gguf" + second = snap / "model-00002-of-00002.gguf" + write_gguf(root / "blob1", [ + ("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0), + ("blk.0.ffn_gate_inp.weight", np.ones((512, 32), np.float32), Q.BF16), + ], split=(0, 2, 5)) + write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0) + for r in ("gate", "up", "down")], split=(1, 2, 5), arch=False) + try: + first.symlink_to(root / "blob1") + except OSError: # Windows without Developer Mode or admin rights + self.skipTest("symlinks are not available here") + with self.assertRaisesRegex(FileNotFoundError, "missing model shards"): + iq_pack.Model(first) + second.symlink_to(root / "blob2") + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]): + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(iq_pack.main(), 0) + expert_index = (out / "native_experts.txt").read_text() + self.assertIn(second.name, expert_index) + self.assertIn("n_expert 512,", expert_index) + (root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64]) + with self.assertRaisesRegex(ValueError, "truncated tensor"): + iq_pack.Model(first) + + + +def bits(u32): + return np.array(u32, dtype=np.uint32).view(np.float32) + + +def pack_one(root, tensors, *flags): + """A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions).""" + source = root / "model.gguf" + write_gguf(source, tensors) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = iq_pack.index_standalone(source, root, iq_pack.Model(source), *flags) + if rc: + return rc, buf.getvalue(), None, None, None + _, rows = iq_pack.read_index(root / "index.txt") + conv = json.loads((root / "conversions.json").read_text()) + return rc, buf.getvalue(), rows, (root / "dense.bin").read_bytes(), conv + + +def stored(rows, dense, name, dtype): + row = rows[name] + return np.frombuffer(dense[int(row[3]):int(row[3]) + int(row[4])], dtype=dtype) + + +class ConversionTests(unittest.TestCase): + """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE + conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" + + def test_exact_f32_to_bf16_by_default(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 + rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_attn_inject.weight", x, Q.F32), + ("blk.0.ssm_beta.weight", x, Q.F32), + ("blk.0.ssm_norm.weight", x, Q.F32)]) + self.assertEqual(rc, 0, log) + for name in ["blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"]: + self.assertEqual(rows[name][2], "4") + np.testing.assert_array_equal(stored(rows, dense, name, "> 16).ravel()) + self.assertEqual(rows["blk.0.ssm_norm.weight"][2], "2") # F32 form: as stored + recs = {r["name"]: r for r in conv["tensors"]} + self.assertEqual(set(recs), {"blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"}) + r = recs["blk.0.ssm_beta.weight"] + self.assertEqual((r["src_type"], r["dst_type"], r["exact"], r["max_abs_err"], r["shard"]), + ("F32", "BF16", True, 0.0, "model.gguf")) + self.assertEqual(r["source_sha256"], hashlib.sha256(x.tobytes()).hexdigest()) + self.assertEqual(conv["schema"], 1) + self.assertEqual(conv["source_shards"], [{"name": "model.gguf", + "size": (Path(tmp) / "model.gguf").stat().st_size}]) + + def test_inexact_f32_rounds_only_with_compat(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + x = np.linspace(-1, 1, 64, dtype=np.float32).reshape(2, 32) + np.float32(1e-4) + rc, log, *_ = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)]) + self.assertEqual(rc, 1) + self.assertIn("not BF16", log) + rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)], True) + self.assertEqual(rc, 0, log) + got = stored(rows, dense, "blk.0.hc_ffn_inject.weight", " None: + """nodes: (gfx_target_version, simd_count, render_minor, product_name or None, vram_bytes)""" + for i, (ver, simd, minor, name, vram) in enumerate(nodes): + n = root / "class/kfd/kfd/topology/nodes" / str(i) + n.mkdir(parents=True) + (n / "properties").write_text(f"cpu_cores_count {0 if simd else 12}\nsimd_count {simd}\n" + f"gfx_target_version {ver}\ndrm_render_minor {minor}\n") + if simd: + d = root / f"class/drm/renderD{minor}/device" + d.mkdir(parents=True) + (d / "mem_info_vram_total").write_text(str(vram)) + if name is not None: + (d / "product_name").write_text(name + "\n") + + +class KfdDetection(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.win = setup.WIN + setup.WIN = False + + def tearDown(self): + setup.WIN = self.win + self.tmp.cleanup() + + def test_every_family(self): + fake_sysfs(self.root, [ + (0, 0, 0, None, 0), # the CPU node: skipped + (110001, 120, 128, "", 16 << 30), # gfx1101 without a product name + (120000, 64, 129, None, 16 << 30), # gfx1200, no product_name file + (120001, 128, 130, "AMD Radeon AI PRO R9700", 32 << 30), + (110002, 64, 131, None, 8 << 30), # gfx1102: listed, not supported + (100306, 4, 132, None, 512 << 20), # an integrated gfx1036: listed, not supported + (110000, 192, 133, "Radeon RX 7900 XTX", 24 << 30), + ]) + g = setup.amd_gpus(str(self.root)) + self.assertEqual([x["arch"] for x in g], ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1036", "gfx1100"]) + self.assertEqual([x["index"] for x in g], [0, 1, 2, 3, 4, 5]) # HIP numbers: GPU nodes only + self.assertEqual(g[0]["name"], setup.AMD_NAMES["gfx1101"]) + self.assertEqual(g[1]["name"], setup.AMD_NAMES["gfx1200"]) + self.assertEqual(g[2]["name"], "AMD Radeon AI PRO R9700") + self.assertEqual(g[3]["name"], "AMD Radeon (gfx1102)") + self.assertAlmostEqual(g[2]["vram_gb"], 32.0) + ok = [x["arch"] for x in g if setup.amd_problem(x) is None] + self.assertEqual(ok, ["gfx1101", "gfx1200", "gfx1201", "gfx1100"]) + self.assertIn("gfx1102", setup.amd_problem(g[3])) + self.assertIn("gfx1036", setup.amd_problem(g[4])) + + def test_no_kfd(self): + self.assertEqual(setup.amd_gpus(str(self.root)), []) + + def test_rocm_index_per_family(self): + for arch in setup.AMD_ARCHS: + self.assertIn(arch, setup.ROCM_INDEXES) + self.assertTrue(setup.ROCM_INDEXES["gfx1101"].endswith("/gfx110X-dgpu/")) + self.assertTrue(setup.ROCM_INDEXES["gfx1200"].endswith("/gfx120X-all/")) + self.assertEqual(setup.ROCM_INDEXES["gfx1101"], setup.ROCM_INDEXES["gfx1100"]) + self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"]) + + +class GpuLists(unittest.TestCase): + """--gpus with AMD cards: every chosen card must be supported; the first is the main one.""" + AMD = [{"index": 0, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0, "arch": "gfx1201"}, + {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"}, + {"index": 2, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}, + {"index": 3, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0, "arch": "gfx1100"}] + + def setUp(self): + self.say = setup.say + setup.say = lambda *a, **k: None + + def tearDown(self): + setup.say = self.say + + def test_list_in_order(self): + self.assertEqual([g["index"] for g in setup.amd_parse_gpus("1,0", self.AMD)], [1, 0]) + self.assertEqual([g["index"] for g in setup.amd_parse_gpus(" 0, 3 ", self.AMD)], [0, 3]) + + def test_all_is_every_supported_card_most_vram_first(self): + self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", self.AMD)], [1, 3, 0]) + + def test_refusals(self): + for text in ("1,2", "1,7", "1", "1,1", "x,y"): + with self.assertRaises(SystemExit, msg=text): + setup.amd_parse_gpus(text, self.AMD) + + def test_wheels_hold_one_family(self): + with tempfile.TemporaryDirectory() as d: # no system ROCm there: the wheels would be needed + old = setup.os.environ.get("ROCM_PATH") + setup.os.environ["ROCM_PATH"] = d + try: + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + finally: + if old is None: + del setup.os.environ["ROCM_PATH"] + else: + setup.os.environ["ROCM_PATH"] = old + + def test_runtime_only_system_rocm_falls_back_to_the_wheels(self): + """#446: a system ROCm 7 with hipcc and libhipblas but no HIP development files (no hip-lang CMake package, no + hip_runtime.h) is not used for the build: a warning says what is missing and the wheels path follows (here + it stops at the two-family check, which only the wheels path makes); with the files it is used as before.""" + said = [] + setup.say = lambda msg="": said.append(msg) # tearDown puts the real one back + with tempfile.TemporaryDirectory() as d: + sysroot = Path(d) + for rel, text in (("bin/hipcc", ""), ("lib/libhipblas.so.3", ""), + ("include/rocm-core/rocm_version.h", + "#define ROCM_VERSION_MAJOR 7\n#define ROCM_VERSION_MINOR 14\n")): + (sysroot / rel).parent.mkdir(parents=True, exist_ok=True) + (sysroot / rel).write_text(text) + with mock.patch.dict(setup.os.environ, {"ROCM_PATH": d}): + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + self.assertIn(f"the ROCm in {sysroot} has no HIP development files (lib/cmake/hip-lang/hip-lang-" + "config.cmake, include/hip/hip_runtime.h): using AMD's wheels", "\n".join(said)) + self.assertIn("two GPU families", "\n".join(said)) + for lib in ("lib64", "lib"): # either place CMake looks + with self.subTest(lib=lib): + cfg = sysroot / lib / "cmake/hip-lang/hip-lang-config.cmake" + cfg.parent.mkdir(parents=True, exist_ok=True) + cfg.write_text("") + said.clear() + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + self.assertIn("(include/hip/hip_runtime.h)", "\n".join(said)) + (sysroot / "include/hip").mkdir(parents=True, exist_ok=True) + (sysroot / "include/hip/hip_runtime.h").write_text("") + self.assertEqual(setup.rocm_root(["gfx1100", "gfx1201"]), (sysroot, [str(sysroot / "lib")])) + cfg.unlink() + (sysroot / "include/hip/hip_runtime.h").unlink() + + def test_build_for_every_arch(self): + """build_engine_hip compiles for the set of the chosen cards' archs and records it in BUILD.json.""" + calls = {} + saved = {k: getattr(setup, k) for k in ("ROOT", "rocm_root", "cmake_build", "source_hash", "source_version", + "ok", "shutil")} + with tempfile.TemporaryDirectory() as d: + root = Path(d) + + def fake_build(src, bdir, target, defs, vcvars, bat): + calls["defs"] = defs + (bdir).mkdir(parents=True, exist_ok=True) + (bdir / setup.EXE).write_text("engine") + + class Sh: + which = staticmethod(lambda name: "/usr/bin/" + name) + copy2 = staticmethod(lambda a, b: Path(b).write_text(Path(a).read_text())) + setup.ROOT, setup.cmake_build, setup.ok, setup.shutil = root, fake_build, lambda *a: None, Sh + setup.source_hash, setup.source_version = (lambda *a: "h"), (lambda: "0.1.31") + setup.rocm_root = lambda archs: (calls.setdefault("archs", archs) and root, [str(root / "lib")]) + try: + setup.build_engine_hip({"arch": "gfx1201", "archs": ["gfx1201", "gfx1100", "gfx1201"]}, root) + self.assertEqual(calls["archs"], ["gfx1100", "gfx1201"]) + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1100;gfx1201", calls["defs"]) + import json + self.assertEqual(json.loads((root / "engine" / "BUILD.json").read_text())["archs"], + ["gfx1100", "gfx1201"]) + calls.clear() # one of those cards alone: already built, no compile + setup.build_engine_hip({"arch": "gfx1100"}, root) + self.assertNotIn("defs", calls) + setup.build_engine_hip({"arch": "gfx1101"}, root) # another arch: compiled again + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1101", calls["defs"]) + finally: + for k, v in saved.items(): + setattr(setup, k, v) + + +class WindowsDetection(unittest.TestCase): + """Windows: the AMD cards from the display adapters (mocked Win32_VideoController rows and display-class registry + values), the HIP runtime's numbering from `strata-device --list-devices`, and the card setup chose matched to its + HIP ordinal (#325: an integrated Radeon is HIP's device 0).""" + ADAPTERS = [ # Win32_VideoController: name, PNPDeviceID, AdapterRAM (32-bit: at most 4 GB) + {"name": "NVIDIA GeForce RTX 5070", "pnp": r"PCI\VEN_10DE&DEV_2F04&SUBSYS_1234&REV_A1\4&1", "ram": 4293918720}, + {"name": "AMD Radeon RX 9070 XT", "pnp": r"PCI\VEN_1002&DEV_7550&SUBSYS_0E3B1002&REV_C0\6&2", "ram": 4293918720}, + {"name": "AMD Radeon(TM) Graphics", "pnp": r"PCI\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1\4&3", "ram": 536870912}, + {"name": "AMD Radeon RX 7800 XT", "pnp": r"PCI\VEN_1002&DEV_7499&SUBSYS_0000&REV_C8\6&4", "ram": 4293918720}, + ] + REGISTRY = [ # the display class's driver instances: 64-bit VRAM size (as int, or as bytes) + {"DriverDesc": "NVIDIA GeForce RTX 5070", "MatchingDeviceId": r"PCI\VEN_10DE&DEV_2F04", + "HardwareInformation.qwMemorySize": 12 << 30}, + {"DriverDesc": "AMD Radeon RX 6600", "MatchingDeviceId": r"PCI\VEN_1002&DEV_73FF", # a removed card + "HardwareInformation.qwMemorySize": 8 << 30}, + {"DriverDesc": "AMD Radeon RX 9070 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7550&REV_C0", + "HardwareInformation.qwMemorySize": (16 << 30).to_bytes(8, "little"), "DriverVersion": "32.0.21013.1000"}, + {"DriverDesc": "AMD Radeon(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_1002&DEV_164E&REV_C1", + "HardwareInformation.qwMemorySize": 512 << 20}, + {"DriverDesc": "AMD Radeon RX 7800 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7499", + "HardwareInformation.qwMemorySize": 16 << 30}, + ] + LIST = ("device 0: AMD Radeon(TM) Graphics\n arch gfx1036, 28.1 GiB, wave32\n" + " cannot run: GPU 0 (AMD Radeon(TM) Graphics, gfx1036) is not an architecture this Strata engine was " + "compiled for (gfx1100,gfx1101,gfx1102,gfx1200,gfx1201,gfx1030); ...\n" + "device 1: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" + "device 2: AMD Radeon RX 7800 XT\n arch gfx1101, 16.0 GiB, wave32\n") + + def test_adapters(self): + g = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + self.assertEqual([x["name"] for x in g], ["AMD Radeon RX 9070 XT", "AMD Radeon(TM) Graphics", + "AMD Radeon RX 7800 XT"]) # AMD only, present only, in order + self.assertEqual([x["index"] for x in g], [0, 1, 2]) + self.assertEqual(g[0]["arch"], "gfx1201") # by PCI device id + self.assertEqual(g[2]["arch"], "gfx1101") # an unlisted id: by its name + self.assertTrue(g[1]["arch"].startswith("unknown")) # the iGPU: listed, not supported + self.assertAlmostEqual(g[0]["vram_gb"], 16.0) # the registry's 64-bit size + self.assertEqual(g[0]["driver"], "32.0.21013.1000") + self.assertEqual([setup.amd_problem(x) is None for x in g], [True, False, True]) + + def test_registry_alone(self): + """No WMI answer: the registry's own list (which can hold a removed card).""" + g = setup.amd_gpus_windows([], self.REGISTRY) + self.assertEqual([x["arch"] for x in g if not x["arch"].startswith("unknown")], ["gfx1201", "gfx1101"]) + + def test_arch_names(self): + for name, arch in (("AMD Radeon RX 9070 GRE", "gfx1201"), ("AMD Radeon AI PRO R9700", "gfx1201"), + ("AMD Radeon RX 9060 XT", "gfx1200"), ("AMD Radeon RX 7900 GRE", "gfx1100"), + ("AMD Radeon PRO W7800", "gfx1100"), ("AMD Radeon RX 7700 XT", "gfx1101"), + ("AMD Radeon RX 7600", "gfx1102"), ("AMD Radeon RX 6950 XT", "gfx1030"), + ("AMD Radeon RX 6800M", ""), ("AMD Radeon 780M Graphics", ""), ("AMD Radeon RX 7700S", "")): + self.assertEqual(setup.win_amd_arch(None, name), arch, name) + self.assertEqual(setup.win_amd_arch(0x744C, "whatever"), "gfx1100") + + def test_list_devices(self): + h = setup.hip_devices(text=self.LIST) + self.assertEqual([(x["index"], x["arch"]) for x in h], [(0, "gfx1036"), (1, "gfx1201"), (2, "gfx1101")]) + self.assertAlmostEqual(h[1]["vram_gb"], 15.9) + self.assertIn("not an architecture", h[0]["cannot_run"]) + self.assertIsNotNone(setup.amd_problem(h[0])) + self.assertIsNone(setup.amd_problem(h[1])) + cannot = setup.hip_devices(text="device 0: AMD Radeon RX 9070 XT\n arch gfx1201, 15.9 GiB, wave32\n" + " cannot run: GPU 0 runs wave64\n") + self.assertEqual(setup.amd_problem(cannot[0]), "GPU 0 runs wave64") # the engine's own check counts + self.assertEqual(setup.hip_devices(text="(no GPU device)\n"), []) + + def test_the_card_by_its_hip_ordinal(self): + """#325: setup's GPU 0 (the 9070 XT, display order) is HIP's device 1 behind the iGPU.""" + listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + hip = setup.hip_devices(text=self.LIST) + self.assertEqual(setup.hip_match(listed[0], listed, hip)["index"], 1) + self.assertEqual(setup.hip_match(listed[2], listed, hip)["index"], 2) + two = [{"index": 0, "arch": "gfx1201"}, {"index": 1, "arch": "gfx1201"}] # two of a kind: by rank + self.assertEqual(setup.hip_match(two[1], two, [{"index": 0, "arch": "gfx1036"}, {"index": 1, "arch": "gfx1201"}, + {"index": 2, "arch": "gfx1201"}])["index"], 2) + self.assertIsNone(setup.hip_match({"index": 0, "arch": "gfx1100"}, [{"index": 0, "arch": "gfx1100"}], hip)) + + def test_hip_card(self): + listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY) + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)), \ + mock.patch.object(setup, "ok", lambda *a: None): + g = setup.hip_card(Path("engine"), listed[0], listed) + self.assertEqual((g["index"], g["count"], g["arch"], g["vram_gb"]), (1, 3, "gfx1201", 15.9)) + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: []), \ + mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): + setup.hip_card(Path("engine"), listed[0], listed) # no AMD driver: stops before the download + with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)[:1]), \ + mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit): + setup.hip_card(Path("engine"), listed[0], listed) # HIP does not list the card + + def test_windows_dispatch(self): + """amd_gpus() on Windows: HIP's numbering once the HIP engine answers, the display adapters before.""" + with mock.patch.object(setup, "WIN", True), \ + mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: None), \ + mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): + self.assertEqual(setup.amd_gpus(), ["display"]) + with mock.patch.object(setup, "WIN", True), \ + mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: ["hip"]), \ + mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]): + self.assertEqual(setup.amd_gpus(), ["hip"]) + + def test_no_hip_engine_no_probe(self): + with tempfile.TemporaryDirectory() as d: + eng = Path(d) + (eng / "strata-device.exe").write_text("x") + (eng / "BUILD.json").write_text('{"backend": "cuda"}') # an NVIDIA engine is never asked + self.assertIsNone(setup.hip_devices(eng / "strata-device.exe")) + + def test_prebuilt_hip_zip(self): + """get_prebuilt_hip: a published zip (here a local folder) is unpacked into engine/; one without code for the + card, or older than the first Windows HIP release, is refused.""" + import json + import zipfile + with tempfile.TemporaryDirectory() as d: + root = Path(d) + pub = root / "pub" + pub.mkdir() + + def publish(meta): + with zipfile.ZipFile(pub / setup.WIN_HIP_ASSET, "w") as z: + z.writestr("strata.exe", "engine") + z.writestr("strata-device.exe", "probe") + z.writestr("rocm/bin/amdhip64_7.dll", "dll") + z.writestr("BUILD.json", json.dumps(meta)) + ver = ".".join(map(str, setup.WIN_HIP_MIN_ENGINE)) + good = {"source": "prebuilt", "backend": "hip", "version": ver, "archs": ["gfx1100", "gfx1201"], + "lib_dirs": ["rocm/bin"]} + with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "say", lambda *a, **k: None), \ + mock.patch.object(setup, "ok", lambda *a: None), mock.patch.object(setup, "warn", lambda *a: None): + publish({**good, "archs": ["gfx1100"]}) + self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) + publish({**good, "version": "0.1.30"}) + self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})) + publish(good) + eng = setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}) + self.assertEqual(eng, root / "engine") + self.assertTrue((eng / "rocm" / "bin" / "amdhip64_7.dll").exists()) + self.assertEqual(setup.hip_lib_dirs(eng), [eng / "rocm" / "bin"]) + (pub / setup.WIN_HIP_ASSET).unlink() # installed: kept, nothing downloaded again + self.assertEqual(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}), eng) + + +_HIP_DEVICES = setup.hip_devices # the real parser, for the tests that mock setup.hip_devices + + +def setup_hip(text): + return _HIP_DEVICES(text=text) + + +class WindowsHipVision(unittest.TestCase): + def test_no_cpu_encoder_on_windows(self): + with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "warn", lambda *a: None): + self.assertEqual(setup.hip_vision("cpu"), "none") + self.assertEqual(setup.hip_vision("yes"), "none") + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "warn", lambda *a: None): + self.assertEqual(setup.hip_vision("cpu"), "cpu") + + +class HipRuntimeBesideExe(unittest.TestCase): + """#468 #461: the bundled HIP runtime (and amd_comgr) goes next to strata.exe, so an AMD driver's System32 copy is + not found first; rocBLAS and the rest stay in rocm/bin.""" + + def test_copies_only_the_runtime(self): + import json + with tempfile.TemporaryDirectory() as d: + eng = Path(d) + rb = eng / "rocm" / "bin" + rb.mkdir(parents=True) + (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "lib_dirs": ["rocm/bin"]})) + for n, data in (("amdhip64_7.dll", b"hip-3686"), ("amd_comgr.dll", b"comgr"), ("rocblas.dll", b"blas")): + (rb / n).write_bytes(data) + setup.hip_runtime_beside_exe(eng) + self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3686") + self.assertEqual((eng / "amd_comgr.dll").read_bytes(), b"comgr") + self.assertFalse((eng / "rocblas.dll").exists()) # finds its kernels relative to rocm/bin + (rb / "amdhip64_7.dll").write_bytes(b"hip-3690-newer") # a newer zip: replaced on the next start + setup.hip_runtime_beside_exe(eng) + self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3690-newer") + + def test_no_rocm_bin_is_a_no_op(self): + with tempfile.TemporaryDirectory() as d: + setup.hip_runtime_beside_exe(Path(d)) # no BUILD.json (a CUDA or Linux engine) + self.assertEqual(list(Path(d).iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_choices.py b/engine/strata/tools/test_setup_choices.py new file mode 100644 index 00000000..cebc2f77 --- /dev/null +++ b/engine/strata/tools/test_setup_choices.py @@ -0,0 +1,271 @@ +"""Tests for setup.py's choices that depend on the PC (no GPU, no network, nothing installed): the image encoder of a +ready-made engine that has no code for the card (#331), --gguf-dir's shard count (#305), the experimental +Pascal/Volta build (#295), the CPU image encoder with the AMD backend (#304). + + python -m unittest tools.test_setup_choices +""" +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + + +def quiet(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return fn(*args, **kw), out.getvalue() + + +class PrebuiltVision(unittest.TestCase): + """#331: the 0.1.30/0.1.31 zip's encoder has no sm_75 code: an RTX 20 card gets the CPU encoder, not a compile.""" + META = {"version": "0.1.31", "archs": [75, 86, 89, 120], "ptx": True, "vision_archs": [86, 89, 120]} + + def test_a_card_the_encoder_has_no_code_for_gets_the_cpu_encoder(self): + got, out = quiet(setup.prebuilt_vision, self.META, {"arch": 75}, "gpu") + self.assertEqual(got, "cpu") + self.assertIn("runs on the CPU instead", out) + + def test_covered_cards_keep_the_gpu_encoder(self): + for arch in (86, 89, 120): + self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": arch}, "gpu")[0], "gpu") + # a newer card than the newest encoder code: only with PTX in the zip + self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89]}, {"arch": 120}, "gpu")[0], + "gpu") + self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89], "ptx": False}, + {"arch": 120}, "gpu")[0], "cpu") + # 0.1.32's zip: the encoder built with 75-real too + self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [75, 86, 89, 120]}, + {"arch": 75}, "gpu")[0], "gpu") + + def test_other_choices_are_left_alone(self): + for v in ("cpu", "none"): + self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": 75}, v), (v, "")) + # an older BUILD.json without vision_archs: the engine's archs + self.assertEqual(quiet(setup.prebuilt_vision, {"archs": [75, 86]}, {"arch": 75}, "gpu")[0], "gpu") + + +class GgufDirShards(unittest.TestCase): + """#305: --gguf-dir reads the shard count from the -of-N part of the name instead of assuming two.""" + + def shards(self, names, family="qwen", model="IQ3_XXS"): + with tempfile.TemporaryDirectory() as d: + for n in names: + (Path(d) / n).write_bytes(b"") + return [p.name for p in setup.gguf_dir_shards(Path(d), setup.FAMILIES[family], model)] + + def test_the_published_two_shards(self): + names = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"] + self.assertEqual(self.shards(names), names) + self.assertEqual(self.shards(names[:1]), names) # shard 2 missing: check_shards says so later + swift = ["Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"] + self.assertEqual(self.shards(swift + ["mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf"], "swift", "Q2_0"), swift) + + def test_four_unsloth_shards(self): + names = ["Qwen3.8-Flash-Next-UD-Q4_K_XL-%05d-of-00004.gguf" % i for i in range(1, 5)] + self.assertEqual(self.shards(names + ["mmproj-F16.gguf"], model="Q4_K_XL"), names) + self.assertEqual(self.shards(names[:1], model="Q4_K_XL"), names) # the others named from the first + + def test_another_split_of_a_setup_size(self): + names = ["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)] + other = ["my-Q2_0-%05d-of-00002.gguf" % i for i in range(1, 3)] + self.assertEqual(self.shards(names + other), names) # the one with the size in its name + self.assertEqual(self.shards(other, model="Q2_0"), other) + + def test_nothing_recognisable_keeps_the_published_names(self): + want = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"] + self.assertEqual(self.shards([]), want) + self.assertEqual(self.shards(["a-00001-of-00002.gguf", "b-00001-of-00002.gguf"]), want) # ambiguous + + +class GgufDirUnsupported(unittest.TestCase): + """#444: --gguf-dir with GGUFs Strata cannot run (Unsloth's UD-IQ3_XXS, UD-Q2_K_XL) says so, names the files it + runs (ISTA-DASLab's GSQ-RCO, the Coder's, Unsloth's UD-Q4_K_XL) and the --family/--model of the usable ones.""" + UD = ["Qwen3.8-Flash-Next-UD-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)] + \ + ["Qwen3.8-Flash-Next-UD-Q2_K_XL-%05d-of-00003.gguf" % i for i in range(1, 4)] + + def problem(self, names, family="qwen", model="IQ3_XXS"): + with tempfile.TemporaryDirectory() as d: + for n in names: + (Path(d) / n).write_bytes(b"") + fam = setup.FAMILIES[family] + first = setup.gguf_dir_shards(Path(d), fam, model)[0] + p = setup.gguf_dir_problem(Path(d), first, fam, model) + return p and (p[0].replace(d, ""), p[1]) + + def test_quant_names(self): + for name, want in (("Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf", "UD-IQ3_XXS"), + ("Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", "UD-Q2_K_XL"), + ("model-Q4_K_M.gguf", "Q4_K_M"), + ("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", None), + ("Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", None), + ("my-IQ3_XXS-00001-of-00003.gguf", None), ("mmproj-F16.gguf", None), + ("a-00001-of-00002.gguf", None)): + self.assertEqual(setup.gguf_unsupported(name), want, name) + + def test_an_unsloth_ud_file_is_not_taken_for_a_gsq_rco_size(self): + msg, hint = self.problem(self.UD) # IQ3_XXS: UD-IQ3_XXS has the size in its name + self.assertEqual(msg, "Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf is UD-IQ3_XXS, a GGUF Strata " + "cannot run") + self.assertIn("ISTA-DASLab's GSQ-RCO files", hint) + self.assertIn("Unsloth's UD-Q4_K_XL only", hint) + + def test_a_folder_without_the_choice_names_what_is_there(self): + gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)] + msg, hint = self.problem(self.UD + gsq, "unsloth", "UD-Q4_K_XL") + self.assertEqual(msg, " has no Qwen3.8-Flash-Next (Unsloth) UD-Q4_K_XL file") + self.assertIn("Not usable here: Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00003.gguf, " + "Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", hint) + self.assertIn("Usable here: --family coder --model IQ1_M", hint) + + def test_usable_folders_are_left_alone(self): + good = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-%05d-of-00002.gguf" % i for i in (1, 2)] + self.assertIsNone(self.problem(good + self.UD)) + self.assertIsNone(self.problem(["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in (1, 2, 3)])) + self.assertIsNone(self.problem([])) # nothing there: check_shards' "missing", as before + + def test_the_size_of_another_family(self): + from test_setup_golden import PROFILES, install + ram, found = PROFILES["64GB-1x32GB"] + with tempfile.TemporaryDirectory() as d: + code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"]) + self.assertEqual(code, 1) + self.assertIn("has no IQ3_XXS model file", out) + self.assertIn("choose one of: UD-Q4_K_XL (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model " + "IQ3_XXS)", out) + self.assertIn("Strata runs ISTA-DASLab's GSQ-RCO files", out) + + +class ExperimentalSm60(unittest.TestCase): + """#295: Pascal (6.x) and Volta (7.0) only with STRATA_EXPERIMENTAL_SM60=1, built with -DSTRATA_EXPERIMENTAL_SM60=ON + and a CUDA 12.x toolkit; nothing changes without the variable.""" + + def card(self, arch): + return {"arch": arch, "vram_gb": 11.0, "index": 0, "name": "card"} + + def test_the_gate(self): + with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""}): + for arch in ("60", "61", "70"): + p = setup.gpu_problem(self.card(arch)) + self.assertIn("not supported", p) + self.assertIn("STRATA_EXPERIMENTAL_SM60=1", p) + self.assertNotIn("STRATA_EXPERIMENTAL_SM60", setup.gpu_problem(self.card("52"))) + self.assertIsNone(setup.gpu_problem(self.card("75"))) + with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}): + for arch in ("60", "61", "70", "75", "120"): + self.assertIsNone(setup.gpu_problem(self.card(arch)), arch) + for arch in ("52", "72"): + self.assertIsNotNone(setup.gpu_problem(self.card(arch)), arch) + + def test_the_build_flag(self): + self.assertEqual(setup.engine_defs([61]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"]) + self.assertEqual(setup.engine_defs([70, 86]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"]) + self.assertEqual(setup.engine_defs([75, 86, 120]), []) + + def test_find_nvcc_below(self): + with tempfile.TemporaryDirectory() as d: + new, old = Path(d) / "13" / "nvcc", Path(d) / "12" / "bin" / "nvcc" + for p in (new, old): + p.parent.mkdir(parents=True) + p.write_bytes(b"") + versions = {str(new): "Cuda compilation tools, release 13.0, V13.0.88", + str(old): "Cuda compilation tools, release 12.9, V12.9.86"} + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: str(new)), \ + mock.patch.dict(os.environ, {"CUDA_PATH": str(Path(d) / "12")}), \ + mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")): # #414 + self.assertEqual(setup.find_nvcc(), (str(new), (13, 0))) + self.assertEqual(setup.find_nvcc(below=(13, 0)), (str(old), (12, 9))) + + def tools(self, archs, nvcc): + seen = [] + + def find(below=None): + seen.append(below) + return nvcc(below) + + with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda: "vcvars"), \ + mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n): + got, _ = quiet(setup.install_build_tools, {"arch": str(archs[0]), "archs": archs}, True) + return got, seen + + def test_pascal_takes_cuda_12(self): + got, seen = self.tools([61], lambda below: ("nvcc12", (12, 9)) if below == (13, 0) else ("nvcc13", (13, 0))) + self.assertEqual(got[0], "nvcc12") + self.assertEqual(seen, [(13, 0)]) + got, seen = self.tools([86, 120], lambda below: ("nvcc13", (13, 0))) + self.assertEqual((got[0], seen), ("nvcc13", [None])) # the default: unchanged + + def test_pascal_without_cuda_12_stops(self): + for archs in ([61], [70, 120]): + with self.subTest(archs=archs), self.assertRaises(SystemExit): + self.tools(archs, lambda below: (None, None) if below else ("nvcc13", (13, 0))) + + +class HipVision(unittest.TestCase): + """#304: --vision cpu with --backend hip builds the CPU image encoder beside the HIP engine.""" + + @mock.patch.object(setup, "WIN", False) # Linux: compiled here (Windows has no AMD image encoder yet) + def test_the_choice(self): + self.assertEqual(quiet(setup.hip_vision, "cpu"), ("cpu", "")) + for asked in (None, "no", "none"): + self.assertEqual(quiet(setup.hip_vision, asked), ("none", "")) + for asked in ("yes", "gpu"): + got, out = quiet(setup.hip_vision, asked) + self.assertEqual(got, "none") + self.assertIn("--vision cpu", out) + + def build(self, meta, vision, vexe=False): + """build_engine_hip with an engine that is already built: only the encoder can be missing.""" + with tempfile.TemporaryDirectory() as d: + root = Path(d) + eng = root / "engine" + eng.mkdir() + (eng / setup.EXE).write_bytes(b"engine") + if vexe: + (eng / setup.VEXE).write_bytes(b"vision") + src, vsrc = "S", "V" + (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "archs": ["gfx1201"], "src": src, **meta})) + built = [] + + def cmake_build(src_dir, bdir, target, defs, vcvars, bat): + built.append((target, defs)) + (bdir / "bin").mkdir(parents=True) + (bdir / "bin" / setup.VEXE).write_bytes(b"vision") + + with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "cmake_build", cmake_build), \ + mock.patch.object(setup, "source_hash", lambda paths: vsrc if paths == setup.VISION_SOURCES else src): + quiet(setup.build_engine_hip, {"arch": "gfx1201"}, "llama", vision) + return built, json.loads((eng / "BUILD.json").read_text()), (eng / setup.VEXE).exists() + + def test_the_cpu_encoder_is_built_once(self): + built, meta, have = self.build({}, "cpu") + self.assertEqual([t for t, _ in built], ["strata-vision"]) + self.assertIn("-DSTRATA_VISION_CUDA=OFF", built[0][1]) + self.assertEqual((meta["vision"], meta["vision_src"], have), ("cpu", "V", True)) + built, meta, _ = self.build({"vision": "cpu", "vision_src": "V"}, "cpu", vexe=True) + self.assertEqual(built, []) # built and unchanged: nothing to do + built, meta, _ = self.build({"vision": "cpu", "vision_src": "old"}, "cpu", vexe=True) + self.assertEqual([t for t, _ in built], ["strata-vision"]) # its source changed: again + + def test_without_images_nothing_changes(self): + built, meta, have = self.build({}, "none") + self.assertEqual((built, have), ([], False)) + self.assertNotIn("vision_src", meta) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_draft_vocab.py b/engine/strata/tools/test_setup_draft_vocab.py new file mode 100644 index 00000000..f0b75692 --- /dev/null +++ b/engine/strata/tools/test_setup_draft_vocab.py @@ -0,0 +1,53 @@ +"""Tests for setup.py's draft-vocabulary choice (#287): a setup run again without --draft-vocab keeps the subset the +model's config chose before (cyrillic, en), and refresh_draft_vocab copies the chosen shipped subset. Pure file work +in a temporary folder - no GPU, no downloads, no prompts. + + python -m unittest tools.test_setup_draft_vocab +""" +from __future__ import annotations + +import hashlib +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class SavedChoice(unittest.TestCase): + def test_a_config_keeps_its_choice(self): + with tempfile.TemporaryDirectory() as d: + for choice in setup.DRAFT_VOCABS: + p = Path(d) / "strata-x.json" + p.write_text(json.dumps({"args": [], "draft_vocab": choice}), encoding="utf-8") + self.assertEqual(setup.saved_draft_vocab(p), choice) + + def test_no_choice_without_a_valid_config(self): + with tempfile.TemporaryDirectory() as d: + self.assertIsNone(setup.saved_draft_vocab(Path(d) / "missing.json")) + for text in ("{}", "[1]", "not json", json.dumps({"draft_vocab": "klingon"})): + p = Path(d) / "strata-y.json" + p.write_text(text, encoding="utf-8") + self.assertIsNone(setup.saved_draft_vocab(p), text) + + +class Refresh(unittest.TestCase): + def test_cyrillic_replaces_a_shipped_subset_and_stays(self): + if not (ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).exists(): + self.skipTest("data/draft_vocab_cyrillic.bin is not in this checkout") + want = hashlib.sha256((ROOT / "data" / setup.DRAFT_VOCABS["cyrillic"]).read_bytes()).hexdigest() + with tempfile.TemporaryDirectory() as d: + rt = Path(d) + (rt / "draft_vocab.bin").write_bytes((ROOT / "data" / setup.DRAFT_VOCABS["cjk"]).read_bytes()) + setup.refresh_draft_vocab(rt, "cyrillic") + self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) + setup.refresh_draft_vocab(rt, "cyrillic") # again: nothing changes + self.assertEqual(hashlib.sha256((rt / "draft_vocab.bin").read_bytes()).hexdigest(), want) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_golden.json b/engine/strata/tools/test_setup_golden.json new file mode 100644 index 00000000..c2110bc5 --- /dev/null +++ b/engine/strata/tools/test_setup_golden.json @@ -0,0 +1,966 @@ +{ + "128GB-1x24GB qwen IQ3_S": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_s", + "--native", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_s.log", + "model_name": "qwen3.8-flash-next-iq3_s", + "port": 8080, + "tokenizer": "/data/packs/iq3_s/tokenizer" + } + }, + "128GB-1x24GB qwen IQ3_XXS": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "128GB-1x24GB qwen Q2_0": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "128GB-1x24GB qwen recommended": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "128GB-1x24GB unsloth UD-Q4_K_XL": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/unsloth-ud-q4_k_xl", + "--native", + "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "32768", + "--kv", + "int8", + "--resident-budget-gib", + "71" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-unsloth-ud-q4_k_xl.log", + "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", + "port": 8080, + "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer" + } + }, + "32GB-2x24GB qwen IQ3_S": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_s", + "--native", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--mmap-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_s.log", + "model_name": "qwen3.8-flash-next-iq3_s", + "port": 8080, + "tokenizer": "/data/packs/iq3_s/tokenizer" + } + }, + "32GB-2x24GB qwen IQ3_XXS": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--mmap-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "32GB-2x24GB qwen Q2_0": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--resident-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "32GB-2x24GB qwen recommended": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--resident-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "32GB-2x24GB unsloth UD-Q4_K_XL": { + "code": 1, + "config": null + }, + "47GB-2x16GB qwen IQ3_S": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_s", + "--native", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--mmap-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_s.log", + "model_name": "qwen3.8-flash-next-iq3_s", + "port": 8080, + "tokenizer": "/data/packs/iq3_s/tokenizer" + } + }, + "47GB-2x16GB qwen IQ3_XXS": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--resident-experts" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "47GB-2x16GB qwen Q2_0": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8" + ], + "cwd": "", + "exe": "/engine/", + "gpu": [ + 0, + 1 + ], + "gpus_asked": true, + "layer_split": "auto", + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "47GB-2x16GB qwen recommended": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8" + ], + "cwd": "", + "exe": "/engine/", + "gpu": [ + 0, + 1 + ], + "gpus_asked": true, + "layer_split": "auto", + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "47GB-2x16GB unsloth UD-Q4_K_XL": { + "code": 1, + "config": null + }, + "64GB-1x32GB qwen IQ3_S": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_s", + "--native", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_s.log", + "model_name": "qwen3.8-flash-next-iq3_s", + "port": 8080, + "tokenizer": "/data/packs/iq3_s/tokenizer" + } + }, + "64GB-1x32GB qwen IQ3_XXS": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "64GB-1x32GB qwen Q2_0": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "64GB-1x32GB qwen recommended": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "64GB-1x32GB unsloth UD-Q4_K_XL": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/unsloth-ud-q4_k_xl", + "--native", + "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "32768", + "--kv", + "int8", + "--resident-budget-gib", + "40" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-unsloth-ud-q4_k_xl.log", + "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", + "port": 8080, + "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer" + } + }, + "96GB-1x16GB qwen IQ3_S": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_s", + "--native", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_s.log", + "model_name": "qwen3.8-flash-next-iq3_s", + "port": 8080, + "tokenizer": "/data/packs/iq3_s/tokenizer" + } + }, + "96GB-1x16GB qwen IQ3_XXS": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "96GB-1x16GB qwen Q2_0": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/q2_0", + "--native", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--ple-gguf", + "/models/Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-q2_0.log", + "model_name": "qwen3.8-flash-next-q2_0", + "port": 8080, + "tokenizer": "/data/packs/q2_0/tokenizer" + } + }, + "96GB-1x16GB qwen recommended": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/iq3_xxs", + "--native", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "65536", + "--kv", + "int8", + "--kv-resident", + "32768" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-iq3_xxs.log", + "model_name": "qwen3.8-flash-next-iq3_xxs", + "port": 8080, + "tokenizer": "/data/packs/iq3_xxs/tokenizer" + } + }, + "96GB-1x16GB unsloth UD-Q4_K_XL": { + "code": 0, + "config": { + "args": [ + "--pack", + "/data/packs/unsloth-ud-q4_k_xl", + "--native", + "/models/unsloth-UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", + "--expert-profile", + "/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/data/mtp/rt", + "--max-context", + "32768", + "--kv", + "int8", + "--resident-budget-gib", + "71" + ], + "cwd": "", + "exe": "/engine/", + "gpu": 0, + "gpus_asked": true, + "lib_dirs": [ + "" + ], + "log": "/strata-unsloth-ud-q4_k_xl.log", + "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", + "port": 8080, + "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer" + } + } +} diff --git a/engine/strata/tools/test_setup_golden.py b/engine/strata/tools/test_setup_golden.py new file mode 100644 index 00000000..054c1c14 --- /dev/null +++ b/engine/strata/tools/test_setup_golden.py @@ -0,0 +1,208 @@ +"""The owner's rule for setup (#403 #406 #364 #384): setup RECOMMENDS, it never forces - and the recommended answers +stay exactly what they were. setup.main() with --yes (and with Enter for every question) on a few PCs writes the same +run config, byte for byte, as 0.1.32 plus the fixes on top of it did (tools/test_setup_golden.json, written by that +setup). Every outside effect is mocked: no GPU, no downloads, nothing written outside a temp folder. + + python -m unittest tools.test_setup_golden + python tools/test_setup_golden.py --write (only to record a new baseline on purpose) +""" +from __future__ import annotations + +import contextlib +import io +import json +import sys +import tempfile +import types +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + +GOLDEN = Path(__file__).with_name("test_setup_golden.json") + + +def card(i, name, vram, arch): + return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": "580.97"} + + +# the PCs: total RAM as ram_gb() reads it (a little under the label), the cards as nvidia-smi lists them +PROFILES = { + "64GB-1x32GB": (63.7, [card(0, "NVIDIA GeForce RTX 5090", 31.8, "120")]), # #406 + "32GB-2x24GB": (31.9, [card(i, "NVIDIA GeForce RTX 3090", 24.0, "86") for i in range(2)]), # #364 + "47GB-2x16GB": (47.0, [card(i, "NVIDIA GeForce RTX 5060 Ti", 15.9, "120") for i in range(2)]), # #384 + "96GB-1x16GB": (95.8, [card(0, "NVIDIA GeForce RTX 5080", 15.9, "120")]), + "128GB-1x24GB": (127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89")]), +} +# (family, model): None = the recommended size +MODELS = [("qwen", None), ("qwen", "Q2_0"), ("qwen", "IQ3_XXS"), ("qwen", "IQ3_S"), ("unsloth", "UD-Q4_K_XL")] + + +class FakeGGUF: + """gguf_reader.GGUFFile: shard 2 holds the PLE table.""" + def __init__(self, path): + names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"] + self.tensors = [types.SimpleNamespace(name=n) for n in names] + + +def normalize(v, t: Path): + """The config with the temp folder and the platform's names taken out (it compares on Windows and Linux).""" + if isinstance(v, dict): + return {k: normalize(x, t) for k, x in v.items()} + if isinstance(v, list): + return [normalize(x, t) for x in v] + if isinstance(v, str): + return v.replace(str(t), "").replace("\\", "/").replace(setup.EXE, "") + return v + + +def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()): + """setup.main() on a mocked PC -> (exit code, printed text, the written config or None, the questions asked). + answers: None = --yes (a question fails the run), "" = Enter for every question, a list of answers in order, or + {words of a question: its answer} (Enter for the others). + extra: more patches (mock.patch objects). configs: (name, dict) run configs already in the Strata folder.""" + with tempfile.TemporaryDirectory() as tmp: + t = Path(tmp) + (t / "data" / "mtp" / "rt").mkdir(parents=True) + (t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"") + eng = t / "engine" + eng.mkdir() + (eng / "BUILD.json").write_text(json.dumps({"version": "0.1.32", "source": "local", "cuda_dirs": [""]})) + for name, c in configs: + (t / name).write_text(json.dumps(c)) + asked = [] + + def fake_input(prompt=""): + asked.append(prompt) + if answers is None: + raise AssertionError(f"asked {prompt!r} with --yes") + if isinstance(answers, list): + return answers.pop(0) if answers else "" + if isinstance(answers, dict): # {words of the question: answer}, else Enter + return next((v for k, v in answers.items() if k in prompt), "") + return answers + + def fake_download(url, dst, what=None): + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_bytes(b"") + setup.mark(dst) + + patches = [ + mock.patch.object(setup, "ROOT", t), + mock.patch.object(setup, "GPU_PICK", None), + mock.patch.object(setup, "data_folder", lambda d: (t / "data", [])), + mock.patch.object(setup, "load_settings", lambda: {}), + mock.patch.object(setup, "save_settings", lambda s: None), + mock.patch.object(setup, "gpus", lambda: found), + mock.patch.object(setup, "amd_gpus", lambda: []), + mock.patch.object(setup, "ram_gb", lambda: ram), + mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, avx512)), + mock.patch.object(setup, "page_file_gb", lambda: 16.0), + mock.patch.object(setup, "is_wsl", lambda: False), + mock.patch.object(setup, "free_gb", lambda p: 900.0), + mock.patch.object(setup, "pip_install", lambda *a, **k: None), + mock.patch.object(setup, "get_llama_cpp", lambda: t / "llama.cpp"), + mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), + mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), + mock.patch.object(setup, "download", fake_download), + mock.patch.object(setup, "check_shards", lambda shards: None), + mock.patch.object(setup, "verify_sha256", lambda *a: None), + mock.patch.object(setup, "run", lambda *a, **k: None), + mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False), + mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: t / f"run-{tag}.bat"), + mock.patch.object(setup, "saved_calibration", lambda cfg: None), + mock.patch.object(setup, "calibrate_config", mock.Mock(side_effect=AssertionError("calibrated"))), + mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), + mock.patch.object(sys, "argv", ["setup.py", "--models-dir", str(t / "models"), *argv] + + (["--yes"] if answers is None else [])), + mock.patch("builtins.input", fake_input), + *extra, + ] + out = io.StringIO() + code = None + with contextlib.ExitStack() as st: + for p in patches: + st.enter_context(p) + with contextlib.redirect_stdout(out): + try: + code = setup.main() + except SystemExit as e: + code = e.code + written = sorted(t.glob("strata-*.json"), key=lambda p: p.stat().st_mtime) + cfg = None + if written and code == 0: + cfg = normalize(json.loads(written[-1].read_text(encoding="utf-8")), t) + return code, out.getvalue(), cfg, asked + + +def argv_for(family, model): + return ["--family", family, "--no-start"] + (["--model", model] if model else []) + + +def record() -> dict: + """Every profile x model with --yes: the exit code and the config (the baseline this test compares against).""" + res = {} + for prof, (ram, found) in PROFILES.items(): + for family, model in MODELS: + code, out, cfg, _ = install(ram, found, argv_for(family, model)) + res[f"{prof} {family} {model or 'recommended'}"] = {"code": code, "config": cfg} + return res + + +class Golden(unittest.TestCase): + """--yes and Enter: the same config as the baseline wherever the baseline wrote one.""" + + @classmethod + def setUpClass(cls): + cls.golden = json.loads(GOLDEN.read_text(encoding="utf-8")) + + def cases(self): + for prof, (ram, found) in PROFILES.items(): + for family, model in MODELS: + key = f"{prof} {family} {model or 'recommended'}" + if self.golden[key]["code"] == 0: + yield key, ram, found, family, model + + def test_the_baseline_covers_every_kind_of_pc(self): + written = [k for k, v in self.golden.items() if v["code"] == 0] + self.assertGreaterEqual(len(written), 20) + lowram_multi = self.golden["32GB-2x24GB qwen IQ3_XXS"]["config"] # #364: low-RAM, two cards -> one + self.assertIn("--resident-experts" if "--resident-experts" in lowram_multi["args"] else "--mmap-experts", + lowram_multi["args"]) + self.assertNotIsInstance(lowram_multi.get("gpu"), list) + + def test_yes(self): + for key, ram, found, family, model in self.cases(): + with self.subTest(key): + code, out, cfg, asked = install(ram, found, argv_for(family, model)) + self.assertEqual(code, 0, out[-3000:]) + self.assertEqual(cfg, self.golden[key]["config"], out[-3000:]) + self.assertEqual(asked, []) + + def test_enter_for_every_question(self): + for key, ram, found, family, model in self.cases(): + with self.subTest(key): + code, out, cfg, asked = install(ram, found, argv_for(family, model), answers="") + self.assertEqual(code, 0, out[-3000:]) + self.assertEqual(cfg, self.golden[key]["config"], out[-3000:]) + + def test_the_refusals_with_yes_alone_stay(self): + """A size the baseline refused with --yes and no explicit --model still stops (--yes alone is no consent).""" + for prof, (ram, found) in PROFILES.items(): + for family, model in MODELS: + key = f"{prof} {family} {model or 'recommended'}" + if self.golden[key]["code"] != 0 and model is None: + with self.subTest(key): + self.assertNotEqual(install(ram, found, argv_for(family, model))[0], 0) + + +if __name__ == "__main__": + if "--write" in sys.argv: + GOLDEN.write_text(json.dumps(record(), indent=1, sort_keys=True) + "\n", encoding="utf-8") + print(f"wrote {GOLDEN}") + else: + unittest.main() diff --git a/engine/strata/tools/test_setup_lowram.py b/engine/strata/tools/test_setup_lowram.py new file mode 100644 index 00000000..b7240b82 --- /dev/null +++ b/engine/strata/tools/test_setup_lowram.py @@ -0,0 +1,84 @@ +"""Tests for setup.py's low-RAM messages and the paging question (#250): the one-GPU warning says why and shows the +RAM math, and an explicit --low-ram off installs with --yes instead of stopping at "Install it anyway?" (default +n). Mocked input - no GPU, no downloads. + + python -m unittest tools.test_setup_lowram +""" +from __future__ import annotations + +import contextlib +import io +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +def run(fn, *args, stdin=None): + """-> (exit code or None, printed text); `stdin` answers input() (None: never asked).""" + out = io.StringIO() + asked = [] + + def fake_input(prompt=""): + asked.append(prompt) + if stdin is None: + raise AssertionError(f"asked {prompt!r} with --yes") + return stdin + + code = None + with contextlib.redirect_stdout(out), mock.patch("builtins.input", fake_input): + try: + fn(*args) + except SystemExit as e: + code = e.code + return code, out.getvalue(), asked + + +class OneGpuWhy(unittest.TestCase): + def test_auto_shows_the_ram_math(self): + lines = setup.low_ram_one_gpu_why("IQ3_XXS", 46, "auto") # the #250 report: 46 GB, IQ3_XXS + text = "\n".join(lines) + arena = setup.MODELS["IQ3_XXS"]["arena_gb"] + need = arena + setup.LOW_RAM_HEADROOM_GB + self.assertIn(f"{arena:.0f} + {setup.LOW_RAM_HEADROOM_GB} = {need:.0f} GB", text) + self.assertIn("this PC has 46 GB", text) + self.assertIn("layer split", text) # why one GPU is recommended + self.assertIn("--gpus 0,1", text) # #364 #384: and the way to use them all + self.assertIn("OS file cache", text) + self.assertNotIn("--low-ram off", text) # (that pages the experts: not the way) + + def test_an_explicit_choice_says_so(self): + text = "\n".join(setup.low_ram_one_gpu_why("Q2_0", 64, "resident")) + self.assertIn("you chose the low-RAM mode (--low-ram resident)", text) + + +class PagingQuestion(unittest.TestCase): + MODEL, RAM = "IQ3_XXS", 46 # 60 GB wanted, 46 here + + def test_yes_with_low_ram_off_installs(self): + code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, "off", True) + self.assertIsNone(code, out) + self.assertEqual(asked, []) + self.assertIn("installing IQ3_XXS with 46 GB of RAM, as you chose (--low-ram off)", out) + + def test_yes_with_auto_still_stops(self): + code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, "auto", True) + self.assertEqual(code, 1) + self.assertIn("IQ3_XXS needs about 60 GB of RAM; this PC has 46 GB", out) + self.assertIn("--low-ram off --yes", out) # the way to insist + + def test_interactive(self): + for choice, answer, want in (("off", "", None), ("auto", "", 1), ("auto", "y", None), ("off", "n", 1)): + with self.subTest(choice=choice, answer=answer): + code, out, asked = run(setup.confirm_paging, self.MODEL, self.RAM, choice, False, stdin=answer) + self.assertEqual(code, want, out) + self.assertEqual(len(asked), 1) + self.assertIn("[y]" if choice == "off" else "[n]", asked[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_pins.py b/engine/strata/tools/test_setup_pins.py new file mode 100644 index 00000000..4cfe3931 --- /dev/null +++ b/engine/strata/tools/test_setup_pins.py @@ -0,0 +1,238 @@ +"""Tests for setup.py's reproducible installs (#214): the engine of the checkout's own release first (the latest as +the fallback), Hugging Face files at pinned revisions (the current files when a revision is gone), the pinned +requirements file, and an existing install left as it is. Mocked network - nothing is downloaded. + + python -m unittest tools.test_setup_pins +""" +from __future__ import annotations + +import contextlib +import io +import json +import re +import sys +import tempfile +import unittest +import urllib.error +import zipfile +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 + +SHA = re.compile(r"/resolve/[0-9a-f]{40}/") + + +class Response(io.BytesIO): + def __init__(self, body=b"", status=200): + super().__init__(body) + self.status = status + self.headers = {"Content-Length": str(len(body))} + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +def not_found(url): + return urllib.error.HTTPError(url, 404, "Not Found", {}, None) + + +def quiet(fn, *args, **kw): + out = io.StringIO() + with contextlib.redirect_stdout(out): + return fn(*args, **kw), out.getvalue() + + +class HuggingFacePins(unittest.TestCase): + def test_every_model_url_is_pinned(self): + for name, fam in setup.FAMILIES.items(): + for key in ("hf", "mmproj_hf"): + with self.subTest(family=name, key=key): + self.assertRegex(fam[key], SHA) + self.assertNotIn("/resolve/main/", fam[key]) + self.assertRegex(setup.HF, SHA) + + def test_unpinned(self): + url = setup.FAMILIES["swift"]["hf"] + "x.gguf" + self.assertEqual(setup.hf_unpinned(url), + "https://huggingface.co/ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF/resolve/main/x.gguf") + self.assertEqual(setup.hf_unpinned("https://example.com/a/b"), "https://example.com/a/b") + + def test_a_gone_revision_downloads_the_current_file(self): + seen = [] + + def urlopen(req, timeout=None): + seen.append((req.get_method(), req.full_url)) + if "/resolve/main/" not in req.full_url: + raise not_found(req.full_url) + return Response(b"model bytes", status=200) + + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen): + dst = Path(d) / "m.gguf" + _, out = quiet(setup.download, setup.FAMILIES["qwen"]["mmproj_hf"] + "m.gguf", dst) + self.assertEqual(dst.read_bytes(), b"model bytes") + self.assertIn("not at the pinned revision any more", out) + self.assertEqual([m for m, _ in seen], ["HEAD", "HEAD", "GET"]) + self.assertTrue(all("/resolve/main/" in u for _, u in seen[1:])) + + def test_mtp_fetch_is_pinned_and_falls_back(self): + import mtp_fetch + self.assertRegex(mtp_fetch.REPO, SHA) + self.assertIn(mtp_fetch.REVISION, mtp_fetch.REPO) + pinned = mtp_fetch.REPO + + def urlopen(req, timeout=None): + raise not_found(req.full_url) + + try: + with mock.patch.object(mtp_fetch.urllib.request, "urlopen", urlopen), \ + contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(mtp_fetch.resolve_repo(), "https://huggingface.co/Qwen/Qwen3.8-Flash-Next/resolve/main/") + self.assertIn("pinned revision", err.getvalue()) + finally: + mtp_fetch.REPO = pinned + + +class Engine(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + (self.root / "engine").mkdir() + self.patches = [mock.patch.object(setup, "ROOT", self.root), + mock.patch.object(setup, "source_version", lambda: "0.1.31")] + for p in self.patches: + p.start() + + def tearDown(self): + for p in reversed(self.patches): + p.stop() + self.tmp.cleanup() + + def fake_download(self, got): + def download(url, dst, what=None): + got.append(url) + with zipfile.ZipFile(dst, "w") as z: + z.writestr("BUILD.json", json.dumps({"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) + z.writestr(setup.EXE, b"engine") + return download + + def run_get(self, published): + heads, got = [], [] + + def urlopen(req, timeout=None): + heads.append(req.full_url) + if not any(req.full_url.startswith(p) for p in published): + raise not_found(req.full_url) + return Response() + + with mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + mock.patch.object(setup, "download", self.fake_download(got)): + eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") + return eng, out, heads, got + + def test_bases(self): + self.assertEqual(setup.prebuilt_bases(setup.PREBUILT_URL), + ["https://github.com/Niko1221/Strata/releases/download/v0.1.31/", setup.PREBUILT_URL]) + self.assertEqual(setup.prebuilt_bases("https://mirror.example/x"), ["https://mirror.example/x/"]) + + def test_the_checkout_s_release_first(self): + tag = "https://github.com/Niko1221/Strata/releases/download/v0.1.31/" + eng, out, heads, got = self.run_get([tag, setup.PREBUILT_URL]) + self.assertEqual(eng, self.root / "engine") + self.assertEqual(got, [tag + setup.PREBUILT_ASSET]) + self.assertEqual(len(heads), 1) + + def test_latest_when_it_is_not_published(self): + eng, out, heads, got = self.run_get([setup.PREBUILT_URL]) + self.assertEqual(eng, self.root / "engine") + self.assertEqual(got, [setup.PREBUILT_URL + setup.PREBUILT_ASSET]) + self.assertIn("No ready-made engine for v0.1.31", out) + + def test_a_refused_archive_is_not_kept(self): + """PR #324: a refused archive (too old, or no code for the GPU) kept its zip and .done mark, and every later + run reused it ("already downloaded") instead of the published one.""" + for meta in ({"version": "0.1.0", "archs": [89]}, + {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [120]}): + with self.subTest(meta=meta): + def download(url, dst, what=None): + with zipfile.ZipFile(dst, "w") as z: + z.writestr("BUILD.json", json.dumps(meta)) + z.writestr(setup.EXE, b"engine") + setup.mark(dst) + + with mock.patch.object(setup.urllib.request, "urlopen", lambda req, timeout=None: Response()), \ + mock.patch.object(setup, "download", download): + eng, _ = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") + self.assertIsNone(eng) + z = self.root / "engine" / setup.PREBUILT_ASSET + self.assertFalse(z.exists()) + self.assertFalse(z.with_name(z.name + ".done").exists()) + + def test_an_installed_engine_is_kept(self): + (self.root / "engine" / "BUILD.json").write_text(json.dumps( + {"version": ".".join(map(str, setup.MIN_ENGINE)), "archs": [89]})) + (self.root / "engine" / setup.EXE).write_bytes(b"old") + + def urlopen(req, timeout=None): + raise AssertionError("asked the network for an installed engine") + + with mock.patch.object(setup.urllib.request, "urlopen", urlopen): + eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") + self.assertEqual(eng, self.root / "engine") + self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"old") + + +class Requirements(unittest.TestCase): + def test_every_package_is_pinned(self): + lines = setup.requirement_lines() + names = {setup.req_name(x) for x in lines} + for p in setup.PY_PACKAGES: + self.assertIn(p, names) + for x in lines: + self.assertIn("==", x, x) + self.assertEqual(setup.req_name('numpy==2.5.3; python_version >= "3.12"'), "numpy") + self.assertEqual(setup.req_name("charset_normalizer==3"), "charset-normalizer") + + def pip(self, stamp, packages, installed=()): + ran = [] + with tempfile.TemporaryDirectory() as d: + if stamp is not None: + (Path(d) / ".strata-pip.json").write_text(json.dumps(stamp)) + with mock.patch.object(setup.sys, "prefix", d), \ + mock.patch.object(setup, "run", lambda cmd, **kw: ran.append(cmd)), \ + mock.patch.object(setup, "_installed", lambda name: name in installed): + quiet(setup.pip_install, packages, "the packages") + after = json.loads((Path(d) / ".strata-pip.json").read_text()) if ran else stamp + return [c for cmd in ran for c in cmd if "==" in c or c in setup.PY_PACKAGES], after + + def test_fresh_install_gets_every_pin(self): + lines = setup.requirement_lines() + ran, stamp = self.pip(None, lines) + self.assertEqual(ran, lines) + self.assertEqual(sorted(stamp), sorted(lines)) + self.assertEqual(self.pip(stamp, lines)[0], []) # the second run: nothing + + def test_an_install_from_before_the_pins_is_left_alone(self): + lines = setup.requirement_lines() + legacy = sorted(setup.PY_PACKAGES) + ["nvidia-cublas==13.0.2.14"] + deps = {"markupsafe", "certifi", "charset-normalizer", "idna", "urllib3", "colorama"} + self.assertEqual(self.pip(legacy, lines, installed=deps)[0], []) + missing = [p for p in legacy if p != "psutil"] # an older list without psutil + ran, _ = self.pip(missing, lines, installed=deps) + self.assertEqual(ran, ["psutil==7.2.2"]) + + def test_a_changed_pin_is_installed(self): + lines = setup.requirement_lines() + old = [x.replace("tqdm==4.70.1", "tqdm==4.60.0") for x in lines] + ran, _ = self.pip(old, lines) + self.assertEqual(ran, ["tqdm==4.70.1"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_prompts.py b/engine/strata/tools/test_setup_prompts.py new file mode 100644 index 00000000..edfe0171 --- /dev/null +++ b/engine/strata/tools/test_setup_prompts.py @@ -0,0 +1,89 @@ +"""Setup prompts require input or --yes; EOF must not authorize system installs (#393). +No GPU, downloads or installers are used. + + python -m unittest tools.test_setup_prompts +""" +from __future__ import annotations + +import contextlib +import io +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class Prompts(unittest.TestCase): + def test_eof_stops_with_guidance(self): + out = io.StringIO() + with mock.patch("sys.stdin", io.StringIO()), contextlib.redirect_stdout(out): + with self.assertRaises(SystemExit) as cm: + setup.ask("Install them now?", ["y", "n"], "y", False) + self.assertEqual(cm.exception.code, 1) + self.assertIn("Install them now?", out.getvalue()) + self.assertIn("--yes", out.getvalue()) + self.assertIn("Setup stopped", out.getvalue()) + + def test_yes_accepts_the_default_without_reading_input(self): + with mock.patch("builtins.input", side_effect=AssertionError("unexpected prompt")): + for default in ("y", "n"): + with self.subTest(default=default): + self.assertEqual(setup.ask("Install?", ["y", "n"], default, True), default) + + def test_enter_and_explicit_answers(self): + for answer, expected in (("\n", "y"), (" \n", "y"), ("y\n", "y"), (" N \n", "n")): + with self.subTest(answer=answer), mock.patch("sys.stdin", io.StringIO(answer)), \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(setup.ask("Install?", ["y", "n"], "y", False), expected) + + def test_invalid_answer_reprompts_and_preserves_choice_case(self): + out = io.StringIO() + with mock.patch("sys.stdin", io.StringIO("invalid\nyArN\n")), contextlib.redirect_stdout(out): + self.assertEqual(setup.ask("Method?", ["Yarn", "Linear"], "Linear", False), "Yarn") + self.assertIn("please answer one of: Yarn, Linear", out.getvalue()) + + def test_eof_after_invalid_answer_stops(self): + with mock.patch("sys.stdin", io.StringIO("invalid\n")), contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit) as cm: + setup.ask("Install?", ["y", "n"], "y", False) + self.assertEqual(cm.exception.code, 1) + + +class BuildTools(unittest.TestCase): + def test_eof_never_starts_an_installer(self): + for win in (True, False): + with self.subTest(win=win), mock.patch.object(setup, "WIN", win), \ + mock.patch.object(setup, "find_nvcc", return_value=(None, (0, 0))), \ + mock.patch.object(setup, "find_vcvars", return_value=None), \ + mock.patch.object(setup.shutil, "which", side_effect=lambda name: None if name == "g++" else name), \ + mock.patch.object(setup, "run", side_effect=AssertionError("installer started")) as run, \ + mock.patch.object(setup, "download", side_effect=AssertionError("download started")) as download, \ + mock.patch("sys.stdin", io.StringIO()), contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit) as cm: + setup.install_build_tools({"arch": "120"}, False) + self.assertEqual(cm.exception.code, 1) + run.assert_not_called() + download.assert_not_called() + + def test_yes_still_installs_missing_windows_tools(self): + nvcc, vcvars = Path("nvcc"), Path("vcvars64.bat") + with mock.patch.object(setup, "WIN", True), \ + mock.patch.object(setup, "find_nvcc", side_effect=[(None, (0, 0)), (nvcc, (13, 0))]), \ + mock.patch.object(setup, "find_vcvars", side_effect=[None, vcvars, vcvars, vcvars]), \ + mock.patch.object(setup.shutil, "which", return_value="winget"), \ + mock.patch.object(setup, "run") as run, \ + mock.patch("builtins.input", side_effect=AssertionError("unexpected prompt")), \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(setup.install_build_tools({"arch": "120"}, True), (nvcc, vcvars)) + commands = [call.args[0] for call in run.call_args_list] + self.assertEqual(len(commands), 2) + self.assertIn("Microsoft.VisualStudio.2022.BuildTools", commands[0]) + self.assertIn("Nvidia.CUDA", commands[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_risk.py b/engine/strata/tools/test_setup_risk.py new file mode 100644 index 00000000..5d567121 --- /dev/null +++ b/engine/strata/tools/test_setup_risk.py @@ -0,0 +1,414 @@ +"""Tests for the owner's rule in setup.py - it recommends, it never forces: a choice bigger than the recommendation is +kept and its risk said (#406's 256K on 64 GB, #364/#384's two GPUs in the low-RAM mode, #403's RAM budget), and the +stops that stay are the ones a user can confirm (confirm_risk: --yes with an explicit flag, or y). The defaults are +tools/test_setup_golden.py's. Mocked - no GPU, no downloads, nothing written outside a temp folder. + + python -m unittest tools.test_setup_risk +""" +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, card, install # noqa: E402 + + +def arg(cfg, flag): + a = cfg["args"] + return a[a.index(flag) + 1] if flag in a else None + + +def run(fn, *args, stdin=None): + """-> (exit code or None, printed text, questions asked); stdin answers every input() (None: never asked).""" + out, asked, code = io.StringIO(), [], None + + def fake_input(prompt=""): + asked.append(prompt) + if stdin is None: + raise AssertionError(f"asked {prompt!r} with --yes") + return stdin + + with contextlib.redirect_stdout(out), mock.patch("builtins.input", fake_input): + try: + fn(*args) + except SystemExit as e: + code = e.code + return code, out.getvalue(), asked + + +class ConfirmRisk(unittest.TestCase): + """S6: one helper for the stops a user may take on.""" + + def go(self, explicit, yes, stdin=None): + return run(setup.confirm_risk, "it may not fit", explicit, yes, "it does not fit", "a smaller size", + stdin=stdin) + + def test_yes_with_an_explicit_choice_is_consent(self): + code, out, asked = self.go(True, True) + self.assertIsNone(code) + self.assertIn("it may not fit", out) + self.assertEqual(asked, []) + + def test_yes_alone_keeps_the_stop(self): + code, out, asked = self.go(False, True) + self.assertEqual(code, 1) + self.assertIn("it does not fit", out) + self.assertIn("a smaller size", out) + + def test_interactive_default_is_no(self): + for explicit in (True, False): + code, out, asked = self.go(explicit, False, stdin="") + self.assertEqual(code, 1) + self.assertIn("[n]", asked[0]) + self.assertIsNone(self.go(explicit, False, stdin="y")[0]) + + def test_paging_with_an_explicit_model(self): + code, out, asked = run(setup.confirm_paging, "IQ3_XXS", 54, "auto", True, True) + self.assertIsNone(code, out) + self.assertIn("installing IQ3_XXS with 54 GB of RAM, as you chose (--model)", out) + + +class Context(unittest.TestCase): + """S1 (#406 #364): the RAM rule recommends, an explicit or picked context is kept with a note.""" + RAM64, GPU32 = PROFILES["64GB-1x32GB"] + + def test_the_ram_rule(self): + self.assertEqual(setup.ram_ctx("IQ3_S", 63.7), 131072) + self.assertEqual(setup.ram_ctx("IQ3_XXS", 63.7), 131072) + self.assertEqual(setup.ram_ctx("IQ3_XXS", 95.8), 524288) # 43 + 7.2 + 24 GB fits 96 + self.assertEqual(setup.ram_ctx("IQ3_S", 76.5), 131072) + self.assertEqual(setup.ram_ctx("IQ3_S", 78.5), 262144) + self.assertEqual(setup.ram_ctx("Q2_0", 31.9), 524288) # other sizes: no RAM rule + self.assertEqual(setup.ram_ctx("IQ3_XXS", 31.9, low_ram=True), 524288) # the KV cache is in VRAM there + self.assertIsNone(setup.ctx_ram_need("IQ3_XXS", 262144, low_ram=True)) + self.assertAlmostEqual(setup.ctx_ram_need("IQ3_S", 262144), 77.9, places=1) + + def test_an_explicit_256k_is_kept(self): + code, out, cfg, _ = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start", + "--context", "262144"]) + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + self.assertNotIn("--rope-scaling", cfg["args"]) + self.assertIn("256K with IQ3_S needs ~78 GB of RAM by setup's estimate", out) + self.assertIn("this PC has 64. Kept as you chose: it may be slower or run out of RAM under load. 128K is the " + "recommended size.", out) + + def test_a_picked_256k_is_kept_and_the_menu_says_the_risk(self): + code, out, cfg, asked = install(self.RAM64, self.GPU32, ["--family", "qwen", "--model", "IQ3_S", "--no-start"], + answers={"Context?": "5"}) + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + self.assertIn("256K tokens (needs ~78 GB RAM, this PC has 64: may run out of memory)", out) + self.assertIn("128K tokens (recommended for your GPU)\n", out) + self.assertIn("Kept as you chose", out) + + def test_low_ram_mode_keeps_262k_without_a_ram_note(self): + ram, found = PROFILES["32GB-2x24GB"] # #364 + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start", + "--context", "262144"]) + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + self.assertNotIn("Kept as you chose: it may be slower", out) + + def test_the_earlier_install_keeps_its_context(self): + """An update (a new copy of Strata) set up like the earlier install keeps its 256K instead of capping it.""" + with tempfile.TemporaryDirectory() as d: + prev = Path(d) / "strata-iq3_s.json" + prev.write_text(json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080})) + started = mock.Mock(return_value=0) + code, out, cfg, _ = install(self.RAM64, self.GPU32, [], extra=[ + mock.patch.object(setup, "previous_config", lambda *a: prev), + mock.patch.object(setup, "start", started)]) + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + self.assertIn("Kept as you chose", out) + self.assertTrue(started.called) + + +class BrokenEarlierConfig(unittest.TestCase): + """#459: a new copy of Strata set up like an earlier install skips an earlier config that does not parse (an + empty strata-*.json crashed START-HERE with JSONDecodeError) and goes on as a fresh install; configs are written + whole (a temporary file moved over the old one).""" + RAM64, GPU32 = PROFILES["64GB-1x32GB"] + + def setup_with(self, files): + with tempfile.TemporaryDirectory() as d: + for i, (name, text) in enumerate(files): # in order, oldest first + (Path(d) / name).write_text(text, encoding="utf-8") + os.utime(Path(d) / name, (1_700_000_000 + i, 1_700_000_000 + i)) + return install(self.RAM64, self.GPU32, [], extra=[ + mock.patch.object(setup, "other_installs", lambda settings: [Path(d)]), + mock.patch.object(setup, "start", mock.Mock(return_value=0))]) + + def test_an_empty_config_is_skipped(self): + for text, why in (("", "the file is empty"), ("{\"args\": [", "not valid JSON"), ("[1]", "not a JSON object")): + with self.subTest(text=text): + code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", text)]) + self.assertEqual(code, 0, out) + self.assertIn("skipped the earlier config ", out) + self.assertIn(f"strata-iq3_s.json ({why}): setting this copy up without it", out) + self.assertNotIn("Found your earlier install", out) + self.assertIsNotNone(cfg) # the fresh install's config + + def test_the_newest_readable_config_is_used(self): + good = json.dumps({"args": ["--max-context", "262144", "--kv", "int8"], "port": 8080}) + code, out, cfg, _ = self.setup_with([("strata-iq3_s.json", good), ("strata-q2_0.json", "")]) + self.assertEqual(code, 0, out) + self.assertIn("strata-q2_0.json (the file is empty)", out) + self.assertIn("Found your earlier install", out) + self.assertIn("(iq3_s)", out) + self.assertEqual(arg(cfg, "--max-context"), "262144") + + def test_write_config_leaves_no_partial_file(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-iq3_s.json" + p.write_text("old", encoding="utf-8") + setup.write_config(p, {"args": ["--kv", "int8"]}) + self.assertEqual(p.read_text(encoding="utf-8"), json.dumps({"args": ["--kv", "int8"]}, indent=1)) + self.assertEqual([f.name for f in Path(d).iterdir()], ["strata-iq3_s.json"]) # no .tmp left + with mock.patch.object(Path, "write_text", side_effect=OSError(28, "No space left on device")): + with self.assertRaises(OSError): + setup.write_config(p, {"args": []}) + self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"args": ["--kv", "int8"]}) # kept whole + + +class LowRamGpus(unittest.TestCase): + """S2/S3 (#364 #384): one GPU recommended in the low-RAM mode, all of them when asked for.""" + + def test_explicit_gpus_are_kept_with_the_mapped_variant(self): + for prof, model in (("32GB-2x24GB", "IQ3_XXS"), ("32GB-2x24GB", "Q2_0"), ("47GB-2x16GB", "IQ3_XXS")): + with self.subTest(prof=prof, model=model): + ram, found = PROFILES[prof] + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", model, "--no-start", + "--gpus", "0,1"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["layer_split"], "auto") + self.assertIn("--mmap-experts", cfg["args"]) + self.assertNotIn("--resident-experts", cfg["args"]) + self.assertIn("as you chose (--gpus)", out) + self.assertIn("RAM can fill up to 0 free", out) + self.assertIn("low-RAM mode on 2 GPUs", out) + + def test_the_share_counts_every_card(self): + ram, found = PROFILES["47GB-2x16GB"] # #384: 2 x 16 GB, 47 GB, IQ3_XXS at 64K + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "IQ3_XXS", "--no-start", + "--gpus", "0,1"]) + one = setup.low_ram_gpu_gb("IQ3_XXS", 15.9, 65536, "int8") + self.assertIn(f"the GPUs hold ~{100 * 2 * one / setup.MODELS['IQ3_XXS']['arena_gb']:.0f}% of them", out) + + def test_asked_and_answered_two(self): + ram, found = PROFILES["32GB-2x24GB"] + code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], + answers={"Low-RAM mode: which GPUs?": "2"}) + self.assertEqual(code, 0, out) + self.assertTrue(any("Low-RAM mode: which GPUs? [1]" in q for q in asked), asked) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--mmap-experts", cfg["args"]) + self.assertIn("1) GPU 0 (NVIDIA GeForce RTX 3090, 24 GB) only", out) + + def test_yes_and_enter_keep_one_gpu(self): + ram, found = PROFILES["32GB-2x24GB"] + for answers in (None, ""): + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start"], + answers=answers) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 0) + self.assertIn("--resident-experts", cfg["args"]) + + def test_low_ram_resident_with_gpus(self): + ram, found = PROFILES["32GB-2x24GB"] + code, out, cfg, _ = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", "--gpus", "0,1", + "--low-ram", "resident"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("--mmap-experts", cfg["args"]) + self.assertIn("--low-ram resident has no layer split yet", out) + + def test_low_ram_resident_alone_keeps_one_gpu_without_asking(self): + ram, found = PROFILES["32GB-2x24GB"] + code, out, cfg, asked = install(ram, found, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--low-ram", "resident"], answers="") + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 0) + self.assertFalse(any("Low-RAM mode" in q for q in asked), asked) + + +class StartOnSeveralGpus(unittest.TestCase): + """A resident low-RAM config started on several GPUs reads the experts through the file cache (#364 #384).""" + + def test_split_mmap(self): + cfg = {"args": ["--pack", "p", "--resident-experts", "--kv", "int8"]} + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertTrue(setup.split_mmap(cfg)) + self.assertFalse(setup.split_mmap(cfg)) + self.assertFalse(setup.split_mmap({"args": ["--mmap-experts"]})) + self.assertEqual(cfg["args"], ["--pack", "p", "--mmap-experts", "--kv", "int8"]) + self.assertIn("no layer split yet", out.getvalue()) + + def offer(self, args, stdin): + found = PROFILES["32GB-2x24GB"][1] + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-q2_0.json" + cfg = {"args": list(args)} + with mock.patch.object(setup, "gpus", lambda: found), \ + mock.patch.object(setup, "engine_runs_on", lambda g: True): + code, out, asked = run(setup.offer_together, p, cfg, stdin is None, stdin=stdin) + return code, out, asked, json.loads(p.read_text()) + + def test_offer_together_recommends_one_gpu_for_a_resident_config(self): + code, out, asked, cfg = self.offer(["--resident-experts"], None) # --yes: the recommendation + self.assertIsNone(code, out) + self.assertNotIn("gpu", cfg) + self.assertEqual(cfg["args"], ["--resident-experts"]) + code, out, asked, cfg = self.offer(["--resident-experts"], "y") + self.assertIn("[n]", asked[0]) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"], ["--mmap-experts"]) + code, out, asked, cfg = self.offer(["--mmap-experts"], None) # other configs: as before + self.assertEqual(cfg["gpu"], [0, 1]) + + def test_start_with_gpus(self): + found = PROFILES["32GB-2x24GB"][1] + with tempfile.TemporaryDirectory() as d: + exe = Path(d) / "strata.exe" + exe.write_bytes(b"") + p = Path(d) / "strata-q2_0.json" + p.write_text(json.dumps({"exe": str(exe), "args": ["--resident-experts"], "gpu": 0, "gpus_asked": True})) + call = mock.Mock(return_value=0) + with mock.patch.object(setup, "gpus", lambda: found), \ + mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \ + mock.patch.object(setup, "is_wsl", lambda: False), \ + mock.patch.object(setup.subprocess, "call", call): + code, out, _ = run(setup.start, p, None, [0, 1], False, True) + cfg = json.loads(p.read_text()) + self.assertIsNone(code, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertEqual(cfg["args"], ["--mmap-experts"]) + self.assertIn("no layer split yet", out) + self.assertTrue(call.called) + + +class SmallCard(unittest.TestCase): + """S9: a card under 8 GB named with --gpus is a risk to confirm, not a stop.""" + FOUND = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), card(1, "NVIDIA GeForce RTX 2060", 6.0, "75")] + + def test_named_with_yes(self): + code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + self.assertIn("GPU 1 (NVIDIA GeForce RTX 2060) has 6 GB of VRAM", out) + self.assertIn("is used together with the others, as you chose", out) + + def test_named_and_enter_stops(self): + code, out, cfg, asked = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1"], answers="") + self.assertEqual(code, 1) + self.assertTrue(any("Use it anyway?" in q for q in asked), asked) + + def test_not_named_is_not_offered(self): + code, out, cfg, _ = install(63.7, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 0) # one card: as before + + +class SplitShortCard(unittest.TestCase): + """#448: a second card too small to lend a split's prompt chunk: the first card alone recommended, the pair kept + when named.""" + FOUND = [card(0, "NVIDIA RTX PRO 4500 Blackwell", 31.8, "120"), card(1, "NVIDIA GeForce RTX 3080", 10.0, "86")] + + def test_rule(self): + self.assertEqual([g["index"] for g in setup.split_short(self.FOUND)], [1]) + self.assertEqual(setup.split_short(PROFILES["32GB-2x24GB"][1]), []) + self.assertEqual(setup.split_short(PROFILES["47GB-2x16GB"][1]), []) + eights = [card(i, "NVIDIA GeForce RTX 3070", 8.0, "86") for i in range(2)] + self.assertEqual(setup.split_short(eights), []) # neither card alone reads more + + def test_yes_takes_the_first_card(self): + code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 0) + self.assertIn("too small to lend a split its prompt buffers", out) + + def test_named_pair_is_kept(self): + code, out, cfg, _ = install(127.8, self.FOUND, ["--family", "qwen", "--model", "Q2_0", "--no-start", + "--gpus", "0,1"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], [0, 1]) + + def test_offer_together_defaults_to_one(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-q2_0.json" + with mock.patch.object(setup, "gpus", lambda: self.FOUND), \ + mock.patch.object(setup, "engine_runs_on", lambda g: True): + code, out, asked = run(setup.offer_together, p, {"args": ["--mmap-experts"]}, True) + cfg = json.loads(p.read_text()) + self.assertIsNone(code, out) + self.assertNotIn("gpu", cfg) + self.assertIn("#448", out) + + +class RamFloor(unittest.TestCase): + """S7: less RAM than the smallest model needs: a stop with --yes alone, a risk with --model.""" + FOUND = [card(0, "NVIDIA GeForce RTX 3060", 8.0, "86")] + + def test_yes_alone_stops(self): + code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "qwen", "--no-start"]) + self.assertEqual(code, 1) + self.assertIn("--model NAME --yes", out) + + def test_an_explicit_model_goes_on(self): + code, out, cfg, _ = install(19.9, self.FOUND, ["--family", "coder", "--model", "IQ1_M", "--no-start"]) + self.assertEqual(code, 0, out) + self.assertIn("going on with 20 GB of RAM, as you chose", out) + + +class KvStreaming(unittest.TestCase): + """8: --kv-streaming on|off|auto (auto: the RAM test, as before).""" + RAM, FOUND = PROFILES["64GB-1x32GB"] + + def go(self, model, *flags): + return install(self.RAM, self.FOUND, ["--family", "qwen", "--model", model, "--no-start", *flags]) + + def test_off(self): + code, out, cfg, _ = self.go("IQ3_XXS", "--kv-streaming", "off") + self.assertEqual(code, 0, out) + self.assertNotIn("--kv-resident", cfg["args"]) + self.assertIn("KV streaming off, as you chose", out) + + def test_on_past_the_ram_test(self): + code, out, cfg, _ = self.go("IQ3_S", "--kv-streaming", "on") # auto leaves it off on 64 GB + self.assertEqual(code, 0, out) + self.assertEqual(arg(cfg, "--kv-resident"), "32768") + self.assertIn("Kept as you chose (--kv-streaming on)", out) + + def test_on_where_it_cannot(self): + code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--kv", "k8v4") + self.assertNotIn("--kv-resident", cfg["args"]) + self.assertIn("it refuses the pair", out) + code, out, cfg, _ = self.go("Q2_0", "--kv-streaming", "on", "--context", "32768") + self.assertNotIn("--kv-resident", cfg["args"]) + self.assertIn("a context under 64K is not streamed", out) + + def test_budget_flag_on_another_size(self): + code, out, cfg, _ = self.go("Q2_0", "--resident-budget-gib", "30") + self.assertEqual(code, 0, out) + self.assertNotIn("--resident-budget-gib", cfg["args"]) + self.assertIn("--resident-budget-gib is for UD-Q4_K_XL", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_rope.py b/engine/strata/tools/test_setup_rope.py new file mode 100644 index 00000000..85b47f98 --- /dev/null +++ b/engine/strata/tools/test_setup_rope.py @@ -0,0 +1,121 @@ +"""Tests for setup.py's automatic rope configuration (§4 + §6): the factor derives from the FINAL context +actually served - RAM reductions first, then final / trained 262144 clamped at 1 - explicit +--rope-scaling/--rope-scale choices win verbatim, an explicit none is refused past the trained range, and +nothing turns on by itself inside it. Pure functions - no GPU, no downloads, no prompts. + + python -m unittest tools.test_setup_rope +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class DerivedFactor(unittest.TestCase): + """The formula itself: max(1.0, final / trained).""" + + def test_the_task_table(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # below the trained range: clamped at 1 + self.assertEqual(setup.derived_factor(262144), 1.0) # exactly the trained range: 1 + self.assertEqual(setup.derived_factor(393216), 1.5) # 384K + self.assertEqual(setup.derived_factor(524288), 2.0) # 512K + + def test_free_form_contexts_get_the_exact_ratio(self): + # /262144 = /2**18 is exact in binary floating point, so no dust + self.assertEqual(setup.derived_factor(600000), 600000 / 262144) + self.assertGreater(setup.derived_factor(600000), 2.0) + + def test_the_clamp_is_what_keeps_128k_at_one(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # NOT the raw 0.5 + + +class ResolveRope(unittest.TestCase): + # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) + def test_omitted_384k_gets_yarn_and_1_5(self): + self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) + + def test_omitted_512k_gets_yarn_and_2(self): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_deterministic_for_yes(self): + # --yes never prompts, so the resolution must be a pure function of its inputs + for _ in range(3): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_omitted_method_with_an_explicit_factor(self): + # --rope-scale alone still expresses the intent to extend: the method defaults, the factor is kept + self.assertEqual(setup.resolve_rope(393216, None, 1.8), ("yarn", 1.8)) + + # ---- explicit selections are respected, verbatim + def test_explicit_method_gets_the_derived_factor(self): + self.assertEqual(setup.resolve_rope(524288, "linear", None), ("linear", 2.0)) + + def test_explicit_method_and_factor_are_kept_verbatim(self): + self.assertEqual(setup.resolve_rope(393216, "linear", 2.0), ("linear", 2.0)) + self.assertEqual(setup.resolve_rope(524288, "yarn", 1.5), ("yarn", 1.5)) + + def test_an_explicit_override_survives_a_context_reduction(self): + # §4: the RAM check reduced the final context to 128K - a user-supplied factor is NOT recalculated + self.assertEqual(setup.resolve_rope(131072, "yarn", 2.0), ("yarn", 2.0)) + self.assertEqual(setup.resolve_rope(131072, "linear", 1.75), ("linear", 1.75)) + + # ---- an explicit none past the trained range is refused with an explanation, not overridden + def test_explicit_none_past_trained_is_refused(self): + with self.assertRaises(ValueError) as cm: + setup.resolve_rope(524288, "none", None) + self.assertIn("262144", str(cm.exception)) + self.assertIn("yarn", str(cm.exception)) # the message names the way out + + def test_explicit_none_within_trained_is_the_stock_model(self): + self.assertEqual(setup.resolve_rope(131072, "none", None), (None, None)) + + # ---- inside the trained range nothing turns on by itself; a chosen method gets factor 1 + def test_omitted_within_trained_adds_nothing(self): + self.assertEqual(setup.resolve_rope(262144, None, None), (None, None)) + self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) + + def test_a_scale_alone_within_trained_is_rejected(self): + with self.assertRaises(ValueError): + setup.resolve_rope(131072, None, 2.0) + + def test_a_chosen_method_within_trained_gets_factor_1(self): + # no more unconditional factor 2: 1 = the trained angles, no automatic expansion + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + self.assertEqual(setup.resolve_rope(262144, "linear", None), ("linear", 1.0)) + + # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so the factor matches the + # context actually served - the 512K-on-IQ3_S-with-under-90-GB case from the task, end to end + def test_512k_on_a_small_ram_machine_resolves_to_128k_factor_1(self): + # asked 524288 with --rope-scaling yarn and no factor; the RAM check brings the final context to 131072 + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + + def test_no_reduction_384k_and_512k_resolve_as_documented(self): + self.assertEqual(setup.resolve_rope(393216, "yarn", None), ("yarn", 1.5)) + self.assertEqual(setup.resolve_rope(524288, "yarn", None), ("yarn", 2.0)) + + # ---- the short-context item's own table: no factor-2 fallback inside the trained window, for either + # method, with the explicit override column kept verbatim + def test_the_short_context_table(self): + cases = [ + (131072, None, "yarn", 1.0), # --context 131072 --rope-scaling yarn + (262144, None, "yarn", 1.0), # --context 262144 --rope-scaling yarn + (393216, None, "yarn", 1.5), + (524288, None, "yarn", 2.0), + (131072, 2.0, "yarn", 2.0), # --rope-scale 2 is kept inside the window + ] + for ctx, scale, method, want in cases: + self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, want), f"ctx {ctx}") + + def test_linear_gets_the_same_rule_as_yarn(self): + # the old fallback applied to both methods, so the fix must too + self.assertEqual(setup.resolve_rope(131072, "linear", None), ("linear", 1.0)) + self.assertEqual(setup.resolve_rope(393216, "linear", None), ("linear", 1.5)) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_setup_unsloth.py b/engine/strata/tools/test_setup_unsloth.py new file mode 100644 index 00000000..e6bd13fe --- /dev/null +++ b/engine/strata/tools/test_setup_unsloth.py @@ -0,0 +1,324 @@ +"""Tests for setup.py's experimental Unsloth UD-Q4_K_XL choice (docs/UNSLOTH_Q4.md): the four pinned shards with +their sizes and SHA-256, the RAM budget from the PC's RAM, the pack with --compat-bf16 (never experts.bin), the +engine version it needs, one GPU, no images. Mocked - no GPU, no downloads, nothing written outside a temp folder. + + python -m unittest tools.test_setup_unsloth +""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import json +import sys +import tempfile +import types +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + +M = "UD-Q4_K_XL" +REV = "38bb39ee97821de2c9009abb7e93950eec396e66" + + +class Pins(unittest.TestCase): + def test_the_four_shards(self): + fam = setup.FAMILIES["unsloth"] + names = [fam["file"].format(q=M, i=i) for i in range(1, fam["shards"] + 1)] + self.assertEqual(names, list(setup.UNSLOTH_SHARDS)) + self.assertEqual(sum(b for b, _ in setup.UNSLOTH_SHARDS.values()), 111334654784) + for _, sha in setup.UNSLOTH_SHARDS.values(): + self.assertRegex(sha, r"^[0-9a-f]{64}$") + self.assertEqual(fam["hf"].format(q=M), + f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/") + self.assertEqual(setup.MODELS[M]["families"], ("unsloth",)) # no other family lists it + self.assertTrue(fam["experimental"]) + self.assertEqual(list(setup.FAMILIES)[0], "qwen") # not the default choice + + def test_not_in_the_other_families(self): + for f in ("qwen", "swift", "coder"): + self.assertNotIn(M, [m for m in setup.MODELS if f in setup.MODELS[m].get("families", ("qwen", "swift"))]) + + +class Budget(unittest.TestCase): + def test_ram_less_24(self): + self.assertEqual(setup.resident_budget_gib(M, 63.7), 40) # this PC (64 GB): the measured setting + self.assertEqual(setup.resident_budget_gib(M, 47.8), 24) + self.assertEqual(setup.resident_budget_gib(M, 96), 71) # at most all of the experts (77 GB = 71.7 GiB) + self.assertEqual(setup.resident_budget_gib(M, 256), 71) + self.assertEqual(setup.resident_budget_gib(M, 20), 8) # the floor + self.assertEqual(setup.resident_budget_gib(M, 63.7, 1.7), 38) # a KV cache streamed to RAM comes out of it + + +def quiet(fn, *args): + """-> (exit code or None, printed text).""" + out = io.StringIO() + code = None + with contextlib.redirect_stdout(out): + try: + code = fn(*args) + except SystemExit as e: + code = e.code + return code, out.getvalue() + + +class Sha256(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.f = Path(self.tmp.name) / "x-00002-of-00004.gguf" + self.f.write_bytes(b"strata" * 1000) + self.sha = hashlib.sha256(self.f.read_bytes()).hexdigest() + + def tearDown(self): + self.tmp.cleanup() + + def test_good_file_marked_once(self): + code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) + self.assertIsNone(code, out) + self.assertIn(f"sha256 {self.sha}", self.f.with_name(self.f.name + ".done").read_text()) + with mock.patch("hashlib.sha256", side_effect=AssertionError("hashed again")): + code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) # the mark says it was checked + self.assertIsNone(code, out) + + def test_a_download_mark_alone_is_not_enough(self): + setup.mark(self.f) # the download's finish mark (a date) + with mock.patch("hashlib.sha256", wraps=hashlib.sha256) as h: + code, out = quiet(setup.verify_sha256, self.f, 6000, self.sha) + self.assertIsNone(code, out) + self.assertTrue(h.called) + + def test_wrong_hash_deletes_it(self): + setup.mark(self.f) + code, out = quiet(setup.verify_sha256, self.f, 6000, "0" * 64) + self.assertEqual(code, 1) + self.assertIn("wrong SHA-256", out) + self.assertFalse(self.f.exists()) + self.assertFalse(self.f.with_name(self.f.name + ".done").exists()) # downloaded again next time + + def test_wrong_size(self): + code, out = quiet(setup.verify_sha256, self.f, 6001, self.sha) + self.assertEqual(code, 1) + self.assertIn("6,000 bytes, not 6,001", out) + self.assertTrue(self.f.exists()) + + +class Config(unittest.TestCase): + def test_choices_from_config(self): + with tempfile.TemporaryDirectory() as t: + for name, family, model in (("strata-unsloth-ud-q4_k_xl.json", "unsloth", M), + ("strata-swift-iq3_xxs.json", "swift", "IQ3_XXS"), + ("strata-iq3_s.json", "qwen", "IQ3_S"), + ("strata-coder-iq1_m.json", "coder", "IQ1_M")): + p = Path(t) / name + p.write_text(json.dumps({"args": ["--max-context", "8192"]})) + ch = setup.choices_from_config(p) + self.assertEqual((ch["family"], ch["model"]), (family, model), name) + + +class FakeGGUF: + """gguf_reader.GGUFFile: shard 2 holds the PLE table.""" + def __init__(self, path): + names = ["per_layer_token_embd.weight"] if "00002-of" in str(path) else ["blk.0.ffn_up_exps.weight"] + self.tensors = [types.SimpleNamespace(name=n) for n in names] + + +class Main(unittest.TestCase): + """setup.main() for the Unsloth choice, every outside effect mocked.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.t = Path(self.tmp.name) + (self.t / "data" / "mtp" / "rt").mkdir(parents=True) + (self.t / "data" / "mtp" / "rt" / "experts.bin").write_bytes(b"") + self.downloads, self.runs, self.verified = [], [], [] + + def tearDown(self): + self.tmp.cleanup() + + def main(self, argv, ram=63.7, version="0.1.32", n_gpus=1, model=True, amd=(), free=500.0): + eng = self.t / "engine" + eng.mkdir(exist_ok=True) + (eng / "BUILD.json").write_text(json.dumps({"version": version, "source": "local"})) + found = [{"index": i, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.9, "arch": "120", "driver": "580.97"} + for i in range(n_gpus)] + + def fake_download(url, dst, what=None): + self.downloads.append(url) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_bytes(b"") + setup.mark(dst) + + def fake_run(cmd, *a, **k): + self.runs.append([str(x) for x in cmd]) + + patches = [ + mock.patch.object(setup, "ROOT", self.t), + mock.patch.object(setup, "GPU_PICK", None), + mock.patch.object(setup, "data_folder", lambda d: (self.t / "data", [])), + mock.patch.object(setup, "installed_configs", lambda: []), + mock.patch.object(setup, "gpus", lambda: found), + mock.patch.object(setup, "amd_gpus", lambda *a: list(amd)), + mock.patch.object(setup, "ram_gb", lambda: ram), + mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, True)), + mock.patch.object(setup, "page_file_gb", lambda: 16.0), + mock.patch.object(setup, "free_gb", lambda p: free), + mock.patch.object(setup, "pip_install", lambda *a, **k: None), + mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"), + mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), + mock.patch.object(setup, "download", fake_download), + mock.patch.object(setup, "check_shards", lambda shards: None), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), + mock.patch.object(setup, "run", fake_run), + mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), + mock.patch.object(setup, "write_run_script", lambda tag, cfg, port: self.t / f"start-{tag}.bat"), + mock.patch.object(setup, "saved_calibration", lambda cfg: None), + mock.patch.object(setup, "start", mock.Mock(side_effect=AssertionError("started"))), + mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FakeGGUF)}), + mock.patch.object(sys, "argv", ["setup.py", "--family", "unsloth", *(["--model", M] if model else []), + "--yes", "--no-start", + "--models-dir", str(self.t / "models"), *argv]), + mock.patch("builtins.input", mock.Mock(side_effect=AssertionError("asked"))), + ] + with contextlib.ExitStack() as st: + for p in patches: + st.enter_context(p) + code, out = quiet(setup.main) + cfg = self.t / "strata-unsloth-ud-q4_k_xl.json" + return code, out, (json.loads(cfg.read_text()) if cfg.exists() else None) + + def test_install(self): + code, out, cfg = self.main(["--context", "8192"]) + self.assertEqual(code, 0, out) + self.assertIn("EXPERIMENTAL", out) + base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV}/UD-Q4_K_XL/" + self.assertEqual(self.downloads, [base + n for n in setup.UNSLOTH_SHARDS]) # no image encoder + self.assertEqual([v[0] for v in self.verified], list(setup.UNSLOTH_SHARDS)) + self.assertEqual([v[1:] for v in self.verified], list(setup.UNSLOTH_SHARDS.values())) + packs = [r for r in self.runs if r[1].endswith("iq_pack.py")] + self.assertEqual(len(packs), 1, self.runs) + self.assertIn("--compat-bf16", packs[0]) + self.assertNotIn("--experts-bin", packs[0]) + self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith("UD-Q4_K_XL-00001-of-00004.gguf")) + args = cfg["args"] + self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") + self.assertTrue(args[args.index("--native") + 1].endswith("-00001-of-00004.gguf")) + for flag in ("--ple-gguf", "--mmap-experts", "--resident-experts", "--vision", "--control-vector-scaled", + "--kv-resident"): + self.assertNotIn(flag, args) + self.assertEqual(args[args.index("--max-context") + 1], "8192") + self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-ud-q4_k_xl") + self.assertNotIn("vision", cfg) + + def test_recommended_context_on_12_gb(self): + code, out, cfg = self.main([]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["args"][cfg["args"].index("--max-context") + 1], "8192") + + def test_more_ram_bigger_budget(self): + code, out, cfg = self.main(["--context", "8192"], ram=95.8) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "71") + + def test_kv_streaming_comes_out_of_the_budget(self): + code, out, cfg = self.main(["--context", "131072"]) + self.assertEqual(code, 0, out) + args = cfg["args"] + self.assertIn("--kv-resident", args) + kv_gb = 131072 * 13 * 1056 / 1e9 + self.assertEqual(args[args.index("--resident-budget-gib") + 1], str(40 - int(-(-kv_gb // 1)))) + + def test_old_engine_stops_before_the_download(self): + code, out, cfg = self.main(["--context", "8192"], version="0.1.31") + self.assertEqual(code, 1) + self.assertIn("needs engine 0.1.32 or newer; this one is 0.1.31", out) + self.assertEqual(self.downloads, []) + self.assertIsNone(cfg) + + def test_too_little_ram(self): + code, out, cfg = self.main(["--context", "8192"], ram=31.9, model=False) # --yes alone: still a stop + self.assertEqual(code, 1) + self.assertIn("needs 48 GB of RAM or more", out) + self.assertIn("--model UD-Q4_K_XL --yes", out) # the way to insist + self.assertEqual(self.downloads, []) + + def test_amd_is_asked_before_the_download(self): + """#429: UD-Q4_K_XL has not run on AMD (CUDA-only prompt kernels): --yes alone stops before the 111 GB + download, saying why; it is not refused outright (the owner's rule: --model with --yes goes on).""" + r9700 = [{"index": 0, "name": "AMD Radeon AI PRO R9700", "vram_gb": 31.9, "arch": "gfx1201", + "driver": "amdgpu"}] + code, out, cfg = self.main(["--context", "8192", "--backend", "hip"], model=False, amd=r9700) + self.assertEqual(code, 1, out) + self.assertIn("has not been run on AMD cards yet", out) + self.assertIn("--model UD-Q4_K_XL --yes", out) + self.assertEqual(self.downloads, []) + + def test_resumed_download_needs_room_for_the_rest_only(self): + """#425: the disk check counts the finished shards and .part files already there (sizes scaled down: a + 2 MB "model" with 1.5 MB on the disk, 8 GB of other room needed, 8.001 GB free).""" + d = self.t / "models" / "unsloth-UD-Q4_K_XL" + d.mkdir(parents=True) + (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) + with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.002}): + code, out, cfg = self.main(["--context", "8192"], free=8.001) + self.assertNotIn("not enough free disk space", out) + self.assertEqual(code, 0, out) + for f in d.iterdir(): # the first run "downloaded" them + f.unlink() + (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) + with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing: no room + code, out, cfg = self.main(["--context", "8192"], free=8.001) + self.assertEqual(code, 1) + self.assertIn("not enough free disk space", out) + + def test_too_little_ram_with_an_explicit_model_installs(self): + """S6 (the owner's rule): --model with --yes is the consent; the risk is said.""" + code, out, cfg = self.main(["--context", "8192"], ram=31.9) + self.assertEqual(code, 0, out) + self.assertIn("needs 48 GB of RAM or more; this PC has 32 GB", out) + self.assertIn("installing UD-Q4_K_XL with 32 GB of RAM, as you chose", out) + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "8") + + def test_budget_flag(self): + """S4: --resident-budget-gib N is kept; more than the recommendation says what it risks.""" + code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "48"]) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "48") + self.assertIn("more than setup recommends for this PC (40 GiB", out) + self.assertIn("Kept as you chose", out) + code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "32.5"]) + self.assertEqual(cfg["args"][cfg["args"].index("--resident-budget-gib") + 1], "32.5") + self.assertNotIn("more than setup recommends", out) + + def test_budget_flag_with_kv_streaming_is_kept(self): + code, out, cfg = self.main(["--context", "131072", "--resident-budget-gib", "40"]) + self.assertEqual(code, 0, out) + args = cfg["args"] + self.assertIn("--kv-resident", args) + self.assertEqual(args[args.index("--resident-budget-gib") + 1], "40") # not 38: the user's number + self.assertIn("come on top of your 40 GiB RAM budget", out) + + def test_budget_flag_needs_a_positive_number(self): + with contextlib.redirect_stderr(io.StringIO()): + code, out, cfg = self.main(["--context", "8192", "--resident-budget-gib", "0"]) + self.assertEqual(code, 2) # argparse: N > 0 + self.assertIsNone(cfg) + + def test_one_gpu_and_no_images(self): + code, out, cfg = self.main(["--context", "8192", "--gpus", "0,1", "--vision", "yes", "--low-ram", "on"], + n_gpus=2) + self.assertEqual(code, 0, out) + self.assertIn("runs on one GPU", out) + self.assertIn("images are not available with UD-Q4_K_XL", out) + self.assertIn("--low-ram on does not apply", out) + self.assertNotIn("layer_split", cfg) + self.assertNotIn("--vision", cfg["args"]) + self.assertNotIn("--mmap-experts", cfg["args"]) + self.assertFalse(any("--experts-bin" in r for r in self.runs)) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/test_shards.py b/engine/strata/tools/test_shards.py new file mode 100644 index 00000000..6d8ba397 --- /dev/null +++ b/engine/strata/tools/test_shards.py @@ -0,0 +1,119 @@ +"""A missing or short model shard is named with its numbers, and a pack's verify reads back the source hash +its manifest recorded - over a minimal GGUF written here (no download, no model, no GPU). + + python -m unittest tools.test_shards +""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import json +import struct +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) +import setup as S # noqa: E402 +import strata_pack # noqa: E402 + + +class Stop(Exception): + """setup.fail(), caught instead of exiting: the message is what the test reads.""" + + +def write_gguf(path: Path, names=("blk.0.attn_q.weight", "blk.0.attn_k.weight")) -> int: + """A GGUF v3 of F32[8] tensors 32 bytes apart from a 32-byte-aligned data start; returns its whole length.""" + b = bytearray(struct.pack(" int: + s = socket.socket() + s.bind(("127.0.0.1", 0)) + p = s.getsockname()[1] + s.close() + return p + + +def wait_for(cond, seconds=30.0): + end = time.time() + seconds + while time.time() < end: + if cond(): + return True + time.sleep(0.1) + return cond() + + +FAKE_HW = {"os": "TestOS 1", "ram_gb": 64.0, "cpu": {"name": "Fake CPU", "cores": 12, "avx2": True, "avx512": True}, + "gpus": [{"index": 0, "name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.9, "arch": "120", "vendor": "nvidia", + "problem": None, "usable": True}]} + + +class FakeRoot(unittest.TestCase): + """A temporary Strata folder: fake setup.py and serve/server.py, its own settings file (data folder).""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + base = Path(self.tmp.name) + self.root = base / "Strata" + (self.root / "serve").mkdir(parents=True) + (self.root / "setup.py").write_text(FAKE_SETUP) + (self.root / "serve" / "server.py").write_text(FAKE_SERVER) + self.env_backup = {k: os.environ.get(k) for k in ("APPDATA", "XDG_CONFIG_HOME")} + os.environ["APPDATA"] = os.environ["XDG_CONFIG_HOME"] = str(base / "config") + self.strata = M.Strata(self.root) + self.strata.python_override = sys.executable + self.strata.health_timeout = 1.0 + self.strata._hardware = lambda: dict(FAKE_HW) + self.strata.disk_free = lambda p: 1000.0 + self.tools = M.Tools(self.strata) + self.extra = [] + + def tearDown(self): + for p in self.extra: + if p.poll() is None: + p.kill() + p.wait(10) + srv = self.strata.state("server") + if srv and M.proc_alive(srv.get("pid"), srv.get("ident")): + M.proc_kill_tree(srv["pid"], srv["ident"]) + M.wait_gone(srv["pid"], srv["ident"], 10) + job = self.strata.state("install") + if job and M.proc_alive(job.get("pid"), job.get("ident")): + M.proc_kill_tree(job["pid"], job["ident"]) + M.wait_gone(job["pid"], job["ident"], 10) + for p in self.strata.children: + try: + p.wait(5) + except subprocess.TimeoutExpired: + pass + for k, v in self.env_backup.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + for _ in range(20): # Windows: a log may still be closing + try: + self.tmp.cleanup() + break + except OSError: + time.sleep(0.25) + + def call(self, name, args=None): + """A tools/call through the JSON-RPC layer: (result dict, isError).""" + srv = M.McpServer(self.strata, io.BytesIO()) + r = srv.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": name, "arguments": args or {}}}) + res = r["result"] + return json.loads(res["content"][0]["text"]), res["isError"] + + def write_config(self, tag="q2_0", port=8080, **extra): + cfg = {"exe": sys.executable, "args": ["--max-context", "32768"], "port": port, + "model_name": f"qwen3.8-flash-next-{tag}", "log": str(self.root / f"strata-{tag}.log"), **extra} + (self.root / f"strata-{tag}.json").write_text(json.dumps(cfg)) + (self.root / f"strata-{tag}.log").write_text("engine line 1\nengine line 2\n") + return cfg + + +# ------------------------------------------------------------------------------------------------ the protocol +class Protocol(FakeRoot): + def run_lines(self, msgs): + inp = io.BytesIO(("\n".join(m if isinstance(m, str) else json.dumps(m) for m in msgs) + "\n").encode()) + out = io.BytesIO() + M.McpServer(self.strata, out).serve(inp) + return {m.get("id"): m for m in (json.loads(x) for x in out.getvalue().decode().splitlines())} + + def test_handshake_list_call(self): + r = self.run_lines([ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "1"}}}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "strata_models", "arguments": {}}}, + {"jsonrpc": "2.0", "id": 4, "method": "ping"}, + ]) + init = r[1]["result"] + self.assertEqual(init["protocolVersion"], "2025-06-18") + self.assertIn("tools", init["capabilities"]) + self.assertEqual(init["serverInfo"]["name"], "strata") + names = [t["name"] for t in r[2]["result"]["tools"]] + self.assertEqual(names, ["strata_status", "strata_models", "strata_install", "strata_start", "strata_stop", + "strata_logs", "strata_benchmark", "strata_connect_info"]) + for t in r[2]["result"]["tools"]: + self.assertEqual(t["inputSchema"]["type"], "object") + self.assertFalse(t["inputSchema"]["additionalProperties"]) + self.assertGreater(len(t["description"]), 60) + call = r[3]["result"] + self.assertFalse(call["isError"]) + self.assertIn("families", call["structuredContent"]) + self.assertEqual(json.loads(call["content"][0]["text"])["recommendation"]["model"], "IQ3_XXS") + self.assertEqual(r[4]["result"], {}) + self.assertNotIn(None, r) # the notification got no answer + + def test_older_protocol_and_errors(self): + r = self.run_lines([ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}, + "{not json", + {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "rm_rf", "arguments": {}}}, + {"jsonrpc": "2.0", "id": 3, "method": "no/such"}, + {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "strata_logs", "arguments": []}}, + ]) + self.assertEqual(r[1]["result"]["protocolVersion"], "2024-11-05") + self.assertEqual(r[None]["error"]["code"], -32700) + self.assertEqual(r[2]["error"]["code"], -32602) + self.assertEqual(r[3]["error"]["code"], -32601) + self.assertTrue(r[4]["result"]["isError"]) + self.assertNotIn("structuredContent", r[4]["result"]) # 2024-11-05 has no structured results + + def test_real_stdio_process(self): + """The script itself over a pipe: stdout carries only JSON-RPC lines.""" + msgs = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", + "params": {"name": "strata_logs", "arguments": {"source": "setup"}}}] + p = subprocess.run([sys.executable, str(HERE / "strata_mcp.py"), "--root", str(self.root)], + input="\n".join(json.dumps(m) for m in msgs) + "\n", capture_output=True, text=True, + timeout=60, env=dict(os.environ)) + lines = [json.loads(x) for x in p.stdout.splitlines()] + self.assertEqual(sorted(m["id"] for m in lines), [1, 2, 3]) + self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 8) + self.assertIn("ready", p.stderr) + + def test_not_a_strata_folder(self): + p = subprocess.run([sys.executable, str(HERE / "strata_mcp.py"), "--root", self.tmp.name], input="", + capture_output=True, text=True, timeout=60) + self.assertEqual(p.returncode, 2) + + +# ------------------------------------------------------------------------------------------------ validation +class Validation(FakeRoot): + def assertRejected(self, tool, args, text): + res, err = self.call(tool, args) + self.assertTrue(err, f"{tool} {args} was accepted: {res}") + self.assertIn(text, res["error"]) + + def test_install_arguments(self): + self.assertRejected("strata_install", {"model": "Q9_X"}, "model must be one of") + self.assertRejected("strata_install", {"family": "llama"}, "family must be one of") + self.assertRejected("strata_install", {"context": 12345}, "context must be one of") + self.assertRejected("strata_install", {"gpus": "0;rm -rf /"}, "gpus=") + self.assertRejected("strata_install", {"gpus": "0 && calc"}, "gpus=") + self.assertRejected("strata_install", {"gpu": -1}, "between") + self.assertRejected("strata_install", {"gpu": "1; calc"}, "whole number") + self.assertRejected("strata_install", {"gpu": 0, "gpus": "0,1"}, "not both") + self.assertRejected("strata_install", {"port": 80}, "between") + self.assertRejected("strata_install", {"backend": "rocm"}, "backend must be one of") + self.assertRejected("strata_install", {"command": "setup.py --build"}, "unknown argument") + self.assertRejected("strata_install", {"family": "swift", "model": "IQ3_S"}, "has no IQ3_S") + self.assertRejected("strata_install", {"family": "unsloth", "vision": "yes"}, "images are not available") + self.assertRejected("strata_install", {"vision": "yes\nrm"}, "control characters") + + def test_data_dir_paths(self): + self.assertRejected("strata_install", {"data_dir": "models"}, "absolute") + self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "x" / ".." / "Strata-x")}, "'..'") + self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "Documents")}, "named Strata") + self.assertRejected("strata_install", {"data_dir": str(self.root.parent / "nope" / "Strata-data")}, + "does not exist") + self.assertRejected("strata_install", {"data_dir": "\\\\server\\share\\Strata-data"}, "network") + sysdir = (os.environ.get("SystemRoot", "C:\\Windows") + "\\Strata-data") if M.WIN else "/etc/Strata-data" + self.assertRejected("strata_install", {"data_dir": sysdir}, "system folder") + ok = [self.root.parent / "Strata-data", self.root / "models-here", self.root.parent / "Strata-big"] + for d in ok: + self.assertEqual(M.norm(self.tools.check_data_dir(str(d))), M.norm(d)) + + def test_other_tools_arguments(self): + self.assertRejected("strata_start", {"model": "../../etc/passwd"}, "not valid") + self.assertRejected("strata_start", {"model": "q2_0"}, "no model is installed") + self.write_config("q2_0") + self.assertRejected("strata_start", {"model": "iq3_s"}, "no installed model 'iq3_s'") + self.assertRejected("strata_start", {"wait_seconds": 100000}, "between") + self.assertRejected("strata_logs", {"lines": 0}, "between") + self.assertRejected("strata_logs", {"source": "/etc/passwd"}, "source must be one of") + self.assertRejected("strata_benchmark", {"max_tokens": 100000}, "between") + self.assertRejected("strata_stop", {"force": "yes"}, "true or false") + + def test_engine_log_outside_is_not_read(self): + self.write_config("q2_0", log=str(Path(self.tmp.name).parent / "elsewhere.log")) + res, err = self.call("strata_logs", {"source": "engine", "model": "q2_0"}) + self.assertTrue(err) + self.assertIn("outside the Strata folder", res["error"]) + self.write_config("q2_0") + res, err = self.call("strata_logs", {"source": "engine"}) + self.assertFalse(err) + self.assertEqual(res["lines"], ["engine line 1", "engine line 2"]) + + +# ------------------------------------------------------------------------------------------------ install +class Install(FakeRoot): + def wait_job(self): + self.assertTrue(wait_for(lambda: not self.strata.install_job()["running"], 60)) + + def test_plan_then_install(self): + res, err = self.call("strata_install", {}) + self.assertFalse(err) + self.assertIn("Nothing was done yet", res["summary"]) + self.assertEqual((res["plan"]["family"], res["plan"]["model"], res["plan"]["context"]), ("qwen", "IQ3_XXS", 32768)) + self.assertFalse((self.root / "setup-args.json").exists()) + self.assertIsNone(self.strata.install_job()) + + res, err = self.call("strata_install", {"model": "Q2_0", "context": 65536, "vision": "no", "confirm": True}) + self.assertFalse(err, res) + self.assertIn("started in the background", res["summary"]) + self.wait_job() + args = json.loads((self.root / "setup-args.json").read_text()) + self.assertEqual(args[:2], ["--yes", "--no-start"]) + for pair in (["--family", "qwen"], ["--model", "Q2_0"], ["--context", "65536"], ["--vision", "no"]): + i = args.index(pair[0]) + self.assertEqual(args[i:i + 2], pair) + res, err = self.call("strata_install", {}) + self.assertEqual(res["install"]["result"], "installed") + self.assertEqual(res["install"]["exit_code"], 0) + self.assertEqual(res["next"], "strata_start") + st, _ = self.call("strata_status", {"hardware": False}) + self.assertEqual([m["model"] for m in st["installed"]["models"]], ["q2_0"]) + + def test_progress_while_running_and_cancel(self): + (self.root / "slow").write_text("") + res, err = self.call("strata_install", {"family": "coder", "confirm": True}) + self.assertFalse(err, res) + self.assertTrue(wait_for(lambda: (self.strata.install_job() or {}).get("download") is not None, 30)) + res, err = self.call("strata_install", {"model": "IQ3_S", "confirm": True}) # a second call: progress only + self.assertFalse(err) + self.assertIn("an install is running", res["summary"]) + self.assertEqual(res["install"]["step"], "5/7: downloading Qwen3.8-Flash-Next Q2_0") + self.assertEqual(res["install"]["download"]["percent"], 30) + res, err = self.call("strata_start", {}) + self.assertTrue(err) + self.assertIn("install is still running", res["error"]) + res, err = self.call("strata_install", {"cancel": True}) + self.assertIn("stopped", res["summary"]) + self.assertFalse(self.strata.install_job()["running"]) + + def test_failure_is_reported(self): + (self.root / "fail").write_text("") + self.call("strata_install", {"model": "Q2_0", "confirm": True}) + self.wait_job() + res, _ = self.call("strata_install", {}) + self.assertEqual(res["install"]["result"], "failed") + self.assertIn("not enough free disk space - use --models-dir on a bigger drive", res["install"]["error"]) + + def test_disk_space_is_checked(self): + self.strata.disk_free = lambda p: 10.0 + res, err = self.call("strata_install", {"model": "Q2_0"}) + self.assertIn("not enough free disk space", res["plan"]["disk_short"]) + res, err = self.call("strata_install", {"model": "Q2_0", "confirm": True}) + self.assertTrue(err) + self.assertIsNone(self.strata.install_job()) + + +# ------------------------------------------------------------------------------------------------ start / stop / status +class StartStop(FakeRoot): + def test_start_status_bench_stop(self): + port = free_port() + self.write_config("q2_0", port=port, delay=1.5) + res, err = self.call("strata_start", {"wait_seconds": 30}) + self.assertFalse(err, res) + self.assertIn("Strata is running", res["summary"]) + pid = res["server"]["pid"] + + st, _ = self.call("strata_status", {"hardware": False}) + self.assertIn(f"running on port {port}", st["summary"]) + srv = st["running"][0] + self.assertEqual(srv["engine_version"], "0.1.32") + self.assertEqual(srv["gpu"]["total_mib"], 12227) + self.assertIn("this MCP server", srv["started_by"]) + + res, err = self.call("strata_start", {}) # already running: nothing new + self.assertIn("already running", res["summary"]) + + b, err = self.call("strata_benchmark", {"max_tokens": 64}) + self.assertFalse(err, b) + self.assertEqual(b["output_tok_s"], 61.5) + sent = json.loads((self.root / "bench-request.json").read_text()) + self.assertEqual((sent["temperature"], sent["max_tokens"], sent["reasoning_effort"]), (0, 64, "none")) + + c, _ = self.call("strata_connect_info", {}) + self.assertEqual(c["openai_base_url"], f"http://127.0.0.1:{port}/v1") + + logs, _ = self.call("strata_logs", {"source": "server"}) + self.assertTrue(any(line.startswith("ready:") for line in logs["lines"])) + + res, err = self.call("strata_stop", {}) + self.assertFalse(err, res) + self.assertIn("Strata stopped", res["summary"]) + self.assertEqual(res["engine_unloaded"], "unloaded") + self.assertEqual((self.root / "unloaded.txt").read_text().split(), [str(port)]) + ident = M.proc_identity(pid) + self.assertIsNone(ident) + st, _ = self.call("strata_status", {"hardware": False}) + self.assertEqual(st["running"], []) + res, _ = self.call("strata_stop", {}) + self.assertEqual(res["summary"], "Strata is not running") + + def test_start_reports_a_crash(self): + self.write_config("q2_0", port=free_port(), crash=True) + res, err = self.call("strata_start", {"wait_seconds": 30}) + self.assertTrue(err) + self.assertIn("out of memory (fake)", res["error"]) + self.assertEqual(self.strata.state("server"), {}) + + def test_loading_then_ready(self): + port = free_port() + self.write_config("q2_0", port=port, delay=3) + res, err = self.call("strata_start", {"wait_seconds": 0}) + self.assertIn("loading", res["summary"]) + st, _ = self.call("strata_status", {"hardware": False}) + self.assertIn("loading", st["summary"]) + self.assertTrue(wait_for(lambda: self.strata.probe(port) is not None, 30)) + + def test_stop_while_busy_needs_force(self): + port = free_port() + self.write_config("q2_0", port=port, busy=True) + self.call("strata_start", {"wait_seconds": 30}) + res, err = self.call("strata_stop", {}) + self.assertTrue(err) + self.assertIn("force=true", res["error"]) + res, err = self.call("strata_stop", {"force": True}) + self.assertFalse(err, res) + + def test_external_server_is_only_unloaded(self): + port = free_port() + self.write_config("q2_0", port=port) + p = subprocess.Popen([sys.executable, str(self.root / "serve" / "server.py"), "--config", + str(self.root / "strata-q2_0.json"), "--port", str(port)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.extra.append(p) + self.assertTrue(wait_for(lambda: self.strata.probe(port) is not None, 30)) + st, _ = self.call("strata_status", {"hardware": False}) + self.assertIn("outside this MCP server", st["running"][0]["started_by"]) + res, err = self.call("strata_start", {}) + self.assertIn("started outside this MCP server", res["summary"]) + res, err = self.call("strata_stop", {}) + self.assertFalse(err, res) + self.assertIn("only its model was unloaded", res["summary"]) + time.sleep(0.5) + self.assertIsNone(p.poll()) # the server itself was not touched + + def test_never_kills_an_unrelated_process(self): + other = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + self.extra.append(other) + # a stale record: this process id, but another start time (a reused id) + self.strata.save_state("server", {"pid": other.pid, "ident": "win:1" if M.WIN else "linux:1", + "port": free_port(), "model": "q2_0"}) + res, _ = self.call("strata_stop", {}) + self.assertEqual(res["summary"], "Strata is not running") + self.assertFalse(M.proc_terminate(other.pid, "linux:1")) + time.sleep(0.3) + self.assertIsNone(other.poll()) + + def test_status_sees_other_programs_on_the_port(self): + class H(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(404) + self.end_headers() + + def log_message(self, *a): + pass + httpd = HTTPServer(("127.0.0.1", 0), H) + port = httpd.server_address[1] + threading.Thread(target=httpd.serve_forever, daemon=True).start() + try: + self.write_config("q2_0", port=port) + st, _ = self.call("strata_status", {"hardware": False}) + self.assertEqual(st["running"], []) + self.assertEqual(st["ports_used_by_other_programs"][0]["port"], port) + res, err = self.call("strata_start", {}) + self.assertTrue(err) + self.assertIn("used by another program", res["error"]) + finally: + httpd.shutdown() + httpd.server_close() + + +# ------------------------------------------------------------------------------------------------ helpers +class Helpers(unittest.TestCase): + def test_progress_from_setup_output(self): + with tempfile.TemporaryDirectory() as d: + f = Path(d) / "setup.log" + f.write_text("=== Step 4: the Strata engine ===\n [ok] engine\n=== Step 5: downloading X ===\n" + "\r a.gguf: 1.00 / 50.00 GB (2%) \r a.gguf: 25.00 / 50.00 GB (50%) \n") + p = M.install_progress(M.read_tail(f, 50)) + self.assertEqual(p["step"], "5/7: downloading X") + self.assertEqual(p["download"], {"file": "a.gguf", "done_gb": 25.0, "total_gb": 50.0, "percent": 50}) + self.assertNotIn("error", p) + + def test_builtin_table_matches_setup(self): + s = M.Strata(HERE.parent) + S = s.setup_module() + self.assertIsNotNone(S, "the repository's setup.py did not import") + self.assertEqual(list(S.MODELS), list(M.FALLBACK_MODELS)) + for m, d in S.MODELS.items(): + for k in ("download_gb", "ram_gb", "arena_gb"): + self.assertEqual(d[k], M.FALLBACK_MODELS[m][k], f"{m} {k}") + self.assertEqual(d.get("families", ("qwen", "swift")), M.FALLBACK_MODELS[m].get("families", ("qwen", "swift"))) + self.assertEqual(list(S.FAMILIES), list(M.FALLBACK_FAMILIES)) + for f, d in S.FAMILIES.items(): + self.assertEqual(d["tag"], M.FALLBACK_FAMILIES[f]["tag"]) + self.assertEqual(list(S.CONTEXTS), M.FALLBACK_CONTEXTS) + + def test_recommendation_follows_ram(self): + s = M.Strata(HERE.parent) + gpu = [{"index": 0, "name": "x", "vram_gb": 24.0, "usable": True, "vendor": "nvidia"}] + cases = {96: ("qwen", "IQ3_XXS", 131072), 48: ("qwen", "Q2_0", 131072), 32: ("coder", "IQ1_M", 131072)} + for ram, want in cases.items(): + r = s.recommend({"ram_gb": ram, "gpus": gpu, "cpu": {"avx2": True}}) + self.assertEqual((r["family"], r["model"], r["context"]), want, ram) + r = s.recommend({"ram_gb": 16, "gpus": [{**gpu[0], "vram_gb": 8.0}], "cpu": {"avx2": True}}) + self.assertIsNone(r["model"]) + r = s.recommend({"ram_gb": 64, "gpus": [], "cpu": {"avx2": True}}) + self.assertIsNone(r["model"]) + r = s.recommend({"ram_gb": 64, "gpus": [{**gpu[0], "vram_gb": 12.0}], "cpu": {"avx2": True}}) + self.assertEqual(r["context"], 32768) + + +if __name__ == "__main__": + unittest.main() diff --git a/engine/strata/tools/vision/CMakeLists.txt b/engine/strata/tools/vision/CMakeLists.txt new file mode 100644 index 00000000..83682037 --- /dev/null +++ b/engine/strata/tools/vision/CMakeLists.txt @@ -0,0 +1,44 @@ +# tools/vision - strata-vision, the image encoder for Strata's multimodal path (optional; setup.py builds it when +# the vision encoder is chosen). Uses llama.cpp's mtmd library at the same pinned commit as the engine's ggml. +# +# cmake -S tools/vision -B build-vision -G Ninja -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=third_party/llama.cpp +# [-DSTRATA_VISION_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=native] +# cmake --build build-vision --target strata-vision +cmake_minimum_required(VERSION 3.21) +project(strata_vision C CXX) + +set(LLAMA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/llama.cpp" CACHE PATH "llama.cpp checkout") +option(STRATA_VISION_CUDA "run the vision encoder on the GPU (builds ggml-cuda)" OFF) +option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" OFF) +if(STRATA_PORTABLE AND MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") +endif() + +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_COMMON OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_TOOLS OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_APP OFF CACHE BOOL "" FORCE) +set(LLAMA_BUILD_MTMD ON CACHE BOOL "" FORCE) +set(LLAMA_OPENSSL OFF CACHE BOOL "" FORCE) +set(LLAMA_CURL OFF CACHE BOOL "" FORCE) +if(STRATA_PORTABLE) + set(GGML_NATIVE OFF CACHE BOOL "" FORCE) + set(GGML_OPENMP OFF CACHE BOOL "" FORCE) # no vcomp140.dll / libgomp needed on the user's PC + foreach(_f GGML_AVX GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2) + set(${_f} ON CACHE BOOL "" FORCE) + endforeach() +else() + set(GGML_NATIVE ON CACHE BOOL "" FORCE) +endif() +set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) +set(GGML_CUDA ${STRATA_VISION_CUDA} CACHE BOOL "" FORCE) + +add_subdirectory(${LLAMA_DIR} llama EXCLUDE_FROM_ALL) + +add_executable(strata-vision strata_vision.cpp) +target_link_libraries(strata-vision PRIVATE mtmd llama) +target_compile_features(strata-vision PRIVATE cxx_std_17) +set_target_properties(strata-vision PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) diff --git a/engine/strata/tools/vision/strata_vision.cpp b/engine/strata/tools/vision/strata_vision.cpp new file mode 100644 index 00000000..6be3f44b --- /dev/null +++ b/engine/strata/tools/vision/strata_vision.cpp @@ -0,0 +1,205 @@ +// tools/vision/strata_vision.cpp - the image half of Strata's multimodal path. +// +// Turns an image into the embeddings the text model reads in place of its <|image_pad|> tokens, with llama.cpp's +// mtmd library and the model's mmproj file (vision encoder + projector). The engine does the rest: it places the +// rows at the image's pad tokens and gives them their 2-D M-RoPE positions (see --serve GENI in generate.cpp). +// +// strata-vision --mmproj --model [--gpu] [--threads N] +// [--max-tokens N] [--flash-attn on|off|auto] +// +// Resident: prints "READY ", then per stdin line +// ENC -> "OK " or "ERR " +// QUIT +// The output file is int32 {0x31455653 'SVE1', n_tokens, nx, ny, n_embd} then float32 [n_tokens][n_embd], +// row i at grid position (x = i % nx, y = i / nx). The text model is opened vocab-only (no weights). +#include "gguf.h" +#include "llama.h" +#include "mtmd.h" +#include "mtmd-helper.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void quiet_log(ggml_log_level level, const char* text, void*) { + if (level >= GGML_LOG_LEVEL_WARN) std::fputs(text, stderr); +} + +// "ENC ": paths may contain spaces, so the image path ends at the last " " before the output path; +// the server always writes paths without spaces, but a user calling the tool by hand might not +bool parse_enc(const std::string& line, std::string& img, std::string& out) { + if (line.rfind("ENC ", 0) != 0) return false; + const std::string rest = line.substr(4); + const size_t sp = rest.rfind(' '); + if (sp == std::string::npos || sp == 0) return false; + img = rest.substr(0, sp); + out = rest.substr(sp + 1); + return !img.empty() && !out.empty(); +} + +} // namespace + +int main(int argc, char** argv) { + std::string mmproj, model; + bool gpu = false; + int threads = 0, max_tokens = 0; + llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); } + return argv[++i]; + }; + if (a == "--mmproj") mmproj = next(); + else if (a == "--model") model = next(); + else if (a == "--gpu") gpu = true; + else if (a == "--threads") threads = std::atoi(next().c_str()); + else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); + else if (a == "--flash-attn") { // FA keeps K and V in FP16; off = the attention in FP32 + const std::string v = next(); + fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED + : LLAMA_FLASH_ATTN_TYPE_AUTO; + } + else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } + } + if (mmproj.empty() || model.empty()) { + std::fprintf(stderr, "usage: strata-vision --mmproj --model [--gpu] [--threads N] " + "[--max-tokens N] [--flash-attn on|off|auto]\n"); + return 2; + } + // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM, + // 150-260 expert slots less for the engine beside it). Before anything reaches the CUDA runtime. + if (!gpu) { +#ifdef _WIN32 + _putenv_s("CUDA_VISIBLE_DEVICES", "-1"); +#else + setenv("CUDA_VISIBLE_DEVICES", "-1", 1); +#endif + } + llama_log_set(quiet_log, nullptr); + mtmd_helper_log_set(quiet_log, nullptr); + llama_backend_init(); + + llama_model_params mp = llama_model_default_params(); + mp.vocab_only = true; + llama_model* text = llama_model_load_from_file(model.c_str(), mp); + if (!text) { std::printf("ERR cannot open the text model %s\n", model.c_str()); std::fflush(stdout); return 1; } + + mtmd_context_params cp = mtmd_context_params_default(); + cp.use_gpu = gpu; + cp.print_timings = false; + cp.warmup = false; + cp.flash_attn_type = fa; + // on the CPU without --threads: one per core (mtmd's own default is 4 threads) + if (threads <= 0 && !gpu) threads = std::max(1u, std::thread::hardware_concurrency() / 2); + if (threads > 0) cp.n_threads = threads; + if (max_tokens > 0) cp.image_max_tokens = max_tokens; + mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp); + if (!ctx || !mtmd_support_vision(ctx)) { + std::printf("ERR cannot load the vision encoder %s\n", mmproj.c_str()); + std::fflush(stdout); + return 1; + } + // a vocab-only model reports no hparams, so the width comes from the projector: its output is the model's input + int n_embd = 0; + { + gguf_init_params gp{true, nullptr}; + gguf_context* gg = gguf_init_from_file(mmproj.c_str(), gp); + const int64_t k = gg ? gguf_find_key(gg, "clip.vision.projection_dim") : -1; + if (k >= 0) n_embd = (int) gguf_get_val_u32(gg, k); + if (gg) gguf_free(gg); + } + if (n_embd <= 0) { std::printf("ERR the vision encoder has no projection_dim\n"); std::fflush(stdout); return 1; } + // Warm up at the LARGEST picture before READY: the encoder's GPU work buffers are allocated now, not at the first + // real picture. The server starts this process before the engine, so the engine sizes its expert cache from + // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and + // the engine crawl to a standstill. (A square image well above any cap; mtmd scales it to the token limit.) + // On the CPU there is no VRAM to reserve, and the warm-up would only delay the engine's start by one encode + // (~6 s at 1,024 tokens). + if (!gpu) std::fprintf(stderr, "strata-vision: on the CPU, %d threads, no warm-up\n", threads); + else { + const uint32_t side = 2048; + std::vector rgb((size_t) side * side * 3, 128); + mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data()); + mtmd_input_chunks* chunks = mtmd_input_chunks_init(); + const std::string marker = mtmd_default_marker(); + mtmd_input_text txt{marker.c_str(), marker.size(), false, true}; + const mtmd_bitmap* bms[1] = {bm}; + int warm_tokens = 0; + if (bm && mtmd_tokenize(ctx, chunks, &txt, bms, 1) == 0) { + for (size_t c = 0; c < mtmd_input_chunks_size(chunks); ++c) { + const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c); + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE && mtmd_encode_chunk(ctx, ch) == 0) + warm_tokens = (int) mtmd_input_chunk_get_n_tokens(ch); + } + } + std::fprintf(stderr, "strata-vision: warmed up at %d image tokens\n", warm_tokens); + mtmd_input_chunks_free(chunks); + if (bm) mtmd_bitmap_free(bm); + } + std::printf("READY %d\n", n_embd); + std::fflush(stdout); + + std::string line; + while (std::getline(std::cin, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); + if (line == "QUIT") break; + std::string img, out; + if (!parse_enc(line, img, out)) { std::printf("ERR expected: ENC \n"); std::fflush(stdout); continue; } + const auto t0 = std::chrono::steady_clock::now(); + mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(ctx, img.c_str(), false, + mtmd_helper_init_opt_default()); + if (!bw.bitmap) { std::printf("ERR cannot read the image %s\n", img.c_str()); std::fflush(stdout); continue; } + mtmd_input_chunks* chunks = mtmd_input_chunks_init(); + const std::string prompt = mtmd_default_marker(); + mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true}; + const mtmd_bitmap* bm[1] = {bw.bitmap}; + std::string err; + const mtmd_input_chunk* ichunk = nullptr; + if (mtmd_tokenize(ctx, chunks, &txt, bm, 1) != 0) err = "the image could not be preprocessed"; + for (size_t c = 0; err.empty() && c < mtmd_input_chunks_size(chunks); ++c) { + const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c); + if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) ichunk = ch; + } + if (err.empty() && !ichunk) err = "no image chunk"; + if (err.empty() && mtmd_encode_chunk(ctx, ichunk) != 0) err = "the vision encoder failed"; + if (err.empty()) { + const mtmd_image_tokens* it = mtmd_input_chunk_get_tokens_image(ichunk); + const int n = (int) mtmd_input_chunk_get_n_tokens(ichunk); + // the grid from the decoder positions (nx/ny getters are deprecated): x and y of the last token + const mtmd_decoder_pos last = mtmd_image_tokens_get_decoder_pos(it, 0, (size_t) n - 1); + const int nx = (int) last.x + 1, ny = (int) last.y + 1; + if (nx * ny != n) err = "the image grid is not rectangular (" + std::to_string(n) + " tokens)"; + const float* embd = mtmd_get_output_embd(ctx); + FILE* f = err.empty() ? std::fopen(out.c_str(), "wb") : nullptr; + if (err.empty() && !f) err = "cannot write " + out; + if (f) { + const int32_t hdr[5] = {0x31455653, n, nx, ny, n_embd}; + const bool ok = std::fwrite(hdr, sizeof hdr, 1, f) == 1 && + std::fwrite(embd, sizeof(float) * (size_t) n_embd, (size_t) n, f) == (size_t) n; + std::fclose(f); + if (!ok) err = "short write to " + out; + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (ok) std::printf("OK %d %d %d %.0f\n", n, nx, ny, ms); + } + } + if (!err.empty()) std::printf("ERR %s\n", err.c_str()); + std::fflush(stdout); + mtmd_input_chunks_free(chunks); + mtmd_bitmap_free(bw.bitmap); + if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx); + } + mtmd_free(ctx); + llama_model_free(text); + llama_backend_free(); + return 0; +} diff --git a/gpu/kar/CMakeLists.txt b/gpu/kar/CMakeLists.txt new file mode 100644 index 00000000..3bb84780 --- /dev/null +++ b/gpu/kar/CMakeLists.txt @@ -0,0 +1,71 @@ +cmake_minimum_required(VERSION 3.24) +project(strata_kar_gpu_smoke LANGUAGES CXX) + +if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The pinned libkar reader uses Linux mmap and requires Linux") +endif() + +enable_language(CUDA) + +if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) + set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "NVIDIA GPU architectures" FORCE) +endif() + +find_package(CUDAToolkit REQUIRED) + +add_library(strata_kar_cuda STATIC vendor/libkar.cu) +target_include_directories(strata_kar_cuda PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vendor) +target_link_libraries(strata_kar_cuda PUBLIC CUDA::cudart) +set_target_properties(strata_kar_cuda PROPERTIES + CUDA_STANDARD 17 + CUDA_STANDARD_REQUIRED ON + POSITION_INDEPENDENT_CODE ON) + +add_library(strata_kar_ple_cache STATIC src/kar_ple_cache.cu) +target_include_directories(strata_kar_ple_cache PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/vendor) +target_link_libraries(strata_kar_ple_cache PUBLIC CUDA::cudart) +set_target_properties(strata_kar_ple_cache PROPERTIES + CUDA_STANDARD 17 + CUDA_STANDARD_REQUIRED ON + POSITION_INDEPENDENT_CODE ON) + +add_executable(strata-kar-ple-cache-probe src/kar_ple_cache_probe.cpp) +target_compile_features(strata-kar-ple-cache-probe PRIVATE cxx_std_20) +target_link_libraries(strata-kar-ple-cache-probe PRIVATE strata_kar_cuda strata_kar_ple_cache) + +add_executable(strata-kar-gpu-smoke src/kar_gpu_smoke.cpp) +target_compile_features(strata-kar-gpu-smoke PRIVATE cxx_std_20) +target_link_libraries(strata-kar-gpu-smoke PRIVATE strata_kar_cuda) + +add_executable(strata-kar-sparse-row-smoke src/kar_sparse_row_smoke.cu) +set_target_properties(strata-kar-sparse-row-smoke PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) +target_link_libraries(strata-kar-sparse-row-smoke PRIVATE strata_kar_cuda) + +add_executable(strata-kar-row-cache-smoke src/kar_row_cache_smoke.cu) +set_target_properties(strata-kar-row-cache-smoke PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) +target_link_libraries(strata-kar-row-cache-smoke PRIVATE strata_kar_cuda) + +add_library(strata_kar_expert STATIC src/kar_expert.cu) +target_include_directories(strata_kar_expert PUBLIC include vendor) +target_link_libraries(strata_kar_expert PUBLIC CUDA::cudart) +set_target_properties(strata_kar_expert PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) +add_executable(strata-kar-expert-probe src/kar_expert_probe.cpp) +target_compile_features(strata-kar-expert-probe PRIVATE cxx_std_20) +target_link_libraries(strata-kar-expert-probe PRIVATE strata_kar_cuda strata_kar_expert) + +enable_testing() +add_executable(strata-kar-expert-test src/kar_expert_test.cpp) +target_compile_features(strata-kar-expert-test PRIVATE cxx_std_20) +target_link_libraries(strata-kar-expert-test PRIVATE strata_kar_expert) +add_test(NAME kar_expert_component COMMAND strata-kar-expert-test) +set_tests_properties(kar_expert_component PROPERTIES TIMEOUT 60) +add_library(strata_kar_miss STATIC src/kar_expert_miss.cpp) +target_compile_features(strata_kar_miss PRIVATE cxx_std_20) +target_link_libraries(strata_kar_miss PUBLIC strata_kar_expert strata_kar_cuda) +add_executable(strata-kar-expert-miss-test src/kar_expert_miss_test.cpp) +target_compile_features(strata-kar-expert-miss-test PRIVATE cxx_std_20) +target_link_libraries(strata-kar-expert-miss-test PRIVATE strata_kar_miss) +add_test(NAME kar_expert_miss COMMAND strata-kar-expert-miss-test "${CMAKE_BINARY_DIR}/expert-fixture.kar") +set_tests_properties(kar_expert_miss PROPERTIES TIMEOUT 60) diff --git a/gpu/kar/README.md b/gpu/kar/README.md new file mode 100644 index 00000000..651ba9c3 --- /dev/null +++ b/gpu/kar/README.md @@ -0,0 +1,202 @@ +# KAR CUDA smoke target + +## Experimental expert component + +`ResidentExpert` (`kar_expert.hpp`) stages one selected expert's gate, up and +down compressed slices from an already verified immutable KAR mapping. It +requires top-down group-32 three-dimensional expert tensors, explicit level +1–8 and at most eight input tokens. Three compressed matrices stay resident; +one F32 matrix scratch buffer is reused for decode, multiply, SiLU and down +projection. Allocations happen in `open`, with a fixed geometry cap and GPU +headroom check. Its own stream/event controls ownership and completion. + +The component has an opt-in native verifier cache-miss adapter described below. +It has no LRU scheduler, and staging waits for its own upload. +Its F32 activation arithmetic differs from native quantized expert arithmetic. +No default, model quality or speed claim follows from its oracle passing. + +On an unused NVIDIA GPU, `scripts/check-kar-expert-gpu.sh` checks exact decoded +bytes, scalar FP64 multiply (absolute tolerance `1e-6` for the synthetic +fixture), one/eight-token windows, expert replacement/reuse and invalid state. +For private target-model evidence, build `strata-kar-expert-probe` and run: + +```sh +strata-kar-expert-probe MODEL.kar LAYER EXPERT LEVEL TOKENS NEW_PRIVATE_DIRECTORY +python3 scripts/check-kar-expert-result.py --archive MODEL.kar --result NEW_PRIVATE_DIRECTORY +``` + +The probe verifies all archive payload CRCs before extracting an expert. The +offline NumPy oracle independently decodes its selected archive slices and +compares every F32 byte (tolerance zero), then compares expert output with FP64 +matrix arithmetic (relative L2 at most `2e-5`, max absolute error at most +`1e-4 * max(1, max(abs(reference)))`). It does not compare KAR with source GGUF +weights. All reconstructed matrices and results must remain outside Git. + +Initial actual-model component check (2026-10-05, RTX 5090, driver 595.91.07, +CUDA 13.2.2) used layer 0, expert 17, level 2 and eight deterministic inputs +from archive SHA-256 +`536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`. +All three reconstructed matrices matched the independent CPU decoder exactly. +Output relative L2 error against FP64 was `1.6218124241392543e-7`, maximum +absolute error `4.847555814223303e-9`. Explicit allocations were 1,536,768 bytes +for compressed weights and 6,758,400 bytes for matrix/activation scratch; +CUDA context overhead is excluded. This is one expert component, not full-model +serving or a comparison with the original IQ3 expert. + +### Experimental native verifier misses + +Build the engine with `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON` and +`STRATA_NEXT_KAR_DIR` pointing to this directory. This option is off by default +and requires Linux CUDA. Set `STRATA_NEXT_KAR_EXPERTS_ARCHIVE` to a trusted, +immutable, separately SHA/provenance-verified target-model KAR archive and +`STRATA_NEXT_KAR_EXPERTS_LEVEL` explicitly to its supported level (1–8). +The reader checks directory integrity, every payload CRC and every layer's +expert geometry before allocating its bounded GPU buffers. This integrity +check does not authenticate the archive's pairing with the loaded GGUF. +Large archives can take minutes to verify; configure an appropriate worker +startup deadline. Keep both model and archive unchanged for the worker's life. + +The adapter requires the native pack, expert pool and a single GPU. It computes +native verifier-window misses, including short prompt ingestion and decode. +Native resident hits, batched prefill, dense weights, PLE and MTP retain their +existing paths. It sets the PCIe miss fraction to zero; +use `--pcie-frac 0` in the comparison baseline as well. This is a mixed precision +experimental arm, not full KAR model residency. Each missed expert is staged +and computed serially on the component's own nonblocking CUDA stream. Its +completed host rows preserve routing order and bypass the CPU expert jobs. +The bounded matrix scratch is reused; no decoded expert bank is allocated. +The exit diagnostic reports computed route entries and explicit GPU bytes. + +The GPU test script also uses the production Rust archive writer to make a +model-free expert bank. It tests eight-token grouped routing against a scalar +oracle (absolute tolerance `1e-6`), preservation of VRAM/PCIe/remote/completed +rows, unsupported archive shape/level and invalid routed IDs. Production +serving does not invoke the fixture generator or Python. + +The optional `strata_next_kar_ple_probe` target belongs to the imported +Strata engine build when `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`. It exercises +the separate CPU PLE quality arm on real KAR rows. A successful checksum does +not imply the sparse CUDA packet path is wired into serving. + +For a same-process CPU gather comparison on the target model, run +`strata_next_kar_ple_probe --compare-random BASE.kar 2 PLE.gguf 4096 42 5 +200000000`. The final number bounds the sampled global row IDs; use the row +count of the selected KAR part when matching a sparse CUDA packet run. The +probe alternates native and KAR gathers after one warmup of each and reports +the median over the requested repeats. The first native gather may incur +storage page faults, while KAR opening already scanned the archive; compare +the warm medians and report first-run times separately. + +For a model-free reader check, run `strata-next model ple-smoke-fixture --output +/tmp/ple-smoke.kar`, then `strata_next_kar_ple_probe /tmp/ple-smoke.kar 2 +--expected-rows 4 0 1 2 3`. The four checksums must match those printed by +the Rust fixture command. Remove the temporary archive afterward. + +`vendor/libkar.h` and `vendor/libkar.cu` are copied unchanged from local `koference` commit `806d2398ae1daaceb2917242911e5680cbfb3608`, paths `r08/code/libkar.h` and `r08/code/libkar.cu`. Their SHA-256 values are `1d725069fd2c275423f5db70fb4190e7d51760e0c48a2a5ebe8c91993936ca92` and `331babd2a2f260abb7de602d414edd97399542ec1bccb23ffcdfad69dc0ade28` respectively. Keep these bytes and upstream provenance traceable when making local changes. + +On Linux with CUDA 13 and a supported NVIDIA GPU, create a model-free fixture and compare its CPU and GPU decode checksums: + +```sh +strata-next model smoke-fixture --output /tmp/strata-smoke.kar +cmake -S gpu/kar -B artifacts/kar-gpu-build -G Ninja -DCMAKE_CUDA_ARCHITECTURES=120 +cmake --build artifacts/kar-gpu-build --target strata-kar-gpu-smoke +artifacts/kar-gpu-build/strata-kar-gpu-smoke /tmp/strata-smoke.kar smoke.expert 2 30 +strata-next model checksum-kar-preview /tmp/strata-smoke.kar smoke.expert 2 +artifacts/kar-gpu-build/strata-kar-gpu-smoke /tmp/strata-smoke.kar smoke.expert 2 30 --row 0 +strata-next model checksum-kar-row /tmp/strata-smoke.kar smoke.expert 2 --row 0 +``` + +An optional fifth argument is an overlay archive. The smoke target opens both +archives with payload CRC verification, checks their virtual-F32 source identity +and every replacement's name, shape, source dtype, source digest, and source +offset, then reserves and decodes +the requested tensor from the overlay when it is present there. It prints +`source=base` or `source=overlay`. For a real overlay, first run +`strata-next model resolve-kar-overlay --base BASE.kar --overlay OVERLAY.kar`: +that Rust verifier additionally checks complete archive SHA-256 values and +provenance. Keep both files unchanged between resolution and this smoke run. +The smoke target alone does not authenticate the archive files against +provenance and is not a serving loader. + +For a bounded resident-row experiment, append `--rows COUNT SEED` instead of +`--row ID`. The smoke validates the archive, copies one compressed record's +level prefix into VRAM once, generates `COUNT` deterministic random row IDs +within that record, uploads those IDs, then times repeated CUDA decoding into +F32 output. It reports the initial `reserve_ms` separately from the warm +`decode_median_ms`. The warm loop reuses both the compressed record and the +same row IDs; it excludes row-ID transfer, cache admission and eviction, +matrix multiplication, and the rest of inference. For example: + +```sh +strata-kar-gpu-smoke MODEL.kar 'per_layer_token_embd.weight#strata-part-001-of-002' 2 100 --rows 4096 42 +``` + +`--rows-ple COUNT SEED` uses the same deterministic row generator as +`strata_next_kar_ple_probe --compare-random`; compare their whole-output +`kar_fnv1a64` and `output_fnv1a64` for an independent CPU/CUDA parity check. +Use the selected part's row count as the CPU probe's `MAX_ROW`. +`--rows-ple-vary COUNT SEED` starts from that same first batch, then changes +every ID before each timed decode. It uses pinned host ID storage and reports +separate GPU-event medians for ID upload, decode, and their combined duration. +The output checksum is for the final, changed batch and therefore does not +match the CPU probe's initial batch. Both modes keep the complete selected +compressed record resident in VRAM; the timing excludes host ID generation, +archive verification, cache admission, eviction, matrix multiplication, and +the rest of inference. + +The smoke program validates the KAR container and payload CRCs, reserves a chosen tensor's compressed level prefix in VRAM, decodes it on a CUDA stream, and reports a warm kernel median over the requested iterations. Compare `output_fnv1a64` with the native CPU command above using the selected archive, tensor, and level. This is a **kernel smoke measurement**, not an end-to-end inference comparison or a model quality result. It does not yet link the decoder into Strata's serving path. Use the original model digest, archive digest, driver/CUDA versions, GPU, tensor, cache state, and iteration count when recording results. + +Before any CUDA allocation, the smoke program checks the selected prefix, F32 output, and optional row ID against currently free VRAM. It leaves at least 512 MiB or one sixteenth of total VRAM free, whichever is larger, and refuses the run if that reserve would be crossed. This admission check protects shared GPU experiments; another process can still allocate memory afterward, so CUDA allocation errors remain possible. It is not an inference scheduler. + +`--row ROW_ID` selects the CUDA row-gather decoder for one row of a compressed record. The row ID is local to the selected KAR part, so `--row 0` on a split PLE part addresses that part's first row. This mode stages the same complete compressed level prefix with `kar_reserve`, then allocates and writes only one F32 row. It reports `mode=row` and the one-row output checksum. Compare a real-model result with `model checksum-kar-row` on the selected archive and part name; that CPU command verifies the complete archive before bounded range decoding. The one-row synthetic fixture above has the same checksum as its full-tensor decode. Row mode does not reduce the initial PCIe transfer of that part and does not make the full model fit in VRAM. + +The smoke program caps the decoded F32 output at 100 million elements. A large PLE part can therefore be used with `--row` if its selected compressed prefix fits the available VRAM; its complete tensor need not fit the full-output cap. + +For a private real-model overlay, `scripts/check-kar-cuda-records.py` accepts a JSON list of `{name, elements}` records (or a report with a `records` array), an archive, the Rust CLI, and the CUDA smoke binary. It checks byte-level CPU/CUDA output parity for each record, using the full tensor up to one million values and row 0 above that limit. It writes the complete result outside Git with mode 0600. Its event timings cover warm CUDA decoding only; it does not time PCIe transfer or multiply, and parity with the CPU KAR decoder is separate from quality against GGUF or end-to-end inference. + +## Bounded compressed-row GPU cache probe + +`strata-kar-row-cache-smoke` exercises an experimental 1–1024 MiB VRAM cache +for the level-2, group-32, 160-value PLE geometry. Each GPU slot uses 64 +bytes for a 50-byte compressed row. A CPU LRU map assigns slots; the program +uploads only missed rows and the batch's slot IDs, scatters misses into VRAM, +and decodes the selected rows with CUDA. Every batch is checked byte for byte +against a fresh CPU decode from the verified archive. This probe is not wired +into serving and its event time does not include archive verification, CPU +planning, output readback, or the parity check. + +Build with `cmake --build artifacts/kar-gpu-build --target +strata-kar-row-cache-smoke`. Invoke as `strata-kar-row-cache-smoke ARCHIVE.kar +'per_layer_token_embd.weight#strata-part-001-of-002' 2 64 TRACE.txt`. The +private trace contains one batch per line with up to 128 space-separated, +part-local decimal row IDs. The cache refuses to run if its allocation would +leave less than 512 MiB or one sixteenth of total VRAM free, whichever is +greater. Keep traces and models outside Git. See +`docs/experiments/2026-10-03-bounded-ple-cache-smoke.md` for the first real +archive checks. + +## Selective row transfer prototype + +`strata-kar-sparse-row-smoke` tests a different staging geometry. The upstream `kar_decode_rows` computes only requested rows but `kar_reserve` first transfers the record's complete level prefix. The prototype verifies the KAR archive, gathers only the selected rows' codebook, group scales, and bit-plane words from the mapped file into a compact host packet, transfers that packet once, and decodes the rows on CUDA. It does not modify the pinned `libkar` source. Its output is compared with `model checksum-kar-row` for each selected row. + +```sh +cmake --build artifacts/kar-gpu-build --target strata-kar-sparse-row-smoke +artifacts/kar-gpu-build/strata-kar-sparse-row-smoke OVERLAY.kar blk.0.ffn_gate_inp.weight 3 30 0 1 +artifacts/kar-gpu-build/strata-kar-sparse-row-smoke BASE.kar 'per_layer_token_embd.weight#strata-part-001-of-002' 2 1000 --range 0 4096 +artifacts/kar-gpu-build/strata-kar-sparse-row-smoke BASE.kar 'per_layer_token_embd.weight#strata-part-001-of-002' 2 1000 --random 4096 42 +``` + +Append `--row-major-cache` to `--random`, `--range`, or explicit row IDs for a +private layout experiment. After archive payload verification, the smoke +transposes one compressed group-32 row tensor into RAM with each row's scales +and selected bit planes adjacent. It refuses more than 12 GiB of host cache +or less than 8 GiB of reported available RAM after allocation. The data are +never written as another model file; the CUDA packet and decoder stay the +same. `row_major_build_ms` and `row_major_cache_bytes` are reported separately +from first and warm packet assembly. This measures an upper bound for a +row-oriented storage layout under warm host-memory conditions. It is not a +bounded GPU cache and does not measure cold random storage access. + +The smoke reports packet bytes, the full-record prefix bytes, warm H2D event time, warm CUDA decode event time, and per-row byte checksums. It reports archive verification and one packet build separately as host wall time; those are not included in the GPU event times. Page faults, output transfer, matrix multiplication, and runtime scheduling need separate accounting. Random rows may trigger storage reads and CPU work, so fewer PCIe bytes do not by themselves establish lower request latency. A production path needs a bounded packet cache, coalescing across requests, provenance binding, backpressure, and integration with the PLE consumer before it can be evaluated as inference. + +The `--range START COUNT` form generates consecutive local row IDs, up to 200,000 rows and the same 100-million-value output cap. `--random COUNT SEED` generates deterministic pseudorandom local IDs within the selected tensor record. Both omit individual row checksums for more than 128 rows but still report the whole output checksum. The contiguous selection is useful for GPU transfer scaling; random selection probes host packet assembly with scattered rows. Neither selection is a representative storage page-fault benchmark because archive payload verification reads the complete file first and can warm the page cache. The smoke times both first packet assembly and a median of five repeated assemblies on the same rows. It also times an upload of the same number of F32 rows from pinned host memory into the output buffer. That upload is the GPU stage of Strata's current PLE prefill path. The comparison excludes its CPU row decoding; compare it with the separate CPU gather probe. Compare the measured stages at the same row count rather than inferring latency from byte counts alone. diff --git a/gpu/kar/include/kar_expert.hpp b/gpu/kar/include/kar_expert.hpp new file mode 100644 index 00000000..d91a7716 --- /dev/null +++ b/gpu/kar/include/kar_expert.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "libkar.h" +#include +#include +#include +#include + +namespace strata::kar { + +// Experimental component. The caller owns an immutable, verified archive mapping. +// One resident compressed expert; one reusable decoded matrix, never a full bank. +// Not thread safe. stage/run may only follow completion of the previous run. +class ResidentExpert { +public: + ResidentExpert(); + ~ResidentExpert(); + ResidentExpert(const ResidentExpert&) = delete; + ResidentExpert& operator=(const ResidentExpert&) = delete; + bool open(uint32_t hidden, uint32_t intermediate, uint32_t level, + uint32_t max_tokens, std::string& error); + bool stage(const uint8_t* archive, size_t bytes, + const kar_tensor_info& gate, const kar_tensor_info& up, + const kar_tensor_info& down, uint32_t expert, std::string& error); + // Input/output are host F32. Only this component's event is waited in finish. + bool run(const float* input, uint32_t tokens, std::string& error); + bool finish(float* output, std::string& error); + // Offline qualification hook: copy one reconstructed matrix to the host. + bool inspect_matrix(uint32_t role, float* output, std::string& error); + uint64_t resident_bytes() const; + uint64_t scratch_bytes() const; +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace strata::kar diff --git a/gpu/kar/include/kar_expert_miss.hpp b/gpu/kar/include/kar_expert_miss.hpp new file mode 100644 index 00000000..4d6a424f --- /dev/null +++ b/gpu/kar/include/kar_expert_miss.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include + +namespace strata::kar { + +// Experimental native verifier cache-miss arm. Batched prefill and cache hits retain +// the native IQ weights. Not a full compressed-model serving implementation. +class ExpertMiss { +public: + ExpertMiss(); + ~ExpertMiss(); + bool open(const char* archive, uint32_t layers, uint32_t experts, + uint32_t hidden, uint32_t intermediate, uint32_t level, + std::string& error); + bool compute(int64_t layer, const float* input, const int32_t* ids, + int64_t tokens, int64_t k, int32_t* kind, float* output, + std::string& error); + static bool dispatch(void* user, int64_t layer, const float* input, + const int32_t* ids, int64_t tokens, int64_t k, + int32_t* kind, float* output, std::string& error); + uint64_t computed() const; +private: + struct Impl; + std::unique_ptr impl_; +}; +} diff --git a/gpu/kar/include/kar_ple_cache.hpp b/gpu/kar/include/kar_ple_cache.hpp new file mode 100644 index 00000000..2c5601f5 --- /dev/null +++ b/gpu/kar/include/kar_ple_cache.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "libkar.h" + +#include +#include +#include +#include +#include + +namespace strata::kar { + +// Parts cover one global PLE table in row order. The archive and its mapped +// bytes must outlive the cache. The caller verifies the archive before open(). +struct PlePart { + uint64_t row_base; + const kar_tensor_info* tensor; +}; + +struct PleCacheStats { + uint64_t hits = 0; + uint64_t misses = 0; + uint64_t compressed_bytes = 0; + uint64_t host_to_device_bytes = 0; +}; + +// Experimental level-2, group-32 PLE cache. Each 160-value row occupies one +// 64-byte compressed VRAM slot; enqueue() decodes requested rows to caller VRAM. +// Calls are serialized. A CUDA event guards the reusable pinned staging buffers +// and slots until the previous launch has completed, even across streams. +class PleRowCache { +public: + PleRowCache(); + ~PleRowCache(); + PleRowCache(const PleRowCache&) = delete; + PleRowCache& operator=(const PleRowCache&) = delete; + + bool open(const uint8_t* archive_map, size_t archive_bytes, + const std::vector& parts, uint32_t cache_mib, + uint32_t max_batch_rows, std::string& err); + bool enqueue(const uint32_t* rows, size_t count, float* device_output, + cudaStream_t stream, std::string& err); + void close(); + PleCacheStats stats() const; + uint32_t slots() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace strata::kar diff --git a/gpu/kar/src/kar_expert.cu b/gpu/kar/src/kar_expert.cu new file mode 100644 index 00000000..9bde4425 --- /dev/null +++ b/gpu/kar/src/kar_expert.cu @@ -0,0 +1,214 @@ +#include "kar_expert.hpp" +#include +#include +#include +#include +#include + +namespace strata::kar { +namespace { +bool check(cudaError_t rc, const char* what, std::string& error) { + if (rc == cudaSuccess) return true; + error = std::string(what) + ": " + cudaGetErrorString(rc); + return false; +} +bool within(uint64_t base, uint64_t relative, uint64_t length, size_t bytes) { + return base <= bytes && relative <= bytes - base && length <= bytes - base - relative; +} +uint64_t align256(uint64_t n) { return (n + 255) & ~uint64_t(255); } + +__global__ void decode(const uint8_t* packet, float* weights, uint32_t values, + uint32_t level, uint32_t words, uint32_t book_bytes) { + const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= values) return; + const auto* book = reinterpret_cast(packet); + const auto* scale = reinterpret_cast(packet + book_bytes); + const auto* planes = reinterpret_cast(packet + book_bytes + words * 2); + uint32_t code = 0; + for (uint32_t p = 0; p < level; ++p) + code = (code << 1) | ((planes[p * words + i / 32] >> (i % 32)) & 1u); + weights[i] = __half2float(book[code]) * __half2float(scale[i / 32]); +} + +// A deliberately plain F32 reduction. This establishes the integration contract, +// not a fast kernel or parity with the native quantized activation arithmetic. +__global__ void multiply(const float* weights, const float* input, float* output, + uint32_t cols, uint32_t rows) { + __shared__ float partial[256]; + const uint32_t row = blockIdx.x, token = blockIdx.y, lane = threadIdx.x; + float sum = 0; + for (uint32_t c = lane; c < cols; c += blockDim.x) + sum = __fadd_rn(sum, __fmul_rn(weights[uint64_t(row) * cols + c], + input[uint64_t(token) * cols + c])); + partial[lane] = sum; + __syncthreads(); + for (uint32_t stride = 128; stride; stride >>= 1) { + if (lane < stride) partial[lane] = __fadd_rn(partial[lane], partial[lane + stride]); + __syncthreads(); + } + if (lane == 0) output[uint64_t(token) * rows + row] = partial[0]; +} +__global__ void activate(float* gate, const float* up, uint32_t values) { + const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < values) gate[i] = (gate[i] / (1.0f + expf(-gate[i]))) * up[i]; +} +} + +struct ResidentExpert::Impl { + uint32_t hidden=0, ff=0, level=0, max_tokens=0, tokens=0, words=0, books=0; + uint64_t packet=0, scratch=0; + bool staged=false, pending=false, failed=false; + cudaStream_t stream=nullptr; + cudaEvent_t done=nullptr; + uint8_t* compressed=nullptr; + uint8_t* host_packet=nullptr; + float *weights=nullptr, *x=nullptr, *gate=nullptr, *up=nullptr, *out=nullptr; + float *host_x=nullptr, *host_out=nullptr; + ~Impl() { + if (stream) cudaStreamSynchronize(stream); + if (done) cudaEventDestroy(done); + for (void* p : {static_cast(compressed), static_cast(weights), + static_cast(x), static_cast(gate), + static_cast(up), static_cast(out)}) if (p) cudaFree(p); + if (host_packet) cudaFreeHost(host_packet); + if (host_x) cudaFreeHost(host_x); + if (host_out) cudaFreeHost(host_out); + if (stream) cudaStreamDestroy(stream); + } +}; +ResidentExpert::ResidentExpert() = default; +ResidentExpert::~ResidentExpert() = default; +uint64_t ResidentExpert::resident_bytes() const { return impl_ ? impl_->packet * 3 : 0; } +uint64_t ResidentExpert::scratch_bytes() const { return impl_ ? impl_->scratch : 0; } + +bool ResidentExpert::open(uint32_t hidden, uint32_t ff, uint32_t level, + uint32_t max_tokens, std::string& error) { + if (impl_) { error="expert is already open"; return false; } + if (!hidden || !ff || hidden > 16384 || ff > 16384 || hidden % 32 || ff % 32 || + level < 1 || level > 8 || !max_tokens || max_tokens > 8 || + uint64_t(hidden) * ff > 16'777'216) { + error="unsupported bounded expert geometry/level/token count"; return false; + } + auto p=std::make_unique(); + p->hidden=hidden; p->ff=ff; p->level=level; p->max_tokens=max_tokens; + p->words=hidden*ff/32; p->books=(1u<packet=align256(p->books + uint64_t(p->words)*(2+4*level)); + p->scratch=uint64_t(hidden)*ff*4 + uint64_t(max_tokens)*(hidden*2+ff*2)*4; + size_t free=0,total=0; + if (!check(cudaMemGetInfo(&free,&total),"expert memory query",error)) return false; + const uint64_t headroom=std::max(512ull<<20,total/16); + if (free < headroom || p->packet*3+p->scratch > free-headroom) { + error="expert budget would cross GPU headroom"; return false; + } + if (!check(cudaStreamCreateWithFlags(&p->stream,cudaStreamNonBlocking),"expert stream",error) || + !check(cudaEventCreateWithFlags(&p->done,cudaEventDisableTiming),"expert event",error) || + !check(cudaMalloc(&p->compressed,p->packet*3),"expert compressed allocation",error) || + !check(cudaMalloc(&p->weights,uint64_t(hidden)*ff*4),"expert matrix scratch",error) || + !check(cudaMalloc(&p->x,uint64_t(max_tokens)*hidden*4),"expert input",error) || + !check(cudaMalloc(&p->out,uint64_t(max_tokens)*hidden*4),"expert output",error) || + !check(cudaMalloc(&p->gate,uint64_t(max_tokens)*ff*4),"expert gate",error) || + !check(cudaMalloc(&p->up,uint64_t(max_tokens)*ff*4),"expert up",error) || + !check(cudaMallocHost(&p->host_packet,p->packet*3),"expert host staging",error) || + !check(cudaMallocHost(&p->host_x,uint64_t(max_tokens)*hidden*4),"expert host input",error) || + !check(cudaMallocHost(&p->host_out,uint64_t(max_tokens)*hidden*4),"expert host output",error)) return false; + impl_=std::move(p); return true; +} + +bool ResidentExpert::stage(const uint8_t* archive, size_t bytes, + const kar_tensor_info& gate, const kar_tensor_info& up, + const kar_tensor_info& down, uint32_t expert, std::string& error) { + if (!impl_ || impl_->pending || impl_->failed || !archive) { + error="expert staging requires an idle healthy instance"; return false; + } + auto& p=*impl_; p.staged=false; + const kar_tensor_info* records[]={&gate,&up,&down}; + // Validate all slices before touching staging or enqueuing a copy. + for (uint32_t role=0;role<3;++role) { + const auto& t=*records[role]; + const uint32_t cols=role==2?p.ff:p.hidden, rows=role==2?p.hidden:p.ff; + const uint64_t first_word=uint64_t(expert)*p.words; + if (t.storage_class!=KAR_NESTED || t.nesting!=KAR_TOPDOWN || t.group!=32 || + t.n_dims!=3 || t.dims[0]!=cols || t.dims[1]!=rows || t.dims[2]>65536 || + expert>=t.dims[2] || p.levelt.planes_max || + t.n_elements!=uint64_t(cols)*rows*t.dims[2] || + !within(t.books_offset,((1ull<pending || impl_->failed || !impl_->staged || !input || + !tokens || tokens>impl_->max_tokens) { error="expert run state/shape invalid"; return false; } + auto& p=*impl_; + for (uint64_t i=0;i>>(p.compressed+role*p.packet,p.weights, + p.hidden*p.ff,p.level,p.words,p.books); + const uint32_t cols=role==2?p.ff:p.hidden, rows=role==2?p.hidden:p.ff; + multiply<<>>(p.weights,role==2?p.gate:p.x, + role==0?p.gate:(role==1?p.up:p.out),cols,rows); + if (role==1) activate<<<(tokens*p.ff+255)/256,256,0,p.stream>>>(p.gate,p.up,tokens*p.ff); + } + if (!check(cudaGetLastError(),"expert kernels",error) || + !check(cudaMemcpyAsync(p.host_out,p.out,uint64_t(tokens)*p.hidden*4,cudaMemcpyDeviceToHost,p.stream),"expert result",error) || + !check(cudaEventRecord(p.done,p.stream),"expert completion",error)) { + p.failed=true; return false; + } + return true; +} +bool ResidentExpert::finish(float* output, std::string& error) { + if (!impl_ || !impl_->pending || impl_->failed || !output) { + error="expert finish without a healthy pending run"; return false; + } + auto& p=*impl_; + if (!check(cudaEventSynchronize(p.done),"expert wait",error)) { p.failed=true; return false; } + p.pending=false; + for (uint64_t i=0;ipending || impl_->failed || !impl_->staged || role>2 || !output) { + error="expert matrix inspection requires idle resident state"; return false; + } + auto& p=*impl_; + decode<<<(p.hidden*p.ff+255)/256,256,0,p.stream>>>(p.compressed+role*p.packet,p.weights, + p.hidden*p.ff,p.level,p.words,p.books); + if (!check(cudaGetLastError(),"expert inspection decode",error) || + !check(cudaMemcpyAsync(output,p.weights,uint64_t(p.hidden)*p.ff*4,cudaMemcpyDeviceToHost,p.stream),"expert inspection copy",error) || + !check(cudaStreamSynchronize(p.stream),"expert inspection wait",error)) { + p.failed=true; return false; + } + return true; +} +} // namespace strata::kar diff --git a/gpu/kar/src/kar_expert_miss.cpp b/gpu/kar/src/kar_expert_miss.cpp new file mode 100644 index 00000000..02650f7e --- /dev/null +++ b/gpu/kar/src/kar_expert_miss.cpp @@ -0,0 +1,112 @@ +#include "kar_expert_miss.hpp" +#include "kar_expert.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::kar { +struct ExpertMiss::Impl { + int fd=-1; + const uint8_t* mapping=nullptr; + size_t bytes=0; + kar_archive* archive=nullptr; + uint32_t layers=0, experts=0, hidden=0, ff=0; + uint64_t computed=0; + std::vector records; + std::vector input, output; + ResidentExpert resident; + ~Impl() { + if(mapping) munmap(const_cast(mapping),bytes); + if(fd>=0) close(fd); + if(archive) kar_close(archive); + } +}; +ExpertMiss::ExpertMiss() = default; +ExpertMiss::~ExpertMiss() { + if(impl_)std::fprintf(stderr,"strata KAR experimental misses: %llu entries computed; compressed=%llu scratch=%llu bytes\n", + (unsigned long long)impl_->computed,(unsigned long long)impl_->resident.resident_bytes(), + (unsigned long long)impl_->resident.scratch_bytes()); +} +uint64_t ExpertMiss::computed() const {return impl_?impl_->computed:0;} +bool ExpertMiss::open(const char* path,uint32_t layers,uint32_t experts,uint32_t hidden, + uint32_t ff,uint32_t level,std::string& error) { + if(impl_ || !path || !*path || layers<1 || layers>512 || experts<1 || experts>65536) { + error="invalid KAR miss configuration";return false; + } + auto p=std::make_unique(); + // Keep a descriptor to the exact inode used by both mappings. Replacing the + // configured path during validation cannot select a different payload. + p->fd=::open(path,O_RDONLY|O_CLOEXEC); + struct stat st{}; + if(p->fd<0 || fstat(p->fd,&st)!=0 || !S_ISREG(st.st_mode) || st.st_size<=0) { + error="KAR miss archive is not a readable regular file";return false; + } + const std::string pinned="/proc/self/fd/"+std::to_string(p->fd); + if(kar_open(pinned.c_str(),KAR_OPEN_VERIFY_PAYLOAD,&p->archive)!=KAR_OK) { + error=std::string("KAR miss archive validation: ")+kar_last_error();return false; + } + p->bytes=static_cast(st.st_size); + void* mapped=mmap(nullptr,p->bytes,PROT_READ,MAP_PRIVATE,p->fd,0); + if(mapped==MAP_FAILED) {error="cannot map KAR miss archive";return false;} + p->mapping=static_cast(mapped); + p->layers=layers;p->experts=experts;p->hidden=hidden;p->ff=ff; + const char* roles[]={"gate","up","down"}; + for(uint32_t layer=0;layerarchive,name.c_str()); + if(index<0) {error="missing KAR expert tensor: "+name;return false;} + const auto* t=kar_tensor(p->archive,index); + if(t->n_dims!=3 || t->dims[0]!=(role==2?ff:hidden) || + t->dims[1]!=(role==2?hidden:ff) || t->dims[2]!=experts || + t->group!=32 || t->storage_class!=KAR_NESTED || t->nesting!=KAR_TOPDOWN || + levelplanes_min || level>t->planes_max) { + error="KAR expert tensor geometry/level mismatch: "+name;return false; + } + p->records.push_back(t); + } + if(!p->resident.open(hidden,ff,level,8,error))return false; + p->input.resize(size_t(hidden)*8);p->output.resize(size_t(hidden)*8); + std::fprintf(stderr,"strata KAR experimental: native verifier misses (short prompt and decode), level=%u, compressed=%llu scratch=%llu; quality not qualified\n", + level,(unsigned long long)p->resident.resident_bytes(),(unsigned long long)p->resident.scratch_bytes()); + impl_=std::move(p);return true; +} +bool ExpertMiss::compute(int64_t layer,const float* input,const int32_t* ids,int64_t tokens, + int64_t k,int32_t* kind,float* output,std::string& error) { + if(!impl_ || layer<0 || layer>=impl_->layers || tokens<1 || tokens>8 || k<1 || k>16 || + !input || !ids || !kind || !output) {error="invalid KAR miss dispatch";return false;} + auto& p=*impl_; + for(int64_t i=0;i=int64_t(p.experts)) {error="KAR routed expert out of range";return false;} + for(int64_t i=0;i=0)continue; + const uint32_t expert=ids[i]; + int64_t positions[8];uint32_t count=0; + // Native top-k routing never duplicates an expert within one token. + for(int64_t j=i;j(user)->compute(layer,input,ids,tokens,k,kind,output,error); +} +} diff --git a/gpu/kar/src/kar_expert_miss_test.cpp b/gpu/kar/src/kar_expert_miss_test.cpp new file mode 100644 index 00000000..9ec684a1 --- /dev/null +++ b/gpu/kar/src/kar_expert_miss_test.cpp @@ -0,0 +1,44 @@ +#include "kar_expert_miss.hpp" +#include +#include +#include +#include + +namespace { +void require(bool ok, const char* error) { if(!ok)throw std::runtime_error(error); } +} +int main(int argc,char** argv) try { + require(argc==2,"expected model-free archive path"); + std::string error; + strata::kar::ExpertMiss miss; + require(!miss.open(argv[1],2,2,64,32,1,error),"missing layer accepted"); + require(!miss.open(argv[1],1,2,64,32,2,error),"unavailable level accepted"); + require(miss.open(argv[1],1,2,64,32,1,error),error.c_str()); + constexpr int H=64,K=2,T=8; + std::vector x(T*H),out(T*K*H,123.0f); + std::vector ids(T*K),kind(T*K,-1); + for(int t=0;t +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +uint32_t number(const char* s) { + uint32_t n; + const auto [p,e]=std::from_chars(s,s+std::strlen(s),n); + if(e!=std::errc() || *p) throw std::runtime_error("invalid unsigned argument"); + return n; +} +struct Mapping { + int fd=-1; size_t size=0; const uint8_t* data=nullptr; + explicit Mapping(const char* path) { + fd=open(path,O_RDONLY|O_CLOEXEC); struct stat st{}; + if(fd<0 || fstat(fd,&st)!=0 || !S_ISREG(st.st_mode) || st.st_size<=0) { + if(fd>=0) close(fd); fd=-1; throw std::runtime_error("mapping stat failed"); + } + size=static_cast(st.st_size); + void* p=mmap(nullptr,size,PROT_READ,MAP_PRIVATE,fd,0); + if(p==MAP_FAILED) { close(fd);fd=-1;throw std::runtime_error("mapping failed"); } + data=static_cast(p); + } + ~Mapping(){if(data)munmap(const_cast(data),size);if(fd>=0)close(fd);} +}; +void write(const std::filesystem::path& p,const std::vector& v) { + std::ofstream f(p,std::ios::binary); f.write(reinterpret_cast(v.data()),v.size()*4); + if(!f)throw std::runtime_error("private evidence write failed"); +} +} +int main(int argc,char** argv) try { + if(argc!=7) { + std::fprintf(stderr,"usage: strata-kar-expert-probe ARCHIVE LAYER EXPERT LEVEL TOKENS NEW_PRIVATE_OUTPUT\n");return 2; + } + umask(0077); + const uint32_t layer=number(argv[2]),expert=number(argv[3]),level=number(argv[4]),tokens=number(argv[5]); + if(layer>4096 || tokens<1 || tokens>8)throw std::runtime_error("layer/token bound"); + const std::filesystem::path output(argv[6]); + if(!std::filesystem::create_directory(output))throw std::runtime_error("output already exists"); + kar_archive* raw=nullptr; + if(kar_open(argv[1],KAR_OPEN_VERIFY_PAYLOAD,&raw)!=KAR_OK)throw std::runtime_error(kar_last_error()); + std::unique_ptr archive(raw,kar_close); + const char* suffix[]={"gate","up","down"}; const kar_tensor_info* t[3]; + for(int i=0;i<3;++i) { + std::string name="blk."+std::to_string(layer)+".ffn_"+suffix[i]+"_exps.weight"; + const int index=kar_find(raw,name.c_str()); + if(index<0)throw std::runtime_error("missing expert tensor"); + t[i]=kar_tensor(raw,index); + } + if(t[0]->dims[0]>16384 || t[0]->dims[1]>16384)throw std::runtime_error("expert geometry cap"); + const uint32_t hidden=t[0]->dims[0],ff=t[0]->dims[1]; + Mapping file(argv[1]); strata::kar::ResidentExpert resident; std::string error; + if(!resident.open(hidden,ff,level,8,error) || + !resident.stage(file.data,file.size,*t[0],*t[1],*t[2],expert,error))throw std::runtime_error(error); + std::vector matrix(uint64_t(hidden)*ff),input(uint64_t(tokens)*hidden),result(input.size()); + for(int role=0;role<3;++role) { + if(!resident.inspect_matrix(role,matrix.data(),error))throw std::runtime_error(error); + write(output/(std::string(suffix[role])+".f32"),matrix); + } + for(size_t i=0;i repeat(result.size()); + if(!resident.run(input.data(),tokens,error) || !resident.finish(repeat.data(),error) || repeat!=result) + throw std::runtime_error("resident reuse failed"); + if(resident.stage(file.data,file.size,*t[0],*t[1],*t[2],uint32_t(t[0]->dims[2]),error)) + throw std::runtime_error("out-of-range expert accepted"); + if(resident.run(input.data(),tokens,error))throw std::runtime_error("run after rejected stage accepted"); + if(!resident.stage(file.data,file.size,*t[0],*t[1],*t[2],expert,error))throw std::runtime_error(error); + input[0]=std::numeric_limits::infinity(); + if(resident.run(input.data(),tokens,error))throw std::runtime_error("nonfinite input accepted"); + auto invalid=*t[0]; invalid.books_offset=std::numeric_limits::max()-3; + if(resident.stage(file.data,file.size,invalid,*t[1],*t[2],expert,error)) + throw std::runtime_error("overflowing metadata accepted"); + if(resident.stage(file.data,32,*t[0],*t[1],*t[2],expert,error)) + throw std::runtime_error("truncated archive accepted"); + std::ofstream meta(output/"metadata.json"); + meta<<"{\"hidden\":"<name<<"\",\"books_offset\":"<books_offset + <<",\"scales_offset\":"<scales_offset<<",\"planes_offset\":"<planes_offset + <<",\"plane_stride_bytes\":"<plane_stride_bytes<<"}"; + } + meta<<"]}\n";if(!meta)throw std::runtime_error("metadata write failed"); + std::printf("resident_bytes=%llu scratch_bytes=%llu tokens=%u; private oracle comparison pending\n", + (unsigned long long)resident.resident_bytes(),(unsigned long long)resident.scratch_bytes(),tokens); + return 0; +} catch(const std::exception& e) {std::fprintf(stderr,"expert probe: %s\n",e.what());return 1;} diff --git a/gpu/kar/src/kar_expert_test.cpp b/gpu/kar/src/kar_expert_test.cpp new file mode 100644 index 00000000..ef567cac --- /dev/null +++ b/gpu/kar/src/kar_expert_test.cpp @@ -0,0 +1,87 @@ +#include "kar_expert.hpp" +#include +#include +#include +#include +#include + +namespace { +void require(bool ok, const char* what) { if(!ok)throw std::runtime_error(what); } +void u16(std::vector& b,size_t at,uint16_t n) { b[at]=n; b[at+1]=n>>8; } +void u32(std::vector& b,size_t at,uint32_t n) { + for(int i=0;i<4;++i)b[at+i]=n>>(8*i); +} +} +int main() try { + constexpr uint32_t H=64,F=32,E=2,W=H*F/32; + // Independent synthetic decoded weights are +/-1 times 1/32. Each of + // three roles and two experts has its own alternating bit pattern. + std::vector archive(3*4096,0); + kar_tensor_info tensors[3]{}; + std::vector reference[3]; + for(uint32_t role=0;role<3;++role) { + auto& t=tensors[role]; const size_t base=role*4096; + t.storage_class=KAR_NESTED;t.nesting=KAR_TOPDOWN;t.group=32;t.n_dims=3; + t.dims[0]=role==2?F:H;t.dims[1]=role==2?H:F;t.dims[2]=E; + t.n_elements=H*F*E;t.planes_min=t.planes_max=1;t.planes_stored=1; + t.books_offset=base;t.scales_offset=base+32;t.planes_offset=base+512; + t.plane_stride_bytes=W*E*4; + u16(archive,base,0xbc00);u16(archive,base+2,0x3c00); // -1,+1 + reference[role].resize(H*F*E); + for(uint32_t word=0;word' + for name, output in [('plain', markup), ('reason', 'Think.\n\n' + markup), ('answer', 'OK')]: + data = output.encode() + (root / name).write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n') + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf 'READY 262144 stop\\n' +count=0 +while IFS= read -r line; do + case "$line" in + 'GEN '*) + count=$((count + 1)) + cat "$2/next" ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'} + + def request(path, body=None): + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + conn.request('POST' if body is not None else 'GET', path, + json.dumps(body) if body is not None else None, + {'Content-Type': 'application/json'}) + response = conn.getresponse() + status, data = response.status, response.read().decode() + conn.close() + return status, data + + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 8 + while True: + try: + if request('/ready')[0] == 200: + break + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline + time.sleep(0.02) + for effort in ['none', 'low']: + for stream in [False, True]: + publish((root / ('plain' if effort == 'none' else 'reason')).read_text()) + payload = {'model': 'fixture', 'input': 'Run source', 'max_output_tokens': 1024, + 'reasoning': {'effort': effort}, 'stream': stream, + 'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]} + code, data = request('/v1/responses', payload) + assert code == 200, (code, data) + if stream: + events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] + assert [e['sequence_number'] for e in events] == list(range(len(events))) + assert events[-1]['type'] == 'response.completed' + assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source + assert next(e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done') == source + assert not any('function_call_arguments' in e['type'] for e in events) + result = events[-1]['response'] + else: + result = json.loads(data) + call = result['output'][-1] + assert call['type'] == 'custom_tool_call' and call['input'] == source + assert call['name'] == 'run' and 'arguments' not in call + publish((root / 'answer').read_text()) + code, data = request('/v1/responses', {'model': 'fixture', 'reasoning': {'effort': 'none'}, + 'previous_response_id': result['id'], 'input': [ + {'type': 'custom_tool_call_output', 'call_id': call['call_id'], 'output': 'done'}]}) + assert code == 200 and json.loads(data)['output'][0]['content'][0]['text'] == 'OK' + regex = r'\n print\("Привіт 🌍"\)\n' + for namespaced in [False, True]: + for effort in ['none', 'low']: + for stream in [False, True]: + for valid in [True, False]: + tool = {'type': 'custom', 'name': 'run', 'format': { + 'type': 'grammar', 'syntax': 'regex', 'definition': regex if valid else 'NEVER_MATCH'}} + tools = [{'type': 'namespace', 'name': 'code', 'tools': [tool]}] if namespaced else [tool] + name = 'ns_' + hashlib.sha256(b'code/run').hexdigest()[:24] if namespaced else 'run' + output = markup.replace('', f'') + if effort == 'low': + output = 'Think.\n\n' + output + data = output.encode() + publish(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n') + payload = {'model': 'fixture', 'input': 'Run source', 'max_output_tokens': 1024, + 'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools} + code, data = request('/v1/responses', payload) + if stream: + assert code == 200, (code, data) + events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] + assert [e['sequence_number'] for e in events] == list(range(len(events))) + assert events[-1]['type'] == ('response.completed' if valid else 'response.failed') + if not valid: + assert not any('custom_tool_call_input' in e['type'] for e in events) + assert not any(e.get('item', {}).get('type') == 'custom_tool_call' for e in events) + continue + assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source + result = events[-1]['response'] + else: + if not valid: + assert code == 502, (code, data) + assert 'output' not in json.loads(data) + continue + assert code == 200, (code, data) + result = json.loads(data) + call = result['output'][-1] + assert call['type'] == 'custom_tool_call' and call['input'] == source + assert call['name'] == 'run' and 'arguments' not in call + assert call.get('namespace') == ('code' if namespaced else None) + saved_id, saved_call = result['id'], call['call_id'] + publish((root / 'answer').read_text()) + code, data = request('/v1/responses', {'model': 'fixture', 'reasoning': {'effort': 'none'}, + 'previous_response_id': saved_id, 'input': [ + {'type': 'custom_tool_call_output', 'call_id': saved_call, 'output': 'done'}]}) + assert code == 200 and json.loads(data)['output'][0]['content'][0]['text'] == 'OK' + payload['tools'] = [{'type': 'custom', 'name': 'run'}] + payload['tools'][0]['format'] = {'type': 'grammar', 'syntax': 'lark', 'definition': 'start: WORD'} + assert request('/v1/responses', payload)[0] == 400 + for definition in ['[', '(?=a)', 'a*?', '(?x:a)', 'a\nb', 'a' * 8193]: + payload['tools'][0]['format'] = {'type': 'grammar', 'syntax': 'regex', 'definition': definition} + assert request('/v1/responses', payload)[0] == 400 + assert json.loads(request('/metrics')[1])['generation']['started'] == 22 + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + print('Custom text/regex tools passed: 22 generations, JSON/SSE, reasoning, namespace, exact input, no invalid call publication, continuation, invalid grammar rejection; CPU only') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-embedded-engine.py b/scripts/smoke-embedded-engine.py new file mode 100644 index 00000000..3fe797f3 --- /dev/null +++ b/scripts/smoke-embedded-engine.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Verify an embedded synthetic CPU ELF through the Linux serving supervisor.""" +import fcntl +import errno +import hashlib +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + fixture = Path(sys.argv[2]).resolve() + info = json.loads(subprocess.check_output([binary, 'engine-info'])) + assert info['embedded'] is True and info['shared_libraries_bundled'] is False + assert info['sha256'] == hashlib.sha256(fixture.read_bytes()).hexdigest() + assert info['bytes'] == fixture.stat().st_size + assert subprocess.check_output([binary, 'engine-help'], text=True).strip() == 'embedded fixture help (GPU hidden)' + spec = importlib.util.spec_from_file_location('cancel_smoke', Path(__file__).with_name('smoke-worker-cancel.py')) + helper = importlib.util.module_from_spec(spec) + spec.loader.exec_module(helper) + with tempfile.TemporaryDirectory(prefix='strata-embedded-smoke-') as directory: + root = Path(directory) + helper.tokenizer(root) + pid_file = root / 'worker.pid' + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + config = root / 'config.json' + config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'embedded-fixture', 'engine_probe': True, + 'engine': {'executable': '@embedded', 'args': [str(pid_file)], + 'tokenizer_dir': str(root), 'startup_timeout_s': 5, + 'max_restarts': 1}})) + checked = json.loads(subprocess.check_output( + [binary, 'check-config', '--config', config], env={'PATH': os.defpath}, text=True)) + assert checked['engine'] == 'embedded' and checked['inference_configured'] + assert checked['readiness_checked'] is False and not pid_file.exists() + assert checked['engine_probe_configured'] and not checked['engine_probe_checked'] + provisioned = json.loads(subprocess.check_output([binary, 'provision', '--config', str(config)], text=True)) + assert not provisioned['worker_started'] and not pid_file.exists() + def request(path, body=None): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=10) + try: + connection.request('POST' if body else 'GET', path, body, + {'Content-Type': 'application/json'}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + with tempfile.TemporaryFile() as log: + process = subprocess.Popen([binary, 'serve', '--config', config], env={'PATH': os.defpath}, + stdout=log, stderr=log) + worker_pids = [] + try: + def ready(previous=None): + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + assert process.poll() is None + try: + pid = int(pid_file.read_text()) + if pid != previous and request('/status')[1]['ready']: + worker_pids.append(pid) + return pid + except (OSError, ValueError): + pass + time.sleep(.02) + raise AssertionError('embedded worker did not become ready') + first = ready() + memfds = [] + for path in Path(f'/proc/{process.pid}/fd').iterdir(): + try: + if 'memfd:strata-engine' in os.readlink(path): + memfds.append(path) + except FileNotFoundError: + pass # HTTP socket fds can close between enumeration and readlink. + assert len(memfds) == 1 + fd_path = memfds[0] + assert hashlib.sha256(fd_path.read_bytes()).hexdigest() == info['sha256'] + with fd_path.open('rb', buffering=0) as handle: + assert fcntl.fcntl(handle, fcntl.F_GET_SEALS) & 15 == 15 + try: + with fd_path.open('r+b', buffering=0) as handle: + handle.write(b'x') + raise AssertionError('sealed engine allowed a write') + except OSError as error: + assert error.errno in (errno.EPERM, errno.ETXTBSY), error + def generate(): + code, result = request('/v1/responses', json.dumps({ + 'model': 'embedded-fixture', 'input': 'Reply A', 'max_output_tokens': 1, + 'reasoning': {'effort': 'none'}})) + assert code == 200 and result['status'] == 'completed', result + assert result['output'][0]['content'][0]['text'] == 'A', result + return result['output'][0]['content'] + expected = generate() + os.kill(first, signal.SIGKILL) + second = ready(first) + assert second != first and generate() == expected + process.terminate() + assert process.wait(timeout=10) == 0 + assert not fd_path.exists() + assert all(not Path(f'/proc/{pid}').exists() for pid in worker_pids) + # The identical fixture as an external executable is the baseline. + external = json.loads(config.read_text()) + external['engine']['executable'] = str(fixture) + config.write_text(json.dumps(external)) + process = subprocess.Popen([binary, 'serve', '--config', config], env={'PATH': os.defpath}, + stdout=log, stderr=log) + ready(second) + assert generate() == expected + process.terminate() + assert process.wait(timeout=10) == 0 + assert all(not Path(f'/proc/{pid}').exists() for pid in worker_pids) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill(); process.wait() + print('Embedded CPU ELF passed: exact payload digest, seals, inference A, crash restart, external baseline equality, worker/fd cleanup') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-engine-probe.py b/scripts/smoke-engine-probe.py new file mode 100644 index 00000000..e433885c --- /dev/null +++ b/scripts/smoke-engine-probe.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""CPU-only engine loader/--help preflight, before any model acquisition.""" +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = str(Path(sys.argv[1]).resolve()) + with tempfile.TemporaryDirectory(prefix='strata-engine-probe-') as tmp: + root = Path(tmp).resolve() + engine, marker, pid_file = [root / n for n in ['engine', 'help-called', 'pid']] + config_path = root / 'config.json' + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + config = {'bind': f'127.0.0.1:{port}', 'engine': {'executable': str(engine), + 'args': ['must-not-reach-help']}} + assets = [{'manifest': str(root / 'absent.json'), 'directory': str(root / 'output')}] + count = 0 + + def fixture(body): + marker.unlink(missing_ok=True) + engine.write_text(f'''#!/bin/sh +[ "$#" = 1 ] && [ "$1" = --help ] || exit 92 +[ "${{CUDA_VISIBLE_DEVICES+x}}" = x ] && [ -z "$CUDA_VISIBLE_DEVICES" ] || exit 93 +printf called > "{marker}" +printf '%s' "$$" > "{pid_file}" +{body} +''') + engine.chmod(0o700) + + def run(command='provision', ok=False, contains=None): + nonlocal count + config_path.write_text(json.dumps(config)) + start = time.monotonic() + result = subprocess.run([binary, command, '--config', str(config_path)], + env={'PATH':os.defpath, 'CUDA_VISIBLE_DEVICES':'0'}, + capture_output=True, text=True, timeout=15) + assert (result.returncode == 0) == ok, (result.stdout, result.stderr) + if contains: + assert contains in result.stderr, result.stderr + assert 'private-child-output' not in result.stderr + result.stdout + assert not (root / 'output').exists() + assert not (root / '.output.strata-stage').exists() + with socket.socket() as sock: + assert sock.connect_ex(('127.0.0.1',port)) != 0 + count += 1 + return result, time.monotonic()-start + + fixture('exit 127') + run(ok=True) # default does not execute the probe + assert not marker.exists() + config['engine_probe'] = True + result, _ = run('check-config', ok=True) + report = json.loads(result.stdout) + assert report['engine_probe_configured'] and not report['engine_probe_checked'] + assert not marker.exists() + worker = config.pop('engine') + run(contains='requires an engine executable') + config['engine'] = worker + config['engine_probe'] = 'yes' + run() + config['engine_probe'] = True + config['assets'] = assets + engine.unlink() + for command in ['provision', 'serve']: + run(command, contains='could not start') + # Permission failure and invalid executable/loader are early failures. + fixture('exit 0') + engine.chmod(0o600) + run(contains='could not start') + engine.write_bytes(b'not an executable format\0') + engine.chmod(0o700) + result, _ = run() + assert 'engine' in result.stderr and ('could not start' in result.stderr or 'probe failed' in result.stderr) + engine.write_text('#!/nonexistent-strata-test-loader\n') + run(contains='could not start') + fixture("printf private-child-output; printf private-child-output >&2; exit 127") + for command in ['provision', 'serve']: + run(command, contains='engine --help probe failed') + assert marker.exists() + # Successful helper exits before acquisition; no serving arguments pass. + fixture('exit 0') + for command in ['provision', 'serve']: + result, _ = run(command) + assert 'engine' not in result.stderr.lower(), result.stderr + assert marker.exists() + config.pop('assets') + run(ok=True) + assert marker.exists() + # Direct-child timeout cleanup, with no grandchildren or persistent process. + config['assets'] = assets + fixture('exec /bin/sleep 60') + _, elapsed = run(contains='timed out after 10 seconds') + assert 9.5 <= elapsed < 14.5, elapsed + try: + os.kill(int(pid_file.read_text()), 0) + except ProcessLookupError: + pass + else: + raise AssertionError('timed-out child alive or unreaped') + print(f'{count} engine probe scenarios passed; no model or GPU inference') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-generation-deadline.py b/scripts/smoke-generation-deadline.py new file mode 100644 index 00000000..e4ad0ede --- /dev/null +++ b/scripts/smoke-generation-deadline.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""CPU-only HTTP execution deadline, no replay, and recovery acceptance.""" +import concurrent.futures +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def exercise(binary, fixture, streaming, restarts): + with tempfile.TemporaryDirectory(prefix='strata-deadline-http-') as directory: + root = Path(directory) + fixture.tokenizer(root) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf '%s\\n' "$$" >> "$2/pids" +if [ -e "$2/booted" ]; then recovered=1; else recovered=0; fi +: > "$2/booted" +printf 'READY 262144 stop\\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) + printf '%s\\n' "$line" >> "$2/requests" + printf 'T 79\\n' + if [ "$recovered" = 1 ]; then + printf 'T 75\\nDONE 2 7 1.0 2.0 stop\\n' + else + # Never finish this command. An execution deadline must kill us. + while IFS= read -r ignored; do :; done + exit 3 + fi ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_GENERATION_TIMEOUT_S': '1', + 'STRATA_MAX_WORKER_RESTARTS': str(restarts)} + + def request(path, body=None): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + try: + connection.request('POST' if body is not None else 'GET', path, + json.dumps(body) if body is not None else None, + {'Content-Type': 'application/json'}) + response = connection.getresponse() + content = response.read().decode() + return response.status, content + finally: + connection.close() + + def get(path): + return json.loads(request(path)[1]) + + def wait_for(predicate): + deadline = time.monotonic() + 8 + while True: + try: + if predicate(): + return + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline, 'condition timed out' + time.sleep(0.01) + + with tempfile.TemporaryFile() as logs, concurrent.futures.ThreadPoolExecutor(2) as pool: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, + start_new_session=True) + try: + wait_for(lambda: request('/ready')[0] == 200) + payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8, + 'reasoning': {'effort': 'none'}, 'stream': streaming} + active = pool.submit(request, '/v1/responses', payload) + wait_for(lambda: (root / 'requests').exists()) + original_pid = int((root / 'pids').read_text().splitlines()[0]) + queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False}) + wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 2) + code, content = active.result(timeout=6) + if streaming: + assert code == 200 + events = [json.loads(line[5:]) for line in content.splitlines() if line.startswith('data:')] + assert [e['sequence_number'] for e in events] == list(range(len(events))) + assert events[-1]['type'] == 'response.failed' + assert events[-1]['response']['status'] == 'failed' + assert 'configured execution deadline' in json.dumps(events[-1]) + assert not any(e['type'] == 'response.completed' for e in events) + else: + assert code == 502 and json.loads(content)['error']['code'] == 'generation_failed' + assert 'configured execution deadline' in content + assert queued.result(timeout=6)[0] in (502, 503) + assert len((root / 'requests').read_text().splitlines()) == 1, 'queued work replayed' + wait_for(lambda: get('/admin/lifecycle')['generation_jobs'] == 0) + assert request('/ready')[0] == 503 + assert get('/metrics')['generation']['failed_or_interrupted'] == 1 + try: + os.kill(original_pid, 0) + except ProcessLookupError: + pass + else: + raise AssertionError('expired worker still alive') + if restarts: + wait_for(lambda: request('/ready')[0] == 200) + code, content = request('/v1/responses', {**payload, 'stream': False}) + assert code == 200 and json.loads(content)['output'][0]['content'][0]['text'] == 'OK' + assert len((root / 'requests').read_text().splitlines()) == 2 + assert len((root / 'pids').read_text().splitlines()) == 2 + assert get('/metrics')['generation']['completed'] == 1 + else: + assert get('/status')['worker'] == 'failed' + assert request('/health')[0] == 200 + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + for streaming in (False, True): + for restarts in (0, 1): + exercise(binary, fixture, streaming, restarts) + print('Generation deadline: 4 HTTP cases passed; terminal failures, kill/reap, no replay, fresh recovery output exactly OK; CPU only') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-gpu-requirement.py b/scripts/smoke-gpu-requirement.py new file mode 100644 index 00000000..50cf0ccd --- /dev/null +++ b/scripts/smoke-gpu-requirement.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""CPU fixtures for explicit CUDA driver policy. Never runs inference or CUDA.""" +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = str(Path(sys.argv[1]).resolve()) + if sys.platform == 'linux' and Path('/proc/driver/nvidia/version').exists(): + raise SystemExit('Requires an isolated CPU runner without an installed NVIDIA kernel driver') + with tempfile.TemporaryDirectory(prefix='strata-driver-gate-') as tmp: + root = Path(tmp).resolve() + probe = root / 'nvidia-smi' + marker = root / 'probe-called' + worker_marker = root / 'worker-called' + worker = root / 'worker' + worker.write_text(f'#!/bin/sh\n: > "{worker_marker}"\nexit 1\n') + worker.chmod(0o700) + path = root / 'config.json' + env = {'PATH': str(root)} + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + config = {'bind': f'127.0.0.1:{port}', 'engine': {'executable': str(worker)}} + count = 0 + + def run(command='provision', ok=False, contains=None, timeout=10): + nonlocal count + path.write_text(json.dumps(config)) + started = time.monotonic() + result = subprocess.run([binary, command, '--config', str(path)], env=env, + capture_output=True, text=True, timeout=timeout) + assert (result.returncode == 0) == ok, (result.stdout, result.stderr) + if contains: + assert contains in result.stderr, result.stderr + assert not worker_marker.exists(), 'worker started before policy/asset checks' + assert not (root / 'output').exists() + assert not (root / '.output.strata-stage').exists() + with socket.socket() as sock: + assert sock.connect_ex(('127.0.0.1', port)) != 0, 'listener opened' + count += 1 + return result, time.monotonic() - started + + def fake(body): + marker.unlink(missing_ok=True) + probe.write_text(f'#!/bin/sh\nprintf called > "{marker}"\n{body}\n') + probe.chmod(0o700) + + # CPU profiles do not query the driver. check-config stays read-only. + fake('exit 1') + run(ok=True) + assert not marker.exists() + config['gpu_requirement'] = 'cuda-13.0-linux' + result, _ = run('check-config', ok=True) + report = json.loads(result.stdout) + assert report['gpu_requirement'] == 'cuda-13.0-linux' + assert report['gpu_requirement_checked'] is False + assert not marker.exists() + config['gpu_requirement'] = 'unknown' + run() + config['gpu_requirement'] = 'cuda-13.0-linux' + engine = config.pop('engine') + run(contains='requires an engine executable') + config['engine'] = engine + # An absent manifest proves failure happens before asset acquisition. + config['assets'] = [{'manifest': str(root / 'absent.json'), 'directory': str(root / 'output')}] + if sys.platform != 'linux': + run(contains='requires Linux') + run('serve', contains='requires Linux') + assert not marker.exists() + print(f'{count} driver policy scenarios passed; Linux probe cases require hosted CPU runner') + return + probe.unlink() + run(contains='driver unavailable') + cases = [ + ("printf '579.99.99\\n'", 'below'), + ("printf '580.65.05\\n'", 'below'), + ("printf '580.65.06\\n580.1.0\\n'", 'below'), + ("printf 'secret malformed output\\n'", 'malformed'), + ("printf '580.65.06\\n'; exit 1", 'query failed'), + ("printf ''", 'malformed'), + ("printf '580.65.06\\nBAD\\n'", 'malformed'), + ("i=0; while [ $i -lt 9000 ]; do printf x; i=$((i+1)); done", 'exceeded 8 KiB'), + ] + for body, error in cases: + fake(body) + run(contains=error) + run('serve', contains=error) + assert marker.exists() + # Bounded probe is killed/reaped. exec keeps the PID unambiguous. + pid_path = root / 'probe.pid' + fake(f'printf "%s" "$$" > "{pid_path}"\nexec /bin/sleep 60') + _, elapsed = run(contains='timed out after 5 seconds') + assert 4.5 <= elapsed < 9, elapsed + pid = int(pid_path.read_text()) + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise AssertionError('timed-out probe still alive or unreaped') + # Accepted versions proceed to manifest lookup, and no farther. + for version in ['580.65.06', '580.100.0', '600.1.0']: + fake(f"printf '{version}\\n'") + result, _ = run() + assert 'NVIDIA' not in result.stderr, result.stderr + assert marker.exists() + config.pop('assets') + run(ok=True) + config['assets'] = [{'manifest': str(root / 'absent.json'), 'directory': str(root / 'output')}] + print(f'{count} driver policy scenarios passed; CPU fixtures only, no GPU readiness claim') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-input-tokens.py b/scripts/smoke-input-tokens.py new file mode 100644 index 00000000..fefa1664 --- /dev/null +++ b/scripts/smoke-input-tokens.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Compare native HTTP input counts with actual GEN wire tokens, without a GPU.""" +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + with tempfile.TemporaryDirectory(prefix='strata-input-tokens-') as directory: + root = Path(directory) + fixture.tokenizer(root) + key = 'fixture-only-input-count-key-00001' + (root / 'key').write_text(key) + (root / 'key').chmod(0o600) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf '%s' "$$" > "$2/pid" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) printf '%s\n' "$line" >> "$2/wire"; cat "$2/output" ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_MODEL_ID': 'fixture', 'STRATA_API_KEY_FILE': str(root / 'key'), + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0', + 'STRATA_RESPONSE_HISTORY_DIR': str(root / 'history'), 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1'} + + def request(method, path, payload=None, auth=True, raw=None): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + headers = {'Content-Type': 'application/json'} + if auth: + headers['Authorization'] = 'Bearer ' + key + try: + connection.request(method, path, raw if raw is not None else json.dumps(payload) if payload is not None else None, headers) + response = connection.getresponse() + data = response.read().decode() + if response.getheader('Content-Type', '').startswith('text/event-stream'): + events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] + data = events[-1]['response'] + else: + data = json.loads(data) if data else None + return response.status, data + finally: + connection.close() + + def wire(): + return (root / 'wire').read_bytes() if (root / 'wire').exists() else b'' + + def snapshot(): + return {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()} + + def count(payload, expected=200): + before, stored = wire(), snapshot() + code, data = request('POST', '/v1/responses/input_tokens', payload) + assert code == expected, (code, data) + assert wire() == before and snapshot() == stored, 'count must not generate or write history' + if code == 200: + assert set(data) == {'object', 'input_tokens'} and data['object'] == 'response.input_tokens', data + assert isinstance(data['input_tokens'], int) and data['input_tokens'] > 0 + return data + + payload = {'model': 'fixture', 'input': 'Привіт 🌍', 'max_output_tokens': 8, 'reasoning': {'effort': 'none'}} + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 10 + while True: + try: + if request('GET', '/ready')[0] == 200: + break + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline + time.sleep(.02) + assert request('POST', '/v1/responses/input_tokens', payload, auth=False)[0] == 401 + assert request('POST', '/v1/responses/input_tokens', raw='{')[0] == 400 + assert request('GET', '/v1/responses/input_tokens')[0] == 405 + tools = [{'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'key': {'type': 'string'}}}}, + {'type': 'custom', 'name': 'patch'}, + {'type': 'namespace', 'name': 'code', 'tools': [{'type': 'custom', 'name': 'run'}]}] + cases = [payload, {**payload, 'stream': True, 'instructions': 'Answer briefly.'}, + {**payload, 'tools': tools}, + {**payload, 'reasoning': {'effort': 'high'}}, + {**payload, 'input': [{'type': 'function_call', 'call_id': 'c1', 'name': 'lookup', 'arguments': '{"key":"value"}'}, + {'type': 'function_call_output', 'call_id': 'c1', 'output': 'Found 🌍'}], 'tools': tools}] + ordinary_output = 'T 65\nDONE 1 7 1.0 2.0 stop\n' + parent = None + for current in cases: + (root / 'output').write_text(('T 259\nT 10\n' if current['reasoning']['effort'] == 'high' else '') + ordinary_output) + measured = count(current)['input_tokens'] + code, result = request('POST', '/v1/responses', current) + assert code == 200 and result['status'] == 'completed', result + ids = wire().decode().splitlines()[-1].split()[-1].split(',') + assert measured == len(ids), (measured, len(ids)) # actual engine wire, not DONE usage + parent = result['id'] + (root / 'output').write_text(ordinary_output) + continued = {**payload, 'previous_response_id': parent, 'instructions': 'New instruction.'} + measured = count(continued)['input_tokens'] + code, result = request('POST', '/v1/responses', continued) + assert code == 200 and measured == len(wire().decode().splitlines()[-1].split()[-1].split(',')) + assert request('DELETE', '/v1/responses/' + parent)[0] == 200 + assert count(continued, 404)['error']['code'] == 'response_not_found' + for bad, status in [({**payload, 'model': 'other'}, 404), ({**payload, 'input': []}, 400), + ({**payload, 'input': [{'type': 'input_image'}]}, 400), + ({**payload, 'truncation': 'auto'}, 501), ({**payload, 'unknown': True}, 400)]: + counted = count(bad, status) + code, generated = request('POST', '/v1/responses', bad) + assert code == status and counted == generated, (counted, generated) + count({**payload, 'store': False}) + # Hold one admitted body open; count must respect shared capacity. + with socket.create_connection(('127.0.0.1', port), timeout=5) as held: + held.sendall(('POST /v1/responses/input_tokens HTTP/1.1\r\nHost: localhost\r\n' + 'Content-Type: application/json\r\nContent-Length: 100\r\n' + 'Authorization: Bearer ' + key + '\r\n\r\n{').encode()) + deadline = time.monotonic() + 5 + while request('GET', '/admin/lifecycle')[1]['requests_in_flight'] == 0: + assert time.monotonic() < deadline + time.sleep(.02) + count(payload, 429) + deadline = time.monotonic() + 5 + while request('GET', '/admin/lifecycle')[1]['requests_in_flight']: + assert time.monotonic() < deadline + time.sleep(.02) + request('POST', '/admin/drain', {}) + count(payload, 503) + request('POST', '/admin/resume', {}) + expected = count(payload) + os.kill(int((root / 'pid').read_text()), signal.SIGKILL) + deadline = time.monotonic() + 5 + while request('GET', '/ready')[0] == 200: + assert time.monotonic() < deadline + time.sleep(.02) + assert count(payload) == expected + assert request('POST', '/v1/responses', payload)[0] == 503 + assert request('GET', '/admin/lifecycle')[1]['generation_jobs'] == 0 + finally: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + if process.returncode != 0: + logs.seek(0) + raise AssertionError(logs.read().decode()) + print('input_tokens: exact GEN wire parity for text/stream/tools/reasoning/continuation, validation/auth/drain/outage and no history mutation PASS') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-messages.py b/scripts/smoke-messages.py new file mode 100644 index 00000000..be52a020 --- /dev/null +++ b/scripts/smoke-messages.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Native Messages real HTTP fixture: wire parity, named SSE and cancellation.""" +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + with tempfile.TemporaryDirectory(prefix='strata-messages-') as directory: + root = Path(directory) + fixture.tokenizer(root) + key = 'fixture-only-messages-key-0000001' + (root / 'key').write_text(key) + (root / 'key').chmod(0o600) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf '%s' "$$" > "$2/pid" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) + printf '%s\n' "$line" >> "$2/wire" + if [ -e "$2/hold" ]; then + printf 'T 65\n' + IFS= read -r line || exit 3 + [ "$line" = STOP ] || exit 4 + : > "$2/stopped" + printf 'DONE 1 7 1.0 2.0 stop\n' + else cat "$2/output"; fi ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', 'STRATA_MODEL_ID': 'fixture', + 'STRATA_API_KEY_FILE': str(root / 'key'), 'STRATA_ENGINE_EXE': str(engine), + 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), 'STRATA_TOKENIZER_DIR': str(root), + 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1', 'STRATA_MAX_WORKER_RESTARTS': '0', + 'STRATA_RESPONSE_HISTORY_DIR': str(root / 'history')} + path = '/v1/messages' + count_path = path + '/count_tokens' + + def open_request(method, target, payload=None, headers=None, raw=None): + h = {'Content-Type': 'application/json'} + h.update({'x-api-key': key, 'anthropic-version': '2023-06-01'} if target in (path, count_path) else {'Authorization': 'Bearer ' + key}) + if headers: + h.update(headers) + h = {k: v for k, v in h.items() if v is not None} + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=6) + conn.request(method, target, raw if raw is not None else json.dumps(payload) if payload is not None else None, h) + return conn, conn.getresponse() + + def request(method, target, payload=None, **kwargs): + conn, response = open_request(method, target, payload, **kwargs) + try: + data = response.read().decode() + if response.getheader('Content-Type', '').startswith('text/event-stream'): + assert '[DONE]' not in data + events = [] + for frame in data.strip().split('\n\n'): + lines = frame.splitlines() + name = next(line[7:] for line in lines if line.startswith('event: ')) + value = json.loads(next(line[6:] for line in lines if line.startswith('data: '))) + assert value['type'] == name + events.append(value) + return response.status, events + return response.status, json.loads(data) if data else None + finally: + conn.close() + + def output(text, reason='stop'): + data = text.encode() + (root / 'output').write_text(''.join(f'T {b}\n' for b in data) + f'DONE {len(data)} 7 1.0 2.0 {reason} 0 0 2\n') + + def wire(): + return (root / 'wire').read_text().splitlines() if (root / 'wire').exists() else [] + + def count(current, expected=200, **kwargs): + payload = {k: v for k, v in current.items() if k not in ('max_tokens', 'stream')} + before = wire() + stored = {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()} + code, value = request('POST', count_path, payload, **kwargs) + assert code == expected, (code, value) + assert wire() == before + assert stored == {p.name: p.read_bytes() for p in (root / 'history').iterdir() if p.is_file()} + if code == 200: + assert set(value) == {'input_tokens'} and isinstance(value['input_tokens'], int) and value['input_tokens'] > 0 + return value['input_tokens'] + assert value['type'] == 'error' + + def rebuild(events): + assert events[0]['type'] == 'message_start' and events[-1] == {'type': 'message_stop'} + assert sum(e['type'] == 'message_stop' for e in events) == 1 + message = events[0]['message'] + assert message['content'] == [] and message['stop_reason'] is None + active = None + args = '' + for e in events[1:]: + kind = e['type'] + if kind == 'content_block_start': + assert active is None and e['index'] == len(message['content']) + active = e['index'] + message['content'].append(e['content_block']) + args = '' + elif kind == 'content_block_delta': + assert e['index'] == active + if e['delta']['type'] == 'text_delta': + message['content'][active]['text'] += e['delta']['text'] + else: + assert e['delta']['type'] == 'input_json_delta' + args += e['delta']['partial_json'] + elif kind == 'content_block_stop': + assert active == e['index'] + if message['content'][active]['type'] == 'tool_use': + message['content'][active]['input'] = json.loads(args) + active = None + elif kind == 'message_delta': + assert active is None + message.update(e['delta']) + message['usage'].update(e['usage']) + elif kind == 'message_stop': + assert active is None + else: + raise AssertionError(e) + return message + + def normalized(message): + value = json.loads(json.dumps(message)) + del value['id'] + for block in value['content']: + if block['type'] == 'tool_use': + assert block['id'].startswith('call_') + block['id'] = 'ID' + return value + + base = {'model': 'fixture', 'max_tokens': 1024, 'messages': [{'role': 'user', 'content': 'Привіт 🌍'}]} + native_base = {'model': 'fixture', 'max_output_tokens': 1024, 'input': base['messages'], 'store': False, 'reasoning': {'effort': 'none'}} + tool = {'name': 'lookup', 'input_schema': {'type': 'object', 'properties': {'key': {'type': 'string'}}}} + native_tool = {'type': 'function', 'name': 'lookup', 'parameters': tool['input_schema']} + tool_text = '\n\n\nvalue\n\n\n' + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 10 + while True: + try: + if request('GET', '/ready')[0] == 200: break + except OSError: pass + assert process.poll() is None and time.monotonic() < deadline + time.sleep(.02) + before = wire() + for headers, status in [({'x-api-key': None}, 401), ({'x-api-key': 'wrong'}, 401), + ({'Authorization': 'Bearer ' + key}, 401), ({'anthropic-version': None}, 400), + ({'anthropic-version': 'future'}, 400), ({'anthropic-beta': 'anything'}, 400)]: + code, value = request('POST', path, base, headers=headers) + assert code == status and value['type'] == 'error' and 'error' in value, value + count(base, status, headers=headers) + assert wire() == before + for duplicate, expected in [('x-api-key', 401), ('anthropic-version', 400)]: + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=6) + conn.putrequest('POST', path) + conn.putheader('Content-Type', 'application/json') + conn.putheader('x-api-key', key) + conn.putheader('anthropic-version', '2023-06-01') + conn.putheader(duplicate, key if duplicate == 'x-api-key' else '2023-06-01') + body = json.dumps(base).encode() + conn.putheader('Content-Length', str(len(body))) + conn.endheaders(body) + response = conn.getresponse() + assert response.status == expected and json.loads(response.read())['type'] == 'error' + conn.close() + assert wire() == before + assert request('POST', path, raw='{')[0] == 400 + assert request('GET', path)[0] == 405 + assert request('GET', count_path)[0] == 405 + assert request('POST', count_path, raw='{')[0] == 400 + count(base, 413, raw=json.dumps({'model': 'fixture', 'messages': [{'role': 'user', 'content': 'x' * (16 * 1024 * 1024)}]})) + for extra in [{'max_tokens': 1}, {'stream': False}, {'temperature': 0}, {'unknown': True}]: + payload = {k: v for k, v in base.items() if k != 'max_tokens'} + code, value = request('POST', count_path, {**payload, **extra}) + assert code == 400 and value['type'] == 'error', value + count({**base, 'model': 'wrong'}, 404) + count(base, headers={'x-api-key': None, 'Authorization': 'Bearer ' + key}) + assert request('GET', '/status', headers={'Authorization': None, 'x-api-key': key})[0] == 401 + output('A') + assert request('POST', path, base, headers={'x-api-key': None, 'Authorization': 'Bearer ' + key})[0] == 200 + cases = [(base, native_base, 'Вітаю 🌍', 'stop'), + ({**base, 'system': [{'type': 'text', 'text': 'A'}, {'type': 'text', 'text': 'B'}], 'messages': [{'role': 'user', 'content': 'Hi'}, {'role': 'user', 'content': [{'type': 'text', 'text': '!'}]}]}, + {**native_base, 'instructions': 'A\nB', 'input': [{'role': 'user', 'content': 'Hi\n!'}]}, 'Limited', 'length')] + for choice, mapped in [({'type': 'auto'}, 'auto'), ({'type': 'any'}, 'required'), ({'type': 'tool', 'name': 'lookup'}, {'type': 'function', 'name': 'lookup'})]: + cases.append(({**base, 'tools': [tool], 'tool_choice': choice}, + {**native_base, 'tools': [native_tool], 'tool_choice': mapped}, tool_text, 'stop')) + cases.append(({**base, 'tools': [tool]}, {**native_base, 'tools': [native_tool]}, 'Before\n' + tool_text + '\nAfter', 'stop')) + cases.append(({**base, 'tools': [tool], 'tool_choice': {'type': 'auto', 'disable_parallel_tool_use': False}}, + {**native_base, 'tools': [native_tool], 'tool_choice': 'auto', 'parallel_tool_calls': True}, tool_text + '\n' + tool_text, 'stop')) + cases.append((base, native_base, '', 'stop')) + for current, native, text, reason in cases: + measured = count(current) + output(text, reason) + code, reference = request('POST', '/v1/responses', native) + assert code == 200, reference + expected_wire = wire()[-1] + assert measured == len(expected_wire.split()[-1].split(',')) + code, result = request('POST', path, current) + assert code == 200 and wire()[-1] == expected_wire, result + assert result['type'] == 'message' and result['role'] == 'assistant' and result['model'] == 'fixture' + expected_content = [] + for item in reference['output']: + if item['type'] == 'message': + expected_content.extend({'type': 'text', 'text': p['text']} for p in item['content']) + elif item['type'] == 'function_call': + expected_content.append({'type': 'tool_use', 'id': 'ID', 'name': item['name'], 'input': json.loads(item['arguments'])}) + assert normalized(result)['content'] == expected_content, (result, reference) + assert result['stop_reason'] == ('max_tokens' if reason == 'length' else 'tool_use' if any(b['type'] == 'tool_use' for b in result['content']) else 'end_turn') + assert result['usage'] == {'input_tokens': 5, 'cache_read_input_tokens': 2, 'cache_creation_input_tokens': 0, 'output_tokens': reference['usage']['output_tokens']} + code, events = request('POST', path, {**current, 'stream': True}) + assert code == 200 and wire()[-1] == expected_wire + streamed = rebuild(events) + assert normalized(streamed) == normalized(result), (streamed, result) + if sum(b['type'] == 'tool_use' for b in streamed['content']) == 2: + parallel_result = streamed + streamed = parallel_result + # Use the stream's actual call IDs/objects in the next request. + calls = [b for b in streamed['content'] if b['type'] == 'tool_use'] + results = [{'type': 'tool_result', 'tool_use_id': b['id'], 'content': [{'type': 'text', 'text': 'Found 🌍'}]} for b in calls] + transcript = base['messages'] + [{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': results}] + native_input = base['messages'] + [{'type': 'function_call', 'call_id': b['id'], 'name': b['name'], 'arguments': json.dumps(b['input'], separators=(',', ':'))} for b in calls] + [{'type': 'function_call_output', 'call_id': b['id'], 'output': 'Found 🌍'} for b in calls] + measured = count({**base, 'messages': transcript, 'tools': [tool]}) + output('Continued') + assert request('POST', '/v1/responses', {**native_base, 'input': native_input, 'tools': [native_tool]})[0] == 200 + expected_wire = wire()[-1] + assert measured == len(expected_wire.split()[-1].split(',')) + code, result = request('POST', path, {**base, 'messages': transcript, 'tools': [tool]}) + assert code == 200 and wire()[-1] == expected_wire and result['content'] == [{'type': 'text', 'text': 'Continued'}], result + # Tool execution failures and empty results continue in the tool role. + error_text = 'Connection failed 🌍\n"quoted" \\ path\u0000' + variants = [ + ([{'content': [{'type': 'text', 'text': error_text}], 'is_error': True}, {}], + [json.dumps({'content': error_text, 'is_error': True}, ensure_ascii=False, separators=(',', ':'), sort_keys=True), '']), + ([{'is_error': True}, {'content': [], 'is_error': False}], + ['{"content":"","is_error":true}', '']), + ([{'content': 'Found 🌍', 'is_error': False}, {'content': 'Found 🌍'}], + ['Found 🌍', 'Found 🌍']), + ] + for fields, expected_outputs in variants: + results = [{'type': 'tool_result', 'tool_use_id': b['id'], **f} for b, f in zip(calls, fields)] + transcript = base['messages'] + [{'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': results}] + current = {**base, 'messages': transcript, 'tools': [tool]} + native_input = base['messages'] + [{'type': 'function_call', 'call_id': b['id'], 'name': b['name'], 'arguments': json.dumps(b['input'], separators=(',', ':'))} for b in calls] + [{'type': 'function_call_output', 'call_id': b['id'], 'output': v} for b, v in zip(calls, expected_outputs)] + measured = count(current) + output('Continued after result') + assert request('POST', '/v1/responses', {**native_base, 'input': native_input, 'tools': [native_tool]})[0] == 200 + expected_wire = wire()[-1] + assert measured == len(expected_wire.split()[-1].split(',')) + code, result = request('POST', path, current) + assert code == 200 and wire()[-1] == expected_wire and result['stop_reason'] == 'end_turn', result + assert result['content'] == [{'type': 'text', 'text': 'Continued after result'}] + code, events = request('POST', path, {**current, 'stream': True}) + assert code == 200 and wire()[-1] == expected_wire + assert normalized(rebuild(events)) == normalized(result) + before = wire() + for bad in [ + {'content': None, 'is_error': True}, {'is_error': 'true'}, + {'content': [{'type': 'image', 'source': {}}], 'is_error': True}, + {'tool_use_id': 'orphan', 'is_error': True}, + {'tool_use_id': calls[1]['id'], 'is_error': True}, + ]: + bad_results = [{'type': 'tool_result', 'tool_use_id': calls[0]['id'], **bad}, + {'type': 'tool_result', 'tool_use_id': calls[1]['id']}] + current = {**base, 'tools': [tool], 'messages': base['messages'] + [ + {'role': 'assistant', 'content': streamed['content']}, {'role': 'user', 'content': bad_results}]} + for streaming in [False, True]: + code, value = request('POST', path, {**current, 'stream': streaming}) + assert code == 400 and value['type'] == 'error', value + count(current, 400) + assert wire() == before + for text, extra, reason in [(tool_text.replace('lookup', 'wrong'), {'tools': [tool]}, 'stop'), ('A', {'tools': [tool], 'tool_choice': {'type': 'any'}}, 'stop'), (tool_text[:35], {'tools': [tool]}, 'length')]: + output(text, reason) + code, value = request('POST', path, {**base, **extra}) + assert code == 502 and value['type'] == 'error', value + code, events = request('POST', path, {**base, **extra, 'stream': True}) + assert code == 200 and events[-1]['type'] == 'error' and not any(e['type'] == 'message_stop' for e in events) + before = wire() + for extra in [{'thinking': {'type': 'enabled', 'budget_tokens': 10}}, {'stop_sequences': ['END']}, {'top_k': 1}, + {'messages': [{'role': 'assistant', 'content': 'prefix'}]}, {'system': [{'type': 'text', 'text': 'secret', 'cache_control': {'type': 'ephemeral'}}]}, + {'tools': [{'type': 'web_search', 'name': 'web_search'}]}, {'messages': [{'role': 'user', 'content': [{'type': 'image', 'source': {}}]}]}]: + code, value = request('POST', path, {**base, **extra}) + assert code == 400 and value['type'] == 'error', value + count({**base, **extra}, 400) + assert wire() == before and not list((root / 'history').glob('*.json')) + (root / 'hold').touch() + conn, response = open_request('POST', path, {**base, 'stream': True}) + while True: + line = response.readline() + assert line + if line.startswith(b'data:'): + event = json.loads(line[5:]) + if event.get('delta', {}).get('text') == 'A': break + # Admission counts the streaming Messages request until it disconnects. + blocked_conn, blocked = open_request('POST', path, base) + assert blocked.status == 429 and blocked.getheader('Retry-After') == '1' + assert json.loads(blocked.read())['error']['type'] == 'rate_limit_error' + blocked_conn.close() + count(base, 429) + conn.sock.shutdown(socket.SHUT_RDWR) + response.close() + conn.close() + deadline = time.monotonic() + 3 + while not (root / 'stopped').exists(): + assert time.monotonic() < deadline, 'STOP not delivered' + time.sleep(.02) + (root / 'hold').unlink() + output('Fresh') + assert request('POST', path, base)[1]['content'] == [{'type': 'text', 'text': 'Fresh'}] + assert request('POST', '/admin/drain', {})[0] == 200 + code, value = request('POST', path, base) + assert code == 503 and value['type'] == 'error' and value['error']['type'] == 'overloaded_error', value + count(base, 503) + assert request('POST', '/admin/resume', {})[0] == 200 + (root / 'output').write_text('ERR fixture error\n') + assert request('POST', path, base)[0] == 502 + code, events = request('POST', path, {**base, 'stream': True}) + assert code == 200 and events[-1]['type'] == 'error' and not any(e['type'] == 'message_stop' for e in events) + measured = count(base) + os.kill(int((root / 'pid').read_text()), signal.SIGKILL) + deadline = time.monotonic() + 3 + while request('GET', '/ready')[0] == 200: + assert time.monotonic() < deadline + time.sleep(.02) + assert count(base) == measured # tokenizer available without a ready worker + finally: + os.killpg(process.pid, signal.SIGTERM) + try: process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=3) + if process.returncode != 0: + logs.seek(0) + raise AssertionError(logs.read().decode()) + print('Messages error/empty/parallel tool results + count/actual GEN equality/no mutation/outage + JSON/named live SSE/block order/tools/continuation/usage/header auth/errors/STOP/fresh: PASS; actual GEN and greedy parity tolerance=0, CPU only') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-mtp-pack.py b/scripts/smoke-mtp-pack.py new file mode 100644 index 00000000..b7f8fb4e --- /dev/null +++ b/scripts/smoke-mtp-pack.py @@ -0,0 +1,176 @@ +#!/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() + names = sorted(set(re.findall(r'\b(q8|bf16|f32)\("([^" ]+)"\)', consumer))) + 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-auth.py b/scripts/smoke-native-auth.py new file mode 100644 index 00000000..2506e100 --- /dev/null +++ b/scripts/smoke-native-auth.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Exercise real native HTTP auth on CPU only; destroy temporary test keys.""" +import http.client +import json +import os +from pathlib import Path +from concurrent.futures import ThreadPoolExecutor +import socket +import subprocess +import sys +import tempfile +import time + + +def init_key(binary, root): + key = root / 'api.key' + def init(path, **kwargs): + return subprocess.run([binary, 'api-key', 'init', '--file', str(path)], + env={'PATH': os.defpath}, capture_output=True, timeout=8, **kwargs) + # Simultaneous cold initialization must converge on one complete key. + with ThreadPoolExecutor(max_workers=12) as pool: + results = list(pool.map(lambda _: init(key), range(12))) + assert all(r.returncode == 0 for r in results) + statuses = [json.loads(r.stdout) for r in results] + assert statuses.count({'created': True, 'reused': False}) == 1 + assert statuses.count({'created': False, 'reused': True}) == 11 + token = key.read_text().rstrip('\n') + assert len(token) == 64 and all(c in '0123456789abcdef' for c in token) + assert key.stat().st_mode & 0o777 == 0o600 + before = key.stat() + reused = init(key) + assert reused.returncode == 0 and json.loads(reused.stdout) == {'created': False, 'reused': True} + assert key.stat().st_ino == before.st_ino and key.stat().st_mtime_ns == before.st_mtime_ns + assert key.read_text() == token + '\n' + assert all(token.encode() not in r.stdout + r.stderr for r in results + [reused]) + assert sorted(p.name for p in root.iterdir()) == ['api.key'] + other = root / 'other.key' + result = init(other, umask=0o777) + assert result.returncode == 0 and other.stat().st_mode & 0o777 == 0o600 + assert other.read_bytes() != key.read_bytes() + other.unlink() + # Refuse unsafe or invalid targets without changing them or the good key. + bad = root / 'bad.key' + for data, mode in [(b'short', 0o600), (b'A'*515, 0o600), (token.encode(), 0o644)]: + bad.write_bytes(data); bad.chmod(mode) + result = init(bad) + assert result.returncode != 0 and bad.read_bytes() == data and bad.stat().st_mode & 0o777 == mode + assert token.encode() not in result.stdout + result.stderr + bad.unlink() + bad.symlink_to(key) + assert init(bad).returncode != 0 and key.read_text() == token + '\n' + bad.unlink(); bad.symlink_to(root/'absent') + assert init(bad).returncode != 0 and not (root/'absent').exists() + bad.unlink(); os.mkfifo(bad, 0o600) + assert init(bad).returncode != 0 + bad.unlink(); bad.mkdir(mode=0o700) + assert init(bad).returncode != 0 + bad.rmdir() + parent = root / 'public'; parent.mkdir(mode=0o755) + assert init(parent/'key').returncode != 0 and not list(parent.iterdir()) + parent.chmod(0o700) + alias = root/'alias'; alias.symlink_to(parent, target_is_directory=True) + assert init(alias/'key').returncode != 0 and not list(parent.iterdir()) + alias.unlink(); parent.rmdir() + assert init(root/'missing'/'key').returncode != 0 and not (root/'missing').exists() + assert sorted(p.name for p in root.iterdir()) == ['api.key'] + return key, token + + +def main(): + binary = Path(sys.argv[1]).resolve() + with tempfile.TemporaryDirectory(prefix='strata-auth-smoke-') as directory: + root = Path(directory) + key, token = init_key(binary, root) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + config = root / 'config.json' + config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'api_key_file': str(key), 'model': 'auth-cpu-smoke'})) + env = {'PATH': os.defpath} + + def request(path, headers=(), body=None, method=None): + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=2) + conn.putrequest(method or ('POST' if body is not None else 'GET'), path) + for name, value in headers: + conn.putheader(name, value) + if body is not None: + conn.putheader('Content-Type', 'application/json') + conn.putheader('Content-Length', str(len(body))) + conn.endheaders(body) + response = conn.getresponse() + result = response.status, dict(response.getheaders()), response.read().decode() + conn.close() + assert token not in result[2] + return result + + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve', '--config', config], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 8 + while True: + try: + assert request('/health')[0] == 200 + break + except OSError: + assert process.poll() is None and time.monotonic() < deadline + time.sleep(0.02) + for headers in [(), (('Authorization', 'Bearer wrong'),), + (('Authorization', 'Bearer ' + token), ('Authorization', 'Bearer ' + token))]: + code, response_headers, _ = request('/v1/responses', headers, b'not-json') + assert code == 401 + assert response_headers.get('www-authenticate') == 'Bearer' + auth = (('Authorization', 'Bearer ' + token),) + model_record = {'id': 'auth-cpu-smoke', 'object': 'model', 'created': 0, 'owned_by': 'local'} + for path in ['/v1/models', '/v1/models/auth-cpu-smoke', '/v1/models/missing?x=1']: + assert request(path)[0] == 401 + assert request(path, (('Authorization', 'Bearer wrong'),))[0] == 401 + assert json.loads(request('/v1/models', auth)[2]) == {'object': 'list', 'data': [model_record]} + assert json.loads(request('/v1/models/auth-cpu-smoke', auth)[2]) == model_record + missing = request('/v1/models/missing', auth) + assert missing[0] == 404 and json.loads(missing[2])['error']['code'] == 'model_not_found' + for path in ['/v1/models?limit=1', '/v1/models/auth-cpu-smoke?x=1']: + assert request(path, auth)[0] == 400 + for method, path in [('POST', '/v1/models'), ('DELETE', '/v1/models/auth-cpu-smoke')]: + assert request(path, auth, method=method)[0] == 405 + assert request('/status')[0] == 401 + assert request('/ready')[0] == 401 + assert request('/metrics')[0] == 401 + for path in ['/admin/drain', '/admin/resume', '/admin/lifecycle']: + assert request(path, body=b'{}')[0] == 401 + status = request('/status', auth) + assert status[0] == 200 and json.loads(status[2])['model'] == 'auth-cpu-smoke' + assert request('/ready', auth)[0] == 503 + metrics = request('/metrics', auth) + assert metrics[0] == 200 + observed = json.loads(metrics[2]) + assert observed['schema_version'] == 1 + assert observed['active'] is False and observed['active_elapsed_ms'] is None + assert observed['queue_capacity'] is None and observed['queue_used'] is None + assert observed['generation']['started'] == 0 + assert observed['generation']['last_done'] is None + assert observed['done_decode_tokens_per_second'] is None + assert request('/v1/responses', auth, b'not-json')[0] == 400 + assert json.loads(request('/admin/lifecycle', auth)[2])['draining'] is False + assert json.loads(request('/admin/drain', auth, b'{}')[2])['drained'] is True + assert json.loads(request('/v1/models', auth)[2]) == {'object': 'list', 'data': [model_record]} + assert json.loads(request('/metrics', auth)[2])['generation']['started'] == 0 + assert request('/v1/responses', auth, b'not-json')[0] == 503 + assert json.loads(request('/admin/resume', auth, b'{}')[2])['draining'] is False + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + logs.seek(0) + assert token.encode() not in logs.read() + + # Each invalid source must fail before binding, with no secret echo. + for content, mode in [(b'short', 0o600), (b'A' * 32 + b'\ninside', 0o600), + (b'A' * 515, 0o600), (token.encode(), 0o644)]: + key.write_bytes(content) + key.chmod(mode) + result = subprocess.run([binary, 'serve', '--config', config], env=env, + capture_output=True, timeout=8) + assert result.returncode != 0 + assert token.encode() not in result.stdout + result.stderr + fifo = root / 'not-a-file' + os.mkfifo(fifo, 0o600) + result = subprocess.run([binary, 'serve', '--config', config], + env={**env, 'STRATA_API_KEY_FILE': str(fifo)}, capture_output=True, timeout=8) + assert result.returncode != 0 and b'regular file' in result.stderr + # An environment override is authoritative, including invalid paths. + result = subprocess.run([binary, 'serve', '--config', config], + env={**env, 'STRATA_API_KEY_FILE': str(root/'missing')}, capture_output=True, timeout=8) + assert result.returncode != 0 + config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'auth-off-fixture'})) + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve', '--config', config], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 8 + while True: + try: + assert request('/status')[0] == 200 + break + except OSError: + assert process.poll() is None and time.monotonic() < deadline + time.sleep(0.02) + assert request('/v1/responses', body=b'not-json')[0] == 400 + assert request('/metrics')[0] == 200 + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + print('Native auth passed: native key init/concurrent reuse/no replacement/private modes, protected routes, duplicate rejection, public health, invalid sources and no key echo') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-native-bootstrap.py b/scripts/smoke-native-bootstrap.py new file mode 100644 index 00000000..e7712559 --- /dev/null +++ b/scripts/smoke-native-bootstrap.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""CPU subprocess bootstrap contract: real download/pack, synthetic worker only.""" +import copy +import fcntl +import hashlib +import http.client +import http.server +import importlib.util +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import threading +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')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + requests = [] + data = b'' + + class Source(http.server.BaseHTTPRequestHandler): + def log_message(self, *_): + pass + def do_GET(self): + requests.append(self.path) + self.send_response(200) + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + with tempfile.TemporaryDirectory(prefix='strata-native-bootstrap-') as tmp: + root = Path(tmp).resolve() + gguf = root / 'fixture.gguf' + fixture.write_gguf(gguf, fixture.fixtures()) + data = gguf.read_bytes() + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Source) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + manifest = root / 'manifest.json' + manifest.write_text(json.dumps({'schema_version': 1, 'files': [{ + 'name': 'model.gguf', 'url': f'http://127.0.0.1:{server.server_port}/model.gguf', + 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}]})) + marker = root / 'started' + worker = root / 'worker.sh' + # Assert the actual pinned engine's --native PATH / --pack DIR grammar. + worker.write_text('''#!/bin/sh +set -eu +[ "$1" = --serve ] +marker="$2" +[ "$3" = --pack ]; pack="$4" +[ "$5" = --native ]; source="$6" +[ -s "$source" ] && [ -s "$pack/receipt.json" ] +[ -s "$pack/dense.bin" ] && [ -s "$pack/tokenizer/vocab.json" ] +printf '%s\\n%s\\n' "$pack" "$source" > "$marker" +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] + source, output = root / 'sources-v1', root / 'pack-v1' + config = {'bind': f'127.0.0.1:{port}', 'native_model': { + 'manifest': str(manifest), 'source_dir': str(source), 'output': str(output)}, + 'engine': {'executable': str(worker), 'args': [str(marker)], 'startup_timeout_s': 5, 'max_restarts': 0}} + config_path = root / 'config.json' + env = {'PATH': os.defpath} + count = 0 + processes = [] + + def save(): + config_path.write_text(json.dumps(config)) + def run(command='provision', ok=True): + nonlocal count + save() + r = subprocess.run([binary, command, '--config', str(config_path)], env=env, capture_output=True, text=True, timeout=15) + assert (r.returncode == 0) == ok, (r.stdout, r.stderr) + count += 1 + return r + def gated_failure(): + marker.unlink(missing_ok=True) + run('serve', ok=False) + assert not marker.exists() + with socket.socket() as check: + check.bind(('127.0.0.1', port)) + def start(): + nonlocal count + save() + log = open(root / f'serve-{len(processes)}.log', 'w+') + p = subprocess.Popen([binary, 'serve', '--config', str(config_path)], env=env, stdout=log, stderr=log) + processes.append((p, log)) + deadline = time.monotonic() + 12 + while time.monotonic() < deadline: + assert p.poll() is None, 'server exited during bootstrap' + 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, http.client.HTTPException): + pass + time.sleep(.03) + else: + raise AssertionError('bootstrap never ready') + assert marker.read_text().splitlines() == [config['native_model']['output'], str(source / 'model.gguf')] + p.terminate(); p.wait(timeout=8) + count += 1 + + try: + report = json.loads(run('check-config').stdout) + assert report['native_model_configured'] and not report['native_model_verified'] and not report['tokenizer_validated'] + assert not requests and not source.exists() and not output.exists() + # Malformed other asset manifest must fail before any source acquisition. + bad = root / 'bad.json'; bad.write_text('{}') + config['assets'] = [{'manifest': str(bad), 'directory': str(root / 'aux')}] + gated_failure() + assert not requests + del config['assets'] + start() # Empty node -> download -> exact conversion -> synthetic worker -> ready. + assert requests == ['/model.gguf'] + before = {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} + server.shutdown(); server.server_close(); thread.join() + report = json.loads(run().stdout) + assert report['native_model_prepared'] and not report['worker_started'] + start() # Offline startup, no regeneration. + assert requests == ['/model.gguf'] + assert before == {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} + # Each invalid cache must fail before listener/worker and preserve the damaged version. + dense = output / 'dense.bin'; original = dense.read_bytes() + dense.write_bytes(bytes([original[0] ^ 1]) + original[1:]) + gated_failure(); assert dense.read_bytes() != original + dense.write_bytes(original) + extra = output / 'extra'; extra.write_text('unexpected'); gated_failure(); extra.unlink() + receipt = output / 'receipt.json'; raw = receipt.read_bytes() + r = json.loads(raw); r['sources']['model.gguf']['sha256'] = '0' * 64 + receipt.write_text(json.dumps(r)); gated_failure(); receipt.write_bytes(raw) + dense.unlink(); dense.symlink_to(gguf); gated_failure(); dense.unlink(); dense.write_bytes(original) + raw_source = (source / 'model.gguf').read_bytes() + (source / 'model.gguf').write_bytes(b'bad'); gated_failure(); (source / 'model.gguf').write_bytes(raw_source) + lock = open(root / '.pack-v1.native-model-lock', 'a+') + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gated_failure(); lock.close() + # New version failure must never mutate previous validated output. + wrong = root / 'wrong.gguf'; fixture.write_gguf(wrong, fixture.fixtures(), architecture='unsupported') + source2 = root / 'sources-v2'; source2.mkdir(); (source2 / 'model.gguf').write_bytes(wrong.read_bytes()) + manifest2 = root / 'manifest-v2.json'; m = json.loads(manifest.read_text()) + m['files'][0].update(size=wrong.stat().st_size, sha256=hashlib.sha256(wrong.read_bytes()).hexdigest()) + manifest2.write_text(json.dumps(m)) + initial = copy.deepcopy(config) + config['native_model'].update(manifest=str(manifest2), source_dir=str(source2), output=str(root / 'pack-v2')) + gated_failure(); assert not (root / 'pack-v2').exists() + assert before == {str(p.relative_to(output)): p.read_bytes() for p in output.rglob('*') if p.is_file()} + config = copy.deepcopy(initial) + config['native_model']['output'] = str(source / 'inside'); gated_failure() + config = copy.deepcopy(initial) + alias = root / 'pack-alias'; alias.symlink_to(output, target_is_directory=True) + config['native_model']['source_dir'] = str(alias / 'new-sources') + gated_failure() + assert not (output / 'new-sources').exists() + alias.unlink() + config = copy.deepcopy(initial) + config['engine']['args'].append('--native'); gated_failure() + config = copy.deepcopy(initial) + config['engine']['tokenizer_dir'] = str(output / 'tokenizer'); gated_failure() + config = copy.deepcopy(initial) + del config['engine']; run(ok=False) + print(json.dumps({'status': 'passed', 'scenarios': count, 'real_model': False, 'worker': 'synthetic', 'gpu_used': False})) + finally: + for p, log in processes: + if p.poll() is None: + p.kill(); p.wait(timeout=5) + log.close() + if thread.is_alive(): + server.shutdown(); server.server_close(); thread.join() + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-native-drain.py b/scripts/smoke-native-drain.py new file mode 100644 index 00000000..abae0905 --- /dev/null +++ b/scripts/smoke-native-drain.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Exercise native drain over HTTP with one active and one queued CPU request.""" +import concurrent.futures +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('cancel_fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + with tempfile.TemporaryDirectory(prefix='strata-drain-http-') as directory: + root = Path(directory) + fixture.tokenizer(root) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf 'READY 262144 stop\\n' +count=0 +while IFS= read -r line; do + case "$line" in + 'GEN '*) + count=$((count + 1)) + printf 'T 79\\n' + if [ "$count" = 1 ]; then + while [ ! -e "$2/release" ]; do sleep 0.01; done + fi + printf 'T 75\\nDONE 2 7 1.0 2.0 stop\\n' ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + key = root / 'key' + key.write_text('fixture-only-admission-secret-00000001') + key.chmod(0o600) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0', + 'STRATA_MAX_IN_FLIGHT_REQUESTS': '2', 'STRATA_API_KEY_FILE': str(key)} + + def open_request(path, body=None): + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + conn.request('POST' if body is not None else 'GET', path, + json.dumps(body) if body is not None else None, + {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key.read_text()}) + return conn, conn.getresponse() + + def request(path, body=None): + conn, response = open_request(path, body) + code, data = response.status, json.loads(response.read()) + conn.close() + return code, data + + def wait_for(predicate): + deadline = time.monotonic() + 8 + while True: + try: + if predicate(): + return + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline, 'condition timed out' + time.sleep(0.02) + + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + conn = None + pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) + try: + wait_for(lambda: request('/ready')[0] == 200) + payload = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 8, + 'reasoning': {'effort': 'none'}, 'stream': True} + conn, response = open_request('/v1/responses', payload) + assert response.status == 200 + events = [] + while True: + line = response.readline().decode() + assert line, 'stream ended before first token' + if line.startswith('data:'): + event = json.loads(line[5:]) + events.append(event) + if event['type'] == 'response.output_text.delta': + break + queued = pool.submit(request, '/v1/responses', {**payload, 'stream': False}) + wait_for(lambda: request('/admin/lifecycle')[1]['generation_jobs'] == 2) + state = request('/admin/lifecycle')[1] + assert state['max_in_flight_requests'] == 2 and state['available_request_slots'] == 0 + assert request('/ready')[0] == 200 and request('/status')[1]['ready'] + # Auth is outermost; admission rejects before JSON parsing, with no extra GEN. + for authenticated, expected in [(False, 401), (True, 429)]: + rejected = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + headers = {'Content-Type': 'application/json'} + if authenticated: + headers['Authorization'] = 'Bearer ' + key.read_text() + rejected.request('POST', '/v1/responses', '{broken', headers) + rejection = rejected.getresponse() + assert rejection.status == expected + error = json.loads(rejection.read()) + if authenticated: + assert rejection.getheader('Retry-After') == '1' + assert error['error']['code'] == 'runtime_overloaded' + rejected.close() + assert request('/metrics')[1]['generation']['started'] == 1 + for _ in range(2): + code, state = request('/admin/drain', {}) + assert code == 200 and state['draining'] and not state['drained'] + assert state['requests_in_flight'] == 2 and state['generation_jobs'] == 2 + assert request('/ready')[0] == 503 + assert request('/status')[1]['ready'] is False + code, error = request('/v1/responses', payload) + assert code == 503 and error['error']['code'] == 'runtime_draining' + assert request('/health')[0] == 200 + (root / 'release').touch() + events += [json.loads(line[5:]) for line in response.read().decode().splitlines() if line.startswith('data:')] + conn.close() + conn = None + assert [e['sequence_number'] for e in events] == list(range(len(events))) + assert ''.join(e['delta'] for e in events if e['type'] == 'response.output_text.delta') == 'OK' + assert events[-1]['type'] == 'response.completed' + code, result = queued.result(timeout=8) + assert code == 200 and result['output'][0]['content'][0]['text'] == 'OK' + wait_for(lambda: request('/admin/lifecycle')[1]['drained']) + assert request('/admin/lifecycle')[1]['available_request_slots'] == 2 + for _ in range(2): + code, state = request('/admin/resume', {}) + assert code == 200 and not state['draining'] and not state['drained'] + assert request('/ready')[0] == 200 + code, result = request('/v1/responses', {**payload, 'stream': False}) + assert code == 200 and result['output'][0]['content'][0]['text'] == 'OK' + assert request('/metrics')[1]['generation']['started'] == 3 + finally: + (root / 'release').touch() + if conn is not None: + conn.close() + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + pool.shutdown(wait=True, cancel_futures=True) + print('Native admission/drain passed: limit 2, auth/429/503 precedence, SSE and queued JSON exact output, capacity release/resume and no excess GEN; CPU fixtures only') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-native-pack.py b/scripts/smoke-native-pack.py new file mode 100644 index 00000000..2ca352c1 --- /dev/null +++ b/scripts/smoke-native-pack.py @@ -0,0 +1,166 @@ +#!/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('0 + result=select('next',check=False) + assert result.returncode!=0 and 'multiple catalog' in result.stderr,result.stderr + assert status('old')['main_pid']==original and status('preflight')['main_pid']==other + control('preflight','stop'); inference('old') + # Parse/preparation failure cannot unload the current model. + Path(profiles['preflight']['config']).write_text('{invalid json') + result=switch('old','preflight',check=False) + assert result.returncode!=0 and 'before previous service drain' in result.stderr,result.stderr + assert status('old')['main_pid']==original + assert json.loads((state/'transaction.json').read_text())['phase']=='preflight_failed' + inference('old') + # Cooperative OS locking refuses another transaction before mutation. + with (state/'switch.lock').open('r+') as lock: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + assert switch('old','next',check=False).returncode!=0 + assert status('old')['main_pid']==original + result=json.loads(select('next').stdout) + assert result['profile']=='next' and result['switched'] + next_pid=status('next')['main_pid']; assert next_pid>0 and status('old')['main_pid']==0 + assert not Path(f'/proc/{original}').exists(); inference('next') + # Failing target is removed before previous profile is restored. + result=select('bad',check=False) + assert result.returncode!=0 and 'rolled_back' in result.stderr,result.stderr + restored=status('next')['main_pid']; assert restored>0 and restored!=next_pid + assert status('bad')['main_pid']==0 and status('old')['main_pid']==0 + assert json.loads((state/'transaction.json').read_text())['phase']=='rolled_back' + inference('next') + # An unfinished durable record is never implicitly replayed. + journal=json.loads((state/'transaction.json').read_text());journal['phase']='starting_target' + (state/'transaction.json').write_text(json.dumps(journal)) + result=switch('next','old',check=False) + assert result.returncode!=0 and 'reconciliation' in result.stderr + assert status('next')['main_pid']==restored and status('old')['main_pid']==0 + inference('next') + # Explicit SHA acknowledgment reconciles stable state without lifecycle replay. + record=state/'transaction.json'; before=record.read_bytes() + digest=hashlib.sha256(before).hexdigest() + def reconcile(sha,check=True): + return run(str(binary),'service-switch','reconcile','--catalog',str(catalog), + '--state-dir',str(state),'--expected-journal-sha',sha,check=check) + assert reconcile('0'*64,check=False).returncode!=0 + assert record.read_bytes()==before and status('next')['main_pid']==restored + original_catalog=catalog.read_bytes();catalog.write_bytes(original_catalog+b' ') + assert reconcile(digest,check=False).returncode!=0 + catalog.write_bytes(original_catalog);assert record.read_bytes()==before + changed=Path(profiles['next']['config']); original_config=changed.read_bytes() + changed.write_bytes(original_config+b' ') + assert reconcile(digest,check=False).returncode!=0 + changed.write_bytes(original_config);assert record.read_bytes()==before + extra=Path(profiles['preflight']['config']); extra_before=extra.read_bytes() + extra_config=json.loads(original_config);extra_config['bind']='127.0.0.1:0' + extra.write_text(json.dumps(extra_config));control('preflight','start') + extra_pid=status('preflight')['main_pid'];assert extra_pid>0 + result=reconcile(digest,check=False) + assert result.returncode!=0 and 'multiple catalog' in result.stderr,result.stderr + assert record.read_bytes()==before and status('next')['main_pid']==restored + control('preflight','stop');extra.write_bytes(extra_before) + reconciled=json.loads(reconcile(digest).stdout) + assert reconciled['reconciled'] and not reconciled['lifecycle_action_requested'] + assert reconciled['pid']==restored and reconciled['profile']=='next' + assert status('next')['main_pid']==restored;inference('next') + terminal=record.read_bytes(); assert json.loads(terminal)['prior_journal_sha256']==digest + assert reconcile(digest,check=False).returncode!=0 and record.read_bytes()==terminal + assert json.loads(select('old').stdout)['profile']=='old';inference('old') + # All-inactive reconciliation also allows a later explicit cold start. + control('old','stop') + prior=json.loads(record.read_bytes());prior['phase']='starting_target' + record.write_text(json.dumps(prior));digest=hashlib.sha256(record.read_bytes()).hexdigest() + reconciled=json.loads(reconcile(digest).stdout) + assert reconciled['pid'] is None and reconciled['profile'] is None + assert json.loads(select('next').stdout)['cold_started'];inference('next') + print('Native reconciliation passed: wrong SHA/catalog/config preserve record, stable PID/A retained, no lifecycle replay, subsequent switch and all-inactive cold selection') + print('Native switch passed: cold failure cleanup/retry, cold start, same-target PID/A reuse, multiple-active refusal, preparation preserves PID/A, OS lock, automatic old-to-next and failed-target rollback/A, durable interrupted refusal; CPU only') + finally: + for unit,path,generated in reversed(owned): + run('systemctl','--user','stop',unit,check=False) + if path.is_file() and not path.is_symlink() and path.read_text()==generated:path.unlink() + run('systemctl','--user','reset-failed',unit,check=False) + run('systemctl','--user','daemon-reload',check=False) + + +if __name__=='__main__':main() diff --git a/scripts/smoke-queue-deadline.py b/scripts/smoke-queue-deadline.py new file mode 100644 index 00000000..e0c5937c --- /dev/null +++ b/scripts/smoke-queue-deadline.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Isolated CPU worker: queued API expiry never sends GEN; active work survives.""" +import concurrent.futures +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + with tempfile.TemporaryDirectory(prefix='strata-queue-') as directory: + root = Path(directory) + fixture.tokenizer(root) + engine = root / 'engine.sh' + engine.write_text("""#!/bin/sh +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) + printf 'GEN\n' >> "$2/requests" + if [ ! -e "$2/active" ]; then + : > "$2/active" + while [ ! -e "$2/release" ]; do sleep 0.01; done + fi + printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + *) exit 4 ;; + esac +done +""") + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_STARTUP_TIMEOUT_S': '5', + 'STRATA_MAX_WORKER_RESTARTS': '0', 'STRATA_QUEUE_TIMEOUT_S': '1'} + + def request(path, payload=None): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=15) + try: + connection.request('POST' if payload is not None else 'GET', path, + json.dumps(payload) if payload is not None else None, + {'Content-Type': 'application/json', 'anthropic-version': '2023-06-01'}) + response = connection.getresponse() + return response.status, response.getheader('Content-Type'), response.read() + finally: + connection.close() + + response_payload = {'model': 'strata-local', 'input': 'Hello', 'reasoning': {'effort': 'none'}} + with tempfile.TemporaryFile() as logs: + runtime = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 8 + while True: + try: + if request('/ready')[0] == 200: + break + except (OSError, http.client.HTTPException): + pass + assert time.monotonic() < deadline, 'runtime not ready' + time.sleep(0.03) + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + active = pool.submit(request, '/v1/responses', response_payload) + try: + while not (root / 'active').exists(): + assert time.monotonic() < deadline, 'first GEN missing' + time.sleep(0.01) + for path, payload in [ + ('/v1/responses', response_payload), + ('/v1/chat/completions', {'model': 'strata-local', 'messages': [{'role':'user','content':'Hello'}]}), + ('/v1/messages', {'model': 'strata-local', 'max_tokens': 16, 'messages': [{'role':'user','content':'Hello'}]}), + ]: + for stream in [False, True]: + start = time.monotonic() + status, content_type, body = request(path, {**payload, 'stream': stream}) + elapsed = time.monotonic() - start + assert status == 504 and 'application/json' in content_type, (path, status, body) + error = json.loads(body)['error'] + assert 'queue deadline' in error['message'], error + if path != '/v1/messages': + assert error['code'] == 'queue_timeout', error + assert 0.7 <= elapsed < 5, elapsed + assert (root / 'requests').read_text().splitlines() == ['GEN'] + assert not active.done(), 'active generation expired under queue deadline' + assert request('/ready')[0] == 200 + finally: + (root / 'release').touch() + status, _, body = active.result(timeout=5) + assert status == 200 and json.loads(body)['output'][0]['content'][0]['text'] == 'A' + # All expired jobs must be skipped before the next live GEN. + for stream in [False, True]: + status, content_type, body = request('/v1/responses', {**response_payload, 'stream': stream}) + assert status == 200, body + if stream: + events = [json.loads(line[6:]) for line in body.decode().splitlines() if line.startswith('data: ')] + assert events[-1]['type'] == 'response.completed' + final = events[-1]['response'] + else: + final = json.loads(body) + assert final['output'][0]['content'][0]['text'] == 'A' + assert (root / 'requests').read_text().splitlines() == ['GEN'] * 3 + lifecycle = json.loads(request('/admin/lifecycle')[2]) + assert lifecycle['generation_jobs'] == 0, lifecycle + print('Queue deadline passed: 6 JSON/SSE Responses/Chat/Messages expirations, no queued GEN, active preserved, next JSON/SSE exact A, zero generation jobs') + finally: + if runtime.poll() is None: + runtime.send_signal(signal.SIGTERM) + try: + runtime.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(runtime.pid, signal.SIGKILL) + runtime.wait(timeout=5) + if runtime.returncode != 0: + logs.seek(0) + raise AssertionError(logs.read().decode()[-3000:]) + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-response-history.py b/scripts/smoke-response-history.py new file mode 100644 index 00000000..bdfc14ee --- /dev/null +++ b/scripts/smoke-response-history.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""CPU HTTP response resource lifecycle, exact terminal JSON and auth gates.""" +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + durable = "--durable" in sys.argv[2:] + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + key = 'fixture-only-response-resource-key-0001' + with tempfile.TemporaryDirectory(prefix='strata-response-history-') as directory: + root = Path(directory) + fixture.tokenizer(root) + key_file = root / 'api.key' + key_file.write_text(key) + key_file.chmod(0o600) + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf '%s' "$$" > "$2/worker.pid" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) printf x >> "$2/generations"; cat "$2/output" ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_MODEL_ID': 'fixture', 'STRATA_API_KEY_FILE': str(key_file), + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'} + + history_dir = root / 'private-history' + if durable: + env['STRATA_RESPONSE_HISTORY_DIR'] = str(history_dir) + + def request(method, path, payload=None, auth=True): + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=8) + headers = {'Content-Type': 'application/json'} + if auth: + headers['Authorization'] = 'Bearer ' + key + try: + connection.request(method, path, json.dumps(payload) if payload is not None else None, headers) + response = connection.getresponse() + data = response.read().decode() + if response.getheader('Content-Type', '').startswith('text/event-stream'): + events = [json.loads(line[5:]) for line in data.splitlines() if line.startswith('data:')] + assert events[-1]['type'] in ('response.completed', 'response.incomplete', 'response.failed'), events[-1] + data = events[-1]['response'] + else: + data = json.loads(data) + return response.status, data + finally: + connection.close() + + def generate(text, options=None, finish='stop'): + data = text.encode() + staged = root / 'output.new' + staged.write_text(''.join(f'T {token}\n' for token in data) + f'DONE {len(data)} 7 1.0 2.0 {finish}\n') + staged.replace(root / 'output') + code, result = request('POST', '/v1/responses', { + 'model': 'fixture', 'input': 'Respond', 'max_output_tokens': 1024, + 'reasoning': {'effort': 'none'}, 'metadata': {'fixture': 'kept'}, **(options or {})}) + assert code == 200, result + return result + + with tempfile.TemporaryFile() as logs: + def start(): + proc = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs) + try: + deadline = time.monotonic() + 10 + while True: + try: + if request('GET', '/ready')[0] == 200: + return proc + except OSError: + pass + assert proc.poll() is None and time.monotonic() < deadline + time.sleep(.02) + except BaseException: + proc.kill() + proc.wait(timeout=5) + raise + + def restart(): + nonlocal process + process.terminate() + assert process.wait(timeout=10) == 0 + process = start() + + if durable: + checked = subprocess.run([binary, 'check-config'], env=env, capture_output=True, timeout=5) + assert checked.returncode == 0 and json.loads(checked.stdout)['response_history'] == 'durable_unchecked' + assert not history_dir.exists() + process = start() + try: + if durable: + assert history_dir.stat().st_mode & 0o777 == 0o700 + duplicate = subprocess.run([binary, 'serve'], env=env, stdout=logs, stderr=logs, timeout=5) + assert duplicate.returncode != 0 + assert request('GET', '/ready')[0] == 200 + tool = '\n\n\nprint(1)\n\n\n' + function = '\n\n1\n\n' + cases = [('A', {}, 'stop'), ('Think.\n\nA', {'reasoning': {'effort': 'low'}}, 'stop'), + ('{"answer":"A"}', {'text': {'format': {'type': 'json_object'}}}, 'stop'), + (tool, {'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}, 'stop'), + ('Think.\n\n' + tool, {'reasoning': {'effort': 'low'}, + 'tools': [{'type': 'custom', 'name': 'run', 'format': {'type': 'text'}}]}, 'stop'), + (function, {'tools': [{'type': 'function', 'name': 'lookup', 'parameters': + {'type': 'object', 'properties': {'x': {'type': 'integer'}}}}]}, 'stop'), + ('A', {}, 'length')] + for text, options, finish in cases: + for stream in (False, True): + for store in (False, True): + result = generate(text, {**options, 'stream': stream, 'store': store}, finish) + path = '/v1/responses/' + result['id'] + if durable: + restart() + assert request('GET', path, auth=False)[0] == 401 + assert request('DELETE', path, auth=False)[0] == 401 + assert request('GET', path + '/input_items', auth=False)[0] == 401 + if not store: + assert request('GET', path + '/input_items')[0] == 404 + assert request('GET', path)[0] == request('DELETE', path)[0] == 404 + continue + assert request('GET', path) == (200, result) + generations = (root / 'generations').read_bytes() + code, page = request('GET', path + '/input_items') + assert code == 200 and page['object'] == 'list' and not page['has_more'], page + assert len(page['data']) == 1 and page['first_id'] == page['last_id'] + assert page['data'][0]['content'] == [{'type': 'input_text', 'text': 'Respond'}] + assert request('GET', path + '/input_items') == (code, page) + assert (root / 'generations').read_bytes() == generations + assert request('GET', path + '?stream=true')[0] == 400 + assert request('DELETE', path + '?unknown=1')[0] == 400 + assert request('GET', path) == (200, result) + assert request('DELETE', path) == (200, {'id': result['id'], 'object': 'response.deleted', 'deleted': True}) + if durable: + restart() + assert request('GET', path)[0] == request('DELETE', path)[0] == 404 + assert request('GET', path + '/input_items')[0] == 404 + parent = generate('A') + if durable: + restart() + child = generate('A', {'previous_response_id': parent['id']}) + child_path = '/v1/responses/' + child['id'] + '/input_items' + code, child_page = request('GET', child_path + '?order=asc') + assert code == 200 and len(child_page['data']) == 3, child_page + assert [item['role'] for item in child_page['data']] == ['user', 'assistant', 'user'] + assert child_page['data'][1]['content'] == parent['output'][0]['content'] + assert request('DELETE', '/v1/responses/' + parent['id'])[0] == 200 + assert request('GET', child_path + '?order=asc') == (200, child_page) + code, result = request('POST', '/v1/responses', {'model': 'fixture', 'input': 'again', 'previous_response_id': parent['id']}) + assert code == 404 and result['error']['code'] == 'response_not_found' + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + for stream in (False, True): + messages = [{'role': 'user', 'id': 'repeated-client-id', 'content': f'Input {i}'} for i in range(25)] + response = generate('A', {'input': messages, 'stream': stream}) + path = '/v1/responses/' + response['id'] + '/input_items' + generations = (root / 'generations').read_bytes() + code, first = request('GET', path) + assert code == 200 and len(first['data']) == 20 and first['has_more'] + assert first['data'][0]['content'][0]['text'] == 'Input 24' + code, second = request('GET', path + '?after=' + first['last_id']) + assert code == 200 and len(second['data']) == 5 and not second['has_more'] + desc = first['data'] + second['data'] + assert len({item['id'] for item in desc}) == 25 + code, asc = request('GET', path + '?order=asc&limit=100') + assert code == 200 and asc['data'] == list(reversed(desc)) and not asc['has_more'] + code, empty = request('GET', path + '?order=asc&after=' + asc['last_id']) + assert code == 200 and empty == {'object': 'list', 'data': [], 'first_id': None, 'last_id': None, 'has_more': False} + for query in ['limit=0', 'limit=101', 'limit=no', 'limit=1&limit=2', 'order=bad', + 'order=asc&order=desc', 'after=', 'after=a&after=b', 'after=missing', + 'after=' + child_page['first_id'], 'include=reasoning.encrypted_content', 'stream=true']: + code, error = request('GET', path + '?' + query) + assert code == 400 and error['error']['code'] == 'invalid_input_items_query', error + assert (root / 'generations').read_bytes() == generations + + typed = generate('A', {'stream': stream, 'input': [ + {'role': 'assistant', 'content': [{'type': 'input_text', 'text': 'Prior answer'}]}, + {'role': 'user', 'content': [{'type': 'output_text', 'text': 'Continue'}]}]}) + code, typed_page = request('GET', '/v1/responses/' + typed['id'] + '/input_items?order=asc') + assert code == 200 + assert typed_page['data'][0]['content'] == [{'type': 'output_text', 'text': 'Prior answer', 'annotations': []}] + assert typed_page['data'][1]['content'] == [{'type': 'input_text', 'text': 'Continue'}] + + history_input = [ + {'role': 'user', 'content': 'Use tools'}, + {'type': 'function_call', 'call_id': 'call_fn', 'namespace': 'files', 'name': 'lookup', 'arguments': '{"x": 1}'}, + {'type': 'function_call_output', 'call_id': 'call_fn', 'output': 'result'}, + {'type': 'custom_tool_call', 'call_id': 'call_custom', 'namespace': 'files', 'name': 'run', 'input': 'line1\nline2'}, + {'type': 'custom_tool_call_output', 'call_id': 'call_custom', 'output': 'done'}] + tools = [{'type': 'namespace', 'name': 'files', 'tools': [ + {'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', 'properties': {'x': {'type': 'integer'}}}}, + {'type': 'custom', 'name': 'run'}]}] + response = generate('A', {'input': history_input, 'tools': tools, 'stream': stream}) + if durable: + restart() + path = '/v1/responses/' + response['id'] + '/input_items?order=asc' + code, page = request('GET', path) + assert code == 200 and len(page['data']) == 5, page + for original, projected in zip(history_input[1:], page['data'][1:]): + assert {k: v for k, v in projected.items() if k != 'id'} == original + # Returned items remain usable for stateless continuation. + assert generate('A', {'input': page['data'], 'tools': tools, 'stream': stream})['status'] == 'completed' + if durable: + snapshot = history_dir / 'history-v1.json' + assert snapshot.stat().st_mode & 0o777 == 0o600 + for stream in (False, True): + committed = snapshot.read_bytes() + stage = history_dir / 'history-v1.pending' + stage.mkdir() + code, error = request('POST', '/v1/responses', { + 'model': 'fixture', 'input': 'storage-fault', + 'reasoning': {'effort': 'none'}, 'stream': stream}) + if stream: + assert code == 200 and error['status'] == 'failed', error + assert request('GET', '/v1/responses/' + error['id'])[0] == 404 + else: + assert code == 507 and error['error']['code'] == 'response_storage_failed', error + assert snapshot.read_bytes() == committed + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + assert request('DELETE', '/v1/responses/' + child['id'])[0] == 507 + stage.rmdir() + restart() + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + # A hard control-plane kill restores the latest acknowledged commit. + process.kill() + process.wait(timeout=5) + process = start() + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + assert request('POST', '/admin/drain', {})[0] == 200 + worker_pid = int((root / 'worker.pid').read_text()) + os.kill(worker_pid, signal.SIGKILL) + deadline = time.monotonic() + 5 + while request('GET', '/status')[1]['ready']: + assert time.monotonic() < deadline + time.sleep(.02) + assert request('GET', '/v1/responses/' + child['id']) == (200, child) + assert request('GET', child_path + '?order=asc') == (200, child_page) + assert request('DELETE', '/v1/responses/' + child['id'])[0] == 200 + assert request('GET', child_path)[0] == 404 + assert request('GET', '/v1/responses/missing')[0] == 404 + process.terminate() + assert process.wait(timeout=10) == 0 + if durable: + # Corruption fails before any new worker spawn, retaining the file. + snapshot = history_dir / 'history-v1.json' + worker_identity = (root / 'worker.pid').read_bytes() + original = snapshot.read_bytes() + snapshot.write_bytes(b'{broken-private-fixture') + failed = subprocess.run([binary, 'serve'], env=env, capture_output=True, timeout=5) + assert failed.returncode != 0 + assert b'broken-private-fixture' not in failed.stderr + assert (root / 'worker.pid').read_bytes() == worker_identity + assert snapshot.read_bytes() == b'{broken-private-fixture' + snapshot.write_bytes(original) + process = start() + assert request('GET', '/v1/responses/' + child['id'])[0] == 404 + process.terminate() + assert process.wait(timeout=10) == 0 + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + print(('Durable restart/fault mode: ' if durable else '') + 'Response resources: 28 original variants plus input-items pagination, exact tool replay, auth/deletion/outage and no extra generation passed') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-runtime-image.py b/scripts/smoke-runtime-image.py new file mode 100644 index 00000000..d4ca1f25 --- /dev/null +++ b/scripts/smoke-runtime-image.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Actual combined CPU image proof. Never use with a model/CUDA image.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import urllib.request +import uuid + + +def docker(*args, check=True): + return subprocess.run(['docker', *map(str, args)], check=check, capture_output=True, text=True, timeout=30) + + +def main(receipt): + proof = json.loads(Path(receipt).read_text()) + assert proof['kind'] == 'cpu-fixture' and proof['gpu_tested'] is False + image = proof['image'] + label = docker('inspect', '--format', '{{index .Config.Labels "io.strata.package-kind"}}', image).stdout.strip() + assert label == 'cpu-fixture' + spec = importlib.util.spec_from_file_location('helper', Path(__file__).with_name('smoke-worker-cancel.py')) + helper = importlib.util.module_from_spec(spec); spec.loader.exec_module(helper) + name = 'strata-runtime-smoke-' + uuid.uuid4().hex + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with tempfile.TemporaryDirectory(prefix='strata-container-fixture-') as tmp: + root = Path(tmp); root.chmod(0o755) + helper.tokenizer(root) + (root/'config.json').write_text(json.dumps({'bind': '0.0.0.0:8081', 'model': 'embedded-fixture', + 'engine_probe': True, 'engine': {'executable': '@embedded', 'args': ['/tmp/worker.pid'], + 'tokenizer_dir': '/fixture', 'startup_timeout_s': 5, 'max_restarts': 1}})) + for path in root.iterdir(): path.chmod(0o644) + try: + docker('run', '-d', '--name', name, '--platform', 'linux/amd64', '--read-only', + '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--user', '65532:65532', + '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '-e', 'CUDA_VISIBLE_DEVICES=', + '-e', 'NVIDIA_VISIBLE_DEVICES=void', '-p', '127.0.0.1::8081', + '--mount', f'type=bind,src={root},dst=/fixture,readonly', image, + 'serve', '--config', '/fixture/config.json') + port = int(docker('port', name, '8081/tcp').stdout.strip().rsplit(':', 1)[1]) + def request(route, body=None): + req = urllib.request.Request(f'http://127.0.0.1:{port}{route}', + data=json.dumps(body).encode() if body else None, headers={'Content-Type': 'application/json'}) + with opener.open(req, timeout=5) as response: return json.load(response) + def ready(): + deadline = time.monotonic()+15 + while time.monotonic()> '{commands}' +if [ "$3" = show ]; then + if [ "$4" = --property=FragmentPath ]; then + printf '%s\\n' 'FragmentPath={fragment}' 'DropInPaths={drop_ins}' 'NeedDaemonReload={reload}' + else + printf '%s' '{status}' + fi + exit 0 +fi +exit {42 if fail_action else 0} +""") + def control(action, check=True): + return run(str(binary), 'service-control', action, *fault_args[2:], env=fault_env, check=check) + manager() + for action in ['status', 'start', 'stop', 'restart', 'enable', 'disable']: + commands.write_text('') + result = json.loads(control(action).stdout) + assert result['manager'] == {'active_state': 'active', 'sub_state': 'running', 'main_pid': 123, 'unit_file_state': 'disabled'} + assert result['action_requested'] == (action != 'status') and result['model_readiness'] == 'not_checked' + lines = commands.read_text().splitlines() + expected = ['show', 'show'] if action == 'status' else ['show', action, 'show'] + if action in ('enable', 'disable'): expected.insert(2, 'show') + assert [line.split('|')[2] for line in lines] == expected + if action != 'status': + assert lines[1] == f'--user|--no-pager|{action}|--|{unit_name}' + assert fault_unit.read_bytes() == retained + # Readiness inputs and private credentials are checked before any manager call. + for ready_args in [[], ['--ready-url', 'http://192.0.2.1', '--ready-model', 'fixture'], + ['--ready-url', 'http://127.0.0.1:1', '--ready-model', 'fixture', '--ready-key-file', str(root/'absent-key')]]: + commands.write_text('') + bad = run(str(binary), 'service-control', 'restart-ready', *fault_args[2:], *ready_args, + env=fault_env, check=False) + assert bad.returncode != 0 and not commands.read_text(), bad.stderr + # Change identity only after the HTTP response. Success requires a fresh + # manager/file check and cannot replay start to hide the mismatch. + for changed in ('pid', 'fragment', 'unit'): + manager(); commands.write_text('') + class ChangingEndpoint(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if changed == 'pid': + manager(status='ActiveState=active\nSubState=running\nMainPID=124\nUnitFileState=disabled\n') + elif changed == 'fragment': manager(fragment='/changed.service') + else: fault_unit.write_text('changed during wait') + data = json.dumps({'service':'strata-control', 'model':'fixture', 'server_pid':123, + 'ready':True, 'worker':'ready'}).encode() + self.send_response(200); self.send_header('Content-Length', str(len(data))) + self.end_headers(); self.wfile.write(data) + def log_message(self, *_): pass + changed_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), ChangingEndpoint) + changed_thread = threading.Thread(target=changed_http.serve_forever, daemon=True); changed_thread.start() + try: + bad = run(str(binary), 'service-control', 'start-ready', *fault_args[2:], + '--ready-url', f'http://127.0.0.1:{changed_http.server_port}', '--ready-model', 'fixture', + '--ready-timeout-s', '2', env=fault_env, check=False) + assert bad.returncode != 0, bad.stdout + actions = [line.split('|')[2] for line in commands.read_text().splitlines()] + assert actions.count('start') == 1 and all(a in ('start','show') for a in actions), actions + finally: + changed_http.shutdown(); changed_http.server_close(); changed_thread.join(timeout=5) + fault_unit.write_bytes(retained) + for fragment, drop_ins in [('/different.service', ''), (None, '/unexpected.conf')]: + manager(fragment, drop_ins); commands.write_text('') + assert control('restart', check=False).returncode != 0 + assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show'] + manager(reload='yes'); commands.write_text('') + assert control('restart', check=False).returncode != 0 + assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show'] + manager(fail_action=True); commands.write_text('') + failed = control('restart', check=False) + assert failed.returncode != 0 and 'may be pending' in failed.stderr + assert [x.split('|')[2] for x in commands.read_text().splitlines()] == ['show', 'restart'] + manager(status='ActiveState=active\nSubState=running\nMainPID=invalid\n') + assert control('status', check=False).returncode != 0 + manager(); commands.write_text('') + fault_unit.chmod(0o644) + assert control('stop', check=False).returncode != 0 and not commands.read_text() + fault_unit.chmod(0o600) + fault_unit.write_text('different') + assert control('stop', check=False).returncode != 0 and not commands.read_text() + fault_unit.unlink(); fault_unit.symlink_to(root/'absent-control') + assert control('stop', check=False).returncode != 0 and not commands.read_text() + fault_unit.unlink() + assert control('status', check=False).returncode != 0 and not fault_unit.exists() + fault_unit.write_bytes(retained); fault_unit.chmod(0o600) + if not args.lifecycle: + print('Native systemd unit syntax and rejected-path checks passed') + return + + def ctl(*commands, check=True): + return run('systemctl', '--user', *commands, check=check) + + link = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'systemd/user' / unit_name + assert not link.exists() and not link.is_symlink(), 'refusing to replace a user unit' + try: + install_args = (str(binary), 'service-install', '--config', str(config), + '--working-dir', str(odd), '--env-file', str(env_file), + '--unit', unit_name) + installed = json.loads(run(*install_args, '--start').stdout) + assert installed['created'] and not installed['reused'], installed + assert installed['model_readiness'] == 'not_checked' and not installed['enable_requested'], installed + assert link.read_text() == generated and link.stat().st_mode & 0o777 == 0o600 + inode = link.stat().st_ino + original_pid = ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip() + repeated = json.loads(run(*install_args, '--start').stdout) + assert ctl('show', '--property=MainPID', '--value', unit_name).stdout.strip() == original_pid + assert repeated['reused'] and not repeated['created'], repeated + assert link.stat().st_ino == inode + # A different config path must not replace the active service unit. + other = odd / 'other-config.json' + other.write_text(config.read_text()) + bad = run(str(binary), 'service-install', '--config', str(other), + '--working-dir', str(odd), '--unit', unit_name, '--start', check=False) + assert bad.returncode != 0 and not bad.stdout + assert link.read_text() == generated and link.stat().st_ino == inode + deadline = time.monotonic() + 15 + while True: + try: + with urllib.request.urlopen(f'http://127.0.0.1:{port}/status', timeout=1) as response: + state = json.load(response) + break + except (OSError, urllib.error.URLError): + assert time.monotonic() < deadline, 'isolated service failed to listen' + time.sleep(0.05) + assert state['model'] == 'service-smoke-env', state + assert state['worker'] == 'unconfigured' and not state['ready'], state + with urllib.request.urlopen(f'http://127.0.0.1:{port}/health', timeout=1) as response: + assert response.status == 200 + try: + urllib.request.urlopen(f'http://127.0.0.1:{port}/ready', timeout=1) + raise AssertionError('no-worker service must not claim inference readiness') + except urllib.error.HTTPError as error: + assert error.code == 503 + error.close() + # Installer readiness is bounded and never treats no-worker health as ready. + before=ctl('show','--property=MainPID','--value',unit_name).stdout.strip() + bad=run(*install_args,'--start-ready','--ready-url',f'http://127.0.0.1:{port}', + '--ready-model','service-smoke-env','--ready-timeout-s','1',check=False) + assert bad.returncode!=0 and 'retained' in bad.stderr,bad.stderr + assert link.read_text()==generated + assert ctl('show','--property=MainPID','--value',unit_name).stdout.strip()==before + def native_ctl(action): + result = run(str(binary), 'service-control', action, *install_args[2:], check=False) + assert result.returncode == 0, (action, result.stderr, ctl('show', '--property=NeedDaemonReload', '--property=UnitFileState', unit_name).stdout) + return json.loads(result.stdout) + status = native_ctl('status') + assert status['manager']['active_state'] == 'active' and status['model_readiness'] == 'not_checked' + pid = status['manager']['main_pid'] + assert pid == int(original_pid) and state['server_pid'] == pid + assert native_ctl('start')['manager']['main_pid'] == pid + assert status['manager']['unit_file_state'] == 'disabled' + activation = link.parent / 'default.target.wants' / unit_name + assert not activation.exists() and not activation.is_symlink() + # Opt-in installation reuses the unit and enables without starting/restarting. + enabled = json.loads(run(*install_args, '--enable').stdout) + assert enabled['reused'] and enabled['enable_requested'] and not enabled['start_requested'] + assert activation.is_symlink() and activation.resolve() == link.resolve() + for _ in range(2): + state = native_ctl('enable')['manager'] + assert state['main_pid'] == pid and state['unit_file_state'] == 'enabled', state + for _ in range(2): + state = native_ctl('disable')['manager'] + assert state['main_pid'] == pid and state['unit_file_state'] == 'disabled', state + assert not activation.exists() and not activation.is_symlink() + # Both activation directions must preserve a conflicting link. + activation.parent.mkdir(exist_ok=True) + activation.symlink_to(root / 'foreign-missing-unit') + activation_inode = activation.lstat().st_ino + for action in ('enable', 'disable'): + bad = run(str(binary), 'service-control', action, *install_args[2:], check=False) + assert bad.returncode != 0 and activation.lstat().st_ino == activation_inode + assert int(ctl('show', '--property=MainPID', '--value', unit_name).stdout) == pid + activation.unlink() + # An intentionally altered activation link can mark the manager + # stale. Reconcile the owned fixture after restoring it. + ctl('daemon-reload') + for action in ('enable', 'disable'): + bad = run(str(binary), 'service-control', action, '--config', str(other), + '--working-dir', str(odd), '--unit', unit_name, check=False) + assert bad.returncode != 0 and not activation.exists() + assert native_ctl('status')['manager']['main_pid'] == pid + assert Path(f'/proc/{pid}/cwd').resolve() == odd.resolve() + assert Path(f'/proc/{pid}/exe').resolve() == binary.resolve() + # Wrong rendered config must fail before touching the running service. + bad = run(str(binary), 'service-control', 'stop', '--config', str(other), + '--working-dir', str(odd), '--unit', unit_name, check=False) + assert bad.returncode != 0 and native_ctl('status')['manager']['main_pid'] == pid + restarted = native_ctl('restart') + next_pid = restarted['manager']['main_pid'] + assert next_pid > 0 and next_pid != pid and not Path(f'/proc/{pid}').exists() + for _ in range(2): + stopped = native_ctl('stop') + assert stopped['manager']['active_state'] == 'inactive' and stopped['manager']['main_pid'] == 0 + assert not Path(f'/proc/{next_pid}').exists() + assert native_ctl('status')['manager']['active_state'] == 'inactive' + assert native_ctl('start')['manager']['main_pid'] > 0 + native_ctl('stop') + # Configure only this stopped, owned fixture for synthetic inference. + spec = importlib.util.spec_from_file_location('worker_fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + tokens = root / 'tokens'; tokens.mkdir(); fixture.tokenizer(tokens) + engine = root / 'ready-worker.sh' + engine.write_text("#!/bin/sh\nprintf 'READY 262144 stop\\n'\nwhile IFS= read -r line; do\n case \"$line\" in\n 'GEN '*) : > \"$2/begun\"; while [ -e \"$2/hold\" ]; do sleep 0.01; done; printf 'T 65\\nDONE 1 7 1.0 2.0 stop\\n' ;;\n QUIT) exit 0 ;;\n esac\ndone\n") + engine.chmod(0o700) + key_file = root / 'api.key'; key_file.write_text('service-fixture-private-key-0123456789'); key_file.chmod(0o600) + config.write_text(json.dumps({'bind': f'127.0.0.1:{port}', 'model': 'service-smoke', + 'api_key_file': str(key_file), 'engine': {'executable': str(engine), 'args':[str(root)], 'tokenizer_dir': str(tokens)}})) + ready_args = ['--ready-url', f'http://127.0.0.1:{port}', '--ready-model', 'service-smoke-env', + '--ready-key-file', str(key_file), '--ready-timeout-s', '10'] + def ready_control(action, options=ready_args, check=True): + value = run(str(binary), 'service-control', action, *install_args[2:], *options, check=False) + if check: assert value.returncode == 0, value.stderr + return value + def inference(): + request = urllib.request.Request(f'http://127.0.0.1:{port}/v1/responses', + data=json.dumps({'model':'service-smoke-env', 'input':'fixture', 'max_output_tokens':8, 'reasoning':{'effort':'none'}}).encode(), + headers={'Content-Type':'application/json', 'Authorization':'Bearer service-fixture-private-key-0123456789'}) + with urllib.request.urlopen(request, timeout=15) as response: + value = json.load(response) + assert value['status'] == 'completed', value + assert value['output'][0]['content'][0]['text'] == 'A', value + # Recreate only the stopped owned fixture to prove fresh install+ready. + assert native_ctl('status')['manager']['main_pid']==0 + assert link.read_text()==generated + link.unlink();ctl('daemon-reload') + bad=run(*install_args,'--start-ready',*ready_args[:4], + '--ready-key-file',str(root/'missing-key'),check=False) + assert bad.returncode!=0 and not link.exists() + first=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) + assert first['created'] and first['start_requested'] + + pid = first['manager']['main_pid'] + assert first['model_readiness'] == 'ready' and first['readiness']['server_pid'] == pid + inference() + repeated=json.loads(run(*install_args,'--start-ready',*ready_args).stdout) + assert repeated['reused'] and repeated['manager']['main_pid']==pid + assert repeated['readiness']['server_pid']==pid + assert json.loads(ready_control('start-ready').stdout)['manager']['main_pid'] == pid + for bad_options in [ready_args + ['--ready-timeout-s', '0'], + ready_args[:4] + ['--ready-key-file', str(root/'missing-key')]]: + assert ready_control('restart-ready', bad_options, check=False).returncode != 0 + assert native_ctl('status')['manager']['main_pid'] == pid + response_body = {'service':'strata-control', 'model':'service-smoke-env', + 'ready':True, 'worker':'ready', 'server_pid':1} + class OtherEndpoint(http.server.BaseHTTPRequestHandler): + def do_GET(self): + data = json.dumps(response_body).encode() + self.send_response(200); self.send_header('Content-Length', str(len(data))) + self.end_headers(); self.wfile.write(data) + def log_message(self, *_): pass + other_http = http.server.ThreadingHTTPServer(('127.0.0.1', 0), OtherEndpoint) + thread = threading.Thread(target=other_http.serve_forever, daemon=True); thread.start() + try: + wrong = ready_args.copy(); wrong[1] = f'http://127.0.0.1:{other_http.server_port}' + bad = ready_control('start-ready', wrong, check=False) + assert bad.returncode != 0 and 'managed server PID' in bad.stderr, bad.stderr + response_body.update(server_pid=pid, ready=False, worker='starting') + wrong[-1] = '1' + began = time.monotonic() + bad = ready_control('start-ready', wrong, check=False) + assert bad.returncode != 0 and 'deadline expired' in bad.stderr and time.monotonic()-began < 5, bad.stderr + assert native_ctl('status')['manager']['main_pid'] == pid + inference() + finally: + other_http.shutdown(); other_http.server_close(); thread.join(timeout=5) + restarted = json.loads(ready_control('restart-ready').stdout) + new_pid = restarted['manager']['main_pid'] + assert new_pid != pid and restarted['readiness']['server_pid'] == new_pid and not Path(f'/proc/{pid}').exists() + inference() + def admin(path='/admin/lifecycle', payload=None): + req = urllib.request.Request(f'http://127.0.0.1:{port}'+path, + data=json.dumps(payload).encode() if payload is not None else None, + headers={'Authorization':'Bearer '+key_file.read_text(), 'Content-Type':'application/json'}) + with urllib.request.urlopen(req, timeout=3) as response: return json.load(response) + def until(predicate): + deadline = time.monotonic()+5 + while not predicate(): + assert time.monotonic()= 0.9, elapsed + worker_pid = int((root / 'worker-pid').read_text()) + try: + os.kill(worker_pid, 0) + except ProcessLookupError: + pass + else: + raise AssertionError('worker survived shutdown') + finally: + (root / 'release').touch() + if conn: + conn.close() + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + pool.shutdown(wait=True, cancel_futures=True) + + +def main(): + binary = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + for signum in [signal.SIGTERM, signal.SIGINT]: + for grace, complete in [(5, True), (1, False), (None, False)]: + run_case(binary, fixture, signum, grace, complete) + print('Signal drain: 6 CPU cases passed; SIGTERM/SIGINT, exact SSE + queued JSON, irreversible drain, expiry/default, terminal events and no orphan worker') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-sse-keepalive.py b/scripts/smoke-sse-keepalive.py new file mode 100644 index 00000000..17b37da0 --- /dev/null +++ b/scripts/smoke-sse-keepalive.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Actual idle HTTP SSE, terminal parity and cancellation on isolated CPU workers.""" +from concurrent.futures import ThreadPoolExecutor +import http.client +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def load(name, filename): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def check(binary, kind, fixture, replay): + with tempfile.TemporaryDirectory(prefix='strata-sse-idle-') as directory: + root = Path(directory) + fixture.tokenizer(root) + text = '{"ok":true}' if kind == 'structured' else 'A' + response = {'model': 'fixture', 'input': 'hello', 'max_output_tokens': 1024, + 'reasoning': {'effort': 'none'}, 'store': False} + path = '/v1/responses' + if kind == 'structured': + response['text'] = {'format': {'type': 'json_object'}} + elif kind == 'tools': + response['tools'] = [{'type': 'function', 'name': 'lookup', 'parameters': { + 'type': 'object', 'properties': {'key': {'type': 'string'}}}}] + text = '\n\n\nvalue\n\n\n' + elif kind in ('chat', 'messages'): + path = '/v1/chat/completions' if kind == 'chat' else '/v1/messages' + response = {'model': 'fixture', 'messages': [{'role': 'user', 'content': 'hello'}], + 'max_tokens': 1024} + data = text.encode() + (root / 'output').write_text(''.join(f'T {b}\n' for b in data) + + f'DONE {len(data)} 7 1.0 2.0 stop\n') + engine = root / 'engine.py' + engine.write_text(f'#!{sys.executable}\n' + '''import os, pathlib, select, sys +root = pathlib.Path(sys.argv[2]) +(root / 'pid').write_text(str(os.getpid())) +print('READY 262144 stop', flush=True) +while True: + line = sys.stdin.readline() + if not line or line.strip() == 'QUIT': break + if not line.startswith('GEN '): continue + with (root / 'wire').open('a') as log: log.write(line) + canceled = False + while not (root / 'release').exists(): + if select.select([sys.stdin], [], [], .02)[0]: + command = sys.stdin.readline().strip() + if command == 'QUIT': sys.exit(0) + if command == 'STOP': + (root / 'stopped').touch() + print('DONE 0 7 1.0 2.0 stop', flush=True) + canceled = True + break + if not canceled: print((root / 'output').read_text(), end='', flush=True) +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', 'STRATA_MODEL_ID': 'fixture', + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_IN_FLIGHT_REQUESTS': '1', + 'STRATA_MAX_WORKER_RESTARTS': '0'} + + def open_request(method, target, payload=None): + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=22) + conn.request(method, target, json.dumps(payload) if payload is not None else None, + {'Content-Type': 'application/json', 'anthropic-version': '2023-06-01'}) + r = conn.getresponse() + assert r.status == 200, (kind, r.status, r.read()) + return conn, r + + def get(target): + conn, r = open_request('GET', target) + try: return json.loads(r.read()) + finally: conn.close() + + def until_comment(r): + started = time.monotonic() + body = bytearray() + while True: + line = r.readline() + assert line, (kind, 'stream ended before idle comment') + body.extend(line) + assert len(body) < 65536, (kind, 'unexpected prefill output') + if line.startswith(b':'): + assert line.strip() == b': keep-alive', line + assert r.readline() == b'\n' + body.extend(b'\n') + assert 13 <= time.monotonic() - started < 22, (kind, 'idle interval') + return body.decode() + + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, + start_new_session=True) + try: + deadline = time.monotonic() + 10 + while True: + try: + if get('/status')['ready']: break + except (OSError, AssertionError): pass + assert process.poll() is None and time.monotonic() < deadline, kind + time.sleep(.02) + pid = (root / 'pid').read_text() + conn, r = open_request('POST', path, {**response, 'stream': True}) + assert r.getheader('Content-Type').startswith('text/event-stream') + before = until_comment(r) + assert 'output_text.delta' not in before and 'content_block_delta' not in before + (root / 'release').touch() + body = before + r.read().decode() # Must end, not keep ticking after terminal. + conn.close() + events = [json.loads(line[5:]) for line in body.splitlines() + if line.startswith('data:') and line[5:].strip() != '[DONE]'] + if path == '/v1/responses': + terminal, _ = replay.verify_sse(body) + expected = replay.semantic(terminal) + elif kind == 'chat': + assert body.count('data: [DONE]') == 1 + assert ''.join(e['choices'][0]['delta'].get('content', '') for e in events) == 'A' + assert [e['choices'][0]['finish_reason'] for e in events + if e['choices'][0]['finish_reason'] is not None] == ['stop'] + else: + assert events[-1]['type'] == 'message_stop' + assert sum(e['type'] == 'message_stop' for e in events) == 1 + assert ''.join(e.get('delta', {}).get('text', '') for e in events) == 'A' + (root / 'release').unlink() + conn, r = open_request('POST', path, {**response, 'stream': True}) + until_comment(r) + conn.sock.shutdown(socket.SHUT_RDWR) + r.close() + conn.close() + deadline = time.monotonic() + 5 + while not (root / 'stopped').exists() or get('/admin/lifecycle')['generation_jobs']: + assert time.monotonic() < deadline, (kind, 'disconnect retained work') + time.sleep(.02) + assert get('/admin/lifecycle')['requests_in_flight'] == 0 + (root / 'release').touch() + conn, r = open_request('POST', path, {**response, 'stream': False}) + result = json.loads(r.read()) + conn.close() + if path == '/v1/responses': + assert replay.semantic(result) == expected + assert result['usage'] == terminal['usage'] + elif kind == 'chat': + assert result['choices'][0]['message']['content'] == 'A' + else: + assert result['content'] == [{'type': 'text', 'text': 'A'}] + wires = (root / 'wire').read_text().splitlines() + assert len(wires) == 3 and wires[0] == wires[1] == wires[2] + assert (root / 'pid').read_text() == pid + print(f'{kind}: idle comment, exact output/GEN parity, terminal EOF, disconnect and same-worker reuse passed') + finally: + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + + +if __name__ == '__main__': + binary = str(Path(sys.argv[1]).resolve()) + fixture = load('fixture', 'smoke-worker-cancel.py') + replay = load('replay', 'replay-live-responses.py') + with ThreadPoolExecutor(max_workers=5) as pool: + futures = [pool.submit(check, binary, kind, fixture, replay) + for kind in ('text', 'structured', 'tools', 'chat', 'messages')] + for future in futures: future.result() diff --git a/scripts/smoke-static-cli.py b/scripts/smoke-static-cli.py new file mode 100644 index 00000000..a1406eb2 --- /dev/null +++ b/scripts/smoke-static-cli.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""CI-only fixture for the standalone Linux CLI; no model assets are retained.""" + +import hashlib +import json +import pathlib +import struct +import subprocess +import sys +import tempfile + + +def fixture() -> bytes: + header = bytearray(b"GGUF" + struct.pack(" None: + encoded = value.encode() + header.extend(struct.pack(" bytes: + header = bytearray(b"GGUF" + struct.pack(" None: + encoded = value.encode() + header.extend(struct.pack(" None: + binary = pathlib.Path(sys.argv[1]).resolve() + with tempfile.TemporaryDirectory(prefix="strata-static-smoke-") as temporary: + root = pathlib.Path(temporary) + source = root / "mixed.gguf" + archive = root / "mixed.kar" + source.write_bytes(fixture()) + derive = subprocess.run( + [binary, "model", "derive-mixed-identity", source], + capture_output=True, + text=True, + check=True, + ) + identity = json.loads(derive.stdout) + expected_source = "c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7" + assert identity["derived_f32_sha256"] == expected_source + prepare = subprocess.run( + [binary, "model", "prepare-mixed-preview", source, "--output", archive, "--levels", "2"], + capture_output=True, + text=True, + check=True, + ) + assert "not eligible for serving" in prepare.stdout + expected_archive = "4053e787d46b2cf2bca3d67e38d06e1ee96a157e80e3155c8dbdbf36835df88c" + assert hashlib.sha256(archive.read_bytes()).hexdigest() == expected_archive + provenance = json.loads((root / "mixed.kar.provenance.json").read_text()) + assert provenance["original_gguf_sha256"] == hashlib.sha256(source.read_bytes()).hexdigest() + assert provenance["derived_f32_sha256"] == expected_source + assert provenance["archive_sha256"] == expected_archive + verify = subprocess.run( + [binary, "model", "verify-mixed-preview", archive, "--source", source], + capture_output=True, + text=True, + check=True, + ) + assert "payload CRCs match" in verify.stdout + + # Projection conversion must preserve every F32 bit and refuse overwrite. + export = root / "dense.f32" + result = subprocess.run([binary, "model", "export-tensor-f32", source, "dense", "--output", export], + capture_output=True, text=True, check=True) + metadata = json.loads(result.stdout) + expected = b"".join(struct.pack("\n\n\n{source}\n\n\n' + patch_call = custom_call.replace(alias, 'patch') + forced_custom = {'type': 'custom', 'name': 'patch'} + both = function_call + '\n' + custom_call + cases = [ + ('auto', True, both, 2, True), + (None, None, both, 2, True), + ('auto', False, 'OK', 0, True), + ('auto', False, function_call, 1, True), + ('auto', False, custom_call, 1, True), + ('auto', False, both, 2, False), + ('none', True, 'OK', 0, True), + ('none', True, custom_call, 1, False), + ('none', False, both, 2, False), + ] + forced = {'type': 'function', 'name': 'lookup'} + cases.extend([ + ('required', True, 'OK', 0, False), + ('required', True, function_call, 1, True), + ('required', True, custom_call, 1, True), + ('required', True, both, 2, True), + ('required', False, both, 2, False), + (forced, True, function_call, 1, True), + (forced, True, custom_call, 1, False), + (forced, True, both, 2, False), + (forced, True, function_call + '\n' + function_call, 2, False), + (forced, True, 'OK', 0, False), + ]) + cases.extend([ + (forced_custom, True, patch_call, 1, True), + (forced_custom, False, patch_call, 1, True), + (forced_custom, True, function_call, 1, False), + (forced_custom, True, custom_call, 1, False), + (forced_custom, True, patch_call + '\n' + patch_call, 2, False), + (forced_custom, True, patch_call + '\n' + function_call, 2, False), + (forced_custom, True, 'OK', 0, False), + ]) + cases = [(*case, 'stop') for case in cases] + cases.extend((choice, True, 'OK', 0, True, 'length') for choice in ['required', forced, forced_custom]) + cases.extend([ + (forced_custom, True, patch_call, 1, True, 'length'), + (forced_custom, True, function_call, 1, False, 'length'), + (forced_custom, True, patch_call + '\n' + patch_call, 2, False, 'length'), + ]) + cases = [(*case, False) for case in cases] + cases.extend([ + (forced_custom, True, patch_call, 1, True, 'stop', True), + (forced_custom, True, patch_call.replace(source, 'FORBIDDEN'), 1, False, 'stop', True), + ]) + # Expected visible prefix counts are fixture expectations, independent + # of the server's subset validation. Reasoning buffers calls until DONE. + cases = [(*case, None) for case in cases] + allow_function = {'type': 'allowed_tools', 'mode': 'auto', 'tools': [forced]} + allow_custom = {'type': 'allowed_tools', 'mode': 'required', 'tools': [forced_custom]} + allow_both = {'type': 'allowed_tools', 'mode': 'auto', 'tools': [forced, forced_custom]} + allow_empty = {'type': 'allowed_tools', 'mode': 'auto', 'tools': []} + cases.extend([ + (allow_function, True, 'OK', 0, True, 'stop', False, 0), + (allow_function, True, function_call, 1, True, 'stop', False, 1), + (allow_function, True, patch_call, 1, False, 'stop', False, 0), + (allow_function, True, custom_call, 1, False, 'stop', False, 0), + (allow_function, True, function_call + '\n' + patch_call, 2, False, 'stop', False, 1), + (allow_function, True, patch_call + '\n' + function_call, 2, False, 'stop', False, 0), + (allow_custom, True, 'OK', 0, False, 'stop', False, 0), + (allow_custom, True, patch_call, 1, True, 'stop', True, 1), + (allow_custom, True, function_call, 1, False, 'stop', False, 0), + (allow_custom, True, patch_call + '\n' + patch_call, 2, True, 'stop', False, 2), + (allow_custom, False, patch_call + '\n' + patch_call, 2, False, 'stop', False, 1), + (allow_custom, True, 'OK', 0, True, 'length', False, 0), + (allow_custom, True, function_call, 1, False, 'length', False, 0), + (allow_custom, True, patch_call + '\n' + function_call, 2, False, 'length', False, 1), + (allow_both, True, function_call + '\n' + patch_call, 2, True, 'stop', False, 2), + (allow_both, True, both, 2, False, 'stop', False, 1), + (allow_empty, True, 'OK', 0, True, 'stop', False, 0), + (allow_empty, True, function_call, 1, False, 'stop', False, 0), + (allow_empty, True, custom_call, 1, False, 'stop', False, 0), + (allow_empty, True, 'OK', 0, True, 'length', False, 0), + ]) + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 8 + while True: + try: + if request('/ready')[0] == 200: + break + except OSError: + pass + assert process.poll() is None and time.monotonic() < deadline + time.sleep(0.01) + total = 0 + for effort in ['none', 'low']: + for stream in [False, True]: + for choice, parallel, output, count, valid, reason, regex, expected_prefix in cases: + data = (('Think.\n\n' if effort == 'low' else '') + output).encode() + # An early failed SSE response can precede the worker's + # final read/EOF. Never truncate the inode cat is reading: + # doing so can splice the next case into this generation. + staged = root / 'next.new' + staged.write_text(''.join(f'T {byte}\n' for byte in data) + f'DONE {len(data)} 7 1.0 2.0 {reason}\n') + staged.replace(root / 'next') + payload = {'model': 'fixture', 'input': 'Use policy', 'max_output_tokens': 1024, + 'reasoning': {'effort': effort}, 'stream': stream, 'tools': tools, + 'metadata': {'fixture': 'policy'}} + if choice is not None: + payload['tool_choice'] = choice + if parallel is not None: + payload['parallel_tool_calls'] = parallel + expected_tools = copy.deepcopy(tools) + if regex: + expected_tools[1]['format'] = {'type': 'grammar', 'syntax': 'regex', + 'definition': r"print\('Привіт 🌍'\)\n # exact spacing"} + payload['tools'] = expected_tools + code, body = request('/v1/responses', payload) + total += 1 + if stream: + assert code == 200, (code, body) + events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')] + assert [e['sequence_number'] for e in events] == list(range(len(events))) + assert events[-1]['type'] == (('response.incomplete' if reason == 'length' else 'response.completed') if valid else 'response.failed'), body + published = [e['item'] for e in events if e['type'] == 'response.output_item.added' + and e['item']['type'] in ('function_call', 'custom_tool_call')] + published_ids = {item['id'] for item in published} + for event in events: + if 'function_call_arguments' in event['type'] or 'custom_tool_call_input' in event['type']: + assert event['item_id'] in published_ids, body + if not valid: + allowed = int(effort == 'none' and ( + (choice == forced_custom and output.startswith(patch_call)) or + (choice not in ('none', forced_custom) and output.startswith(function_call)))) + if expected_prefix is not None: + allowed = expected_prefix if effort == 'none' else 0 + assert len(published) == allowed, body + inputs = [e for e in events if 'custom_tool_call_input' in e['type']] + if allowed and published[0]['type'] == 'custom_tool_call': + assert published[0]['name'] == 'patch' + assert ''.join(e['delta'] for e in inputs if e['type'].endswith('.delta')) == source + assert [e['input'] for e in inputs if e['type'].endswith('.done')] == [source] + else: + assert not inputs, body + continue + assert len(published) == count + result = events[-1]['response'] + else: + if not valid: + assert code == 502 and 'output' not in json.loads(body), (code, body) + continue + assert code == 200, (code, body) + result = json.loads(body) + assert result['status'] == ('incomplete' if reason == 'length' else 'completed') + assert result['tool_choice'] == (choice or 'auto') + assert result['parallel_tool_calls'] == (parallel if parallel is not None else True) + assert result['tools'] == expected_tools and result['metadata'] == {'fixture': 'policy'} + calls = [item for item in result['output'] if item['type'] in ('function_call', 'custom_tool_call')] + assert len(calls) == count + if stream: + custom_count = sum(call['type'] == 'custom_tool_call' for call in calls) + assert ''.join(e['delta'] for e in events if e['type'] == 'response.custom_tool_call_input.delta') == source * custom_count + assert [e['input'] for e in events if e['type'] == 'response.custom_tool_call_input.done'] == [source] * custom_count + assert [i['call_id'] for i in published] == [call['call_id'] for call in calls] + for call in calls: + if call['type'] == 'custom_tool_call': + assert call['input'] == source + if call['name'] == 'patch': + assert 'namespace' not in call + else: + assert call['name'] == 'run' and call['namespace'] == 'code' + else: + assert json.loads(call['arguments']) == {'key': 'value'} + if count == 0: + assert result['output'][-1]['content'][0]['text'] == 'OK' + invalid_choices = [ + {'tool_choice': 'required', 'tools': []}, + {'tool_choice': 'required', 'tools': [{'type': 'namespace', 'name': 'empty', 'tools': []}]}, + {'tool_choice': {'type': 'function'}}, + {'tool_choice': {'type': 'function', 'name': 'missing'}}, + {'tool_choice': {'type': 'function', 'name': alias}}, + {'tool_choice': {'type': 'function', 'name': 1}}, + {'tool_choice': {**forced, 'namespace': 'code'}}, + {'tool_choice': forced, 'tools': [{'type': 'custom', 'name': 'lookup'}]}, + {'tool_choice': {'type': 'custom'}}, + {'tool_choice': {'type': 'custom', 'name': 'missing'}}, + {'tool_choice': {'type': 'custom', 'name': alias}}, + {'tool_choice': {'type': 'custom', 'name': 'run'}}, + {'tool_choice': {'type': 'custom', 'name': 1}}, + {'tool_choice': {'type': 'custom', 'name': 'lookup'}}, + {'tool_choice': {**forced_custom, 'namespace': 'code'}}, + ] + for choice in [ + {'type': 'allowed_tools'}, + {**allow_function, 'mode': 'none'}, + {**allow_function, 'mode': None}, + {**allow_function, 'extra': True}, + {**allow_function, 'tools': None}, + {**allow_function, 'tools': {}}, + {**allow_empty, 'mode': 'required'}, + {**allow_function, 'tools': [forced, forced]}, + {**allow_function, 'tools': [{'type': 'function', 'name': 'patch'}]}, + {**allow_function, 'tools': [{'type': 'custom', 'name': 'lookup'}]}, + {**allow_function, 'tools': [{'type': 'function', 'name': 'missing'}]}, + {**allow_function, 'tools': [{'type': 'custom', 'name': alias}]}, + {**allow_function, 'tools': [{'type': 'custom', 'name': 'run', 'namespace': 'code'}]}, + {**allow_function, 'tools': [{'type': 'mcp', 'server_label': 'fixture'}]}, + {**allow_function, 'tools': [{'type': 'function'}]}, + {**allow_function, 'tools': [{'type': 'function', 'name': 1}]}, + {**allow_function, 'tools': [None]}, + {**allow_function, 'tools': [forced, {'type': 'function', 'name': 'missing'}]}, + ]: + invalid_choices.append({'tool_choice': choice}) + for invalid in invalid_choices: + assert request('/v1/responses', {**payload, **invalid})[0] == 400, invalid + for unsupported in [{'type': 'unknown'}]: + payload['tool_choice'] = unsupported + assert request('/v1/responses', payload)[0] == 501 + assert json.loads(request('/metrics')[1])['generation']['started'] == total == 216 + except Exception: + logs.seek(0) + print('Synthetic tool-policy worker log:', logs.read().decode(errors='replace'), file=sys.stderr) + raise + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + print('Tool policy: 216 CPU HTTP cases passed; auto/none/required/forced/allowed_tools, single-call, incomplete, mixed tools, reasoning, JSON/SSE, 33 malformed choices, metadata and exact accepted input') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-wait-ready.py b/scripts/smoke-wait-ready.py new file mode 100644 index 00000000..12a27264 --- /dev/null +++ b/scripts/smoke-wait-ready.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Actual HTTP deadline/admission checks for native GET-only deployment readiness.""" +import http.client +import http.server +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time + + +def main(): + binary = Path(sys.argv[1]).resolve() + key = 'fixture-only-wait-ready-key-00001' + ready = {'service': 'strata-control', 'model': 'fixture', 'worker': 'ready', 'ready': True} + state = {'mode': 'ready', 'calls': 0, 'paths': [], 'auth': []} + stopped = threading.Event() + + class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + def log_message(self, *_): + pass + + def do_GET(self): + self.close_connection = True + state['calls'] += 1 + state['paths'].append(self.path) + state['auth'].append(self.headers.get('Authorization') == 'Bearer ' + key) + mode = state['mode'] + body = dict(ready) + status = 200 + try: + if mode == 'headers': + self.wfile.write(b'HTTP/1.1 200 OK\r\nX-Drip: ') + while not stopped.wait(.1): + self.wfile.write(b'x') + self.wfile.flush() + return + if mode == 'loading' and state['calls'] < 3: + body.update(worker='starting', ready=False) + if mode == 'unavailable' and state['calls'] < 3: + status = 503 + if mode == 'wrong_model': + body['model'] = 'other' + if mode == 'wrong_service': + body['service'] = 'other' + if mode == 'inconsistent': + body['worker'] = 'failed' + if mode == 'wrong_type': + body['ready'] = 'true' + if mode == 'auth': + status = 401 + if mode == 'redirect': + status = 302 + encoded = json.dumps(body).encode() + if mode == 'malformed': + encoded = b'not-json-fixture-peer-body' + if mode in ('oversize', 'chunked_oversize'): + encoded = b'x' * 65537 + self.send_response(status) + if mode == 'redirect': + self.send_header('Location', f'http://127.0.0.1:{self.server.server_port}/redirect-leak') + if mode == 'chunked_oversize': + self.send_header('Transfer-Encoding', 'chunked') + else: + self.send_header('Content-Length', str(len(encoded))) + self.end_headers() + if mode == 'body': + for byte in encoded: + if stopped.wait(.1): + break + self.wfile.write(bytes([byte])) + self.wfile.flush() + elif mode == 'chunked_oversize': + self.wfile.write(f'{len(encoded):x}\r\n'.encode() + encoded + b'\r\n0\r\n\r\n') + else: + self.wfile.write(encoded) + except (BrokenPipeError, ConnectionResetError): + pass + + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + server.daemon_threads = True + thread = threading.Thread(target=server.serve_forever) + thread.start() + with tempfile.TemporaryDirectory(prefix='strata-wait-ready-') as directory: + root = Path(directory) + key_file = root / 'key' + initialized = subprocess.run([binary, 'api-key', 'init', '--file', key_file], + capture_output=True, timeout=8) + assert initialized.returncode == 0 + key = key_file.read_text().strip() + assert key.encode() not in initialized.stdout + initialized.stderr + env = {'PATH': os.defpath, 'http_proxy': 'http://127.0.0.1:1', 'HTTP_PROXY': 'http://127.0.0.1:1', + 'ALL_PROXY': 'http://127.0.0.1:1', 'NO_PROXY': '', 'no_proxy': ''} + origin = f'http://127.0.0.1:{server.server_port}' + + def run(url=origin, budget='2', keyed=True): + command = [binary, 'wait-ready', '--url', url, '--model', 'fixture', '--timeout-s', budget] + if keyed: + command += ['--key-file', str(key_file)] + began = time.monotonic() + result = subprocess.run(command, env=env, capture_output=True, timeout=6) + elapsed = time.monotonic() - began + assert key.encode() not in result.stdout + result.stderr + assert b'not-json-fixture-peer-body' not in result.stdout + result.stderr + return result, elapsed + + try: + for mode in ['ready', 'loading', 'unavailable']: + state.update(mode=mode, calls=0, paths=[], auth=[]) + result, _ = run() + assert result.returncode == 0, result.stderr + data = json.loads(result.stdout) + assert data == {**{'service': 'strata-control', 'model': 'fixture', 'ready': True}, 'attempts': state['calls']} + assert state['calls'] == (1 if mode == 'ready' else 3) + assert all(state['auth']) and set(state['paths']) == {'/status'} + for mode, message in [('wrong_model', 'does not match'), ('wrong_service', 'does not match'), + ('inconsistent', 'inconsistent'), ('wrong_type', 'invalid readiness flag'), + ('auth', 'authentication rejected'), ('redirect', 'redirects'), + ('malformed', 'invalid readiness JSON'), ('oversize', '64 KiB'), ('chunked_oversize', '64 KiB')]: + state.update(mode=mode, calls=0, paths=[], auth=[]) + result, _ = run() + assert result.returncode != 0 and message.encode() in result.stderr, (mode, result.stderr) + assert state['calls'] == 1 and state['paths'] == ['/status'] + for mode in ['headers', 'body']: + state.update(mode=mode, calls=0, paths=[], auth=[]) + result, elapsed = run(budget='1') + assert result.returncode != 0 and b'deadline expired' in result.stderr, (mode, result.stderr) + assert .8 <= elapsed < 2.5, (mode, elapsed) + state.update(mode='ready', calls=0) + key_file.chmod(0o644) + result, _ = run() + assert result.returncode != 0 and state['calls'] == 0 + key_file.chmod(0o600) + key_file.write_text('bad-key') + result, _ = run() + assert result.returncode != 0 and state['calls'] == 0 + key_file.write_text(key) + # Same binary serves a real isolated native /status. No GEN permitted. + spec = importlib.util.spec_from_file_location('fixture', Path(__file__).with_name('smoke-worker-cancel.py')) + fixture = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fixture) + fixture.tokenizer(root) + worker = root / 'engine.sh' + worker.write_text('''#!/bin/sh +printf '%s' "$$" > "$2/pid" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in QUIT) exit 0 ;; *) printf x > "$2/unexpected-command"; exit 7 ;; esac +done +''') + worker.chmod(0o700) + with socket.socket() as port_probe: + port_probe.bind(('127.0.0.1', 0)) + port = port_probe.getsockname()[1] + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env={'PATH': os.defpath, + 'STRATA_BIND': f'127.0.0.1:{port}', 'STRATA_MODEL_ID': 'fixture', + 'STRATA_ENGINE_EXE': str(worker), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_API_KEY_FILE': str(key_file), + 'STRATA_MAX_WORKER_RESTARTS': '0'}, stdout=logs, stderr=logs) + try: + result, _ = run(url=f'http://127.0.0.1:{port}') + assert result.returncode == 0, result.stderr + os.kill(int((root / 'pid').read_text()), signal.SIGKILL) + # Observe actual readiness revocation before asking the waiter. + deadline = time.monotonic() + 3 + while True: + connection = http.client.HTTPConnection('127.0.0.1', port, timeout=1) + connection.request('GET', '/ready', headers={'Authorization': 'Bearer ' + key}) + response = connection.getresponse() + response.read() + connection.close() + if response.status == 503: + break + assert time.monotonic() < deadline + time.sleep(.02) + result, elapsed = run(url=f'http://127.0.0.1:{port}', budget='1') + assert result.returncode != 0 and b'deadline expired' in result.stderr + assert elapsed < 2.5 and not (root / 'unexpected-command').exists() + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + logs.seek(0) + assert key.encode() not in logs.read() + finally: + stopped.set() + server.shutdown() + server.server_close() + thread.join(timeout=3) + print('wait-ready: exact identity/loading/auth/redirect/no-proxy/64KiB/drip deadline/private key and native worker outage passed; GET only, no inference') + + +if __name__ == '__main__': + main() diff --git a/scripts/smoke-worker-cancel.py b/scripts/smoke-worker-cancel.py new file mode 100644 index 00000000..a9bcef7b --- /dev/null +++ b/scripts/smoke-worker-cancel.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Exercise STOP isolation and optional crash recovery through real HTTP.""" + +import http.client +import json +import os +import pathlib +import signal +import socket +import subprocess +import sys +import tempfile +import time + + +def tokenizer(root): + visible = set(range(33, 127)) | set(range(161, 173)) | set(range(174, 256)) + shifted = iter(range(256, 512)) + tokens = [chr(i if i in visible else next(shifted)) for i in range(256)] + tokens += ["<|im_start|>", "<|im_end|>", "", ""] + pattern = ( + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])" + r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}" + r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" + ) + files = { + "vocab.json": {token: i for i, token in enumerate(tokens)}, + "token_type.json": [1] * 256 + [3] * 4, + "tokenizer.json": { + "model": "gpt2", "pre": "qwen35", "vocab_size": len(tokens), + "n_merges": 0, "special_ids": {}, "pre_pattern": pattern, + }, + } + for name, value in files.items(): + (root / name).write_text(json.dumps(value)) + (root / "merges.txt").write_text("") + + +def main(): + binary = pathlib.Path(sys.argv[1]).resolve() + recovery = len(sys.argv) == 3 and sys.argv[2] == "--restart" + with tempfile.TemporaryDirectory(prefix="strata-cancel-http-") as directory: + root = pathlib.Path(directory) + tokenizer(root) + engine = root / "engine.sh" + pid_path, stopped = root / "worker.pid", root / "stopped" + engine.write_text("""#!/bin/sh +printf '%s' "$$" > "$2" +printf 'READY 262144 stop\n' +IFS= read -r line || exit 3 +case "$line" in 'GEN '*) ;; *) exit 4 ;; esac +printf 'T 65\n' +IFS= read -r line || exit 3 +[ "$line" = STOP ] || exit 4 +: > "$3" +printf 'T 66\n' +while IFS= read -r line; do + case "$line" in QUIT) exit 0 ;; esac +done +""") + if recovery: + engine.write_text("""#!/bin/sh +printf '%s' "$$" > "$2" +printf 'boot\n' >> "$3.boots" +printf 'READY 262144 stop\n' +while IFS= read -r line; do + case "$line" in + 'GEN '*) + printf '%s\n' "$line" >> "$3.requests" + if [ ! -e "$3.crashed" ]; then + : > "$3.crashed" + printf 'T 65\n' + exit 7 + fi + printf 'T 65\nDONE 1 1 1.0 2.0 stop\n' ;; + QUIT) exit 0 ;; + esac +done +""") + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + env = { + "PATH": os.defpath, "STRATA_BIND": f"127.0.0.1:{port}", + "STRATA_ENGINE_EXE": str(engine), + "STRATA_ENGINE_ARGS_JSON": json.dumps([str(pid_path), str(stopped)]), + "STRATA_TOKENIZER_DIR": str(root), "STRATA_STARTUP_TIMEOUT_S": "5", + "STRATA_MAX_WORKER_RESTARTS": "1" if recovery else "0", + } + + def request(method, path, body=None, timeout=30): + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) + connection.request(method, path, body, {"Content-Type": "application/json"}) + return connection, connection.getresponse() + + with tempfile.TemporaryFile() as logs: + runtime = subprocess.Popen([binary, "serve"], env=env, stdout=logs, + stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 8 + while True: + try: + conn, response = request("GET", "/ready", timeout=1) + ready = response.status == 200 + response.read() + conn.close() + if ready: + break + except (OSError, http.client.HTTPException): + pass + assert time.monotonic() < deadline, "runtime did not become ready" + time.sleep(0.02) + payload = {"model": "fixture", "input": "hello", "max_output_tokens": 3, + "reasoning": {"effort": "none"}, "stream": True} + if recovery: + payload["stream"] = False + began = time.monotonic() + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 503, (response.status, response.read()) + assert json.loads(response.read())["error"]["code"] == "worker_not_ready" + conn.close() + conn, response = request("GET", "/ready") + state = json.loads(response.read()) + assert response.status == 503 and state["worker"] == "restarting" + assert state["max_context"] is None + conn.close() + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 503 + response.read() + conn.close() + while True: + conn, response = request("GET", "/ready") + ready = response.status == 200 + response.read() + conn.close() + if ready: + break + assert time.monotonic() - began < 8, "worker did not recover" + time.sleep(0.02) + elapsed = time.monotonic() - began + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 200 + answer = json.loads(response.read()) + assert answer["output"][0]["content"][0]["text"] == "A" + assert answer["status"] == "completed" + conn.close() + assert pathlib.Path(str(stopped) + ".boots").read_text().splitlines() == ["boot", "boot"] + assert len(pathlib.Path(str(stopped) + ".requests").read_text().splitlines()) == 2 + print(json.dumps({"restart_seconds": round(elapsed, 3), + "failed_request": 503, "during_recovery": 503, + "fresh_request": 200, "fresh_text": "A", + "process_starts": 2, "generations": 2, + "failed_generation_replayed": False})) + return + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 200 + while b"response.output_text.delta" not in response.readline(): + assert not response.isclosed(), "stream ended before first token" + conn.sock.shutdown(socket.SHUT_RDWR) + response.close() + conn.close() + cancel_at = time.monotonic() + while not stopped.exists(): + assert time.monotonic() - cancel_at < 3, "STOP was not delivered" + time.sleep(0.02) + payload["stream"] = False + conn, response = request("POST", "/v1/responses", json.dumps(payload)) + assert response.status == 503, (response.status, response.read()) + failure = json.loads(response.read()) + assert failure["error"]["code"] == "worker_not_ready" + conn.close() + elapsed = time.monotonic() - cancel_at + assert 19.5 <= elapsed < 25, elapsed + conn, response = request("GET", "/ready") + state = json.loads(response.read()) + assert response.status == 503 and state["worker"] == "failed" + assert state["max_context"] is None + conn.close() + conn, response = request("GET", "/health") + assert response.status == 200 + response.read() + conn.close() + try: + os.kill(int(pid_path.read_text()), 0) + except ProcessLookupError: + pass + else: + raise AssertionError("worker was not reaped") + print(json.dumps({"stop_drain_seconds": round(elapsed, 3), + "queued_request": 503, "readiness": "failed", + "worker_reaped": True, "health": 200})) + finally: + if runtime.poll() is None: + os.killpg(runtime.pid, signal.SIGTERM) + try: + runtime.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(runtime.pid, signal.SIGKILL) + runtime.wait() + + +if __name__ == "__main__": + main() diff --git a/scripts/split-ple-row-trace.py b/scripts/split-ple-row-trace.py new file mode 100644 index 00000000..5884e78e --- /dev/null +++ b/scripts/split-ple-row-trace.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Convert a private global PLE row trace into one KAR part's local batches.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--trace", required=True, type=Path) + parser.add_argument("--part-start", required=True, type=int) + parser.add_argument("--part-rows", required=True, type=int) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + if args.part_start < 0 or args.part_rows < 1 or args.part_start + args.part_rows > 2**32: + parser.error("part bounds must fit global u32 row IDs") + if args.output.exists(): + parser.error("output already exists; choose a new private path") + + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(args.output, flags, 0o600) + tokens = batches = accesses = 0 + output_hash = hashlib.sha256() + try: + with args.trace.open() as source, os.fdopen(fd, "w") as output: + header = f"# KAR part global rows [{args.part_start},{args.part_start + args.part_rows})\n" + output.write(header) + output_hash.update(header.encode()) + for number, line in enumerate(source, 1): + if not line.strip() or line.startswith("#"): + continue + try: + global_rows = [int(field) for field in line.split()] + except ValueError as exc: + raise ValueError(f"invalid trace row on line {number}") from exc + if len(global_rows) != 16 or any(row < 0 or row > 0xFFFFFFFF for row in global_rows): + raise ValueError(f"expected sixteen global u32 rows on line {number}") + tokens += 1 + local = [row - args.part_start for row in global_rows + if args.part_start <= row < args.part_start + args.part_rows] + if local: + text = " ".join(map(str, local)) + "\n" + output.write(text) + output_hash.update(text.encode()) + batches += 1 + accesses += len(local) + print(json.dumps({ + "tokens": tokens, "batches": batches, "row_accesses": accesses, + "part_start": args.part_start, "part_rows": args.part_rows, + "input_sha256": hashlib.sha256(args.trace.read_bytes()).hexdigest(), + "output_sha256": output_hash.hexdigest(), + })) + except BaseException: + args.output.unlink(missing_ok=True) + raise + + +if __name__ == "__main__": + main() diff --git a/scripts/strata-agent-profile.py b/scripts/strata-agent-profile.py new file mode 100644 index 00000000..4115fd98 --- /dev/null +++ b/scripts/strata-agent-profile.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Start one private Strata A/B agent profile on the Linux GPU host. + +This is an offline experiment controller. It keeps its config in tmpfs, never +prints credentials, and does not modify the ordinary Strata service on port 8080. +""" + +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import urllib.request + + +ROOT = Path('/home/para/.cache/strata-next/agent-profiles') +STATE = ROOT / 'state.json' +CONFIG = Path('/dev/shm/strata-next-agent-profile.json') +SOURCE = Path('/home/para/inference/strata/strata-iq3_s.json') +SERVER = Path('/home/para/inference/strata/serve/server.py') +PYTHON = Path('/home/para/inference/strata/.venv/bin/python') +ARCHIVE = Path('/mnt/microcrm-flash-preflight/microcrm-flash-next-experiment/strata-next/qwen-iq3-s-l2-v4.kar') +KEYLESS_ROUTING = Path('/home/para/.cache/strata-next/keyless-feasibility/query-routing-distilled-wide.bin') +EXES = { + 'strata-next-v-only': Path('/home/para/.cache/strata-next/keyless-runtime-20261003/build/strata'), + 'strata-next-baseline': Path('/home/para/.cache/strata-next/engine-fork-f80a3e0/build/strata'), + 'strata-next-kar-ple': Path('/home/para/.cache/strata-next/engine-kar-ple-build/strata'), + 'strata-next-kar-ple-gpu': Path('/home/para/.cache/strata-next/engine-ple-gpu-36e512a/build/strata'), +} +HOST = '192.168.1.196' +PORT = 18081 +URL = f'http://{HOST}:{PORT}' + + +def pid_alive(pid): + try: + os.kill(pid, 0) + return True + except (ProcessLookupError, PermissionError): + return False + + +def state(): + if not STATE.exists(): + return None + value = json.loads(STATE.read_text()) + if not pid_alive(value['pid']): + return None + return value + + +def health(): + try: + with urllib.request.urlopen(URL + '/health', timeout=3) as response: + value = json.load(response) + return {'ready': bool(value.get('loaded') and value.get('max_context') == 262144), + 'context': value.get('max_context')} + except (OSError, ValueError): + return {'ready': False} + + +def status(): + current = state() + observed = health() if current else {'ready': False} + return {'profile': current['profile'] if current else None, + 'pid': current['pid'] if current else None, + 'kv_mode': 'without-key' if current and current['profile'] == 'strata-next-v-only' else 'with-key', + 'quality_gate': (json.loads(Path(str(KEYLESS_ROUTING) + '.json').read_text()).get('quality_gate', 'not_run') + if current and current['profile'] == 'strata-next-v-only' else None), **observed} + + +def unload(current): + if health()['ready']: + key = json.loads(CONFIG.read_text())['api_key'] + request = urllib.request.Request(URL + '/unload', data=b'{}', method='POST', + headers={'Authorization': 'Bearer ' + key, + 'Content-Type': 'application/json'}) + with urllib.request.urlopen(request, timeout=180) as response: + if response.status != 200: + raise RuntimeError('model unload failed') + try: + os.killpg(current['pid'], signal.SIGTERM) + except ProcessLookupError: + pass + for _ in range(30): + if not pid_alive(current['pid']): + break + time.sleep(1) + if pid_alive(current['pid']): + os.killpg(current['pid'], signal.SIGKILL) + STATE.unlink(missing_ok=True) + CONFIG.unlink(missing_ok=True) + + +def ensure_idle(): + current = state() + if not current: + return + config = json.loads(CONFIG.read_text()) + key = config['api_key'] + request = urllib.request.Request(URL + '/slots', + headers={'Authorization': 'Bearer ' + key}) + try: + with urllib.request.urlopen(request, timeout=5) as response: + slots = json.load(response) + except (OSError, ValueError): + raise RuntimeError('experimental server is loading or its state is unknown') + if not slots or any(slot.get('is_processing', True) for slot in slots): + raise RuntimeError('experimental server is processing a request') + + +def prepare(profile): + if profile not in EXES: + raise ValueError('unknown experiment profile') + routing_identity = None + if profile == 'strata-next-v-only': + routing_report = Path(str(KEYLESS_ROUTING) + '.json') + if not KEYLESS_ROUTING.is_file() or not routing_report.is_file(): + raise FileNotFoundError(KEYLESS_ROUTING) + routing_identity = json.loads(routing_report.read_text())['routing_sha256'] + for path in (SOURCE, SERVER, PYTHON, EXES[profile]): + if not path.is_file(): + raise FileNotFoundError(path) + if profile in {'strata-next-kar-ple', 'strata-next-kar-ple-gpu'} and not ARCHIVE.is_file(): + raise FileNotFoundError(ARCHIVE) + environment = dict(os.environ) + environment.pop('STRATA_KEYLESS_ROUTING', None) + environment.pop('STRATA_KEYLESS_TRACE', None) + if profile == 'strata-next-v-only': + if not KEYLESS_ROUTING.is_file(): + raise FileNotFoundError(KEYLESS_ROUTING) + environment['STRATA_KEYLESS_ROUTING'] = str(KEYLESS_ROUTING) + raw = json.loads(SOURCE.read_text()) + args = raw['args'] + if (args[args.index('--max-context') + 1] != '262144' or + args[args.index('--kv') + 1] != 'int8' or + args[args.index('--kv-resident') + 1] != '32768'): + raise RuntimeError('expected 1x256K with INT8 K+V and 32768 resident cells') + if ('--ple-kar' in args or '--ple-kar-gpu-cache-mib' in args or + '--control-vector-scaled' in args): + raise RuntimeError('source config contains another experiment') + cfg = dict(raw) + cfg['exe'] = str(EXES[profile]) + cfg['args'] = list(args) + if profile in {'strata-next-kar-ple', 'strata-next-kar-ple-gpu'}: + cfg['args'] += ['--ple-kar', str(ARCHIVE), '--ple-kar-level', '2'] + if profile == 'strata-next-kar-ple-gpu': + cfg['args'] += ['--ple-kar-gpu-cache-mib', '64'] + return cfg, environment, routing_identity + + +def start(profile): + cfg, environment, routing_identity = prepare(profile) + current = state() + if current and current['profile'] == profile and current.get('routing_identity') == routing_identity: + return {'started': False, **status()} + if current: + ensure_idle() + unload(current) + elif STATE.exists(): + STATE.unlink() + CONFIG.unlink(missing_ok=True) + if health()['ready']: + raise RuntimeError('port is already occupied by an untracked server') + used = subprocess.check_output( + ['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], + text=True).strip() + if int(used.splitlines()[0]) > 1024: + raise RuntimeError('GPU is already occupied by another workload') + ROOT.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(ROOT, 0o700) + cfg['log'] = str(ROOT / f'{profile}-engine.log') + fd = os.open(CONFIG, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, 'w') as file: + json.dump(cfg, file) + log = ROOT / f'{profile}-server.log' + with log.open('ab') as output: + proc = subprocess.Popen([str(PYTHON), '-u', str(SERVER), '--engine', 'strata', + '--config', str(CONFIG), '--host', HOST, '--port', str(PORT)], + cwd=cfg['cwd'], stdout=output, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True, env=environment) + STATE.write_text(json.dumps({'pid': proc.pid, 'profile': profile, 'routing_identity': routing_identity}) + '\n') + os.chmod(STATE, 0o600) + except BaseException: + CONFIG.unlink(missing_ok=True) + raise + return {'started': True, **status()} + + +def main(): + action = sys.argv[1] + payload = json.load(sys.stdin) + if action == 'status': + result = status() + elif action == 'prepare': + prepare(payload['profile']) + result = {'prepared': True} + elif action == 'start': + result = start(payload['profile']) + elif action == 'stop': + current = state() + if current: + ensure_idle() + unload(current) + result = {'stopped': bool(current)} + else: + raise ValueError('unknown action') + print(json.dumps(result)) + + +if __name__ == '__main__': + try: + main() + except Exception as exc: + print(type(exc).__name__ + ': ' + str(exc), file=sys.stderr) + sys.exit(1) diff --git a/scripts/strata-dual-256-experiment.py b/scripts/strata-dual-256-experiment.py new file mode 100644 index 00000000..ae99b222 --- /dev/null +++ b/scripts/strata-dual-256-experiment.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Private Linux GPU experiment: two independent 256K Strata workers. + +This offline controller reuses a local source configuration and its credential. +It never prints or persists the credential outside private tmpfs config files. +The normal Strata service on port 8080 is not touched. +""" + +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import urllib.request + + +SOURCE = Path('/home/para/inference/strata/strata-iq3_s.json') +ENGINE = Path('/home/para/.cache/strata-next/engine-fork-f80a3e0/build/strata') +PYTHON = Path('/home/para/inference/strata/.venv/bin/python') +SERVER = Path('/home/para/inference/strata/serve/server.py') +ROOT = Path('/home/para/.cache/strata-next/dual-256') +STATE = ROOT / 'state.json' +HOST = '192.168.1.196' +PORTS = (18081, 18082) +EXPERT_SLOTS = 2000 + + +def config_path(port): + return Path(f'/dev/shm/strata-next-dual-{port}.json') + + +def process_is_ours(pid, port): + try: + command = Path(f'/proc/{pid}/cmdline').read_bytes().replace(b'\0', b' ').decode() + except (OSError, ValueError): + return False + return str(SERVER) in command and str(config_path(port)) in command + + +def health(port): + try: + with urllib.request.urlopen(f'http://{HOST}:{port}/health', timeout=2) as response: + value = json.load(response) + return bool(value.get('loaded') and value.get('max_context') == 262144) + except (OSError, ValueError): + return False + + +def gpu_mib(): + output = subprocess.check_output( + ['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True) + return int(output.splitlines()[0].strip()) + + +def read_state(): + return json.loads(STATE.read_text()) if STATE.exists() else {'workers': []} + + +def status(): + workers = read_state()['workers'] + return {'workers': [{'port': w['port'], 'pid': w['pid'], + 'alive': process_is_ours(w['pid'], w['port']), + 'ready': health(w['port'])} for w in workers], + 'gpu_used_mib': gpu_mib()} + + +def stop(): + workers = read_state()['workers'] + for w in workers: + port, pid = w['port'], w['pid'] + cfg = config_path(port) + if process_is_ours(pid, port) and cfg.exists() and health(port): + key = json.loads(cfg.read_text())['api_key'] + request = urllib.request.Request( + f'http://{HOST}:{port}/unload', data=b'{}', method='POST', + headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'}) + try: + urllib.request.urlopen(request, timeout=90).close() + except OSError: + pass + if process_is_ours(pid, port): + os.killpg(pid, signal.SIGTERM) + for _ in range(30): + if not any(process_is_ours(w['pid'], w['port']) for w in workers): + break + time.sleep(1) + for w in workers: + if process_is_ours(w['pid'], w['port']): + os.killpg(w['pid'], signal.SIGKILL) + config_path(w['port']).unlink(missing_ok=True) + STATE.unlink(missing_ok=True) + return status() + + +def start(): + if STATE.exists(): + raise RuntimeError('dual experiment already has state; inspect or stop it first') + if gpu_mib() > 1024: + raise RuntimeError('GPU is occupied; dual experiment requires an idle GPU') + if any(health(port) for port in PORTS): + raise RuntimeError('an experiment port already has a ready server') + for path in (SOURCE, ENGINE, PYTHON, SERVER): + if not path.is_file(): + raise FileNotFoundError(path) + source = json.loads(SOURCE.read_text()) + args = source['args'] + if (args[args.index('--max-context') + 1] != '262144' or + args[args.index('--kv') + 1] != 'int8' or + args[args.index('--kv-resident') + 1] != '32768' or + args[args.index('--expert-cache') + 1] != 'auto'): + raise RuntimeError('source config differs from the measured 1x256K INT8 baseline') + ROOT.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(ROOT, 0o700) + workers = [] + try: + for port in PORTS: + cfg = dict(source) + cfg['exe'] = str(ENGINE) + cfg['port'] = port + cfg['args'] = list(args) + cfg['args'][cfg['args'].index('--expert-cache') + 1] = str(EXPERT_SLOTS) + cfg['log'] = str(ROOT / f'engine-{port}.log') + path = config_path(port) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as file: + json.dump(cfg, file) + with (ROOT / f'server-{port}.log').open('ab') as output: + proc = subprocess.Popen( + [str(PYTHON), '-u', str(SERVER), '--engine', 'strata', + '--config', str(path), '--host', HOST, '--port', str(port)], + cwd=source['cwd'], stdout=output, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True) + workers.append({'port': port, 'pid': proc.pid}) + STATE.write_text(json.dumps({'workers': workers}) + '\n') + os.chmod(STATE, 0o600) + deadline = time.monotonic() + 360 + grace = time.monotonic() + 5 + while time.monotonic() < deadline: + if health(port): + break + if time.monotonic() > grace and not process_is_ours(proc.pid, port): + raise RuntimeError(f'worker on {port} exited during startup') + time.sleep(3) + else: + raise TimeoutError(f'worker on {port} did not become ready') + return status() + except BaseException: + stop() + for port in PORTS: + config_path(port).unlink(missing_ok=True) + raise + + +def main(): + if len(sys.argv) != 2 or sys.argv[1] not in ('start', 'status', 'stop'): + raise SystemExit('usage: strata-dual-256-experiment.py start|status|stop') + print(json.dumps({'start': start, 'status': status, 'stop': stop}[sys.argv[1]]())) + + +if __name__ == '__main__': + main() diff --git a/scripts/strata-dual-request-proxy.py b/scripts/strata-dual-request-proxy.py new file mode 100644 index 00000000..23a8a24a --- /dev/null +++ b/scripts/strata-dual-request-proxy.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Experimental one-endpoint admission for two independent Strata workers. + +Each upstream still owns one sequence. This proxy accepts two concurrent HTTP +requests and gives each a different worker; it does not batch model kernels. +Production serving must use the Rust control plane instead. +""" + +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import hmac +import json +from pathlib import Path +import threading +import urllib.error +import urllib.request + + +class Pool: + def __init__(self, upstreams): + self.upstreams = upstreams + self.free = [True] * len(upstreams) + self.condition = threading.Condition() + + def acquire(self): + with self.condition: + self.condition.wait_for(lambda: any(self.free)) + # Serial turns stay on worker zero for prefix reuse. A concurrent + # second request goes to worker one. + index = self.free.index(True) + self.free[index] = False + return index + + def release(self, index): + with self.condition: + self.free[index] = True + self.condition.notify() + + +class Handler(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + server_version = 'StrataDualExperiment/0.1' + + def log_message(self, format, *args): + # Requests may contain private prompts and credentials. + pass + + def do_GET(self): + self.forward() + + def do_POST(self): + self.forward() + + def forward(self): + if not hmac.compare_digest(self.headers.get('Authorization', ''), + 'Bearer ' + self.server.api_key): + self.send_error(401) + return + if self.path not in ('/health', '/slots', '/v1/models', '/models', + '/v1/chat/completions', '/v1/completions'): + self.send_error(404) + return + try: + length = int(self.headers.get('Content-Length', '0')) + except ValueError: + self.send_error(400) + return + if length < 0 or length > 64 * 1024 * 1024: + self.send_error(413) + return + body = self.rfile.read(length) if length else None + index = self.server.pool.acquire() + response_started = False + try: + request = urllib.request.Request( + self.server.pool.upstreams[index] + self.path, + data=body if self.command == 'POST' else None, + method=self.command, + headers={ + 'Authorization': self.headers['Authorization'], + 'Content-Type': self.headers.get('Content-Type', 'application/json'), + 'Accept': self.headers.get('Accept', '*/*'), + }, + ) + try: + response = urllib.request.urlopen(request, timeout=900) + except urllib.error.HTTPError as error: + response = error + with response: + self.send_response(response.status) + self.send_header('Content-Type', response.headers.get('Content-Type', + 'application/json')) + self.send_header('Connection', 'close') + self.end_headers() + response_started = True + self.close_connection = True + reader = getattr(response, 'read1', response.read) + while chunk := reader(65536): + self.wfile.write(chunk) + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + pass + except (OSError, ValueError): + if not response_started: + self.send_error(502) + finally: + self.server.pool.release(index) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--host', default='127.0.0.1') + parser.add_argument('--port', type=int, default=18080) + parser.add_argument('--upstream', action='append', required=True) + parser.add_argument('--config', type=Path, required=True, + help='private Strata JSON config containing api_key') + options = parser.parse_args() + if len(options.upstream) != 2 or not 1 <= options.port <= 65535: + parser.error('exactly two --upstream values and a valid port are required') + config = json.loads(options.config.read_text()) + with ThreadingHTTPServer((options.host, options.port), Handler) as server: + server.api_key = config['api_key'] + server.pool = Pool([url.rstrip('/') for url in options.upstream]) + print(json.dumps({'host': options.host, 'port': options.port, + 'upstream_count': len(options.upstream)}), flush=True) + server.serve_forever(poll_interval=0.2) + + +if __name__ == '__main__': + main() diff --git a/scripts/strata-model-switch.py b/scripts/strata-model-switch.py new file mode 100644 index 00000000..df95ace3 --- /dev/null +++ b/scripts/strata-model-switch.py @@ -0,0 +1,479 @@ +#!/usr/bin/env python3 +"""Private Linux console controller: prepare, switch known model owner, rollback. + +No inference serving code. Existing backend helpers retain download/launch logic. +""" +import argparse +import fcntl +import http.client +import re +import stat +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import urllib.request +from urllib.parse import urlsplit + +ROOT = Path('/home/para/.cache/strata-next/model-switch') +NATIVE = Path('/home/para/.cache/strata-next/native-console-20261004') +CONTROL = Path('/home/para/inference/codex-qwen') + + +def private_bytes(path, limit): + fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as source: + info = os.fstat(source.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('deployment and key files must be private regular files owned by this user') + data = source.read(limit + 1) + if len(data) > limit: + raise ValueError('private input exceeds size limit') + return data + + +def load_deployment(path): + try: + value = json.loads(private_bytes(path, 65536)) + required = {'schema_version', 'root', 'native', 'control', 'agent_helper', + 'binary', 'config', 'cwd', 'url', 'model'} + if (not isinstance(value, dict) or set(value) - required - {'key_file'} or + not required <= set(value) or type(value['schema_version']) is not int or value['schema_version'] != 1): + raise ValueError('schema') + for key in ('root', 'native', 'control', 'agent_helper', 'binary', 'config', 'cwd', 'key_file'): + if key not in value: + continue + text = value[key] + if not isinstance(text, str) or not text or any(ord(c) < 32 or ord(c) == 127 for c in text) or not Path(text).is_absolute(): + raise ValueError('absolute paths required') + value[key] = str(Path(text).resolve()) + if value['root'] == value['native']: + raise ValueError('state directories must be distinct') + for key in ('root', 'native'): + directory = Path(value[key]) + if directory.exists(): + info = directory.stat() + if not directory.is_dir() or info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('state directories must be private and owned by this user') + if not isinstance(value['url'], str) or any(ord(c) <= 32 or ord(c) >= 127 for c in value['url']): + raise ValueError('url') + url = urlsplit(value['url']) + if (url.scheme != 'http' or url.hostname not in {'127.0.0.1','::1'} or + url.username is not None or url.password is not None or url.path or url.query or url.fragment or + url.port is None or not 1 <= url.port <= 65535): + raise ValueError('plain loopback HTTP URL with explicit port required') + if not isinstance(value['model'], str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,180}', value['model']): + raise ValueError('model') + if value.get('key_file'): + key = private_bytes(value['key_file'], 4096).decode().strip() + if not key or any(ord(c) < 33 or ord(c) > 126 for c in key): + raise ValueError('invalid private key file') + return value + except (OSError, ValueError, TypeError, KeyError): + raise RuntimeError('Invalid deployment manifest: check private file, schema, absolute paths and loopback URL') from None + + +def provision_recipe(recipe, budget): + # Native CLI resolves assets, @embedded and generated tokenizer paths itself. + try: + with subprocess.Popen([recipe['binary'], 'provision', '--config', recipe['config']], + cwd=recipe['cwd'], env={**os.environ, **recipe['env']}, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) as process: + try: + if process.wait(timeout=budget): + raise RuntimeError('Native provisioning failed; current model preserved') + except BaseException: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + raise + except (OSError, subprocess.TimeoutExpired): + raise RuntimeError('Native provisioning failed or timed out; current model preserved') from None + + +def save(path, value): + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + temporary = path.with_suffix('.tmp') + with temporary.open('w') as out: + os.chmod(temporary, 0o600) + json.dump(value, out) + os.replace(temporary, path) + + +def identity(pid): + try: + fields = Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')', 1)[1].split() + if fields[0] == 'Z': + return None + return {'pid': int(pid), 'start_ticks': fields[19], 'ppid': int(fields[1])} + except (OSError, ValueError, IndexError): + return None + + +def owned(pid, roots): + seen = set() + while pid > 1 and pid not in seen: + if pid in roots: + return True + seen.add(pid) + current = identity(pid) + if current is None: + return False + pid = current['ppid'] + return False + + +def same_process(record): + current = identity(record['pid']) + return current is not None and current['start_ticks'] == record['start_ticks'] + + +def switch(host, target, budget): + """All prerequisites/ownership checks precede unloading; tested with fake hosts.""" + host.prepare(target, budget) + previous = host.inventory() + host.check_owners(previous) + if len(previous) > 1: + raise RuntimeError('Multiple managed model owners are active; refusing an ambiguous switch') + if previous and host.matches(previous[0], target) and host.ready(target): + return host.existing_result(target) + host.journal('prepared', previous, target) + try: + for owner in previous: + host.stop(owner) + host.free_gpu() + host.journal('loading', previous, target) + result = host.launch(target) + host.wait_ready(target, budget) + host.journal('ready', previous, target) + return result + except BaseException: + host.journal('restoring', previous, target) + try: + current = host.inventory() + host.check_owners(current) + for owner in current: + if host.matches(owner, target): + host.stop(owner, failed=True) + elif not any(host.matches(owner, old['target']) for old in previous): + raise RuntimeError('Managed owner changed during switch') + for old in previous: + if not host.ready(old['target']): + host.free_gpu() + host.restore(old) + host.wait_ready(old['target'], budget) + host.journal('restored' if previous else 'failed', previous, target) + except BaseException: + host.journal('restore_failed', previous, target) + raise RuntimeError('Model switch failed and previous model could not be restored; private switch state/logs retained') from None + raise RuntimeError('Selected model failed to start; previous model restored' if previous else 'Selected model failed to start; no previous model was running') from None + + +class Host: + def __init__(self, deployment=None): + self.deployment = deployment + self.root = Path(deployment['root']) if deployment else ROOT + self.native = Path(deployment['native']) if deployment else NATIVE + self.control = Path(deployment['control']) if deployment else CONTROL + self.binary = Path(deployment['binary']) if deployment else self.native/'strata-next' + self.config = Path(deployment['config']) if deployment else self.native/'config.json' + sys.path.insert(0, str(self.control)) + import qwen_remote + import strata_remote + self.q, self.s = qwen_remote, strata_remote + spec = importlib.util.spec_from_file_location('agent_profile', deployment['agent_helper'] if deployment else '/home/para/.cache/strata-next/agent-profile.py') + self.a = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.a) + + def native_recipe(self): + path = self.root/'native-recipe.json' + state_path = self.native/'state.json' + state = json.loads(state_path.read_text()) if state_path.exists() else None + if state and same_process(state): + pid = state['pid'] + if Path(f'/proc/{pid}/exe').resolve() != self.binary.resolve(): + raise RuntimeError('Native PID does not match its recorded executable') + env = {} + for item in Path(f'/proc/{pid}/environ').read_bytes().split(b'\0'): + key, _, value = item.partition(b'=') + key = key.decode() + if key.startswith('STRATA_') or key in {'LD_LIBRARY_PATH', 'CUDA_VISIBLE_DEVICES'}: + env[key] = value.decode() + recipe = {'cwd': str(Path(f'/proc/{pid}/cwd').resolve()), 'env': env, + 'binary': str(self.binary), 'config': str(self.config)} + save(path, recipe) + elif not path.exists(): + if not self.deployment: + raise RuntimeError('Native launch recipe missing; cannot reconstruct an unrecorded runtime') + return {'binary': str(self.binary), 'config': str(self.config), + 'cwd': self.deployment['cwd'], 'env': {}} + return json.loads(path.read_text()) + + def prepare(self, target, budget): + backend = target['backend'] + if backend == 'agent': + self.a.prepare(target['profile']) + elif backend == 'native': + recipe = self.native_recipe() + if self.deployment: + provision_recipe(recipe, budget) + return + cfg = json.loads(Path(recipe['config']).read_text()) + for p in [recipe['binary'], cfg['engine']['executable']]: + if not Path(p).is_file() or not os.access(p, os.X_OK): + raise RuntimeError('Native executable missing or inaccessible') + if not Path(cfg['engine']['tokenizer_dir']).is_dir() or not Path(recipe['cwd']).is_dir(): + raise RuntimeError('Native tokenizer or working directory is missing') + elif backend == 'llama': + model = self.q.model_by_id(target['id']) + self.q.validate(model, target['layout']) + self.q.validate_cache(target.get('kvCache', 'f16')) + self.q.fetch(model) + elif backend == 'strata': + deadline = time.monotonic() + budget + observed = self.s.prepare() + while observed['stage'] != 'ready': + if str(observed['stage']).startswith('failed') or time.monotonic() >= deadline: + raise RuntimeError('Ordinary Strata preparation failed or timed out; current model preserved') + time.sleep(2) + observed = self.s.status() + cfg = json.loads((self.s.ROOT/'strata-iq3_s.json').read_text()) + args = cfg['args'] + if args[args.index('--max-context')+1] != '262144' or args[args.index('--kv')+1] != 'int8' or '--control-vector-scaled' in args: + raise RuntimeError('Unexpected ordinary Strata configuration') + for item in json.loads((self.s.STATE/'strata-artifacts.json').read_text())['files']: + p = self.s.DATA/'models'/item['path'] + receipt = json.loads(p.with_suffix('.verified.json').read_text()) + if p.stat().st_size != item['bytes'] or receipt['sha256'] != item['sha256'] or receipt['mtime_ns'] != p.stat().st_mtime_ns: + raise RuntimeError('Ordinary Strata receipt mismatch; current model preserved') + else: + raise RuntimeError('Unknown model backend') + + def unit(self, name): + p = subprocess.run(['systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID'], capture_output=True, text=True, check=True) + return dict(line.split('=', 1) for line in p.stdout.splitlines() if '=' in line) + + def inventory(self): + result = [] + if (self.native/'state.json').exists(): + state = json.loads((self.native/'state.json').read_text()) + if same_process(state): + recipe = self.native_recipe() + result.append({'target': {'backend': 'native'}, 'roots': [state['pid']], 'state': state, 'recipe': recipe}) + state = self.a.state() + if state and identity(state['pid']): + cmd = Path(f"/proc/{state['pid']}/cmdline").read_bytes().split(b'\0') + if str(self.a.SERVER).encode() not in cmd or str(self.a.CONFIG).encode() not in cmd or os.getpgid(state['pid']) != state['pid']: + raise RuntimeError('Experiment PID identity mismatch') + result.append({'target': {'backend': 'agent', 'profile': state['profile']}, 'roots': [state['pid']], + 'state': {**state, **identity(state['pid'])}}) + for backend, name in [('strata', self.s.UNIT), ('llama', self.q.SERVICE)]: + unit = self.unit(name) + if unit.get('ActiveState') not in {'inactive', 'failed'}: + roots = [int(unit.get('MainPID', 0))] + target = {'backend': backend, 'days': 7} + owner = {'target': target, 'roots': roots, 'unit': name} + if backend == 'llama': + active = self.q.read(self.q.ACTIVE) + target.update(id=active['id'], layout=active['layout'], kvCache=active.get('kvCache', 'f16')) + owner['active'] = active + container = subprocess.run(['docker', 'inspect', '--format', '{{.State.Pid}}', self.q.CONTAINER], capture_output=True, text=True) + if container.returncode == 0: + roots.append(int(container.stdout.strip())) + result.append(owner) + return result + + def check_owners(self, owners): + roots = {pid for owner in owners for pid in owner['roots'] if pid > 1} + p = subprocess.run(['nvidia-smi', '--query-compute-apps=pid', '--format=csv,noheader,nounits'], capture_output=True, text=True, check=True) + for line in p.stdout.splitlines(): + if line.strip() and not owned(int(line.strip()), roots): + raise RuntimeError('GPU belongs to an unrelated workload; it was not stopped') + + def matches(self, owner, target): + previous = owner['target'] + fields = {'native': [], 'strata': [], 'agent': ['profile'], 'llama': ['id', 'layout', 'kvCache']} + if previous['backend'] != target['backend']: + return False + return all(previous.get(k, 'f16' if k == 'kvCache' else None) == target.get(k, 'f16' if k == 'kvCache' else None) for k in fields[target['backend']]) + + def stop(self, owner, failed=False): + print('Вивантаження поточної моделі: ' + owner['target']['backend'], file=sys.stderr, flush=True) + backend = owner['target']['backend'] + if backend in {'native', 'agent'}: + record = owner['state'] + if not same_process(record): + raise RuntimeError('Managed process identity changed before stop') + if backend == 'agent': + if not failed: + self.a.ensure_idle() + self.a.unload(record) + else: + # This legacy qualified runtime has no admin drain endpoint. + # An explicit model switch authorizes its normal SIGTERM stop. + os.kill(record['pid'], signal.SIGTERM) + deadline = time.monotonic() + 35 + while same_process(record): + if time.monotonic() >= deadline: + raise RuntimeError('Native runtime did not terminate; not killing an unknown process') + time.sleep(.1) + else: + if not failed: + if backend == 'strata': + self.s.ensure_idle() + else: + self.q.ensure_idle(self.q.observation()) + subprocess.run(['sudo', '-n', 'systemctl', 'stop', owner['unit']], check=True, capture_output=True, timeout=60) + + def free_gpu(self): + deadline = time.monotonic() + 15 + while True: + try: + self.check_owners([]) + except RuntimeError: + if time.monotonic() >= deadline: + raise + time.sleep(.25) + continue + used = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used', '--format=csv,noheader,nounits'], text=True) + if int(used.splitlines()[0]) <= 1024: + return + if time.monotonic() >= deadline: + raise RuntimeError('GPU memory did not release after managed shutdown') + time.sleep(.25) + + def launch(self, target): + print('Завантаження вибраної моделі: ' + target['backend'], file=sys.stderr, flush=True) + if target['backend'] == 'agent': + return self.a.start(target['profile']) + if target['backend'] == 'llama': + return self.q.start(target) + if target['backend'] == 'strata': + return self.s.start(target) + recipe = self.native_recipe() + env = {**os.environ, **recipe['env']} + self.native.mkdir(parents=True, exist_ok=True, mode=0o700) + with (self.native/'runtime.log').open('ab') as log: + process = subprocess.Popen([recipe['binary'], 'serve', '--config', recipe['config']], + cwd=recipe['cwd'], env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) + record = identity(process.pid) + if not record: + raise RuntimeError('Native supervisor exited immediately') + try: + with open(recipe['binary'], 'rb') as binary: + record['cli_sha256'] = hashlib.file_digest(binary, 'sha256').hexdigest() + save(self.native/'state.json', record) + except BaseException: + process.terminate() + process.wait(timeout=35) + raise + return {'started': True} + + def restore(self, owner): + if owner['target']['backend'] == 'native': + save(self.root/'native-recipe.json', owner['recipe']) + if owner['target']['backend'] == 'llama': + self.q.atomic(self.q.ACTIVE, owner['active']) + subprocess.run(['sudo', '-n', 'systemctl', 'start', self.q.SERVICE], check=True, capture_output=True, timeout=30) + else: + self.launch(owner['target']) + + def native_ready(self): + url = urlsplit(self.deployment['url']) + headers = {} + if self.deployment.get('key_file'): + key = private_bytes(self.deployment['key_file'], 4096).decode().strip() + if not key or any(ord(c) < 33 or ord(c) > 126 for c in key): + return False + headers['Authorization'] = 'Bearer ' + key + conn = http.client.HTTPConnection(url.hostname, url.port, timeout=3) + try: + conn.request('GET', '/status', headers=headers) + response = conn.getresponse() + if response.status != 200: + return False + data = response.read(65537) + if len(data) > 65536: + return False + value = json.loads(data) + return (isinstance(value, dict) and value.get('service') == 'strata-control' and + value.get('model') == self.deployment['model'] and value.get('ready') is True) + finally: + conn.close() + + def ready(self, target): + try: + backend = target['backend'] + if backend == 'agent': + observed = self.a.status() + return observed['profile'] == target['profile'] and observed['ready'] + if backend == 'native' and self.deployment: + return self.native_ready() + if backend == 'native': + with urllib.request.urlopen('http://127.0.0.1:18082/status', timeout=3) as response: + value = json.load(response) + return value.get('service') == 'strata-control' and value.get('model') == 'strata-native-iq3-s' and value.get('ready') is True + models = (self.q if backend == 'llama' else self.s).api('/v1/models')['data'] + return len(models) == 1 and (backend != 'llama' or models[0]['id'] == target['id'] + '--' + target['layout'] + 'k') + except (OSError, ValueError, KeyError, RuntimeError, http.client.HTTPException): + return False + + def wait_ready(self, target, budget): + started = time.monotonic() + deadline = started + budget + next_update = started + 20 + while not self.ready(target): + if not any(self.matches(owner, target) for owner in self.inventory()) or time.monotonic() >= deadline: + raise RuntimeError('Target model failed or readiness deadline expired') + if time.monotonic() >= next_update: + print(f'Очікування готовності моделі: {int(time.monotonic() - started)} с', file=sys.stderr, flush=True) + next_update = time.monotonic() + 20 + time.sleep(1) + print('Модель готова.', file=sys.stderr, flush=True) + + def existing_result(self, target): + if target['backend'] == 'agent': + return {'started': False, **self.a.status()} + if target['backend'] == 'llama': + return {'started': False, 'key': self.q.KEY.read_text().strip(), 'state': self.q.observation()} + return {'started': False, 'preparing': False} + + def journal(self, phase, previous, target): + save(self.root/'state.json', {'phase': phase, 'previous': previous, 'target': target, 'updated_at': time.time()}) + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--deployment', type=Path, help='private schema1 host layout; does not change installed defaults') + parser.add_argument('action', choices=['start']) + args = parser.parse_args() + deployment = load_deployment(args.deployment) if args.deployment else None + root = Path(deployment['root']) if deployment else ROOT + target = json.load(sys.stdin) + budget = target.pop('waitSeconds', 3600) + if type(budget) is not int or not 1 <= budget <= 7200: + raise RuntimeError('Switch waitSeconds must be 1..7200') + if type(target.get('days', 7)) is not int or not 1 <= target.get('days', 7) <= 31: + raise RuntimeError('days must be1..31') + root.mkdir(parents=True, exist_ok=True, mode=0o700) + with (root/'switch.lock').open('a') as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise RuntimeError('Another model switch is already running') from None + result = switch(Host(deployment), target, budget) + print(json.dumps(result)) + + +if __name__ == '__main__': + try: + main() + except Exception as exc: + print(str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__ + ': switch failed; current state saved privately', file=sys.stderr) + sys.exit(1) diff --git a/scripts/test-benchmark-harness.py b/scripts/test-benchmark-harness.py new file mode 100644 index 00000000..3fa7c285 --- /dev/null +++ b/scripts/test-benchmark-harness.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Exercise paired benchmark ordering, readiness, quality and secret handling.""" + +import http.server +from importlib.machinery import SourceFileLoader +import json +import pathlib +import stat +import subprocess +import tempfile +import threading + + +TOKEN = "fixture-token-do-not-log" +HEALTH_CHECKS = 0 + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + global HEALTH_CHECKS + HEALTH_CHECKS += 1 + self.reply({"loaded": True, "max_context": 0 if HEALTH_CHECKS == 1 else 262144}) + + def do_POST(self): + if self.headers.get("Authorization") != "Bearer " + TOKEN: + self.send_error(401) + return + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if "tools" in body: + message = {"role": "assistant", "content": None, + "tool_calls": [{"function": {"name": "get_weather", + "arguments": '{"city":"Paris"}'}}]} + finish = "tool_calls" + else: + question = body["messages"][0]["content"] + message = {"role": "assistant", "content": "323" if "17 * 19" in question else "Cora"} + finish = "stop" + self.reply({"choices": [{"message": message, "finish_reason": finish}], + "usage": {"prompt_tokens": 20, "completion_tokens": 2}, + "timings": {"prompt_n": 20, "prompt_per_second": 200.0, + "predicted_n": 2, "predicted_per_second": 50.0}}) + + def reply(self, payload): + data = json.dumps(payload).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *_args): + pass + + +def main(): + root = pathlib.Path(__file__).resolve().parent.parent + benchmark = SourceFileLoader("chat_benchmark", str(root / "scripts/bench-chat-paired.py")).load_module() + quality = json.loads((root / "benchmarks/fixtures/chat/quality-v1.json").read_text()) + long_case = next(case for case in quality["cases"] if case["id"] == "long-retrieval") + prompt = benchmark.materialize_messages(long_case["messages"])[0]["content"] + assert prompt.count("filler row:") == 4400 + assert prompt.count("VALID AUDIT CODE: amber-731") == 1 + failed = [{"arm": arm, "case_id": "broken", "repeat": 0, "warmup": False, + "wall_seconds": 1.0, "http_status": 500, "response": {}, + "quality": {"passed": False}} + for arm in ("baseline", "candidate")] + assert benchmark.summarize(failed, True)["paired"]["same_normalized_output"] == 0 + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with tempfile.TemporaryDirectory() as directory: + private = pathlib.Path(directory) + config = private / "config.json" + config.write_text(json.dumps({"api_key": TOKEN})) + report = private / "report.json" + url = f"http://127.0.0.1:{server.server_port}" + subprocess.run([ + "python3", str(root / "scripts/bench-chat-paired.py"), + "--suite", str(root / "benchmarks/fixtures/chat/paired-smoke.json"), + "--baseline-url", url + "/chat", "--candidate-url", url + "/chat", + "--baseline-ready-url", url + "/health", + "--candidate-ready-url", url + "/health", + "--baseline-auth-config", str(config), + "--model", "mock", "--repeats", "1", "--output", str(report), + ], check=True, capture_output=True, text=True) + data = report.read_text() + assert TOKEN not in data + assert stat.S_IMODE(report.stat().st_mode) == 0o600 + summary = json.loads(data)["summary"] + assert summary["baseline"]["quality_passed"] == 3 + assert summary["candidate"]["quality_passed"] == 3 + assert summary["paired"]["pairs"] == 3 + assert summary["paired"]["same_normalized_output"] == 3 + assert HEALTH_CHECKS >= 3 + solo = [] + for name in ("baseline", "candidate"): + path = private / f"{name}.json" + subprocess.run([ + "python3", str(root / "scripts/bench-chat-paired.py"), + "--suite", str(root / "benchmarks/fixtures/chat/paired-smoke.json"), + "--baseline-url", url + "/chat", + "--baseline-auth-config", str(config), + "--model", "mock", "--repeats", "1", "--output", str(path), + ], check=True, capture_output=True, text=True) + solo.append(path) + compared = private / "sequential-comparison.json" + subprocess.run([ + "python3", str(root / "scripts/compare-chat-reports.py"), + str(solo[0]), str(solo[1]), "--output", str(compared), + ], check=True, capture_output=True, text=True) + assert stat.S_IMODE(compared.stat().st_mode) == 0o600 + assert TOKEN not in compared.read_text() + sequential = json.loads(compared.read_text())["summary"] + assert sequential["pairs"] == 3 + assert sequential["same_normalized_output"] == 3 + assert sequential["candidate_quality_passed"] == 3 + assert sequential["decode"]["pairs"] == 3 + assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0 + finally: + server.shutdown() + server.server_close() + print("paired benchmark harness: OK") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-cuda-bootstrap.py b/scripts/test-cuda-bootstrap.py new file mode 100644 index 00000000..8e5b21d2 --- /dev/null +++ b/scripts/test-cuda-bootstrap.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +import importlib.util +import io +import json +from pathlib import Path +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +spec=importlib.util.spec_from_file_location('bootstrap',Path(__file__).with_name('bootstrap-cuda-toolkit.py')) +m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + +class Tests(unittest.TestCase): + def test_safe_tree_and_internal_link(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo('component/lib/a');item.size=1;t.addfile(item,io.BytesIO(b'a')) + item=tarfile.TarInfo('component/lib/b');item.type=tarfile.SYMTYPE;item.linkname='a';t.addfile(item) + out=m.extract(archive,root/'out','component') + self.assertEqual((out/'lib/b').read_bytes(),b'a') + def test_bad_archive_paths_and_links(self): + for name,link in [('../escape',None),('/escape',None),('other/file',None),('component/b','../../escape')]: + with self.subTest(name=name),tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);archive=root/'test.tar.xz' + with tarfile.open(archive,'w:xz') as t: + item=tarfile.TarInfo(name) + if link:item.type=tarfile.SYMTYPE;item.linkname=link + t.addfile(item) + with self.assertRaises((ValueError,tarfile.TarError)):m.extract(archive,root/'out','component') + self.assertFalse((root/'escape').exists()) + def test_component_merge_rejects_conflict(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);a=root/'a';b=root/'b';a.mkdir();b.mkdir() + (a/'x').write_text('a');(b/'x').write_text('b') + with self.assertRaises(ValueError):m.merge(a,b) + self.assertEqual((b/'x').read_text(),'b') + def test_identical_merge_and_moving(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp);a=root/'a';b=root/'b';a.mkdir();b.mkdir() + (a/'x').write_text('a');(b/'x').write_text('a');(a/'y').write_text('y') + m.merge(a,b);self.assertEqual((b/'y').read_text(),'y');self.assertFalse((a/'y').exists()) + def test_download_mismatch_size_and_redirect(self): + for data,url,sha,limit in [(b'bad',m.BASE+'x','0'*64,4),(b'large',m.BASE+'x','0'*64,2),(b'x','https://other.invalid/x','0'*64,2)]: + with tempfile.TemporaryDirectory() as tmp: + response=io.BytesIO(data);response.url=url + with patch.object(m.urllib.request,'urlopen',return_value=response),self.assertRaises(ValueError): + m.download(m.BASE+'x',Path(tmp)/'file',sha,limit) + def test_lock_pins_match_reference(self): + lock=json.loads((Path(__file__).resolve().parents[1]/'deploy/cuda-toolkit.lock.json').read_text()) + manifest={x['component']:{'version':x['version'],'linux-x86_64':x.copy()} for x in lock['components']} + m.validate_lock(lock,manifest) + lock['components'][0]['sha256']='0'*64 + with self.assertRaises(ValueError):m.validate_lock(lock,manifest) + def test_resource_gate_before_download(self): + with patch.object(m.Path,'read_text',return_value='MemTotal: 1024 kB\n'),self.assertRaises(ValueError):m.resource_gate(Path('/tmp')) + +if __name__=='__main__':unittest.main() diff --git a/scripts/test-keyless-routing.py b/scripts/test-keyless-routing.py new file mode 100644 index 00000000..af557098 --- /dev/null +++ b/scripts/test-keyless-routing.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Independent identities for the paper's effective query projection.""" +import importlib.util +from pathlib import Path +import unittest +import numpy as np + +spec = importlib.util.spec_from_file_location("routing", Path(__file__).with_name("prepare-keyless-routing.py")) +routing = importlib.util.module_from_spec(spec) +spec.loader.exec_module(routing) + + +calibration_spec = importlib.util.spec_from_file_location("calibration", Path(__file__).with_name("calibrate-keyless-routing.py")) +calibration = importlib.util.module_from_spec(calibration_spec) +calibration_spec.loader.exec_module(calibration) + + +class FrozenRoutingCalibration(unittest.TestCase): + def test_positional_attention_gradient_against_finite_difference(self): + rng = np.random.default_rng(9023) + q, v, raw_v = rng.normal(size=(2,3,256)), rng.normal(size=(2,4,256)), rng.normal(size=(2,4,256)) + qp=np.array([31,63,95]); mask=(np.array([0,16,32,80])[None,:]<=qp[:,None])[None,:,:] + teacher=rng.normal(size=(2,3,4)); target=calibration.softmax(teacher,mask) + data=(q,qp,v,raw_v,mask,teacher,target) + matrix=rng.normal(size=(2,256,256))*.01 + loss, gradient=calibration.objective_gradient(matrix,data) + direction=rng.normal(size=matrix.shape); direction/=np.linalg.norm(direction) + epsilon=1e-4 + plus=calibration.objective_gradient(matrix+epsilon*direction,data)[0].sum() + minus=calibration.objective_gradient(matrix-epsilon*direction,data)[0].sum() + self.assertAlmostEqual(float((plus-minus)/(2*epsilon)),float(np.sum(gradient*direction)),places=7) + x=rng.normal(size=(2,3,256)) + np.testing.assert_allclose(calibration.rotate(calibration.rotate(x,qp),qp,inverse=True),x,rtol=2e-7,atol=2e-7) + + +class QueryRouting(unittest.TestCase): + def test_square_value_projection_preserves_logits(self): + rng = np.random.default_rng(4102) + q, k, v = (rng.normal(size=(7, 7)) for _ in range(3)) + x, y = rng.normal(size=(19, 7)), rng.normal(size=(13, 7)) + a, report = routing.query_routing(q, k, v) + teacher = (x @ q.T) @ (y @ k.T).T + candidate = ((x @ q.T) @ a) @ (y @ v.T).T + np.testing.assert_allclose(candidate, teacher, rtol=1e-10, atol=1e-10) + self.assertLess(report["score_weight_relative_l2"], 1e-11) + + def test_rectangular_equivalence_under_subspace_condition(self): + rng = np.random.default_rng(319) + q, v = rng.normal(size=(4, 17)), rng.normal(size=(4, 17)) + k = rng.normal(size=(4, 4)) @ v + a, report = routing.query_routing(q, k, v) + np.testing.assert_allclose(q.T @ a @ v, q.T @ k, rtol=1e-11, atol=1e-11) + self.assertLess(report["key_subspace_relative_l2"], 1e-11) + + def test_out_of_subspace_residual_is_reported(self): + rng = np.random.default_rng(521) + q, k, v = (rng.normal(size=(4, 17)) for _ in range(3)) + a, report = routing.query_routing(q, k, v) + direct = np.linalg.norm(q.T @ k - q.T @ a @ v) / np.linalg.norm(q.T @ k) + self.assertAlmostEqual(report["score_weight_relative_l2"], direct, places=12) + self.assertGreater(report["score_weight_relative_l2"], .1) + # The residual must be orthogonal to every value-space basis vector. + np.testing.assert_allclose((k - a @ v) @ v.T, 0, atol=1e-11) + + def test_rank_deficiency_is_explicit(self): + v = np.array([[1., 0., 0.], [2., 0., 0.]]) + _, report = routing.query_routing(v, v, v) + self.assertEqual(report["value_rank"], 1) + with self.assertRaises(ValueError): + routing.query_routing(v, v, np.zeros_like(v)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-linux-package.py b/scripts/test-linux-package.py new file mode 100644 index 00000000..13e931a7 --- /dev/null +++ b/scripts/test-linux-package.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Fault boundaries for offline package publication; real assembly runs in Linux CI.""" +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('package', Path(__file__).with_name('build-linux-package.py')) +pkg = importlib.util.module_from_spec(spec) +spec.loader.exec_module(pkg) + + +class PackageTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def test_snapshot_digest_exact_and_bad_pin(self): + source = self.root / 'engine' + payload = b'fixture' * 20000 + source.write_bytes(payload) + digest = hashlib.sha256(payload).hexdigest() + out = self.root / 'copy' + self.assertEqual(pkg.snapshot(source, out, digest), len(payload)) + self.assertEqual(out.read_bytes(), payload) + self.assertEqual(out.stat().st_mode & 0o777, 0o700) + for pin in ['0' * 64, 'bad']: + with self.assertRaises(ValueError): + pkg.snapshot(source, self.root / pin, pin) + + def test_snapshot_rejects_oversize_and_nonregular_without_block(self): + source = self.root / 'engine' + source.write_bytes(b'over limit') + with patch.object(pkg, 'LIMIT', 4), self.assertRaisesRegex(ValueError, 'limit'): + pkg.snapshot(source, self.root / 'copy', hashlib.sha256(source.read_bytes()).hexdigest()) + fifo = self.root / 'pipe' + os.mkfifo(fifo) + with self.assertRaisesRegex(ValueError, 'regular'): + pkg.snapshot(fifo, self.root / 'fifo-copy', '0' * 64) + + def test_source_pin_and_dirty_tree(self): + subprocess.run(['git', 'init', '-q', self.root], check=True) + (self.root / 'source').write_text('initial') + subprocess.run(['git', '-C', self.root, 'add', '.'], check=True) + subprocess.run(['git', '-C', self.root, '-c', 'user.email=fixture@example.invalid', '-c', + 'user.name=Fixture', 'commit', '-qm', 'fixture'], check=True) + revision = pkg.run(['git', '-C', self.root, 'rev-parse', 'HEAD']) + pkg.source_check(self.root, revision) + untracked = self.root / 'untracked-source' + untracked.write_text('not in revision') + with self.assertRaisesRegex(ValueError, 'clean'): + pkg.source_check(self.root, revision) + untracked.unlink() + for wrong in ['bad', '0' * 40]: + with self.assertRaises(ValueError): + pkg.source_check(self.root, wrong) + (self.root / 'source').write_text('changed') + with self.assertRaisesRegex(ValueError, 'clean'): + pkg.source_check(self.root, revision) + + def test_lock_excludes_other_builder_and_symlink(self): + path = self.root / 'lock' + with pkg.lock(path), self.assertRaises(BlockingIOError): + with pkg.lock(path): + self.fail('second writer acquired lock') + alias = self.root / 'alias' + alias.symlink_to(path) + with self.assertRaises(OSError): + with pkg.lock(alias): + self.fail('symlink lock accepted') + + @unittest.skipUnless(sys.platform == 'linux', 'Linux atomic publication') + def test_atomic_publication_never_replaces_existing_directory(self): + staged, output = self.root / 'stage', self.root / 'out' + staged.mkdir() + (staged / 'sentinel').write_text('new') + output.mkdir() + with self.assertRaises(FileExistsError): + pkg.publish(staged, output) + self.assertEqual(list(output.iterdir()), []) + output.rmdir() + pkg.publish(staged, output) + self.assertFalse(staged.exists()) + self.assertEqual((output / 'sentinel').read_text(), 'new') + + def test_outer_elf_rejects_loader_or_shared_library(self): + for outputs in [('INTERP', ''), ('', '(NEEDED)')]: + with patch.object(pkg, 'run', side_effect=outputs), self.assertRaises(ValueError): + pkg.static_outer(Path('fixture')) + with patch.object(pkg, 'run', side_effect=['static headers', 'no dynamic section']): + self.assertIn('program_headers', pkg.static_outer(Path('fixture'))) + + def test_failed_build_cleans_stage_and_does_not_publish(self): + from types import SimpleNamespace + engine = self.root / 'engine' + engine.write_bytes(b'fixture') + output = self.root / 'final' + args = SimpleNamespace(engine=engine, sha256=pkg.sha256(engine), revision='a' * 40, + output=output, cargo_target_dir=self.root / 'target', cpu_fixture=True) + with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'cargo')): + with self.assertRaises(subprocess.CalledProcessError): + pkg.assemble(args) + self.assertFalse(output.exists()) + self.assertFalse(list(self.root.glob('.final.stage-*'))) + output.mkdir() + (output / 'old').write_text('keep') + with patch.object(pkg.platform, 'system', return_value='Linux'), patch.object(pkg.platform, 'machine', return_value='x86_64'), patch.object(pkg, 'source_check'), patch.object(pkg.subprocess, 'run') as build: + with self.assertRaisesRegex(ValueError, 'already exists'): + pkg.assemble(args) + build.assert_not_called() + self.assertEqual((output / 'old').read_text(), 'keep') + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-live-responses-replay.py b/scripts/test-live-responses-replay.py new file mode 100644 index 00000000..4e4cfbae --- /dev/null +++ b/scripts/test-live-responses-replay.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Actual isolated native HTTP replay plus independent corrupted-evidence tests.""" +import copy +import http.client +import http.server +import importlib.util +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time + + +def load(name, filename): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def main(): + replay = load('replay', 'replay-live-responses.py') + fixture = load('fixture', 'smoke-worker-cancel.py') + binary = str(Path(sys.argv[1]).resolve()) + script = Path(__file__).with_name('replay-live-responses.py') + with tempfile.TemporaryDirectory(prefix='strata-live-replay-') as directory: + root = Path(directory) + fixture.tokenizer(root) + key = 'fixture-private-key-not-in-captures-0001' + (root / 'key').write_text(key) + (root / 'key').chmod(0o600) + tool = '\n\n\nvalue\n\n\n' + for name, text in [('one', tool), ('two', 'CONFIRMED-731')]: + data = text.encode() + (root / name).write_text(''.join(f'T {b}\n' for b in data) + f'DONE {len(data)} 7 1.0 2.0 stop\n') + engine = root / 'engine.sh' + engine.write_text('''#!/bin/sh +printf 'READY 262144 stop\\n' +n=0 +while IFS= read -r line; do + case "$line" in + 'GEN '*) n=$((n+1)); printf x >> "$2/generations" + if [ $((n % 2)) = 1 ]; then cat "$2/one"; else cat "$2/two"; fi ;; + QUIT) exit 0 ;; + esac +done +''') + engine.chmod(0o700) + with socket.socket() as probe: + probe.bind(('127.0.0.1', 0)) + port = probe.getsockname()[1] + origin = f'http://127.0.0.1:{port}' + env = {'PATH': os.defpath, 'STRATA_BIND': f'127.0.0.1:{port}', + 'STRATA_MODEL_ID': 'fixture', 'STRATA_API_KEY_FILE': str(root / 'key'), + 'STRATA_ENGINE_EXE': str(engine), 'STRATA_ENGINE_ARGS_JSON': json.dumps([str(root)]), + 'STRATA_TOKENIZER_DIR': str(root), 'STRATA_MAX_WORKER_RESTARTS': '0'} + function = {'type': 'function', 'name': 'lookup', 'parameters': {'type': 'object', + 'properties': {'key': {'type': 'string'}}, 'required': ['key'], 'additionalProperties': False}} + base = {'model': 'fixture', 'max_output_tokens': 1024, 'reasoning': {'effort': 'none'}, 'tools': [function]} + episode = {'schema': 1, 'sanitized': True, 'provenance': {'class': 'synthetic CPU worker'}, 'steps': [ + {'request': {**base, 'input': 'Use lookup', 'tool_choice': {'type': 'function', 'name': 'lookup'}}, + 'expect': [{'type': 'function_call', 'name': 'lookup', 'arguments': {'key': 'value'}}]}, + {'request': {**base, 'input': 'Confirm the tool result', 'tool_choice': 'none'}, + 'tool_results': ['CONFIRMED-731'], 'expect': [{'type': 'text', 'text': 'CONFIRMED-731'}]}]} + suite = root / 'episode.json' + suite.write_text(json.dumps(episode)) + with tempfile.TemporaryFile() as logs: + process = subprocess.Popen([binary, 'serve'], env=env, stdout=logs, stderr=logs, start_new_session=True) + try: + deadline = time.monotonic() + 10 + while True: + try: + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=.5) + conn.request('GET', '/ready', headers={'Authorization': 'Bearer ' + key}) + ready = conn.getresponse().status == 200 + conn.close() + if ready: + break + except OSError: + pass + if process.poll() is not None or time.monotonic() >= deadline: + logs.seek(0) + raise AssertionError(logs.read().decode()) + time.sleep(.02) + out = root / 'evidence' + command = [sys.executable, str(script), '--endpoint', origin, '--fixture', str(suite), + '--output', str(out), '--key-file', str(root / 'key'), '--timeout', '8'] + result = subprocess.run(command, capture_output=True, text=True, timeout=45) + assert result.returncode == 0, (result.stderr, (out / 'report.json').read_text() if out.exists() else '') + report = json.loads((out / 'report.json').read_text()) + assert report['protocol_passed'] and len(report['arms']) == 2 + assert (root / 'generations').read_bytes() == b'xxxx' + for path in out.iterdir(): + assert path.stat().st_mode & 0o777 == 0o600 + assert key not in path.read_text() + assert out.stat().st_mode & 0o777 == 0o700 + continuation = json.loads((out / 'sse-001-request.json').read_text())['input'] + call = next(x for x in continuation if x.get('type') == 'function_call') + result_item = next(x for x in continuation if x.get('type') == 'function_call_output') + assert call['call_id'] == result_item['call_id'] and result_item['output'] == 'CONFIRMED-731' + assert subprocess.run(command, capture_output=True, timeout=10).returncode != 0 + assert (root / 'generations').read_bytes() == b'xxxx' + cases = 0 + for filename in ['sse-000-body.txt', 'sse-001-body.txt']: + body = (out / filename).read_text() + replay.verify_sse(body) + with_comments = ': keep-alive\n\n' + body.replace('\n\n', '\n\n: keep-alive\n\n') + assert replay.verify_sse(with_comments) == replay.verify_sse(body) + events = [json.loads(line[5:]) for line in body.splitlines() if line.startswith('data:')] + + def reject(changed): + nonlocal cases + for i, e in enumerate(changed): + e['sequence_number'] = i + wire = ''.join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in changed) + try: + replay.verify_sse(wire) + except (replay.Invalid, KeyError, TypeError, IndexError, ValueError): + cases += 1 + else: + raise AssertionError('corrupt stream passed') + + reject(copy.deepcopy(events[:-1])) + reject(copy.deepcopy(events + events[-1:])) + reject(copy.deepcopy(events[:2] + events[1:])) + reject([copy.deepcopy(e) for e in events if e['type'] != 'response.output_item.done']) + reject([copy.deepcopy(e) for e in events if not e['type'].endswith('_arguments.done') and e['type'] != 'response.output_text.done']) + bad = copy.deepcopy(events) + next(e for e in bad if e['type'].endswith('.delta'))['delta'] += 'tampered' + reject(bad) + bad = copy.deepcopy(events) + next(e for e in bad if e['type'] == 'response.output_item.added')['item']['id'] = 'wrong' + reject(bad) + bad = copy.deepcopy(events) + bad[-1]['response']['usage']['total_tokens'] += 1 + reject(bad) + bad = copy.deepcopy(events) + bad[-1]['response']['status'] = 'failed' + reject(bad) + if filename == 'sse-000-body.txt': + bad = copy.deepcopy(events) + next(e for e in bad if e['type'] == 'response.output_item.added')['item']['arguments'] = 'unverified' + reject(bad) + bad = copy.deepcopy(events) + bad[-1]['response']['output'][0]['arguments'] = 'not JSON' + reject(bad) + bad = copy.deepcopy(events) + next(e for e in bad if e['type'] == 'response.output_item.added')['item']['name'] = 'other_tool' + reject(bad) + command[command.index('--output') + 1] = str(root / 'unauthorized') + at = command.index('--key-file') + del command[at:at + 2] + assert subprocess.run(command, capture_output=True, timeout=10).returncode != 0 + assert (root / 'generations').read_bytes() == b'xxxx' + assert not json.loads((root / 'unauthorized/report.json').read_text())['protocol_passed'] + finally: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + class Drip(http.server.BaseHTTPRequestHandler): + def do_GET(self): + try: + if self.path in ('/large', '/secret'): + body = b'x' * (replay.LIMIT + 1) if self.path == '/large' else key.encode() + self.send_response(200) + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + return + for _ in range(100): + self.wfile.write(b'H') + self.wfile.flush() + time.sleep(.05) + except OSError: + pass + def log_message(self, *_): + pass + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Drip) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + for path in ('/large', '/secret'): + try: + replay.exchange(f'http://127.0.0.1:{server.server_port}', key, path, None, 5) + except replay.Invalid: + pass + else: + raise AssertionError('oversize body or credential reflection passed') + started = time.monotonic() + try: + replay.exchange(f'http://127.0.0.1:{server.server_port}', '', '/ready', None, .4) + except replay.Invalid: + assert time.monotonic() - started < 2 + else: + raise AssertionError('drip-fed headers escaped wall deadline') + finally: + server.shutdown() + server.server_close() + thread.join() + print(f'Live Responses replay: actual native CPU tool continuation in JSON/SSE, {cases} corrupt streams, private evidence, auth, no-overwrite and wall deadline passed') + + +if __name__ == '__main__': + main() diff --git a/scripts/test-model-switch.py b/scripts/test-model-switch.py new file mode 100644 index 00000000..787cea1a --- /dev/null +++ b/scripts/test-model-switch.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Transaction tests without touching GPUs, processes, or user services.""" +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import time +from types import SimpleNamespace +from pathlib import Path +import unittest +from unittest.mock import Mock, patch + +spec = importlib.util.spec_from_file_location('switcher', Path(__file__).with_name('strata-model-switch.py')) +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +OLD = {'backend': 'native'} +NEW = {'backend': 'agent', 'profile': 'kar'} + +class Fake: + def __init__(self, old=True): + self.current = [{'target': OLD}] if old else [] + self.events = [] + self.fail = None + self.unrelated = False + def prepare(self, target, budget): + self.events.append('prepare') + if self.fail == 'prepare': raise RuntimeError('missing file') + def inventory(self): return list(self.current) + def check_owners(self, owners): + self.events.append('owners') + if self.unrelated: raise RuntimeError('unrelated') + def matches(self, owner, target): return owner['target'] == target + def ready(self, target): return any(self.matches(o, target) for o in self.current) + def existing_result(self, target): return {'started': False} + def journal(self, phase, previous, target): self.events.append(phase) + def stop(self, owner, failed=False): + self.events.append('cleanup' if failed else 'stop') + self.current.remove(owner) + def free_gpu(self): self.events.append('free') + def launch(self, target): + self.events.append('launch') + self.current = [{'target': target}] + return {'started': True} + def wait_ready(self, target, budget): + self.events.append('wait') + if target == NEW and self.fail in {'ready', 'restore'}: raise RuntimeError('load failed') + def restore(self, owner): + self.events.append('restore') + if self.fail == 'restore': raise RuntimeError('restore failed') + self.current = [owner] + +class Tests(unittest.TestCase): + def test_success_order(self): + h = Fake(); self.assertEqual(m.switch(h, NEW, 10), {'started': True}) + self.assertEqual(h.events, ['prepare','owners','prepared','stop','free','loading','launch','wait','ready']) + def test_preflight_failure_keeps_old(self): + h=Fake(); h.fail='prepare' + with self.assertRaisesRegex(RuntimeError, 'missing'): m.switch(h, NEW, 10) + self.assertTrue(h.ready(OLD)); self.assertEqual(h.events,['prepare']) + def test_unrelated_owner_untouched(self): + h=Fake(); h.unrelated=True + with self.assertRaisesRegex(RuntimeError, 'unrelated'): m.switch(h, NEW, 10) + self.assertTrue(h.ready(OLD)); self.assertNotIn('stop',h.events) + def test_ambiguous_owners_untouched(self): + h=Fake();h.current.append({'target': NEW}) + with self.assertRaisesRegex(RuntimeError,'Multiple'):m.switch(h,NEW,10) + self.assertNotIn('stop',h.events) + def test_idempotent(self): + h=Fake();self.assertFalse(m.switch(h,OLD,10)['started']);self.assertNotIn('stop',h.events) + def test_failed_start_rolls_back(self): + h=Fake();h.fail='ready' + with self.assertRaisesRegex(RuntimeError,'previous model restored'):m.switch(h,NEW,10) + self.assertTrue(h.ready(OLD));self.assertIn('cleanup',h.events);self.assertEqual(h.events[-1],'restored') + def test_failed_restore_reported(self): + h=Fake();h.fail='restore' + with self.assertRaisesRegex(RuntimeError,'could not be restored'):m.switch(h,NEW,10) + self.assertEqual(h.events[-1],'restore_failed') + def test_failure_without_previous_cleans_target(self): + h=Fake(False);h.fail='ready' + with self.assertRaisesRegex(RuntimeError,'no previous'):m.switch(h,NEW,10) + self.assertEqual(h.current,[]) + def test_pid_reuse_and_ancestry(self): + processes={20:dict(pid=20,start_ticks='2',ppid=10),10:dict(pid=10,start_ticks='1',ppid=1)} + with patch.object(m,'identity',side_effect=processes.get): + self.assertTrue(m.owned(20,{10}));self.assertFalse(m.owned(20,{30})) + self.assertFalse(m.same_process(dict(pid=20,start_ticks='1'))) + self.assertTrue(m.same_process(dict(pid=20,start_ticks='2'))) + +class PreparationTests(unittest.TestCase): + def test_agent_preflight_failure_never_unloads(self): + spec=importlib.util.spec_from_file_location('agent',Path(__file__).with_name('strata-agent-profile.py')) + agent=importlib.util.module_from_spec(spec);spec.loader.exec_module(agent) + with patch.object(agent,'prepare',side_effect=FileNotFoundError('missing')), patch.object(agent,'state') as state, patch.object(agent,'unload') as unload: + with self.assertRaises(FileNotFoundError):agent.start('strata-next-kar-ple-gpu') + state.assert_not_called();unload.assert_not_called() + + def test_gpu_release_waits_without_killing(self): + host=object.__new__(m.Host) + with patch.object(host,'check_owners',side_effect=[RuntimeError('still exiting'),None]) as owners, patch.object(m.time,'sleep'), patch.object(m.subprocess,'check_output',return_value='500\n'): + host.free_gpu() + self.assertEqual(owners.call_count,2) + +class DeploymentTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='strata-controller-') + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name).resolve() + self.value = dict(schema_version=1, **{key: str(self.root/key) for key in + ('root','native','control','agent_helper','binary','config','cwd')}, + url='http://127.0.0.1:12345', model='fixture') + self.path = self.root/'deployment.json' + + def write(self, value=None): + self.path.write_text(json.dumps(value or self.value)); self.path.chmod(0o600) + return self.path + + def host(self, explicit=True): + host = object.__new__(m.Host) + host.deployment = self.value if explicit else None + for key in ('root','native','control','binary','config'): + setattr(host, key, Path(self.value[key])) + return host + + def test_private_manifest_and_no_mutations(self): + self.assertEqual(m.load_deployment(self.write()), self.value) + self.assertFalse(Path(self.value['root']).exists()) + self.path.chmod(0o644) + with self.assertRaisesRegex(RuntimeError,'Invalid deployment'): m.load_deployment(self.path) + self.path.chmod(0o600) + alias = self.root/'alias'; alias.symlink_to(self.path) + with self.assertRaises(RuntimeError): m.load_deployment(alias) + + def test_schema_paths_loopback_and_private_directories(self): + changes = [{'schema_version':True}, {'unexpected':'secret'}, {'binary':'relative'}, + {'url':'http://server:1234'}, {'url':'http://127.0.0.1:1234/path'}, + {'url':'http://user:secret@127.0.0.1:1234'}, {'url':'http://127.0.0.1'}, + {'model':'bad name'}, {'root':self.value['native']}] + for change in changes: + with self.subTest(change=change), self.assertRaises(RuntimeError) as caught: + m.load_deployment(self.write({**self.value, **change})) + self.assertNotIn('secret', str(caught.exception)) + directory=Path(self.value['root']); directory.mkdir(mode=0o755); directory.chmod(0o755) + with self.assertRaises(RuntimeError): m.load_deployment(self.write()) + directory.chmod(0o700) + self.assertEqual(m.load_deployment(self.write())['root'], str(directory)) + + def test_cold_start_and_cached_recipe(self): + host=self.host() + recipe=host.native_recipe() + self.assertEqual(recipe, {key:self.value[key] for key in ('binary','config','cwd')} | {'env':{}}) + self.assertFalse(host.root.exists()) + cached={**recipe,'env':{'STRATA_FIXTURE':'1'}} + m.save(host.root/'native-recipe.json',cached) + self.assertEqual(host.native_recipe(),cached) + with patch.object(m,'provision_recipe') as provision: + host.prepare(OLD,11) + provision.assert_called_once_with(cached,11) + + def test_key_rejected_before_lifecycle(self): + key=self.root/'key';self.value['key_file']=str(key) + for content,mode in [('fixture-token',0o644),('bad\nkey',0o600),('',0o600)]: + key.write_text(content);key.chmod(mode) + with self.assertRaises(RuntimeError):m.load_deployment(self.write()) + self.assertFalse(Path(self.value['root']).exists()) + key.write_text('fixture-token');key.chmod(0o600) + self.assertEqual(m.load_deployment(self.write())['key_file'],str(key)) + + def test_legacy_missing_recipe_is_not_invented(self): + with self.assertRaisesRegex(RuntimeError,'recipe missing'):self.host(False).native_recipe() + + def test_literal_provision_invocation_and_suppressed_failure(self): + host=self.host(); host.binary=Path(sys.executable) + cwd=Path(self.value['cwd']); cwd.mkdir() + script=cwd/'provision' + script.write_text("import json,os,sys; json.dump([sys.argv[1:], os.environ['STRATA_FIXTURE']],open('seen','w'))") + recipe={'binary':sys.executable,'config':'literal $HOME `x` path','cwd':str(cwd),'env':{'STRATA_FIXTURE':'yes'}} + m.provision_recipe(recipe,5) + self.assertEqual(json.loads((cwd/'seen').read_text()),[['--config',recipe['config']],'yes']) + script.write_text("import sys; print('private secret',file=sys.stderr); sys.exit(7)") + with self.assertRaisesRegex(RuntimeError,'current model preserved') as caught:m.provision_recipe(recipe,5) + self.assertNotIn('secret',str(caught.exception)) + + def test_provision_timeout_reaps_child(self): + cwd=Path(self.value['cwd']);cwd.mkdir() + (cwd/'provision').write_text("import os,time; open('pid','w').write(str(os.getpid())); time.sleep(60)") + recipe={'binary':sys.executable,'config':'unused','cwd':str(cwd),'env':{}} + started=time.monotonic() + with self.assertRaisesRegex(RuntimeError,'timed out'):m.provision_recipe(recipe,.5) + self.assertLess(time.monotonic()-started,3) + with self.assertRaises(ProcessLookupError):os.kill(int((cwd/'pid').read_text()),0) + + def test_readiness_identity_auth_and_no_redirect(self): + host=self.host(); key=self.root/'key';key.write_text('fixture-token');key.chmod(0o600) + self.value['key_file']=str(key) + response=Mock(status=200) + response.read.return_value=json.dumps(dict(service='strata-control',model='fixture',ready=True)).encode() + conn=Mock();conn.getresponse.return_value=response + with patch.object(m.http.client,'HTTPConnection',return_value=conn): + self.assertTrue(host.ready(OLD)) + conn.request.assert_called_with('GET','/status',headers={'Authorization':'Bearer fixture-token'}) + response.status=302;self.assertFalse(host.ready(OLD)) + response.status=200;response.read.return_value=b'{}';self.assertFalse(host.ready(OLD)) + conn.getresponse.side_effect=m.http.client.BadStatusLine('invalid');self.assertFalse(host.ready(OLD)) + self.assertEqual(conn.close.call_count,4) + + def test_ordinary_strata_recipe_unchanged(self): + host=self.host() + cfg=self.root/'strata-iq3_s.json' + cfg.write_text(json.dumps({'args':['--max-context','262144','--kv','int8']})) + (self.root/'strata-artifacts.json').write_text(json.dumps({'files':[]})) + host.s=SimpleNamespace(ROOT=self.root,STATE=self.root,DATA=self.root,prepare=lambda:{'stage':'ready'}) + # Existing service command remains delegated; no configurable path may rewrite helper ROOT. + with patch.object(m.subprocess,'run',return_value=SimpleNamespace(returncode=0)), patch.object(m.subprocess,'Popen'): + try: host.prepare({'backend':'strata'},1) + except (KeyError,AttributeError) as error: self.fail(str(error)) + +if __name__ == '__main__': unittest.main() diff --git a/scripts/test-native-api.py b/scripts/test-native-api.py new file mode 100644 index 00000000..a9fb7910 --- /dev/null +++ b/scripts/test-native-api.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Native controller behavior checks; no GPU or user endpoint is contacted.""" +import contextlib +import importlib.util +import io +import json +import os +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import patch + +import qwen_native_api as client + + +def load(name): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + '.py')) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +installer = load('install-qwen-native-api') +service_installer = load('install-qwen-native-service') +TARGET = {'backend': 'strata-native', 'url': 'http://127.0.0.1:18084'} + + +def state(draining=False, jobs=0): + return dict(draining=draining, drained=draining and jobs == 0, + requests_in_flight=0, generation_jobs=jobs, worker='ready') + + +class ControlTests(unittest.TestCase): + def test_wait_ready_retries_connections_and_startup_without_mutation(self): + now, calls = [0], [] + replies = [None, 'starting', 'restarting', 'ready'] + token = 'fixture-only-readiness-token' + def transport(url, method, path, key, *, timeout): + calls.append((method, path, key, timeout)) + worker = replies.pop(0) + if worker is None: + raise client.NativeConnectionError('offline') + return {'service': 'strata-control', 'ready': worker == 'ready', 'worker': worker} + result = client.control('wait-ready', dict(TARGET, key_file='private'), lambda _: token, + wait=1, transport=transport, clock=lambda: now[0], + sleep=lambda seconds: now.__setitem__(0, now[0] + seconds)) + self.assertTrue(result['runtime']['ready']) + self.assertFalse(result['connection_changed']) + self.assertEqual(calls, [('GET', '/status', token, n) for n in [1, .75, .5, .25]]) + + def test_wait_ready_single_check_and_deadline_includes_initial_request(self): + ready = {'service': 'strata-control', 'ready': True, 'worker': 'ready'} + self.assertEqual(client.control('wait-ready', TARGET, None, + transport=lambda *a, **k: ready)['runtime'], ready) + for response in [dict(ready, ready=False), None]: + calls = [] + def transport(*args, **kwargs): + calls.append(args) + if response is None: + raise client.NativeConnectionError('offline') + return response + with self.assertRaisesRegex(RuntimeError, 'not ready'): + client.control('wait-ready', TARGET, None, transport=transport) + self.assertEqual(len(calls), 1) + for late_ready in [False, True]: + now, calls = [0], [] + def transport(*args, **kwargs): + calls.append(kwargs['timeout']) + now[0] += 1 if late_ready else .4 + return dict(ready, ready=late_ready) + with self.assertRaisesRegex(RuntimeError, 'timed out'): + client.control('wait-ready', TARGET, None, wait=1, transport=transport, + clock=lambda: now[0], sleep=lambda s: now.__setitem__(0, now[0] + s)) + self.assertEqual(calls, [1] if late_ready else [1, .35]) + + def test_wait_ready_rejects_terminal_and_invalid_status_without_retry(self): + for worker in ['failed', 'stopping', 'unconfigured', 'unknown', None, [], {}]: + for ready in [False, True]: + calls = [] + def transport(*args, **kwargs): + calls.append(args) + return {'service': 'strata-control', 'ready': ready, 'worker': worker} + with self.assertRaises(RuntimeError): + client.control('wait-ready', TARGET, None, wait=5, transport=transport) + self.assertEqual(len(calls), 1) + for bad in [{'service': 'other', 'ready': True}, {'service': 'strata-control', 'ready': 1}]: + with self.assertRaisesRegex(RuntimeError, 'not a native'): + client.control('wait-ready', TARGET, None, wait=1, transport=lambda *a, **k: bad) + calls = [] + def rejected(*args, **kwargs): + calls.append(args) + raise RuntimeError('HTTP authentication or JSON rejection') + with self.assertRaisesRegex(RuntimeError, 'rejection'): + client.control('wait-ready', TARGET, None, wait=1, transport=rejected) + self.assertEqual(len(calls), 1) + + def test_identity_precedes_mutation_and_ready_false_allows_resume(self): + calls = [] + def transport(url, method, path, token): + calls.append((method, path)) + return {'service': 'strata-control', 'ready': False} if path == '/status' else state() + result = client.control('resume', TARGET, None, transport=transport) + self.assertFalse(result['connection_changed']) + self.assertEqual(calls, [('GET', '/status'), ('POST', '/admin/resume')]) + calls.clear() + def wrong(*args): + calls.append(args[2]) + return {'service': 'other', 'ready': True} + with self.assertRaisesRegex(RuntimeError, 'not a native'): + client.control('drain', TARGET, None, transport=wrong) + self.assertEqual(calls, ['/status']) + + def test_invalid_target_and_wait_never_send_or_read_key(self): + def unexpected(*args, **kwargs): + self.fail('Invalid input reached I/O') + for url in ['https://127.0.0.1', 'http://remote', 'http://user@localhost', + 'http://127.0.0.1/path', 'http://localhost?q=x', + 'http://127.0.0.1:0', 'http://127.0.0.1:65536', 'http://localhost\n']: + with self.subTest(url=url), self.assertRaises(ValueError): + client.control('drain', dict(TARGET, url=url, key_file='private'), unexpected, transport=unexpected) + for wait in [-1, float('nan'), float('inf'), 3601]: + for action in ['drain', 'wait-ready']: + with self.assertRaises(ValueError): + client.control(action, TARGET, unexpected, wait=wait, transport=unexpected) + with self.assertRaises(ValueError): + client.control('metrics', TARGET, unexpected, wait=1, transport=unexpected) + with self.assertRaises(ValueError): + client.control('drain', dict(TARGET, backend='strata'), unexpected, transport=unexpected) + self.assertEqual(client.endpoint('http://localhost:99'), ('127.0.0.1', 99)) + self.assertEqual(client.endpoint('http://[::1]:99'), ('::1', 99)) + + def test_wait_completion_timeout_and_concurrent_resume(self): + for ending in ['complete', 'timeout', 'resume']: + with self.subTest(ending=ending): + calls = [] + now = [0] + def sleep(seconds): + now[0] += seconds + def transport(url, method, path, token, **kwargs): + calls.append((method, path)) + if path == '/status': + return {'service': 'strata-control', 'ready': True} + if path == '/admin/drain' or ending == 'timeout': + return state(True, 1) + return state(ending == 'complete') + def run(): + return client.control('drain', TARGET, None, wait=1, transport=transport, + sleep=sleep, clock=lambda: now[0]) + if ending == 'complete': + self.assertTrue(run()['runtime']['drained']) + else: + with self.assertRaisesRegex(RuntimeError, 'timed out' if ending == 'timeout' else 'resumed concurrently'): + run() + self.assertEqual([path for method, path in calls if method == 'POST'], ['/admin/drain']) + + def test_rejects_inconsistent_lifecycle_and_metrics(self): + for invalid in [dict(state(), drained=True), dict(state(True), generation_jobs=1), + dict(state(True), worker='starting'), dict(state(), generation_jobs=True)]: + with self.assertRaises(RuntimeError): + client.lifecycle(invalid) + with self.assertRaisesRegex(RuntimeError, 'metrics'): + client.control('metrics', TARGET, None, transport=lambda u, m, p, t: + {'service': 'strata-control', 'ready': True} if p == '/status' else {'schema_version': 2}) + + def test_cli_auth_is_not_inherited_for_url_overrides(self): + def unexpected(*args): + self.fail('Connection or key should not be read') + for argv in [['status', '--url', TARGET['url']], ['status', '--no-auth'], + ['drain', '--key-file', 'private']]: + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + client.main(argv, connection=unexpected, read_key=unexpected) + with patch.object(client, 'control', return_value={}) as control, contextlib.redirect_stdout(io.StringIO()): + client.main(['status', '--url', TARGET['url'], '--no-auth'], connection=unexpected, read_key=unexpected) + self.assertIsNone(control.call_args.args[1]['key_file']) + client.main(['metrics'], connection=lambda: dict(TARGET, key_file='selected'), read_key=unexpected) + self.assertEqual(control.call_args.args[1]['key_file'], 'selected') + client.main(['wait-ready', '--wait', '12', '--url', TARGET['url'], '--no-auth'], + connection=unexpected, read_key=unexpected) + self.assertEqual(control.call_args.args[0], 'wait-ready') + self.assertEqual(control.call_args.kwargs['wait'], 12) + + +class HttpTests(unittest.TestCase): + def test_wait_ready_over_authenticated_http_and_connection_classification(self): + seen = [] + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get('Authorization'))) + ready = len(seen) > 1 + body = json.dumps({'service': 'strata-control', 'ready': ready, + 'worker': 'ready' if ready else 'starting'}).encode() + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + def log_message(self, *_): + pass + server = HTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + target = dict(TARGET, url=f'http://127.0.0.1:{server.server_port}', key_file='private') + try: + result = client.control('wait-ready', target, lambda _: 'fixture-key', wait=2) + self.assertTrue(result['runtime']['ready']) + self.assertEqual(seen, [('/status', 'Bearer fixture-key')] * 2) + self.assertNotIn('fixture-key', json.dumps(result)) + finally: + server.shutdown() + server.server_close() + thread.join() + with patch.object(client.http.client.HTTPConnection, 'request', side_effect=ConnectionRefusedError): + with self.assertRaises(client.NativeConnectionError): + client.request(target['url'], 'GET', '/status', 'fixture-key') + + def test_direct_auth_bounded_json_no_redirect_or_secret_echo(self): + token = 'fixture-private-' + 'x' * 32 + reply = [200, 'application/json', b'{"ok":true}'] + seen = [] + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + seen.append((self.path, self.headers.get('Authorization'))) + self.send_response(reply[0]) + self.send_header('Content-Type', reply[1]) + self.send_header('Content-Length', str(len(reply[2]))) + self.send_header('Location', '/redirect-must-not-be-followed') + self.end_headers() + self.wfile.write(reply[2]) + def log_message(self, *_): + pass + server = HTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + url = f'http://127.0.0.1:{server.server_port}' + try: + with patch.dict(os.environ, {'http_proxy': 'http://127.0.0.1:1', 'HTTP_PROXY': 'http://127.0.0.1:1'}): + self.assertEqual(client.request(url, 'GET', '/status', token), {'ok': True}) + self.assertEqual(seen, [('/status', 'Bearer ' + token)]) + for response in [(302, 'application/json', b'{}'), (401, 'application/json', token.encode()), + (200, 'text/plain', b'{}'), (200, 'application/json', b'x' * (client.LIMIT + 1)), + (200, 'application/json', b'{"x":NaN}'), (200, 'application/json', b'[]'), + (200, 'application/json', json.dumps({'echo': token}).encode()), + (200, 'application/json', ('{"echo":"' + ''.join(f'\\u{ord(c):04x}' for c in token) + '"}').encode())]: + reply[:] = response + count = len(seen) + with self.assertRaises(RuntimeError) as error: + client.request(url, 'GET', '/status', token) + self.assertNotIn(token, str(error.exception)) + self.assertEqual(len(seen), count + 1) + finally: + server.shutdown() + server.server_close() + thread.join() + + +class InstallerTests(unittest.TestCase): + SOURCE = '''import argparse, sys +HOST = 'fixture' +def connection(): return {} +def native_key(target): return '' +def ctl_main(): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest='command', required=True) + sub.add_parser('status') +# Strata Next native Responses integration v1 +# Strata Next native bearer file integration v1 +''' + + def test_install_coexists_both_orders_is_idempotent_and_preserves_connection(self): + for order in [(installer, service_installer), (service_installer, installer)]: + with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()): + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + connection = root / 'connection.json' + connection.write_text('{"unchanged":true}') + for item in order: + item.install(launcher) + first = launcher.read_bytes() + installer.install(launcher) + service_installer.install(launcher) + self.assertEqual(launcher.read_bytes(), first) + self.assertEqual(connection.read_text(), '{"unchanged":true}') + self.assertEqual(len(list(root.glob('*.before-native-api-*'))), 1) + self.assertEqual((root / 'qwen_native_api.py').stat().st_mode & 0o777, 0o600) + self.assertEqual(first.count(b"sys.argv[1] == 'native-api'"), 1) + self.assertEqual(first.count(b"sys.argv[1] == 'native-service'"), 1) + + def test_unrelated_helper_and_missing_anchor_are_preserved(self): + with self.assertRaises(RuntimeError): + installer.patched(self.SOURCE.replace('def ctl_main():', 'def other():')) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + (root / 'qwen_native_api.py').write_text('unrelated') + with self.assertRaises(RuntimeError): + installer.install(launcher) + self.assertEqual(launcher.read_text(), self.SOURCE) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-native-launcher-auth.py b/scripts/test-native-launcher-auth.py new file mode 100644 index 00000000..f432c723 --- /dev/null +++ b/scripts/test-native-launcher-auth.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Check an installed native launcher's key-file transport without launching an agent.""" +import importlib.util +import json +import os +from pathlib import Path +import secrets +import subprocess +import sys +import tempfile +from unittest.mock import patch + + +def main(): + path = Path(sys.argv[1]).resolve() + spec = importlib.util.spec_from_file_location('native_launcher_fixture', path) + launcher = importlib.util.module_from_spec(spec) + spec.loader.exec_module(launcher) + with tempfile.TemporaryDirectory(prefix='strata-launcher-auth-') as directory: + root = Path(directory) + key = root / 'key with spaces' + token = secrets.token_urlsafe(32) + key.write_text(token + '\n') + key.chmod(0o600) + target = {'backend': 'strata-native', 'url': 'http://127.0.0.1:18084', 'key_file': str(key)} + launcher.validate_connection(target) + assert launcher.connection_key(target) == token + key.chmod(0o644) + try: + launcher.connection_key(target) + raise AssertionError('insecure key accepted') + except RuntimeError: + pass + key.chmod(0o600) + state = {'backend': 'strata-native', 'model': 'fixture', 'context': 262144, 'parallel': 1} + captured = {} + + class ExecCaptured(BaseException): + pass + + def capture(binary, command, env): + captured.update(binary=binary, command=command, env=env) + raise ExecCaptured() + + with patch.object(launcher, 'connection', return_value=target), \ + patch.object(launcher, 'discover', return_value=state), \ + patch.object(launcher, 'configure', return_value=({'reasoning': 'none'}, 229376, root/'catalog.json')), \ + patch.object(launcher.shutil, 'which', return_value='/bin/echo'), \ + patch.object(launcher.os, 'execvpe', side_effect=capture), \ + patch.object(launcher.sys, 'argv', ['qwen-codex', 'exec', 'fixture']): + try: + launcher.launch_main() + raise AssertionError('native exec not reached') + except ExecCaptured: + pass + serialized = json.dumps(captured) + assert token not in serialized, 'key leaked into argv or environment' + command = captured['command'] + settings = [command[i+1] for i, arg in enumerate(command[:-1]) if arg == '--config'] + helper = json.loads(next(s.split('=', 1)[1] for s in settings if s.startswith('model_providers.qwen_native.auth.command='))) + args = json.loads(next(s.split('=', 1)[1] for s in settings if s.startswith('model_providers.qwen_native.auth.args='))) + assert helper == '/bin/cat' and args == [str(key.resolve())] + assert subprocess.check_output([helper, *args], text=True).strip() == token + assert not list(root.glob('*.json')), 'intercepted launcher unexpectedly wrote config' + print('Installed launcher auth passed: private key validation, token-free argv/environment and exact auth helper output') + + +if __name__ == '__main__': + main() diff --git a/scripts/test-native-menu.py b/scripts/test-native-menu.py new file mode 100644 index 00000000..838252c7 --- /dev/null +++ b/scripts/test-native-menu.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Sanitized picker fixture; no remote calls or user profile access.""" +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import os +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch +import qwen_native_profile as native_profile + +spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-menu.py')) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) +SOURCE = '''import json +from pathlib import Path +# Strata Next native bearer file integration v1 +STRATA_MODEL = dict(id='old', backend='strata') +STRATA_AGENT_MODELS = [dict(id='kar', backend='strata-agent')] +def registry(): return [dict(id='first')] +def start_strata(args): + strata_remote('start', {'days': args.days}) + strata_remote('start', {'days': args.days}) +def remote(action, payload=None, stream=False, helper='/fixture/remote'): + proc = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', HOST, + 'python3', helper, action], input=json.dumps(payload or {})) + return proc +def normal(args, kv_cache): + if not 0 <= args.wait_seconds <= 7200: raise RuntimeError('wait-seconds must be 0..7200') + return dict(days=args.days, kvCache=kv_cache) +def start_strata_agent(args, model): + observed = strata_agent_remote('start', {'profile': model['id']}) + return observed +def list_models(): + for model in [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS]: + if model.get('backend') == 'strata': modes = '1x256 · KV int8 · окремий рушій Strata' + print(model['id']) +def select_model(value): + models = [*registry(), STRATA_MODEL, *STRATA_AGENT_MODELS] + return next(m for m in models if m['id'] == value) +def dispatch(args, model): + if args.command == 'start': + if model.get('backend') == 'strata-agent': return start_strata_agent(args, model) + elif args.command == 'fetch': + if model.get('backend') == 'strata-agent': + return +''' + + +def args(**values): + return SimpleNamespace(**dict(dict(command='start', layout=None, kv_cache=None, kv_mode='with-key', wait_seconds=60, days=7), **values)) + + +class MenuTests(unittest.TestCase): + def setUp(self): + socket_patch = patch('socket.socket') + self.socket = socket_patch.start() + self.socket.return_value.__enter__.return_value.connect_ex.return_value = 0 + self.addCleanup(socket_patch.stop) + def module(self): + result = {} + exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), result) + state = dict(backend='strata-native', model='strata-native-iq3-s', context=262144, parallel=1) + result.update(PROFILE=Path('/fixture'), validate_connection=Mock(), discover=Mock(return_value=state), + configure=Mock(), atomic=Mock(), strata_agent_remote=Mock(), + HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent', + subprocess=Mock(), remote=Mock()) + return result + + def test_append_preserves_choices_and_switches_native(self): + m = self.module() + with contextlib.redirect_stdout(io.StringIO()) as out: + m['list_models']() + self.assertEqual(out.getvalue().splitlines(), ['first', 'old', 'kar', 'strata-native']) + with contextlib.redirect_stdout(io.StringIO()): + m['dispatch'](args(), m['select_model']('strata-native')) + target = m['discover'].call_args.args[0] + self.assertEqual(target['backend'], 'strata-native') + self.assertEqual(target['url'], 'http://127.0.0.1:18084') + self.assertFalse(target['managed']) + m['configure'].assert_called_once() + self.assertEqual(json.loads(m['atomic'].call_args.args[1]), target) + m['strata_agent_remote'].assert_not_called() + m['remote'].assert_called_once_with('start', {'backend': 'native', 'waitSeconds': 60}, stream=True, helper=m['STRATA_SWITCH_HELPER']) + + def test_failure_and_incompatible_options_do_not_write_profile(self): + for changes in [dict(layout='2x256'), dict(kv_cache='f16'), dict(kv_mode='without-key')]: + m = self.module() + with self.assertRaises(RuntimeError): + m['start_strata_native'](args(**changes)) + m['discover'].assert_not_called() + m['atomic'].assert_not_called() + for result in [OSError('offline'), RuntimeError('not ready'), {'model': 'other'}]: + m = self.module() + if isinstance(result, Exception): + m['discover'].side_effect = result + else: + m['discover'].return_value = result + with self.assertRaises(RuntimeError): + m['start_strata_native'](args()) + m['configure'].assert_not_called() + m['atomic'].assert_not_called() + + def test_all_managed_start_calls_route_through_switcher(self): + m = {} + exec(compile(installer.patched(SOURCE), 'fixture', 'exec'), m) + m.update(HOST='fixture', REMOTE='/fixture/remote', STRATA_AGENT_HELPER='/fixture/agent', subprocess=Mock()) + for helper, backend in [('/fixture/remote', 'llama'), ('/fixture/agent', 'agent'), ('/home/para/inference/codex-qwen/strata_remote.py', 'strata')]: + m['remote']('start', {'id': 'test'}, helper=helper) + call = m['subprocess'].run.call_args + self.assertEqual(call.args[0][-2], m['STRATA_SWITCH_HELPER']) + self.assertEqual(json.loads(call.kwargs['input'])['backend'], backend) + m['remote']('status', helper='/fixture/remote') + self.assertEqual(m['subprocess'].run.call_args.args[0][-2], '/fixture/remote') + + def test_switch_failure_does_not_write_profile(self): + m = self.module();m['remote'].side_effect=RuntimeError('rollback') + with self.assertRaisesRegex(RuntimeError,'rollback'):m['start_strata_native'](args()) + m['atomic'].assert_not_called();m['configure'].assert_not_called() + + def test_installer_backup_idempotence_and_anchor_fail_closed(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root/'qwen_local.py' + path.write_text(SOURCE) + connection = root/'connection.json' + connection.write_text('{"unchanged":true}') + self.assertTrue(installer.install(path)) + first = path.read_bytes() + self.assertFalse(installer.install(path)) + self.assertEqual(path.read_bytes(), first) + self.assertEqual(connection.read_text(), '{"unchanged":true}') + backups = list(root.glob('*.before-native-picker-*')) + self.assertEqual(len(backups), 1) + self.assertEqual(backups[0].read_text(), SOURCE) + self.assertEqual(backups[0].stat().st_mode & 0o777, 0o600) + self.assertEqual((root/'qwen_native_profile.py').stat().st_mode & 0o777, 0o600) + with self.assertRaises(RuntimeError): + installer.patched(SOURCE.replace('def start_strata(args):', 'def changed(args):')) + + def test_v1_upgrade_and_unrelated_helper(self): + # Build a genuine v1 fixture by suppressing only the new upgrade stage. + with patch.object(installer, 'profile_patch', side_effect=lambda s: s): + old = installer.patched(SOURCE) + upgraded = installer.patched(old) + self.assertIn(installer.PROFILE_MARKER, upgraded) + self.assertEqual(installer.patched(upgraded), upgraded) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory)/'qwen_local.py'; path.write_text(old) + helper = path.with_name('qwen_native_profile.py'); helper.write_text('unrelated') + with self.assertRaises(RuntimeError): installer.install(path) + self.assertEqual(path.read_text(), old) + self.assertEqual(helper.read_text(), 'unrelated') + + def test_explicit_ready_profile_never_uses_remote_or_tunnel(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + manifest = root/'native-picker.json' + manifest.write_text(json.dumps(dict(schema_version=1, mode='attach', + url='http://127.0.0.1:19123', model='fixture-native', key_file='/private/key'))) + manifest.chmod(0o600) + m=self.module();m['PROFILE']=root + m['discover'].return_value=dict(backend='strata-native', model='fixture-native', context=262144, parallel=1) + with contextlib.redirect_stdout(io.StringIO()):m['start_strata_native'](args()) + m['remote'].assert_not_called();m['subprocess'].run.assert_not_called() + target=json.loads(m['atomic'].call_args.args[1]) + self.assertEqual(target['url'],'http://127.0.0.1:19123') + self.assertEqual(target['key_file'],'/private/key') + for changes in [dict(model='wrong'),dict(context=524288),dict(parallel=2),dict(parallel=True),dict(backend='strata')]: + m['atomic'].reset_mock();m['configure'].reset_mock() + m['discover'].return_value=dict(dict(backend='strata-native',model='fixture-native',context=262144,parallel=1),**changes) + with self.assertRaises(RuntimeError):m['start_strata_native'](args()) + m['atomic'].assert_not_called();m['configure'].assert_not_called();m['remote'].assert_not_called() + manifest.write_text('{}') + with self.assertRaises(RuntimeError):m['start_strata_native'](args()) + m['remote'].assert_not_called() + + +class ProfileTests(unittest.TestCase): + def test_invalid_files_and_schema_fail_closed(self): + good=dict(schema_version=1,mode='attach',url='http://127.0.0.1:19123',model='fixture',key_file=None) + with tempfile.TemporaryDirectory() as directory: + p=Path(directory)/'native-picker.json' + self.assertIsNone(native_profile.load(p)) + for change in [dict(schema_version=True),dict(mode='start'),dict(extra=1),dict(model='a\nb'), + dict(key_file='relative'),dict(url='http://remote:80'),dict(url='http://user@localhost:80'), + dict(url='http://localhost:0'),dict(url='http://localhost:80/'),dict(url='http://localhost:80?q=x'), + dict(url='http://localhost:80\n'),dict(url='http://localhost:99999')]: + p.write_text(json.dumps(dict(good,**change)));p.chmod(0o600) + with self.subTest(change=change),self.assertRaises(RuntimeError):native_profile.load(p) + for raw in ['[]','{'+'"x":0,'*100+'"x":1}',json.dumps(good)+' '*16385]: + p.write_text(raw) + with self.assertRaises(RuntimeError):native_profile.load(p) + p.write_text(json.dumps(good));p.chmod(0o644) + with self.assertRaises(RuntimeError):native_profile.load(p) + p.unlink();p.symlink_to(Path(directory)/'missing') + with self.assertRaises(RuntimeError):native_profile.load(p) + p.unlink();os.mkfifo(p,0o600) + with self.assertRaises(RuntimeError):native_profile.load(p) + + def test_offline_and_key_errors_do_not_commit(self): + with tempfile.TemporaryDirectory() as directory: + root=Path(directory);p=root/'native-picker.json' + p.write_text(json.dumps(dict(schema_version=1,mode='attach',url='http://localhost:19123',model='fixture',key_file=None))) + p.chmod(0o600) + for validate,discover in [(Mock(side_effect=RuntimeError('key invalid')),Mock()), + (Mock(),Mock(side_effect=OSError('offline')))]: + configure,atomic=Mock(),Mock() + with self.assertRaises(RuntimeError):native_profile.attach(root,validate=validate,discover=discover,configure=configure,atomic=atomic) + configure.assert_not_called();atomic.assert_not_called() + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-native-service.py b/scripts/test-native-service.py new file mode 100644 index 00000000..00c70981 --- /dev/null +++ b/scripts/test-native-service.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Behavior checks for opt-in native service control; never contact a real host.""" +import importlib.util +import contextlib +import io +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import qwen_native_service as client + +spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-service.py')) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + + +class FakeHost: + def __init__(self): + self.active = False + self.calls = [] + self.loaded = True + + def __call__(self, host, command): + self.calls.append((host, command)) + if command[0] == 'journalctl': + return 'fixture log\n' + action = command[2] + if action == 'show': + return ('LoadState=' + ('loaded' if self.loaded else 'not-found') + '\n' + 'ActiveState=' + ('active' if self.active else 'inactive') + '\n' + 'SubState=' + ('running' if self.active else 'dead') + '\n' + 'MainPID=' + ('123' if self.active else '0') + '\nResult=success\n' + 'Environment=must-not-be-returned\n') + if action in {'start', 'stop'}: + self.active = action == 'start' + return '' + raise AssertionError(command) + + +class ControlTests(unittest.TestCase): + def test_idempotent_start_stop_and_readiness_is_not_inferred(self): + host = FakeHost() + def call(action): + return client.control(action, 'rnr5090', 'strata-next-test.service', runner=host) + self.assertFalse(call('status')['changed']) + self.assertTrue(call('start')['changed']) + again = call('start') + self.assertFalse(again['changed']) + self.assertEqual(again['model_readiness'], 'not_checked') + self.assertFalse(again['connection_changed']) + self.assertNotIn('Environment', again['process']) + self.assertTrue(call('stop')['changed']) + self.assertFalse(call('stop')['changed']) + mutations = [args for _, args in host.calls if args[2] in {'start', 'stop'}] + self.assertEqual([args[2] for args in mutations], ['start', 'stop']) + self.assertTrue(all(args[-2:] == ['--', 'strata-next-test.service'] for args in mutations)) + + def test_rejected_selectors_never_reach_ssh(self): + host = FakeHost() + for bad in ['-oProxyCommand=x', 'host;id', 'host\nother', 'user@host', 'host name']: + with self.assertRaises(ValueError): + client.control('start', bad, 'strata-next.service', runner=host) + for bad in ['sshd.service', 'strata-next.service;id', '../strata-next.service', 'strata-next@a.service']: + with self.assertRaises(ValueError): + client.control('stop', 'rnr5090', bad, runner=host) + self.assertEqual(host.calls, []) + + def test_missing_service_is_not_created_or_started(self): + host = FakeHost() + host.loaded = False + with self.assertRaisesRegex(RuntimeError, 'provision'): + client.control('start', 'rnr5090', 'strata-next.service', runner=host) + self.assertEqual(len(host.calls), 1) + self.assertEqual(host.calls[0][1][2], 'show') + + def test_invalid_status_fails_closed(self): + with self.assertRaisesRegex(RuntimeError, 'invalid'): + client.control('start', 'rnr5090', 'strata-next.service', + runner=lambda *_: 'LoadState=loaded\nActiveState=active\nMainPID=oops') + + def test_logs_are_scoped_and_bounded(self): + host = FakeHost() + self.assertEqual(client.control('logs', 'rnr5090', 'strata-next-test.service', runner=host), 'fixture log\n') + self.assertEqual(host.calls[-1][1], ['journalctl', '--user', '--unit=strata-next-test.service', + '--lines=100', '--no-pager', '--output=short-iso']) + + +class InstallerTests(unittest.TestCase): + SOURCE = '''import argparse, sys +HOST = 'fixture' +def ctl_main(): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest='command', required=True) + sub.add_parser('status') +# Strata Next native Responses integration v1 +''' + + def test_install_reinstall_backup_and_no_profile_write(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + connection = root / 'connection.json' + connection.write_text('{"untouched":true}') + installer.install(launcher) + first = launcher.read_bytes() + installer.install(launcher) + self.assertEqual(launcher.read_bytes(), first) + self.assertEqual(connection.read_text(), '{"untouched":true}') + backups = list(root.glob('qwen_local.py.before-native-service-*')) + self.assertEqual(len(backups), 1) + self.assertEqual(backups[0].read_text(), self.SOURCE) + self.assertTrue((root / 'qwen_native_service.py').is_file()) + + def test_changed_launcher_or_unrelated_helper_is_preserved(self): + with self.assertRaises(RuntimeError): + installer.patched(self.SOURCE.replace('def ctl_main():', 'def different():')) + with self.assertRaises(RuntimeError): + installer.patched('unrelated launcher') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + launcher = root / 'qwen_local.py' + launcher.write_text(self.SOURCE) + (root / 'qwen_native_service.py').write_text('unrelated helper') + with self.assertRaises(RuntimeError): + installer.install(launcher) + self.assertEqual(launcher.read_text(), self.SOURCE) + + +class PreflightTests(unittest.TestCase): + REPORT = {'schema_version': 1, 'configuration_valid': True, 'platform': 'linux', + 'bind': '127.0.0.1:18082', 'model': 'fixture', 'authentication_enabled': True, + 'engine': 'external', 'tokenizer_validated': True, + 'inference_configured': True, 'readiness_checked': False} + + def test_cli_dispatch_and_incompatible_flags(self): + with patch.object(client, 'check_config', return_value={'fixture': True}) as check: + with contextlib.redirect_stdout(io.StringIO()) as output: + client.main(['check-config', '--binary', '/b', '--config', '/c', '--working-dir', '/d']) + self.assertEqual(json.loads(output.getvalue()), {'fixture': True}) + check.assert_called_once_with('rnr5090', '/b', '/c', '/d') + for args in [['check-config'], ['status', '--binary', '/b'], + ['check-config', '--binary', '/b', '--config', '/c', '--working-dir', '/d', '--unit', 'strata-next.service']]: + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + client.main(args) + + def test_report_is_filtered_and_does_not_claim_readiness(self): + calls = [] + def runner(host, arguments): + calls.append((host, arguments)) + return json.dumps({**self.REPORT, 'secret': 'do-not-echo'}) + report = client.check_config('rnr5090', '/srv/bin', '/srv/config', '/srv/work', runner=runner) + self.assertEqual(report['configuration'], self.REPORT) + self.assertFalse(report['connection_changed']) + self.assertEqual(report['model_readiness'], 'not_checked') + self.assertEqual(len(calls), 1) + self.assertNotIn('systemctl', calls[0][1]) + + def test_invalid_selectors_are_rejected_before_transport(self): + def forbidden(*args): + self.fail('invalid selector reached SSH') + for path in ['relative', '/srv/line\nbreak', '/srv/zero\0byte', '/srv/\x7f']: + with self.assertRaises(ValueError): + client.check_config('rnr5090', path, '/c', '/d', runner=forbidden) + with self.assertRaises(ValueError): + client.check_config('-oBad', '/b', '/c', '/d', runner=forbidden) + + def test_remote_shell_preserves_paths_and_does_not_expand_them(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + working = root / "work space ' $HOME `false`" + working.mkdir() + binary = working / 'candidate " $(touch INJECTED)' + config = working / 'config "; touch INJECTED; "' + config.write_text('fixture') + output = json.dumps(self.REPORT) + binary.write_text(f'#!{sys.executable}\nimport os,sys\n' + f'assert os.path.samefile(os.getcwd(), {str(working)!r})\n' + f'assert sys.argv[1:] == ["check-config", "--config", {str(config)!r}]\n' + f'print({output!r})\n') + binary.chmod(0o700) + def runner(host, arguments): + return subprocess.check_output(['sh', '-c', shlex.join(arguments)], text=True, timeout=5) + client.check_config('fixture', str(binary), str(config), str(working), runner=runner) + self.assertFalse((working / 'INJECTED').exists()) + + def test_bad_responses_and_failures_never_echo_remote_text(self): + secret = 'remote-private-marker' + bad = [secret, secret * 7000, '[]', '{}', + json.dumps({**self.REPORT, 'readiness_checked': True}), + json.dumps({**self.REPORT, 'inference_configured': False}), + json.dumps({**self.REPORT, 'schema_version': True}), + json.dumps({**self.REPORT, 'bind': secret}), + json.dumps({**self.REPORT, 'model': secret + '\n'})] + for response in bad: + with self.assertRaises(RuntimeError) as raised: + client.check_config('fixture', '/b', '/c', '/d', runner=lambda *_: response) + self.assertNotIn(secret, str(raised.exception)) + def fail(*_): + raise RuntimeError(secret) + with self.assertRaises(RuntimeError) as raised: + client.check_config('fixture', '/b', '/c', '/d', runner=fail) + self.assertNotIn(secret, str(raised.exception)) + + def test_ssh_transport_caps_output_and_suppresses_stderr(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'ssh' + def script(body): + path.write_text(f'#!{sys.executable}\nimport sys\n' + body) + path.chmod(0o700) + with patch.dict(os.environ, {'PATH': directory}): + script('print("ok")\n') + self.assertEqual(client.ssh_check('fixture', ['true']), 'ok\n') + for body in ['print("x" * 70000)\n', + 'print("secret-transport-marker", file=sys.stderr)\nsys.exit(1)\n', + 'sys.stdout.buffer.write(bytes([255]))\n']: + script(body) + with self.assertRaises(RuntimeError) as raised: + client.ssh_check('fixture', ['true']) + self.assertNotIn('secret-transport-marker', str(raised.exception)) + script('print("ok")\n') + with patch.object(client.time, 'monotonic', side_effect=[0, 31]): + with self.assertRaises(RuntimeError): + client.ssh_check('fixture', ['true']) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-runtime-image.py b/scripts/test-runtime-image.py new file mode 100644 index 00000000..5fcf9034 --- /dev/null +++ b/scripts/test-runtime-image.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Package corruption and ABI rejection without Docker or GPU access.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('builder', Path(__file__).with_name('build-runtime-image.py')) +b = importlib.util.module_from_spec(spec) +spec.loader.exec_module(b) + + +class PackageTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + root = Path(self.tmp.name) + self.pkg, self.stage = root/'package', root/'stage' + self.pkg.mkdir(); self.stage.mkdir() + self.provenance = {'schema_version': 1, 'kind': 'static-cuda-preview', + 'source_revision': 'a'*40, 'target': 'x86_64-unknown-linux-musl', + 'engine': {'embedded': True, 'target_os': 'linux', 'target_arch': 'x86_64', + 'declared_source_revision': 'a'*40, 'bytes': 3, 'sha256': 'b'*64}, + 'engine_elf_audit': {'toolkit_shared_libraries': False, + 'host_glibc_required': True, 'minimum_glibc': '2.43'}} + (self.pkg/b.NAME).write_bytes(b'not executable; validator does not execute input') + self.write() + + def write(self): + (self.pkg/'PROVENANCE.json').write_text(json.dumps(self.provenance)) + (self.pkg/'SHA256SUMS').write_text(''.join(f'{b.digest(self.pkg/n)} {n}\n' for n in (b.NAME, 'PROVENANCE.json'))) + self.sha = b.digest(self.pkg/'SHA256SUMS') + + def freeze(self, fixture=False): + return b.freeze(self.pkg, self.stage, self.sha, fixture) + + def test_frozen_bytes_and_explicit_abi_gate(self): + p = self.freeze() + (self.pkg/b.NAME).write_bytes(b'modified source after freeze') + self.assertNotEqual((self.pkg/b.NAME).read_bytes(), (self.stage/b.NAME).read_bytes()) + self.assertEqual(b.check_glibc(p, 'glibc 2.43\n'), '2.43') + with self.assertRaisesRegex(ValueError, 'below engine'): + b.check_glibc(p, 'glibc 2.39\n') + with self.assertRaises(ValueError): b.check_glibc(p, 'musl 1.2.5') + + def test_pinned_receipt_rejects_replaced_hashes(self): + (self.pkg/'SHA256SUMS').write_text('a'*64 + ' ../outside\n') + with self.assertRaisesRegex(ValueError, 'pinned receipt'): self.freeze() + + def test_corrupt_binary(self): + (self.pkg/b.NAME).write_bytes(b'corruption') + with self.assertRaisesRegex(ValueError, 'checksum'): self.freeze() + + def test_duplicate_or_traversal_receipt_even_with_matching_pin(self): + for data in ['a'*64+' ../outside\n', (self.pkg/'SHA256SUMS').read_text()*2]: + with self.subTest(data=data), tempfile.TemporaryDirectory() as stage: + (self.pkg/'SHA256SUMS').write_text(data) + with self.assertRaisesRegex(ValueError, 'receipt'): + b.freeze(self.pkg, Path(stage), b.digest(self.pkg/'SHA256SUMS'), False) + + def test_no_extra_files_or_symlinks(self): + extra = self.pkg/'private-model' + extra.write_text('fixture') + with self.assertRaisesRegex(ValueError, 'exactly'): self.freeze() + extra.unlink() + (self.pkg/b.NAME).unlink() + (self.pkg/b.NAME).symlink_to('/dev/null') + with self.assertRaises(OSError): self.freeze() + + def test_fixture_requires_explicit_flag_and_architecture_is_checked(self): + self.provenance['kind'] = 'cpu-fixture'; self.write() + with self.assertRaisesRegex(ValueError, 'fixture mode'): self.freeze() + with tempfile.TemporaryDirectory() as stage: + self.assertEqual(b.freeze(self.pkg, Path(stage), self.sha, True)['kind'], 'cpu-fixture') + self.provenance['engine']['target_arch'] = 'aarch64'; self.write() + with tempfile.TemporaryDirectory() as stage: + with self.assertRaisesRegex(ValueError, 'identity'): b.freeze(self.pkg, Path(stage), self.sha, True) + + def test_bad_package_never_reaches_docker(self): + args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256='0'*64, cpu_fixture=False) + with patch.object(b, 'docker') as docker: + with self.assertRaisesRegex(ValueError, 'pinned receipt'): b.assemble(args) + docker.assert_not_called() + + def test_failed_image_identity_removes_only_created_image(self): + args = SimpleNamespace(base=b.BASE, package=self.pkg, receipt_sha256=self.sha, cpu_fixture=False) + image = 'sha256:' + 'c'*64 + calls = [] + def docker(*argv, **kwargs): + calls.append(argv) + if argv[0] == 'build': + Path(argv[argv.index('--iidfile')+1]).write_text(image) + return SimpleNamespace(stdout='') + with patch.object(b, 'docker', side_effect=docker), patch.object(b, 'isolated_run', side_effect=['glibc 2.43', '{}']): + with self.assertRaisesRegex(ValueError, 'metadata differs'): b.assemble(args) + self.assertEqual(calls[-1], ('image','rm',image)) + self.assertFalse(any('--gpus' in call for call in calls)) + + def test_missing_elf_audit_and_size_bound(self): + self.provenance['engine_elf_audit'] = {}; self.write() + with self.assertRaisesRegex(ValueError, 'ELF audit'): self.freeze() + with tempfile.TemporaryDirectory() as stage: + with self.assertRaisesRegex(ValueError, 'size limit'): + b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-static-cuda-elf.py b/scripts/test-static-cuda-elf.py new file mode 100644 index 00000000..2d7a1d92 --- /dev/null +++ b/scripts/test-static-cuda-elf.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Exercise ELF dependency gates with CPU fixtures, without a CUDA toolchain.""" +import importlib.util +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location('audit', Path(__file__).with_name('check-static-cuda-elf.py')) +audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(audit) + + +@unittest.skipUnless(sys.platform == 'linux' and shutil.which('cc') and shutil.which('readelf'), + 'Linux C compiler and readelf required') +class ElfGateTests(unittest.TestCase): + def test_dependency_closure_and_host_path_rejection(self): + with tempfile.TemporaryDirectory(prefix='strata-elf-gate-') as directory: + root = Path(directory) + source = root / 'fixture.c' + source.write_text('#include \nint main(void) { puts("fixture"); return 0; }\n') + executable = root / 'fixture' + def compile(*extra): + subprocess.run(['cc', str(source), '-o', str(executable), *extra], check=True, capture_output=True) + compile() + self.assertTrue(audit.inspect(executable)['host_glibc_required']) + compile('-Wl,-rpath,/private/build/toolkit') + with self.assertRaisesRegex(RuntimeError, 'build-host'): + audit.inspect(executable) + library_source = root / 'library.c' + library_source.write_text('void fake_cuda_symbol(void) {}\n') + library = root / 'libfixture.so' + subprocess.run(['cc', '-shared', '-fPIC', str(library_source), + '-Wl,-soname,libcudart.so.13', '-o', str(library)], check=True, capture_output=True) + compile('-Wl,--no-as-needed', str(library)) + with self.assertRaisesRegex(RuntimeError, 'libcudart.so.13'): + audit.inspect(executable) + + +if __name__ == '__main__': + unittest.main()